uneeq-js 2.44.4 → 2.44.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -32,7 +32,7 @@ var r=n(101),i=n(102),o=n(103);function s(){return c.TYPED_ARRAY_SUPPORT?2147483
32
32
  /*! safe-buffer. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */
33
33
  var r=n(44),i=r.Buffer;function o(t,e){for(var n in t)e[n]=t[n]}function s(t,e,n){return i(t,e,n)}i.from&&i.alloc&&i.allocUnsafe&&i.allocUnsafeSlow?t.exports=r:(o(r,e),e.Buffer=s),s.prototype=Object.create(i.prototype),o(i,s),s.from=function(t,e,n){if("number"==typeof t)throw new TypeError("Argument must not be a number");return i(t,e,n)},s.alloc=function(t,e,n){if("number"!=typeof t)throw new TypeError("Argument must be a number");var r=i(t);return void 0!==e?"string"==typeof n?r.fill(e,n):r.fill(e):r.fill(0),r},s.allocUnsafe=function(t){if("number"!=typeof t)throw new TypeError("Argument must be a number");return i(t)},s.allocUnsafeSlow=function(t){if("number"!=typeof t)throw new TypeError("Argument must be a number");return r.SlowBuffer(t)}},function(t,e,n){"use strict";(function(e,r){var i;t.exports=C,C.ReadableState=T;n(88).EventEmitter;var o=function(t,e){return t.listeners(e).length},s=n(89),a=n(44).Buffer,c=e.Uint8Array||function(){};var u,h=n(122);u=h&&h.debuglog?h.debuglog("stream"):function(){};var l,f,d,p=n(123),v=n(90),g=n(91).getHighWaterMark,m=n(45).codes,y=m.ERR_INVALID_ARG_TYPE,b=m.ERR_STREAM_PUSH_AFTER_EOF,_=m.ERR_METHOD_NOT_IMPLEMENTED,w=m.ERR_STREAM_UNSHIFT_AFTER_END_EVENT;n(59)(C,s);var S=v.errorOrDestroy,x=["error","close","destroy","pause","resume"];function T(t,e,r){i=i||n(46),t=t||{},"boolean"!=typeof r&&(r=e instanceof i),this.objectMode=!!t.objectMode,r&&(this.objectMode=this.objectMode||!!t.readableObjectMode),this.highWaterMark=g(this,t,"readableHighWaterMark",r),this.buffer=new p,this.length=0,this.pipes=null,this.pipesCount=0,this.flowing=null,this.ended=!1,this.endEmitted=!1,this.reading=!1,this.sync=!0,this.needReadable=!1,this.emittedReadable=!1,this.readableListening=!1,this.resumeScheduled=!1,this.paused=!0,this.emitClose=!1!==t.emitClose,this.autoDestroy=!!t.autoDestroy,this.destroyed=!1,this.defaultEncoding=t.defaultEncoding||"utf8",this.awaitDrain=0,this.readingMore=!1,this.decoder=null,this.encoding=null,t.encoding&&(l||(l=n(93).StringDecoder),this.decoder=new l(t.encoding),this.encoding=t.encoding)}function C(t){if(i=i||n(46),!(this instanceof C))return new C(t);var e=this instanceof i;this._readableState=new T(t,this,e),this.readable=!0,t&&("function"==typeof t.read&&(this._read=t.read),"function"==typeof t.destroy&&(this._destroy=t.destroy)),s.call(this)}function E(t,e,n,r,i){u("readableAddChunk",e);var o,s=t._readableState;if(null===e)s.reading=!1,function(t,e){if(u("onEofChunk"),e.ended)return;if(e.decoder){var n=e.decoder.end();n&&n.length&&(e.buffer.push(n),e.length+=e.objectMode?1:n.length)}e.ended=!0,e.sync?O(t):(e.needReadable=!1,e.emittedReadable||(e.emittedReadable=!0,A(t)))}(t,s);else if(i||(o=function(t,e){var n;r=e,a.isBuffer(r)||r instanceof c||"string"==typeof e||void 0===e||t.objectMode||(n=new y("chunk",["string","Buffer","Uint8Array"],e));var r;return n}(s,e)),o)S(t,o);else if(s.objectMode||e&&e.length>0)if("string"==typeof e||s.objectMode||Object.getPrototypeOf(e)===a.prototype||(e=function(t){return a.from(t)}(e)),r)s.endEmitted?S(t,new w):R(t,s,e,!0);else if(s.ended)S(t,new b);else{if(s.destroyed)return!1;s.reading=!1,s.decoder&&!n?(e=s.decoder.write(e),s.objectMode||0!==e.length?R(t,s,e,!1):P(t,s)):R(t,s,e,!1)}else r||(s.reading=!1,P(t,s));return!s.ended&&(s.length<s.highWaterMark||0===s.length)}function R(t,e,n,r){e.flowing&&0===e.length&&!e.sync?(e.awaitDrain=0,t.emit("data",n)):(e.length+=e.objectMode?1:n.length,r?e.buffer.unshift(n):e.buffer.push(n),e.needReadable&&O(t)),P(t,e)}Object.defineProperty(C.prototype,"destroyed",{enumerable:!1,get:function(){return void 0!==this._readableState&&this._readableState.destroyed},set:function(t){this._readableState&&(this._readableState.destroyed=t)}}),C.prototype.destroy=v.destroy,C.prototype._undestroy=v.undestroy,C.prototype._destroy=function(t,e){e(t)},C.prototype.push=function(t,e){var n,r=this._readableState;return r.objectMode?n=!0:"string"==typeof t&&((e=e||r.defaultEncoding)!==r.encoding&&(t=a.from(t,e),e=""),n=!0),E(this,t,e,!1,n)},C.prototype.unshift=function(t){return E(this,t,null,!0,!1)},C.prototype.isPaused=function(){return!1===this._readableState.flowing},C.prototype.setEncoding=function(t){l||(l=n(93).StringDecoder);var e=new l(t);this._readableState.decoder=e,this._readableState.encoding=this._readableState.decoder.encoding;for(var r=this._readableState.buffer.head,i="";null!==r;)i+=e.write(r.data),r=r.next;return this._readableState.buffer.clear(),""!==i&&this._readableState.buffer.push(i),this._readableState.length=i.length,this};function M(t,e){return t<=0||0===e.length&&e.ended?0:e.objectMode?1:t!=t?e.flowing&&e.length?e.buffer.head.data.length:e.length:(t>e.highWaterMark&&(e.highWaterMark=function(t){return t>=1073741824?t=1073741824:(t--,t|=t>>>1,t|=t>>>2,t|=t>>>4,t|=t>>>8,t|=t>>>16,t++),t}(t)),t<=e.length?t:e.ended?e.length:(e.needReadable=!0,0))}function O(t){var e=t._readableState;u("emitReadable",e.needReadable,e.emittedReadable),e.needReadable=!1,e.emittedReadable||(u("emitReadable",e.flowing),e.emittedReadable=!0,r.nextTick(A,t))}function A(t){var e=t._readableState;u("emitReadable_",e.destroyed,e.length,e.ended),e.destroyed||!e.length&&!e.ended||(t.emit("readable"),e.emittedReadable=!1),e.needReadable=!e.flowing&&!e.ended&&e.length<=e.highWaterMark,j(t)}function P(t,e){e.readingMore||(e.readingMore=!0,r.nextTick(k,t,e))}function k(t,e){for(;!e.reading&&!e.ended&&(e.length<e.highWaterMark||e.flowing&&0===e.length);){var n=e.length;if(u("maybeReadMore read 0"),t.read(0),n===e.length)break}e.readingMore=!1}function I(t){var e=t._readableState;e.readableListening=t.listenerCount("readable")>0,e.resumeScheduled&&!e.paused?e.flowing=!0:t.listenerCount("data")>0&&t.resume()}function D(t){u("readable nexttick read 0"),t.read(0)}function N(t,e){u("resume",e.reading),e.reading||t.read(0),e.resumeScheduled=!1,t.emit("resume"),j(t),e.flowing&&!e.reading&&t.read(0)}function j(t){var e=t._readableState;for(u("flow",e.flowing);e.flowing&&null!==t.read(););}function L(t,e){return 0===e.length?null:(e.objectMode?n=e.buffer.shift():!t||t>=e.length?(n=e.decoder?e.buffer.join(""):1===e.buffer.length?e.buffer.first():e.buffer.concat(e.length),e.buffer.clear()):n=e.buffer.consume(t,e.decoder),n);var n}function U(t){var e=t._readableState;u("endReadable",e.endEmitted),e.endEmitted||(e.ended=!0,r.nextTick(F,e,t))}function F(t,e){if(u("endReadableNT",t.endEmitted,t.length),!t.endEmitted&&0===t.length&&(t.endEmitted=!0,e.readable=!1,e.emit("end"),t.autoDestroy)){var n=e._writableState;(!n||n.autoDestroy&&n.finished)&&e.destroy()}}function B(t,e){for(var n=0,r=t.length;n<r;n++)if(t[n]===e)return n;return-1}C.prototype.read=function(t){u("read",t),t=parseInt(t,10);var e=this._readableState,n=t;if(0!==t&&(e.emittedReadable=!1),0===t&&e.needReadable&&((0!==e.highWaterMark?e.length>=e.highWaterMark:e.length>0)||e.ended))return u("read: emitReadable",e.length,e.ended),0===e.length&&e.ended?U(this):O(this),null;if(0===(t=M(t,e))&&e.ended)return 0===e.length&&U(this),null;var r,i=e.needReadable;return u("need readable",i),(0===e.length||e.length-t<e.highWaterMark)&&u("length less than watermark",i=!0),e.ended||e.reading?u("reading or ended",i=!1):i&&(u("do read"),e.reading=!0,e.sync=!0,0===e.length&&(e.needReadable=!0),this._read(e.highWaterMark),e.sync=!1,e.reading||(t=M(n,e))),null===(r=t>0?L(t,e):null)?(e.needReadable=e.length<=e.highWaterMark,t=0):(e.length-=t,e.awaitDrain=0),0===e.length&&(e.ended||(e.needReadable=!0),n!==t&&e.ended&&U(this)),null!==r&&this.emit("data",r),r},C.prototype._read=function(t){S(this,new _("_read()"))},C.prototype.pipe=function(t,e){var n=this,i=this._readableState;switch(i.pipesCount){case 0:i.pipes=t;break;case 1:i.pipes=[i.pipes,t];break;default:i.pipes.push(t)}i.pipesCount+=1,u("pipe count=%d opts=%j",i.pipesCount,e);var s=(!e||!1!==e.end)&&t!==r.stdout&&t!==r.stderr?c:g;function a(e,r){u("onunpipe"),e===n&&r&&!1===r.hasUnpiped&&(r.hasUnpiped=!0,u("cleanup"),t.removeListener("close",p),t.removeListener("finish",v),t.removeListener("drain",h),t.removeListener("error",d),t.removeListener("unpipe",a),n.removeListener("end",c),n.removeListener("end",g),n.removeListener("data",f),l=!0,!i.awaitDrain||t._writableState&&!t._writableState.needDrain||h())}function c(){u("onend"),t.end()}i.endEmitted?r.nextTick(s):n.once("end",s),t.on("unpipe",a);var h=function(t){return function(){var e=t._readableState;u("pipeOnDrain",e.awaitDrain),e.awaitDrain&&e.awaitDrain--,0===e.awaitDrain&&o(t,"data")&&(e.flowing=!0,j(t))}}(n);t.on("drain",h);var l=!1;function f(e){u("ondata");var r=t.write(e);u("dest.write",r),!1===r&&((1===i.pipesCount&&i.pipes===t||i.pipesCount>1&&-1!==B(i.pipes,t))&&!l&&(u("false write response, pause",i.awaitDrain),i.awaitDrain++),n.pause())}function d(e){u("onerror",e),g(),t.removeListener("error",d),0===o(t,"error")&&S(t,e)}function p(){t.removeListener("finish",v),g()}function v(){u("onfinish"),t.removeListener("close",p),g()}function g(){u("unpipe"),n.unpipe(t)}return n.on("data",f),function(t,e,n){if("function"==typeof t.prependListener)return t.prependListener(e,n);t._events&&t._events[e]?Array.isArray(t._events[e])?t._events[e].unshift(n):t._events[e]=[n,t._events[e]]:t.on(e,n)}(t,"error",d),t.once("close",p),t.once("finish",v),t.emit("pipe",n),i.flowing||(u("pipe resume"),n.resume()),t},C.prototype.unpipe=function(t){var e=this._readableState,n={hasUnpiped:!1};if(0===e.pipesCount)return this;if(1===e.pipesCount)return t&&t!==e.pipes||(t||(t=e.pipes),e.pipes=null,e.pipesCount=0,e.flowing=!1,t&&t.emit("unpipe",this,n)),this;if(!t){var r=e.pipes,i=e.pipesCount;e.pipes=null,e.pipesCount=0,e.flowing=!1;for(var o=0;o<i;o++)r[o].emit("unpipe",this,{hasUnpiped:!1});return this}var s=B(e.pipes,t);return-1===s||(e.pipes.splice(s,1),e.pipesCount-=1,1===e.pipesCount&&(e.pipes=e.pipes[0]),t.emit("unpipe",this,n)),this},C.prototype.on=function(t,e){var n=s.prototype.on.call(this,t,e),i=this._readableState;return"data"===t?(i.readableListening=this.listenerCount("readable")>0,!1!==i.flowing&&this.resume()):"readable"===t&&(i.endEmitted||i.readableListening||(i.readableListening=i.needReadable=!0,i.flowing=!1,i.emittedReadable=!1,u("on readable",i.length,i.reading),i.length?O(this):i.reading||r.nextTick(D,this))),n},C.prototype.addListener=C.prototype.on,C.prototype.removeListener=function(t,e){var n=s.prototype.removeListener.call(this,t,e);return"readable"===t&&r.nextTick(I,this),n},C.prototype.removeAllListeners=function(t){var e=s.prototype.removeAllListeners.apply(this,arguments);return"readable"!==t&&void 0!==t||r.nextTick(I,this),e},C.prototype.resume=function(){var t=this._readableState;return t.flowing||(u("resume"),t.flowing=!t.readableListening,function(t,e){e.resumeScheduled||(e.resumeScheduled=!0,r.nextTick(N,t,e))}(this,t)),t.paused=!1,this},C.prototype.pause=function(){return u("call pause flowing=%j",this._readableState.flowing),!1!==this._readableState.flowing&&(u("pause"),this._readableState.flowing=!1,this.emit("pause")),this._readableState.paused=!0,this},C.prototype.wrap=function(t){var e=this,n=this._readableState,r=!1;for(var i in t.on("end",(function(){if(u("wrapped end"),n.decoder&&!n.ended){var t=n.decoder.end();t&&t.length&&e.push(t)}e.push(null)})),t.on("data",(function(i){(u("wrapped data"),n.decoder&&(i=n.decoder.write(i)),n.objectMode&&null==i)||(n.objectMode||i&&i.length)&&(e.push(i)||(r=!0,t.pause()))})),t)void 0===this[i]&&"function"==typeof t[i]&&(this[i]=function(e){return function(){return t[e].apply(t,arguments)}}(i));for(var o=0;o<x.length;o++)t.on(x[o],this.emit.bind(this,x[o]));return this._read=function(e){u("wrapped _read",e),r&&(r=!1,t.resume())},this},"function"==typeof Symbol&&(C.prototype[Symbol.asyncIterator]=function(){return void 0===f&&(f=n(126)),f(this)}),Object.defineProperty(C.prototype,"readableHighWaterMark",{enumerable:!1,get:function(){return this._readableState.highWaterMark}}),Object.defineProperty(C.prototype,"readableBuffer",{enumerable:!1,get:function(){return this._readableState&&this._readableState.buffer}}),Object.defineProperty(C.prototype,"readableFlowing",{enumerable:!1,get:function(){return this._readableState.flowing},set:function(t){this._readableState&&(this._readableState.flowing=t)}}),C._fromList=L,Object.defineProperty(C.prototype,"readableLength",{enumerable:!1,get:function(){return this._readableState.length}}),"function"==typeof Symbol&&(C.from=function(t,e){return void 0===d&&(d=n(127)),d(C,t,e)})}).call(this,n(34),n(38))},function(t,e,n){"use strict";var r,i="object"==typeof Reflect?Reflect:null,o=i&&"function"==typeof i.apply?i.apply:function(t,e,n){return Function.prototype.apply.call(t,e,n)};r=i&&"function"==typeof i.ownKeys?i.ownKeys:Object.getOwnPropertySymbols?function(t){return Object.getOwnPropertyNames(t).concat(Object.getOwnPropertySymbols(t))}:function(t){return Object.getOwnPropertyNames(t)};var s=Number.isNaN||function(t){return t!=t};function a(){a.init.call(this)}t.exports=a,t.exports.once=function(t,e){return new Promise((function(n,r){function i(n){t.removeListener(e,o),r(n)}function o(){"function"==typeof t.removeListener&&t.removeListener("error",i),n([].slice.call(arguments))}m(t,e,o,{once:!0}),"error"!==e&&function(t,e,n){"function"==typeof t.on&&m(t,"error",e,n)}(t,i,{once:!0})}))},a.EventEmitter=a,a.prototype._events=void 0,a.prototype._eventsCount=0,a.prototype._maxListeners=void 0;var c=10;function u(t){if("function"!=typeof t)throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof t)}function h(t){return void 0===t._maxListeners?a.defaultMaxListeners:t._maxListeners}function l(t,e,n,r){var i,o,s,a;if(u(n),void 0===(o=t._events)?(o=t._events=Object.create(null),t._eventsCount=0):(void 0!==o.newListener&&(t.emit("newListener",e,n.listener?n.listener:n),o=t._events),s=o[e]),void 0===s)s=o[e]=n,++t._eventsCount;else if("function"==typeof s?s=o[e]=r?[n,s]:[s,n]:r?s.unshift(n):s.push(n),(i=h(t))>0&&s.length>i&&!s.warned){s.warned=!0;var c=new Error("Possible EventEmitter memory leak detected. "+s.length+" "+String(e)+" listeners added. Use emitter.setMaxListeners() to increase limit");c.name="MaxListenersExceededWarning",c.emitter=t,c.type=e,c.count=s.length,a=c,console&&console.warn&&console.warn(a)}return t}function f(){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 d(t,e,n){var r={fired:!1,wrapFn:void 0,target:t,type:e,listener:n},i=f.bind(r);return i.listener=n,r.wrapFn=i,i}function p(t,e,n){var r=t._events;if(void 0===r)return[];var i=r[e];return void 0===i?[]:"function"==typeof i?n?[i.listener||i]:[i]:n?function(t){for(var e=new Array(t.length),n=0;n<e.length;++n)e[n]=t[n].listener||t[n];return e}(i):g(i,i.length)}function v(t){var e=this._events;if(void 0!==e){var n=e[t];if("function"==typeof n)return 1;if(void 0!==n)return n.length}return 0}function g(t,e){for(var n=new Array(e),r=0;r<e;++r)n[r]=t[r];return n}function m(t,e,n,r){if("function"==typeof t.on)r.once?t.once(e,n):t.on(e,n);else{if("function"!=typeof t.addEventListener)throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof t);t.addEventListener(e,(function i(o){r.once&&t.removeEventListener(e,i),n(o)}))}}Object.defineProperty(a,"defaultMaxListeners",{enumerable:!0,get:function(){return c},set:function(t){if("number"!=typeof t||t<0||s(t))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+t+".");c=t}}),a.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},a.prototype.setMaxListeners=function(t){if("number"!=typeof t||t<0||s(t))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+t+".");return this._maxListeners=t,this},a.prototype.getMaxListeners=function(){return h(this)},a.prototype.emit=function(t){for(var e=[],n=1;n<arguments.length;n++)e.push(arguments[n]);var r="error"===t,i=this._events;if(void 0!==i)r=r&&void 0===i.error;else if(!r)return!1;if(r){var s;if(e.length>0&&(s=e[0]),s instanceof Error)throw s;var a=new Error("Unhandled error."+(s?" ("+s.message+")":""));throw a.context=s,a}var c=i[t];if(void 0===c)return!1;if("function"==typeof c)o(c,this,e);else{var u=c.length,h=g(c,u);for(n=0;n<u;++n)o(h[n],this,e)}return!0},a.prototype.addListener=function(t,e){return l(this,t,e,!1)},a.prototype.on=a.prototype.addListener,a.prototype.prependListener=function(t,e){return l(this,t,e,!0)},a.prototype.once=function(t,e){return u(e),this.on(t,d(this,t,e)),this},a.prototype.prependOnceListener=function(t,e){return u(e),this.prependListener(t,d(this,t,e)),this},a.prototype.removeListener=function(t,e){var n,r,i,o,s;if(u(e),void 0===(r=this._events))return this;if(void 0===(n=r[t]))return this;if(n===e||n.listener===e)0==--this._eventsCount?this._events=Object.create(null):(delete r[t],r.removeListener&&this.emit("removeListener",t,n.listener||e));else if("function"!=typeof n){for(i=-1,o=n.length-1;o>=0;o--)if(n[o]===e||n[o].listener===e){s=n[o].listener,i=o;break}if(i<0)return this;0===i?n.shift():function(t,e){for(;e+1<t.length;e++)t[e]=t[e+1];t.pop()}(n,i),1===n.length&&(r[t]=n[0]),void 0!==r.removeListener&&this.emit("removeListener",t,s||e)}return this},a.prototype.off=a.prototype.removeListener,a.prototype.removeAllListeners=function(t){var e,n,r;if(void 0===(n=this._events))return this;if(void 0===n.removeListener)return 0===arguments.length?(this._events=Object.create(null),this._eventsCount=0):void 0!==n[t]&&(0==--this._eventsCount?this._events=Object.create(null):delete n[t]),this;if(0===arguments.length){var i,o=Object.keys(n);for(r=0;r<o.length;++r)"removeListener"!==(i=o[r])&&this.removeAllListeners(i);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if("function"==typeof(e=n[t]))this.removeListener(t,e);else if(void 0!==e)for(r=e.length-1;r>=0;r--)this.removeListener(t,e[r]);return this},a.prototype.listeners=function(t){return p(this,t,!0)},a.prototype.rawListeners=function(t){return p(this,t,!1)},a.listenerCount=function(t,e){return"function"==typeof t.listenerCount?t.listenerCount(e):v.call(t,e)},a.prototype.listenerCount=v,a.prototype.eventNames=function(){return this._eventsCount>0?r(this._events):[]}},function(t,e,n){t.exports=n(88).EventEmitter},function(t,e,n){"use strict";(function(e){function n(t,e){i(t,e),r(t)}function r(t){t._writableState&&!t._writableState.emitClose||t._readableState&&!t._readableState.emitClose||t.emit("close")}function i(t,e){t.emit("error",e)}t.exports={destroy:function(t,o){var s=this,a=this._readableState&&this._readableState.destroyed,c=this._writableState&&this._writableState.destroyed;return a||c?(o?o(t):t&&(this._writableState?this._writableState.errorEmitted||(this._writableState.errorEmitted=!0,e.nextTick(i,this,t)):e.nextTick(i,this,t)),this):(this._readableState&&(this._readableState.destroyed=!0),this._writableState&&(this._writableState.destroyed=!0),this._destroy(t||null,(function(t){!o&&t?s._writableState?s._writableState.errorEmitted?e.nextTick(r,s):(s._writableState.errorEmitted=!0,e.nextTick(n,s,t)):e.nextTick(n,s,t):o?(e.nextTick(r,s),o(t)):e.nextTick(r,s)})),this)},undestroy:function(){this._readableState&&(this._readableState.destroyed=!1,this._readableState.reading=!1,this._readableState.ended=!1,this._readableState.endEmitted=!1),this._writableState&&(this._writableState.destroyed=!1,this._writableState.ended=!1,this._writableState.ending=!1,this._writableState.finalCalled=!1,this._writableState.prefinished=!1,this._writableState.finished=!1,this._writableState.errorEmitted=!1)},errorOrDestroy:function(t,e){var n=t._readableState,r=t._writableState;n&&n.autoDestroy||r&&r.autoDestroy?t.destroy(e):t.emit("error",e)}}}).call(this,n(38))},function(t,e,n){"use strict";var r=n(45).codes.ERR_INVALID_OPT_VALUE;t.exports={getHighWaterMark:function(t,e,n,i){var o=function(t,e,n){return null!=t.highWaterMark?t.highWaterMark:e?t[n]:null}(e,i,n);if(null!=o){if(!isFinite(o)||Math.floor(o)!==o||o<0)throw new r(i?n:"highWaterMark",o);return Math.floor(o)}return t.objectMode?16:16384}}},function(t,e,n){"use strict";(function(e,r){function i(t){var e=this;this.next=null,this.entry=null,this.finish=function(){!function(t,e,n){var r=t.entry;t.entry=null;for(;r;){var i=r.callback;e.pendingcb--,i(n),r=r.next}e.corkedRequestsFree.next=t}(e,t)}}var o;t.exports=C,C.WritableState=T;var s={deprecate:n(125)},a=n(89),c=n(44).Buffer,u=e.Uint8Array||function(){};var h,l=n(90),f=n(91).getHighWaterMark,d=n(45).codes,p=d.ERR_INVALID_ARG_TYPE,v=d.ERR_METHOD_NOT_IMPLEMENTED,g=d.ERR_MULTIPLE_CALLBACK,m=d.ERR_STREAM_CANNOT_PIPE,y=d.ERR_STREAM_DESTROYED,b=d.ERR_STREAM_NULL_VALUES,_=d.ERR_STREAM_WRITE_AFTER_END,w=d.ERR_UNKNOWN_ENCODING,S=l.errorOrDestroy;function x(){}function T(t,e,s){o=o||n(46),t=t||{},"boolean"!=typeof s&&(s=e instanceof o),this.objectMode=!!t.objectMode,s&&(this.objectMode=this.objectMode||!!t.writableObjectMode),this.highWaterMark=f(this,t,"writableHighWaterMark",s),this.finalCalled=!1,this.needDrain=!1,this.ending=!1,this.ended=!1,this.finished=!1,this.destroyed=!1;var a=!1===t.decodeStrings;this.decodeStrings=!a,this.defaultEncoding=t.defaultEncoding||"utf8",this.length=0,this.writing=!1,this.corked=0,this.sync=!0,this.bufferProcessing=!1,this.onwrite=function(t){!function(t,e){var n=t._writableState,i=n.sync,o=n.writecb;if("function"!=typeof o)throw new g;if(function(t){t.writing=!1,t.writecb=null,t.length-=t.writelen,t.writelen=0}(n),e)!function(t,e,n,i,o){--e.pendingcb,n?(r.nextTick(o,i),r.nextTick(P,t,e),t._writableState.errorEmitted=!0,S(t,i)):(o(i),t._writableState.errorEmitted=!0,S(t,i),P(t,e))}(t,n,i,e,o);else{var s=O(n)||t.destroyed;s||n.corked||n.bufferProcessing||!n.bufferedRequest||M(t,n),i?r.nextTick(R,t,n,s,o):R(t,n,s,o)}}(e,t)},this.writecb=null,this.writelen=0,this.bufferedRequest=null,this.lastBufferedRequest=null,this.pendingcb=0,this.prefinished=!1,this.errorEmitted=!1,this.emitClose=!1!==t.emitClose,this.autoDestroy=!!t.autoDestroy,this.bufferedRequestCount=0,this.corkedRequestsFree=new i(this)}function C(t){var e=this instanceof(o=o||n(46));if(!e&&!h.call(C,this))return new C(t);this._writableState=new T(t,this,e),this.writable=!0,t&&("function"==typeof t.write&&(this._write=t.write),"function"==typeof t.writev&&(this._writev=t.writev),"function"==typeof t.destroy&&(this._destroy=t.destroy),"function"==typeof t.final&&(this._final=t.final)),a.call(this)}function E(t,e,n,r,i,o,s){e.writelen=r,e.writecb=s,e.writing=!0,e.sync=!0,e.destroyed?e.onwrite(new y("write")):n?t._writev(i,e.onwrite):t._write(i,o,e.onwrite),e.sync=!1}function R(t,e,n,r){n||function(t,e){0===e.length&&e.needDrain&&(e.needDrain=!1,t.emit("drain"))}(t,e),e.pendingcb--,r(),P(t,e)}function M(t,e){e.bufferProcessing=!0;var n=e.bufferedRequest;if(t._writev&&n&&n.next){var r=e.bufferedRequestCount,o=new Array(r),s=e.corkedRequestsFree;s.entry=n;for(var a=0,c=!0;n;)o[a]=n,n.isBuf||(c=!1),n=n.next,a+=1;o.allBuffers=c,E(t,e,!0,e.length,o,"",s.finish),e.pendingcb++,e.lastBufferedRequest=null,s.next?(e.corkedRequestsFree=s.next,s.next=null):e.corkedRequestsFree=new i(e),e.bufferedRequestCount=0}else{for(;n;){var u=n.chunk,h=n.encoding,l=n.callback;if(E(t,e,!1,e.objectMode?1:u.length,u,h,l),n=n.next,e.bufferedRequestCount--,e.writing)break}null===n&&(e.lastBufferedRequest=null)}e.bufferedRequest=n,e.bufferProcessing=!1}function O(t){return t.ending&&0===t.length&&null===t.bufferedRequest&&!t.finished&&!t.writing}function A(t,e){t._final((function(n){e.pendingcb--,n&&S(t,n),e.prefinished=!0,t.emit("prefinish"),P(t,e)}))}function P(t,e){var n=O(e);if(n&&(function(t,e){e.prefinished||e.finalCalled||("function"!=typeof t._final||e.destroyed?(e.prefinished=!0,t.emit("prefinish")):(e.pendingcb++,e.finalCalled=!0,r.nextTick(A,t,e)))}(t,e),0===e.pendingcb&&(e.finished=!0,t.emit("finish"),e.autoDestroy))){var i=t._readableState;(!i||i.autoDestroy&&i.endEmitted)&&t.destroy()}return n}n(59)(C,a),T.prototype.getBuffer=function(){for(var t=this.bufferedRequest,e=[];t;)e.push(t),t=t.next;return e},function(){try{Object.defineProperty(T.prototype,"buffer",{get:s.deprecate((function(){return this.getBuffer()}),"_writableState.buffer is deprecated. Use _writableState.getBuffer instead.","DEP0003")})}catch(t){}}(),"function"==typeof Symbol&&Symbol.hasInstance&&"function"==typeof Function.prototype[Symbol.hasInstance]?(h=Function.prototype[Symbol.hasInstance],Object.defineProperty(C,Symbol.hasInstance,{value:function(t){return!!h.call(this,t)||this===C&&(t&&t._writableState instanceof T)}})):h=function(t){return t instanceof this},C.prototype.pipe=function(){S(this,new m)},C.prototype.write=function(t,e,n){var i,o=this._writableState,s=!1,a=!o.objectMode&&(i=t,c.isBuffer(i)||i instanceof u);return a&&!c.isBuffer(t)&&(t=function(t){return c.from(t)}(t)),"function"==typeof e&&(n=e,e=null),a?e="buffer":e||(e=o.defaultEncoding),"function"!=typeof n&&(n=x),o.ending?function(t,e){var n=new _;S(t,n),r.nextTick(e,n)}(this,n):(a||function(t,e,n,i){var o;return null===n?o=new b:"string"==typeof n||e.objectMode||(o=new p("chunk",["string","Buffer"],n)),!o||(S(t,o),r.nextTick(i,o),!1)}(this,o,t,n))&&(o.pendingcb++,s=function(t,e,n,r,i,o){if(!n){var s=function(t,e,n){t.objectMode||!1===t.decodeStrings||"string"!=typeof e||(e=c.from(e,n));return e}(e,r,i);r!==s&&(n=!0,i="buffer",r=s)}var a=e.objectMode?1:r.length;e.length+=a;var u=e.length<e.highWaterMark;u||(e.needDrain=!0);if(e.writing||e.corked){var h=e.lastBufferedRequest;e.lastBufferedRequest={chunk:r,encoding:i,isBuf:n,callback:o,next:null},h?h.next=e.lastBufferedRequest:e.bufferedRequest=e.lastBufferedRequest,e.bufferedRequestCount+=1}else E(t,e,!1,a,r,i,o);return u}(this,o,a,t,e,n)),s},C.prototype.cork=function(){this._writableState.corked++},C.prototype.uncork=function(){var t=this._writableState;t.corked&&(t.corked--,t.writing||t.corked||t.bufferProcessing||!t.bufferedRequest||M(this,t))},C.prototype.setDefaultEncoding=function(t){if("string"==typeof t&&(t=t.toLowerCase()),!(["hex","utf8","utf-8","ascii","binary","base64","ucs2","ucs-2","utf16le","utf-16le","raw"].indexOf((t+"").toLowerCase())>-1))throw new w(t);return this._writableState.defaultEncoding=t,this},Object.defineProperty(C.prototype,"writableBuffer",{enumerable:!1,get:function(){return this._writableState&&this._writableState.getBuffer()}}),Object.defineProperty(C.prototype,"writableHighWaterMark",{enumerable:!1,get:function(){return this._writableState.highWaterMark}}),C.prototype._write=function(t,e,n){n(new v("_write()"))},C.prototype._writev=null,C.prototype.end=function(t,e,n){var i=this._writableState;return"function"==typeof t?(n=t,t=null,e=null):"function"==typeof e&&(n=e,e=null),null!=t&&this.write(t,e),i.corked&&(i.corked=1,this.uncork()),i.ending||function(t,e,n){e.ending=!0,P(t,e),n&&(e.finished?r.nextTick(n):t.once("finish",n));e.ended=!0,t.writable=!1}(this,i,n),this},Object.defineProperty(C.prototype,"writableLength",{enumerable:!1,get:function(){return this._writableState.length}}),Object.defineProperty(C.prototype,"destroyed",{enumerable:!1,get:function(){return void 0!==this._writableState&&this._writableState.destroyed},set:function(t){this._writableState&&(this._writableState.destroyed=t)}}),C.prototype.destroy=l.destroy,C.prototype._undestroy=l.undestroy,C.prototype._destroy=function(t,e){e(t)}}).call(this,n(34),n(38))},function(t,e,n){"use strict";var r=n(86).Buffer,i=r.isEncoding||function(t){switch((t=""+t)&&t.toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":case"raw":return!0;default:return!1}};function o(t){var e;switch(this.encoding=function(t){var e=function(t){if(!t)return"utf8";for(var e;;)switch(t){case"utf8":case"utf-8":return"utf8";case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return"utf16le";case"latin1":case"binary":return"latin1";case"base64":case"ascii":case"hex":return t;default:if(e)return;t=(""+t).toLowerCase(),e=!0}}(t);if("string"!=typeof e&&(r.isEncoding===i||!i(t)))throw new Error("Unknown encoding: "+t);return e||t}(t),this.encoding){case"utf16le":this.text=c,this.end=u,e=4;break;case"utf8":this.fillLast=a,e=4;break;case"base64":this.text=h,this.end=l,e=3;break;default:return this.write=f,void(this.end=d)}this.lastNeed=0,this.lastTotal=0,this.lastChar=r.allocUnsafe(e)}function s(t){return t<=127?0:t>>5==6?2:t>>4==14?3:t>>3==30?4:t>>6==2?-1:-2}function a(t){var e=this.lastTotal-this.lastNeed,n=function(t,e,n){if(128!=(192&e[0]))return t.lastNeed=0,"�";if(t.lastNeed>1&&e.length>1){if(128!=(192&e[1]))return t.lastNeed=1,"�";if(t.lastNeed>2&&e.length>2&&128!=(192&e[2]))return t.lastNeed=2,"�"}}(this,t);return void 0!==n?n:this.lastNeed<=t.length?(t.copy(this.lastChar,e,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal)):(t.copy(this.lastChar,e,0,t.length),void(this.lastNeed-=t.length))}function c(t,e){if((t.length-e)%2==0){var n=t.toString("utf16le",e);if(n){var r=n.charCodeAt(n.length-1);if(r>=55296&&r<=56319)return this.lastNeed=2,this.lastTotal=4,this.lastChar[0]=t[t.length-2],this.lastChar[1]=t[t.length-1],n.slice(0,-1)}return n}return this.lastNeed=1,this.lastTotal=2,this.lastChar[0]=t[t.length-1],t.toString("utf16le",e,t.length-1)}function u(t){var e=t&&t.length?this.write(t):"";if(this.lastNeed){var n=this.lastTotal-this.lastNeed;return e+this.lastChar.toString("utf16le",0,n)}return e}function h(t,e){var n=(t.length-e)%3;return 0===n?t.toString("base64",e):(this.lastNeed=3-n,this.lastTotal=3,1===n?this.lastChar[0]=t[t.length-1]:(this.lastChar[0]=t[t.length-2],this.lastChar[1]=t[t.length-1]),t.toString("base64",e,t.length-n))}function l(t){var e=t&&t.length?this.write(t):"";return this.lastNeed?e+this.lastChar.toString("base64",0,3-this.lastNeed):e}function f(t){return t.toString(this.encoding)}function d(t){return t&&t.length?this.write(t):""}e.StringDecoder=o,o.prototype.write=function(t){if(0===t.length)return"";var e,n;if(this.lastNeed){if(void 0===(e=this.fillLast(t)))return"";n=this.lastNeed,this.lastNeed=0}else n=0;return n<t.length?e?e+this.text(t,n):this.text(t,n):e||""},o.prototype.end=function(t){var e=t&&t.length?this.write(t):"";return this.lastNeed?e+"�":e},o.prototype.text=function(t,e){var n=function(t,e,n){var r=e.length-1;if(r<n)return 0;var i=s(e[r]);if(i>=0)return i>0&&(t.lastNeed=i-1),i;if(--r<n||-2===i)return 0;if((i=s(e[r]))>=0)return i>0&&(t.lastNeed=i-2),i;if(--r<n||-2===i)return 0;if((i=s(e[r]))>=0)return i>0&&(2===i?i=0:t.lastNeed=i-3),i;return 0}(this,t,e);if(!this.lastNeed)return t.toString("utf8",e);this.lastTotal=n;var r=t.length-(n-this.lastNeed);return t.copy(this.lastChar,0,r),t.toString("utf8",e,r)},o.prototype.fillLast=function(t){if(this.lastNeed<=t.length)return t.copy(this.lastChar,this.lastTotal-this.lastNeed,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal);t.copy(this.lastChar,this.lastTotal-this.lastNeed,0,t.length),this.lastNeed-=t.length}},function(t,e,n){"use strict";t.exports=h;var r=n(45).codes,i=r.ERR_METHOD_NOT_IMPLEMENTED,o=r.ERR_MULTIPLE_CALLBACK,s=r.ERR_TRANSFORM_ALREADY_TRANSFORMING,a=r.ERR_TRANSFORM_WITH_LENGTH_0,c=n(46);function u(t,e){var n=this._transformState;n.transforming=!1;var r=n.writecb;if(null===r)return this.emit("error",new o);n.writechunk=null,n.writecb=null,null!=e&&this.push(e),r(t);var i=this._readableState;i.reading=!1,(i.needReadable||i.length<i.highWaterMark)&&this._read(i.highWaterMark)}function h(t){if(!(this instanceof h))return new h(t);c.call(this,t),this._transformState={afterTransform:u.bind(this),needTransform:!1,transforming:!1,writecb:null,writechunk:null,writeencoding:null},this._readableState.needReadable=!0,this._readableState.sync=!1,t&&("function"==typeof t.transform&&(this._transform=t.transform),"function"==typeof t.flush&&(this._flush=t.flush)),this.on("prefinish",l)}function l(){var t=this;"function"!=typeof this._flush||this._readableState.destroyed?f(this,null,null):this._flush((function(e,n){f(t,e,n)}))}function f(t,e,n){if(e)return t.emit("error",e);if(null!=n&&t.push(n),t._writableState.length)throw new a;if(t._transformState.transforming)throw new s;return t.push(null)}n(59)(h,c),h.prototype.push=function(t,e){return this._transformState.needTransform=!1,c.prototype.push.call(this,t,e)},h.prototype._transform=function(t,e,n){n(new i("_transform()"))},h.prototype._write=function(t,e,n){var r=this._transformState;if(r.writecb=n,r.writechunk=t,r.writeencoding=e,!r.transforming){var i=this._readableState;(r.needTransform||i.needReadable||i.length<i.highWaterMark)&&this._read(i.highWaterMark)}},h.prototype._read=function(t){var e=this._transformState;null===e.writechunk||e.transforming?e.needTransform=!0:(e.transforming=!0,this._transform(e.writechunk,e.writeencoding,e.afterTransform))},h.prototype._destroy=function(t,e){c.prototype._destroy.call(this,t,(function(t){e(t)}))}},function(t,e,n){"use strict";function r(t){return(r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t})(t)}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function o(t,e){for(var n=0;n<e.length;n++){var r=e[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(t,r.key,r)}}function s(t,e){return!e||"object"!==r(e)&&"function"!=typeof e?function(t){if(void 0===t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return t}(t):e}function a(t){return(a=Object.setPrototypeOf?Object.getPrototypeOf:function(t){return t.__proto__||Object.getPrototypeOf(t)})(t)}function c(t,e){return(c=Object.setPrototypeOf||function(t,e){return t.__proto__=e,t})(t,e)}Object.defineProperty(e,"__esModule",{value:!0}),e.Counter=void 0;var u=function(t){function e(){return i(this,e),s(this,a(e).apply(this,arguments))}var n,r,u;return function(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function");t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,writable:!0,configurable:!0}}),e&&c(t,e)}(e,t),n=e,(r=[{key:"inc",value:function(t){return this.add(1,t),this}},{key:"add",value:function(t,e){if(t<0)throw new Error("Expected increment amount to be greater than -1. Received: ".concat(t));var n=this.get(e);return this.set(n?n.value+t:t,e),this}},{key:"reset",value:function(t){this.set(0,t)}}])&&o(n.prototype,r),u&&o(n,u),e}(n(96).Collector);e.Counter=u},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.Collector=void 0;var r=n(64),i=n(97);function o(t,e){for(var n=0;n<e.length;n++){var r=e[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(t,r.key,r)}}var s=function(){function t(){var e,n,r;!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,t),r=void 0,(n="data")in(e=this)?Object.defineProperty(e,n,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[n]=r,this.data=[]}var e,n,s;return e=t,(n=[{key:"get",value:function(t){return(0,i.findExistingMetric)(t,this.data)}},{key:"set",value:function(t,e){var n=(0,i.findExistingMetric)(e,this.data);return n?n.value=t:this.data.push({labels:e,value:t}),this}},{key:"collect",value:function(t){return(0,r.filter)(this.data,(function(e){return(0,r.matches)(t)(e.labels)}))}},{key:"resetAll",value:function(){var t=this;return(0,r.each)(this.data,(function(e){t.reset(e.labels)})),this}}])&&o(e.prototype,n),s&&o(e,s),t}();e.Collector=s},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.formatHistogramOrSummary=function(t,e){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"le",o="",s=i(e);s.length>0?(o+="".concat(t,"_count{").concat(s,"} ").concat(e.value.count,"\n"),o+="".concat(t,"_sum{").concat(s,"} ").concat(e.value.sum,"\n")):(o+="".concat(t,"_count ").concat(e.value.count,"\n"),o+="".concat(t,"_sum ").concat(e.value.sum,"\n"));return(0,r.reduce)(e.value.entries,(function(e,r,i){return s.length>0?o+="".concat(t,"_bucket{").concat(n,'="').concat(i,'",').concat(s,"} ").concat(r,"\n"):o+="".concat(t,"_bucket{").concat(n,'="').concat(i,'"} ').concat(r,"\n"),o}),o)},e.findExistingMetric=function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:[];if(!t)return e[0];return(0,r.find)(e,(function(e){return(0,r.isEqual)(e.labels,t)}))},e.formatCounterOrGauge=function(t,e){var n=" ".concat(e.value.toString());if(null==e.labels||0===Object.keys(e.labels).length)return"".concat(t).concat(n,"\n");var i=(0,r.map)(e.labels,(function(t,e){return"".concat(e,'="').concat(t,'"')}));return"".concat(t,"{").concat(i.join(","),"}").concat(n,"\n")};var r=n(64);function i(t){var e=(0,r.map)(t.labels,(function(t,e){return"".concat(e,'="').concat(t,'"')}));return 0===e.length?"":"".concat(e.join(","))}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.MessagingState=void 0,function(t){t[t.DISCONNECTED=0]="DISCONNECTED",t[t.CONNECTING=1]="CONNECTING",t[t.CONNECTED=2]="CONNECTED"}(e.MessagingState||(e.MessagingState={}))},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.VoiceInputMode=void 0,function(t){t.PUSH_TO_TALK="PUSH_TO_TALK",t.VOICE_ACTIVITY="VOICE_ACTIVITY"}(e.VoiceInputMode||(e.VoiceInputMode={}))},function(t,e,n){(function(t,e){!function(t){function n(){}function r(t,e){if(t=void 0===t?"utf-8":t,e=void 0===e?{fatal:!1}:e,-1===o.indexOf(t.toLowerCase()))throw new RangeError("Failed to construct 'TextDecoder': The encoding label provided ('"+t+"') is invalid.");if(e.fatal)throw Error("Failed to construct 'TextDecoder': the 'fatal' option is unsupported.")}function i(t){for(var e=0,n=Math.min(65536,t.length+1),r=new Uint16Array(n),i=[],o=0;;){var s=e<t.length;if(!s||o>=n-1){if(i.push(String.fromCharCode.apply(null,r.subarray(0,o))),!s)return i.join("");t=t.subarray(e),o=e=0}if(0==(128&(s=t[e++])))r[o++]=s;else if(192==(224&s)){var a=63&t[e++];r[o++]=(31&s)<<6|a}else if(224==(240&s)){a=63&t[e++];var c=63&t[e++];r[o++]=(31&s)<<12|a<<6|c}else if(240==(248&s)){65535<(s=(7&s)<<18|(a=63&t[e++])<<12|(c=63&t[e++])<<6|63&t[e++])&&(s-=65536,r[o++]=s>>>10&1023|55296,s=56320|1023&s),r[o++]=s}}}if(t.TextEncoder&&t.TextDecoder)return!1;var o=["utf-8","utf8","unicode-1-1-utf-8"];Object.defineProperty(n.prototype,"encoding",{value:"utf-8"}),n.prototype.encode=function(t,e){if((e=void 0===e?{stream:!1}:e).stream)throw Error("Failed to encode: the 'stream' option is unsupported.");e=0;for(var n=t.length,r=0,i=Math.max(32,n+(n>>>1)+7),o=new Uint8Array(i>>>3<<3);e<n;){var s=t.charCodeAt(e++);if(55296<=s&&56319>=s){if(e<n){var a=t.charCodeAt(e);56320==(64512&a)&&(++e,s=((1023&s)<<10)+(1023&a)+65536)}if(55296<=s&&56319>=s)continue}if(r+4>o.length&&(i+=8,i=(i*=1+e/t.length*2)>>>3<<3,(a=new Uint8Array(i)).set(o),o=a),0==(4294967168&s))o[r++]=s;else{if(0==(4294965248&s))o[r++]=s>>>6&31|192;else if(0==(4294901760&s))o[r++]=s>>>12&15|224,o[r++]=s>>>6&63|128;else{if(0!=(4292870144&s))continue;o[r++]=s>>>18&7|240,o[r++]=s>>>12&63|128,o[r++]=s>>>6&63|128}o[r++]=63&s|128}}return o.slice?o.slice(0,r):o.subarray(0,r)},Object.defineProperty(r.prototype,"encoding",{value:"utf-8"}),Object.defineProperty(r.prototype,"fatal",{value:!1}),Object.defineProperty(r.prototype,"ignoreBOM",{value:!1});var s=i;"function"==typeof e&&e.from?s=function(t){return e.from(t.buffer,t.byteOffset,t.byteLength).toString("utf-8")}:"function"==typeof Blob&&"function"==typeof URL&&"function"==typeof URL.createObjectURL&&(s=function(t){try{var e=URL.createObjectURL(new Blob([t],{type:"text/plain;charset=UTF-8"})),n=new XMLHttpRequest;return n.open("GET",e,!1),n.send(),n.responseText}catch(e){return i(t)}finally{e&&URL.revokeObjectURL(e)}}),r.prototype.decode=function(t,e){if((e=void 0===e?{stream:!1}:e).stream)throw Error("Failed to decode: the 'stream' option is unsupported.");return t=t instanceof Uint8Array?t:t.buffer instanceof ArrayBuffer?new Uint8Array(t.buffer):new Uint8Array(t),s(t)},t.TextEncoder=n,t.TextDecoder=r}("undefined"!=typeof window?window:void 0!==t?t:this)}).call(this,n(34),n(44).Buffer)},function(t,e,n){"use strict";e.byteLength=function(t){var e=u(t),n=e[0],r=e[1];return 3*(n+r)/4-r},e.toByteArray=function(t){var e,n,r=u(t),s=r[0],a=r[1],c=new o(function(t,e,n){return 3*(e+n)/4-n}(0,s,a)),h=0,l=a>0?s-4:s;for(n=0;n<l;n+=4)e=i[t.charCodeAt(n)]<<18|i[t.charCodeAt(n+1)]<<12|i[t.charCodeAt(n+2)]<<6|i[t.charCodeAt(n+3)],c[h++]=e>>16&255,c[h++]=e>>8&255,c[h++]=255&e;2===a&&(e=i[t.charCodeAt(n)]<<2|i[t.charCodeAt(n+1)]>>4,c[h++]=255&e);1===a&&(e=i[t.charCodeAt(n)]<<10|i[t.charCodeAt(n+1)]<<4|i[t.charCodeAt(n+2)]>>2,c[h++]=e>>8&255,c[h++]=255&e);return c},e.fromByteArray=function(t){for(var e,n=t.length,i=n%3,o=[],s=0,a=n-i;s<a;s+=16383)o.push(h(t,s,s+16383>a?a:s+16383));1===i?(e=t[n-1],o.push(r[e>>2]+r[e<<4&63]+"==")):2===i&&(e=(t[n-2]<<8)+t[n-1],o.push(r[e>>10]+r[e>>4&63]+r[e<<2&63]+"="));return o.join("")};for(var r=[],i=[],o="undefined"!=typeof Uint8Array?Uint8Array:Array,s="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",a=0,c=s.length;a<c;++a)r[a]=s[a],i[s.charCodeAt(a)]=a;function u(t){var e=t.length;if(e%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var n=t.indexOf("=");return-1===n&&(n=e),[n,n===e?0:4-n%4]}function h(t,e,n){for(var i,o,s=[],a=e;a<n;a+=3)i=(t[a]<<16&16711680)+(t[a+1]<<8&65280)+(255&t[a+2]),s.push(r[(o=i)>>18&63]+r[o>>12&63]+r[o>>6&63]+r[63&o]);return s.join("")}i["-".charCodeAt(0)]=62,i["_".charCodeAt(0)]=63},function(t,e){
34
34
  /*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh <https://feross.org/opensource> */
35
- e.read=function(t,e,n,r,i){var o,s,a=8*i-r-1,c=(1<<a)-1,u=c>>1,h=-7,l=n?i-1:0,f=n?-1:1,d=t[e+l];for(l+=f,o=d&(1<<-h)-1,d>>=-h,h+=a;h>0;o=256*o+t[e+l],l+=f,h-=8);for(s=o&(1<<-h)-1,o>>=-h,h+=r;h>0;s=256*s+t[e+l],l+=f,h-=8);if(0===o)o=1-u;else{if(o===c)return s?NaN:1/0*(d?-1:1);s+=Math.pow(2,r),o-=u}return(d?-1:1)*s*Math.pow(2,o-r)},e.write=function(t,e,n,r,i,o){var s,a,c,u=8*o-i-1,h=(1<<u)-1,l=h>>1,f=23===i?Math.pow(2,-24)-Math.pow(2,-77):0,d=r?0:o-1,p=r?1:-1,v=e<0||0===e&&1/e<0?1:0;for(e=Math.abs(e),isNaN(e)||e===1/0?(a=isNaN(e)?1:0,s=h):(s=Math.floor(Math.log(e)/Math.LN2),e*(c=Math.pow(2,-s))<1&&(s--,c*=2),(e+=s+l>=1?f/c:f*Math.pow(2,1-l))*c>=2&&(s++,c/=2),s+l>=h?(a=0,s=h):s+l>=1?(a=(e*c-1)*Math.pow(2,i),s+=l):(a=e*Math.pow(2,l-1)*Math.pow(2,i),s=0));i>=8;t[n+d]=255&a,d+=p,a/=256,i-=8);for(s=s<<i|a,u+=i;u>0;t[n+d]=255&s,d+=p,s/=256,u-=8);t[n+d-p]|=128*v}},function(t,e){var n={}.toString;t.exports=Array.isArray||function(t){return"[object Array]"==n.call(t)}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),n(105)},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var r=n(47),i=n(106);r.Observable.prototype.filter=i.filter},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var r=n(81);e.filter=function(t,e){return r.filter(t,e)(this)}},function(t){t.exports=JSON.parse('{"name":"uneeq-js","version":"2.44.4","description":"","main":"dist/index.js","types":"dist/src/index.d.ts","scripts":{"start":"npx webpack -w","test-local":"./node_modules/karma/bin/karma start karma.conf.js -logLevel=DEBUG","test":"./node_modules/karma/bin/karma start --browsers ChromeHeadless --single-run","test:windows":"karma start karma.conf.js","build":"webpack --config webpack.config.prod.js && webpack --config webpack.config.umd.js","lint":"./node_modules/tslint/bin/tslint -p tsconfig.json --fix","docs":"./node_modules/typedoc/bin/typedoc --options"},"files":["dist","!dist/test"],"author":"","license":"ISC","dependencies":{"@stomp/stompjs":"^6.0.0","@uehreka/seriously":"^1.0.1","fast-text-encoding":"^1.0.0","intrinsic-scale":"^3.0.4","promjs":"^0.4.1","rxjs":"^6.2.2","rxjs-compat":"^6.3.2","simple-peer":"9.11.0","webrtc-adapter":"8.1.0"},"devDependencies":{"@types/jasmine":"^2.8.8","@types/node":"^10.9.4","fetch-mock":"7.7.3","ignore-styles":"^5.0.1","jasmine":"^3.2.0","jasmine-class-mock":"^1.0.1","jasmine-core":"^3.3.0","karma":"^5.0.0","karma-chrome-launcher":"^2.2.0","karma-firefox-launcher":"^1.1.0","karma-jasmine":"^2.0.1","karma-jasmine-html-reporter":"^1.4.0","karma-requirejs":"^1.1.0","karma-safari-launcher":"^1.0.0","karma-typescript":"^5.0.0","karma-typescript-es6-transform":"^5.0.0","nock":"^9.6.1","requirejs":"^2.3.6","ts-loader":"^5.0.0","ts-node":"^7.0.1","tslint":"^5.11.0","tslint-no-focused-test":"^0.5.0","typedoc":"^0.18.0","typescript":"^3.9.7","webpack":"^4.17.1","webpack-cli":"^3.1.0"}}')},function(t,e,n){"use strict";var r=this&&this.__awaiter||function(t,e,n,r){return new(n||(n=Promise))((function(i,o){function s(t){try{c(r.next(t))}catch(t){o(t)}}function a(t){try{c(r.throw(t))}catch(t){o(t)}}function c(t){var e;t.done?i(t.value):(e=t.value,e instanceof n?e:new n((function(t){t(e)}))).then(s,a)}c((r=r.apply(t,e||[])).next())}))};Object.defineProperty(e,"__esModule",{value:!0}),e.API=void 0;e.API=class{constructor(t,e="",n=(()=>{})){this.xAuthToken="",this.apiUrl=t,this.apiKey=e,this.loggedOutHandler=n}set callId(t){this._callId=t}get authToken(){return this.xAuthToken}startSession(t){return this.postRequest("/api/v1/customers/",t,{},{"faceme-api-key":this.apiKey})}endCall(){return this.postRequest("/api/v1/calls/"+this._callId+"/endCall")}avatarStart(t){return this.postRequest("/api/v1/avatar/"+this._callId+"/start",t)}avatarWelcome(){return this.postRequest("/api/v1/avatar/"+this._callId+"/welcome")}avatarAsk(t){return this.postRequest("/api/v1/avatar/"+this._callId+"/ask",{text:t})}avatarStartRecording(){return this.postRequest("/api/v1/avatar/"+this._callId+"/audioCapture/start")}avatarStopRecording(){return this.postRequest("/api/v1/avatar/"+this._callId+"/audioCapture/stop")}avatarStopSpeaking(){return this.postRequest("/api/v1/avatar/"+this._callId+"/stopSpeaking")}getAvailableAvatarCount(){return this.getRequest("/api/v1/avatar/"+this._callId+"/available")}startSessionWithToken(t){return this.postRequest("/api/v2/clients/start-session",t,{},{"x-timezone-name":this.getTimeZone()})}setAvatarDebug(t){return this.putRequest("/api/v1/avatar/"+this._callId+"/debug",{enabled:t})}sendMediaUnavailable(t){return this.postRequest("/api/v1/avatar/"+this._callId+"/media/unavailable-update",t)}getEdgeNodeId(t){let e=t.replace("turn:","http://");e=e.replace("turns:","https://");const n=new Request(e,{method:"GET"});return this.makeRequest(n)}getTimeZone(){return Intl.DateTimeFormat().resolvedOptions().timeZone}makeRequest(t){return r(this,void 0,void 0,(function*(){const e=yield fetch(t);if(!e.ok){401===e.status&&this.loggedOutHandler();const t=yield e.json();throw{status:e.status,body:t}}return 204===e.status?new Promise((t,e)=>{t()}):(this.xAuthToken=e.headers.get("x-auth-token")||this.xAuthToken,yield e.json())}))}getRequest(t){const e=new Request(this.apiUrl+t,{method:"GET",credentials:"omit",headers:{"x-auth-token":this.xAuthToken}});return this.makeRequest(e)}postRequest(t,e={},n={},r={}){const i={method:"POST",credentials:"omit",headers:Object.assign({"Content-Type":"application/json","x-auth-token":this.xAuthToken},r),body:JSON.stringify(e)},o=new Request(this.apiUrl+t,Object.assign(i,n));return this.makeRequest(o)}putRequest(t,e={},n={}){const r={method:"PUT",credentials:"omit",headers:{"Content-Type":"application/json","x-auth-token":this.xAuthToken},body:JSON.stringify(e)},i=new Request(this.apiUrl+t,Object.assign(r,n));return this.makeRequest(i)}}},function(t,e,n){"use strict";var r=this&&this.__awaiter||function(t,e,n,r){return new(n||(n=Promise))((function(i,o){function s(t){try{c(r.next(t))}catch(t){o(t)}}function a(t){try{c(r.throw(t))}catch(t){o(t)}}function c(t){var e;t.done?i(t.value):(e=t.value,e instanceof n?e:new n((function(t){t(e)}))).then(s,a)}c((r=r.apply(t,e||[])).next())}))};Object.defineProperty(e,"__esModule",{value:!0}),e.DeviceManager=void 0;const i=n(37),o=n(110);e.DeviceManager=class{constructor(t,e){this.options=t,this.api=e,this.speakerConstraints={},this.publishStream=new MediaStream,this.devices={audioInput:[],audioOutput:[],videoInput:[]},this.previousMediaOptions={},this.mediaHandler=new o.MediaHandler(this.options,()=>this.remoteVideoReady()),this.initMediaConstraints(),this.getDevices(!1)}set edgeNodeId(t){this.mediaHandler.setEdgeNodeId(t),this.getDevices(!0)}enableLocalDevices(t,e){const n=this.options.uneeqOptions.sendLocalVideo!==t,r=this.options.uneeqOptions.sendLocalAudio!==e;(n||r)&&(this.previousMediaOptions={sendLocalVideo:this.options.uneeqOptions.sendLocalVideo,sendLocalAudio:this.options.uneeqOptions.sendLocalAudio},this.options.uneeqOptions.sendLocalVideo=t,this.options.uneeqOptions.sendLocalAudio=e,n&&!1===t&&this.publishStream.getVideoTracks().forEach(t=>t.stop()),r&&!1===e&&this.publishStream.getAudioTracks().forEach(t=>t.stop()),this.mediaHandler.publishingStream=!1,this.initMediaConstraints(),this.getDevices(!0))}getDevices(t=!0){if(!this.options.uneeqOptions.sendLocalVideo&&!this.options.uneeqOptions.sendLocalAudio)return void this.initStreamWithoutDevices();const e=this;this.publishStream=new MediaStream,this.options.streamManager.addCanvasVideoTrackToStream(this.publishStream),this.options.streamManager.addSilentAudioTrackToStream(this.publishStream),navigator.mediaDevices.getUserMedia(this.userMediaConstraints).then(e=>r(this,void 0,void 0,(function*(){if(this.initDeviceList(),this.options.internalMessages$.next({faceMeMessageType:"DevicePermissionAllowedInternal"}),t){if(this.options.uneeqOptions.sendLocalVideo){const t=e.getVideoTracks();t.length>0&&(this.publishStream.getVideoTracks().forEach(t=>this.publishStream.removeTrack(t)),this.publishStream.addTrack(t[0]))}if(this.options.uneeqOptions.sendLocalAudio){const t=e.getAudioTracks();t.length>0&&(this.publishStream.getAudioTracks().forEach(t=>this.publishStream.removeTrack(t)),this.publishStream.addTrack(t[0]))}this.mediaHandler.localStream$.next(this.publishStream)}}))).catch(t=>{e.options.userMessages.next(new i.DeviceErrorMessage(t)),console.error("device error: ",t),this.sendMediaUnavailableInfo("NotAllowedError"===t.name),this.revertMediaOptions()})}setMicDevice(t,e=!0){const n=this.devices.audioInput.filter(e=>e.deviceId===t);if(n&&n.length>0)this.options.uneeqOptions.preferredMicrophoneId=t,this.audioConstraints.deviceId=t,e&&(this.mediaHandler.publishingStream=!1,this.getDevices(!0)),this.options.userMessages.next(new i.SetMicSuccessMessage(t));else{const e="Uneeq setMic: Error setting device. Device not found.";this.options.userMessages.next(new i.DeviceNotFoundErrorMessage(e,t))}}setCamDevice(t,e=!0){const n=this.devices.videoInput.filter(e=>e.deviceId===t);if(n&&n.length>0)this.options.uneeqOptions.preferredCameraId=t,this.videoConstraints.deviceId=t,e&&(this.mediaHandler.publishingStream=!1,this.getDevices(!0)),this.options.userMessages.next(new i.SetCameraSuccessMessage(t));else{const e="Uneeq setCamera: Error setting device. Device not found.";this.options.userMessages.next(new i.DeviceNotFoundErrorMessage(e,t))}}setAvatarSpeakerDevice(t){if(this.mediaHandler.avatarVideoElement){const e=this.devices.audioOutput.filter(e=>e.deviceId===t);if(e&&e.length>0)this.options.uneeqOptions.preferredSpeakerId=t,this.mediaHandler.avatarVideoElement.setSinkId(t).then(()=>{this.speakerConstraints.deviceId=t,this.options.userMessages.next(new i.SetSpeakerSuccessMessage(t))}).catch(e=>{const n="Uneeq setSpeaker: Error setting device. "+e.message;this.options.userMessages.next(new i.DeviceNotFoundErrorMessage(n,t))});else{const e="Uneeq setSpeaker: Error setting device. Device not found.";this.options.userMessages.next(new i.DeviceNotFoundErrorMessage(e,t))}}}revertMediaOptions(){this.previousMediaOptions&&(this.options.uneeqOptions.sendLocalAudio=this.previousMediaOptions.sendLocalAudio,this.options.uneeqOptions.sendLocalVideo=this.previousMediaOptions.sendLocalVideo)}initMediaConstraints(){this.audioConstraints={},this.videoConstraints={facingMode:"user",width:640,height:480},this.userMediaConstraints={audio:!!this.options.uneeqOptions.sendLocalAudio&&this.audioConstraints,video:!!this.options.uneeqOptions.sendLocalVideo&&this.videoConstraints}}initStreamWithoutDevices(){this.publishStream.getTracks().forEach(t=>this.publishStream.removeTrack(t)),this.publishStream=new MediaStream,this.options.internalMessages$.next({faceMeMessageType:"DevicePermissionAllowedInternal"}),this.options.streamManager.addCanvasVideoTrackToStream(this.publishStream),this.options.streamManager.addSilentAudioTrackToStream(this.publishStream),this.mediaHandler.localStream$.next(this.publishStream)}remoteVideoReady(){this.options.uneeqOptions.preferredSpeakerId&&this.setAvatarSpeakerDevice(this.options.uneeqOptions.preferredSpeakerId)}sendMediaUnavailableInfo(t){return r(this,void 0,void 0,(function*(){const e=yield this.getMediaDevices(),n={audioInputs:e.audioInput.length,videoInputs:e.videoInput.length,hasUserDeniedPermission:t};return this.api.sendMediaUnavailable(n)}))}getMediaDevices(){return r(this,void 0,void 0,(function*(){const t=yield navigator.mediaDevices.enumerateDevices(),e={audioInput:[],audioOutput:[],videoInput:[]};return e.audioInput=t.filter(t=>"audioinput"===t.kind),e.audioOutput=t.filter(t=>"audiooutput"===t.kind),e.videoInput=t.filter(t=>"videoinput"===t.kind),e}))}initDeviceList(){return r(this,void 0,void 0,(function*(){navigator.mediaDevices.ondevicechange=t=>{this.initDeviceList()};const t=yield this.getMediaDevices();JSON.stringify(t)!==JSON.stringify(this.devices)&&(this.devices=t,this.options.uneeqOptions.preferredCameraId&&this.setCamDevice(this.options.uneeqOptions.preferredCameraId,!1),this.options.uneeqOptions.preferredMicrophoneId&&this.setMicDevice(this.options.uneeqOptions.preferredMicrophoneId,!1),this.options.userMessages.next(new i.DeviceListUpdatedMessage(this.devices)))}))}}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.MediaHandler=void 0;const r=n(47),i=n(37),o=n(111),s=n(85),a=n(113),c=n(35),u=n(114);e.MediaHandler=class{constructor(t,e){this.options=t,this.remoteVideoReady=e,this.remoteStream$=new r.BehaviorSubject(null),this.localStream$=new r.BehaviorSubject(null),this.publishState$=new r.BehaviorSubject(s.PublishSubscribeState.DISCONNECTED),this.publishingStream=!1,this.remoteStream$.filter(t=>null!==t).subscribe(n=>{this.avatarVideoElement=this.options.digitalHumanVideoElement,this.avatarVideoElement.srcObject=n,t.uneeqOptions.avatarVideoContainerElement.style.overflow="hidden",t.uneeqOptions.avatarVideoContainerElement.innerHTML="",t.uneeqOptions.avatarVideoContainerElement.appendChild(this.avatarVideoElement),this.options.uneeqOptions.enableTransparentBackground&&this.initTransparentBackground(this.avatarVideoElement),e()}),this.localStream$.filter(t=>null!==t).subscribe(e=>{const n=document.createElement("video");this.localVideoElement=n,n.srcObject=e,n.autoplay=!0,n.muted=!0,n.setAttribute("playsinline","true"),n.setAttribute("style","width: 100%; height: 100%;"),t.uneeqOptions.localVideoContainerElement.innerHTML="",t.uneeqOptions.localVideoContainerElement.appendChild(n),this.options.voiceInputManager.initMicActivity(e),this.options.session.edgeNodeId&&!this.publishingStream&&this.publishVideo()}),this.options.internalMessages$.filter(t=>"AnswerMessage"===t.faceMeMessageType).subscribe(t=>{void 0!==this.webRTC&&this.webRTC.handleAnswerMessage(t)}),this.options.internalMessages$.filter(t=>"IceCandidateMessage"===t.faceMeMessageType).subscribe(t=>{void 0!==this.webRTC&&this.webRTC.handleIceCandidate(t)})}setEdgeNodeId(t){this.options.session.edgeNodeId=t,this.options.session.edgeNodeId&&!this.publishingStream&&this.localStream$.getValue()&&this.publishVideo()}unpublishVideo(){c.logger.log("UserSession | unpublishVideo"),void 0!==this.webRTC&&(this.webRTC.close(),this.webRTC=void 0),this.publishState$.next(s.PublishSubscribeState.DISCONNECTED)}pause(){const t=this.remoteStream$.getValue(),e=this.localStream$.getValue();this.avatarVideoElement.pause(),this.localVideoElement.pause(),e&&e.getTracks().forEach(t=>t.enabled=!1),t&&t.getTracks().forEach(t=>t.enabled=!1)}resume(){const t=this.remoteStream$.getValue(),e=this.localStream$.getValue();e&&e.getTracks().forEach(t=>t.enabled=!0),t&&t.getTracks().forEach(t=>t.enabled=!0),this.avatarVideoElement.play(),this.localVideoElement.play()}stopAllLocalStreams(){const t=this.localStream$.getValue();t&&t.getTracks().forEach(t=>t.stop()),this.publishingStream=!1}endSession(){this.stopAllLocalStreams(),this.options.uneeqOptions.localVideoContainerElement&&this.options.uneeqOptions.localVideoContainerElement&&(this.options.uneeqOptions.localVideoContainerElement.innerHTML=""),this.unpublishVideo(),this.options.uneeqOptions.avatarVideoContainerElement&&this.options.uneeqOptions.avatarVideoContainerElement&&(this.options.uneeqOptions.avatarVideoContainerElement.innerHTML="");const t=this.remoteStream$.getValue();t&&t.getTracks().forEach(t=>t.stop()),this.options.voiceInputManager.handleSessionEnd()}sendDataMessage(t){this.webRTC&&this.webRTC.sendDataMessage(t)}gatherWebRTCStats(t){var e;null===(e=this.webRTC)||void 0===e||e.getStats(t)}publishVideo(){const t=this.options.session.streamId,e=this.options.session.avatarStreamId,n=this.options.session.turnServerAddresses,r=this.options.session.turnUsername,o=this.options.session.turnPassword,a=this.options.session.forceTurnServerUse,h=this.publishState$,l=this.remoteStream$,f=this.localStream$.getValue();if(!f||!this.options.session.edgeNodeId)return void console.error("Not ready to publish");let d=0;c.logger.log("UserSession | publishVideo - stream:",f,"publishStreamName:",t),c.logger.log("PublishVideo with edge node id: ",this.options.session.edgeNodeId),this.publishingStream=!0,null==this.webRTC?(this.webRTC=new u.UneeqWebRTC({messaging:this.options.messaging,userMessages:this.options.userMessages,publishStreamName:t,subscribeStreamName:e,edgeNodeId:this.options.session.edgeNodeId||"id",diagnostics:this.options.uneeqOptions.diagnostics,onAddStream:t=>{c.logger.log("WEBRTC: onAddStream "+t.stream),l.next(t.stream)},forceTurnServerUse:a,iceServers:[{urls:n,username:r,credential:o}],onConnect:()=>{c.logger.log("UserSession | publishVideo | webRtcInstance | onStateChange - connected");h.getValue()===s.PublishSubscribeState.CONNECTING&&h.next(s.PublishSubscribeState.CONNECTED)},onError:t=>{c.logger.log("UserSession | publishVideo | webRtcInstance | onConnectionFailed - ",d),d<3?(d++,this.performWebRTCConnection(f),this.options.userMessages.next(new i.ConnectionLostMessage(s.PublishSubscribeState.DISCONNECTED))):(c.logger.log("UserSession | publishVideo | webRtcInstance | Publish failures > 3, so giving up"),h.next(s.PublishSubscribeState.FAILED),this.options.userMessages.next(new i.ConnectionLostMessage(s.PublishSubscribeState.FAILED)))}}),this.performWebRTCConnection(f)):this.webRTC.updateStreamTracks(f)}performWebRTCConnection(t){this.webRTC&&(this.publishState$.next(s.PublishSubscribeState.CONNECTING),this.webRTC.connect(t))}initTransparentBackground(t){const e=new a.CanvasService(this.options.uneeqOptions).createCanvas();(new o.VideoEditor).applyChromaKeyEffect(e,t),this.avatarVideoElement.style.display="none"}}},function(t,e,n){"use strict";var r=this&&this.__createBinding||(Object.create?function(t,e,n,r){void 0===r&&(r=n),Object.defineProperty(t,r,{enumerable:!0,get:function(){return e[n]}})}:function(t,e,n,r){void 0===r&&(r=n),t[r]=e[n]}),i=this&&this.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),o=this&&this.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(null!=t)for(var n in t)"default"!==n&&Object.hasOwnProperty.call(t,n)&&r(e,t,n);return i(e,t),e};Object.defineProperty(e,"__esModule",{value:!0}),e.VideoEditor=void 0;const s=o(n(83));e.VideoEditor=class{constructor(){}applyChromaKeyEffect(t,e){try{n(112);const r=s.default();let i,o,a;i=r.transform("reformat"),i.source=e,i.width=t.width,i.height=t.height,a=r.target(t),o=r.effect("chroma"),o.source=i,a.source=o,r.go()}catch(t){console.error(t)}}}},function(t,e,n){"use strict";n.r(e),n(83).default.plugin("chroma",{shader:function(t,e){return e.vertex=["precision mediump float;","attribute vec4 position;","attribute vec2 texCoord;","uniform vec2 resolution;","uniform mat4 transform;","varying vec2 vTexCoord;","uniform vec4 screen;","uniform float balance;","varying float screenSat;","varying vec3 screenPrimary;","void main(void) {","\tfloat fmin = min(min(screen.r, screen.g), screen.b);","\tfloat fmax = max(max(screen.r, screen.g), screen.b);","\tfloat secondaryComponents;","\tscreenPrimary = step(fmax, screen.rgb);","\tsecondaryComponents = dot(1.0 - screenPrimary, screen.rgb);","\tscreenSat = fmax - mix(secondaryComponents - fmin, secondaryComponents / 2.0, balance);","\tvec4 screenPosition = vec4(position.xy * resolution / 2.0, position.z, position.w);","\tscreenPosition = transform * screenPosition;","\tgl_Position = screenPosition;","\tgl_Position.xy = screenPosition.xy * 2.0 / resolution;","\tgl_Position.z = screenPosition.z * 2.0 / (resolution.x / resolution.y);","\tvTexCoord = texCoord;","}"].join("\n"),e.fragment=[this.inputs.mask?"#define MASK":"","precision mediump float;","varying vec2 vTexCoord;","uniform sampler2D source;","uniform vec4 screen;","uniform float screenWeight;","uniform float balance;","uniform float clipBlack;","uniform float clipWhite;","uniform bool mask;","varying float screenSat;","varying vec3 screenPrimary;","void main(void) {","\tfloat pixelSat, secondaryComponents;","\tvec4 sourcePixel = texture2D(source, vTexCoord);","\tfloat fmin = min(min(sourcePixel.r, sourcePixel.g), sourcePixel.b);","\tfloat fmax = max(max(sourcePixel.r, sourcePixel.g), sourcePixel.b);","\tvec3 pixelPrimary = step(fmax, sourcePixel.rgb);","\tsecondaryComponents = dot(1.0 - pixelPrimary, sourcePixel.rgb);","\tpixelSat = fmax - mix(secondaryComponents - fmin, secondaryComponents / 2.0, balance);","\tfloat diffPrimary = dot(abs(pixelPrimary - screenPrimary), vec3(1.0));","\tfloat solid = step(1.0, step(pixelSat, 0.1) + step(fmax, 0.1) + diffPrimary);","\tfloat alpha = max(0.0, 1.0 - pixelSat / screenSat);","\talpha = smoothstep(clipBlack, clipWhite, alpha);","\tvec4 semiTransparentPixel = vec4((sourcePixel.rgb - (1.0 - alpha) * screen.rgb * screenWeight) / max(0.00001, alpha), alpha);","\tvec4 pixel = mix(semiTransparentPixel, sourcePixel, solid);","#ifdef MASK","\tgl_FragColor = vec4(vec3(pixel.a), 1.0);","#else","\tgl_FragColor = pixel;","#endif","}"].join("\n"),e},inPlace:!0,inputs:{source:{type:"image",uniform:"source"},screen:{type:"color",uniform:"screen",defaultValue:[66/255,195/255,31/255,1]},weight:{type:"number",uniform:"screenWeight",defaultValue:1,min:0},balance:{type:"number",uniform:"balance",defaultValue:1,min:0,max:1},clipBlack:{type:"number",uniform:"clipBlack",defaultValue:0,min:0,max:1},clipWhite:{type:"number",uniform:"clipWhite",defaultValue:1,min:0,max:1},mask:{type:"boolean",defaultValue:!1,uniform:"mask",shaderDirty:!0}},title:"Chroma Key",description:""})},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.CanvasService=void 0;e.CanvasService=class{constructor(t){this.canvasHeight=720,this.canvasWidth=1280,this.uneeqOptions=t}createCanvas(){const t=document.createElement("canvas");return this.uneeqOptions.avatarVideoContainerElement.appendChild(t),t.setAttribute("style","object-fit: cover; width: 100%; height: 100%;"),t.height=this.canvasHeight,t.width=this.canvasWidth,t}}},function(t,e,n){"use strict";var r=this&&this.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(e,"__esModule",{value:!0}),e.UneeqWebRTC=void 0;const i=r(n(115)),o=r(n(82)),s=n(37),a=n(35);e.UneeqWebRTC=class{constructor(t){this.fakeDataChannel={},this.MESSAGING_ENDPOINT="/app/v2/webRTC",this.onStats=(t,e)=>{this.options.userMessages.next(new s.WebRtcStatsMessage(e)),this.statTimer=window.setTimeout(()=>{this.client.getStats(this.onStats)},2e3)},this.options=Object.assign({forceTurnServerUse:!1,iceServers:[]},t),this.log("Options",this.options),this.uniqueId=Math.random().toString(36).substring(2,12),RTCPeerConnection.prototype.createDataChannel||(this.warn("Implementing a fake createDataChannel"),RTCPeerConnection.prototype.createDataChannel=()=>this.fakeDataChannel)}connect(t){this.close(),this.client=new i.default({initiator:!0,config:{iceServers:this.options.iceServers},stream:t,channelName:"UneeqChannel"}),this.options.diagnostics&&this.enableDiagnostics(),this.fakeDataChannel.onopen&&(this.warn("Calling channel open on fake data channel"),this.fakeDataChannel.onopen()),this.client.on("error",t=>{this.log("error",t),void 0!==this.options.onError&&this.options.onError(t)}),this.client.on("signal",t=>{const e={payload:"",publishStreamName:this.options.publishStreamName,subscribeStreamName:this.options.subscribeStreamName,uniqueId:this.uniqueId,userAgent:navigator.userAgent,edgeNodeId:this.options.edgeNodeId};if("type"in t&&"offer"===t.type)e.payload=JSON.stringify({type:"offer",sdp:t.sdp}),e.type="OfferMessage",this.log("Offer payload ",e),this.options.messaging.send(this.MESSAGING_ENDPOINT,e);else if("candidate"in t){const n=JSON.stringify(t.candidate);this.options.forceTurnServerUse&&!n.match(/typ relay/)||n.match(/::/)||(e.payload=n,e.type="IceCandidate",this.log("IC payload ",e),this.options.messaging.send(this.MESSAGING_ENDPOINT,e))}else this.warn("WARNING Unhandled signal: ",JSON.stringify(t))}),this.client.on("connect",()=>{this.log("CONNECT"),void 0!==this.options.onConnect&&this.options.onConnect()}),this.client.on("data",t=>{this.log("data: "+t),void 0!==this.options.onData&&this.options.onData(t),this.options.userMessages.next(new s.WebRtcDataMessage(t))}),this.client.on("close",()=>{this.log("WebRTC session closed: "+this.uniqueId),this.client=null,void 0!==this.options.onClose&&this.options.onClose()}),this.client.on("stream",t=>{void 0!==this.options.onAddStream&&this.options.onAddStream({stream:t})})}close(){this.client&&(this.client.destroy(),this.client=null),this.statTimer&&clearTimeout(this.statTimer)}handleAnswerMessage(t){if(this.isMessageForUs(t)&&this.client){const e=JSON.parse(t.payload);return this.log("got answer: ",e),this.client.signal(e),!0}return this.log("ignoring answer: ",t),!1}handleIceCandidate(t){if(this.isMessageForUs(t)&&this.client){const e=JSON.parse(t.payload);if("candidate"in e&&""===e.candidate){if("edge"===o.default.browserDetails.browser){const t=this.client._pc;t.remoteDescription&&t.remoteDescription.type&&t.addIceCandidate(null)}}else this.client.signal({candidate:e});return!0}return!1}sendDataMessage(t){this.client.send(t)}getStats(t){return this.client&&this.client.getStats(t)}updateStreamTracks(t){t.getTracks().forEach(t=>{this.client._pc.getSenders().find(e=>t.kind===e.track.kind).replaceTrack(t).then(()=>{a.logger.log("Updated publish media stream track for "+t.kind)}).catch(e=>{a.logger.error("Error: updating publish media stream track failed for "+t.kind,e)})})}enableDiagnostics(){this.client._pc&&0!==this.client._pc.getStats.length&&(this.client._pc.getStats=""),this.client.getStats(this.onStats)}isMessageForUs(t){return t.requestUniqueId===this.uniqueId}log(t,...e){a.logger.log("UneeqWebRTC: "+t,e)}warn(t,...e){a.logger.warn("UneeqWebRTC: "+t,e)}}},function(t,e,n){
35
+ e.read=function(t,e,n,r,i){var o,s,a=8*i-r-1,c=(1<<a)-1,u=c>>1,h=-7,l=n?i-1:0,f=n?-1:1,d=t[e+l];for(l+=f,o=d&(1<<-h)-1,d>>=-h,h+=a;h>0;o=256*o+t[e+l],l+=f,h-=8);for(s=o&(1<<-h)-1,o>>=-h,h+=r;h>0;s=256*s+t[e+l],l+=f,h-=8);if(0===o)o=1-u;else{if(o===c)return s?NaN:1/0*(d?-1:1);s+=Math.pow(2,r),o-=u}return(d?-1:1)*s*Math.pow(2,o-r)},e.write=function(t,e,n,r,i,o){var s,a,c,u=8*o-i-1,h=(1<<u)-1,l=h>>1,f=23===i?Math.pow(2,-24)-Math.pow(2,-77):0,d=r?0:o-1,p=r?1:-1,v=e<0||0===e&&1/e<0?1:0;for(e=Math.abs(e),isNaN(e)||e===1/0?(a=isNaN(e)?1:0,s=h):(s=Math.floor(Math.log(e)/Math.LN2),e*(c=Math.pow(2,-s))<1&&(s--,c*=2),(e+=s+l>=1?f/c:f*Math.pow(2,1-l))*c>=2&&(s++,c/=2),s+l>=h?(a=0,s=h):s+l>=1?(a=(e*c-1)*Math.pow(2,i),s+=l):(a=e*Math.pow(2,l-1)*Math.pow(2,i),s=0));i>=8;t[n+d]=255&a,d+=p,a/=256,i-=8);for(s=s<<i|a,u+=i;u>0;t[n+d]=255&s,d+=p,s/=256,u-=8);t[n+d-p]|=128*v}},function(t,e){var n={}.toString;t.exports=Array.isArray||function(t){return"[object Array]"==n.call(t)}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),n(105)},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var r=n(47),i=n(106);r.Observable.prototype.filter=i.filter},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var r=n(81);e.filter=function(t,e){return r.filter(t,e)(this)}},function(t){t.exports=JSON.parse('{"name":"uneeq-js","version":"2.44.6","description":"","main":"dist/index.js","types":"dist/src/index.d.ts","scripts":{"start":"npx webpack -w","test-local":"npx karma start karma.conf.js -logLevel=DEBUG","test":"npx karma start --browsers ChromeHeadless --single-run","test:windows":"karma start karma.conf.js","build":"webpack --config webpack.config.prod.js && webpack --config webpack.config.umd.js","lint":"npx tslint -p tsconfig.json --fix","docs":"npx typedoc --options"},"files":["dist","!dist/test"],"author":"","license":"ISC","dependencies":{"@stomp/stompjs":"^6.0.0","@uehreka/seriously":"^1.0.1","fast-text-encoding":"^1.0.0","intrinsic-scale":"^3.0.4","promjs":"^0.4.1","rxjs":"^6.2.2","rxjs-compat":"^6.3.2","simple-peer":"9.11.0","webrtc-adapter":"8.1.0"},"devDependencies":{"@types/jasmine":"^2.8.8","@types/node":"^10.9.4","fetch-mock":"7.7.3","ignore-styles":"^5.0.1","jasmine":"^3.2.0","jasmine-class-mock":"^1.0.1","jasmine-core":"^3.3.0","karma":"^5.0.0","karma-chrome-launcher":"^2.2.0","karma-firefox-launcher":"^1.1.0","karma-jasmine":"^2.0.1","karma-jasmine-html-reporter":"^1.4.0","karma-requirejs":"^1.1.0","karma-safari-launcher":"^1.0.0","karma-typescript":"^5.0.0","karma-typescript-es6-transform":"^5.0.0","nock":"^9.6.1","requirejs":"^2.3.6","ts-loader":"^5.0.0","ts-node":"^7.0.1","tslint":"^5.11.0","tslint-no-focused-test":"^0.5.0","typedoc":"^0.18.0","typescript":"^3.9.7","webpack":"^4.17.1","webpack-cli":"^3.1.0"}}')},function(t,e,n){"use strict";var r=this&&this.__awaiter||function(t,e,n,r){return new(n||(n=Promise))((function(i,o){function s(t){try{c(r.next(t))}catch(t){o(t)}}function a(t){try{c(r.throw(t))}catch(t){o(t)}}function c(t){var e;t.done?i(t.value):(e=t.value,e instanceof n?e:new n((function(t){t(e)}))).then(s,a)}c((r=r.apply(t,e||[])).next())}))};Object.defineProperty(e,"__esModule",{value:!0}),e.API=void 0;e.API=class{constructor(t,e="",n=(()=>{})){this.xAuthToken="",this.apiUrl=t,this.apiKey=e,this.loggedOutHandler=n}set callId(t){this._callId=t}get authToken(){return this.xAuthToken}startSession(t){return this.postRequest("/api/v1/customers/",t,{},{"faceme-api-key":this.apiKey})}endCall(){return this.postRequest("/api/v1/calls/"+this._callId+"/endCall")}avatarStart(t){return this.postRequest("/api/v1/avatar/"+this._callId+"/start",t)}avatarWelcome(){return this.postRequest("/api/v1/avatar/"+this._callId+"/welcome")}avatarAsk(t){return this.postRequest("/api/v1/avatar/"+this._callId+"/ask",{text:t})}avatarStartRecording(){return this.postRequest("/api/v1/avatar/"+this._callId+"/audioCapture/start")}avatarStopRecording(){return this.postRequest("/api/v1/avatar/"+this._callId+"/audioCapture/stop")}avatarStopSpeaking(){return this.postRequest("/api/v1/avatar/"+this._callId+"/stopSpeaking")}getAvailableAvatarCount(){return this.getRequest("/api/v1/avatar/"+this._callId+"/available")}startSessionWithToken(t){return this.postRequest("/api/v2/clients/start-session",t,{},{"x-timezone-name":this.getTimeZone()})}setAvatarDebug(t){return this.putRequest("/api/v1/avatar/"+this._callId+"/debug",{enabled:t})}sendMediaUnavailable(t){return this.postRequest("/api/v1/avatar/"+this._callId+"/media/unavailable-update",t)}getEdgeNodeId(t){let e=t.replace("turn:","http://");e=e.replace("turns:","https://");const n=new Request(e,{method:"GET"});return this.makeRequest(n)}getTimeZone(){return Intl.DateTimeFormat().resolvedOptions().timeZone}makeRequest(t){return r(this,void 0,void 0,(function*(){const e=yield fetch(t);if(!e.ok){401===e.status&&this.loggedOutHandler();const t=yield e.json();throw{status:e.status,body:t}}return 204===e.status?new Promise((t,e)=>{t()}):(this.xAuthToken=e.headers.get("x-auth-token")||this.xAuthToken,yield e.json())}))}getRequest(t){const e=new Request(this.apiUrl+t,{method:"GET",credentials:"omit",headers:{"x-auth-token":this.xAuthToken}});return this.makeRequest(e)}postRequest(t,e={},n={},r={}){const i={method:"POST",credentials:"omit",headers:Object.assign({"Content-Type":"application/json","x-auth-token":this.xAuthToken},r),body:JSON.stringify(e)},o=new Request(this.apiUrl+t,Object.assign(i,n));return this.makeRequest(o)}putRequest(t,e={},n={}){const r={method:"PUT",credentials:"omit",headers:{"Content-Type":"application/json","x-auth-token":this.xAuthToken},body:JSON.stringify(e)},i=new Request(this.apiUrl+t,Object.assign(r,n));return this.makeRequest(i)}}},function(t,e,n){"use strict";var r=this&&this.__awaiter||function(t,e,n,r){return new(n||(n=Promise))((function(i,o){function s(t){try{c(r.next(t))}catch(t){o(t)}}function a(t){try{c(r.throw(t))}catch(t){o(t)}}function c(t){var e;t.done?i(t.value):(e=t.value,e instanceof n?e:new n((function(t){t(e)}))).then(s,a)}c((r=r.apply(t,e||[])).next())}))};Object.defineProperty(e,"__esModule",{value:!0}),e.DeviceManager=void 0;const i=n(37),o=n(110);e.DeviceManager=class{constructor(t,e){this.options=t,this.api=e,this.speakerConstraints={},this.publishStream=new MediaStream,this.devices={audioInput:[],audioOutput:[],videoInput:[]},this.previousMediaOptions={},this.mediaHandler=new o.MediaHandler(this.options,()=>this.remoteVideoReady()),this.initMediaConstraints(),this.getDevices(!1)}set edgeNodeId(t){this.mediaHandler.setEdgeNodeId(t),this.getDevices(!0)}enableLocalDevices(t,e){const n=this.options.uneeqOptions.sendLocalVideo!==t,r=this.options.uneeqOptions.sendLocalAudio!==e;(n||r)&&(this.previousMediaOptions={sendLocalVideo:this.options.uneeqOptions.sendLocalVideo,sendLocalAudio:this.options.uneeqOptions.sendLocalAudio},this.options.uneeqOptions.sendLocalVideo=t,this.options.uneeqOptions.sendLocalAudio=e,n&&!1===t&&this.publishStream.getVideoTracks().forEach(t=>t.stop()),r&&!1===e&&this.publishStream.getAudioTracks().forEach(t=>t.stop()),this.mediaHandler.publishingStream=!1,this.initMediaConstraints(),this.getDevices(!0))}getDevices(t=!0){if(!this.options.uneeqOptions.sendLocalVideo&&!this.options.uneeqOptions.sendLocalAudio)return void this.initStreamWithoutDevices();const e=this;this.publishStream=new MediaStream,this.options.streamManager.addCanvasVideoTrackToStream(this.publishStream),this.options.streamManager.addSilentAudioTrackToStream(this.publishStream),navigator.mediaDevices.getUserMedia(this.userMediaConstraints).then(e=>r(this,void 0,void 0,(function*(){if(this.initDeviceList(),this.options.internalMessages$.next({faceMeMessageType:"DevicePermissionAllowedInternal"}),t){if(this.options.uneeqOptions.sendLocalVideo){const t=e.getVideoTracks();t.length>0&&(this.publishStream.getVideoTracks().forEach(t=>this.publishStream.removeTrack(t)),this.publishStream.addTrack(t[0]))}if(this.options.uneeqOptions.sendLocalAudio){const t=e.getAudioTracks();t.length>0&&(this.publishStream.getAudioTracks().forEach(t=>this.publishStream.removeTrack(t)),this.publishStream.addTrack(t[0]))}this.mediaHandler.localStream$.next(this.publishStream)}}))).catch(t=>{e.options.userMessages.next(new i.DeviceErrorMessage(t)),console.error("device error: ",t),this.sendMediaUnavailableInfo("NotAllowedError"===t.name),this.revertMediaOptions()})}setMicDevice(t,e=!0){const n=this.devices.audioInput.filter(e=>e.deviceId===t);if(n&&n.length>0)this.options.uneeqOptions.preferredMicrophoneId=t,this.audioConstraints.deviceId=t,e&&(this.mediaHandler.publishingStream=!1,this.getDevices(!0)),this.options.userMessages.next(new i.SetMicSuccessMessage(t));else{const e="Uneeq setMic: Error setting device. Device not found.";this.options.userMessages.next(new i.DeviceNotFoundErrorMessage(e,t))}}setCamDevice(t,e=!0){const n=this.devices.videoInput.filter(e=>e.deviceId===t);if(n&&n.length>0)this.options.uneeqOptions.preferredCameraId=t,this.videoConstraints.deviceId=t,e&&(this.mediaHandler.publishingStream=!1,this.getDevices(!0)),this.options.userMessages.next(new i.SetCameraSuccessMessage(t));else{const e="Uneeq setCamera: Error setting device. Device not found.";this.options.userMessages.next(new i.DeviceNotFoundErrorMessage(e,t))}}setAvatarSpeakerDevice(t){if(this.mediaHandler.avatarVideoElement){const e=this.devices.audioOutput.filter(e=>e.deviceId===t);if(e&&e.length>0)this.options.uneeqOptions.preferredSpeakerId=t,this.mediaHandler.avatarVideoElement.setSinkId(t).then(()=>{this.speakerConstraints.deviceId=t,this.options.userMessages.next(new i.SetSpeakerSuccessMessage(t))}).catch(e=>{const n="Uneeq setSpeaker: Error setting device. "+e.message;this.options.userMessages.next(new i.DeviceNotFoundErrorMessage(n,t))});else{const e="Uneeq setSpeaker: Error setting device. Device not found.";this.options.userMessages.next(new i.DeviceNotFoundErrorMessage(e,t))}}}revertMediaOptions(){this.previousMediaOptions&&(this.options.uneeqOptions.sendLocalAudio=this.previousMediaOptions.sendLocalAudio,this.options.uneeqOptions.sendLocalVideo=this.previousMediaOptions.sendLocalVideo)}initMediaConstraints(){this.audioConstraints={},this.videoConstraints={facingMode:"user",width:640,height:480},this.userMediaConstraints={audio:!!this.options.uneeqOptions.sendLocalAudio&&this.audioConstraints,video:!!this.options.uneeqOptions.sendLocalVideo&&this.videoConstraints}}initStreamWithoutDevices(){this.publishStream.getTracks().forEach(t=>this.publishStream.removeTrack(t)),this.publishStream=new MediaStream,this.options.internalMessages$.next({faceMeMessageType:"DevicePermissionAllowedInternal"}),this.options.streamManager.addCanvasVideoTrackToStream(this.publishStream),this.options.streamManager.addSilentAudioTrackToStream(this.publishStream),this.mediaHandler.localStream$.next(this.publishStream)}remoteVideoReady(){this.options.uneeqOptions.preferredSpeakerId&&this.setAvatarSpeakerDevice(this.options.uneeqOptions.preferredSpeakerId)}sendMediaUnavailableInfo(t){return r(this,void 0,void 0,(function*(){const e=yield this.getMediaDevices(),n={audioInputs:e.audioInput.length,videoInputs:e.videoInput.length,hasUserDeniedPermission:t};return this.api.sendMediaUnavailable(n)}))}getMediaDevices(){return r(this,void 0,void 0,(function*(){const t=yield navigator.mediaDevices.enumerateDevices(),e={audioInput:[],audioOutput:[],videoInput:[]};return e.audioInput=t.filter(t=>"audioinput"===t.kind),e.audioOutput=t.filter(t=>"audiooutput"===t.kind),e.videoInput=t.filter(t=>"videoinput"===t.kind),e}))}initDeviceList(){return r(this,void 0,void 0,(function*(){navigator.mediaDevices.ondevicechange=t=>{this.initDeviceList()};const t=yield this.getMediaDevices();JSON.stringify(t)!==JSON.stringify(this.devices)&&(this.devices=t,this.options.uneeqOptions.preferredCameraId&&this.setCamDevice(this.options.uneeqOptions.preferredCameraId,!1),this.options.uneeqOptions.preferredMicrophoneId&&this.setMicDevice(this.options.uneeqOptions.preferredMicrophoneId,!1),this.options.userMessages.next(new i.DeviceListUpdatedMessage(this.devices)))}))}}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.MediaHandler=void 0;const r=n(47),i=n(37),o=n(111),s=n(85),a=n(113),c=n(35),u=n(114);e.MediaHandler=class{constructor(t,e){this.options=t,this.remoteVideoReady=e,this.remoteStream$=new r.BehaviorSubject(null),this.localStream$=new r.BehaviorSubject(null),this.publishState$=new r.BehaviorSubject(s.PublishSubscribeState.DISCONNECTED),this.publishingStream=!1,this.remoteStream$.filter(t=>null!==t).subscribe(n=>{this.avatarVideoElement=this.options.digitalHumanVideoElement,this.avatarVideoElement.srcObject=n,t.uneeqOptions.avatarVideoContainerElement.style.overflow="hidden",t.uneeqOptions.avatarVideoContainerElement.innerHTML="",t.uneeqOptions.avatarVideoContainerElement.appendChild(this.avatarVideoElement),this.options.uneeqOptions.enableTransparentBackground&&this.initTransparentBackground(this.avatarVideoElement),e()}),this.localStream$.filter(t=>null!==t).subscribe(e=>{const n=document.createElement("video");this.localVideoElement=n,n.srcObject=e,n.autoplay=!0,n.muted=!0,n.setAttribute("playsinline","true"),n.setAttribute("style","width: 100%; height: 100%;"),t.uneeqOptions.localVideoContainerElement.innerHTML="",t.uneeqOptions.localVideoContainerElement.appendChild(n),this.options.voiceInputManager.initMicActivity(e),this.options.session.edgeNodeId&&!this.publishingStream&&this.publishVideo()}),this.options.internalMessages$.filter(t=>"AnswerMessage"===t.faceMeMessageType).subscribe(t=>{void 0!==this.webRTC&&this.webRTC.handleAnswerMessage(t)}),this.options.internalMessages$.filter(t=>"IceCandidateMessage"===t.faceMeMessageType).subscribe(t=>{void 0!==this.webRTC&&this.webRTC.handleIceCandidate(t)})}setEdgeNodeId(t){this.options.session.edgeNodeId=t,this.options.session.edgeNodeId&&!this.publishingStream&&this.localStream$.getValue()&&this.publishVideo()}unpublishVideo(){c.logger.log("UserSession | unpublishVideo"),void 0!==this.webRTC&&(this.webRTC.close(),this.webRTC=void 0),this.publishState$.next(s.PublishSubscribeState.DISCONNECTED)}pause(){const t=this.remoteStream$.getValue(),e=this.localStream$.getValue();this.avatarVideoElement.pause(),this.localVideoElement.pause(),e&&e.getTracks().forEach(t=>t.enabled=!1),t&&t.getTracks().forEach(t=>t.enabled=!1)}resume(){const t=this.remoteStream$.getValue(),e=this.localStream$.getValue();e&&e.getTracks().forEach(t=>t.enabled=!0),t&&t.getTracks().forEach(t=>t.enabled=!0),this.avatarVideoElement.play(),this.localVideoElement.play()}stopAllLocalStreams(){const t=this.localStream$.getValue();t&&t.getTracks().forEach(t=>t.stop()),this.publishingStream=!1}endSession(){this.stopAllLocalStreams(),this.options.uneeqOptions.localVideoContainerElement&&this.options.uneeqOptions.localVideoContainerElement&&(this.options.uneeqOptions.localVideoContainerElement.innerHTML=""),this.unpublishVideo(),this.options.uneeqOptions.avatarVideoContainerElement&&this.options.uneeqOptions.avatarVideoContainerElement&&(this.options.uneeqOptions.avatarVideoContainerElement.innerHTML="");const t=this.remoteStream$.getValue();t&&t.getTracks().forEach(t=>t.stop()),this.options.voiceInputManager.handleSessionEnd()}sendDataMessage(t){this.webRTC&&this.webRTC.sendDataMessage(t)}gatherWebRTCStats(t){var e;null===(e=this.webRTC)||void 0===e||e.getStats(t)}publishVideo(){const t=this.options.session.streamId,e=this.options.session.avatarStreamId,n=this.options.session.turnServerAddresses,r=this.options.session.turnUsername,o=this.options.session.turnPassword,a=this.options.session.forceTurnServerUse,h=this.publishState$,l=this.remoteStream$,f=this.localStream$.getValue();if(!f||!this.options.session.edgeNodeId)return void console.error("Not ready to publish");let d=0;c.logger.log("UserSession | publishVideo - stream:",f,"publishStreamName:",t),c.logger.log("PublishVideo with edge node id: ",this.options.session.edgeNodeId),this.publishingStream=!0,null==this.webRTC?(this.webRTC=new u.UneeqWebRTC({messaging:this.options.messaging,userMessages:this.options.userMessages,publishStreamName:t,subscribeStreamName:e,edgeNodeId:this.options.session.edgeNodeId||"id",diagnostics:this.options.uneeqOptions.diagnostics,onAddStream:t=>{c.logger.log("WEBRTC: onAddStream "+t.stream),l.next(t.stream)},forceTurnServerUse:a,iceServers:[{urls:n,username:r,credential:o}],onConnect:()=>{c.logger.log("UserSession | publishVideo | webRtcInstance | onStateChange - connected");h.getValue()===s.PublishSubscribeState.CONNECTING&&h.next(s.PublishSubscribeState.CONNECTED)},onError:t=>{c.logger.log("UserSession | publishVideo | webRtcInstance | onConnectionFailed - ",d),d<3?(d++,this.performWebRTCConnection(f),this.options.userMessages.next(new i.ConnectionLostMessage(s.PublishSubscribeState.DISCONNECTED))):(c.logger.log("UserSession | publishVideo | webRtcInstance | Publish failures > 3, so giving up"),h.next(s.PublishSubscribeState.FAILED),this.options.userMessages.next(new i.ConnectionLostMessage(s.PublishSubscribeState.FAILED)))}}),this.performWebRTCConnection(f)):this.webRTC.updateStreamTracks(f)}performWebRTCConnection(t){this.webRTC&&(this.publishState$.next(s.PublishSubscribeState.CONNECTING),this.webRTC.connect(t))}initTransparentBackground(t){const e=new a.CanvasService(this.options.uneeqOptions).createCanvas();(new o.VideoEditor).applyChromaKeyEffect(e,t),this.avatarVideoElement.style.display="none"}}},function(t,e,n){"use strict";var r=this&&this.__createBinding||(Object.create?function(t,e,n,r){void 0===r&&(r=n),Object.defineProperty(t,r,{enumerable:!0,get:function(){return e[n]}})}:function(t,e,n,r){void 0===r&&(r=n),t[r]=e[n]}),i=this&&this.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),o=this&&this.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(null!=t)for(var n in t)"default"!==n&&Object.hasOwnProperty.call(t,n)&&r(e,t,n);return i(e,t),e};Object.defineProperty(e,"__esModule",{value:!0}),e.VideoEditor=void 0;const s=o(n(83));e.VideoEditor=class{constructor(){}applyChromaKeyEffect(t,e){try{n(112);const r=s.default();let i,o,a;i=r.transform("reformat"),i.source=e,i.width=t.width,i.height=t.height,a=r.target(t),o=r.effect("chroma"),o.source=i,a.source=o,r.go()}catch(t){console.error(t)}}}},function(t,e,n){"use strict";n.r(e),n(83).default.plugin("chroma",{shader:function(t,e){return e.vertex=["precision mediump float;","attribute vec4 position;","attribute vec2 texCoord;","uniform vec2 resolution;","uniform mat4 transform;","varying vec2 vTexCoord;","uniform vec4 screen;","uniform float balance;","varying float screenSat;","varying vec3 screenPrimary;","void main(void) {","\tfloat fmin = min(min(screen.r, screen.g), screen.b);","\tfloat fmax = max(max(screen.r, screen.g), screen.b);","\tfloat secondaryComponents;","\tscreenPrimary = step(fmax, screen.rgb);","\tsecondaryComponents = dot(1.0 - screenPrimary, screen.rgb);","\tscreenSat = fmax - mix(secondaryComponents - fmin, secondaryComponents / 2.0, balance);","\tvec4 screenPosition = vec4(position.xy * resolution / 2.0, position.z, position.w);","\tscreenPosition = transform * screenPosition;","\tgl_Position = screenPosition;","\tgl_Position.xy = screenPosition.xy * 2.0 / resolution;","\tgl_Position.z = screenPosition.z * 2.0 / (resolution.x / resolution.y);","\tvTexCoord = texCoord;","}"].join("\n"),e.fragment=[this.inputs.mask?"#define MASK":"","precision mediump float;","varying vec2 vTexCoord;","uniform sampler2D source;","uniform vec4 screen;","uniform float screenWeight;","uniform float balance;","uniform float clipBlack;","uniform float clipWhite;","uniform bool mask;","varying float screenSat;","varying vec3 screenPrimary;","void main(void) {","\tfloat pixelSat, secondaryComponents;","\tvec4 sourcePixel = texture2D(source, vTexCoord);","\tfloat fmin = min(min(sourcePixel.r, sourcePixel.g), sourcePixel.b);","\tfloat fmax = max(max(sourcePixel.r, sourcePixel.g), sourcePixel.b);","\tvec3 pixelPrimary = step(fmax, sourcePixel.rgb);","\tsecondaryComponents = dot(1.0 - pixelPrimary, sourcePixel.rgb);","\tpixelSat = fmax - mix(secondaryComponents - fmin, secondaryComponents / 2.0, balance);","\tfloat diffPrimary = dot(abs(pixelPrimary - screenPrimary), vec3(1.0));","\tfloat solid = step(1.0, step(pixelSat, 0.1) + step(fmax, 0.1) + diffPrimary);","\tfloat alpha = max(0.0, 1.0 - pixelSat / screenSat);","\talpha = smoothstep(clipBlack, clipWhite, alpha);","\tvec4 semiTransparentPixel = vec4((sourcePixel.rgb - (1.0 - alpha) * screen.rgb * screenWeight) / max(0.00001, alpha), alpha);","\tvec4 pixel = mix(semiTransparentPixel, sourcePixel, solid);","#ifdef MASK","\tgl_FragColor = vec4(vec3(pixel.a), 1.0);","#else","\tgl_FragColor = pixel;","#endif","}"].join("\n"),e},inPlace:!0,inputs:{source:{type:"image",uniform:"source"},screen:{type:"color",uniform:"screen",defaultValue:[66/255,195/255,31/255,1]},weight:{type:"number",uniform:"screenWeight",defaultValue:1,min:0},balance:{type:"number",uniform:"balance",defaultValue:1,min:0,max:1},clipBlack:{type:"number",uniform:"clipBlack",defaultValue:0,min:0,max:1},clipWhite:{type:"number",uniform:"clipWhite",defaultValue:1,min:0,max:1},mask:{type:"boolean",defaultValue:!1,uniform:"mask",shaderDirty:!0}},title:"Chroma Key",description:""})},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.CanvasService=void 0;e.CanvasService=class{constructor(t){this.canvasHeight=720,this.canvasWidth=1280,this.uneeqOptions=t}createCanvas(){const t=document.createElement("canvas");return this.uneeqOptions.avatarVideoContainerElement.appendChild(t),t.setAttribute("style","object-fit: cover; width: 100%; height: 100%;"),t.height=this.canvasHeight,t.width=this.canvasWidth,t}}},function(t,e,n){"use strict";var r=this&&this.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(e,"__esModule",{value:!0}),e.UneeqWebRTC=void 0;const i=r(n(115)),o=r(n(82)),s=n(37),a=n(35);e.UneeqWebRTC=class{constructor(t){this.fakeDataChannel={},this.MESSAGING_ENDPOINT="/app/v2/webRTC",this.onStats=(t,e)=>{this.options.userMessages.next(new s.WebRtcStatsMessage(e)),this.statTimer=window.setTimeout(()=>{this.client.getStats(this.onStats)},2e3)},this.options=Object.assign({forceTurnServerUse:!1,iceServers:[]},t),this.log("Options",this.options),this.uniqueId=Math.random().toString(36).substring(2,12),RTCPeerConnection.prototype.createDataChannel||(this.warn("Implementing a fake createDataChannel"),RTCPeerConnection.prototype.createDataChannel=()=>this.fakeDataChannel)}connect(t){this.close(),this.client=new i.default({initiator:!0,config:{iceServers:this.options.iceServers},stream:t,channelName:"UneeqChannel"}),this.options.diagnostics&&this.enableDiagnostics(),this.fakeDataChannel.onopen&&(this.warn("Calling channel open on fake data channel"),this.fakeDataChannel.onopen()),this.client.on("error",t=>{this.log("error",t),void 0!==this.options.onError&&this.options.onError(t)}),this.client.on("signal",t=>{const e={payload:"",publishStreamName:this.options.publishStreamName,subscribeStreamName:this.options.subscribeStreamName,uniqueId:this.uniqueId,userAgent:navigator.userAgent,edgeNodeId:this.options.edgeNodeId};if("type"in t&&"offer"===t.type)e.payload=JSON.stringify({type:"offer",sdp:t.sdp}),e.type="OfferMessage",this.log("Offer payload ",e),this.options.messaging.send(this.MESSAGING_ENDPOINT,e);else if("candidate"in t){const n=JSON.stringify(t.candidate);this.options.forceTurnServerUse&&!n.match(/typ relay/)||n.match(/::/)||(e.payload=n,e.type="IceCandidate",this.log("IC payload ",e),this.options.messaging.send(this.MESSAGING_ENDPOINT,e))}else this.warn("WARNING Unhandled signal: ",JSON.stringify(t))}),this.client.on("connect",()=>{this.log("CONNECT"),void 0!==this.options.onConnect&&this.options.onConnect()}),this.client.on("data",t=>{this.log("data: "+t),void 0!==this.options.onData&&this.options.onData(t),this.options.userMessages.next(new s.WebRtcDataMessage(t))}),this.client.on("close",()=>{this.log("WebRTC session closed: "+this.uniqueId),this.client=null,void 0!==this.options.onClose&&this.options.onClose()}),this.client.on("stream",t=>{void 0!==this.options.onAddStream&&this.options.onAddStream({stream:t})})}close(){this.client&&(this.client.destroy(),this.client=null),this.statTimer&&clearTimeout(this.statTimer)}handleAnswerMessage(t){if(this.isMessageForUs(t)&&this.client){const e=JSON.parse(t.payload);return this.log("got answer: ",e),this.client.signal(e),!0}return this.log("ignoring answer: ",t),!1}handleIceCandidate(t){if(this.isMessageForUs(t)&&this.client){const e=JSON.parse(t.payload);if("candidate"in e&&""===e.candidate){if("edge"===o.default.browserDetails.browser){const t=this.client._pc;t.remoteDescription&&t.remoteDescription.type&&t.addIceCandidate(null)}}else this.client.signal({candidate:e});return!0}return!1}sendDataMessage(t){this.client.send(t)}getStats(t){return this.client&&this.client.getStats(t)}updateStreamTracks(t){t.getTracks().forEach(t=>{this.client._pc.getSenders().find(e=>t.kind===e.track.kind).replaceTrack(t).then(()=>{a.logger.log("Updated publish media stream track for "+t.kind)}).catch(e=>{a.logger.error("Error: updating publish media stream track failed for "+t.kind,e)})})}enableDiagnostics(){this.client._pc&&0!==this.client._pc.getStats.length&&(this.client._pc.getStats=""),this.client.getStats(this.onStats)}isMessageForUs(t){return t.requestUniqueId===this.uniqueId}log(t,...e){a.logger.log("UneeqWebRTC: "+t,e)}warn(t,...e){a.logger.warn("UneeqWebRTC: "+t,e)}}},function(t,e,n){
36
36
  /*! simple-peer. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */
37
37
  const r=n(116)("simple-peer"),i=n(119),o=n(120),s=n(121),a=n(130),c=n(131),{Buffer:u}=n(44);function h(t){return t.replace(/a=ice-options:trickle\s\n/g,"")}class l extends s.Duplex{constructor(t){if(super(t=Object.assign({allowHalfOpen:!1},t)),this._id=o(4).toString("hex").slice(0,7),this._debug("new peer %o",t),this.channelName=t.initiator?t.channelName||o(20).toString("hex"):null,this.initiator=t.initiator||!1,this.channelConfig=t.channelConfig||l.channelConfig,this.channelNegotiated=this.channelConfig.negotiated,this.config=Object.assign({},l.config,t.config),this.offerOptions=t.offerOptions||{},this.answerOptions=t.answerOptions||{},this.sdpTransform=t.sdpTransform||(t=>t),this.streams=t.streams||(t.stream?[t.stream]:[]),this.trickle=void 0===t.trickle||t.trickle,this.allowHalfTrickle=void 0!==t.allowHalfTrickle&&t.allowHalfTrickle,this.iceCompleteTimeout=t.iceCompleteTimeout||5e3,this.destroyed=!1,this.destroying=!1,this._connected=!1,this.remoteAddress=void 0,this.remoteFamily=void 0,this.remotePort=void 0,this.localAddress=void 0,this.localFamily=void 0,this.localPort=void 0,this._wrtc=t.wrtc&&"object"==typeof t.wrtc?t.wrtc:i(),!this._wrtc)throw"undefined"==typeof window?c(new Error("No WebRTC support: Specify `opts.wrtc` option in this environment"),"ERR_WEBRTC_SUPPORT"):c(new Error("No WebRTC support: Not a supported browser"),"ERR_WEBRTC_SUPPORT");this._pcReady=!1,this._channelReady=!1,this._iceComplete=!1,this._iceCompleteTimer=null,this._channel=null,this._pendingCandidates=[],this._isNegotiating=!1,this._firstNegotiation=!0,this._batchedNegotiation=!1,this._queuedNegotiation=!1,this._sendersAwaitingStable=[],this._senderMap=new Map,this._closingInterval=null,this._remoteTracks=[],this._remoteStreams=[],this._chunk=null,this._cb=null,this._interval=null;try{this._pc=new this._wrtc.RTCPeerConnection(this.config)}catch(t){return void this.destroy(c(t,"ERR_PC_CONSTRUCTOR"))}this._isReactNativeWebrtc="number"==typeof this._pc._peerConnectionId,this._pc.oniceconnectionstatechange=()=>{this._onIceStateChange()},this._pc.onicegatheringstatechange=()=>{this._onIceStateChange()},this._pc.onconnectionstatechange=()=>{this._onConnectionStateChange()},this._pc.onsignalingstatechange=()=>{this._onSignalingStateChange()},this._pc.onicecandidate=t=>{this._onIceCandidate(t)},"object"==typeof this._pc.peerIdentity&&this._pc.peerIdentity.catch(t=>{this.destroy(c(t,"ERR_PC_PEER_IDENTITY"))}),this.initiator||this.channelNegotiated?this._setupData({channel:this._pc.createDataChannel(this.channelName,this.channelConfig)}):this._pc.ondatachannel=t=>{this._setupData(t)},this.streams&&this.streams.forEach(t=>{this.addStream(t)}),this._pc.ontrack=t=>{this._onTrack(t)},this._debug("initial negotiation"),this._needsNegotiation(),this._onFinishBound=()=>{this._onFinish()},this.once("finish",this._onFinishBound)}get bufferSize(){return this._channel&&this._channel.bufferedAmount||0}get connected(){return this._connected&&"open"===this._channel.readyState}address(){return{port:this.localPort,family:this.localFamily,address:this.localAddress}}signal(t){if(!this.destroying){if(this.destroyed)throw c(new Error("cannot signal after peer is destroyed"),"ERR_DESTROYED");if("string"==typeof t)try{t=JSON.parse(t)}catch(e){t={}}this._debug("signal()"),t.renegotiate&&this.initiator&&(this._debug("got request to renegotiate"),this._needsNegotiation()),t.transceiverRequest&&this.initiator&&(this._debug("got request for transceiver"),this.addTransceiver(t.transceiverRequest.kind,t.transceiverRequest.init)),t.candidate&&(this._pc.remoteDescription&&this._pc.remoteDescription.type?this._addIceCandidate(t.candidate):this._pendingCandidates.push(t.candidate)),t.sdp&&this._pc.setRemoteDescription(new this._wrtc.RTCSessionDescription(t)).then(()=>{this.destroyed||(this._pendingCandidates.forEach(t=>{this._addIceCandidate(t)}),this._pendingCandidates=[],"offer"===this._pc.remoteDescription.type&&this._createAnswer())}).catch(t=>{this.destroy(c(t,"ERR_SET_REMOTE_DESCRIPTION"))}),t.sdp||t.candidate||t.renegotiate||t.transceiverRequest||this.destroy(c(new Error("signal() called with invalid signal data"),"ERR_SIGNALING"))}}_addIceCandidate(t){const e=new this._wrtc.RTCIceCandidate(t);this._pc.addIceCandidate(e).catch(t=>{var n;!e.address||e.address.endsWith(".local")?(n="Ignoring unsupported ICE candidate.",console.warn(n)):this.destroy(c(t,"ERR_ADD_ICE_CANDIDATE"))})}send(t){if(!this.destroying){if(this.destroyed)throw c(new Error("cannot send after peer is destroyed"),"ERR_DESTROYED");this._channel.send(t)}}addTransceiver(t,e){if(!this.destroying){if(this.destroyed)throw c(new Error("cannot addTransceiver after peer is destroyed"),"ERR_DESTROYED");if(this._debug("addTransceiver()"),this.initiator)try{this._pc.addTransceiver(t,e),this._needsNegotiation()}catch(t){this.destroy(c(t,"ERR_ADD_TRANSCEIVER"))}else this.emit("signal",{type:"transceiverRequest",transceiverRequest:{kind:t,init:e}})}}addStream(t){if(!this.destroying){if(this.destroyed)throw c(new Error("cannot addStream after peer is destroyed"),"ERR_DESTROYED");this._debug("addStream()"),t.getTracks().forEach(e=>{this.addTrack(e,t)})}}addTrack(t,e){if(this.destroying)return;if(this.destroyed)throw c(new Error("cannot addTrack after peer is destroyed"),"ERR_DESTROYED");this._debug("addTrack()");const n=this._senderMap.get(t)||new Map;let r=n.get(e);if(r)throw r.removed?c(new Error("Track has been removed. You should enable/disable tracks that you want to re-add."),"ERR_SENDER_REMOVED"):c(new Error("Track has already been added to that stream."),"ERR_SENDER_ALREADY_ADDED");r=this._pc.addTrack(t,e),n.set(e,r),this._senderMap.set(t,n),this._needsNegotiation()}replaceTrack(t,e,n){if(this.destroying)return;if(this.destroyed)throw c(new Error("cannot replaceTrack after peer is destroyed"),"ERR_DESTROYED");this._debug("replaceTrack()");const r=this._senderMap.get(t),i=r?r.get(n):null;if(!i)throw c(new Error("Cannot replace track that was never added."),"ERR_TRACK_NOT_ADDED");e&&this._senderMap.set(e,r),null!=i.replaceTrack?i.replaceTrack(e):this.destroy(c(new Error("replaceTrack is not supported in this browser"),"ERR_UNSUPPORTED_REPLACETRACK"))}removeTrack(t,e){if(this.destroying)return;if(this.destroyed)throw c(new Error("cannot removeTrack after peer is destroyed"),"ERR_DESTROYED");this._debug("removeSender()");const n=this._senderMap.get(t),r=n?n.get(e):null;if(!r)throw c(new Error("Cannot remove track that was never added."),"ERR_TRACK_NOT_ADDED");try{r.removed=!0,this._pc.removeTrack(r)}catch(t){"NS_ERROR_UNEXPECTED"===t.name?this._sendersAwaitingStable.push(r):this.destroy(c(t,"ERR_REMOVE_TRACK"))}this._needsNegotiation()}removeStream(t){if(!this.destroying){if(this.destroyed)throw c(new Error("cannot removeStream after peer is destroyed"),"ERR_DESTROYED");this._debug("removeSenders()"),t.getTracks().forEach(e=>{this.removeTrack(e,t)})}}_needsNegotiation(){this._debug("_needsNegotiation"),this._batchedNegotiation||(this._batchedNegotiation=!0,a(()=>{this._batchedNegotiation=!1,this.initiator||!this._firstNegotiation?(this._debug("starting batched negotiation"),this.negotiate()):this._debug("non-initiator initial negotiation request discarded"),this._firstNegotiation=!1}))}negotiate(){if(!this.destroying){if(this.destroyed)throw c(new Error("cannot negotiate after peer is destroyed"),"ERR_DESTROYED");this.initiator?this._isNegotiating?(this._queuedNegotiation=!0,this._debug("already negotiating, queueing")):(this._debug("start negotiation"),setTimeout(()=>{this._createOffer()},0)):this._isNegotiating?(this._queuedNegotiation=!0,this._debug("already negotiating, queueing")):(this._debug("requesting negotiation from initiator"),this.emit("signal",{type:"renegotiate",renegotiate:!0})),this._isNegotiating=!0}}destroy(t){this._destroy(t,()=>{})}_destroy(t,e){this.destroyed||this.destroying||(this.destroying=!0,this._debug("destroying (error: %s)",t&&(t.message||t)),a(()=>{if(this.destroyed=!0,this.destroying=!1,this._debug("destroy (error: %s)",t&&(t.message||t)),this.readable=this.writable=!1,this._readableState.ended||this.push(null),this._writableState.finished||this.end(),this._connected=!1,this._pcReady=!1,this._channelReady=!1,this._remoteTracks=null,this._remoteStreams=null,this._senderMap=null,clearInterval(this._closingInterval),this._closingInterval=null,clearInterval(this._interval),this._interval=null,this._chunk=null,this._cb=null,this._onFinishBound&&this.removeListener("finish",this._onFinishBound),this._onFinishBound=null,this._channel){try{this._channel.close()}catch(t){}this._channel.onmessage=null,this._channel.onopen=null,this._channel.onclose=null,this._channel.onerror=null}if(this._pc){try{this._pc.close()}catch(t){}this._pc.oniceconnectionstatechange=null,this._pc.onicegatheringstatechange=null,this._pc.onsignalingstatechange=null,this._pc.onicecandidate=null,this._pc.ontrack=null,this._pc.ondatachannel=null}this._pc=null,this._channel=null,t&&this.emit("error",t),this.emit("close"),e()}))}_setupData(t){if(!t.channel)return this.destroy(c(new Error("Data channel event is missing `channel` property"),"ERR_DATA_CHANNEL"));this._channel=t.channel,this._channel.binaryType="arraybuffer","number"==typeof this._channel.bufferedAmountLowThreshold&&(this._channel.bufferedAmountLowThreshold=65536),this.channelName=this._channel.label,this._channel.onmessage=t=>{this._onChannelMessage(t)},this._channel.onbufferedamountlow=()=>{this._onChannelBufferedAmountLow()},this._channel.onopen=()=>{this._onChannelOpen()},this._channel.onclose=()=>{this._onChannelClose()},this._channel.onerror=t=>{const e=t.error instanceof Error?t.error:new Error(`Datachannel error: ${t.message} ${t.filename}:${t.lineno}:${t.colno}`);this.destroy(c(e,"ERR_DATA_CHANNEL"))};let e=!1;this._closingInterval=setInterval(()=>{this._channel&&"closing"===this._channel.readyState?(e&&this._onChannelClose(),e=!0):e=!1},5e3)}_read(){}_write(t,e,n){if(this.destroyed)return n(c(new Error("cannot write after peer is destroyed"),"ERR_DATA_CHANNEL"));if(this._connected){try{this.send(t)}catch(t){return this.destroy(c(t,"ERR_DATA_CHANNEL"))}this._channel.bufferedAmount>65536?(this._debug("start backpressure: bufferedAmount %d",this._channel.bufferedAmount),this._cb=n):n(null)}else this._debug("write before connect"),this._chunk=t,this._cb=n}_onFinish(){if(this.destroyed)return;const t=()=>{setTimeout(()=>this.destroy(),1e3)};this._connected?t():this.once("connect",t)}_startIceCompleteTimeout(){this.destroyed||this._iceCompleteTimer||(this._debug("started iceComplete timeout"),this._iceCompleteTimer=setTimeout(()=>{this._iceComplete||(this._iceComplete=!0,this._debug("iceComplete timeout completed"),this.emit("iceTimeout"),this.emit("_iceComplete"))},this.iceCompleteTimeout))}_createOffer(){this.destroyed||this._pc.createOffer(this.offerOptions).then(t=>{if(this.destroyed)return;this.trickle||this.allowHalfTrickle||(t.sdp=h(t.sdp)),t.sdp=this.sdpTransform(t.sdp);const e=()=>{if(this.destroyed)return;const e=this._pc.localDescription||t;this._debug("signal"),this.emit("signal",{type:e.type,sdp:e.sdp})};this._pc.setLocalDescription(t).then(()=>{this._debug("createOffer success"),this.destroyed||(this.trickle||this._iceComplete?e():this.once("_iceComplete",e))}).catch(t=>{this.destroy(c(t,"ERR_SET_LOCAL_DESCRIPTION"))})}).catch(t=>{this.destroy(c(t,"ERR_CREATE_OFFER"))})}_requestMissingTransceivers(){this._pc.getTransceivers&&this._pc.getTransceivers().forEach(t=>{t.mid||!t.sender.track||t.requested||(t.requested=!0,this.addTransceiver(t.sender.track.kind))})}_createAnswer(){this.destroyed||this._pc.createAnswer(this.answerOptions).then(t=>{if(this.destroyed)return;this.trickle||this.allowHalfTrickle||(t.sdp=h(t.sdp)),t.sdp=this.sdpTransform(t.sdp);const e=()=>{if(this.destroyed)return;const e=this._pc.localDescription||t;this._debug("signal"),this.emit("signal",{type:e.type,sdp:e.sdp}),this.initiator||this._requestMissingTransceivers()};this._pc.setLocalDescription(t).then(()=>{this.destroyed||(this.trickle||this._iceComplete?e():this.once("_iceComplete",e))}).catch(t=>{this.destroy(c(t,"ERR_SET_LOCAL_DESCRIPTION"))})}).catch(t=>{this.destroy(c(t,"ERR_CREATE_ANSWER"))})}_onConnectionStateChange(){this.destroyed||"failed"===this._pc.connectionState&&this.destroy(c(new Error("Connection failed."),"ERR_CONNECTION_FAILURE"))}_onIceStateChange(){if(this.destroyed)return;const t=this._pc.iceConnectionState,e=this._pc.iceGatheringState;this._debug("iceStateChange (connection: %s) (gathering: %s)",t,e),this.emit("iceStateChange",t,e),"connected"!==t&&"completed"!==t||(this._pcReady=!0,this._maybeReady()),"failed"===t&&this.destroy(c(new Error("Ice connection failed."),"ERR_ICE_CONNECTION_FAILURE")),"closed"===t&&this.destroy(c(new Error("Ice connection closed."),"ERR_ICE_CONNECTION_CLOSED"))}getStats(t){const e=t=>("[object Array]"===Object.prototype.toString.call(t.values)&&t.values.forEach(e=>{Object.assign(t,e)}),t);0===this._pc.getStats.length||this._isReactNativeWebrtc?this._pc.getStats().then(n=>{const r=[];n.forEach(t=>{r.push(e(t))}),t(null,r)},e=>t(e)):this._pc.getStats.length>0?this._pc.getStats(n=>{if(this.destroyed)return;const r=[];n.result().forEach(t=>{const n={};t.names().forEach(e=>{n[e]=t.stat(e)}),n.id=t.id,n.type=t.type,n.timestamp=t.timestamp,r.push(e(n))}),t(null,r)},e=>t(e)):t(null,[])}_maybeReady(){if(this._debug("maybeReady pc %s channel %s",this._pcReady,this._channelReady),this._connected||this._connecting||!this._pcReady||!this._channelReady)return;this._connecting=!0;const t=()=>{this.destroyed||this.getStats((e,n)=>{if(this.destroyed)return;e&&(n=[]);const r={},i={},o={};let s=!1;n.forEach(t=>{"remotecandidate"!==t.type&&"remote-candidate"!==t.type||(r[t.id]=t),"localcandidate"!==t.type&&"local-candidate"!==t.type||(i[t.id]=t),"candidatepair"!==t.type&&"candidate-pair"!==t.type||(o[t.id]=t)});const a=t=>{s=!0;let e=i[t.localCandidateId];e&&(e.ip||e.address)?(this.localAddress=e.ip||e.address,this.localPort=Number(e.port)):e&&e.ipAddress?(this.localAddress=e.ipAddress,this.localPort=Number(e.portNumber)):"string"==typeof t.googLocalAddress&&(e=t.googLocalAddress.split(":"),this.localAddress=e[0],this.localPort=Number(e[1])),this.localAddress&&(this.localFamily=this.localAddress.includes(":")?"IPv6":"IPv4");let n=r[t.remoteCandidateId];n&&(n.ip||n.address)?(this.remoteAddress=n.ip||n.address,this.remotePort=Number(n.port)):n&&n.ipAddress?(this.remoteAddress=n.ipAddress,this.remotePort=Number(n.portNumber)):"string"==typeof t.googRemoteAddress&&(n=t.googRemoteAddress.split(":"),this.remoteAddress=n[0],this.remotePort=Number(n[1])),this.remoteAddress&&(this.remoteFamily=this.remoteAddress.includes(":")?"IPv6":"IPv4"),this._debug("connect local: %s:%s remote: %s:%s",this.localAddress,this.localPort,this.remoteAddress,this.remotePort)};if(n.forEach(t=>{"transport"===t.type&&t.selectedCandidatePairId&&a(o[t.selectedCandidatePairId]),("googCandidatePair"===t.type&&"true"===t.googActiveConnection||("candidatepair"===t.type||"candidate-pair"===t.type)&&t.selected)&&a(t)}),s||Object.keys(o).length&&!Object.keys(i).length){if(this._connecting=!1,this._connected=!0,this._chunk){try{this.send(this._chunk)}catch(e){return this.destroy(c(e,"ERR_DATA_CHANNEL"))}this._chunk=null,this._debug('sent chunk from "write before connect"');const t=this._cb;this._cb=null,t(null)}"number"!=typeof this._channel.bufferedAmountLowThreshold&&(this._interval=setInterval(()=>this._onInterval(),150),this._interval.unref&&this._interval.unref()),this._debug("connect"),this.emit("connect")}else setTimeout(t,100)})};t()}_onInterval(){!this._cb||!this._channel||this._channel.bufferedAmount>65536||this._onChannelBufferedAmountLow()}_onSignalingStateChange(){this.destroyed||("stable"===this._pc.signalingState&&(this._isNegotiating=!1,this._debug("flushing sender queue",this._sendersAwaitingStable),this._sendersAwaitingStable.forEach(t=>{this._pc.removeTrack(t),this._queuedNegotiation=!0}),this._sendersAwaitingStable=[],this._queuedNegotiation?(this._debug("flushing negotiation queue"),this._queuedNegotiation=!1,this._needsNegotiation()):(this._debug("negotiated"),this.emit("negotiated"))),this._debug("signalingStateChange %s",this._pc.signalingState),this.emit("signalingStateChange",this._pc.signalingState))}_onIceCandidate(t){this.destroyed||(t.candidate&&this.trickle?this.emit("signal",{type:"candidate",candidate:{candidate:t.candidate.candidate,sdpMLineIndex:t.candidate.sdpMLineIndex,sdpMid:t.candidate.sdpMid}}):t.candidate||this._iceComplete||(this._iceComplete=!0,this.emit("_iceComplete")),t.candidate&&this._startIceCompleteTimeout())}_onChannelMessage(t){if(this.destroyed)return;let e=t.data;e instanceof ArrayBuffer&&(e=u.from(e)),this.push(e)}_onChannelBufferedAmountLow(){if(this.destroyed||!this._cb)return;this._debug("ending backpressure: bufferedAmount %d",this._channel.bufferedAmount);const t=this._cb;this._cb=null,t(null)}_onChannelOpen(){this._connected||this.destroyed||(this._debug("on channel open"),this._channelReady=!0,this._maybeReady())}_onChannelClose(){this.destroyed||(this._debug("on channel close"),this.destroy())}_onTrack(t){this.destroyed||t.streams.forEach(e=>{this._debug("on track"),this.emit("track",t.track,e),this._remoteTracks.push({track:t.track,stream:e}),this._remoteStreams.some(t=>t.id===e.id)||(this._remoteStreams.push(e),a(()=>{this._debug("on stream"),this.emit("stream",e)}))})}_debug(){const t=[].slice.call(arguments);t[0]="["+this._id+"] "+t[0],r.apply(null,t)}}l.WEBRTC_SUPPORT=!!i(),l.config={iceServers:[{urls:["stun:stun.l.google.com:19302","stun:global.stun.twilio.com:3478"]}],sdpSemantics:"unified-plan"},l.channelConfig={},t.exports=l},function(t,e,n){(function(r){e.formatArgs=function(e){if(e[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+e[0]+(this.useColors?"%c ":" ")+"+"+t.exports.humanize(this.diff),!this.useColors)return;const n="color: "+this.color;e.splice(1,0,n,"color: inherit");let r=0,i=0;e[0].replace(/%[a-zA-Z%]/g,t=>{"%%"!==t&&(r++,"%c"===t&&(i=r))}),e.splice(i,0,n)},e.save=function(t){try{t?e.storage.setItem("debug",t):e.storage.removeItem("debug")}catch(t){}},e.load=function(){let t;try{t=e.storage.getItem("debug")}catch(t){}!t&&void 0!==r&&"env"in r&&(t=r.env.DEBUG);return t},e.useColors=function(){if("undefined"!=typeof window&&window.process&&("renderer"===window.process.type||window.process.__nwjs))return!0;if("undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;return"undefined"!=typeof document&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||"undefined"!=typeof window&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)&&parseInt(RegExp.$1,10)>=31||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)},e.storage=function(){try{return localStorage}catch(t){}}(),e.destroy=(()=>{let t=!1;return()=>{t||(t=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})(),e.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"],e.log=console.debug||console.log||(()=>{}),t.exports=n(117)(e);const{formatters:i}=t.exports;i.j=function(t){try{return JSON.stringify(t)}catch(t){return"[UnexpectedJSONParseError]: "+t.message}}}).call(this,n(38))},function(t,e,n){t.exports=function(t){function e(t){let n,i,o,s=null;function a(...t){if(!a.enabled)return;const r=a,i=Number(new Date),o=i-(n||i);r.diff=o,r.prev=n,r.curr=i,n=i,t[0]=e.coerce(t[0]),"string"!=typeof t[0]&&t.unshift("%O");let s=0;t[0]=t[0].replace(/%([a-zA-Z%])/g,(n,i)=>{if("%%"===n)return"%";s++;const o=e.formatters[i];if("function"==typeof o){const e=t[s];n=o.call(r,e),t.splice(s,1),s--}return n}),e.formatArgs.call(r,t);(r.log||e.log).apply(r,t)}return a.namespace=t,a.useColors=e.useColors(),a.color=e.selectColor(t),a.extend=r,a.destroy=e.destroy,Object.defineProperty(a,"enabled",{enumerable:!0,configurable:!1,get:()=>null!==s?s:(i!==e.namespaces&&(i=e.namespaces,o=e.enabled(t)),o),set:t=>{s=t}}),"function"==typeof e.init&&e.init(a),a}function r(t,n){const r=e(this.namespace+(void 0===n?":":n)+t);return r.log=this.log,r}function i(t){return t.toString().substring(2,t.toString().length-2).replace(/\.\*\?$/,"*")}return e.debug=e,e.default=e,e.coerce=function(t){if(t instanceof Error)return t.stack||t.message;return t},e.disable=function(){const t=[...e.names.map(i),...e.skips.map(i).map(t=>"-"+t)].join(",");return e.enable(""),t},e.enable=function(t){let n;e.save(t),e.namespaces=t,e.names=[],e.skips=[];const r=("string"==typeof t?t:"").split(/[\s,]+/),i=r.length;for(n=0;n<i;n++)r[n]&&("-"===(t=r[n].replace(/\*/g,".*?"))[0]?e.skips.push(new RegExp("^"+t.slice(1)+"$")):e.names.push(new RegExp("^"+t+"$")))},e.enabled=function(t){if("*"===t[t.length-1])return!0;let n,r;for(n=0,r=e.skips.length;n<r;n++)if(e.skips[n].test(t))return!1;for(n=0,r=e.names.length;n<r;n++)if(e.names[n].test(t))return!0;return!1},e.humanize=n(118),e.destroy=function(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")},Object.keys(t).forEach(n=>{e[n]=t[n]}),e.names=[],e.skips=[],e.formatters={},e.selectColor=function(t){let n=0;for(let e=0;e<t.length;e++)n=(n<<5)-n+t.charCodeAt(e),n|=0;return e.colors[Math.abs(n)%e.colors.length]},e.enable(e.load()),e}},function(t,e){var n=1e3,r=6e4,i=60*r,o=24*i;function s(t,e,n,r){var i=e>=1.5*n;return Math.round(t/n)+" "+r+(i?"s":"")}t.exports=function(t,e){e=e||{};var a=typeof t;if("string"===a&&t.length>0)return function(t){if((t=String(t)).length>100)return;var e=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(t);if(!e)return;var s=parseFloat(e[1]);switch((e[2]||"ms").toLowerCase()){case"years":case"year":case"yrs":case"yr":case"y":return 315576e5*s;case"weeks":case"week":case"w":return 6048e5*s;case"days":case"day":case"d":return s*o;case"hours":case"hour":case"hrs":case"hr":case"h":return s*i;case"minutes":case"minute":case"mins":case"min":case"m":return s*r;case"seconds":case"second":case"secs":case"sec":case"s":return s*n;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return s;default:return}}(t);if("number"===a&&isFinite(t))return e.long?function(t){var e=Math.abs(t);if(e>=o)return s(t,e,o,"day");if(e>=i)return s(t,e,i,"hour");if(e>=r)return s(t,e,r,"minute");if(e>=n)return s(t,e,n,"second");return t+" ms"}(t):function(t){var e=Math.abs(t);if(e>=o)return Math.round(t/o)+"d";if(e>=i)return Math.round(t/i)+"h";if(e>=r)return Math.round(t/r)+"m";if(e>=n)return Math.round(t/n)+"s";return t+"ms"}(t);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(t))}},function(t,e){t.exports=function(){if("undefined"==typeof globalThis)return null;var t={RTCPeerConnection:globalThis.RTCPeerConnection||globalThis.mozRTCPeerConnection||globalThis.webkitRTCPeerConnection,RTCSessionDescription:globalThis.RTCSessionDescription||globalThis.mozRTCSessionDescription||globalThis.webkitRTCSessionDescription,RTCIceCandidate:globalThis.RTCIceCandidate||globalThis.mozRTCIceCandidate||globalThis.webkitRTCIceCandidate};return t.RTCPeerConnection?t:null}},function(t,e,n){"use strict";(function(e,r){var i=n(86).Buffer,o=e.crypto||e.msCrypto;o&&o.getRandomValues?t.exports=function(t,e){if(t>4294967295)throw new RangeError("requested too many random bytes");var n=i.allocUnsafe(t);if(t>0)if(t>65536)for(var s=0;s<t;s+=65536)o.getRandomValues(n.slice(s,s+65536));else o.getRandomValues(n);if("function"==typeof e)return r.nextTick((function(){e(null,n)}));return n}:t.exports=function(){throw new Error("Secure random number generation is not supported by this browser.\nUse Chrome, Firefox or Internet Explorer 11")}}).call(this,n(34),n(38))},function(t,e,n){(e=t.exports=n(87)).Stream=e,e.Readable=e,e.Writable=n(92),e.Duplex=n(46),e.Transform=n(94),e.PassThrough=n(128),e.finished=n(79),e.pipeline=n(129)},function(t,e){},function(t,e,n){"use strict";function r(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter((function(e){return Object.getOwnPropertyDescriptor(t,e).enumerable}))),n.push.apply(n,r)}return n}function i(t,e,n){return e in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function o(t,e){for(var n=0;n<e.length;n++){var r=e[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(t,r.key,r)}}var s=n(44).Buffer,a=n(124).inspect,c=a&&a.custom||"inspect";t.exports=function(){function t(){!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,t),this.head=null,this.tail=null,this.length=0}var e,n,u;return e=t,(n=[{key:"push",value:function(t){var e={data:t,next:null};this.length>0?this.tail.next=e:this.head=e,this.tail=e,++this.length}},{key:"unshift",value:function(t){var e={data:t,next:this.head};0===this.length&&(this.tail=e),this.head=e,++this.length}},{key:"shift",value:function(){if(0!==this.length){var t=this.head.data;return 1===this.length?this.head=this.tail=null:this.head=this.head.next,--this.length,t}}},{key:"clear",value:function(){this.head=this.tail=null,this.length=0}},{key:"join",value:function(t){if(0===this.length)return"";for(var e=this.head,n=""+e.data;e=e.next;)n+=t+e.data;return n}},{key:"concat",value:function(t){if(0===this.length)return s.alloc(0);for(var e,n,r,i=s.allocUnsafe(t>>>0),o=this.head,a=0;o;)e=o.data,n=i,r=a,s.prototype.copy.call(e,n,r),a+=o.data.length,o=o.next;return i}},{key:"consume",value:function(t,e){var n;return t<this.head.data.length?(n=this.head.data.slice(0,t),this.head.data=this.head.data.slice(t)):n=t===this.head.data.length?this.shift():e?this._getString(t):this._getBuffer(t),n}},{key:"first",value:function(){return this.head.data}},{key:"_getString",value:function(t){var e=this.head,n=1,r=e.data;for(t-=r.length;e=e.next;){var i=e.data,o=t>i.length?i.length:t;if(o===i.length?r+=i:r+=i.slice(0,t),0==(t-=o)){o===i.length?(++n,e.next?this.head=e.next:this.head=this.tail=null):(this.head=e,e.data=i.slice(o));break}++n}return this.length-=n,r}},{key:"_getBuffer",value:function(t){var e=s.allocUnsafe(t),n=this.head,r=1;for(n.data.copy(e),t-=n.data.length;n=n.next;){var i=n.data,o=t>i.length?i.length:t;if(i.copy(e,e.length-t,0,o),0==(t-=o)){o===i.length?(++r,n.next?this.head=n.next:this.head=this.tail=null):(this.head=n,n.data=i.slice(o));break}++r}return this.length-=r,e}},{key:c,value:function(t,e){return a(this,function(t){for(var e=1;e<arguments.length;e++){var n=null!=arguments[e]?arguments[e]:{};e%2?r(Object(n),!0).forEach((function(e){i(t,e,n[e])})):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):r(Object(n)).forEach((function(e){Object.defineProperty(t,e,Object.getOwnPropertyDescriptor(n,e))}))}return t}({},e,{depth:0,customInspect:!1}))}}])&&o(e.prototype,n),u&&o(e,u),t}()},function(t,e){},function(t,e,n){(function(e){function n(t){try{if(!e.localStorage)return!1}catch(t){return!1}var n=e.localStorage[t];return null!=n&&"true"===String(n).toLowerCase()}t.exports=function(t,e){if(n("noDeprecation"))return t;var r=!1;return function(){if(!r){if(n("throwDeprecation"))throw new Error(e);n("traceDeprecation")?console.trace(e):console.warn(e),r=!0}return t.apply(this,arguments)}}}).call(this,n(34))},function(t,e,n){"use strict";(function(e){var r;function i(t,e,n){return e in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}var o=n(79),s=Symbol("lastResolve"),a=Symbol("lastReject"),c=Symbol("error"),u=Symbol("ended"),h=Symbol("lastPromise"),l=Symbol("handlePromise"),f=Symbol("stream");function d(t,e){return{value:t,done:e}}function p(t){var e=t[s];if(null!==e){var n=t[f].read();null!==n&&(t[h]=null,t[s]=null,t[a]=null,e(d(n,!1)))}}function v(t){e.nextTick(p,t)}var g=Object.getPrototypeOf((function(){})),m=Object.setPrototypeOf((i(r={get stream(){return this[f]},next:function(){var t=this,n=this[c];if(null!==n)return Promise.reject(n);if(this[u])return Promise.resolve(d(void 0,!0));if(this[f].destroyed)return new Promise((function(n,r){e.nextTick((function(){t[c]?r(t[c]):n(d(void 0,!0))}))}));var r,i=this[h];if(i)r=new Promise(function(t,e){return function(n,r){t.then((function(){e[u]?n(d(void 0,!0)):e[l](n,r)}),r)}}(i,this));else{var o=this[f].read();if(null!==o)return Promise.resolve(d(o,!1));r=new Promise(this[l])}return this[h]=r,r}},Symbol.asyncIterator,(function(){return this})),i(r,"return",(function(){var t=this;return new Promise((function(e,n){t[f].destroy(null,(function(t){t?n(t):e(d(void 0,!0))}))}))})),r),g);t.exports=function(t){var e,n=Object.create(m,(i(e={},f,{value:t,writable:!0}),i(e,s,{value:null,writable:!0}),i(e,a,{value:null,writable:!0}),i(e,c,{value:null,writable:!0}),i(e,u,{value:t._readableState.endEmitted,writable:!0}),i(e,l,{value:function(t,e){var r=n[f].read();r?(n[h]=null,n[s]=null,n[a]=null,t(d(r,!1))):(n[s]=t,n[a]=e)},writable:!0}),e));return n[h]=null,o(t,(function(t){if(t&&"ERR_STREAM_PREMATURE_CLOSE"!==t.code){var e=n[a];return null!==e&&(n[h]=null,n[s]=null,n[a]=null,e(t)),void(n[c]=t)}var r=n[s];null!==r&&(n[h]=null,n[s]=null,n[a]=null,r(d(void 0,!0))),n[u]=!0})),t.on("readable",v.bind(null,n)),n}}).call(this,n(38))},function(t,e){t.exports=function(){throw new Error("Readable.from is not available in the browser")}},function(t,e,n){"use strict";t.exports=i;var r=n(94);function i(t){if(!(this instanceof i))return new i(t);r.call(this,t)}n(59)(i,r),i.prototype._transform=function(t,e,n){n(null,t)}},function(t,e,n){"use strict";var r;var i=n(45).codes,o=i.ERR_MISSING_ARGS,s=i.ERR_STREAM_DESTROYED;function a(t){if(t)throw t}function c(t,e,i,o){o=function(t){var e=!1;return function(){e||(e=!0,t.apply(void 0,arguments))}}(o);var a=!1;t.on("close",(function(){a=!0})),void 0===r&&(r=n(79)),r(t,{readable:e,writable:i},(function(t){if(t)return o(t);a=!0,o()}));var c=!1;return function(e){if(!a&&!c)return c=!0,function(t){return t.setHeader&&"function"==typeof t.abort}(t)?t.abort():"function"==typeof t.destroy?t.destroy():void o(e||new s("pipe"))}}function u(t){t()}function h(t,e){return t.pipe(e)}function l(t){return t.length?"function"!=typeof t[t.length-1]?a:t.pop():a}t.exports=function(){for(var t=arguments.length,e=new Array(t),n=0;n<t;n++)e[n]=arguments[n];var r,i=l(e);if(Array.isArray(e[0])&&(e=e[0]),e.length<2)throw new o("streams");var s=e.map((function(t,n){var o=n<e.length-1;return c(t,o,n>0,(function(t){r||(r=t),t&&s.forEach(u),o||(s.forEach(u),i(r))}))}));return e.reduce(h)}},function(t,e,n){(function(e){/*! queue-microtask. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */
38
- let n;t.exports="function"==typeof queueMicrotask?queueMicrotask.bind("undefined"!=typeof window?window:e):t=>(n||(n=Promise.resolve())).then(t).catch(t=>setTimeout(()=>{throw t},0))}).call(this,n(34))},function(t,e,n){"use strict";function r(t,e){for(const n in e)Object.defineProperty(t,n,{value:e[n],enumerable:!0,configurable:!0});return t}t.exports=function(t,e,n){if(!t||"string"==typeof t)throw new TypeError("Please pass an Error to err-code");n||(n={}),"object"==typeof e&&(n=e,e=""),e&&(n.code=e);try{return r(t,n)}catch(e){n.message=t.message,n.stack=t.stack;const i=function(){};i.prototype=Object.create(Object.getPrototypeOf(t));return r(new i,n)}}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.DigitalHumanVideoPlayManager=void 0;const r=n(63),i=n(35);e.DigitalHumanVideoPlayManager=class{constructor(t,e){this.messages=t,this.publicUnmuteDigitalHumanMethod=e,this.remoteVideoPlayCount=0}play(t){this.video=t,this.playRemoteVideo()}unmuteVideo(){this.video&&this.video.muted&&(this.video.muted=!1,this.messages.next(new r.DigitalHumanUnmuted))}playRemoteVideo(){this.video&&(this.video.onerror=t=>{this.messages.next(new r.DigitalHumanVideoError(t))},this.video.play().then(()=>{this.messages.next(new r.DigitalHumanUnmuted)}).catch(()=>{this.digitalHumanFailedToPlayUnmuted()}))}digitalHumanFailedToPlayUnmuted(){this.messages.next(new r.DigitalHumanFailedToPlay),this.video.muted=!0,this.video.play().then(()=>{i.logger.log("Muting the digital human and playing it succeeded."),this.messages.next(new r.DigitalHumanPlayedInMutedModeSuccess),this.video.addEventListener("click",()=>{this.publicUnmuteDigitalHumanMethod()},{once:!0})}).catch(t=>{i.logger.log("Could not play digital human video even as muted, starting exponential backoff.",t),this.playRemoteVideoWithExponentialBackoff()})}playRemoteVideoWithExponentialBackoff(){this.video&&(this.video.autoplay=!0,this.video.play().then(()=>{this.messages.next(new r.DigitalHumanUnmuted)}),this.remoteVideoPlayCount++,setTimeout(()=>{this.remoteVideoPlayCount<10&&this.playRemoteVideoWithExponentialBackoff()},100*(this.remoteVideoPlayCount-1)))}}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.MessageHandler=void 0;const r=n(37),i=n(80);e.MessageHandler=class{constructor(t,e){this.internalMessages$=t,this.messages=e,this.deviceManager={getDevices:(t,e)=>{}},this.getMessagesOfType("AvatarQuestionText").subscribe(t=>{const e={type:i.PromMessageType.QuestionMessageReceived,value:{id:t.id,receivedOn:Date.now()}};this.internalMessages$.next({faceMeMessageType:"prom",promMsg:e}),this.messages.next(new r.AvatarQuestionMessage(t.question,t.id))}),this.getMessagesOfType("AvatarAnswerText").subscribe(t=>{const e={type:i.PromMessageType.AnswerMessageReceived,value:{id:t.questionId,receivedOn:Date.now()}};this.internalMessages$.next({faceMeMessageType:"prom",promMsg:e}),this.messages.next(new r.AvatarAnswerMessage(t.answer,t.answerAvatar,t.answerSpeech,t.questionId))}),this.getMessagesOfType("AvatarAnswerHTML").subscribe(t=>{this.messages.next(new r.AvatarAnswerContentMessage(t.html,t.messageId,t.hasDisplayHtml)),this.messages.next(new r.InstructionsMessage(t.instructions))}),this.getMessagesOfType("AvatarTextInputStarted").subscribe(t=>this.messages.next(new r.StartedSpeakingMessage)),this.getMessagesOfType("AvatarTextInputFinished").subscribe(t=>{this.messages.next(new r.FinishedSpeakingMessage),this.messages.next(new r.AvatarTextInputFinishedMessage)}),this.getMessagesOfType("AvatarStarting").subscribe(t=>{this.deviceManager.edgeNodeId=t.edgeNodeId}),this.getMessagesOfType("ClientMediaStreamUpdate").subscribe(t=>{this.messages.next(new r.ClientMediaStreamUpdateMessage(t.clientStreamingAudio,t.clientStreamingVideo,t.serverStreamingAudio,t.serverStreamingVideo)),t.clientStreamingAudio&&t.clientStreamingVideo&&t.serverStreamingAudio&&t.serverStreamingVideo&&(this.internalMessages$.next({faceMeMessageType:"sessionLive"}),this.internalMessages$.next({faceMeMessageType:"remoteVideoReadyToPlay"}))}),this.getMessagesOfType("SessionErrorMessage").subscribe(t=>{console.error(t.error),this.messages.next(new r.SessionErrorMessage(t.error))}),this.getMessagesOfType("SessionInfoMessage").subscribe(t=>{this.messages.next(new r.SessionInfoMessage(t.info))}),this.getMessagesOfType("SessionEndedMessage").subscribe(()=>{const t={type:i.PromMessageType.SessionEnded,value:{receivedOn:Date.now()}};this.internalMessages$.next({faceMeMessageType:"prom",promMsg:t}),this.internalMessages$.next({faceMeMessageType:"sessionEnd"})}),this.getMessagesOfType("AvatarRequestCompleted").subscribe(t=>{this.messages.next(new r.AvatarRequestCompleted(t.reason))}),this.getMessagesOfType("AvatarRequestIgnored").subscribe(t=>{this.messages.next(new r.AvatarRequestIgnored(t.reason))})}setDeviceManager(t){this.deviceManager=t}getMessagesOfType(t){return this.internalMessages$.filter(e=>e.faceMeMessageType===t)}}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var r={};e.default=void 0;var i=n(135),o=n(139);Object.keys(o).forEach((function(t){"default"!==t&&"__esModule"!==t&&(Object.prototype.hasOwnProperty.call(r,t)||Object.defineProperty(e,t,{enumerable:!0,get:function(){return o[t]}}))}));e.default=function(){return new i.Registry}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.Registry=void 0;var r=n(64),i=n(95),o=n(137),s=n(138),a=n(97);function c(t,e){for(var n=0;n<e.length;n++){var r=e[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(t,r.key,r)}}var u=function(){function t(){var e,n,r;!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,t),r=void 0,(n="data")in(e=this)?Object.defineProperty(e,n,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[n]=r,this.data={counter:{},gauge:{},histogram:{}}}var e,n,u;return e=t,(n=[{key:"validateInput",value:function(t,e,n,i){if(""===String(e))throw new Error("Metric name cannot be empty");if(-1===["counter","gauge","histogram"].indexOf(t))throw new Error("Unknown metric type ".concat(t));if("string"!=typeof n&&null!=n)throw new Error("help must be string or undefined/null");if((0,r.has)(this.data,"".concat(t,".").concat(e)))throw new Error("A metric with the name '".concat(e,"' already exists for type '").concat(t,"'"));if(!Array.isArray(i)&&null!=i)throw new Error("buckets must be array or undefined/null")}},{key:"create",value:function(t,e){var n,r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"",a=arguments.length>3&&void 0!==arguments[3]?arguments[3]:[];return this.validateInput(t,e,r,a),"counter"===t?(n=new i.Counter,this.data.counter[e]={help:r,instance:n,type:t}):"gauge"===t?(n=new o.Gauge,this.data.gauge[e]={help:r,instance:n,type:t}):(n=new s.Histogram(a),this.data.histogram[e]={help:r,instance:n,type:t}),n}},{key:"metrics",value:function(){return(0,r.reduce)(this.data,(function(t,e,n){return t+(0,r.reduce)(e,(function(t,e,i){var o=e.instance.collect(),s=t;return e.help.length>0&&(s+="# HELP ".concat(i," ").concat(e.help,"\n")),s+="# TYPE ".concat(i," ").concat(n,"\n"),s+=(0,r.reduce)(o,(function(t,e){return t+("histogram"===n?(0,a.formatHistogramOrSummary)(i,e):(0,a.formatCounterOrGauge)(i,e))}),"")}),"")}),"")}},{key:"reset",value:function(){return(0,r.each)(this.data,(function(t){(0,r.each)(t,(function(t){t.instance.resetAll()}))})),this}},{key:"clear",value:function(){return this.data={counter:{},gauge:{},histogram:{}},this}},{key:"get",value:function(t,e){var n=(null!=t?[this.data[t]]:(0,r.valuesIn)(this.data)).find((function(t){return(0,r.has)(t,e)}));return null!=n?n[e].instance:void 0}}])&&c(e.prototype,n),u&&c(e,u),t}();e.Registry=u},function(t,e){t.exports=function(t){return t.webpackPolyfill||(t.deprecate=function(){},t.paths=[],t.children||(t.children=[]),Object.defineProperty(t,"loaded",{enumerable:!0,get:function(){return t.l}}),Object.defineProperty(t,"id",{enumerable:!0,get:function(){return t.i}}),t.webpackPolyfill=1),t}},function(t,e,n){"use strict";function r(t){return(r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t})(t)}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function o(t,e){for(var n=0;n<e.length;n++){var r=e[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(t,r.key,r)}}function s(t,e){return!e||"object"!==r(e)&&"function"!=typeof e?function(t){if(void 0===t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return t}(t):e}function a(t){return(a=Object.setPrototypeOf?Object.getPrototypeOf:function(t){return t.__proto__||Object.getPrototypeOf(t)})(t)}function c(t,e){return(c=Object.setPrototypeOf||function(t,e){return t.__proto__=e,t})(t,e)}Object.defineProperty(e,"__esModule",{value:!0}),e.Gauge=void 0;var u=function(t){function e(){return i(this,e),s(this,a(e).apply(this,arguments))}var n,r,u;return function(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function");t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,writable:!0,configurable:!0}}),e&&c(t,e)}(e,t),n=e,(r=[{key:"dec",value:function(t){var e=this.get(t);return this.set(e?e.value-1:0,t),this}},{key:"sub",value:function(t,e){var n=this.get(e);return this.set(n?n.value-t:0,e),this}}])&&o(n.prototype,r),u&&o(n,u),e}(n(95).Counter);e.Gauge=u},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.Histogram=void 0;var r=n(64);function i(t){return(i="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t})(t)}function o(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function s(t,e){for(var n=0;n<e.length;n++){var r=e[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(t,r.key,r)}}function a(t,e){return!e||"object"!==i(e)&&"function"!=typeof e?u(t):e}function c(t){return(c=Object.setPrototypeOf?Object.getPrototypeOf:function(t){return t.__proto__||Object.getPrototypeOf(t)})(t)}function u(t){if(void 0===t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return t}function h(t,e){return(h=Object.setPrototypeOf||function(t,e){return t.__proto__=e,t})(t,e)}function l(t,e,n){return e in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function f(t){return{entries:(0,r.reduce)(t,(function(t,e){return t[e.toString()]=0,t}),{"+Inf":0}),sum:0,count:0,raw:[]}}var d=function(t){function e(){var t,n=arguments.length>0&&void 0!==arguments[0]?arguments[0]:[];return o(this,e),l(u(t=a(this,c(e).call(this))),"buckets",void 0),t.buckets=n.sort((function(t,e){return t>e?1:-1})),t.set(f(t.buckets)),t.observe=t.observe.bind(u(t)),t}var n,i,d;return function(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function");t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,writable:!0,configurable:!0}}),e&&h(t,e)}(e,t),n=e,(i=[{key:"observe",value:function(t,e){var n=this.get(e);null==n&&(n=this.set(f(this.buckets),e).get(e)),n.value.raw.push(t),n.value.entries["+Inf"]+=1;var i=function(t,e){if(e<t[t.length-1])for(var n=0;n<t.length;n+=1)if(e<=t[n])return n}(this.buckets,t);if(null!=i)for(var o=i;o<this.buckets.length;o+=1){var s=n.value.entries[this.buckets[o].toString()];n.value.entries[this.buckets[o].toString()]=s+1}return n.value.sum=(0,r.sum)(n.value.raw),n.value.count+=1,this}},{key:"reset",value:function(t){this.set(f(this.buckets),t)}}])&&s(n.prototype,i),d&&s(n,d),e}(n(96).Collector);e.Histogram=d},function(t,e,n){},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.MessagingState=e.MessagingService=void 0;const r=n(141);Object.defineProperty(e,"MessagingService",{enumerable:!0,get:function(){return r.MessagingService}});const i=n(98);Object.defineProperty(e,"MessagingState",{enumerable:!0,get:function(){return i.MessagingState}})},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.MessagingService=void 0;const r=n(155),i=n(142),o=n(144),s=n(35),a=n(98);e.MessagingService=class{constructor(t,e){this.options={autoReconnect:!0,reconnectTime:5e3,maxReconnectAttempts:3,connectionHeaders:{},maxReconnectLimitReached:()=>{},onReconnect:()=>{}},this.url=t,this.options=Object.assign(this.options,e),this.subscriptions={},this.connectionAttempts=0,this.state$=new i.BehaviorSubject(a.MessagingState.DISCONNECTED),this.messages$=new o.Subject,console.log("connect headers messaging: ",this.options.connectionHeaders);const n={connectHeaders:this.options.connectionHeaders,reconnectDelay:0,connectionTimeout:5e3,discardWebsocketOnCommFailure:!0,brokerURL:this.url.replace("https://","wss://").replace("http://","ws://")};this.stompClient=new r.Client(n),this.stompClient.onConnect=t=>this.onStompConnected(t),this.stompClient.onDisconnect=t=>{s.logger.log("Stomp client disconnected",t)},this.stompClient.onStompError=t=>{s.logger.log("Stomp client error",t),this.onStompClientConnectionClosed(t)},this.stompClient.onWebSocketError=t=>{s.logger.log("Stomp client web socket error",t),this.onStompClientConnectionClosed(t)},this.stompClient.onWebSocketClose=t=>{s.logger.log("Stomp client web socket closed",t),this.onStompClientConnectionClosed(t)}}connect(){this.disconnect(),s.logger.log("MessagingService | connecting..."),this.state$.next(a.MessagingState.CONNECTING),this.connectionAttempts++,this.stompClient.activate()}disconnect(){const t=this.state$.getValue();if(t===a.MessagingState.CONNECTED||t===a.MessagingState.CONNECTING){s.logger.log("Disconnecting stomp client");try{this.subscriptions={},this.stompClient.deactivate(),this.stompClient.forceDisconnect(),this.state$.next(a.MessagingState.DISCONNECTED)}catch(t){console.error("MessagingService | disconnect: error",t),this.state$.next(a.MessagingState.DISCONNECTED)}}}send(t,e){s.logger.log("MessagingService | send:",t,e);const n={"content-type":"application/json","x-auth-token":this.options.connectionHeaders["x-auth-token"]},r=JSON.stringify(e);this.stompClient.publish({destination:t,body:r,headers:n})}getTopic(t){s.logger.log("MessagingService | subscribeToTopic: "+t);const e=this.subscriptions[t];if(e)return s.logger.log("existing subscription... not re-subscribing to topic"),e;const n=new o.Subject;return this.stompClient.subscribe(t,t=>{n.next(t),this.messages$.next(t)}),this.subscriptions[t]=n,n}onStompConnected(t){s.logger.log("MessagingService | connected"),this.state$.next(a.MessagingState.CONNECTED),this.initMessagingSubscription(),this.connectionAttempts=0}onStompClientConnectionClosed(t){this.options.autoReconnect?this.options.maxReconnectAttempts&&this.connectionAttempts<this.options.maxReconnectAttempts?setTimeout(()=>{this.connect()},this.options.reconnectTime):this.options.maxReconnectLimitReached&&(this.options.maxReconnectLimitReached(),this.disconnect()):this.disconnect()}initMessagingSubscription(){s.logger.log("MessagingService | initMessagingSubscription");this.stompClient.subscribe("/",t=>{this.messages$.next(t)})}}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),function(t){for(var n in t)e.hasOwnProperty(n)||(e[n]=t[n])}(n(143))},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var r=n(47);e.BehaviorSubject=r.BehaviorSubject},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),function(t){for(var n in t)e.hasOwnProperty(n)||(e[n]=t[n])}(n(145))},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var r=n(47);e.Subject=r.Subject},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.MetricsService=void 0;const r=n(37),i=n(147),o=n(80);e.MetricsService=class{constructor(t,e,n){this.uneeqOptions=t,this.internalMessages=e,this.messages=n,this.clientPerformanceStats={},this.options=t,this.internalMessages$=e,this.messages$=n}parseAndLogWebRtcStats(t){try{t.forEach(t=>{var e,n;if("inbound-rtp"===t.type&&"video"===t.kind){this.clientPerformanceStats.frameHeight=new i.ClientPerformanceStat("Frame height",t.frameHeight),this.clientPerformanceStats.frameWidth=new i.ClientPerformanceStat("Frame width",t.frameWidth);const r=t.framesDropped,o=r?r-(null===(e=this.clientPerformanceStats.totalFramesDropped)||void 0===e?void 0:e.value):0;this.clientPerformanceStats.newFramesDropped=o?new i.ClientPerformanceStat("New Frames Dropped",o):new i.ClientPerformanceStat,this.clientPerformanceStats.totalFramesDropped=r?new i.ClientPerformanceStat("Total Frames Dropped",r):new i.ClientPerformanceStat;const s=t.packetsLost,a=s?s-(null===(n=this.clientPerformanceStats.inboundTotalPacketsLost)||void 0===n?void 0:n.value):0;this.clientPerformanceStats.inboundNewPacketsLost=a?new i.ClientPerformanceStat("New packets lost",a):new i.ClientPerformanceStat,this.clientPerformanceStats.inboundTotalPacketsLost=s?new i.ClientPerformanceStat("Total packets lost",s):new i.ClientPerformanceStat;const c=t.framesPerSecond;this.clientPerformanceStats.framesPerSec=c?new i.ClientPerformanceStat("Frames per second",c):new i.ClientPerformanceStat}else if("remote-inbound-rtp"===t.type&&"video"===t.kind){const e=t.roundTripTime;this.clientPerformanceStats.inboundRoundTripTime=e?new i.ClientPerformanceStat("Round Trip Time",e):new i.ClientPerformanceStat}else if("outbound-rtp"===t.type&&"video"===t.kind){const e=t.qualityLimitationReason;this.clientPerformanceStats.outboundQualityLimitationReason=new i.ClientPerformanceStat("Quality Limitation Reason",e)}}),this.options.enableClientPerformanceMessage&&this.messages$.next(new r.ClientPerformanceMessage(this.clientPerformanceStats));const e={type:o.PromMessageType.WebRtcPerformance,value:this.clientPerformanceStats};this.internalMessages$.next({faceMeMessageType:"prom",promMsg:e})}catch(t){console.warn("Unable to parseAndLogWebRTCStats",t)}}}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.ClientPerformanceStat=void 0;e.ClientPerformanceStat=class{constructor(t="",e=0){this.label=t,this.value=e}}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.OnlineStatusService=void 0;const r=n(37);e.OnlineStatusService=class{constructor(t,e){this.messages=t,this.offlineTimeoutLimitHandler=e,this.online=!0,this.offlineDisconnectTimeLimitMS=1e4,window.addEventListener("offline",()=>this.handleOffline()),window.addEventListener("online",()=>this.handleOnline())}handleOffline(){this.online=!1,this.disconnectTimer=setTimeout(()=>{this.offlineTimeoutLimitHandler()},this.offlineDisconnectTimeLimitMS),this.sendStatusUpdate()}handleOnline(){this.online=!0,window.clearTimeout(this.disconnectTimer),this.sendStatusUpdate()}sendStatusUpdate(){this.messages.next(new r.OnlineStatusUpdateMessage(this.online))}}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.ResumeSessionCheck=void 0;const r=n(35);class i{static validate(t){let e=void 0!==t.resumeSession&&t.resumeSession;localStorage.getItem("uneeqResumeSessionPersonaId")===t.conversationId||(r.logger.log("UneeQ: Persona Id's do not match, unable to resume session."),e=!1);const n=i.browserTabIsActive();if(e&&!n&&(r.logger.log("UneeQ: Browser tab is not active so unable to resume"),e=!1),e){const t=localStorage.getItem("uneeqResumeSessionId");if(null!==t)return{resumeSession:!0,resumeSessionId:t}}return{resumeSession:!1}}static browserTabIsActive(){return!document.hidden}}e.ResumeSessionCheck=i},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.StreamManager=void 0;e.StreamManager=class{constructor(){window.AudioContext=window.AudioContext||window.webkitAudioContext,this.silentAudioTrack=this.generateSilentAudioTrack(),this.canvasVideoTrack=this.generateCanvasVideoTrack()}addCanvasVideoTrackToStream(t){return t.getVideoTracks().forEach(e=>t.removeTrack(e)),t.addTrack(this.canvasVideoTrack),t}addSilentAudioTrackToStream(t){return t.getAudioTracks().forEach(e=>t.removeTrack(e)),t.addTrack(this.silentAudioTrack),t}resumeAudioContext(){this.audioContextInstance&&this.audioContextInstance.resume()}generateCanvasVideoTrack(){const t=document.createElement("canvas");t.width=40,t.height=30;return t.captureStream(1).getVideoTracks()[0]}generateSilentAudioTrack(){if(!this.audioSourceNode||!this.audioSourceDestination){const t=new window.AudioContext;this.audioContextInstance=t,this.audioSourceDestination=t.createMediaStreamDestination()}return this.audioSourceDestination.stream.getAudioTracks()[0]}}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.VoiceInputManager=void 0;const r=n(81),i=n(152),o=n(63),s=n(99),a=n(35);e.VoiceInputManager=class{constructor(t,e,n,r){this.options=t,this.api=e,this.messages=n,this.enableMicrophone=r,this.microphoneEngageVolume=.02,this.microphoneDisengageVolume=.02,this.voiceActivityNotSpeakingTimeoutMS=1e3,this.voiceActivityAllowInterruptions=!1,this.digitalHumanSpeaking=!1,this.recording=!1,this.setVoiceInputMode(t.voiceInputMode);try{window.AudioContext=window.AudioContext||window.webkitAudioContext,this.audioContext=new AudioContext}catch(t){this.audioContextNotSupported()}this.handleAppMessages()}setVoiceInputMode(t){t===s.VoiceInputMode.PUSH_TO_TALK?this.options.voiceInputMode=s.VoiceInputMode.PUSH_TO_TALK:t===s.VoiceInputMode.VOICE_ACTIVITY?this.options.voiceInputMode=s.VoiceInputMode.VOICE_ACTIVITY:this.messages.next(new o.WarningMessage("Invalid voice input mode selected: "+t))}startRecording(){this.options.voiceInputMode===s.VoiceInputMode.PUSH_TO_TALK?this.apiStartRecording():this.requestNotSupportedInVoiceActivityMode("startRecording")}stopRecording(){this.options.voiceInputMode===s.VoiceInputMode.PUSH_TO_TALK?this.apiStopRecording():this.requestNotSupportedInVoiceActivityMode("stopRecording")}handleSessionEnd(){this.soundMeter&&this.soundMeter.stop()}resumeAudioContext(){a.logger.log("UneeQ: resuming publish stream audio context and initializing mic activity."),this.audioContext&&(this.audioContext.resume(),this.stream&&this.initMicActivity(this.stream))}initMicActivity(t){this.stream=t,this.soundMeter=new i.SoundMeter(this.audioContext),this.soundMeter.connectToSource(t,t=>this.micActivityConnected(t))}audioContextNotSupported(){this.options.micActivityMessages&&this.messages.next(new o.MicActivityNotSupportedMessage),this.messages.next(new o.VoiceActivityInputModeNotSupportedMessage),this.setVoiceInputMode(s.VoiceInputMode.PUSH_TO_TALK)}handleAppMessages(){this.messages.subscribe(t=>{switch(t.uneeqMessageType){case o.UneeqMessageType.StartedSpeaking:console.log("StartSpeaking message"),this.digitalHumanSpeaking=!0;break;case o.UneeqMessageType.FinishedSpeaking:this.digitalHumanSpeaking=!1}})}requestNotSupportedInVoiceActivityMode(t){this.messages.next(new o.WarningMessage("Request not supported in voice activity mode: "+t))}apiStartRecording(){this.recording=!0,this.messages.next(new o.RecordingStartedMessage),this.api.avatarStartRecording().catch(()=>{this.recording=!1,this.messages.next(new o.RecordingStoppedMessage)})}apiStopRecording(){this.recording=!1,this.api.avatarStopRecording().finally(()=>this.messages.next(new o.RecordingStoppedMessage))}micActivityConnected(t){t?this.messages.next(new o.MicActivityErrorMessage(t)):this.soundMeter&&this.soundMeter.instant$.pipe(r.distinctUntilChanged()).subscribe(t=>{this.handleVoiceActivity(t)})}handleVoiceActivity(t){this.options.micActivityMessages&&this.messages.next(new o.MicActivityMessage(t)),this.options.voiceInputMode!==s.VoiceInputMode.VOICE_ACTIVITY||this.digitalHumanSpeaking&&!this.voiceActivityAllowInterruptions||(t>this.microphoneEngageVolume?(this.recording||this.apiStartRecording(),this.clearSilenceTimeout()):t<this.microphoneDisengageVolume&&this.recording&&(this.clearSilenceTimeout(),this.silenceTimeout=setTimeout(()=>{this.recording&&this.apiStopRecording()},this.voiceActivityNotSpeakingTimeoutMS)))}clearSilenceTimeout(){this.silenceTimeout&&clearTimeout(this.silenceTimeout)}}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.SoundMeter=void 0;const r=n(47),i=n(35);e.SoundMeter=class{constructor(t){this.instant$=new r.BehaviorSubject(0),this.context=t,this.instant=0,this.slow=0,this.clip=0,this.script=t.createScriptProcessor(2048,1,1);const e=this;this.script.onaudioprocess=t=>{const n=t.inputBuffer.getChannelData(0);let r,i=0,o=0;for(r=0;r<n.length;++r)i+=n[r]*n[r],Math.abs(n[r])>.99&&(o+=1);e.instant=Math.sqrt(i/n.length),e.slow=.95*e.slow+.05*e.instant,e.clip=o/n.length,e.instant$.next(parseFloat(e.instant.toFixed(2)))}}connectToSource(t,e){i.logger.log("SoundMeter connecting");try{this.mic=this.context.createMediaStreamSource(t),this.mic.connect(this.script),this.script.connect(this.context.destination),void 0!==e&&e(null)}catch(t){console.error(t),void 0!==e&&e(t)}}stop(){this.mic.disconnect(),this.script.disconnect()}}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.SessionType=void 0,function(t){t[t.WEB=0]="WEB"}(e.SessionType||(e.SessionType={}))},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.SourceApp=void 0,function(t){t.HOSTED_EXPERIENCE="HOSTED_EXPERIENCE",t.SHOWCASE="SHOWCASE",t.SPLIT_SCREEN="SPLIT_SCREEN",t.INTERACTIONS="INTERACTIONS",t.UNKNOWN="UNKNOWN"}(e.SourceApp||(e.SourceApp={}))},function(t,e,n){"use strict";n.r(e),n.d(e,"Client",(function(){return f})),n.d(e,"FrameImpl",(function(){return o})),n.d(e,"Parser",(function(){return s})),n.d(e,"StompConfig",(function(){return d})),n.d(e,"StompHeaders",(function(){return p})),n.d(e,"StompSubscription",(function(){return v})),n.d(e,"StompSocketState",(function(){return a})),n.d(e,"ActivationState",(function(){return c})),n.d(e,"Versions",(function(){return u})),n.d(e,"CompatClient",(function(){return m})),n.d(e,"Stomp",(function(){return y}));const r="\n",i="\0";class o{constructor(t){const{command:e,headers:n,body:r,binaryBody:i,escapeHeaderValues:o,skipContentLengthHeader:s}=t;this.command=e,this.headers=Object.assign({},n||{}),i?(this._binaryBody=i,this.isBinaryBody=!0):(this._body=r||"",this.isBinaryBody=!1),this.escapeHeaderValues=o||!1,this.skipContentLengthHeader=s||!1}get body(){return!this._body&&this.isBinaryBody&&(this._body=(new TextDecoder).decode(this._binaryBody)),this._body}get binaryBody(){return this._binaryBody||this.isBinaryBody||(this._binaryBody=(new TextEncoder).encode(this._body)),this._binaryBody}static fromRawFrame(t,e){const n={},r=t=>t.replace(/^\s+|\s+$/g,"");for(const i of t.headers.reverse()){i.indexOf(":");const s=r(i[0]);let a=r(i[1]);e&&"CONNECT"!==t.command&&"CONNECTED"!==t.command&&(a=o.hdrValueUnEscape(a)),n[s]=a}return new o({command:t.command,headers:n,binaryBody:t.binaryBody,escapeHeaderValues:e})}toString(){return this.serializeCmdAndHeaders()}serialize(){const t=this.serializeCmdAndHeaders();return this.isBinaryBody?o.toUnit8Array(t,this._binaryBody).buffer:t+this._body+i}serializeCmdAndHeaders(){const t=[this.command];this.skipContentLengthHeader&&delete this.headers["content-length"];for(const e of Object.keys(this.headers||{})){const n=this.headers[e];this.escapeHeaderValues&&"CONNECT"!==this.command&&"CONNECTED"!==this.command?t.push(`${e}:${o.hdrValueEscape(""+n)}`):t.push(`${e}:${n}`)}return(this.isBinaryBody||!this.isBodyEmpty()&&!this.skipContentLengthHeader)&&t.push("content-length:"+this.bodyLength()),t.join(r)+r+r}isBodyEmpty(){return 0===this.bodyLength()}bodyLength(){const t=this.binaryBody;return t?t.length:0}static sizeOfUTF8(t){return t?(new TextEncoder).encode(t).length:0}static toUnit8Array(t,e){const n=(new TextEncoder).encode(t),r=new Uint8Array([0]),i=new Uint8Array(n.length+e.length+r.length);return i.set(n),i.set(e,n.length),i.set(r,n.length+e.length),i}static marshall(t){return new o(t).serialize()}static hdrValueEscape(t){return t.replace(/\\/g,"\\\\").replace(/\r/g,"\\r").replace(/\n/g,"\\n").replace(/:/g,"\\c")}static hdrValueUnEscape(t){return t.replace(/\\r/g,"\r").replace(/\\n/g,"\n").replace(/\\c/g,":").replace(/\\\\/g,"\\")}}class s{constructor(t,e){this.onFrame=t,this.onIncomingPing=e,this._encoder=new TextEncoder,this._decoder=new TextDecoder,this._token=[],this._initState()}parseChunk(t,e=!1){let n;if(n=t instanceof ArrayBuffer?new Uint8Array(t):this._encoder.encode(t),e&&0!==n[n.length-1]){const t=new Uint8Array(n.length+1);t.set(n,0),t[n.length]=0,n=t}for(let t=0;t<n.length;t++){const e=n[t];this._onByte(e)}}_collectFrame(t){0!==t&&13!==t&&(10!==t?(this._onByte=this._collectCommand,this._reinjectByte(t)):this.onIncomingPing())}_collectCommand(t){if(13!==t)return 10===t?(this._results.command=this._consumeTokenAsUTF8(),void(this._onByte=this._collectHeaders)):void this._consumeByte(t)}_collectHeaders(t){13!==t&&(10!==t?(this._onByte=this._collectHeaderKey,this._reinjectByte(t)):this._setupCollectBody())}_reinjectByte(t){this._onByte(t)}_collectHeaderKey(t){if(58===t)return this._headerKey=this._consumeTokenAsUTF8(),void(this._onByte=this._collectHeaderValue);this._consumeByte(t)}_collectHeaderValue(t){if(13!==t)return 10===t?(this._results.headers.push([this._headerKey,this._consumeTokenAsUTF8()]),this._headerKey=void 0,void(this._onByte=this._collectHeaders)):void this._consumeByte(t)}_setupCollectBody(){const t=this._results.headers.filter(t=>"content-length"===t[0])[0];t?(this._bodyBytesRemaining=parseInt(t[1],10),this._onByte=this._collectBodyFixedSize):this._onByte=this._collectBodyNullTerminated}_collectBodyNullTerminated(t){0!==t?this._consumeByte(t):this._retrievedBody()}_collectBodyFixedSize(t){0!=this._bodyBytesRemaining--?this._consumeByte(t):this._retrievedBody()}_retrievedBody(){this._results.binaryBody=this._consumeTokenAsRaw(),this.onFrame(this._results),this._initState()}_consumeByte(t){this._token.push(t)}_consumeTokenAsUTF8(){return this._decoder.decode(this._consumeTokenAsRaw())}_consumeTokenAsRaw(){const t=new Uint8Array(this._token);return this._token=[],t}_initState(){this._results={command:void 0,headers:[],binaryBody:void 0},this._token=[],this._headerKey=void 0,this._onByte=this._collectFrame}}var a,c;!function(t){t[t.CONNECTING=0]="CONNECTING",t[t.OPEN=1]="OPEN",t[t.CLOSING=2]="CLOSING",t[t.CLOSED=3]="CLOSED"}(a||(a={})),function(t){t[t.ACTIVE=0]="ACTIVE",t[t.DEACTIVATING=1]="DEACTIVATING",t[t.INACTIVE=2]="INACTIVE"}(c||(c={}));class u{constructor(t){this.versions=t}supportedVersions(){return this.versions.join(",")}protocolVersions(){return this.versions.map(t=>`v${t.replace(".","")}.stomp`)}}u.V1_0="1.0",u.V1_1="1.1",u.V1_2="1.2",u.default=new u([u.V1_0,u.V1_1,u.V1_2]);class h{constructor(t,e,n={}){this._client=t,this._webSocket=e,this._serverFrameHandlers={CONNECTED:t=>{this.debug("connected to server "+t.headers.server),this._connected=!0,this._connectedVersion=t.headers.version,this._connectedVersion===u.V1_2&&(this._escapeHeaderValues=!0),this._setupHeartbeat(t.headers),this.onConnect(t)},MESSAGE:t=>{const e=t.headers.subscription,n=this._subscriptions[e]||this.onUnhandledMessage,r=t,i=this,o=this._connectedVersion===u.V1_2?r.headers.ack:r.headers["message-id"];r.ack=(t={})=>i.ack(o,e,t),r.nack=(t={})=>i.nack(o,e,t),n(r)},RECEIPT:t=>{const e=this._receiptWatchers[t.headers["receipt-id"]];e?(e(t),delete this._receiptWatchers[t.headers["receipt-id"]]):this.onUnhandledReceipt(t)},ERROR:t=>{this.onStompError(t)}},this._counter=0,this._subscriptions={},this._receiptWatchers={},this._partialData="",this._escapeHeaderValues=!1,this._lastServerActivityTS=Date.now(),this.configure(n)}get connectedVersion(){return this._connectedVersion}get connected(){return this._connected}configure(t){Object.assign(this,t)}start(){const t=new s(t=>{const e=o.fromRawFrame(t,this._escapeHeaderValues);this.logRawCommunication||this.debug("<<< "+e);(this._serverFrameHandlers[e.command]||this.onUnhandledFrame)(e)},()=>{this.debug("<<< PONG")});this._webSocket.onmessage=e=>{if(this.debug("Received data"),this._lastServerActivityTS=Date.now(),this.logRawCommunication){const t=e.data instanceof ArrayBuffer?(new TextDecoder).decode(e.data):e.data;this.debug("<<< "+t)}t.parseChunk(e.data,this.appendMissingNULLonIncoming)},this._onclose=t=>{this.debug("Connection closed to "+this._client.brokerURL),this._cleanUp(),this.onWebSocketClose(t)},this._webSocket.onclose=this._onclose,this._webSocket.onerror=t=>{this.onWebSocketError(t)},this._webSocket.onopen=()=>{const t=Object.assign({},this.connectHeaders);this.debug("Web Socket Opened..."),t["accept-version"]=this.stompVersions.supportedVersions(),t["heart-beat"]=[this.heartbeatOutgoing,this.heartbeatIncoming].join(","),this._transmit({command:"CONNECT",headers:t})}}_setupHeartbeat(t){if(t.version!==u.V1_1&&t.version!==u.V1_2)return;if(!t["heart-beat"])return;const[e,n]=t["heart-beat"].split(",").map(t=>parseInt(t,10));if(0!==this.heartbeatOutgoing&&0!==n){const t=Math.max(this.heartbeatOutgoing,n);this.debug(`send PING every ${t}ms`),this._pinger=setInterval(()=>{this._webSocket.readyState===a.OPEN&&(this._webSocket.send(r),this.debug(">>> PING"))},t)}if(0!==this.heartbeatIncoming&&0!==e){const t=Math.max(this.heartbeatIncoming,e);this.debug(`check PONG every ${t}ms`),this._ponger=setInterval(()=>{const e=Date.now()-this._lastServerActivityTS;e>2*t&&(this.debug(`did not receive server activity for the last ${e}ms`),this._closeOrDiscardWebsocket())},t)}}_closeOrDiscardWebsocket(){this.discardWebsocketOnCommFailure?(this.debug("Discarding websocket, the underlying socket may linger for a while"),this._discardWebsocket()):(this.debug("Issuing close on the websocket"),this._closeWebsocket())}forceDisconnect(){this._webSocket&&(this._webSocket.readyState!==a.CONNECTING&&this._webSocket.readyState!==a.OPEN||this._closeOrDiscardWebsocket())}_closeWebsocket(){this._webSocket.onmessage=()=>{},this._webSocket.close()}_discardWebsocket(){var t,e;this._webSocket.terminate||(t=this._webSocket,e=t=>this.debug(t),t.terminate=function(){const t=()=>{};this.onerror=t,this.onmessage=t,this.onopen=t;const n=new Date,r=this.onclose;this.onclose=t=>{const r=(new Date).getTime()-n.getTime();e(`Discarded socket closed after ${r}ms, with code/reason: ${t.code}/${t.reason}`)},this.close(),r.call(this,{code:4001,reason:"Heartbeat failure, discarding the socket",wasClean:!1})}),this._webSocket.terminate()}_transmit(t){const{command:e,headers:n,body:r,binaryBody:i,skipContentLengthHeader:s}=t,a=new o({command:e,headers:n,body:r,binaryBody:i,escapeHeaderValues:this._escapeHeaderValues,skipContentLengthHeader:s});let c=a.serialize();if(this.logRawCommunication?this.debug(">>> "+c):this.debug(">>> "+a),this.forceBinaryWSFrames&&"string"==typeof c&&(c=(new TextEncoder).encode(c)),"string"==typeof c&&this.splitLargeFrames){let t=c;for(;t.length>0;){const e=t.substring(0,this.maxWebSocketChunkSize);t=t.substring(this.maxWebSocketChunkSize),this._webSocket.send(e),this.debug(`chunk sent = ${e.length}, remaining = ${t.length}`)}}else this._webSocket.send(c)}dispose(){if(this.connected)try{const t=Object.assign({},this.disconnectHeaders);t.receipt||(t.receipt="close-"+this._counter++),this.watchForReceipt(t.receipt,t=>{this._closeWebsocket(),this._cleanUp(),this.onDisconnect(t)}),this._transmit({command:"DISCONNECT",headers:t})}catch(t){this.debug("Ignoring error during disconnect "+t)}else this._webSocket.readyState!==a.CONNECTING&&this._webSocket.readyState!==a.OPEN||this._closeWebsocket()}_cleanUp(){this._connected=!1,this._pinger&&clearInterval(this._pinger),this._ponger&&clearInterval(this._ponger)}publish(t){const{destination:e,headers:n,body:r,binaryBody:i,skipContentLengthHeader:o}=t,s=Object.assign({destination:e},n);this._transmit({command:"SEND",headers:s,body:r,binaryBody:i,skipContentLengthHeader:o})}watchForReceipt(t,e){this._receiptWatchers[t]=e}subscribe(t,e,n={}){(n=Object.assign({},n)).id||(n.id="sub-"+this._counter++),n.destination=t,this._subscriptions[n.id]=e,this._transmit({command:"SUBSCRIBE",headers:n});const r=this;return{id:n.id,unsubscribe:t=>r.unsubscribe(n.id,t)}}unsubscribe(t,e={}){e=Object.assign({},e),delete this._subscriptions[t],e.id=t,this._transmit({command:"UNSUBSCRIBE",headers:e})}begin(t){const e=t||"tx-"+this._counter++;this._transmit({command:"BEGIN",headers:{transaction:e}});const n=this;return{id:e,commit(){n.commit(e)},abort(){n.abort(e)}}}commit(t){this._transmit({command:"COMMIT",headers:{transaction:t}})}abort(t){this._transmit({command:"ABORT",headers:{transaction:t}})}ack(t,e,n={}){n=Object.assign({},n),this._connectedVersion===u.V1_2?n.id=t:n["message-id"]=t,n.subscription=e,this._transmit({command:"ACK",headers:n})}nack(t,e,n={}){return n=Object.assign({},n),this._connectedVersion===u.V1_2?n.id=t:n["message-id"]=t,n.subscription=e,this._transmit({command:"NACK",headers:n})}}var l=function(t,e,n,r){return new(n||(n=Promise))((function(i,o){function s(t){try{c(r.next(t))}catch(t){o(t)}}function a(t){try{c(r.throw(t))}catch(t){o(t)}}function c(t){var e;t.done?i(t.value):(e=t.value,e instanceof n?e:new n((function(t){t(e)}))).then(s,a)}c((r=r.apply(t,e||[])).next())}))};class f{constructor(t={}){this.stompVersions=u.default,this.connectionTimeout=0,this.reconnectDelay=5e3,this.heartbeatIncoming=1e4,this.heartbeatOutgoing=1e4,this.splitLargeFrames=!1,this.maxWebSocketChunkSize=8192,this.forceBinaryWSFrames=!1,this.appendMissingNULLonIncoming=!1,this.state=c.INACTIVE;const e=()=>{};this.debug=e,this.beforeConnect=e,this.onConnect=e,this.onDisconnect=e,this.onUnhandledMessage=e,this.onUnhandledReceipt=e,this.onUnhandledFrame=e,this.onStompError=e,this.onWebSocketClose=e,this.onWebSocketError=e,this.logRawCommunication=!1,this.onChangeState=e,this.connectHeaders={},this._disconnectHeaders={},this.configure(t)}get webSocket(){return this._stompHandler?this._stompHandler._webSocket:void 0}get disconnectHeaders(){return this._disconnectHeaders}set disconnectHeaders(t){this._disconnectHeaders=t,this._stompHandler&&(this._stompHandler.disconnectHeaders=this._disconnectHeaders)}get connected(){return!!this._stompHandler&&this._stompHandler.connected}get connectedVersion(){return this._stompHandler?this._stompHandler.connectedVersion:void 0}get active(){return this.state===c.ACTIVE}_changeState(t){this.state=t,this.onChangeState(t)}configure(t){Object.assign(this,t)}activate(){if(this.state===c.DEACTIVATING)throw this.debug("Still DEACTIVATING, please await call to deactivate before trying to re-activate"),new Error("Still DEACTIVATING, can not activate now");this.active?this.debug("Already ACTIVE, ignoring request to activate"):(this._changeState(c.ACTIVE),this._connect())}_connect(){return l(this,void 0,void 0,(function*(){if(this.connected)return void this.debug("STOMP: already connected, nothing to do");if(yield this.beforeConnect(),!this.active)return void this.debug("Client has been marked inactive, will not attempt to connect");this.connectionTimeout>0&&(this._connectionWatcher&&clearTimeout(this._connectionWatcher),this._connectionWatcher=setTimeout(()=>{this.connected||(this.debug(`Connection not established in ${this.connectionTimeout}ms, closing socket`),this.forceDisconnect())},this.connectionTimeout)),this.debug("Opening Web Socket...");const t=this._createWebSocket();this._stompHandler=new h(this,t,{debug:this.debug,stompVersions:this.stompVersions,connectHeaders:this.connectHeaders,disconnectHeaders:this._disconnectHeaders,heartbeatIncoming:this.heartbeatIncoming,heartbeatOutgoing:this.heartbeatOutgoing,splitLargeFrames:this.splitLargeFrames,maxWebSocketChunkSize:this.maxWebSocketChunkSize,forceBinaryWSFrames:this.forceBinaryWSFrames,logRawCommunication:this.logRawCommunication,appendMissingNULLonIncoming:this.appendMissingNULLonIncoming,discardWebsocketOnCommFailure:this.discardWebsocketOnCommFailure,onConnect:t=>{if(this._connectionWatcher&&(clearTimeout(this._connectionWatcher),this._connectionWatcher=void 0),!this.active)return this.debug("STOMP got connected while deactivate was issued, will disconnect now"),void this._disposeStompHandler();this.onConnect(t)},onDisconnect:t=>{this.onDisconnect(t)},onStompError:t=>{this.onStompError(t)},onWebSocketClose:t=>{this._stompHandler=void 0,this.state===c.DEACTIVATING&&(this._resolveSocketClose(),this._resolveSocketClose=void 0,this._changeState(c.INACTIVE)),this.onWebSocketClose(t),this.active&&this._schedule_reconnect()},onWebSocketError:t=>{this.onWebSocketError(t)},onUnhandledMessage:t=>{this.onUnhandledMessage(t)},onUnhandledReceipt:t=>{this.onUnhandledReceipt(t)},onUnhandledFrame:t=>{this.onUnhandledFrame(t)}}),this._stompHandler.start()}))}_createWebSocket(){let t;return t=this.webSocketFactory?this.webSocketFactory():new WebSocket(this.brokerURL,this.stompVersions.protocolVersions()),t.binaryType="arraybuffer",t}_schedule_reconnect(){this.reconnectDelay>0&&(this.debug(`STOMP: scheduling reconnection in ${this.reconnectDelay}ms`),this._reconnector=setTimeout(()=>{this._connect()},this.reconnectDelay))}deactivate(){return l(this,void 0,void 0,(function*(){let t;return this.state!==c.ACTIVE?(this.debug(`Already ${c[this.state]}, ignoring call to deactivate`),Promise.resolve()):(this._changeState(c.DEACTIVATING),this._reconnector&&clearTimeout(this._reconnector),this._stompHandler&&this.webSocket.readyState!==a.CLOSED?(t=new Promise((t,e)=>{this._resolveSocketClose=t}),this._disposeStompHandler(),t):(this._changeState(c.INACTIVE),Promise.resolve()))}))}forceDisconnect(){this._stompHandler&&this._stompHandler.forceDisconnect()}_disposeStompHandler(){this._stompHandler&&(this._stompHandler.dispose(),this._stompHandler=null)}publish(t){this._stompHandler.publish(t)}watchForReceipt(t,e){this._stompHandler.watchForReceipt(t,e)}subscribe(t,e,n={}){return this._stompHandler.subscribe(t,e,n)}unsubscribe(t,e={}){this._stompHandler.unsubscribe(t,e)}begin(t){return this._stompHandler.begin(t)}commit(t){this._stompHandler.commit(t)}abort(t){this._stompHandler.abort(t)}ack(t,e,n={}){this._stompHandler.ack(t,e,n)}nack(t,e,n={}){this._stompHandler.nack(t,e,n)}}class d{}class p{}class v{}class g{constructor(t){this.client=t}get outgoing(){return this.client.heartbeatOutgoing}set outgoing(t){this.client.heartbeatOutgoing=t}get incoming(){return this.client.heartbeatIncoming}set incoming(t){this.client.heartbeatIncoming=t}}class m extends f{constructor(t){super(),this.maxWebSocketFrameSize=16384,this._heartbeatInfo=new g(this),this.reconnect_delay=0,this.webSocketFactory=t,this.debug=(...t)=>{console.log(...t)}}_parseConnect(...t){let e,n,r,i={};if(t.length<2)throw new Error("Connect requires at least 2 arguments");if("function"==typeof t[1])[i,n,r,e]=t;else switch(t.length){case 6:[i.login,i.passcode,n,r,e,i.host]=t;break;default:[i.login,i.passcode,n,r,e]=t}return[i,n,r,e]}connect(...t){const e=this._parseConnect(...t);e[0]&&(this.connectHeaders=e[0]),e[1]&&(this.onConnect=e[1]),e[2]&&(this.onStompError=e[2]),e[3]&&(this.onWebSocketClose=e[3]),super.activate()}disconnect(t,e={}){t&&(this.onDisconnect=t),this.disconnectHeaders=e,super.deactivate()}send(t,e={},n=""){const r=!1===(e=Object.assign({},e))["content-length"];r&&delete e["content-length"],this.publish({destination:t,headers:e,body:n,skipContentLengthHeader:r})}set reconnect_delay(t){this.reconnectDelay=t}get ws(){return this.webSocket}get version(){return this.connectedVersion}get onreceive(){return this.onUnhandledMessage}set onreceive(t){this.onUnhandledMessage=t}get onreceipt(){return this.onUnhandledReceipt}set onreceipt(t){this.onUnhandledReceipt=t}get heartbeat(){return this._heartbeatInfo}set heartbeat(t){this.heartbeatIncoming=t.incoming,this.heartbeatOutgoing=t.outgoing}}class y{static client(t,e){null==e&&(e=u.default.protocolVersions());return new m(()=>new(y.WebSocketClass||WebSocket)(t,e))}static over(t){let e;return"function"==typeof t?e=t:(console.warn("Stomp.over did not receive a factory, auto reconnect will not work. Please see https://stomp-js.github.io/api-docs/latest/classes/Stomp.html#over"),e=()=>t),new m(e)}}y.WebSocketClass=null}]));
38
+ let n;t.exports="function"==typeof queueMicrotask?queueMicrotask.bind("undefined"!=typeof window?window:e):t=>(n||(n=Promise.resolve())).then(t).catch(t=>setTimeout(()=>{throw t},0))}).call(this,n(34))},function(t,e,n){"use strict";function r(t,e){for(const n in e)Object.defineProperty(t,n,{value:e[n],enumerable:!0,configurable:!0});return t}t.exports=function(t,e,n){if(!t||"string"==typeof t)throw new TypeError("Please pass an Error to err-code");n||(n={}),"object"==typeof e&&(n=e,e=""),e&&(n.code=e);try{return r(t,n)}catch(e){n.message=t.message,n.stack=t.stack;const i=function(){};i.prototype=Object.create(Object.getPrototypeOf(t));return r(new i,n)}}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.DigitalHumanVideoPlayManager=void 0;const r=n(63),i=n(35);e.DigitalHumanVideoPlayManager=class{constructor(t,e){this.messages=t,this.publicUnmuteDigitalHumanMethod=e,this.remoteVideoPlayCount=0}play(t){this.video=t,this.playRemoteVideo()}unmuteVideo(){this.video&&this.video.muted&&(this.video.muted=!1,this.messages.next(new r.DigitalHumanUnmuted))}playRemoteVideo(){this.video&&(this.video.onerror=t=>{this.messages.next(new r.DigitalHumanVideoError(t))},this.video.play().then(()=>{this.messages.next(new r.DigitalHumanUnmuted)}).catch(()=>{this.digitalHumanFailedToPlayUnmuted()}))}digitalHumanFailedToPlayUnmuted(){this.messages.next(new r.DigitalHumanFailedToPlay),this.video.muted=!0,this.video.play().then(()=>{i.logger.log("Muting the digital human and playing it succeeded."),this.messages.next(new r.DigitalHumanPlayedInMutedModeSuccess),this.video.addEventListener("click",()=>{this.publicUnmuteDigitalHumanMethod()},{once:!0})}).catch(t=>{i.logger.log("Could not play digital human video even as muted, starting exponential backoff.",t),this.playRemoteVideoWithExponentialBackoff()})}playRemoteVideoWithExponentialBackoff(){this.video&&(this.video.autoplay=!0,this.video.play().then(()=>{this.messages.next(new r.DigitalHumanUnmuted)}),this.remoteVideoPlayCount++,setTimeout(()=>{this.remoteVideoPlayCount<10&&this.playRemoteVideoWithExponentialBackoff()},100*(this.remoteVideoPlayCount-1)))}}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.MessageHandler=void 0;const r=n(37),i=n(80);e.MessageHandler=class{constructor(t,e){this.internalMessages$=t,this.messages=e,this.deviceManager={getDevices:(t,e)=>{}},this.getMessagesOfType("AvatarQuestionText").subscribe(t=>{const e={type:i.PromMessageType.QuestionMessageReceived,value:{id:t.id,receivedOn:Date.now()}};this.internalMessages$.next({faceMeMessageType:"prom",promMsg:e}),this.messages.next(new r.AvatarQuestionMessage(t.question,t.id))}),this.getMessagesOfType("AvatarAnswerText").subscribe(t=>{const e={type:i.PromMessageType.AnswerMessageReceived,value:{id:t.questionId,receivedOn:Date.now()}};this.internalMessages$.next({faceMeMessageType:"prom",promMsg:e}),this.messages.next(new r.AvatarAnswerMessage(t.answer,t.answerAvatar,t.answerSpeech,t.questionId))}),this.getMessagesOfType("AvatarAnswerHTML").subscribe(t=>{this.messages.next(new r.AvatarAnswerContentMessage(t.html,t.messageId,t.hasDisplayHtml)),this.messages.next(new r.InstructionsMessage(t.instructions))}),this.getMessagesOfType("AvatarTextInputStarted").subscribe(t=>this.messages.next(new r.StartedSpeakingMessage)),this.getMessagesOfType("AvatarTextInputFinished").subscribe(t=>{this.messages.next(new r.FinishedSpeakingMessage),this.messages.next(new r.AvatarTextInputFinishedMessage)}),this.getMessagesOfType("AvatarStarting").subscribe(t=>{this.deviceManager.edgeNodeId=t.edgeNodeId}),this.getMessagesOfType("ClientMediaStreamUpdate").subscribe(t=>{this.messages.next(new r.ClientMediaStreamUpdateMessage(t.clientStreamingAudio,t.clientStreamingVideo,t.serverStreamingAudio,t.serverStreamingVideo)),t.clientStreamingAudio&&t.clientStreamingVideo&&t.serverStreamingAudio&&t.serverStreamingVideo&&(this.internalMessages$.next({faceMeMessageType:"sessionLive"}),this.internalMessages$.next({faceMeMessageType:"remoteVideoReadyToPlay"}))}),this.getMessagesOfType("SessionErrorMessage").subscribe(t=>{console.error(t.error),this.messages.next(new r.SessionErrorMessage(t.error))}),this.getMessagesOfType("SessionInfoMessage").subscribe(t=>{this.messages.next(new r.SessionInfoMessage(t.info))}),this.getMessagesOfType("SessionEndedMessage").subscribe(()=>{const t={type:i.PromMessageType.SessionEnded,value:{receivedOn:Date.now()}};this.internalMessages$.next({faceMeMessageType:"prom",promMsg:t}),this.internalMessages$.next({faceMeMessageType:"sessionEnd"})}),this.getMessagesOfType("AvatarRequestCompleted").subscribe(t=>{this.messages.next(new r.AvatarRequestCompleted(t.reason))}),this.getMessagesOfType("AvatarRequestIgnored").subscribe(t=>{this.messages.next(new r.AvatarRequestIgnored(t.reason))})}setDeviceManager(t){this.deviceManager=t}getMessagesOfType(t){return this.internalMessages$.filter(e=>e.faceMeMessageType===t)}}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var r={};e.default=void 0;var i=n(135),o=n(139);Object.keys(o).forEach((function(t){"default"!==t&&"__esModule"!==t&&(Object.prototype.hasOwnProperty.call(r,t)||Object.defineProperty(e,t,{enumerable:!0,get:function(){return o[t]}}))}));e.default=function(){return new i.Registry}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.Registry=void 0;var r=n(64),i=n(95),o=n(137),s=n(138),a=n(97);function c(t,e){for(var n=0;n<e.length;n++){var r=e[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(t,r.key,r)}}var u=function(){function t(){var e,n,r;!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,t),r=void 0,(n="data")in(e=this)?Object.defineProperty(e,n,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[n]=r,this.data={counter:{},gauge:{},histogram:{}}}var e,n,u;return e=t,(n=[{key:"validateInput",value:function(t,e,n,i){if(""===String(e))throw new Error("Metric name cannot be empty");if(-1===["counter","gauge","histogram"].indexOf(t))throw new Error("Unknown metric type ".concat(t));if("string"!=typeof n&&null!=n)throw new Error("help must be string or undefined/null");if((0,r.has)(this.data,"".concat(t,".").concat(e)))throw new Error("A metric with the name '".concat(e,"' already exists for type '").concat(t,"'"));if(!Array.isArray(i)&&null!=i)throw new Error("buckets must be array or undefined/null")}},{key:"create",value:function(t,e){var n,r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"",a=arguments.length>3&&void 0!==arguments[3]?arguments[3]:[];return this.validateInput(t,e,r,a),"counter"===t?(n=new i.Counter,this.data.counter[e]={help:r,instance:n,type:t}):"gauge"===t?(n=new o.Gauge,this.data.gauge[e]={help:r,instance:n,type:t}):(n=new s.Histogram(a),this.data.histogram[e]={help:r,instance:n,type:t}),n}},{key:"metrics",value:function(){return(0,r.reduce)(this.data,(function(t,e,n){return t+(0,r.reduce)(e,(function(t,e,i){var o=e.instance.collect(),s=t;return e.help.length>0&&(s+="# HELP ".concat(i," ").concat(e.help,"\n")),s+="# TYPE ".concat(i," ").concat(n,"\n"),s+=(0,r.reduce)(o,(function(t,e){return t+("histogram"===n?(0,a.formatHistogramOrSummary)(i,e):(0,a.formatCounterOrGauge)(i,e))}),"")}),"")}),"")}},{key:"reset",value:function(){return(0,r.each)(this.data,(function(t){(0,r.each)(t,(function(t){t.instance.resetAll()}))})),this}},{key:"clear",value:function(){return this.data={counter:{},gauge:{},histogram:{}},this}},{key:"get",value:function(t,e){var n=(null!=t?[this.data[t]]:(0,r.valuesIn)(this.data)).find((function(t){return(0,r.has)(t,e)}));return null!=n?n[e].instance:void 0}}])&&c(e.prototype,n),u&&c(e,u),t}();e.Registry=u},function(t,e){t.exports=function(t){return t.webpackPolyfill||(t.deprecate=function(){},t.paths=[],t.children||(t.children=[]),Object.defineProperty(t,"loaded",{enumerable:!0,get:function(){return t.l}}),Object.defineProperty(t,"id",{enumerable:!0,get:function(){return t.i}}),t.webpackPolyfill=1),t}},function(t,e,n){"use strict";function r(t){return(r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t})(t)}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function o(t,e){for(var n=0;n<e.length;n++){var r=e[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(t,r.key,r)}}function s(t,e){return!e||"object"!==r(e)&&"function"!=typeof e?function(t){if(void 0===t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return t}(t):e}function a(t){return(a=Object.setPrototypeOf?Object.getPrototypeOf:function(t){return t.__proto__||Object.getPrototypeOf(t)})(t)}function c(t,e){return(c=Object.setPrototypeOf||function(t,e){return t.__proto__=e,t})(t,e)}Object.defineProperty(e,"__esModule",{value:!0}),e.Gauge=void 0;var u=function(t){function e(){return i(this,e),s(this,a(e).apply(this,arguments))}var n,r,u;return function(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function");t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,writable:!0,configurable:!0}}),e&&c(t,e)}(e,t),n=e,(r=[{key:"dec",value:function(t){var e=this.get(t);return this.set(e?e.value-1:0,t),this}},{key:"sub",value:function(t,e){var n=this.get(e);return this.set(n?n.value-t:0,e),this}}])&&o(n.prototype,r),u&&o(n,u),e}(n(95).Counter);e.Gauge=u},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.Histogram=void 0;var r=n(64);function i(t){return(i="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t})(t)}function o(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function s(t,e){for(var n=0;n<e.length;n++){var r=e[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(t,r.key,r)}}function a(t,e){return!e||"object"!==i(e)&&"function"!=typeof e?u(t):e}function c(t){return(c=Object.setPrototypeOf?Object.getPrototypeOf:function(t){return t.__proto__||Object.getPrototypeOf(t)})(t)}function u(t){if(void 0===t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return t}function h(t,e){return(h=Object.setPrototypeOf||function(t,e){return t.__proto__=e,t})(t,e)}function l(t,e,n){return e in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function f(t){return{entries:(0,r.reduce)(t,(function(t,e){return t[e.toString()]=0,t}),{"+Inf":0}),sum:0,count:0,raw:[]}}var d=function(t){function e(){var t,n=arguments.length>0&&void 0!==arguments[0]?arguments[0]:[];return o(this,e),l(u(t=a(this,c(e).call(this))),"buckets",void 0),t.buckets=n.sort((function(t,e){return t>e?1:-1})),t.set(f(t.buckets)),t.observe=t.observe.bind(u(t)),t}var n,i,d;return function(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function");t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,writable:!0,configurable:!0}}),e&&h(t,e)}(e,t),n=e,(i=[{key:"observe",value:function(t,e){var n=this.get(e);null==n&&(n=this.set(f(this.buckets),e).get(e)),n.value.raw.push(t),n.value.entries["+Inf"]+=1;var i=function(t,e){if(e<t[t.length-1])for(var n=0;n<t.length;n+=1)if(e<=t[n])return n}(this.buckets,t);if(null!=i)for(var o=i;o<this.buckets.length;o+=1){var s=n.value.entries[this.buckets[o].toString()];n.value.entries[this.buckets[o].toString()]=s+1}return n.value.sum=(0,r.sum)(n.value.raw),n.value.count+=1,this}},{key:"reset",value:function(t){this.set(f(this.buckets),t)}}])&&s(n.prototype,i),d&&s(n,d),e}(n(96).Collector);e.Histogram=d},function(t,e,n){},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.MessagingState=e.MessagingService=void 0;const r=n(141);Object.defineProperty(e,"MessagingService",{enumerable:!0,get:function(){return r.MessagingService}});const i=n(98);Object.defineProperty(e,"MessagingState",{enumerable:!0,get:function(){return i.MessagingState}})},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.MessagingService=void 0;const r=n(155),i=n(142),o=n(144),s=n(35),a=n(98);e.MessagingService=class{constructor(t,e){this.options={autoReconnect:!0,reconnectTime:5e3,maxReconnectAttempts:3,connectionHeaders:{},maxReconnectLimitReached:()=>{},onReconnect:()=>{}},this.url=t,this.options=Object.assign(this.options,e),this.subscriptions={},this.connectionAttempts=0,this.state$=new i.BehaviorSubject(a.MessagingState.DISCONNECTED),this.messages$=new o.Subject,console.log("connect headers messaging: ",this.options.connectionHeaders);const n={connectHeaders:this.options.connectionHeaders,reconnectDelay:0,connectionTimeout:5e3,discardWebsocketOnCommFailure:!0,brokerURL:this.url.replace("https://","wss://").replace("http://","ws://")};this.stompClient=new r.Client(n),this.stompClient.onConnect=t=>this.onStompConnected(t),this.stompClient.onDisconnect=t=>{s.logger.log("Stomp client disconnected",t)},this.stompClient.onStompError=t=>{s.logger.log("Stomp client error",t),this.onStompClientConnectionClosed(t)},this.stompClient.onWebSocketError=t=>{s.logger.log("Stomp client web socket error",t),this.onStompClientConnectionClosed(t)},this.stompClient.onWebSocketClose=t=>{s.logger.log("Stomp client web socket closed",t),this.onStompClientConnectionClosed(t)}}connect(){this.disconnect(),s.logger.log("MessagingService | connecting..."),this.state$.next(a.MessagingState.CONNECTING),this.connectionAttempts++,this.stompClient.activate()}disconnect(){const t=this.state$.getValue();if(t===a.MessagingState.CONNECTED||t===a.MessagingState.CONNECTING){s.logger.log("Disconnecting stomp client");try{this.subscriptions={},this.options.autoReconnect=!1,this.stompClient.deactivate(),this.stompClient.forceDisconnect(),this.state$.next(a.MessagingState.DISCONNECTED)}catch(t){console.error("MessagingService | disconnect: error",t),this.state$.next(a.MessagingState.DISCONNECTED)}}}send(t,e){s.logger.log("MessagingService | send:",t,e);const n={"content-type":"application/json","x-auth-token":this.options.connectionHeaders["x-auth-token"]},r=JSON.stringify(e);this.stompClient.publish({destination:t,body:r,headers:n})}getTopic(t){s.logger.log("MessagingService | subscribeToTopic: "+t);const e=this.subscriptions[t];if(e)return s.logger.log("existing subscription... not re-subscribing to topic"),e;const n=new o.Subject;return this.stompClient.subscribe(t,t=>{n.next(t),this.messages$.next(t)}),this.subscriptions[t]=n,n}onStompConnected(t){s.logger.log("MessagingService | connected"),this.state$.next(a.MessagingState.CONNECTED),this.initMessagingSubscription(),this.connectionAttempts=0}onStompClientConnectionClosed(t){this.options.autoReconnect?this.options.maxReconnectAttempts&&this.connectionAttempts<this.options.maxReconnectAttempts?setTimeout(()=>{this.connect()},this.options.reconnectTime):this.options.maxReconnectLimitReached&&(this.options.maxReconnectLimitReached(),this.disconnect()):this.disconnect()}initMessagingSubscription(){s.logger.log("MessagingService | initMessagingSubscription");this.stompClient.subscribe("/",t=>{this.messages$.next(t)})}}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),function(t){for(var n in t)e.hasOwnProperty(n)||(e[n]=t[n])}(n(143))},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var r=n(47);e.BehaviorSubject=r.BehaviorSubject},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),function(t){for(var n in t)e.hasOwnProperty(n)||(e[n]=t[n])}(n(145))},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var r=n(47);e.Subject=r.Subject},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.MetricsService=void 0;const r=n(37),i=n(147),o=n(80);e.MetricsService=class{constructor(t,e,n){this.uneeqOptions=t,this.internalMessages=e,this.messages=n,this.clientPerformanceStats={},this.options=t,this.internalMessages$=e,this.messages$=n}parseAndLogWebRtcStats(t){try{t.forEach(t=>{var e,n;if("inbound-rtp"===t.type&&"video"===t.kind){this.clientPerformanceStats.frameHeight=new i.ClientPerformanceStat("Frame height",t.frameHeight),this.clientPerformanceStats.frameWidth=new i.ClientPerformanceStat("Frame width",t.frameWidth);const r=t.framesDropped,o=r?r-(null===(e=this.clientPerformanceStats.totalFramesDropped)||void 0===e?void 0:e.value):0;this.clientPerformanceStats.newFramesDropped=o?new i.ClientPerformanceStat("New Frames Dropped",o):new i.ClientPerformanceStat,this.clientPerformanceStats.totalFramesDropped=r?new i.ClientPerformanceStat("Total Frames Dropped",r):new i.ClientPerformanceStat;const s=t.packetsLost,a=s?s-(null===(n=this.clientPerformanceStats.inboundTotalPacketsLost)||void 0===n?void 0:n.value):0;this.clientPerformanceStats.inboundNewPacketsLost=a?new i.ClientPerformanceStat("New packets lost",a):new i.ClientPerformanceStat,this.clientPerformanceStats.inboundTotalPacketsLost=s?new i.ClientPerformanceStat("Total packets lost",s):new i.ClientPerformanceStat;const c=t.framesPerSecond;this.clientPerformanceStats.framesPerSec=c?new i.ClientPerformanceStat("Frames per second",c):new i.ClientPerformanceStat}else if("remote-inbound-rtp"===t.type&&"video"===t.kind){const e=t.roundTripTime;this.clientPerformanceStats.inboundRoundTripTime=e?new i.ClientPerformanceStat("Round Trip Time",e):new i.ClientPerformanceStat}else if("outbound-rtp"===t.type&&"video"===t.kind){const e=t.qualityLimitationReason;this.clientPerformanceStats.outboundQualityLimitationReason=new i.ClientPerformanceStat("Quality Limitation Reason",e)}}),this.options.enableClientPerformanceMessage&&this.messages$.next(new r.ClientPerformanceMessage(this.clientPerformanceStats));const e={type:o.PromMessageType.WebRtcPerformance,value:this.clientPerformanceStats};this.internalMessages$.next({faceMeMessageType:"prom",promMsg:e})}catch(t){console.warn("Unable to parseAndLogWebRTCStats",t)}}}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.ClientPerformanceStat=void 0;e.ClientPerformanceStat=class{constructor(t="",e=0){this.label=t,this.value=e}}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.OnlineStatusService=void 0;const r=n(37);e.OnlineStatusService=class{constructor(t,e){this.messages=t,this.offlineTimeoutLimitHandler=e,this.online=!0,this.offlineDisconnectTimeLimitMS=1e4,window.addEventListener("offline",()=>this.handleOffline()),window.addEventListener("online",()=>this.handleOnline())}handleOffline(){this.online=!1,this.disconnectTimer=setTimeout(()=>{this.offlineTimeoutLimitHandler()},this.offlineDisconnectTimeLimitMS),this.sendStatusUpdate()}handleOnline(){this.online=!0,window.clearTimeout(this.disconnectTimer),this.sendStatusUpdate()}sendStatusUpdate(){this.messages.next(new r.OnlineStatusUpdateMessage(this.online))}}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.ResumeSessionCheck=void 0;const r=n(35);class i{static validate(t){let e=void 0!==t.resumeSession&&t.resumeSession;localStorage.getItem("uneeqResumeSessionPersonaId")===t.conversationId||(r.logger.log("UneeQ: Persona Id's do not match, unable to resume session."),e=!1);const n=i.browserTabIsActive();if(e&&!n&&(r.logger.log("UneeQ: Browser tab is not active so unable to resume"),e=!1),e){const t=localStorage.getItem("uneeqResumeSessionId");if(null!==t)return{resumeSession:!0,resumeSessionId:t}}return{resumeSession:!1}}static browserTabIsActive(){return!document.hidden}}e.ResumeSessionCheck=i},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.StreamManager=void 0;e.StreamManager=class{constructor(){window.AudioContext=window.AudioContext||window.webkitAudioContext,this.silentAudioTrack=this.generateSilentAudioTrack(),this.canvasVideoTrack=this.generateCanvasVideoTrack()}addCanvasVideoTrackToStream(t){return t.getVideoTracks().forEach(e=>t.removeTrack(e)),t.addTrack(this.canvasVideoTrack),t}addSilentAudioTrackToStream(t){return t.getAudioTracks().forEach(e=>t.removeTrack(e)),t.addTrack(this.silentAudioTrack),t}resumeAudioContext(){this.audioContextInstance&&this.audioContextInstance.resume()}generateCanvasVideoTrack(){const t=document.createElement("canvas");t.width=40,t.height=30,t.getContext("2d");return t.captureStream(1).getVideoTracks()[0]}generateSilentAudioTrack(){if(!this.audioSourceNode||!this.audioSourceDestination){const t=new window.AudioContext;this.audioContextInstance=t,this.audioSourceDestination=t.createMediaStreamDestination()}return this.audioSourceDestination.stream.getAudioTracks()[0]}}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.VoiceInputManager=void 0;const r=n(81),i=n(152),o=n(63),s=n(99),a=n(35);e.VoiceInputManager=class{constructor(t,e,n,r){this.options=t,this.api=e,this.messages=n,this.enableMicrophone=r,this.microphoneEngageVolume=.02,this.microphoneDisengageVolume=.02,this.voiceActivityNotSpeakingTimeoutMS=1e3,this.voiceActivityAllowInterruptions=!1,this.digitalHumanSpeaking=!1,this.recording=!1,this.setVoiceInputMode(t.voiceInputMode);try{window.AudioContext=window.AudioContext||window.webkitAudioContext,this.audioContext=new AudioContext}catch(t){this.audioContextNotSupported()}this.handleAppMessages()}setVoiceInputMode(t){t===s.VoiceInputMode.PUSH_TO_TALK?this.options.voiceInputMode=s.VoiceInputMode.PUSH_TO_TALK:t===s.VoiceInputMode.VOICE_ACTIVITY?this.options.voiceInputMode=s.VoiceInputMode.VOICE_ACTIVITY:this.messages.next(new o.WarningMessage("Invalid voice input mode selected: "+t))}startRecording(){this.options.voiceInputMode===s.VoiceInputMode.PUSH_TO_TALK?this.apiStartRecording():this.requestNotSupportedInVoiceActivityMode("startRecording")}stopRecording(){this.options.voiceInputMode===s.VoiceInputMode.PUSH_TO_TALK?this.apiStopRecording():this.requestNotSupportedInVoiceActivityMode("stopRecording")}handleSessionEnd(){this.soundMeter&&this.soundMeter.stop()}resumeAudioContext(){a.logger.log("UneeQ: resuming publish stream audio context and initializing mic activity."),this.audioContext&&(this.audioContext.resume(),this.stream&&this.initMicActivity(this.stream))}initMicActivity(t){this.stream=t,this.soundMeter=new i.SoundMeter(this.audioContext),this.soundMeter.connectToSource(t,t=>this.micActivityConnected(t))}audioContextNotSupported(){this.options.micActivityMessages&&this.messages.next(new o.MicActivityNotSupportedMessage),this.messages.next(new o.VoiceActivityInputModeNotSupportedMessage),this.setVoiceInputMode(s.VoiceInputMode.PUSH_TO_TALK)}handleAppMessages(){this.messages.subscribe(t=>{switch(t.uneeqMessageType){case o.UneeqMessageType.StartedSpeaking:console.log("StartSpeaking message"),this.digitalHumanSpeaking=!0;break;case o.UneeqMessageType.FinishedSpeaking:this.digitalHumanSpeaking=!1}})}requestNotSupportedInVoiceActivityMode(t){this.messages.next(new o.WarningMessage("Request not supported in voice activity mode: "+t))}apiStartRecording(){this.recording=!0,this.messages.next(new o.RecordingStartedMessage),this.api.avatarStartRecording().catch(()=>{this.recording=!1,this.messages.next(new o.RecordingStoppedMessage)})}apiStopRecording(){this.recording=!1,this.api.avatarStopRecording().finally(()=>this.messages.next(new o.RecordingStoppedMessage))}micActivityConnected(t){t?this.messages.next(new o.MicActivityErrorMessage(t)):this.soundMeter&&this.soundMeter.instant$.pipe(r.distinctUntilChanged()).subscribe(t=>{this.handleVoiceActivity(t)})}handleVoiceActivity(t){this.options.micActivityMessages&&this.messages.next(new o.MicActivityMessage(t)),this.options.voiceInputMode!==s.VoiceInputMode.VOICE_ACTIVITY||this.digitalHumanSpeaking&&!this.voiceActivityAllowInterruptions||(t>this.microphoneEngageVolume?(this.recording||this.apiStartRecording(),this.clearSilenceTimeout()):t<this.microphoneDisengageVolume&&this.recording&&(this.clearSilenceTimeout(),this.silenceTimeout=setTimeout(()=>{this.recording&&this.apiStopRecording()},this.voiceActivityNotSpeakingTimeoutMS)))}clearSilenceTimeout(){this.silenceTimeout&&clearTimeout(this.silenceTimeout)}}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.SoundMeter=void 0;const r=n(47),i=n(35);e.SoundMeter=class{constructor(t){this.instant$=new r.BehaviorSubject(0),this.context=t,this.instant=0,this.slow=0,this.clip=0,this.script=t.createScriptProcessor(2048,1,1);const e=this;this.script.onaudioprocess=t=>{const n=t.inputBuffer.getChannelData(0);let r,i=0,o=0;for(r=0;r<n.length;++r)i+=n[r]*n[r],Math.abs(n[r])>.99&&(o+=1);e.instant=Math.sqrt(i/n.length),e.slow=.95*e.slow+.05*e.instant,e.clip=o/n.length,e.instant$.next(parseFloat(e.instant.toFixed(2)))}}connectToSource(t,e){i.logger.log("SoundMeter connecting");try{this.mic=this.context.createMediaStreamSource(t),this.mic.connect(this.script),this.script.connect(this.context.destination),void 0!==e&&e(null)}catch(t){console.error(t),void 0!==e&&e(t)}}stop(){this.mic.disconnect(),this.script.disconnect()}}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.SessionType=void 0,function(t){t[t.WEB=0]="WEB"}(e.SessionType||(e.SessionType={}))},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.SourceApp=void 0,function(t){t.HOSTED_EXPERIENCE="HOSTED_EXPERIENCE",t.SHOWCASE="SHOWCASE",t.SPLIT_SCREEN="SPLIT_SCREEN",t.INTERACTIONS="INTERACTIONS",t.UNKNOWN="UNKNOWN"}(e.SourceApp||(e.SourceApp={}))},function(t,e,n){"use strict";n.r(e),n.d(e,"Client",(function(){return f})),n.d(e,"FrameImpl",(function(){return o})),n.d(e,"Parser",(function(){return s})),n.d(e,"StompConfig",(function(){return d})),n.d(e,"StompHeaders",(function(){return p})),n.d(e,"StompSubscription",(function(){return v})),n.d(e,"StompSocketState",(function(){return a})),n.d(e,"ActivationState",(function(){return c})),n.d(e,"Versions",(function(){return u})),n.d(e,"CompatClient",(function(){return m})),n.d(e,"Stomp",(function(){return y}));const r="\n",i="\0";class o{constructor(t){const{command:e,headers:n,body:r,binaryBody:i,escapeHeaderValues:o,skipContentLengthHeader:s}=t;this.command=e,this.headers=Object.assign({},n||{}),i?(this._binaryBody=i,this.isBinaryBody=!0):(this._body=r||"",this.isBinaryBody=!1),this.escapeHeaderValues=o||!1,this.skipContentLengthHeader=s||!1}get body(){return!this._body&&this.isBinaryBody&&(this._body=(new TextDecoder).decode(this._binaryBody)),this._body}get binaryBody(){return this._binaryBody||this.isBinaryBody||(this._binaryBody=(new TextEncoder).encode(this._body)),this._binaryBody}static fromRawFrame(t,e){const n={},r=t=>t.replace(/^\s+|\s+$/g,"");for(const i of t.headers.reverse()){i.indexOf(":");const s=r(i[0]);let a=r(i[1]);e&&"CONNECT"!==t.command&&"CONNECTED"!==t.command&&(a=o.hdrValueUnEscape(a)),n[s]=a}return new o({command:t.command,headers:n,binaryBody:t.binaryBody,escapeHeaderValues:e})}toString(){return this.serializeCmdAndHeaders()}serialize(){const t=this.serializeCmdAndHeaders();return this.isBinaryBody?o.toUnit8Array(t,this._binaryBody).buffer:t+this._body+i}serializeCmdAndHeaders(){const t=[this.command];this.skipContentLengthHeader&&delete this.headers["content-length"];for(const e of Object.keys(this.headers||{})){const n=this.headers[e];this.escapeHeaderValues&&"CONNECT"!==this.command&&"CONNECTED"!==this.command?t.push(`${e}:${o.hdrValueEscape(""+n)}`):t.push(`${e}:${n}`)}return(this.isBinaryBody||!this.isBodyEmpty()&&!this.skipContentLengthHeader)&&t.push("content-length:"+this.bodyLength()),t.join(r)+r+r}isBodyEmpty(){return 0===this.bodyLength()}bodyLength(){const t=this.binaryBody;return t?t.length:0}static sizeOfUTF8(t){return t?(new TextEncoder).encode(t).length:0}static toUnit8Array(t,e){const n=(new TextEncoder).encode(t),r=new Uint8Array([0]),i=new Uint8Array(n.length+e.length+r.length);return i.set(n),i.set(e,n.length),i.set(r,n.length+e.length),i}static marshall(t){return new o(t).serialize()}static hdrValueEscape(t){return t.replace(/\\/g,"\\\\").replace(/\r/g,"\\r").replace(/\n/g,"\\n").replace(/:/g,"\\c")}static hdrValueUnEscape(t){return t.replace(/\\r/g,"\r").replace(/\\n/g,"\n").replace(/\\c/g,":").replace(/\\\\/g,"\\")}}class s{constructor(t,e){this.onFrame=t,this.onIncomingPing=e,this._encoder=new TextEncoder,this._decoder=new TextDecoder,this._token=[],this._initState()}parseChunk(t,e=!1){let n;if(n=t instanceof ArrayBuffer?new Uint8Array(t):this._encoder.encode(t),e&&0!==n[n.length-1]){const t=new Uint8Array(n.length+1);t.set(n,0),t[n.length]=0,n=t}for(let t=0;t<n.length;t++){const e=n[t];this._onByte(e)}}_collectFrame(t){0!==t&&13!==t&&(10!==t?(this._onByte=this._collectCommand,this._reinjectByte(t)):this.onIncomingPing())}_collectCommand(t){if(13!==t)return 10===t?(this._results.command=this._consumeTokenAsUTF8(),void(this._onByte=this._collectHeaders)):void this._consumeByte(t)}_collectHeaders(t){13!==t&&(10!==t?(this._onByte=this._collectHeaderKey,this._reinjectByte(t)):this._setupCollectBody())}_reinjectByte(t){this._onByte(t)}_collectHeaderKey(t){if(58===t)return this._headerKey=this._consumeTokenAsUTF8(),void(this._onByte=this._collectHeaderValue);this._consumeByte(t)}_collectHeaderValue(t){if(13!==t)return 10===t?(this._results.headers.push([this._headerKey,this._consumeTokenAsUTF8()]),this._headerKey=void 0,void(this._onByte=this._collectHeaders)):void this._consumeByte(t)}_setupCollectBody(){const t=this._results.headers.filter(t=>"content-length"===t[0])[0];t?(this._bodyBytesRemaining=parseInt(t[1],10),this._onByte=this._collectBodyFixedSize):this._onByte=this._collectBodyNullTerminated}_collectBodyNullTerminated(t){0!==t?this._consumeByte(t):this._retrievedBody()}_collectBodyFixedSize(t){0!=this._bodyBytesRemaining--?this._consumeByte(t):this._retrievedBody()}_retrievedBody(){this._results.binaryBody=this._consumeTokenAsRaw(),this.onFrame(this._results),this._initState()}_consumeByte(t){this._token.push(t)}_consumeTokenAsUTF8(){return this._decoder.decode(this._consumeTokenAsRaw())}_consumeTokenAsRaw(){const t=new Uint8Array(this._token);return this._token=[],t}_initState(){this._results={command:void 0,headers:[],binaryBody:void 0},this._token=[],this._headerKey=void 0,this._onByte=this._collectFrame}}var a,c;!function(t){t[t.CONNECTING=0]="CONNECTING",t[t.OPEN=1]="OPEN",t[t.CLOSING=2]="CLOSING",t[t.CLOSED=3]="CLOSED"}(a||(a={})),function(t){t[t.ACTIVE=0]="ACTIVE",t[t.DEACTIVATING=1]="DEACTIVATING",t[t.INACTIVE=2]="INACTIVE"}(c||(c={}));class u{constructor(t){this.versions=t}supportedVersions(){return this.versions.join(",")}protocolVersions(){return this.versions.map(t=>`v${t.replace(".","")}.stomp`)}}u.V1_0="1.0",u.V1_1="1.1",u.V1_2="1.2",u.default=new u([u.V1_0,u.V1_1,u.V1_2]);class h{constructor(t,e,n={}){this._client=t,this._webSocket=e,this._serverFrameHandlers={CONNECTED:t=>{this.debug("connected to server "+t.headers.server),this._connected=!0,this._connectedVersion=t.headers.version,this._connectedVersion===u.V1_2&&(this._escapeHeaderValues=!0),this._setupHeartbeat(t.headers),this.onConnect(t)},MESSAGE:t=>{const e=t.headers.subscription,n=this._subscriptions[e]||this.onUnhandledMessage,r=t,i=this,o=this._connectedVersion===u.V1_2?r.headers.ack:r.headers["message-id"];r.ack=(t={})=>i.ack(o,e,t),r.nack=(t={})=>i.nack(o,e,t),n(r)},RECEIPT:t=>{const e=this._receiptWatchers[t.headers["receipt-id"]];e?(e(t),delete this._receiptWatchers[t.headers["receipt-id"]]):this.onUnhandledReceipt(t)},ERROR:t=>{this.onStompError(t)}},this._counter=0,this._subscriptions={},this._receiptWatchers={},this._partialData="",this._escapeHeaderValues=!1,this._lastServerActivityTS=Date.now(),this.configure(n)}get connectedVersion(){return this._connectedVersion}get connected(){return this._connected}configure(t){Object.assign(this,t)}start(){const t=new s(t=>{const e=o.fromRawFrame(t,this._escapeHeaderValues);this.logRawCommunication||this.debug("<<< "+e);(this._serverFrameHandlers[e.command]||this.onUnhandledFrame)(e)},()=>{this.debug("<<< PONG")});this._webSocket.onmessage=e=>{if(this.debug("Received data"),this._lastServerActivityTS=Date.now(),this.logRawCommunication){const t=e.data instanceof ArrayBuffer?(new TextDecoder).decode(e.data):e.data;this.debug("<<< "+t)}t.parseChunk(e.data,this.appendMissingNULLonIncoming)},this._onclose=t=>{this.debug("Connection closed to "+this._client.brokerURL),this._cleanUp(),this.onWebSocketClose(t)},this._webSocket.onclose=this._onclose,this._webSocket.onerror=t=>{this.onWebSocketError(t)},this._webSocket.onopen=()=>{const t=Object.assign({},this.connectHeaders);this.debug("Web Socket Opened..."),t["accept-version"]=this.stompVersions.supportedVersions(),t["heart-beat"]=[this.heartbeatOutgoing,this.heartbeatIncoming].join(","),this._transmit({command:"CONNECT",headers:t})}}_setupHeartbeat(t){if(t.version!==u.V1_1&&t.version!==u.V1_2)return;if(!t["heart-beat"])return;const[e,n]=t["heart-beat"].split(",").map(t=>parseInt(t,10));if(0!==this.heartbeatOutgoing&&0!==n){const t=Math.max(this.heartbeatOutgoing,n);this.debug(`send PING every ${t}ms`),this._pinger=setInterval(()=>{this._webSocket.readyState===a.OPEN&&(this._webSocket.send(r),this.debug(">>> PING"))},t)}if(0!==this.heartbeatIncoming&&0!==e){const t=Math.max(this.heartbeatIncoming,e);this.debug(`check PONG every ${t}ms`),this._ponger=setInterval(()=>{const e=Date.now()-this._lastServerActivityTS;e>2*t&&(this.debug(`did not receive server activity for the last ${e}ms`),this._closeOrDiscardWebsocket())},t)}}_closeOrDiscardWebsocket(){this.discardWebsocketOnCommFailure?(this.debug("Discarding websocket, the underlying socket may linger for a while"),this._discardWebsocket()):(this.debug("Issuing close on the websocket"),this._closeWebsocket())}forceDisconnect(){this._webSocket&&(this._webSocket.readyState!==a.CONNECTING&&this._webSocket.readyState!==a.OPEN||this._closeOrDiscardWebsocket())}_closeWebsocket(){this._webSocket.onmessage=()=>{},this._webSocket.close()}_discardWebsocket(){var t,e;this._webSocket.terminate||(t=this._webSocket,e=t=>this.debug(t),t.terminate=function(){const t=()=>{};this.onerror=t,this.onmessage=t,this.onopen=t;const n=new Date,r=this.onclose;this.onclose=t=>{const r=(new Date).getTime()-n.getTime();e(`Discarded socket closed after ${r}ms, with code/reason: ${t.code}/${t.reason}`)},this.close(),r.call(this,{code:4001,reason:"Heartbeat failure, discarding the socket",wasClean:!1})}),this._webSocket.terminate()}_transmit(t){const{command:e,headers:n,body:r,binaryBody:i,skipContentLengthHeader:s}=t,a=new o({command:e,headers:n,body:r,binaryBody:i,escapeHeaderValues:this._escapeHeaderValues,skipContentLengthHeader:s});let c=a.serialize();if(this.logRawCommunication?this.debug(">>> "+c):this.debug(">>> "+a),this.forceBinaryWSFrames&&"string"==typeof c&&(c=(new TextEncoder).encode(c)),"string"==typeof c&&this.splitLargeFrames){let t=c;for(;t.length>0;){const e=t.substring(0,this.maxWebSocketChunkSize);t=t.substring(this.maxWebSocketChunkSize),this._webSocket.send(e),this.debug(`chunk sent = ${e.length}, remaining = ${t.length}`)}}else this._webSocket.send(c)}dispose(){if(this.connected)try{const t=Object.assign({},this.disconnectHeaders);t.receipt||(t.receipt="close-"+this._counter++),this.watchForReceipt(t.receipt,t=>{this._closeWebsocket(),this._cleanUp(),this.onDisconnect(t)}),this._transmit({command:"DISCONNECT",headers:t})}catch(t){this.debug("Ignoring error during disconnect "+t)}else this._webSocket.readyState!==a.CONNECTING&&this._webSocket.readyState!==a.OPEN||this._closeWebsocket()}_cleanUp(){this._connected=!1,this._pinger&&clearInterval(this._pinger),this._ponger&&clearInterval(this._ponger)}publish(t){const{destination:e,headers:n,body:r,binaryBody:i,skipContentLengthHeader:o}=t,s=Object.assign({destination:e},n);this._transmit({command:"SEND",headers:s,body:r,binaryBody:i,skipContentLengthHeader:o})}watchForReceipt(t,e){this._receiptWatchers[t]=e}subscribe(t,e,n={}){(n=Object.assign({},n)).id||(n.id="sub-"+this._counter++),n.destination=t,this._subscriptions[n.id]=e,this._transmit({command:"SUBSCRIBE",headers:n});const r=this;return{id:n.id,unsubscribe:t=>r.unsubscribe(n.id,t)}}unsubscribe(t,e={}){e=Object.assign({},e),delete this._subscriptions[t],e.id=t,this._transmit({command:"UNSUBSCRIBE",headers:e})}begin(t){const e=t||"tx-"+this._counter++;this._transmit({command:"BEGIN",headers:{transaction:e}});const n=this;return{id:e,commit(){n.commit(e)},abort(){n.abort(e)}}}commit(t){this._transmit({command:"COMMIT",headers:{transaction:t}})}abort(t){this._transmit({command:"ABORT",headers:{transaction:t}})}ack(t,e,n={}){n=Object.assign({},n),this._connectedVersion===u.V1_2?n.id=t:n["message-id"]=t,n.subscription=e,this._transmit({command:"ACK",headers:n})}nack(t,e,n={}){return n=Object.assign({},n),this._connectedVersion===u.V1_2?n.id=t:n["message-id"]=t,n.subscription=e,this._transmit({command:"NACK",headers:n})}}var l=function(t,e,n,r){return new(n||(n=Promise))((function(i,o){function s(t){try{c(r.next(t))}catch(t){o(t)}}function a(t){try{c(r.throw(t))}catch(t){o(t)}}function c(t){var e;t.done?i(t.value):(e=t.value,e instanceof n?e:new n((function(t){t(e)}))).then(s,a)}c((r=r.apply(t,e||[])).next())}))};class f{constructor(t={}){this.stompVersions=u.default,this.connectionTimeout=0,this.reconnectDelay=5e3,this.heartbeatIncoming=1e4,this.heartbeatOutgoing=1e4,this.splitLargeFrames=!1,this.maxWebSocketChunkSize=8192,this.forceBinaryWSFrames=!1,this.appendMissingNULLonIncoming=!1,this.state=c.INACTIVE;const e=()=>{};this.debug=e,this.beforeConnect=e,this.onConnect=e,this.onDisconnect=e,this.onUnhandledMessage=e,this.onUnhandledReceipt=e,this.onUnhandledFrame=e,this.onStompError=e,this.onWebSocketClose=e,this.onWebSocketError=e,this.logRawCommunication=!1,this.onChangeState=e,this.connectHeaders={},this._disconnectHeaders={},this.configure(t)}get webSocket(){return this._stompHandler?this._stompHandler._webSocket:void 0}get disconnectHeaders(){return this._disconnectHeaders}set disconnectHeaders(t){this._disconnectHeaders=t,this._stompHandler&&(this._stompHandler.disconnectHeaders=this._disconnectHeaders)}get connected(){return!!this._stompHandler&&this._stompHandler.connected}get connectedVersion(){return this._stompHandler?this._stompHandler.connectedVersion:void 0}get active(){return this.state===c.ACTIVE}_changeState(t){this.state=t,this.onChangeState(t)}configure(t){Object.assign(this,t)}activate(){if(this.state===c.DEACTIVATING)throw this.debug("Still DEACTIVATING, please await call to deactivate before trying to re-activate"),new Error("Still DEACTIVATING, can not activate now");this.active?this.debug("Already ACTIVE, ignoring request to activate"):(this._changeState(c.ACTIVE),this._connect())}_connect(){return l(this,void 0,void 0,(function*(){if(this.connected)return void this.debug("STOMP: already connected, nothing to do");if(yield this.beforeConnect(),!this.active)return void this.debug("Client has been marked inactive, will not attempt to connect");this.connectionTimeout>0&&(this._connectionWatcher&&clearTimeout(this._connectionWatcher),this._connectionWatcher=setTimeout(()=>{this.connected||(this.debug(`Connection not established in ${this.connectionTimeout}ms, closing socket`),this.forceDisconnect())},this.connectionTimeout)),this.debug("Opening Web Socket...");const t=this._createWebSocket();this._stompHandler=new h(this,t,{debug:this.debug,stompVersions:this.stompVersions,connectHeaders:this.connectHeaders,disconnectHeaders:this._disconnectHeaders,heartbeatIncoming:this.heartbeatIncoming,heartbeatOutgoing:this.heartbeatOutgoing,splitLargeFrames:this.splitLargeFrames,maxWebSocketChunkSize:this.maxWebSocketChunkSize,forceBinaryWSFrames:this.forceBinaryWSFrames,logRawCommunication:this.logRawCommunication,appendMissingNULLonIncoming:this.appendMissingNULLonIncoming,discardWebsocketOnCommFailure:this.discardWebsocketOnCommFailure,onConnect:t=>{if(this._connectionWatcher&&(clearTimeout(this._connectionWatcher),this._connectionWatcher=void 0),!this.active)return this.debug("STOMP got connected while deactivate was issued, will disconnect now"),void this._disposeStompHandler();this.onConnect(t)},onDisconnect:t=>{this.onDisconnect(t)},onStompError:t=>{this.onStompError(t)},onWebSocketClose:t=>{this._stompHandler=void 0,this.state===c.DEACTIVATING&&(this._resolveSocketClose(),this._resolveSocketClose=void 0,this._changeState(c.INACTIVE)),this.onWebSocketClose(t),this.active&&this._schedule_reconnect()},onWebSocketError:t=>{this.onWebSocketError(t)},onUnhandledMessage:t=>{this.onUnhandledMessage(t)},onUnhandledReceipt:t=>{this.onUnhandledReceipt(t)},onUnhandledFrame:t=>{this.onUnhandledFrame(t)}}),this._stompHandler.start()}))}_createWebSocket(){let t;return t=this.webSocketFactory?this.webSocketFactory():new WebSocket(this.brokerURL,this.stompVersions.protocolVersions()),t.binaryType="arraybuffer",t}_schedule_reconnect(){this.reconnectDelay>0&&(this.debug(`STOMP: scheduling reconnection in ${this.reconnectDelay}ms`),this._reconnector=setTimeout(()=>{this._connect()},this.reconnectDelay))}deactivate(){return l(this,void 0,void 0,(function*(){let t;return this.state!==c.ACTIVE?(this.debug(`Already ${c[this.state]}, ignoring call to deactivate`),Promise.resolve()):(this._changeState(c.DEACTIVATING),this._reconnector&&clearTimeout(this._reconnector),this._stompHandler&&this.webSocket.readyState!==a.CLOSED?(t=new Promise((t,e)=>{this._resolveSocketClose=t}),this._disposeStompHandler(),t):(this._changeState(c.INACTIVE),Promise.resolve()))}))}forceDisconnect(){this._stompHandler&&this._stompHandler.forceDisconnect()}_disposeStompHandler(){this._stompHandler&&(this._stompHandler.dispose(),this._stompHandler=null)}publish(t){this._stompHandler.publish(t)}watchForReceipt(t,e){this._stompHandler.watchForReceipt(t,e)}subscribe(t,e,n={}){return this._stompHandler.subscribe(t,e,n)}unsubscribe(t,e={}){this._stompHandler.unsubscribe(t,e)}begin(t){return this._stompHandler.begin(t)}commit(t){this._stompHandler.commit(t)}abort(t){this._stompHandler.abort(t)}ack(t,e,n={}){this._stompHandler.ack(t,e,n)}nack(t,e,n={}){this._stompHandler.nack(t,e,n)}}class d{}class p{}class v{}class g{constructor(t){this.client=t}get outgoing(){return this.client.heartbeatOutgoing}set outgoing(t){this.client.heartbeatOutgoing=t}get incoming(){return this.client.heartbeatIncoming}set incoming(t){this.client.heartbeatIncoming=t}}class m extends f{constructor(t){super(),this.maxWebSocketFrameSize=16384,this._heartbeatInfo=new g(this),this.reconnect_delay=0,this.webSocketFactory=t,this.debug=(...t)=>{console.log(...t)}}_parseConnect(...t){let e,n,r,i={};if(t.length<2)throw new Error("Connect requires at least 2 arguments");if("function"==typeof t[1])[i,n,r,e]=t;else switch(t.length){case 6:[i.login,i.passcode,n,r,e,i.host]=t;break;default:[i.login,i.passcode,n,r,e]=t}return[i,n,r,e]}connect(...t){const e=this._parseConnect(...t);e[0]&&(this.connectHeaders=e[0]),e[1]&&(this.onConnect=e[1]),e[2]&&(this.onStompError=e[2]),e[3]&&(this.onWebSocketClose=e[3]),super.activate()}disconnect(t,e={}){t&&(this.onDisconnect=t),this.disconnectHeaders=e,super.deactivate()}send(t,e={},n=""){const r=!1===(e=Object.assign({},e))["content-length"];r&&delete e["content-length"],this.publish({destination:t,headers:e,body:n,skipContentLengthHeader:r})}set reconnect_delay(t){this.reconnectDelay=t}get ws(){return this.webSocket}get version(){return this.connectedVersion}get onreceive(){return this.onUnhandledMessage}set onreceive(t){this.onUnhandledMessage=t}get onreceipt(){return this.onUnhandledReceipt}set onreceipt(t){this.onUnhandledReceipt=t}get heartbeat(){return this._heartbeatInfo}set heartbeat(t){this.heartbeatIncoming=t.incoming,this.heartbeatOutgoing=t.outgoing}}class y{static client(t,e){null==e&&(e=u.default.protocolVersions());return new m(()=>new(y.WebSocketClass||WebSocket)(t,e))}static over(t){let e;return"function"==typeof t?e=t:(console.warn("Stomp.over did not receive a factory, auto reconnect will not work. Please see https://stomp-js.github.io/api-docs/latest/classes/Stomp.html#over"),e=()=>t),new m(e)}}y.WebSocketClass=null}]));
package/dist/umd/index.js CHANGED
@@ -18156,7 +18156,7 @@ function zipAll(project) {
18156
18156
  /* 224 */
18157
18157
  /***/ (function(module) {
18158
18158
 
18159
- module.exports = JSON.parse("{\"name\":\"uneeq-js\",\"version\":\"2.44.4\",\"description\":\"\",\"main\":\"dist/index.js\",\"types\":\"dist/src/index.d.ts\",\"scripts\":{\"start\":\"npx webpack -w\",\"test-local\":\"./node_modules/karma/bin/karma start karma.conf.js -logLevel=DEBUG\",\"test\":\"./node_modules/karma/bin/karma start --browsers ChromeHeadless --single-run\",\"test:windows\":\"karma start karma.conf.js\",\"build\":\"webpack --config webpack.config.prod.js && webpack --config webpack.config.umd.js\",\"lint\":\"./node_modules/tslint/bin/tslint -p tsconfig.json --fix\",\"docs\":\"./node_modules/typedoc/bin/typedoc --options\"},\"files\":[\"dist\",\"!dist/test\"],\"author\":\"\",\"license\":\"ISC\",\"dependencies\":{\"@stomp/stompjs\":\"^6.0.0\",\"@uehreka/seriously\":\"^1.0.1\",\"fast-text-encoding\":\"^1.0.0\",\"intrinsic-scale\":\"^3.0.4\",\"promjs\":\"^0.4.1\",\"rxjs\":\"^6.2.2\",\"rxjs-compat\":\"^6.3.2\",\"simple-peer\":\"9.11.0\",\"webrtc-adapter\":\"8.1.0\"},\"devDependencies\":{\"@types/jasmine\":\"^2.8.8\",\"@types/node\":\"^10.9.4\",\"fetch-mock\":\"7.7.3\",\"ignore-styles\":\"^5.0.1\",\"jasmine\":\"^3.2.0\",\"jasmine-class-mock\":\"^1.0.1\",\"jasmine-core\":\"^3.3.0\",\"karma\":\"^5.0.0\",\"karma-chrome-launcher\":\"^2.2.0\",\"karma-firefox-launcher\":\"^1.1.0\",\"karma-jasmine\":\"^2.0.1\",\"karma-jasmine-html-reporter\":\"^1.4.0\",\"karma-requirejs\":\"^1.1.0\",\"karma-safari-launcher\":\"^1.0.0\",\"karma-typescript\":\"^5.0.0\",\"karma-typescript-es6-transform\":\"^5.0.0\",\"nock\":\"^9.6.1\",\"requirejs\":\"^2.3.6\",\"ts-loader\":\"^5.0.0\",\"ts-node\":\"^7.0.1\",\"tslint\":\"^5.11.0\",\"tslint-no-focused-test\":\"^0.5.0\",\"typedoc\":\"^0.18.0\",\"typescript\":\"^3.9.7\",\"webpack\":\"^4.17.1\",\"webpack-cli\":\"^3.1.0\"}}");
18159
+ module.exports = JSON.parse("{\"name\":\"uneeq-js\",\"version\":\"2.44.6\",\"description\":\"\",\"main\":\"dist/index.js\",\"types\":\"dist/src/index.d.ts\",\"scripts\":{\"start\":\"npx webpack -w\",\"test-local\":\"npx karma start karma.conf.js -logLevel=DEBUG\",\"test\":\"npx karma start --browsers ChromeHeadless --single-run\",\"test:windows\":\"karma start karma.conf.js\",\"build\":\"webpack --config webpack.config.prod.js && webpack --config webpack.config.umd.js\",\"lint\":\"npx tslint -p tsconfig.json --fix\",\"docs\":\"npx typedoc --options\"},\"files\":[\"dist\",\"!dist/test\"],\"author\":\"\",\"license\":\"ISC\",\"dependencies\":{\"@stomp/stompjs\":\"^6.0.0\",\"@uehreka/seriously\":\"^1.0.1\",\"fast-text-encoding\":\"^1.0.0\",\"intrinsic-scale\":\"^3.0.4\",\"promjs\":\"^0.4.1\",\"rxjs\":\"^6.2.2\",\"rxjs-compat\":\"^6.3.2\",\"simple-peer\":\"9.11.0\",\"webrtc-adapter\":\"8.1.0\"},\"devDependencies\":{\"@types/jasmine\":\"^2.8.8\",\"@types/node\":\"^10.9.4\",\"fetch-mock\":\"7.7.3\",\"ignore-styles\":\"^5.0.1\",\"jasmine\":\"^3.2.0\",\"jasmine-class-mock\":\"^1.0.1\",\"jasmine-core\":\"^3.3.0\",\"karma\":\"^5.0.0\",\"karma-chrome-launcher\":\"^2.2.0\",\"karma-firefox-launcher\":\"^1.1.0\",\"karma-jasmine\":\"^2.0.1\",\"karma-jasmine-html-reporter\":\"^1.4.0\",\"karma-requirejs\":\"^1.1.0\",\"karma-safari-launcher\":\"^1.0.0\",\"karma-typescript\":\"^5.0.0\",\"karma-typescript-es6-transform\":\"^5.0.0\",\"nock\":\"^9.6.1\",\"requirejs\":\"^2.3.6\",\"ts-loader\":\"^5.0.0\",\"ts-node\":\"^7.0.1\",\"tslint\":\"^5.11.0\",\"tslint-no-focused-test\":\"^0.5.0\",\"typedoc\":\"^0.18.0\",\"typescript\":\"^3.9.7\",\"webpack\":\"^4.17.1\",\"webpack-cli\":\"^3.1.0\"}}");
18160
18160
 
18161
18161
  /***/ }),
18162
18162
  /* 225 */
@@ -51101,6 +51101,7 @@ class MessagingService {
51101
51101
  logger_1.logger.log('Disconnecting stomp client');
51102
51102
  try {
51103
51103
  this.subscriptions = {};
51104
+ this.options.autoReconnect = false; // turn off reconnection because it has been manually disconnected
51104
51105
  this.stompClient.deactivate();
51105
51106
  this.stompClient.forceDisconnect();
51106
51107
  this.state$.next(messaging_state_1.MessagingState.DISCONNECTED);
@@ -53434,6 +53435,7 @@ class StreamManager {
53434
53435
  const canvas = document.createElement('canvas');
53435
53436
  canvas.width = 40; // 40px canvas width
53436
53437
  canvas.height = 30; // 30px canvas height
53438
+ canvas.getContext('2d'); // get the canvas context before canvas.captureStream, needed for Firefox
53437
53439
  const canvasStream = canvas.captureStream(1); // use the canvas as a video stream at 1 fps
53438
53440
  return canvasStream.getVideoTracks()[0];
53439
53441
  }
package/package.json CHANGED
@@ -1,17 +1,17 @@
1
1
  {
2
2
  "name": "uneeq-js",
3
- "version": "2.44.4",
3
+ "version": "2.44.6",
4
4
  "description": "",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/src/index.d.ts",
7
7
  "scripts": {
8
8
  "start": "npx webpack -w",
9
- "test-local": "./node_modules/karma/bin/karma start karma.conf.js -logLevel=DEBUG",
10
- "test": "./node_modules/karma/bin/karma start --browsers ChromeHeadless --single-run",
9
+ "test-local": "npx karma start karma.conf.js -logLevel=DEBUG",
10
+ "test": "npx karma start --browsers ChromeHeadless --single-run",
11
11
  "test:windows": "karma start karma.conf.js",
12
12
  "build": "webpack --config webpack.config.prod.js && webpack --config webpack.config.umd.js",
13
- "lint": "./node_modules/tslint/bin/tslint -p tsconfig.json --fix",
14
- "docs": "./node_modules/typedoc/bin/typedoc --options"
13
+ "lint": "npx tslint -p tsconfig.json --fix",
14
+ "docs": "npx typedoc --options"
15
15
  },
16
16
  "files": [
17
17
  "dist",
package/readme.md CHANGED
@@ -8,6 +8,12 @@ https://docs.uneeq.io/build-your-own-experience
8
8
  To use uneeq-js with a typescript version < 3.8, 'skipLibCheck' must be set to true.
9
9
 
10
10
  ## Release Notes
11
+ #### 2.44.6
12
+ * Fixed an issue when ending a session that would cause newly created sessions to be ended shortly after.
13
+
14
+ #### 2.44.5
15
+ * Fixed issue preventing Firefox based sessions from starting
16
+
11
17
  #### 2.44.4
12
18
  * Updated voice activity mode to no longer request the users microphone when the session becomes live.
13
19