holostaff-widget 3.0.0-alpha.21 → 3.0.0-alpha.23
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/{BufferResource-BMTertZ1.js → BufferResource-C4_7WYjm.js} +2 -2
- package/dist/{BufferResource-BMTertZ1.js.map → BufferResource-C4_7WYjm.js.map} +1 -1
- package/dist/{CanvasRenderer-2nOUZyIX.js → CanvasRenderer-3x3b66kA.js} +3 -3
- package/dist/{CanvasRenderer-2nOUZyIX.js.map → CanvasRenderer-3x3b66kA.js.map} +1 -1
- package/dist/{Filter-C9quYwP8.js → Filter-BjzXdx91.js} +2 -2
- package/dist/{Filter-C9quYwP8.js.map → Filter-BjzXdx91.js.map} +1 -1
- package/dist/{RenderTargetSystem-CnkdQo8m.js → RenderTargetSystem-Bq1Lyvc6.js} +3 -3
- package/dist/{RenderTargetSystem-CnkdQo8m.js.map → RenderTargetSystem-Bq1Lyvc6.js.map} +1 -1
- package/dist/{WebGLRenderer-qDJexSYN.js → WebGLRenderer-BnMU8zq9.js} +4 -4
- package/dist/{WebGLRenderer-qDJexSYN.js.map → WebGLRenderer-BnMU8zq9.js.map} +1 -1
- package/dist/{WebGPURenderer-DbTkVbYN.js → WebGPURenderer-Cz0GaLUb.js} +4 -4
- package/dist/{WebGPURenderer-DbTkVbYN.js.map → WebGPURenderer-Cz0GaLUb.js.map} +1 -1
- package/dist/{browserAll-CPx8PdE0.js → browserAll-DB9tb1aJ.js} +3 -3
- package/dist/{browserAll-CPx8PdE0.js.map → browserAll-DB9tb1aJ.js.map} +1 -1
- package/dist/hs-widget.es.js +1 -1
- package/dist/hs-widget.umd.js +3 -3
- package/dist/hs-widget.umd.js.map +1 -1
- package/dist/{index-DTNiKN29.js → index-RtR241n6.js} +253 -253
- package/dist/{index-DTNiKN29.js.map → index-RtR241n6.js.map} +1 -1
- package/dist/{webworkerAll-D4zwlAW2.js → webworkerAll-MGrJla4b.js} +3 -3
- package/dist/{webworkerAll-D4zwlAW2.js.map → webworkerAll-MGrJla4b.js.map} +1 -1
- package/package.json +1 -1
package/dist/hs-widget.es.js
CHANGED
package/dist/hs-widget.umd.js
CHANGED
|
@@ -934,7 +934,7 @@ registerProcessor('pcm-buffer-processor', PcmBufferProcessor)
|
|
|
934
934
|
*
|
|
935
935
|
* @author Feross Aboukhadijeh <https://feross.org>
|
|
936
936
|
* @license MIT
|
|
937
|
-
*/var Ru;function hx(){return Ru||(Ru=1,(function(s){const e=lx(),t=cx(),i=typeof Symbol=="function"&&typeof Symbol.for=="function"?Symbol.for("nodejs.util.inspect.custom"):null;s.Buffer=a,s.SlowBuffer=v,s.INSPECT_MAX_BYTES=50;const r=2147483647;s.kMaxLength=r,a.TYPED_ARRAY_SUPPORT=n(),!a.TYPED_ARRAY_SUPPORT&&typeof console<"u"&&typeof console.error=="function"&&console.error("This browser lacks typed array (Uint8Array) support which is required by `buffer` v5.x. Use `buffer` v4.x if you require old browser support.");function n(){try{const b=new Uint8Array(1),p={foo:function(){return 42}};return Object.setPrototypeOf(p,Uint8Array.prototype),Object.setPrototypeOf(b,p),b.foo()===42}catch{return!1}}Object.defineProperty(a.prototype,"parent",{enumerable:!0,get:function(){if(a.isBuffer(this))return this.buffer}}),Object.defineProperty(a.prototype,"offset",{enumerable:!0,get:function(){if(a.isBuffer(this))return this.byteOffset}});function o(b){if(b>r)throw new RangeError('The value "'+b+'" is invalid for option "size"');const p=new Uint8Array(b);return Object.setPrototypeOf(p,a.prototype),p}function a(b,p,m){if(typeof b=="number"){if(typeof p=="string")throw new TypeError('The "string" argument must be of type string. Received type number');return u(b)}return l(b,p,m)}a.poolSize=8192;function l(b,p,m){if(typeof b=="string")return f(b,p);if(ArrayBuffer.isView(b))return g(b);if(b==null)throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof b);if(tt(b,ArrayBuffer)||b&&tt(b.buffer,ArrayBuffer)||typeof SharedArrayBuffer<"u"&&(tt(b,SharedArrayBuffer)||b&&tt(b.buffer,SharedArrayBuffer)))return _(b,p,m);if(typeof b=="number")throw new TypeError('The "value" argument must not be of type number. Received type number');const S=b.valueOf&&b.valueOf();if(S!=null&&S!==b)return a.from(S,p,m);const T=y(b);if(T)return T;if(typeof Symbol<"u"&&Symbol.toPrimitive!=null&&typeof b[Symbol.toPrimitive]=="function")return a.from(b[Symbol.toPrimitive]("string"),p,m);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof b)}a.from=function(b,p,m){return l(b,p,m)},Object.setPrototypeOf(a.prototype,Uint8Array.prototype),Object.setPrototypeOf(a,Uint8Array);function c(b){if(typeof b!="number")throw new TypeError('"size" argument must be of type number');if(b<0)throw new RangeError('The value "'+b+'" is invalid for option "size"')}function h(b,p,m){return c(b),b<=0?o(b):p!==void 0?typeof m=="string"?o(b).fill(p,m):o(b).fill(p):o(b)}a.alloc=function(b,p,m){return h(b,p,m)};function u(b){return c(b),o(b<0?0:x(b)|0)}a.allocUnsafe=function(b){return u(b)},a.allocUnsafeSlow=function(b){return u(b)};function f(b,p){if((typeof p!="string"||p==="")&&(p="utf8"),!a.isEncoding(p))throw new TypeError("Unknown encoding: "+p);const m=C(b,p)|0;let S=o(m);const T=S.write(b,p);return T!==m&&(S=S.slice(0,T)),S}function d(b){const p=b.length<0?0:x(b.length)|0,m=o(p);for(let S=0;S<p;S+=1)m[S]=b[S]&255;return m}function g(b){if(tt(b,Uint8Array)){const p=new Uint8Array(b);return _(p.buffer,p.byteOffset,p.byteLength)}return d(b)}function _(b,p,m){if(p<0||b.byteLength<p)throw new RangeError('"offset" is outside of buffer bounds');if(b.byteLength<p+(m||0))throw new RangeError('"length" is outside of buffer bounds');let S;return p===void 0&&m===void 0?S=new Uint8Array(b):m===void 0?S=new Uint8Array(b,p):S=new Uint8Array(b,p,m),Object.setPrototypeOf(S,a.prototype),S}function y(b){if(a.isBuffer(b)){const p=x(b.length)|0,m=o(p);return m.length===0||b.copy(m,0,0,p),m}if(b.length!==void 0)return typeof b.length!="number"||Ki(b.length)?o(0):d(b);if(b.type==="Buffer"&&Array.isArray(b.data))return d(b.data)}function x(b){if(b>=r)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+r.toString(16)+" bytes");return b|0}function v(b){return+b!=b&&(b=0),a.alloc(+b)}a.isBuffer=function(p){return p!=null&&p._isBuffer===!0&&p!==a.prototype},a.compare=function(p,m){if(tt(p,Uint8Array)&&(p=a.from(p,p.offset,p.byteLength)),tt(m,Uint8Array)&&(m=a.from(m,m.offset,m.byteLength)),!a.isBuffer(p)||!a.isBuffer(m))throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(p===m)return 0;let S=p.length,T=m.length;for(let M=0,P=Math.min(S,T);M<P;++M)if(p[M]!==m[M]){S=p[M],T=m[M];break}return S<T?-1:T<S?1:0},a.isEncoding=function(p){switch(String(p).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"latin1":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}},a.concat=function(p,m){if(!Array.isArray(p))throw new TypeError('"list" argument must be an Array of Buffers');if(p.length===0)return a.alloc(0);let S;if(m===void 0)for(m=0,S=0;S<p.length;++S)m+=p[S].length;const T=a.allocUnsafe(m);let M=0;for(S=0;S<p.length;++S){let P=p[S];if(tt(P,Uint8Array))M+P.length>T.length?(a.isBuffer(P)||(P=a.from(P)),P.copy(T,M)):Uint8Array.prototype.set.call(T,P,M);else if(a.isBuffer(P))P.copy(T,M);else throw new TypeError('"list" argument must be an Array of Buffers');M+=P.length}return T};function C(b,p){if(a.isBuffer(b))return b.length;if(ArrayBuffer.isView(b)||tt(b,ArrayBuffer))return b.byteLength;if(typeof b!="string")throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof b);const m=b.length,S=arguments.length>2&&arguments[2]===!0;if(!S&&m===0)return 0;let T=!1;for(;;)switch(p){case"ascii":case"latin1":case"binary":return m;case"utf8":case"utf-8":return St(b).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return m*2;case"hex":return m>>>1;case"base64":return Ft(b).length;default:if(T)return S?-1:St(b).length;p=(""+p).toLowerCase(),T=!0}}a.byteLength=C;function E(b,p,m){let S=!1;if((p===void 0||p<0)&&(p=0),p>this.length||((m===void 0||m>this.length)&&(m=this.length),m<=0)||(m>>>=0,p>>>=0,m<=p))return"";for(b||(b="utf8");;)switch(b){case"hex":return N(this,p,m);case"utf8":case"utf-8":return W(this,p,m);case"ascii":return G(this,p,m);case"latin1":case"binary":return X(this,p,m);case"base64":return U(this,p,m);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return V(this,p,m);default:if(S)throw new TypeError("Unknown encoding: "+b);b=(b+"").toLowerCase(),S=!0}}a.prototype._isBuffer=!0;function A(b,p,m){const S=b[p];b[p]=b[m],b[m]=S}a.prototype.swap16=function(){const p=this.length;if(p%2!==0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(let m=0;m<p;m+=2)A(this,m,m+1);return this},a.prototype.swap32=function(){const p=this.length;if(p%4!==0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(let m=0;m<p;m+=4)A(this,m,m+3),A(this,m+1,m+2);return this},a.prototype.swap64=function(){const p=this.length;if(p%8!==0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(let m=0;m<p;m+=8)A(this,m,m+7),A(this,m+1,m+6),A(this,m+2,m+5),A(this,m+3,m+4);return this},a.prototype.toString=function(){const p=this.length;return p===0?"":arguments.length===0?W(this,0,p):E.apply(this,arguments)},a.prototype.toLocaleString=a.prototype.toString,a.prototype.equals=function(p){if(!a.isBuffer(p))throw new TypeError("Argument must be a Buffer");return this===p?!0:a.compare(this,p)===0},a.prototype.inspect=function(){let p="";const m=s.INSPECT_MAX_BYTES;return p=this.toString("hex",0,m).replace(/(.{2})/g,"$1 ").trim(),this.length>m&&(p+=" ... "),"<Buffer "+p+">"},i&&(a.prototype[i]=a.prototype.inspect),a.prototype.compare=function(p,m,S,T,M){if(tt(p,Uint8Array)&&(p=a.from(p,p.offset,p.byteLength)),!a.isBuffer(p))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof p);if(m===void 0&&(m=0),S===void 0&&(S=p?p.length:0),T===void 0&&(T=0),M===void 0&&(M=this.length),m<0||S>p.length||T<0||M>this.length)throw new RangeError("out of range index");if(T>=M&&m>=S)return 0;if(T>=M)return-1;if(m>=S)return 1;if(m>>>=0,S>>>=0,T>>>=0,M>>>=0,this===p)return 0;let P=M-T,re=S-m;const Pe=Math.min(P,re),we=this.slice(T,M),ke=p.slice(m,S);for(let Se=0;Se<Pe;++Se)if(we[Se]!==ke[Se]){P=we[Se],re=ke[Se];break}return P<re?-1:re<P?1:0};function w(b,p,m,S,T){if(b.length===0)return-1;if(typeof m=="string"?(S=m,m=0):m>2147483647?m=2147483647:m<-2147483648&&(m=-2147483648),m=+m,Ki(m)&&(m=T?0:b.length-1),m<0&&(m=b.length+m),m>=b.length){if(T)return-1;m=b.length-1}else if(m<0)if(T)m=0;else return-1;if(typeof p=="string"&&(p=a.from(p,S)),a.isBuffer(p))return p.length===0?-1:R(b,p,m,S,T);if(typeof p=="number")return p=p&255,typeof Uint8Array.prototype.indexOf=="function"?T?Uint8Array.prototype.indexOf.call(b,p,m):Uint8Array.prototype.lastIndexOf.call(b,p,m):R(b,[p],m,S,T);throw new TypeError("val must be string, number or Buffer")}function R(b,p,m,S,T){let M=1,P=b.length,re=p.length;if(S!==void 0&&(S=String(S).toLowerCase(),S==="ucs2"||S==="ucs-2"||S==="utf16le"||S==="utf-16le")){if(b.length<2||p.length<2)return-1;M=2,P/=2,re/=2,m/=2}function Pe(ke,Se){return M===1?ke[Se]:ke.readUInt16BE(Se*M)}let we;if(T){let ke=-1;for(we=m;we<P;we++)if(Pe(b,we)===Pe(p,ke===-1?0:we-ke)){if(ke===-1&&(ke=we),we-ke+1===re)return ke*M}else ke!==-1&&(we-=we-ke),ke=-1}else for(m+re>P&&(m=P-re),we=m;we>=0;we--){let ke=!0;for(let Se=0;Se<re;Se++)if(Pe(b,we+Se)!==Pe(p,Se)){ke=!1;break}if(ke)return we}return-1}a.prototype.includes=function(p,m,S){return this.indexOf(p,m,S)!==-1},a.prototype.indexOf=function(p,m,S){return w(this,p,m,S,!0)},a.prototype.lastIndexOf=function(p,m,S){return w(this,p,m,S,!1)};function D(b,p,m,S){m=Number(m)||0;const T=b.length-m;S?(S=Number(S),S>T&&(S=T)):S=T;const M=p.length;S>M/2&&(S=M/2);let P;for(P=0;P<S;++P){const re=parseInt(p.substr(P*2,2),16);if(Ki(re))return P;b[m+P]=re}return P}function B(b,p,m,S){return ft(St(p,b.length-m),b,m,S)}function k(b,p,m,S){return ft(fi(p),b,m,S)}function O(b,p,m,S){return ft(Ft(p),b,m,S)}function L(b,p,m,S){return ft(Yi(p,b.length-m),b,m,S)}a.prototype.write=function(p,m,S,T){if(m===void 0)T="utf8",S=this.length,m=0;else if(S===void 0&&typeof m=="string")T=m,S=this.length,m=0;else if(isFinite(m))m=m>>>0,isFinite(S)?(S=S>>>0,T===void 0&&(T="utf8")):(T=S,S=void 0);else throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");const M=this.length-m;if((S===void 0||S>M)&&(S=M),p.length>0&&(S<0||m<0)||m>this.length)throw new RangeError("Attempt to write outside buffer bounds");T||(T="utf8");let P=!1;for(;;)switch(T){case"hex":return D(this,p,m,S);case"utf8":case"utf-8":return B(this,p,m,S);case"ascii":case"latin1":case"binary":return k(this,p,m,S);case"base64":return O(this,p,m,S);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return L(this,p,m,S);default:if(P)throw new TypeError("Unknown encoding: "+T);T=(""+T).toLowerCase(),P=!0}},a.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};function U(b,p,m){return p===0&&m===b.length?e.fromByteArray(b):e.fromByteArray(b.slice(p,m))}function W(b,p,m){m=Math.min(b.length,m);const S=[];let T=p;for(;T<m;){const M=b[T];let P=null,re=M>239?4:M>223?3:M>191?2:1;if(T+re<=m){let Pe,we,ke,Se;switch(re){case 1:M<128&&(P=M);break;case 2:Pe=b[T+1],(Pe&192)===128&&(Se=(M&31)<<6|Pe&63,Se>127&&(P=Se));break;case 3:Pe=b[T+1],we=b[T+2],(Pe&192)===128&&(we&192)===128&&(Se=(M&15)<<12|(Pe&63)<<6|we&63,Se>2047&&(Se<55296||Se>57343)&&(P=Se));break;case 4:Pe=b[T+1],we=b[T+2],ke=b[T+3],(Pe&192)===128&&(we&192)===128&&(ke&192)===128&&(Se=(M&15)<<18|(Pe&63)<<12|(we&63)<<6|ke&63,Se>65535&&Se<1114112&&(P=Se))}}P===null?(P=65533,re=1):P>65535&&(P-=65536,S.push(P>>>10&1023|55296),P=56320|P&1023),S.push(P),T+=re}return F(S)}const te=4096;function F(b){const p=b.length;if(p<=te)return String.fromCharCode.apply(String,b);let m="",S=0;for(;S<p;)m+=String.fromCharCode.apply(String,b.slice(S,S+=te));return m}function G(b,p,m){let S="";m=Math.min(b.length,m);for(let T=p;T<m;++T)S+=String.fromCharCode(b[T]&127);return S}function X(b,p,m){let S="";m=Math.min(b.length,m);for(let T=p;T<m;++T)S+=String.fromCharCode(b[T]);return S}function N(b,p,m){const S=b.length;(!p||p<0)&&(p=0),(!m||m<0||m>S)&&(m=S);let T="";for(let M=p;M<m;++M)T+=wr[b[M]];return T}function V(b,p,m){const S=b.slice(p,m);let T="";for(let M=0;M<S.length-1;M+=2)T+=String.fromCharCode(S[M]+S[M+1]*256);return T}a.prototype.slice=function(p,m){const S=this.length;p=~~p,m=m===void 0?S:~~m,p<0?(p+=S,p<0&&(p=0)):p>S&&(p=S),m<0?(m+=S,m<0&&(m=0)):m>S&&(m=S),m<p&&(m=p);const T=this.subarray(p,m);return Object.setPrototypeOf(T,a.prototype),T};function K(b,p,m){if(b%1!==0||b<0)throw new RangeError("offset is not uint");if(b+p>m)throw new RangeError("Trying to access beyond buffer length")}a.prototype.readUintLE=a.prototype.readUIntLE=function(p,m,S){p=p>>>0,m=m>>>0,S||K(p,m,this.length);let T=this[p],M=1,P=0;for(;++P<m&&(M*=256);)T+=this[p+P]*M;return T},a.prototype.readUintBE=a.prototype.readUIntBE=function(p,m,S){p=p>>>0,m=m>>>0,S||K(p,m,this.length);let T=this[p+--m],M=1;for(;m>0&&(M*=256);)T+=this[p+--m]*M;return T},a.prototype.readUint8=a.prototype.readUInt8=function(p,m){return p=p>>>0,m||K(p,1,this.length),this[p]},a.prototype.readUint16LE=a.prototype.readUInt16LE=function(p,m){return p=p>>>0,m||K(p,2,this.length),this[p]|this[p+1]<<8},a.prototype.readUint16BE=a.prototype.readUInt16BE=function(p,m){return p=p>>>0,m||K(p,2,this.length),this[p]<<8|this[p+1]},a.prototype.readUint32LE=a.prototype.readUInt32LE=function(p,m){return p=p>>>0,m||K(p,4,this.length),(this[p]|this[p+1]<<8|this[p+2]<<16)+this[p+3]*16777216},a.prototype.readUint32BE=a.prototype.readUInt32BE=function(p,m){return p=p>>>0,m||K(p,4,this.length),this[p]*16777216+(this[p+1]<<16|this[p+2]<<8|this[p+3])},a.prototype.readBigUInt64LE=pt(function(p){p=p>>>0,Re(p,"offset");const m=this[p],S=this[p+7];(m===void 0||S===void 0)&&pe(p,this.length-8);const T=m+this[++p]*2**8+this[++p]*2**16+this[++p]*2**24,M=this[++p]+this[++p]*2**8+this[++p]*2**16+S*2**24;return BigInt(T)+(BigInt(M)<<BigInt(32))}),a.prototype.readBigUInt64BE=pt(function(p){p=p>>>0,Re(p,"offset");const m=this[p],S=this[p+7];(m===void 0||S===void 0)&&pe(p,this.length-8);const T=m*2**24+this[++p]*2**16+this[++p]*2**8+this[++p],M=this[++p]*2**24+this[++p]*2**16+this[++p]*2**8+S;return(BigInt(T)<<BigInt(32))+BigInt(M)}),a.prototype.readIntLE=function(p,m,S){p=p>>>0,m=m>>>0,S||K(p,m,this.length);let T=this[p],M=1,P=0;for(;++P<m&&(M*=256);)T+=this[p+P]*M;return M*=128,T>=M&&(T-=Math.pow(2,8*m)),T},a.prototype.readIntBE=function(p,m,S){p=p>>>0,m=m>>>0,S||K(p,m,this.length);let T=m,M=1,P=this[p+--T];for(;T>0&&(M*=256);)P+=this[p+--T]*M;return M*=128,P>=M&&(P-=Math.pow(2,8*m)),P},a.prototype.readInt8=function(p,m){return p=p>>>0,m||K(p,1,this.length),this[p]&128?(255-this[p]+1)*-1:this[p]},a.prototype.readInt16LE=function(p,m){p=p>>>0,m||K(p,2,this.length);const S=this[p]|this[p+1]<<8;return S&32768?S|4294901760:S},a.prototype.readInt16BE=function(p,m){p=p>>>0,m||K(p,2,this.length);const S=this[p+1]|this[p]<<8;return S&32768?S|4294901760:S},a.prototype.readInt32LE=function(p,m){return p=p>>>0,m||K(p,4,this.length),this[p]|this[p+1]<<8|this[p+2]<<16|this[p+3]<<24},a.prototype.readInt32BE=function(p,m){return p=p>>>0,m||K(p,4,this.length),this[p]<<24|this[p+1]<<16|this[p+2]<<8|this[p+3]},a.prototype.readBigInt64LE=pt(function(p){p=p>>>0,Re(p,"offset");const m=this[p],S=this[p+7];(m===void 0||S===void 0)&&pe(p,this.length-8);const T=this[p+4]+this[p+5]*2**8+this[p+6]*2**16+(S<<24);return(BigInt(T)<<BigInt(32))+BigInt(m+this[++p]*2**8+this[++p]*2**16+this[++p]*2**24)}),a.prototype.readBigInt64BE=pt(function(p){p=p>>>0,Re(p,"offset");const m=this[p],S=this[p+7];(m===void 0||S===void 0)&&pe(p,this.length-8);const T=(m<<24)+this[++p]*2**16+this[++p]*2**8+this[++p];return(BigInt(T)<<BigInt(32))+BigInt(this[++p]*2**24+this[++p]*2**16+this[++p]*2**8+S)}),a.prototype.readFloatLE=function(p,m){return p=p>>>0,m||K(p,4,this.length),t.read(this,p,!0,23,4)},a.prototype.readFloatBE=function(p,m){return p=p>>>0,m||K(p,4,this.length),t.read(this,p,!1,23,4)},a.prototype.readDoubleLE=function(p,m){return p=p>>>0,m||K(p,8,this.length),t.read(this,p,!0,52,8)},a.prototype.readDoubleBE=function(p,m){return p=p>>>0,m||K(p,8,this.length),t.read(this,p,!1,52,8)};function H(b,p,m,S,T,M){if(!a.isBuffer(b))throw new TypeError('"buffer" argument must be a Buffer instance');if(p>T||p<M)throw new RangeError('"value" argument is out of bounds');if(m+S>b.length)throw new RangeError("Index out of range")}a.prototype.writeUintLE=a.prototype.writeUIntLE=function(p,m,S,T){if(p=+p,m=m>>>0,S=S>>>0,!T){const re=Math.pow(2,8*S)-1;H(this,p,m,S,re,0)}let M=1,P=0;for(this[m]=p&255;++P<S&&(M*=256);)this[m+P]=p/M&255;return m+S},a.prototype.writeUintBE=a.prototype.writeUIntBE=function(p,m,S,T){if(p=+p,m=m>>>0,S=S>>>0,!T){const re=Math.pow(2,8*S)-1;H(this,p,m,S,re,0)}let M=S-1,P=1;for(this[m+M]=p&255;--M>=0&&(P*=256);)this[m+M]=p/P&255;return m+S},a.prototype.writeUint8=a.prototype.writeUInt8=function(p,m,S){return p=+p,m=m>>>0,S||H(this,p,m,1,255,0),this[m]=p&255,m+1},a.prototype.writeUint16LE=a.prototype.writeUInt16LE=function(p,m,S){return p=+p,m=m>>>0,S||H(this,p,m,2,65535,0),this[m]=p&255,this[m+1]=p>>>8,m+2},a.prototype.writeUint16BE=a.prototype.writeUInt16BE=function(p,m,S){return p=+p,m=m>>>0,S||H(this,p,m,2,65535,0),this[m]=p>>>8,this[m+1]=p&255,m+2},a.prototype.writeUint32LE=a.prototype.writeUInt32LE=function(p,m,S){return p=+p,m=m>>>0,S||H(this,p,m,4,4294967295,0),this[m+3]=p>>>24,this[m+2]=p>>>16,this[m+1]=p>>>8,this[m]=p&255,m+4},a.prototype.writeUint32BE=a.prototype.writeUInt32BE=function(p,m,S){return p=+p,m=m>>>0,S||H(this,p,m,4,4294967295,0),this[m]=p>>>24,this[m+1]=p>>>16,this[m+2]=p>>>8,this[m+3]=p&255,m+4};function $(b,p,m,S,T){le(p,S,T,b,m,7);let M=Number(p&BigInt(4294967295));b[m++]=M,M=M>>8,b[m++]=M,M=M>>8,b[m++]=M,M=M>>8,b[m++]=M;let P=Number(p>>BigInt(32)&BigInt(4294967295));return b[m++]=P,P=P>>8,b[m++]=P,P=P>>8,b[m++]=P,P=P>>8,b[m++]=P,m}function se(b,p,m,S,T){le(p,S,T,b,m,7);let M=Number(p&BigInt(4294967295));b[m+7]=M,M=M>>8,b[m+6]=M,M=M>>8,b[m+5]=M,M=M>>8,b[m+4]=M;let P=Number(p>>BigInt(32)&BigInt(4294967295));return b[m+3]=P,P=P>>8,b[m+2]=P,P=P>>8,b[m+1]=P,P=P>>8,b[m]=P,m+8}a.prototype.writeBigUInt64LE=pt(function(p,m=0){return $(this,p,m,BigInt(0),BigInt("0xffffffffffffffff"))}),a.prototype.writeBigUInt64BE=pt(function(p,m=0){return se(this,p,m,BigInt(0),BigInt("0xffffffffffffffff"))}),a.prototype.writeIntLE=function(p,m,S,T){if(p=+p,m=m>>>0,!T){const Pe=Math.pow(2,8*S-1);H(this,p,m,S,Pe-1,-Pe)}let M=0,P=1,re=0;for(this[m]=p&255;++M<S&&(P*=256);)p<0&&re===0&&this[m+M-1]!==0&&(re=1),this[m+M]=(p/P>>0)-re&255;return m+S},a.prototype.writeIntBE=function(p,m,S,T){if(p=+p,m=m>>>0,!T){const Pe=Math.pow(2,8*S-1);H(this,p,m,S,Pe-1,-Pe)}let M=S-1,P=1,re=0;for(this[m+M]=p&255;--M>=0&&(P*=256);)p<0&&re===0&&this[m+M+1]!==0&&(re=1),this[m+M]=(p/P>>0)-re&255;return m+S},a.prototype.writeInt8=function(p,m,S){return p=+p,m=m>>>0,S||H(this,p,m,1,127,-128),p<0&&(p=255+p+1),this[m]=p&255,m+1},a.prototype.writeInt16LE=function(p,m,S){return p=+p,m=m>>>0,S||H(this,p,m,2,32767,-32768),this[m]=p&255,this[m+1]=p>>>8,m+2},a.prototype.writeInt16BE=function(p,m,S){return p=+p,m=m>>>0,S||H(this,p,m,2,32767,-32768),this[m]=p>>>8,this[m+1]=p&255,m+2},a.prototype.writeInt32LE=function(p,m,S){return p=+p,m=m>>>0,S||H(this,p,m,4,2147483647,-2147483648),this[m]=p&255,this[m+1]=p>>>8,this[m+2]=p>>>16,this[m+3]=p>>>24,m+4},a.prototype.writeInt32BE=function(p,m,S){return p=+p,m=m>>>0,S||H(this,p,m,4,2147483647,-2147483648),p<0&&(p=4294967295+p+1),this[m]=p>>>24,this[m+1]=p>>>16,this[m+2]=p>>>8,this[m+3]=p&255,m+4},a.prototype.writeBigInt64LE=pt(function(p,m=0){return $(this,p,m,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))}),a.prototype.writeBigInt64BE=pt(function(p,m=0){return se(this,p,m,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))});function ue(b,p,m,S,T,M){if(m+S>b.length)throw new RangeError("Index out of range");if(m<0)throw new RangeError("Index out of range")}function z(b,p,m,S,T){return p=+p,m=m>>>0,T||ue(b,p,m,4),t.write(b,p,m,S,23,4),m+4}a.prototype.writeFloatLE=function(p,m,S){return z(this,p,m,!0,S)},a.prototype.writeFloatBE=function(p,m,S){return z(this,p,m,!1,S)};function Q(b,p,m,S,T){return p=+p,m=m>>>0,T||ue(b,p,m,8),t.write(b,p,m,S,52,8),m+8}a.prototype.writeDoubleLE=function(p,m,S){return Q(this,p,m,!0,S)},a.prototype.writeDoubleBE=function(p,m,S){return Q(this,p,m,!1,S)},a.prototype.copy=function(p,m,S,T){if(!a.isBuffer(p))throw new TypeError("argument should be a Buffer");if(S||(S=0),!T&&T!==0&&(T=this.length),m>=p.length&&(m=p.length),m||(m=0),T>0&&T<S&&(T=S),T===S||p.length===0||this.length===0)return 0;if(m<0)throw new RangeError("targetStart out of bounds");if(S<0||S>=this.length)throw new RangeError("Index out of range");if(T<0)throw new RangeError("sourceEnd out of bounds");T>this.length&&(T=this.length),p.length-m<T-S&&(T=p.length-m+S);const M=T-S;return this===p&&typeof Uint8Array.prototype.copyWithin=="function"?this.copyWithin(m,S,T):Uint8Array.prototype.set.call(p,this.subarray(S,T),m),M},a.prototype.fill=function(p,m,S,T){if(typeof p=="string"){if(typeof m=="string"?(T=m,m=0,S=this.length):typeof S=="string"&&(T=S,S=this.length),T!==void 0&&typeof T!="string")throw new TypeError("encoding must be a string");if(typeof T=="string"&&!a.isEncoding(T))throw new TypeError("Unknown encoding: "+T);if(p.length===1){const P=p.charCodeAt(0);(T==="utf8"&&P<128||T==="latin1")&&(p=P)}}else typeof p=="number"?p=p&255:typeof p=="boolean"&&(p=Number(p));if(m<0||this.length<m||this.length<S)throw new RangeError("Out of range index");if(S<=m)return this;m=m>>>0,S=S===void 0?this.length:S>>>0,p||(p=0);let M;if(typeof p=="number")for(M=m;M<S;++M)this[M]=p;else{const P=a.isBuffer(p)?p:a.from(p,T),re=P.length;if(re===0)throw new TypeError('The value "'+p+'" is invalid for argument "value"');for(M=0;M<S-m;++M)this[M+m]=P[M%re]}return this};const ae={};function j(b,p,m){ae[b]=class extends m{constructor(){super(),Object.defineProperty(this,"message",{value:p.apply(this,arguments),writable:!0,configurable:!0}),this.name=`${this.name} [${b}]`,this.stack,delete this.name}get code(){return b}set code(T){Object.defineProperty(this,"code",{configurable:!0,enumerable:!0,value:T,writable:!0})}toString(){return`${this.name} [${b}]: ${this.message}`}}}j("ERR_BUFFER_OUT_OF_BOUNDS",function(b){return b?`${b} is outside of buffer bounds`:"Attempt to access memory outside buffer bounds"},RangeError),j("ERR_INVALID_ARG_TYPE",function(b,p){return`The "${b}" argument must be of type number. Received type ${typeof p}`},TypeError),j("ERR_OUT_OF_RANGE",function(b,p,m){let S=`The value of "${b}" is out of range.`,T=m;return Number.isInteger(m)&&Math.abs(m)>2**32?T=_e(String(m)):typeof m=="bigint"&&(T=String(m),(m>BigInt(2)**BigInt(32)||m<-(BigInt(2)**BigInt(32)))&&(T=_e(T)),T+="n"),S+=` It must be ${p}. Received ${T}`,S},RangeError);function _e(b){let p="",m=b.length;const S=b[0]==="-"?1:0;for(;m>=S+4;m-=3)p=`_${b.slice(m-3,m)}${p}`;return`${b.slice(0,m)}${p}`}function ee(b,p,m){Re(p,"offset"),(b[p]===void 0||b[p+m]===void 0)&&pe(p,b.length-(m+1))}function le(b,p,m,S,T,M){if(b>m||b<p){const P=typeof p=="bigint"?"n":"";let re;throw p===0||p===BigInt(0)?re=`>= 0${P} and < 2${P} ** ${(M+1)*8}${P}`:re=`>= -(2${P} ** ${(M+1)*8-1}${P}) and < 2 ** ${(M+1)*8-1}${P}`,new ae.ERR_OUT_OF_RANGE("value",re,b)}ee(S,T,M)}function Re(b,p){if(typeof b!="number")throw new ae.ERR_INVALID_ARG_TYPE(p,"number",b)}function pe(b,p,m){throw Math.floor(b)!==b?(Re(b,m),new ae.ERR_OUT_OF_RANGE("offset","an integer",b)):p<0?new ae.ERR_BUFFER_OUT_OF_BOUNDS:new ae.ERR_OUT_OF_RANGE("offset",`>= 0 and <= ${p}`,b)}const Ve=/[^+/0-9A-Za-z-_]/g;function Jt(b){if(b=b.split("=")[0],b=b.trim().replace(Ve,""),b.length<2)return"";for(;b.length%4!==0;)b=b+"=";return b}function St(b,p){p=p||1/0;let m;const S=b.length;let T=null;const M=[];for(let P=0;P<S;++P){if(m=b.charCodeAt(P),m>55295&&m<57344){if(!T){if(m>56319){(p-=3)>-1&&M.push(239,191,189);continue}else if(P+1===S){(p-=3)>-1&&M.push(239,191,189);continue}T=m;continue}if(m<56320){(p-=3)>-1&&M.push(239,191,189),T=m;continue}m=(T-55296<<10|m-56320)+65536}else T&&(p-=3)>-1&&M.push(239,191,189);if(T=null,m<128){if((p-=1)<0)break;M.push(m)}else if(m<2048){if((p-=2)<0)break;M.push(m>>6|192,m&63|128)}else if(m<65536){if((p-=3)<0)break;M.push(m>>12|224,m>>6&63|128,m&63|128)}else if(m<1114112){if((p-=4)<0)break;M.push(m>>18|240,m>>12&63|128,m>>6&63|128,m&63|128)}else throw new Error("Invalid code point")}return M}function fi(b){const p=[];for(let m=0;m<b.length;++m)p.push(b.charCodeAt(m)&255);return p}function Yi(b,p){let m,S,T;const M=[];for(let P=0;P<b.length&&!((p-=2)<0);++P)m=b.charCodeAt(P),S=m>>8,T=m%256,M.push(T),M.push(S);return M}function Ft(b){return e.toByteArray(Jt(b))}function ft(b,p,m,S){let T;for(T=0;T<S&&!(T+m>=p.length||T>=b.length);++T)p[T+m]=b[T];return T}function tt(b,p){return b instanceof p||b!=null&&b.constructor!=null&&b.constructor.name!=null&&b.constructor.name===p.name}function Ki(b){return b!==b}const wr=(function(){const b="0123456789abcdef",p=new Array(256);for(let m=0;m<16;++m){const S=m*16;for(let T=0;T<16;++T)p[S+T]=b[m]+b[T]}return p})();function pt(b){return typeof BigInt>"u"?Ir:b}function Ir(){throw new Error("BigInt not supported")}})(wo)),wo}var ux=hx();const dx="https://api.anam.ai",fx="/v1",Mu={client:"js-sdk",version:"4.12.0"};var px=function(s,e,t,i){function r(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(h){try{c(i.next(h))}catch(u){o(u)}}function l(h){try{c(i.throw(h))}catch(u){o(u)}}function c(h){h.done?n(h.value):r(h.value).then(a,l)}c((i=i.apply(s,e||[])).next())})};const Pu="https://api.anam.ai",Io="/v1";var Nt;(function(s){s.CLIENT_METRIC_MEASUREMENT_ERROR="client_error",s.CLIENT_METRIC_MEASUREMENT_CONNECTION_CLOSED="client_connection_closed",s.CLIENT_METRIC_MEASUREMENT_CONNECTION_ESTABLISHED="client_connection_established",s.CLIENT_METRIC_MEASUREMENT_SESSION_ATTEMPT="client_session_attempt",s.CLIENT_METRIC_MEASUREMENT_SESSION_SUCCESS="client_session_success"})(Nt||(Nt={}));let Ao=Pu,ku=Io,jt,Bu=!1;const mx=(s,e=Io)=>{Ao=s,ku=e},gx=s=>{jt=s},_x=s=>{Bu=s};let Xt={sessionId:null,organizationId:null,attemptCorrelationId:null};const Li=s=>{Xt=Object.assign(Object.assign({},Xt),s)},ui=(s,e,t)=>px(void 0,void 0,void 0,function*(){if(!Bu)try{const i=Object.assign(Object.assign({},Mu),t);Xt.sessionId&&(i.sessionId=Xt.sessionId),Xt.organizationId&&(i.organizationId=Xt.organizationId),Xt.attemptCorrelationId&&(i.attemptCorrelationId=Xt.attemptCorrelationId);const r=`${ku}/metrics/client`;let n,o={"Content-Type":"application/json"};jt!=null&&jt.enabled&&(jt!=null&&jt.baseUrl)?(n=`${jt.baseUrl}${r}`,o["X-Anam-Target-Url"]=`${Ao}${r}`):n=`${Ao}${r}`,yield fetch(n,{method:"POST",headers:o,body:JSON.stringify({name:s,value:e,tags:i})})}catch(i){console.error("Failed to send error metric:",i)}}),yx=(s,e="console")=>{var t,i,r;const n={};s.forEach(u=>{n[u.type]||(n[u.type]=[]),n[u.type].push(u)});const o={issues:[]},a=((t=n["inbound-rtp"])===null||t===void 0?void 0:t.filter(u=>u.kind==="video"))||[];a.length>0&&(o.personaVideoStream=[],a.forEach(u=>{var f,d,g,_,y;const x={framesReceived:(f=u.framesReceived)!==null&&f!==void 0?f:"unknown",framesDropped:(d=u.framesDropped)!==null&&d!==void 0?d:"unknown",framesPerSecond:(g=u.framesPerSecond)!==null&&g!==void 0?g:"unknown",packetsReceived:(_=u.packetsReceived)!==null&&_!==void 0?_:"unknown",packetsLost:(y=u.packetsLost)!==null&&y!==void 0?y:"unknown",resolution:u.frameWidth&&u.frameHeight?`${u.frameWidth}x${u.frameHeight}`:void 0,jitter:u.jitter!==void 0?u.jitter:void 0};o.personaVideoStream.push(x)}));const l=((i=n["inbound-rtp"])===null||i===void 0?void 0:i.filter(u=>u.kind==="audio"))||[];l.length>0&&(o.personaAudioStream=[],l.forEach(u=>{var f,d,g;const _={packetsReceived:(f=u.packetsReceived)!==null&&f!==void 0?f:"unknown",packetsLost:(d=u.packetsLost)!==null&&d!==void 0?d:"unknown",audioLevel:(g=u.audioLevel)!==null&&g!==void 0?g:"unknown",jitter:u.jitter!==void 0?u.jitter:void 0,totalAudioEnergy:u.totalAudioEnergy!==void 0?u.totalAudioEnergy:void 0};o.personaAudioStream.push(_)}));const c=((r=n["outbound-rtp"])===null||r===void 0?void 0:r.filter(u=>u.kind==="audio"))||[];c.length>0&&(o.userAudioInput=[],c.forEach(u=>{var f,d;const g={packetsSent:(f=u.packetsSent)!==null&&f!==void 0?f:"unknown",retransmittedPackets:(d=u.retransmittedPacketsSent)!==null&&d!==void 0?d:void 0,avgPacketSendDelay:u.totalPacketSendDelay!==void 0?u.totalPacketSendDelay/(u.packetsSent||1)*1e3:void 0};o.userAudioInput.push(g)})),n.codec&&(o.codecs=[],n.codec.forEach(u=>{const f={status:u.payloadType?"Active":"Available",mimeType:u.mimeType||"Unknown",payloadType:u.payloadType||"N/A",clockRate:u.clockRate||void 0,channels:u.channels||void 0};o.codecs.push(f)})),n.transport&&(o.transportLayer=[],n.transport.forEach(u=>{const f={dtlsState:u.dtlsState||"unknown",iceState:u.iceState||"unknown",bytesSent:u.bytesSent||void 0,bytesReceived:u.bytesReceived||void 0};o.transportLayer.push(f)}));const h=[];if(a.forEach(u=>{typeof u.framesDropped=="number"&&u.framesDropped>0&&h.push(`Video: ${u.framesDropped} frames dropped`),typeof u.packetsLost=="number"&&u.packetsLost>0&&h.push(`Video: ${u.packetsLost} packets lost`),typeof u.framesPerSecond=="number"&&u.framesPerSecond<23&&h.push(`Video: Low frame rate (${u.framesPerSecond} fps)`)}),l.forEach(u=>{typeof u.packetsLost=="number"&&u.packetsLost>0&&h.push(`Audio: ${u.packetsLost} packets lost`),typeof u.jitter=="number"&&u.jitter>.1&&h.push(`Audio: High jitter (${(u.jitter*1e3).toFixed(1)}ms)`)}),o.issues=h,e==="json")return o;console.group("📊 WebRTC Session Statistics Report"),o.personaVideoStream&&o.personaVideoStream.length>0&&(console.group("📹 Persona Video Stream (Inbound)"),o.personaVideoStream.forEach(u=>{console.log(`Frames Received: ${u.framesReceived}`),console.log(`Frames Dropped: ${u.framesDropped}`),console.log(`Frames Per Second: ${u.framesPerSecond}`),console.log(`Packets Received: ${typeof u.packetsReceived=="number"?u.packetsReceived.toLocaleString():u.packetsReceived}`),console.log(`Packets Lost: ${u.packetsLost}`),u.resolution&&console.log(`Resolution: ${u.resolution}`),u.jitter!==void 0&&console.log(`Jitter: ${u.jitter.toFixed(5)}ms`)}),console.groupEnd()),o.personaAudioStream&&o.personaAudioStream.length>0&&(console.group("🔊 Persona Audio Stream (Inbound)"),o.personaAudioStream.forEach(u=>{console.log(`Packets Received: ${typeof u.packetsReceived=="number"?u.packetsReceived.toLocaleString():u.packetsReceived}`),console.log(`Packets Lost: ${u.packetsLost}`),console.log(`Audio Level: ${u.audioLevel}`),u.jitter!==void 0&&console.log(`Jitter: ${u.jitter.toFixed(5)}ms`),u.totalAudioEnergy!==void 0&&console.log(`Total Audio Energy: ${u.totalAudioEnergy.toFixed(6)}`)}),console.groupEnd()),o.userAudioInput&&o.userAudioInput.length>0&&(console.group("🎤 User Audio Input (Outbound)"),o.userAudioInput.forEach(u=>{console.log(`Packets Sent: ${typeof u.packetsSent=="number"?u.packetsSent.toLocaleString():u.packetsSent}`),u.retransmittedPackets&&console.log(`Retransmitted Packets: ${u.retransmittedPackets}`),u.avgPacketSendDelay!==void 0&&console.log(`Avg Packet Send Delay: ${u.avgPacketSendDelay.toFixed(5)}ms`)}),console.groupEnd()),o.codecs&&o.codecs.length>0&&(console.group("🔧 Codecs Used"),o.codecs.forEach(u=>{console.log(`${u.status} ${u.mimeType} - Payload Type: ${u.payloadType}`),u.clockRate&&console.log(` Clock Rate: ${u.clockRate}Hz`),u.channels&&console.log(` Channels: ${u.channels}`)}),console.groupEnd()),o.transportLayer&&o.transportLayer.length>0&&(console.group("🚚 Transport Layer"),o.transportLayer.forEach(u=>{console.log(`DTLS State: ${u.dtlsState}`),console.log(`ICE State: ${u.iceState}`),(u.bytesReceived||u.bytesSent)&&console.log(`Data Transfer (bytes) - Sent: ${(u.bytesSent||0).toLocaleString()}, Received: ${(u.bytesReceived||0).toLocaleString()}`)}),console.groupEnd()),o.issues.length>0?(console.group("⚠️ Potential Issues Detected"),o.issues.forEach(u=>console.warn(u)),console.groupEnd()):console.log("✅ No significant issues detected"),console.groupEnd()};var $e;(function(s){s.CLIENT_ERROR_CODE_USAGE_LIMIT_REACHED="CLIENT_ERROR_CODE_USAGE_LIMIT_REACHED",s.CLIENT_ERROR_CODE_SPEND_CAP_REACHED="CLIENT_ERROR_CODE_SPEND_CAP_REACHED",s.CLIENT_ERROR_CODE_VALIDATION_ERROR="CLIENT_ERROR_CODE_VALIDATION_ERROR",s.CLIENT_ERROR_CODE_AUTHENTICATION_ERROR="CLIENT_ERROR_CODE_AUTHENTICATION_ERROR",s.CLIENT_ERROR_CODE_SERVER_ERROR="CLIENT_ERROR_CODE_SERVER_ERROR",s.CLIENT_ERROR_CODE_MAX_CONCURRENT_SESSIONS_REACHED="CLIENT_ERROR_CODE_MAX_CONCURRENT_SESSIONS_REACHED",s.CLIENT_ERROR_CODE_SERVICE_BUSY="CLIENT_ERROR_CODE_SERVICE_BUSY",s.CLIENT_ERROR_CODE_NO_PLAN_FOUND="CLIENT_ERROR_CODE_NO_PLAN_FOUND",s.CLIENT_ERROR_CODE_UNKNOWN_ERROR="CLIENT_ERROR_CODE_UNKNOWN_ERROR",s.CLIENT_ERROR_CODE_CONFIGURATION_ERROR="CLIENT_ERROR_CODE_CONFIGURATION_ERROR"})($e||($e={}));class Ne extends Error{constructor(e,t,i=500,r){super(e),this.name="ClientError",this.code=t,this.statusCode=i,this.details=r,Object.setPrototypeOf(this,Ne.prototype),ui(Nt.CLIENT_METRIC_MEASUREMENT_ERROR,t,{details:r,statusCode:i})}}function Ou(){return typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID():Date.now().toString(36)+Math.random().toString(36).substr(2,9)}function bx(s){if(!(!s||!s.enabled)){if(!s.baseUrl)return"API Gateway baseUrl is required when enabled";try{const e=new URL(s.baseUrl);if(!["http:","https:","ws:","wss:"].includes(e.protocol))return`Invalid API Gateway baseUrl protocol: ${e.protocol}. Must be http:, https:, ws:, or wss:`}catch{return`Invalid API Gateway baseUrl: ${s.baseUrl}`}if(s.wsPath&&!s.wsPath.startsWith("/"))return"API Gateway wsPath must start with /"}}var Ye;(function(s){s.OFFER="offer",s.ANSWER="answer",s.ICE_CANDIDATE="icecandidate",s.END_SESSION="endsession",s.HEARTBEAT="heartbeat",s.WARNING="warning",s.TALK_STREAM_INTERRUPTED="talkinputstreaminterrupted",s.TALK_STREAM_INPUT="talkstream",s.SESSION_READY="sessionready",s.AGENT_AUDIO_INPUT="agentaudioinput",s.AGENT_AUDIO_INPUT_END="agentaudioinputend"})(Ye||(Ye={}));var vt;(function(s){s.SPEECH_TEXT="speechText",s.CLIENT_TOOL_EVENT="clientToolEvent",s.TOOL_CALL_STARTED_EVENT="toolCallStarted",s.TOOL_CALL_COMPLETED_EVENT="toolCallCompleted",s.TOOL_CALL_FAILED_EVENT="toolCallFailed",s.REASONING_TEXT="reasoningText",s.USER_SPEECH_STARTED="userSpeechStarted",s.USER_SPEECH_ENDED="userSpeechEnded"})(vt||(vt={}));var Yt;(function(s){s.PENDING="pending",s.GRANTED="granted",s.DENIED="denied",s.NOT_REQUESTED="not_requested"})(Yt||(Yt={}));var _r;(function(s){s.USER="user",s.PERSONA="persona"})(_r||(_r={}));var oe;(function(s){s.MESSAGE_HISTORY_UPDATED="MESSAGE_HISTORY_UPDATED",s.MESSAGE_STREAM_EVENT_RECEIVED="MESSAGE_STREAM_EVENT_RECEIVED",s.CONNECTION_ESTABLISHED="CONNECTION_ESTABLISHED",s.CONNECTION_CLOSED="CONNECTION_CLOSED",s.INPUT_AUDIO_STREAM_STARTED="INPUT_AUDIO_STREAM_STARTED",s.VIDEO_STREAM_STARTED="VIDEO_STREAM_STARTED",s.VIDEO_PLAY_STARTED="VIDEO_PLAY_STARTED",s.AUDIO_STREAM_STARTED="AUDIO_STREAM_STARTED",s.TALK_STREAM_INTERRUPTED="TALK_STREAM_INTERRUPTED",s.SESSION_READY="SESSION_READY",s.SERVER_WARNING="SERVER_WARNING",s.MIC_PERMISSION_PENDING="MIC_PERMISSION_PENDING",s.MIC_PERMISSION_GRANTED="MIC_PERMISSION_GRANTED",s.MIC_PERMISSION_DENIED="MIC_PERMISSION_DENIED",s.INPUT_AUDIO_DEVICE_CHANGED="INPUT_AUDIO_DEVICE_CHANGED",s.CLIENT_TOOL_EVENT_RECEIVED="CLIENT_TOOL_EVENT_RECEIVED",s.TOOL_CALL_STARTED="TOOL_CALL_STARTED",s.TOOL_CALL_COMPLETED="TOOL_CALL_COMPLETED",s.TOOL_CALL_FAILED="TOOL_CALL_FAILED",s.REASONING_HISTORY_UPDATED="REASONING_HISTORY_UPDATED",s.REASONING_STREAM_EVENT_RECEIVED="REASONING_STREAM_EVENT_RECEIVED",s.USER_SPEECH_STARTED="USER_SPEECH_STARTED",s.USER_SPEECH_ENDED="USER_SPEECH_ENDED"})(oe||(oe={}));var Fe;(function(s){s.WEB_SOCKET_OPEN="WEB_SOCKET_OPEN",s.SIGNAL_MESSAGE_RECEIVED="SIGNAL_MESSAGE_RECEIVED",s.WEBRTC_CHAT_MESSAGE_RECEIVED="WEBRTC_CHAT_MESSAGE_RECEIVED",s.WEBRTC_CLIENT_TOOL_EVENT_RECEIVED="WEBRTC_CLIENT_TOOL_EVENT_RECEIVED",s.WEBRTC_TOOL_CALL_STARTED_EVENT_RECEIVED="WEBRTC_TOOL_CALL_STARTED_EVENT_RECEIVED",s.WEBRTC_TOOL_CALL_COMPLETED_EVENT_RECEIVED="WEBRTC_TOOL_CALL_COMPLETED_EVENT_RECEIVED",s.WEBRTC_TOOL_CALL_FAILED_EVENT_RECEIVED="WEBRTC_TOOL_CALL_FAILED_EVENT_RECEIVED",s.WEBRTC_REASONING_TEXT_MESSAGE_RECEIVED="WEBRTC_REASONING_TEXT_MESSAGE_RECEIVED"})(Fe||(Fe={}));var Kt;(function(s){s.NORMAL="CONNECTION_CLOSED_CODE_NORMAL",s.MICROPHONE_PERMISSION_DENIED="CONNECTION_CLOSED_CODE_MICROPHONE_PERMISSION_DENIED",s.SIGNALLING_CLIENT_CONNECTION_FAILURE="CONNECTION_CLOSED_CODE_SIGNALLING_CLIENT_CONNECTION_FAILURE",s.WEBRTC_FAILURE="CONNECTION_CLOSED_CODE_WEBRTC_FAILURE",s.SERVER_CLOSED_CONNECTION="CONNECTION_CLOSED_CODE_SERVER_CLOSED_CONNECTION"})(Kt||(Kt={}));class xx{constructor(e,t){this.sequenceNumber=0,this.config=e,this.signallingClient=t}sendAudioChunk(e){const i={audioData:typeof e=="string"?e:this.arrayBufferToBase64(e),encoding:this.config.encoding,sampleRate:this.config.sampleRate,channels:this.config.channels,sequenceNumber:this.sequenceNumber++};this.signallingClient.sendAgentAudioInput(i)}endSequence(){this.signallingClient.sendAgentAudioInputEnd(),this.sequenceNumber=0}getSequenceNumber(){return this.sequenceNumber}getConfig(){return this.config}arrayBufferToBase64(e){const t=e instanceof Uint8Array?e:new Uint8Array(e),i=Array.from(t,r=>String.fromCharCode(r)).join("");return btoa(i)}}var Gi=function(s,e,t,i){function r(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(h){try{c(i.next(h))}catch(u){o(u)}}function l(h){try{c(i.throw(h))}catch(u){o(u)}}function c(h){h.done?n(h.value):r(h.value).then(a,l)}c((i=i.apply(s,e||[])).next())})};const vx=5,Sx=5;class Cx{constructor(e,t,i,r,n){var o,a,l,c,h;if(this.stopSignal=!1,this.sendingBuffer=[],this.wsConnectionAttempts=0,this.socket=null,this.heartBeatIntervalRef=null,this.publicEventEmitter=i,this.internalEventEmitter=r,this.apiGatewayConfig=n,!e)throw new Error("Signalling Client: sessionId is required");this.sessionId=e;const{heartbeatIntervalSeconds:u,maxWsReconnectionAttempts:f,url:d}=t;if(this.heartbeatIntervalSeconds=u||vx,this.maxWsReconnectionAttempts=f||Sx,!d.baseUrl)throw new Error("Signalling Client: baseUrl is required");if(!((o=this.apiGatewayConfig)===null||o===void 0)&&o.enabled&&(!((a=this.apiGatewayConfig)===null||a===void 0)&&a.baseUrl)){const g=new URL(this.apiGatewayConfig.baseUrl),_=(l=this.apiGatewayConfig.wsPath)!==null&&l!==void 0?l:"/ws";g.protocol=g.protocol.replace("http","ws"),g.pathname=_,this.url=g;const y=d.protocol||"https",x=y==="http"?"ws":"wss",v=`${y}://${d.baseUrl}`,C=(c=d.signallingPath)!==null&&c!==void 0?c:"/ws",E=new URL(v);E.protocol=x==="ws"?"ws:":"wss:",d.port&&(E.port=d.port),E.pathname=C,E.searchParams.append("session_id",e),this.url.searchParams.append("target_url",E.href)}else{const _=`${d.protocol||"https"}://${d.baseUrl}`;this.url=new URL(_),this.url.protocol=d.protocol==="http"?"ws:":"wss:",d.port&&(this.url.port=d.port),this.url.pathname=(h=d.signallingPath)!==null&&h!==void 0?h:"/ws",this.url.searchParams.append("session_id",e)}}stop(){this.stopSignal=!0,this.closeSocket()}connect(){return this.socket=new WebSocket(this.url.href),this.socket.onopen=this.onOpen.bind(this),this.socket.onclose=this.onClose.bind(this),this.socket.onerror=this.onError.bind(this),this.socket}sendOffer(e){return Gi(this,void 0,void 0,function*(){const t={connectionDescription:e,userUid:this.sessionId},i={actionType:Ye.OFFER,sessionId:this.sessionId,payload:t};this.sendSignalMessage(i)})}sendIceCandidate(e){return Gi(this,void 0,void 0,function*(){const t={actionType:Ye.ICE_CANDIDATE,sessionId:this.sessionId,payload:e.toJSON()};this.sendSignalMessage(t)})}sendSignalMessage(e){var t;if(((t=this.socket)===null||t===void 0?void 0:t.readyState)===WebSocket.OPEN)try{this.socket.send(JSON.stringify(e))}catch(i){console.error("SignallingClient - sendSignalMessage: error sending message",i)}else this.sendingBuffer.push(e)}sendTalkMessage(e){return Gi(this,void 0,void 0,function*(){const t={actionType:Ye.TALK_STREAM_INPUT,sessionId:this.sessionId,payload:e};this.sendSignalMessage(t)})}sendAgentAudioInput(e){const t={actionType:Ye.AGENT_AUDIO_INPUT,sessionId:this.sessionId,payload:e};this.sendSignalMessage(t)}sendAgentAudioInputEnd(){const e={actionType:Ye.AGENT_AUDIO_INPUT_END,sessionId:this.sessionId,payload:{}};this.sendSignalMessage(e)}closeSocket(){this.socket&&(this.socket.close(),this.socket=null),this.heartBeatIntervalRef&&(clearInterval(this.heartBeatIntervalRef),this.heartBeatIntervalRef=null)}onOpen(){return Gi(this,void 0,void 0,function*(){if(!this.socket)throw new Error("SignallingClient - onOpen: socket is null");try{this.wsConnectionAttempts=0,this.flushSendingBuffer(),this.socket.onmessage=this.onMessage.bind(this),this.startSendingHeartBeats(),this.internalEventEmitter.emit(Fe.WEB_SOCKET_OPEN)}catch(e){console.error("SignallingClient - onOpen: error in onOpen",e),this.publicEventEmitter.emit(oe.CONNECTION_CLOSED,Kt.SIGNALLING_CLIENT_CONNECTION_FAILURE)}})}onClose(){return Gi(this,void 0,void 0,function*(){this.wsConnectionAttempts+=1,!this.stopSignal&&(this.wsConnectionAttempts<=this.maxWsReconnectionAttempts?(this.socket=null,setTimeout(()=>{this.connect()},100*this.wsConnectionAttempts)):(this.heartBeatIntervalRef&&(clearInterval(this.heartBeatIntervalRef),this.heartBeatIntervalRef=null),this.publicEventEmitter.emit(oe.CONNECTION_CLOSED,Kt.SIGNALLING_CLIENT_CONNECTION_FAILURE)))})}onError(e){this.stopSignal||console.error("SignallingClient - onError: ",e)}flushSendingBuffer(){const e=[];this.sendingBuffer.length>0&&this.sendingBuffer.forEach(t=>{var i;((i=this.socket)===null||i===void 0?void 0:i.readyState)===WebSocket.OPEN?this.socket.send(JSON.stringify(t)):e.push(t)}),this.sendingBuffer=e}onMessage(e){return Gi(this,void 0,void 0,function*(){const t=JSON.parse(e.data);this.internalEventEmitter.emit(Fe.SIGNAL_MESSAGE_RECEIVED,t)})}startSendingHeartBeats(){if(!this.socket)throw new Error("SignallingClient - startSendingHeartBeats: socket is null");this.heartBeatIntervalRef&&console.warn("SignallingClient - startSendingHeartBeats: heartbeat interval already set");const e=this.heartbeatIntervalSeconds*1e3,t={actionType:Ye.HEARTBEAT,sessionId:this.sessionId,payload:""},i=JSON.stringify(t);this.heartBeatIntervalRef=setInterval(()=>{var r;this.stopSignal||((r=this.socket)===null||r===void 0?void 0:r.readyState)===WebSocket.OPEN&&this.socket.send(i)},e)}}function Ex(s){return"brainType"in s||"llmId"in s}var Du=function(s,e,t,i){function r(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(h){try{c(i.next(h))}catch(u){o(u)}}function l(h){try{c(i.throw(h))}catch(u){o(u)}}function c(h){h.done?n(h.value):r(h.value).then(a,l)}c((i=i.apply(s,e||[])).next())})};class Tx{constructor(e,t,i){if(!e&&!t)throw new Error("Either sessionToken or apiKey must be provided");this.sessionToken=e||null,this.apiKey=t||null,this.baseUrl=(i==null?void 0:i.baseUrl)||dx,this.apiVersion=(i==null?void 0:i.apiVersion)||fx,this.apiGatewayConfig=(i==null?void 0:i.apiGateway)||void 0}buildGatewayUrlAndHeaders(e,t){var i,r;if(!((i=this.apiGatewayConfig)===null||i===void 0)&&i.enabled&&(!((r=this.apiGatewayConfig)===null||r===void 0)&&r.baseUrl)){const n=`${this.apiGatewayConfig.baseUrl}${e}`,o=new URL(`${this.baseUrl}${e}`),a=Object.assign(Object.assign({},t),{"X-Anam-Target-Url":o.href});return{url:n,headers:a}}else return{url:`${this.baseUrl}${e}`,headers:t}}startSession(e,t){return Du(this,void 0,void 0,function*(){if(!this.sessionToken){if(!e)throw new Ne("Persona configuration must be provided when using apiKey",$e.CLIENT_ERROR_CODE_VALIDATION_ERROR,400);this.sessionToken=yield this.unsafe_getSessionToken(e)}e&&"brainType"in e&&console.warn("Warning: brainType is deprecated and will be removed in a future version. Please use llmId instead.");try{const i=`${this.apiVersion}/engine/session`,{url:r,headers:n}=this.buildGatewayUrlAndHeaders(i,{"Content-Type":"application/json",Authorization:`Bearer ${this.sessionToken}`}),o=yield fetch(r,{method:"POST",headers:n,body:JSON.stringify({personaConfig:e,sessionOptions:t,clientMetadata:Mu})}),a=yield o.json(),l=a.error;switch(o.status){case 200:case 201:return a;case 400:throw new Ne("Invalid request to start session",$e.CLIENT_ERROR_CODE_VALIDATION_ERROR,400,{cause:a.message});case 401:throw new Ne("Authentication failed when starting session",$e.CLIENT_ERROR_CODE_AUTHENTICATION_ERROR,401,{cause:a.message});case 402:throw new Ne("Please sign up for a plan to start a session",$e.CLIENT_ERROR_CODE_NO_PLAN_FOUND,402,{cause:a.message});case 403:throw new Ne("Authentication failed when starting session",$e.CLIENT_ERROR_CODE_AUTHENTICATION_ERROR,403,{cause:a.message});case 429:throw l==="Concurrent session limit reached"?new Ne("Concurrency limit reached, please upgrade your plan",$e.CLIENT_ERROR_CODE_MAX_CONCURRENT_SESSIONS_REACHED,429,{cause:a.message}):l==="Spend cap reached"?new Ne("Spend cap reached, please upgrade your plan",$e.CLIENT_ERROR_CODE_SPEND_CAP_REACHED,429,{cause:a.message}):new Ne("Usage limit reached, please upgrade your plan",$e.CLIENT_ERROR_CODE_USAGE_LIMIT_REACHED,429,{cause:a.message});case 503:throw new Ne("There are no available personas, please try again later",$e.CLIENT_ERROR_CODE_SERVICE_BUSY,503,{cause:a.message});default:throw new Ne("Unknown error when starting session",$e.CLIENT_ERROR_CODE_SERVER_ERROR,500,{cause:a.message})}}catch(i){throw i instanceof Ne?i:new Ne("Failed to start session",$e.CLIENT_ERROR_CODE_SERVER_ERROR,500,{cause:i instanceof Error?i.message:String(i)})}})}unsafe_getSessionToken(e){return Du(this,void 0,void 0,function*(){if(console.warn("Using unsecure method. This method should not be used in production."),!this.apiKey)throw new Error("No apiKey provided");e&&"brainType"in e&&console.warn("Warning: brainType is deprecated and will be removed in a future version. Please use llmId instead.");let t={clientLabel:"js-sdk-api-key"};Ex(e)&&(t=Object.assign(Object.assign({},t),{personaConfig:e}));try{const i=`${this.apiVersion}/auth/session-token`,{url:r,headers:n}=this.buildGatewayUrlAndHeaders(i,{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`});return(yield(yield fetch(r,{method:"POST",headers:n,body:JSON.stringify(t)})).json()).sessionToken}catch{throw new Error("Failed to get session token")}})}getApiUrl(){return`${this.baseUrl}${this.apiVersion}`}}var wx=function(s,e,t,i){function r(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(h){try{c(i.next(h))}catch(u){o(u)}}function l(h){try{c(i.throw(h))}catch(u){o(u)}}function c(h){h.done?n(h.value):r(h.value).then(a,l)}c((i=i.apply(s,e||[])).next())})};class Ix{constructor(e,t,i){this.baseUrl=e,this.sessionId=t,this.apiGatewayConfig=i}sendTalkCommand(e){return wx(this,void 0,void 0,function*(){var t,i;try{let r,n={"Content-Type":"application/json"};const o="/talk",a=`?session_id=${this.sessionId}`;if(!((t=this.apiGatewayConfig)===null||t===void 0)&&t.enabled&&(!((i=this.apiGatewayConfig)===null||i===void 0)&&i.baseUrl)){r=`${this.apiGatewayConfig.baseUrl}${o}${a}`;const c=new URL(`${this.baseUrl}${o}${a}`);n["X-Anam-Target-Url"]=c.href}else r=`${this.baseUrl}${o}${a}`;const l=yield fetch(r,{method:"POST",headers:n,body:JSON.stringify({content:e})});if(!l.ok)throw new Error(`Failed to send talk command: ${l.status} ${l.statusText}`)}catch(r){throw console.error(r),new Error("EngineApiRestClient - sendTalkCommand: Failed to send talk command")}})}}class Ax{constructor(){this.listeners={}}addListener(e,t){this.listeners[e]||(this.listeners[e]=new Set),this.listeners[e].add(t)}removeListener(e,t){this.listeners[e]&&this.listeners[e].delete(t)}emit(e,...t){this.listeners[e]&&this.listeners[e].forEach(i=>{i(...t)})}}class Rx{constructor(e,t){this.messages=[],this.publicEventEmitter=e,this.internalEventEmitter=t,this.internalEventEmitter.addListener(Fe.WEBRTC_CHAT_MESSAGE_RECEIVED,this.processWebRtcTextMessageEvent.bind(this))}webRtcTextMessageEventToMessageStreamEvent(e){return{id:`${e.role}::${e.message_id}`,content:e.content,role:e.role,endOfSpeech:e.end_of_speech,interrupted:e.interrupted}}processUserMessage(e){const t={id:e.id,content:e.content,role:e.role};this.messages.push(t)}processPersonaMessage(e){const t={id:e.id,content:e.content,role:e.role,interrupted:e.interrupted},i=this.messages.findIndex(r=>r.id===t.id);if(i!==-1){const r=this.messages[i];this.messages[i]=Object.assign(Object.assign({},r),{content:r.content+t.content,interrupted:r.interrupted||t.interrupted})}else this.messages.push(t)}processWebRtcTextMessageEvent(e){const t=this.webRtcTextMessageEventToMessageStreamEvent(e);switch(this.publicEventEmitter.emit(oe.MESSAGE_STREAM_EVENT_RECEIVED,t),t.role){case _r.USER:this.processUserMessage(t);break;case _r.PERSONA:this.processPersonaMessage(t);break}t.endOfSpeech&&this.publicEventEmitter.emit(oe.MESSAGE_HISTORY_UPDATED,this.messages)}}class Mx{constructor(){this.listeners={}}addListener(e,t){this.listeners[e]||(this.listeners[e]=new Set),this.listeners[e].add(t)}removeListener(e,t){this.listeners[e]&&this.listeners[e].delete(t)}emit(e,...t){if(e===oe.CONNECTION_ESTABLISHED&&ui(Nt.CLIENT_METRIC_MEASUREMENT_CONNECTION_ESTABLISHED,"1"),e===oe.CONNECTION_CLOSED){const[i,r]=t;ui(Nt.CLIENT_METRIC_MEASUREMENT_CONNECTION_CLOSED,i,r?{details:r}:void 0)}this.listeners[e]&&this.listeners[e].forEach(i=>{i(...t)})}}var qe;(function(s){s[s.UNSTARTED=0]="UNSTARTED",s[s.STREAMING=1]="STREAMING",s[s.INTERRUPTED=2]="INTERRUPTED",s[s.ENDED=3]="ENDED"})(qe||(qe={}));var Ro=function(s,e,t,i){function r(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(h){try{c(i.next(h))}catch(u){o(u)}}function l(h){try{c(i.throw(h))}catch(u){o(u)}}function c(h){h.done?n(h.value):r(h.value).then(a,l)}c((i=i.apply(s,e||[])).next())})};class Px{constructor(e,t,i){this.state=qe.UNSTARTED,this.correlationId=e,this.internalEventEmitter=t,this.signallingClient=i,this.internalEventEmitter.addListener(Fe.SIGNAL_MESSAGE_RECEIVED,this.onSignalMessage.bind(this))}onDeactivate(){this.internalEventEmitter.removeListener(Fe.SIGNAL_MESSAGE_RECEIVED,this.onSignalMessage.bind(this))}onSignalMessage(e){return Ro(this,void 0,void 0,function*(){e.actionType===Ye.TALK_STREAM_INTERRUPTED&&e.payload.correlationId===this.correlationId&&(this.state=qe.INTERRUPTED,this.onDeactivate())})}endMessage(){return Ro(this,void 0,void 0,function*(){if(this.state===qe.ENDED){console.warn("Talk stream is already ended via end of speech. No need to call endMessage.");return}if(this.state!==qe.STREAMING){console.warn("Talk stream is not active state: "+this.state);return}const e={content:"",startOfSpeech:!1,endOfSpeech:!0,correlationId:this.correlationId};yield this.signallingClient.sendTalkMessage(e),this.state=qe.ENDED,this.onDeactivate()})}streamMessageChunk(e,t){return Ro(this,void 0,void 0,function*(){if(this.state!==qe.STREAMING&&this.state!==qe.UNSTARTED)throw new Error("Talk stream is not in an active state: "+this.state);const i={content:e,startOfSpeech:this.state===qe.UNSTARTED,endOfSpeech:t,correlationId:this.correlationId};this.state=t?qe.ENDED:qe.STREAMING,this.state===qe.ENDED&&this.onDeactivate(),yield this.signallingClient.sendTalkMessage(i)})}getCorrelationId(){return this.correlationId}isActive(){return this.state===qe.STREAMING||this.state===qe.UNSTARTED}getState(){return this.state}}var Mo=function(s,e,t,i){function r(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(h){try{c(i.next(h))}catch(u){o(u)}}function l(h){try{c(i.throw(h))}catch(u){o(u)}}function c(h){h.done?n(h.value):r(h.value).then(a,l)}c((i=i.apply(s,e||[])).next())})};const Nu=(s,e)=>{if(isNaN(s)||isNaN(e))return 0;const t=e-s;return t>0?t:0};class Fu{constructor(e){this.handlers=Object.create(null),this.pendingCalls=Object.create(null),this.publicEventEmitter=e}clearPendingCalls(){this.pendingCalls=Object.create(null)}registerHandler(e,t){return this.handlers[e]=t,()=>{delete this.handlers[e]}}processToolCallStartedEvent(e){return Mo(this,void 0,void 0,function*(){const{tool_name:t,timestamp:i}=e,r=this.WebRTCToolCallStartedEventToToolCallStartedPayload(e),n=new Date(i);if(this.pendingCalls[e.tool_call_id]={payload:r,timestamp:n.getTime()},!(t in this.handlers))return;const o=this.handlers[t];if(o.onStart)try{let a=yield o.onStart(r);if(e.tool_type==="client"){yield this.processToolCallCompletedEvent(Object.assign(Object.assign({},e),{result:a,timestamp:new Date().toISOString()}));return}}catch(a){a instanceof Error?yield this.processToolCallFailedEvent(Object.assign(Object.assign({},e),{error_message:`Error in onStart handler: ${a.message}`,timestamp:new Date().toISOString()})):yield this.processToolCallFailedEvent(Object.assign(Object.assign({},e),{error_message:`Error in onStart handler: ${String(a)}`,timestamp:new Date().toISOString()}));return}})}processToolCallCompletedEvent(e){return Mo(this,void 0,void 0,function*(){const{tool_name:t,tool_call_id:i,timestamp:r}=e,n=this.webRTCToolCallCompletedEventToToolCallCompletedPayload(e);if(i in this.pendingCalls&&delete this.pendingCalls[i],!(t in this.handlers))return;const o=this.handlers[t];if(o.onComplete){e.tool_type==="client"&&this.publicEventEmitter.emit(oe.TOOL_CALL_COMPLETED,n);try{yield o.onComplete(n)}catch(a){console.error(`Error in onComplete handler for tool ${t}:`,a);return}}})}processToolCallFailedEvent(e){return Mo(this,void 0,void 0,function*(){const{tool_name:t,tool_call_id:i,timestamp:r}=e,n=this.webRTCToolCallFailedEventToToolCallFailedPayload(e);if(i in this.pendingCalls&&delete this.pendingCalls[i],!(t in this.handlers))return;const o=this.handlers[t];if(o.onFail){e.tool_type==="client"&&this.publicEventEmitter.emit(oe.TOOL_CALL_FAILED,n);try{yield o.onFail(n)}catch(a){console.error(`Error in onFail handler for tool ${t}:`,a);return}}})}static WebRTCClientToolEventToClientToolEvent(e){return{eventUid:e.event_uid,sessionId:e.session_id,eventName:e.event_name,eventData:e.event_data,timestamp:e.timestamp,timestampUserAction:e.timestamp_user_action,userActionCorrelationId:e.user_action_correlation_id}}static WebRTCToolCallStartedEventToClientToolEvent(e){return{eventUid:e.event_uid,sessionId:e.session_id,eventName:e.tool_name,eventData:e.arguments,timestamp:e.timestamp,timestampUserAction:e.timestamp_user_action,userActionCorrelationId:e.user_action_correlation_id}}WebRTCToolCallStartedEventToToolCallStartedPayload(e){return{eventUid:e.event_uid,toolCallId:e.tool_call_id,toolName:e.tool_name,toolType:e.tool_type,toolSubtype:e.tool_subtype,arguments:e.arguments,timestamp:e.timestamp,timestampUserAction:e.timestamp_user_action,userActionCorrelationId:e.user_action_correlation_id}}webRTCToolCallCompletedEventToToolCallCompletedPayload(e){const t=new Date(e.timestamp),i=this.pendingCalls[e.tool_call_id],r=i?Nu(i.timestamp,t.getTime()):0;return{eventUid:e.event_uid,toolCallId:e.tool_call_id,toolName:e.tool_name,toolType:e.tool_type,toolSubtype:e.tool_subtype,result:e.result,executionTime:r>0?r:0,timestamp:e.timestamp,documentsAccessed:e.documents_accessed,timestampUserAction:e.timestamp_user_action,userActionCorrelationId:e.user_action_correlation_id}}webRTCToolCallFailedEventToToolCallFailedPayload(e){const t=new Date(e.timestamp),i=this.pendingCalls[e.tool_call_id],r=i?Nu(i.timestamp,t.getTime()):0;return{eventUid:e.event_uid,toolCallId:e.tool_call_id,toolName:e.tool_name,toolType:e.tool_type,toolSubtype:e.tool_subtype,errorMessage:e.error_message,executionTime:r>0?r:0,timestamp:e.timestamp,timestampUserAction:e.timestamp_user_action,userActionCorrelationId:e.user_action_correlation_id}}}var st=function(s,e,t,i){function r(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(h){try{c(i.next(h))}catch(u){o(u)}}function l(h){try{c(i.throw(h))}catch(u){o(u)}}function c(h){h.done?n(h.value):r(h.value).then(a,l)}c((i=i.apply(s,e||[])).next())})};const kx=15e3,Bx=5e3,Ox=2;class Dx{constructor(e,t,i,r,n){var o,a,l,c;this.peerConnection=null,this.connectionReceivedAnswer=!1,this.remoteIceCandidateBuffer=[],this.inputAudioStream=null,this.dataChannel=null,this.videoElement=null,this.videoStream=null,this.audioStream=null,this.inputAudioState={isMuted:!1,permissionState:Yt.NOT_REQUESTED},this.successMetricPoller=null,this.successMetricFired=!1,this.showPeerConnectionStatsReport=!1,this.peerConnectionStatsReportOutputFormat="console",this.statsCollectionInterval=null,this.agentAudioInputStream=null,this.publicEventEmitter=i,this.internalEventEmitter=r,this.toolCallManager=n,this.apiGatewayConfig=t.apiGateway;const{inputAudio:h}=t;this.inputAudioState=h.inputAudioState,t.inputAudio.userProvidedMediaStream&&(this.inputAudioStream=t.inputAudio.userProvidedMediaStream),this.disableInputAudio=t.inputAudio.disableInputAudio===!0,this.internalEventEmitter.addListener(Fe.WEB_SOCKET_OPEN,this.onSignallingClientConnected.bind(this)),this.internalEventEmitter.addListener(Fe.SIGNAL_MESSAGE_RECEIVED,this.onSignalMessage.bind(this)),this.internalEventEmitter.addListener(Fe.WEBRTC_TOOL_CALL_STARTED_EVENT_RECEIVED,this.toolCallManager.processToolCallStartedEvent.bind(this.toolCallManager)),this.internalEventEmitter.addListener(Fe.WEBRTC_TOOL_CALL_COMPLETED_EVENT_RECEIVED,this.toolCallManager.processToolCallCompletedEvent.bind(this.toolCallManager)),this.internalEventEmitter.addListener(Fe.WEBRTC_TOOL_CALL_FAILED_EVENT_RECEIVED,this.toolCallManager.processToolCallFailedEvent.bind(this.toolCallManager)),this.iceServers=t.iceServers,this.signallingClient=new Cx(e,t.signalling,this.publicEventEmitter,this.internalEventEmitter,this.apiGatewayConfig),this.engineApiRestClient=new Ix(t.engine.baseUrl,e,this.apiGatewayConfig),this.audioDeviceId=t.inputAudio.audioDeviceId,this.showPeerConnectionStatsReport=(a=(o=t.metrics)===null||o===void 0?void 0:o.showPeerConnectionStatsReport)!==null&&a!==void 0?a:!1,this.peerConnectionStatsReportOutputFormat=(c=(l=t.metrics)===null||l===void 0?void 0:l.peerConnectionStatsReportOutputFormat)!==null&&c!==void 0?c:"console"}onInputAudioStateChange(e,t){e.isMuted!==t.isMuted&&(t.isMuted?this.muteAllAudioTracks():this.unmuteAllAudioTracks())}muteAllAudioTracks(){var e;(e=this.inputAudioStream)===null||e===void 0||e.getAudioTracks().forEach(t=>{t.enabled=!1})}unmuteAllAudioTracks(){var e;(e=this.inputAudioStream)===null||e===void 0||e.getAudioTracks().forEach(t=>{t.enabled=!0})}startStatsCollection(){this.statsCollectionInterval||(this.statsCollectionInterval=setInterval(()=>st(this,void 0,void 0,function*(){if(!(!this.peerConnection||!this.dataChannel||this.dataChannel.readyState!=="open"))try{const e=yield this.peerConnection.getStats();this.sendClientSideMetrics(e)}catch(e){console.error("Failed to collect and send stats:",e)}}),Bx))}sendClientSideMetrics(e){e.forEach(t=>{if(t.type==="inbound-rtp"){const i={message_type:"remote_rtp_stats",data:t};this.dataChannel&&this.dataChannel.readyState==="open"&&this.dataChannel.send(JSON.stringify(i))}})}startSuccessMetricPolling(){if(this.successMetricPoller||this.successMetricFired)return;const e=setTimeout(()=>{this.successMetricPoller&&(console.warn("No video frames received, there is a problem with the connection."),clearInterval(this.successMetricPoller),this.successMetricPoller=null)},kx);this.successMetricPoller=setInterval(()=>st(this,void 0,void 0,function*(){if(!this.peerConnection||this.successMetricFired){this.successMetricPoller&&clearInterval(this.successMetricPoller),clearTimeout(e);return}try{const t=yield this.peerConnection.getStats();let i=!1,r=null;t.forEach(n=>{n.type==="inbound-rtp"&&n.kind==="video"&&(n.framesDecoded!==void 0&&n.framesDecoded>0?(i=!0,r="framesDecoded"):n.framesReceived!==void 0&&n.framesReceived>0?(i=!0,r="framesReceived"):n.bytesReceived>0&&n.packetsReceived>0&&n.bytesReceived>1e5&&(i=!0,r="bytesReceived"))}),i&&!this.successMetricFired&&(this.successMetricFired=!0,ui(Nt.CLIENT_METRIC_MEASUREMENT_SESSION_SUCCESS,"1",r?{detectionMethod:r}:void 0),this.successMetricPoller&&clearInterval(this.successMetricPoller),clearTimeout(e),this.successMetricPoller=null)}catch{}}),500)}muteInputAudio(){const e=this.inputAudioState,t=Object.assign(Object.assign({},this.inputAudioState),{isMuted:!0});return this.inputAudioState=t,this.onInputAudioStateChange(e,t),this.inputAudioState}unmuteInputAudio(){const e=this.inputAudioState,t=Object.assign(Object.assign({},this.inputAudioState),{isMuted:!1});return this.inputAudioState=t,this.onInputAudioStateChange(e,t),this.inputAudioState}getInputAudioState(){return this.inputAudioState}getPeerConnection(){return this.peerConnection}changeAudioInputDevice(e){return st(this,void 0,void 0,function*(){if(!this.peerConnection)throw new Error("StreamingClient - changeAudioInputDevice: peer connection is not initialized. Start streaming first.");if(e==null)throw new Error("StreamingClient - changeAudioInputDevice: deviceId is required");const t=this.inputAudioState.isMuted;try{this.inputAudioStream&&this.inputAudioStream.getAudioTracks().forEach(r=>{r.stop()});const i={echoCancellation:!0,deviceId:{exact:e}};this.inputAudioStream=yield navigator.mediaDevices.getUserMedia({audio:i}),this.audioDeviceId=e,yield this.setupAudioTrack(),t&&this.muteAllAudioTracks(),this.publicEventEmitter.emit(oe.INPUT_AUDIO_DEVICE_CHANGED,e)}catch(i){throw console.error("Failed to change audio input device:",i),new Error(`StreamingClient - changeAudioInputDevice: ${i instanceof Error?i.message:String(i)}`)}})}getInputAudioStream(){return this.inputAudioStream}getVideoStream(){return this.videoStream}getAudioStream(){return this.audioStream}sendDataMessage(e){this.dataChannel&&this.dataChannel.readyState==="open"&&this.dataChannel.send(e)}setMediaStreamTargetById(e){if(e){const t=document.getElementById(e);if(!t)throw new Error(`StreamingClient: video element with id ${e} not found`);this.videoElement=t}}startConnection(){try{if(this.peerConnection){console.error("StreamingClient - startConnection: peer connection already exists");return}this.signallingClient.connect()}catch(e){console.error("StreamingClient - startConnection: error",e),this.handleWebrtcFailure(e)}}stopConnection(){return st(this,void 0,void 0,function*(){yield this.shutdown()})}sendTalkCommand(e){return st(this,void 0,void 0,function*(){if(!this.peerConnection)throw new Error("StreamingClient - sendTalkCommand: peer connection is null");yield this.engineApiRestClient.sendTalkCommand(e)})}startTalkMessageStream(e){return e||(e=Math.random().toString(36).substring(2,15)),new Px(e,this.internalEventEmitter,this.signallingClient)}createAgentAudioInputStream(e){return this.agentAudioInputStream=new xx(e,this.signallingClient),this.agentAudioInputStream}getAgentAudioInputStream(){return this.agentAudioInputStream}initPeerConnection(){return st(this,void 0,void 0,function*(){this.peerConnection=new RTCPeerConnection({iceServers:this.iceServers,iceCandidatePoolSize:Ox}),this.peerConnection.onicecandidate=this.onIceCandidate.bind(this),this.peerConnection.oniceconnectionstatechange=this.onIceConnectionStateChange.bind(this),this.peerConnection.onconnectionstatechange=this.onConnectionStateChange.bind(this),this.peerConnection.addEventListener("track",this.onTrackEventHandler.bind(this)),yield this.setupDataChannels(),this.peerConnection.addTransceiver("video",{direction:"recvonly"}),this.disableInputAudio?this.peerConnection.addTransceiver("audio",{direction:"recvonly"}):(this.peerConnection.addTransceiver("audio",{direction:"sendrecv"}),this.inputAudioStream?yield this.setupAudioTrack():this.requestMicrophonePermissionAsync().catch(e=>{console.error("Async microphone permission request failed:",e)}))})}onSignalMessage(e){return st(this,void 0,void 0,function*(){if(!this.peerConnection){console.error("StreamingClient - onSignalMessage: peerConnection is not initialized");return}switch(e.actionType){case Ye.ANSWER:const t=e.payload;yield this.peerConnection.setRemoteDescription(t),this.connectionReceivedAnswer=!0,this.flushRemoteIceCandidateBuffer();break;case Ye.ICE_CANDIDATE:const i=e.payload,r=new RTCIceCandidate(i);this.connectionReceivedAnswer?yield this.peerConnection.addIceCandidate(r):this.remoteIceCandidateBuffer.push(r);break;case Ye.END_SESSION:const n=e.payload;this.publicEventEmitter.emit(oe.CONNECTION_CLOSED,Kt.SERVER_CLOSED_CONNECTION,n),this.shutdown();break;case Ye.WARNING:const o=e.payload;console.warn("Warning received from server: "+o),this.publicEventEmitter.emit(oe.SERVER_WARNING,o);break;case Ye.TALK_STREAM_INTERRUPTED:const a=e.payload;this.publicEventEmitter.emit(oe.TALK_STREAM_INTERRUPTED,a.correlationId);break;case Ye.SESSION_READY:const l=e.sessionId;this.publicEventEmitter.emit(oe.SESSION_READY,l);break;case Ye.HEARTBEAT:break;default:console.warn("StreamingClient - onSignalMessage: unknown signal message action type. Is your anam-sdk version up to date?",e)}})}onSignallingClientConnected(){return st(this,void 0,void 0,function*(){if(!this.peerConnection)try{yield this.initPeerConnectionAndSendOffer()}catch(e){console.error("StreamingClient - onSignallingClientConnected: Error initializing peer connection",e),this.handleWebrtcFailure(e)}})}flushRemoteIceCandidateBuffer(){this.remoteIceCandidateBuffer.forEach(e=>{var t;(t=this.peerConnection)===null||t===void 0||t.addIceCandidate(e)}),this.remoteIceCandidateBuffer=[]}onIceCandidate(e){e.candidate&&this.signallingClient.sendIceCandidate(e.candidate)}onIceConnectionStateChange(){var e,t;(((e=this.peerConnection)===null||e===void 0?void 0:e.iceConnectionState)==="connected"||((t=this.peerConnection)===null||t===void 0?void 0:t.iceConnectionState)==="completed")&&(this.publicEventEmitter.emit(oe.CONNECTION_ESTABLISHED),this.startStatsCollection())}onConnectionStateChange(){var e;((e=this.peerConnection)===null||e===void 0?void 0:e.connectionState)==="closed"&&(console.error("StreamingClient - onConnectionStateChange: Connection closed"),this.handleWebrtcFailure("The connection to our servers was lost. Please try again."))}handleWebrtcFailure(e){console.error({message:"StreamingClient - handleWebrtcFailure: ",err:e}),e.name==="NotAllowedError"&&e.message==="Permission denied"?this.publicEventEmitter.emit(oe.CONNECTION_CLOSED,Kt.MICROPHONE_PERMISSION_DENIED):this.publicEventEmitter.emit(oe.CONNECTION_CLOSED,Kt.WEBRTC_FAILURE);try{this.stopConnection()}catch(t){console.error("StreamingClient - handleWebrtcFailure: error stopping connection",t)}}onTrackEventHandler(e){if(e.track.kind==="video"){if(this.startSuccessMetricPolling(),this.videoStream=e.streams[0],this.publicEventEmitter.emit(oe.VIDEO_STREAM_STARTED,this.videoStream),this.videoElement){this.videoElement.srcObject=this.videoStream;const t=this.videoElement.requestVideoFrameCallback(()=>{var i;(i=this.videoElement)===null||i===void 0||i.cancelVideoFrameCallback(t),this.publicEventEmitter.emit(oe.VIDEO_PLAY_STARTED),this.successMetricFired||(this.successMetricFired=!0,ui(Nt.CLIENT_METRIC_MEASUREMENT_SESSION_SUCCESS,"1",{detectionMethod:"videoElement"}))})}}else e.track.kind==="audio"&&(this.audioStream=e.streams[0],this.publicEventEmitter.emit(oe.AUDIO_STREAM_STARTED,this.audioStream))}setupDataChannels(){return st(this,void 0,void 0,function*(){if(!this.peerConnection){console.error("StreamingClient - setupDataChannels: peer connection is not initialized");return}if(!this.disableInputAudio&&this.inputAudioStream&&!this.inputAudioStream.getAudioTracks().length)throw new Error("StreamingClient - setupDataChannels: user provided stream does not have audio tracks");const e=this.peerConnection.createDataChannel("session",{ordered:!0});e.onopen=()=>{this.dataChannel=e??null},e.onclose=()=>{},e.onmessage=t=>{var i,r,n,o;try{const a=JSON.parse(t.data);switch(a.messageType){case vt.SPEECH_TEXT:this.internalEventEmitter.emit(Fe.WEBRTC_CHAT_MESSAGE_RECEIVED,a.data);break;case vt.CLIENT_TOOL_EVENT:const l=a.data;this.internalEventEmitter.emit(Fe.WEBRTC_CLIENT_TOOL_EVENT_RECEIVED,l);const c=Fu.WebRTCClientToolEventToClientToolEvent(l);this.publicEventEmitter.emit(oe.CLIENT_TOOL_EVENT_RECEIVED,c);break;case vt.TOOL_CALL_STARTED_EVENT:const h=a.data;this.publicEventEmitter.emit(oe.TOOL_CALL_STARTED,this.toolCallManager.WebRTCToolCallStartedEventToToolCallStartedPayload(h)),this.internalEventEmitter.emit(Fe.WEBRTC_TOOL_CALL_STARTED_EVENT_RECEIVED,h);break;case vt.TOOL_CALL_COMPLETED_EVENT:const u=a.data;this.publicEventEmitter.emit(oe.TOOL_CALL_COMPLETED,this.toolCallManager.webRTCToolCallCompletedEventToToolCallCompletedPayload(u)),this.internalEventEmitter.emit(Fe.WEBRTC_TOOL_CALL_COMPLETED_EVENT_RECEIVED,u);break;case vt.TOOL_CALL_FAILED_EVENT:const f=a.data;this.publicEventEmitter.emit(oe.TOOL_CALL_FAILED,this.toolCallManager.webRTCToolCallFailedEventToToolCallFailedPayload(f)),this.internalEventEmitter.emit(Fe.WEBRTC_TOOL_CALL_FAILED_EVENT_RECEIVED,f);break;case vt.REASONING_TEXT:this.internalEventEmitter.emit(Fe.WEBRTC_REASONING_TEXT_MESSAGE_RECEIVED,a.data);break;case vt.USER_SPEECH_STARTED:this.publicEventEmitter.emit(oe.USER_SPEECH_STARTED,(r=(i=a.data)===null||i===void 0?void 0:i.user_action_correlation_id)!==null&&r!==void 0?r:"unknown");break;case vt.USER_SPEECH_ENDED:this.publicEventEmitter.emit(oe.USER_SPEECH_ENDED,(o=(n=a.data)===null||n===void 0?void 0:n.user_action_correlation_id)!==null&&o!==void 0?o:"unknown");break;default:break}}catch(a){console.error("Failed to parse data channel message:",a)}}})}requestMicrophonePermissionAsync(){return st(this,void 0,void 0,function*(){if(this.inputAudioState.permissionState!==Yt.PENDING){this.inputAudioState=Object.assign(Object.assign({},this.inputAudioState),{permissionState:Yt.PENDING}),this.publicEventEmitter.emit(oe.MIC_PERMISSION_PENDING);try{const e={echoCancellation:!0};this.audioDeviceId&&(e.deviceId={exact:this.audioDeviceId}),this.inputAudioStream=yield navigator.mediaDevices.getUserMedia({audio:e}),this.inputAudioState=Object.assign(Object.assign({},this.inputAudioState),{permissionState:Yt.GRANTED}),this.publicEventEmitter.emit(oe.MIC_PERMISSION_GRANTED),yield this.setupAudioTrack()}catch(e){console.error("Failed to get microphone permission:",e),this.inputAudioState=Object.assign(Object.assign({},this.inputAudioState),{permissionState:Yt.DENIED});const t=e instanceof Error?e.message:String(e);this.publicEventEmitter.emit(oe.MIC_PERMISSION_DENIED,t)}}})}setupAudioTrack(){return st(this,void 0,void 0,function*(){if(!this.peerConnection||!this.inputAudioStream)return;if(!this.inputAudioStream.getAudioTracks().length){console.error("StreamingClient - setupAudioTrack: stream does not have audio tracks");return}this.inputAudioState.isMuted&&this.muteAllAudioTracks();const e=this.inputAudioStream.getAudioTracks()[0],i=this.peerConnection.getSenders().find(r=>{var n;return((n=r.track)===null||n===void 0?void 0:n.kind)==="audio"||r.track===null&&r.dtmf!==null});if(i)try{yield i.replaceTrack(e)}catch(r){console.error("Failed to replace audio track:",r),this.peerConnection.addTrack(e,this.inputAudioStream)}else this.peerConnection.addTrack(e,this.inputAudioStream);this.publicEventEmitter.emit(oe.INPUT_AUDIO_STREAM_STARTED,this.inputAudioStream)})}initPeerConnectionAndSendOffer(){return st(this,void 0,void 0,function*(){if(yield this.initPeerConnection(),!this.peerConnection){console.error("StreamingClient - initPeerConnectionAndSendOffer: peer connection is not initialized");return}try{const e=yield this.peerConnection.createOffer();yield this.peerConnection.setLocalDescription(e)}catch(e){console.error("StreamingClient - initPeerConnectionAndSendOffer: error creating offer",e)}if(!this.peerConnection.localDescription)throw new Error("StreamingClient - initPeerConnectionAndSendOffer: local description is null");yield this.signallingClient.sendOffer(this.peerConnection.localDescription)})}shutdown(){return st(this,void 0,void 0,function*(){var e;if(this.showPeerConnectionStatsReport){const t=yield(e=this.peerConnection)===null||e===void 0?void 0:e.getStats();if(t){const i=yx(t,this.peerConnectionStatsReportOutputFormat);i&&console.log(i,void 0,2)}}this.statsCollectionInterval&&(clearInterval(this.statsCollectionInterval),this.statsCollectionInterval=null),this.successMetricPoller&&(clearInterval(this.successMetricPoller),this.successMetricPoller=null),this.successMetricFired=!1;try{this.inputAudioStream&&this.inputAudioStream.getTracks().forEach(t=>{t.stop()}),this.inputAudioStream=null}catch(t){console.error("StreamingClient - shutdown: error stopping input audio stream",t)}try{this.signallingClient.stop()}catch(t){console.error("StreamingClient - shutdown: error stopping signallilng",t)}this.toolCallManager.clearPendingCalls();try{this.peerConnection&&this.peerConnection.connectionState!=="closed"&&(this.peerConnection.onconnectionstatechange=null,this.peerConnection.close(),this.peerConnection=null)}catch(t){console.error("StreamingClient - shutdown: error closing peer connection",t)}})}}class Nx{constructor(e,t){this.reasoning_messages=[],this.publicEventEmitter=e,this.internalEventEmitter=t,this.internalEventEmitter.addListener(Fe.WEBRTC_REASONING_TEXT_MESSAGE_RECEIVED,this.processWebRtcReasoningTextMessageEvent.bind(this))}webRtcTextMessageEventToReasoningStreamEvent(e){return{id:`${e.role}::${e.message_id}`,content:e.content,endOfThought:e.end_of_thought,role:e.role}}processWebRtcReasoningTextMessageEvent(e){const t=this.webRtcTextMessageEventToReasoningStreamEvent(e);this.publicEventEmitter.emit(oe.REASONING_STREAM_EVENT_RECEIVED,t);const i={id:t.id,content:t.content,role:t.role},r=this.reasoning_messages.findIndex(n=>n.id===i.id);if(r!==-1){const n=this.reasoning_messages[r];n.content+=i.content,this.reasoning_messages[r]=n}else this.reasoning_messages.push(i);t.endOfThought&&this.publicEventEmitter.emit(oe.REASONING_HISTORY_UPDATED,this.reasoning_messages)}}var qt=function(s,e,t,i){function r(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(h){try{c(i.next(h))}catch(u){o(u)}}function l(h){try{c(i.throw(h))}catch(u){o(u)}}function c(h){h.done?n(h.value):r(h.value).then(a,l)}c((i=i.apply(s,e||[])).next())})};class Fx{constructor(e,t,i){var r,n,o,a,l;this.inputAudioState={isMuted:!1,permissionState:Yt.NOT_REQUESTED},this.sessionId=null,this.organizationId=null,this.streamingClient=null,this._isStreaming=!1;const c=this.validateClientConfig(e,t,i);if(c)throw new Ne(c,$e.CLIENT_ERROR_CODE_CONFIGURATION_ERROR,400);this.personaConfig=t,this.clientOptions=i,(!((r=i==null?void 0:i.api)===null||r===void 0)&&r.baseUrl||!((n=i==null?void 0:i.api)===null||n===void 0)&&n.apiVersion)&&mx(i.api.baseUrl||Pu,i.api.apiVersion||Io),!((a=(o=i==null?void 0:i.api)===null||o===void 0?void 0:o.apiGateway)===null||a===void 0)&&a.enabled&&gx(i.api.apiGateway),!((l=i==null?void 0:i.metrics)===null||l===void 0)&&l.disableClientMetrics&&_x(!0),this.publicEventEmitter=new Mx,this.internalEventEmitter=new Ax,this.toolCallManager=new Fu(this.publicEventEmitter),this.apiClient=new Tx(e,i==null?void 0:i.apiKey,i==null?void 0:i.api),this.messageHistoryClient=new Rx(this.publicEventEmitter,this.internalEventEmitter),this.reasoningHistoryClient=new Nx(this.publicEventEmitter,this.internalEventEmitter)}decodeJwt(e){try{const t=e.split(".")[1],i=ux.Buffer.from(t,"base64").toString("utf8");return JSON.parse(i)}catch{throw new Error("Invalid session token format")}}validateClientConfig(e,t,i){var r,n;if(!e&&!(i!=null&&i.apiKey))return"Either sessionToken or apiKey must be provided";if(i!=null&&i.apiKey&&e)return"Only one of sessionToken or apiKey should be used";const o=bx((r=i==null?void 0:i.api)===null||r===void 0?void 0:r.apiGateway);if(o)return o;if(e){const a=this.decodeJwt(e);this.organizationId=a.accountId,Li({organizationId:this.organizationId});const l=(n=a.type)===null||n===void 0?void 0:n.toLowerCase();if(l==="legacy")return"Legacy session tokens are no longer supported. Please define your persona when creating your session token. See https://docs.anam.ai/resources/migrating-legacy for more information.";if((l==="ephemeral"||l==="stateful")&&t)return"This session token already contains a persona configuration. Please remove the personaConfig parameter."}else if(!t)return"Missing persona config. Persona configuration must be provided when using apiKey";if(i!=null&&i.voiceDetection){if(i.disableInputAudio)return"Voice detection is disabled because input audio is disabled. Please set disableInputAudio to false to enable voice detection.";if(i.voiceDetection.endOfSpeechSensitivity!==void 0){if(typeof i.voiceDetection.endOfSpeechSensitivity!="number")return"End of speech sensitivity must be a number";if(i.voiceDetection.endOfSpeechSensitivity<0||i.voiceDetection.endOfSpeechSensitivity>1)return"End of speech sensitivity must be between 0 and 1"}}}buildStartSessionOptionsForClient(){var e;const t={};if(!((e=this.clientOptions)===null||e===void 0)&&e.voiceDetection&&(t.voiceDetection=this.clientOptions.voiceDetection),Object.keys(t).length!==0)return t}startSession(e){return qt(this,void 0,void 0,function*(){var t,i,r,n,o,a,l,c,h,u,f,d;const g=this.personaConfig,_=this.buildStartSessionOptionsForClient(),y=yield this.apiClient.startSession(g,_),{sessionId:x,clientConfig:v,engineHost:C,engineProtocol:E,signallingEndpoint:A}=y,{heartbeatIntervalSeconds:w,maxWsReconnectionAttempts:R,iceServers:D}=v;this.sessionId=x,Li({sessionId:this.sessionId});const B=!((t=this.clientOptions)===null||t===void 0)&&t.iceServers?this.clientOptions.iceServers:D;try{this.streamingClient=new Dx(x,{engine:{baseUrl:`${E}://${C}`},signalling:{heartbeatIntervalSeconds:w,maxWsReconnectionAttempts:R,url:{baseUrl:C,protocol:E,signallingPath:A}},iceServers:B,inputAudio:{inputAudioState:this.inputAudioState,userProvidedMediaStream:!((i=this.clientOptions)===null||i===void 0)&&i.disableInputAudio?void 0:e,audioDeviceId:(r=this.clientOptions)===null||r===void 0?void 0:r.audioDeviceId,disableInputAudio:(n=this.clientOptions)===null||n===void 0?void 0:n.disableInputAudio},apiGateway:(a=(o=this.clientOptions)===null||o===void 0?void 0:o.api)===null||a===void 0?void 0:a.apiGateway,metrics:{showPeerConnectionStatsReport:(h=(c=(l=this.clientOptions)===null||l===void 0?void 0:l.metrics)===null||c===void 0?void 0:c.showPeerConnectionStatsReport)!==null&&h!==void 0?h:!1,peerConnectionStatsReportOutputFormat:(d=(f=(u=this.clientOptions)===null||u===void 0?void 0:u.metrics)===null||f===void 0?void 0:f.peerConnectionStatsReportOutputFormat)!==null&&d!==void 0?d:"console"}},this.publicEventEmitter,this.internalEventEmitter,this.toolCallManager)}catch(k){throw Li({sessionId:null}),new Ne("Failed to initialize streaming client",$e.CLIENT_ERROR_CODE_SERVER_ERROR,500,{cause:k instanceof Error?k.message:String(k),sessionId:x})}return x})}startSessionIfNeeded(e){return qt(this,void 0,void 0,function*(){if((!this.sessionId||!this.streamingClient)&&(yield this.startSession(e),!this.sessionId||!this.streamingClient))throw new Ne("Session ID or streaming client is not available after starting session",$e.CLIENT_ERROR_CODE_SERVER_ERROR,500,{cause:"Failed to initialize session properly"})})}stream(e){return qt(this,void 0,void 0,function*(){var t;if(this._isStreaming)throw new Error("Already streaming");const i=Ou();return Li({attemptCorrelationId:i,sessionId:null}),ui(Nt.CLIENT_METRIC_MEASUREMENT_SESSION_ATTEMPT,"1"),!((t=this.clientOptions)===null||t===void 0)&&t.disableInputAudio&&e&&console.warn("AnamClient:Input audio is disabled. User provided audio stream will be ignored."),yield this.startSessionIfNeeded(e),this._isStreaming=!0,new Promise(r=>{var n;const o=[];let a=!1,l=!1;this.publicEventEmitter.addListener(oe.VIDEO_STREAM_STARTED,c=>{o.push(c),a=!0,l&&r(o)}),this.publicEventEmitter.addListener(oe.AUDIO_STREAM_STARTED,c=>{o.push(c),l=!0,a&&r(o)}),(n=this.streamingClient)===null||n===void 0||n.startConnection()})})}streamToVideoAndAudioElements(e,t,i){return qt(this,void 0,void 0,function*(){console.warn("AnamClient: streamToVideoAndAudioElements is deprecated. To avoid possible audio issues, please use streamToVideoElement instead."),yield this.streamToVideoElement(e,i)})}streamToVideoElement(e,t){return qt(this,void 0,void 0,function*(){var i;const r=Ou();Li({attemptCorrelationId:r,sessionId:null}),ui(Nt.CLIENT_METRIC_MEASUREMENT_SESSION_ATTEMPT,"1"),!((i=this.clientOptions)===null||i===void 0)&&i.disableInputAudio&&t&&console.warn("AnamClient:Input audio is disabled. User provided audio stream will be ignored.");try{yield this.startSessionIfNeeded(t)}catch(n){throw n instanceof Ne?n:new Ne("Failed to start session",$e.CLIENT_ERROR_CODE_SERVER_ERROR,500,{cause:n instanceof Error?n.message:String(n),sessionId:this.sessionId})}if(this._isStreaming)throw new Error("Already streaming");if(this._isStreaming=!0,!this.streamingClient)throw new Error("Failed to stream: streaming client is not available");this.streamingClient.setMediaStreamTargetById(e),this.streamingClient.startConnection()})}talk(e){return qt(this,void 0,void 0,function*(){if(!this.streamingClient)throw new Error("Failed to send talk command: session is not started. Have you called startSession?");if(!this._isStreaming)throw new Error("Failed to send talk command: not currently streaming. Have you called stream?");yield this.streamingClient.sendTalkCommand(e)})}sendDataMessage(e){if(this.streamingClient)this.streamingClient.sendDataMessage(e);else throw new Error("Failed to send message: session is not started.")}sendUserMessage(e){if(!this._isStreaming)throw console.warn("AnamClient: Not currently streaming. User message will not be sent."),new Error("Failed to send user message: not currently streaming");const t=this.getActiveSessionId();if(!t)throw new Error("Failed to send user message: no active session");const i=new Date().toISOString().replace("Z",""),r=JSON.stringify({content:e,timestamp:i,session_id:t,message_type:"speech"});this.sendDataMessage(r)}interruptPersona(){if(!this._isStreaming)throw new Error("Failed to send interrupt command: not currently streaming");const e=this.getActiveSessionId();if(!e)throw new Error("Failed to send interrupt command: no active session");const t=JSON.stringify({message_type:"interrupt",session_id:e,timestamp:new Date().toISOString()});this.sendDataMessage(t)}addContext(e){if(!this._isStreaming)throw new Error("Failed to add context: not currently streaming");const t=this.getActiveSessionId();if(!t)throw new Error("Failed to add context: no active session");const i=JSON.stringify({message_type:"context",session_id:t,content:e});this.sendDataMessage(i)}stopStreaming(){return qt(this,void 0,void 0,function*(){this.streamingClient&&(this.publicEventEmitter.emit(oe.CONNECTION_CLOSED,Kt.NORMAL),yield this.streamingClient.stopConnection(),this.streamingClient=null,this.sessionId=null,Li({attemptCorrelationId:null,sessionId:null,organizationId:this.organizationId}),this._isStreaming=!1)})}isStreaming(){return this._isStreaming}setPersonaConfig(e){this.personaConfig=e}getPersonaConfig(){return this.personaConfig}getInputAudioState(){var e;return!((e=this.clientOptions)===null||e===void 0)&&e.disableInputAudio&&console.warn("AnamClient: Audio state will not be used because input audio is disabled."),this.streamingClient&&(this.inputAudioState=this.streamingClient.getInputAudioState()),this.inputAudioState}muteInputAudio(){var e,t;return!((e=this.clientOptions)===null||e===void 0)&&e.disableInputAudio&&console.warn("AnamClient: Input audio is disabled. Muting input audio will have no effect."),this.streamingClient&&!(!((t=this.clientOptions)===null||t===void 0)&&t.disableInputAudio)?this.inputAudioState=this.streamingClient.muteInputAudio():this.inputAudioState=Object.assign(Object.assign({},this.inputAudioState),{isMuted:!0}),this.inputAudioState}unmuteInputAudio(){var e,t;return!((e=this.clientOptions)===null||e===void 0)&&e.disableInputAudio&&console.warn("AnamClient: Input audio is disabled. Unmuting input audio will have no effect."),this.streamingClient&&!(!((t=this.clientOptions)===null||t===void 0)&&t.disableInputAudio)?this.inputAudioState=this.streamingClient.unmuteInputAudio():this.inputAudioState=Object.assign(Object.assign({},this.inputAudioState),{isMuted:!1}),this.inputAudioState}changeAudioInputDevice(e){return qt(this,void 0,void 0,function*(){var t;if(!((t=this.clientOptions)===null||t===void 0)&&t.disableInputAudio)throw new Error("AnamClient: Cannot change audio input device because input audio is disabled.");if(!this._isStreaming)throw new Error("AnamClient: Cannot change audio input device while not streaming. Start streaming first.");if(!this.streamingClient)throw new Error("AnamClient: Cannot change audio input device because streaming client is not available. Start streaming first.");yield this.streamingClient.changeAudioInputDevice(e)})}createTalkMessageStream(e){if(!this.streamingClient)throw new Error("Failed to start talk message stream: session is not started.");if(e&&e.trim()==="")throw new Error("Failed to start talk message stream: correlationId is empty");return this.streamingClient.startTalkMessageStream(e)}createAgentAudioInputStream(e){if(!this.streamingClient)throw new Error("Failed to create agent audio input stream: session is not started.");return this.streamingClient.createAgentAudioInputStream(e)}addListener(e,t){this.publicEventEmitter.addListener(e,t)}removeListener(e,t){this.publicEventEmitter.removeListener(e,t)}getActiveSessionId(){return this.sessionId}registerToolCallHandler(e,t){return this.toolCallManager.registerHandler(e,t)}}const Lx=(s,e)=>new Fx(s,void 0,e);let Lu=0;class Gx{constructor(e){this.onVideoReady=null,this.onConnected=null,this.onDisconnected=null,this.onTalkStreamInterrupted=null,this.onError=null,this.audioInputStream=null,this.videoElement=null,this.videoWrapper=null,this._connected=!1,this._closing=!1,this.client=Lx(e.sessionToken,{disableInputAudio:!0,metrics:{disableClientMetrics:!0}})}get isConnected(){return this._connected}get videoEl(){return this.videoElement}async connect(){var e;try{const t=`anam-avatar-video-${++Lu}`;if(!document.getElementById("hs-avatar-clip")){const i=document.createElementNS("http://www.w3.org/2000/svg","svg");i.setAttribute("width","0"),i.setAttribute("height","0"),i.style.position="absolute",i.id="hs-avatar-clip",i.innerHTML='<defs><clipPath id="hs-rounded-top" clipPathUnits="objectBoundingBox"><path d="M0.057,0 H0.943 Q1,0 1,0.04 V1 H0 V0.04 Q0,0 0.057,0 Z"/></clipPath></defs>',document.body.appendChild(i)}this.videoWrapper=document.createElement("div"),this.videoWrapper.id=`anam-avatar-wrapper-${Lu}`,this.videoWrapper.style.cssText=`
|
|
937
|
+
*/var Ru;function hx(){return Ru||(Ru=1,(function(s){const e=lx(),t=cx(),i=typeof Symbol=="function"&&typeof Symbol.for=="function"?Symbol.for("nodejs.util.inspect.custom"):null;s.Buffer=a,s.SlowBuffer=v,s.INSPECT_MAX_BYTES=50;const r=2147483647;s.kMaxLength=r,a.TYPED_ARRAY_SUPPORT=n(),!a.TYPED_ARRAY_SUPPORT&&typeof console<"u"&&typeof console.error=="function"&&console.error("This browser lacks typed array (Uint8Array) support which is required by `buffer` v5.x. Use `buffer` v4.x if you require old browser support.");function n(){try{const b=new Uint8Array(1),p={foo:function(){return 42}};return Object.setPrototypeOf(p,Uint8Array.prototype),Object.setPrototypeOf(b,p),b.foo()===42}catch{return!1}}Object.defineProperty(a.prototype,"parent",{enumerable:!0,get:function(){if(a.isBuffer(this))return this.buffer}}),Object.defineProperty(a.prototype,"offset",{enumerable:!0,get:function(){if(a.isBuffer(this))return this.byteOffset}});function o(b){if(b>r)throw new RangeError('The value "'+b+'" is invalid for option "size"');const p=new Uint8Array(b);return Object.setPrototypeOf(p,a.prototype),p}function a(b,p,m){if(typeof b=="number"){if(typeof p=="string")throw new TypeError('The "string" argument must be of type string. Received type number');return u(b)}return l(b,p,m)}a.poolSize=8192;function l(b,p,m){if(typeof b=="string")return f(b,p);if(ArrayBuffer.isView(b))return g(b);if(b==null)throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof b);if(tt(b,ArrayBuffer)||b&&tt(b.buffer,ArrayBuffer)||typeof SharedArrayBuffer<"u"&&(tt(b,SharedArrayBuffer)||b&&tt(b.buffer,SharedArrayBuffer)))return _(b,p,m);if(typeof b=="number")throw new TypeError('The "value" argument must not be of type number. Received type number');const S=b.valueOf&&b.valueOf();if(S!=null&&S!==b)return a.from(S,p,m);const T=y(b);if(T)return T;if(typeof Symbol<"u"&&Symbol.toPrimitive!=null&&typeof b[Symbol.toPrimitive]=="function")return a.from(b[Symbol.toPrimitive]("string"),p,m);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof b)}a.from=function(b,p,m){return l(b,p,m)},Object.setPrototypeOf(a.prototype,Uint8Array.prototype),Object.setPrototypeOf(a,Uint8Array);function c(b){if(typeof b!="number")throw new TypeError('"size" argument must be of type number');if(b<0)throw new RangeError('The value "'+b+'" is invalid for option "size"')}function h(b,p,m){return c(b),b<=0?o(b):p!==void 0?typeof m=="string"?o(b).fill(p,m):o(b).fill(p):o(b)}a.alloc=function(b,p,m){return h(b,p,m)};function u(b){return c(b),o(b<0?0:x(b)|0)}a.allocUnsafe=function(b){return u(b)},a.allocUnsafeSlow=function(b){return u(b)};function f(b,p){if((typeof p!="string"||p==="")&&(p="utf8"),!a.isEncoding(p))throw new TypeError("Unknown encoding: "+p);const m=C(b,p)|0;let S=o(m);const T=S.write(b,p);return T!==m&&(S=S.slice(0,T)),S}function d(b){const p=b.length<0?0:x(b.length)|0,m=o(p);for(let S=0;S<p;S+=1)m[S]=b[S]&255;return m}function g(b){if(tt(b,Uint8Array)){const p=new Uint8Array(b);return _(p.buffer,p.byteOffset,p.byteLength)}return d(b)}function _(b,p,m){if(p<0||b.byteLength<p)throw new RangeError('"offset" is outside of buffer bounds');if(b.byteLength<p+(m||0))throw new RangeError('"length" is outside of buffer bounds');let S;return p===void 0&&m===void 0?S=new Uint8Array(b):m===void 0?S=new Uint8Array(b,p):S=new Uint8Array(b,p,m),Object.setPrototypeOf(S,a.prototype),S}function y(b){if(a.isBuffer(b)){const p=x(b.length)|0,m=o(p);return m.length===0||b.copy(m,0,0,p),m}if(b.length!==void 0)return typeof b.length!="number"||Ki(b.length)?o(0):d(b);if(b.type==="Buffer"&&Array.isArray(b.data))return d(b.data)}function x(b){if(b>=r)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+r.toString(16)+" bytes");return b|0}function v(b){return+b!=b&&(b=0),a.alloc(+b)}a.isBuffer=function(p){return p!=null&&p._isBuffer===!0&&p!==a.prototype},a.compare=function(p,m){if(tt(p,Uint8Array)&&(p=a.from(p,p.offset,p.byteLength)),tt(m,Uint8Array)&&(m=a.from(m,m.offset,m.byteLength)),!a.isBuffer(p)||!a.isBuffer(m))throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(p===m)return 0;let S=p.length,T=m.length;for(let M=0,P=Math.min(S,T);M<P;++M)if(p[M]!==m[M]){S=p[M],T=m[M];break}return S<T?-1:T<S?1:0},a.isEncoding=function(p){switch(String(p).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"latin1":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}},a.concat=function(p,m){if(!Array.isArray(p))throw new TypeError('"list" argument must be an Array of Buffers');if(p.length===0)return a.alloc(0);let S;if(m===void 0)for(m=0,S=0;S<p.length;++S)m+=p[S].length;const T=a.allocUnsafe(m);let M=0;for(S=0;S<p.length;++S){let P=p[S];if(tt(P,Uint8Array))M+P.length>T.length?(a.isBuffer(P)||(P=a.from(P)),P.copy(T,M)):Uint8Array.prototype.set.call(T,P,M);else if(a.isBuffer(P))P.copy(T,M);else throw new TypeError('"list" argument must be an Array of Buffers');M+=P.length}return T};function C(b,p){if(a.isBuffer(b))return b.length;if(ArrayBuffer.isView(b)||tt(b,ArrayBuffer))return b.byteLength;if(typeof b!="string")throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof b);const m=b.length,S=arguments.length>2&&arguments[2]===!0;if(!S&&m===0)return 0;let T=!1;for(;;)switch(p){case"ascii":case"latin1":case"binary":return m;case"utf8":case"utf-8":return St(b).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return m*2;case"hex":return m>>>1;case"base64":return Ft(b).length;default:if(T)return S?-1:St(b).length;p=(""+p).toLowerCase(),T=!0}}a.byteLength=C;function E(b,p,m){let S=!1;if((p===void 0||p<0)&&(p=0),p>this.length||((m===void 0||m>this.length)&&(m=this.length),m<=0)||(m>>>=0,p>>>=0,m<=p))return"";for(b||(b="utf8");;)switch(b){case"hex":return N(this,p,m);case"utf8":case"utf-8":return W(this,p,m);case"ascii":return G(this,p,m);case"latin1":case"binary":return X(this,p,m);case"base64":return U(this,p,m);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return V(this,p,m);default:if(S)throw new TypeError("Unknown encoding: "+b);b=(b+"").toLowerCase(),S=!0}}a.prototype._isBuffer=!0;function A(b,p,m){const S=b[p];b[p]=b[m],b[m]=S}a.prototype.swap16=function(){const p=this.length;if(p%2!==0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(let m=0;m<p;m+=2)A(this,m,m+1);return this},a.prototype.swap32=function(){const p=this.length;if(p%4!==0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(let m=0;m<p;m+=4)A(this,m,m+3),A(this,m+1,m+2);return this},a.prototype.swap64=function(){const p=this.length;if(p%8!==0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(let m=0;m<p;m+=8)A(this,m,m+7),A(this,m+1,m+6),A(this,m+2,m+5),A(this,m+3,m+4);return this},a.prototype.toString=function(){const p=this.length;return p===0?"":arguments.length===0?W(this,0,p):E.apply(this,arguments)},a.prototype.toLocaleString=a.prototype.toString,a.prototype.equals=function(p){if(!a.isBuffer(p))throw new TypeError("Argument must be a Buffer");return this===p?!0:a.compare(this,p)===0},a.prototype.inspect=function(){let p="";const m=s.INSPECT_MAX_BYTES;return p=this.toString("hex",0,m).replace(/(.{2})/g,"$1 ").trim(),this.length>m&&(p+=" ... "),"<Buffer "+p+">"},i&&(a.prototype[i]=a.prototype.inspect),a.prototype.compare=function(p,m,S,T,M){if(tt(p,Uint8Array)&&(p=a.from(p,p.offset,p.byteLength)),!a.isBuffer(p))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof p);if(m===void 0&&(m=0),S===void 0&&(S=p?p.length:0),T===void 0&&(T=0),M===void 0&&(M=this.length),m<0||S>p.length||T<0||M>this.length)throw new RangeError("out of range index");if(T>=M&&m>=S)return 0;if(T>=M)return-1;if(m>=S)return 1;if(m>>>=0,S>>>=0,T>>>=0,M>>>=0,this===p)return 0;let P=M-T,re=S-m;const Pe=Math.min(P,re),we=this.slice(T,M),ke=p.slice(m,S);for(let Se=0;Se<Pe;++Se)if(we[Se]!==ke[Se]){P=we[Se],re=ke[Se];break}return P<re?-1:re<P?1:0};function w(b,p,m,S,T){if(b.length===0)return-1;if(typeof m=="string"?(S=m,m=0):m>2147483647?m=2147483647:m<-2147483648&&(m=-2147483648),m=+m,Ki(m)&&(m=T?0:b.length-1),m<0&&(m=b.length+m),m>=b.length){if(T)return-1;m=b.length-1}else if(m<0)if(T)m=0;else return-1;if(typeof p=="string"&&(p=a.from(p,S)),a.isBuffer(p))return p.length===0?-1:R(b,p,m,S,T);if(typeof p=="number")return p=p&255,typeof Uint8Array.prototype.indexOf=="function"?T?Uint8Array.prototype.indexOf.call(b,p,m):Uint8Array.prototype.lastIndexOf.call(b,p,m):R(b,[p],m,S,T);throw new TypeError("val must be string, number or Buffer")}function R(b,p,m,S,T){let M=1,P=b.length,re=p.length;if(S!==void 0&&(S=String(S).toLowerCase(),S==="ucs2"||S==="ucs-2"||S==="utf16le"||S==="utf-16le")){if(b.length<2||p.length<2)return-1;M=2,P/=2,re/=2,m/=2}function Pe(ke,Se){return M===1?ke[Se]:ke.readUInt16BE(Se*M)}let we;if(T){let ke=-1;for(we=m;we<P;we++)if(Pe(b,we)===Pe(p,ke===-1?0:we-ke)){if(ke===-1&&(ke=we),we-ke+1===re)return ke*M}else ke!==-1&&(we-=we-ke),ke=-1}else for(m+re>P&&(m=P-re),we=m;we>=0;we--){let ke=!0;for(let Se=0;Se<re;Se++)if(Pe(b,we+Se)!==Pe(p,Se)){ke=!1;break}if(ke)return we}return-1}a.prototype.includes=function(p,m,S){return this.indexOf(p,m,S)!==-1},a.prototype.indexOf=function(p,m,S){return w(this,p,m,S,!0)},a.prototype.lastIndexOf=function(p,m,S){return w(this,p,m,S,!1)};function D(b,p,m,S){m=Number(m)||0;const T=b.length-m;S?(S=Number(S),S>T&&(S=T)):S=T;const M=p.length;S>M/2&&(S=M/2);let P;for(P=0;P<S;++P){const re=parseInt(p.substr(P*2,2),16);if(Ki(re))return P;b[m+P]=re}return P}function B(b,p,m,S){return ft(St(p,b.length-m),b,m,S)}function k(b,p,m,S){return ft(fi(p),b,m,S)}function O(b,p,m,S){return ft(Ft(p),b,m,S)}function L(b,p,m,S){return ft(Yi(p,b.length-m),b,m,S)}a.prototype.write=function(p,m,S,T){if(m===void 0)T="utf8",S=this.length,m=0;else if(S===void 0&&typeof m=="string")T=m,S=this.length,m=0;else if(isFinite(m))m=m>>>0,isFinite(S)?(S=S>>>0,T===void 0&&(T="utf8")):(T=S,S=void 0);else throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");const M=this.length-m;if((S===void 0||S>M)&&(S=M),p.length>0&&(S<0||m<0)||m>this.length)throw new RangeError("Attempt to write outside buffer bounds");T||(T="utf8");let P=!1;for(;;)switch(T){case"hex":return D(this,p,m,S);case"utf8":case"utf-8":return B(this,p,m,S);case"ascii":case"latin1":case"binary":return k(this,p,m,S);case"base64":return O(this,p,m,S);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return L(this,p,m,S);default:if(P)throw new TypeError("Unknown encoding: "+T);T=(""+T).toLowerCase(),P=!0}},a.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};function U(b,p,m){return p===0&&m===b.length?e.fromByteArray(b):e.fromByteArray(b.slice(p,m))}function W(b,p,m){m=Math.min(b.length,m);const S=[];let T=p;for(;T<m;){const M=b[T];let P=null,re=M>239?4:M>223?3:M>191?2:1;if(T+re<=m){let Pe,we,ke,Se;switch(re){case 1:M<128&&(P=M);break;case 2:Pe=b[T+1],(Pe&192)===128&&(Se=(M&31)<<6|Pe&63,Se>127&&(P=Se));break;case 3:Pe=b[T+1],we=b[T+2],(Pe&192)===128&&(we&192)===128&&(Se=(M&15)<<12|(Pe&63)<<6|we&63,Se>2047&&(Se<55296||Se>57343)&&(P=Se));break;case 4:Pe=b[T+1],we=b[T+2],ke=b[T+3],(Pe&192)===128&&(we&192)===128&&(ke&192)===128&&(Se=(M&15)<<18|(Pe&63)<<12|(we&63)<<6|ke&63,Se>65535&&Se<1114112&&(P=Se))}}P===null?(P=65533,re=1):P>65535&&(P-=65536,S.push(P>>>10&1023|55296),P=56320|P&1023),S.push(P),T+=re}return F(S)}const te=4096;function F(b){const p=b.length;if(p<=te)return String.fromCharCode.apply(String,b);let m="",S=0;for(;S<p;)m+=String.fromCharCode.apply(String,b.slice(S,S+=te));return m}function G(b,p,m){let S="";m=Math.min(b.length,m);for(let T=p;T<m;++T)S+=String.fromCharCode(b[T]&127);return S}function X(b,p,m){let S="";m=Math.min(b.length,m);for(let T=p;T<m;++T)S+=String.fromCharCode(b[T]);return S}function N(b,p,m){const S=b.length;(!p||p<0)&&(p=0),(!m||m<0||m>S)&&(m=S);let T="";for(let M=p;M<m;++M)T+=wr[b[M]];return T}function V(b,p,m){const S=b.slice(p,m);let T="";for(let M=0;M<S.length-1;M+=2)T+=String.fromCharCode(S[M]+S[M+1]*256);return T}a.prototype.slice=function(p,m){const S=this.length;p=~~p,m=m===void 0?S:~~m,p<0?(p+=S,p<0&&(p=0)):p>S&&(p=S),m<0?(m+=S,m<0&&(m=0)):m>S&&(m=S),m<p&&(m=p);const T=this.subarray(p,m);return Object.setPrototypeOf(T,a.prototype),T};function K(b,p,m){if(b%1!==0||b<0)throw new RangeError("offset is not uint");if(b+p>m)throw new RangeError("Trying to access beyond buffer length")}a.prototype.readUintLE=a.prototype.readUIntLE=function(p,m,S){p=p>>>0,m=m>>>0,S||K(p,m,this.length);let T=this[p],M=1,P=0;for(;++P<m&&(M*=256);)T+=this[p+P]*M;return T},a.prototype.readUintBE=a.prototype.readUIntBE=function(p,m,S){p=p>>>0,m=m>>>0,S||K(p,m,this.length);let T=this[p+--m],M=1;for(;m>0&&(M*=256);)T+=this[p+--m]*M;return T},a.prototype.readUint8=a.prototype.readUInt8=function(p,m){return p=p>>>0,m||K(p,1,this.length),this[p]},a.prototype.readUint16LE=a.prototype.readUInt16LE=function(p,m){return p=p>>>0,m||K(p,2,this.length),this[p]|this[p+1]<<8},a.prototype.readUint16BE=a.prototype.readUInt16BE=function(p,m){return p=p>>>0,m||K(p,2,this.length),this[p]<<8|this[p+1]},a.prototype.readUint32LE=a.prototype.readUInt32LE=function(p,m){return p=p>>>0,m||K(p,4,this.length),(this[p]|this[p+1]<<8|this[p+2]<<16)+this[p+3]*16777216},a.prototype.readUint32BE=a.prototype.readUInt32BE=function(p,m){return p=p>>>0,m||K(p,4,this.length),this[p]*16777216+(this[p+1]<<16|this[p+2]<<8|this[p+3])},a.prototype.readBigUInt64LE=pt(function(p){p=p>>>0,Re(p,"offset");const m=this[p],S=this[p+7];(m===void 0||S===void 0)&&pe(p,this.length-8);const T=m+this[++p]*2**8+this[++p]*2**16+this[++p]*2**24,M=this[++p]+this[++p]*2**8+this[++p]*2**16+S*2**24;return BigInt(T)+(BigInt(M)<<BigInt(32))}),a.prototype.readBigUInt64BE=pt(function(p){p=p>>>0,Re(p,"offset");const m=this[p],S=this[p+7];(m===void 0||S===void 0)&&pe(p,this.length-8);const T=m*2**24+this[++p]*2**16+this[++p]*2**8+this[++p],M=this[++p]*2**24+this[++p]*2**16+this[++p]*2**8+S;return(BigInt(T)<<BigInt(32))+BigInt(M)}),a.prototype.readIntLE=function(p,m,S){p=p>>>0,m=m>>>0,S||K(p,m,this.length);let T=this[p],M=1,P=0;for(;++P<m&&(M*=256);)T+=this[p+P]*M;return M*=128,T>=M&&(T-=Math.pow(2,8*m)),T},a.prototype.readIntBE=function(p,m,S){p=p>>>0,m=m>>>0,S||K(p,m,this.length);let T=m,M=1,P=this[p+--T];for(;T>0&&(M*=256);)P+=this[p+--T]*M;return M*=128,P>=M&&(P-=Math.pow(2,8*m)),P},a.prototype.readInt8=function(p,m){return p=p>>>0,m||K(p,1,this.length),this[p]&128?(255-this[p]+1)*-1:this[p]},a.prototype.readInt16LE=function(p,m){p=p>>>0,m||K(p,2,this.length);const S=this[p]|this[p+1]<<8;return S&32768?S|4294901760:S},a.prototype.readInt16BE=function(p,m){p=p>>>0,m||K(p,2,this.length);const S=this[p+1]|this[p]<<8;return S&32768?S|4294901760:S},a.prototype.readInt32LE=function(p,m){return p=p>>>0,m||K(p,4,this.length),this[p]|this[p+1]<<8|this[p+2]<<16|this[p+3]<<24},a.prototype.readInt32BE=function(p,m){return p=p>>>0,m||K(p,4,this.length),this[p]<<24|this[p+1]<<16|this[p+2]<<8|this[p+3]},a.prototype.readBigInt64LE=pt(function(p){p=p>>>0,Re(p,"offset");const m=this[p],S=this[p+7];(m===void 0||S===void 0)&&pe(p,this.length-8);const T=this[p+4]+this[p+5]*2**8+this[p+6]*2**16+(S<<24);return(BigInt(T)<<BigInt(32))+BigInt(m+this[++p]*2**8+this[++p]*2**16+this[++p]*2**24)}),a.prototype.readBigInt64BE=pt(function(p){p=p>>>0,Re(p,"offset");const m=this[p],S=this[p+7];(m===void 0||S===void 0)&&pe(p,this.length-8);const T=(m<<24)+this[++p]*2**16+this[++p]*2**8+this[++p];return(BigInt(T)<<BigInt(32))+BigInt(this[++p]*2**24+this[++p]*2**16+this[++p]*2**8+S)}),a.prototype.readFloatLE=function(p,m){return p=p>>>0,m||K(p,4,this.length),t.read(this,p,!0,23,4)},a.prototype.readFloatBE=function(p,m){return p=p>>>0,m||K(p,4,this.length),t.read(this,p,!1,23,4)},a.prototype.readDoubleLE=function(p,m){return p=p>>>0,m||K(p,8,this.length),t.read(this,p,!0,52,8)},a.prototype.readDoubleBE=function(p,m){return p=p>>>0,m||K(p,8,this.length),t.read(this,p,!1,52,8)};function H(b,p,m,S,T,M){if(!a.isBuffer(b))throw new TypeError('"buffer" argument must be a Buffer instance');if(p>T||p<M)throw new RangeError('"value" argument is out of bounds');if(m+S>b.length)throw new RangeError("Index out of range")}a.prototype.writeUintLE=a.prototype.writeUIntLE=function(p,m,S,T){if(p=+p,m=m>>>0,S=S>>>0,!T){const re=Math.pow(2,8*S)-1;H(this,p,m,S,re,0)}let M=1,P=0;for(this[m]=p&255;++P<S&&(M*=256);)this[m+P]=p/M&255;return m+S},a.prototype.writeUintBE=a.prototype.writeUIntBE=function(p,m,S,T){if(p=+p,m=m>>>0,S=S>>>0,!T){const re=Math.pow(2,8*S)-1;H(this,p,m,S,re,0)}let M=S-1,P=1;for(this[m+M]=p&255;--M>=0&&(P*=256);)this[m+M]=p/P&255;return m+S},a.prototype.writeUint8=a.prototype.writeUInt8=function(p,m,S){return p=+p,m=m>>>0,S||H(this,p,m,1,255,0),this[m]=p&255,m+1},a.prototype.writeUint16LE=a.prototype.writeUInt16LE=function(p,m,S){return p=+p,m=m>>>0,S||H(this,p,m,2,65535,0),this[m]=p&255,this[m+1]=p>>>8,m+2},a.prototype.writeUint16BE=a.prototype.writeUInt16BE=function(p,m,S){return p=+p,m=m>>>0,S||H(this,p,m,2,65535,0),this[m]=p>>>8,this[m+1]=p&255,m+2},a.prototype.writeUint32LE=a.prototype.writeUInt32LE=function(p,m,S){return p=+p,m=m>>>0,S||H(this,p,m,4,4294967295,0),this[m+3]=p>>>24,this[m+2]=p>>>16,this[m+1]=p>>>8,this[m]=p&255,m+4},a.prototype.writeUint32BE=a.prototype.writeUInt32BE=function(p,m,S){return p=+p,m=m>>>0,S||H(this,p,m,4,4294967295,0),this[m]=p>>>24,this[m+1]=p>>>16,this[m+2]=p>>>8,this[m+3]=p&255,m+4};function $(b,p,m,S,T){le(p,S,T,b,m,7);let M=Number(p&BigInt(4294967295));b[m++]=M,M=M>>8,b[m++]=M,M=M>>8,b[m++]=M,M=M>>8,b[m++]=M;let P=Number(p>>BigInt(32)&BigInt(4294967295));return b[m++]=P,P=P>>8,b[m++]=P,P=P>>8,b[m++]=P,P=P>>8,b[m++]=P,m}function se(b,p,m,S,T){le(p,S,T,b,m,7);let M=Number(p&BigInt(4294967295));b[m+7]=M,M=M>>8,b[m+6]=M,M=M>>8,b[m+5]=M,M=M>>8,b[m+4]=M;let P=Number(p>>BigInt(32)&BigInt(4294967295));return b[m+3]=P,P=P>>8,b[m+2]=P,P=P>>8,b[m+1]=P,P=P>>8,b[m]=P,m+8}a.prototype.writeBigUInt64LE=pt(function(p,m=0){return $(this,p,m,BigInt(0),BigInt("0xffffffffffffffff"))}),a.prototype.writeBigUInt64BE=pt(function(p,m=0){return se(this,p,m,BigInt(0),BigInt("0xffffffffffffffff"))}),a.prototype.writeIntLE=function(p,m,S,T){if(p=+p,m=m>>>0,!T){const Pe=Math.pow(2,8*S-1);H(this,p,m,S,Pe-1,-Pe)}let M=0,P=1,re=0;for(this[m]=p&255;++M<S&&(P*=256);)p<0&&re===0&&this[m+M-1]!==0&&(re=1),this[m+M]=(p/P>>0)-re&255;return m+S},a.prototype.writeIntBE=function(p,m,S,T){if(p=+p,m=m>>>0,!T){const Pe=Math.pow(2,8*S-1);H(this,p,m,S,Pe-1,-Pe)}let M=S-1,P=1,re=0;for(this[m+M]=p&255;--M>=0&&(P*=256);)p<0&&re===0&&this[m+M+1]!==0&&(re=1),this[m+M]=(p/P>>0)-re&255;return m+S},a.prototype.writeInt8=function(p,m,S){return p=+p,m=m>>>0,S||H(this,p,m,1,127,-128),p<0&&(p=255+p+1),this[m]=p&255,m+1},a.prototype.writeInt16LE=function(p,m,S){return p=+p,m=m>>>0,S||H(this,p,m,2,32767,-32768),this[m]=p&255,this[m+1]=p>>>8,m+2},a.prototype.writeInt16BE=function(p,m,S){return p=+p,m=m>>>0,S||H(this,p,m,2,32767,-32768),this[m]=p>>>8,this[m+1]=p&255,m+2},a.prototype.writeInt32LE=function(p,m,S){return p=+p,m=m>>>0,S||H(this,p,m,4,2147483647,-2147483648),this[m]=p&255,this[m+1]=p>>>8,this[m+2]=p>>>16,this[m+3]=p>>>24,m+4},a.prototype.writeInt32BE=function(p,m,S){return p=+p,m=m>>>0,S||H(this,p,m,4,2147483647,-2147483648),p<0&&(p=4294967295+p+1),this[m]=p>>>24,this[m+1]=p>>>16,this[m+2]=p>>>8,this[m+3]=p&255,m+4},a.prototype.writeBigInt64LE=pt(function(p,m=0){return $(this,p,m,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))}),a.prototype.writeBigInt64BE=pt(function(p,m=0){return se(this,p,m,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))});function ue(b,p,m,S,T,M){if(m+S>b.length)throw new RangeError("Index out of range");if(m<0)throw new RangeError("Index out of range")}function z(b,p,m,S,T){return p=+p,m=m>>>0,T||ue(b,p,m,4),t.write(b,p,m,S,23,4),m+4}a.prototype.writeFloatLE=function(p,m,S){return z(this,p,m,!0,S)},a.prototype.writeFloatBE=function(p,m,S){return z(this,p,m,!1,S)};function Q(b,p,m,S,T){return p=+p,m=m>>>0,T||ue(b,p,m,8),t.write(b,p,m,S,52,8),m+8}a.prototype.writeDoubleLE=function(p,m,S){return Q(this,p,m,!0,S)},a.prototype.writeDoubleBE=function(p,m,S){return Q(this,p,m,!1,S)},a.prototype.copy=function(p,m,S,T){if(!a.isBuffer(p))throw new TypeError("argument should be a Buffer");if(S||(S=0),!T&&T!==0&&(T=this.length),m>=p.length&&(m=p.length),m||(m=0),T>0&&T<S&&(T=S),T===S||p.length===0||this.length===0)return 0;if(m<0)throw new RangeError("targetStart out of bounds");if(S<0||S>=this.length)throw new RangeError("Index out of range");if(T<0)throw new RangeError("sourceEnd out of bounds");T>this.length&&(T=this.length),p.length-m<T-S&&(T=p.length-m+S);const M=T-S;return this===p&&typeof Uint8Array.prototype.copyWithin=="function"?this.copyWithin(m,S,T):Uint8Array.prototype.set.call(p,this.subarray(S,T),m),M},a.prototype.fill=function(p,m,S,T){if(typeof p=="string"){if(typeof m=="string"?(T=m,m=0,S=this.length):typeof S=="string"&&(T=S,S=this.length),T!==void 0&&typeof T!="string")throw new TypeError("encoding must be a string");if(typeof T=="string"&&!a.isEncoding(T))throw new TypeError("Unknown encoding: "+T);if(p.length===1){const P=p.charCodeAt(0);(T==="utf8"&&P<128||T==="latin1")&&(p=P)}}else typeof p=="number"?p=p&255:typeof p=="boolean"&&(p=Number(p));if(m<0||this.length<m||this.length<S)throw new RangeError("Out of range index");if(S<=m)return this;m=m>>>0,S=S===void 0?this.length:S>>>0,p||(p=0);let M;if(typeof p=="number")for(M=m;M<S;++M)this[M]=p;else{const P=a.isBuffer(p)?p:a.from(p,T),re=P.length;if(re===0)throw new TypeError('The value "'+p+'" is invalid for argument "value"');for(M=0;M<S-m;++M)this[M+m]=P[M%re]}return this};const ae={};function j(b,p,m){ae[b]=class extends m{constructor(){super(),Object.defineProperty(this,"message",{value:p.apply(this,arguments),writable:!0,configurable:!0}),this.name=`${this.name} [${b}]`,this.stack,delete this.name}get code(){return b}set code(T){Object.defineProperty(this,"code",{configurable:!0,enumerable:!0,value:T,writable:!0})}toString(){return`${this.name} [${b}]: ${this.message}`}}}j("ERR_BUFFER_OUT_OF_BOUNDS",function(b){return b?`${b} is outside of buffer bounds`:"Attempt to access memory outside buffer bounds"},RangeError),j("ERR_INVALID_ARG_TYPE",function(b,p){return`The "${b}" argument must be of type number. Received type ${typeof p}`},TypeError),j("ERR_OUT_OF_RANGE",function(b,p,m){let S=`The value of "${b}" is out of range.`,T=m;return Number.isInteger(m)&&Math.abs(m)>2**32?T=_e(String(m)):typeof m=="bigint"&&(T=String(m),(m>BigInt(2)**BigInt(32)||m<-(BigInt(2)**BigInt(32)))&&(T=_e(T)),T+="n"),S+=` It must be ${p}. Received ${T}`,S},RangeError);function _e(b){let p="",m=b.length;const S=b[0]==="-"?1:0;for(;m>=S+4;m-=3)p=`_${b.slice(m-3,m)}${p}`;return`${b.slice(0,m)}${p}`}function ee(b,p,m){Re(p,"offset"),(b[p]===void 0||b[p+m]===void 0)&&pe(p,b.length-(m+1))}function le(b,p,m,S,T,M){if(b>m||b<p){const P=typeof p=="bigint"?"n":"";let re;throw p===0||p===BigInt(0)?re=`>= 0${P} and < 2${P} ** ${(M+1)*8}${P}`:re=`>= -(2${P} ** ${(M+1)*8-1}${P}) and < 2 ** ${(M+1)*8-1}${P}`,new ae.ERR_OUT_OF_RANGE("value",re,b)}ee(S,T,M)}function Re(b,p){if(typeof b!="number")throw new ae.ERR_INVALID_ARG_TYPE(p,"number",b)}function pe(b,p,m){throw Math.floor(b)!==b?(Re(b,m),new ae.ERR_OUT_OF_RANGE("offset","an integer",b)):p<0?new ae.ERR_BUFFER_OUT_OF_BOUNDS:new ae.ERR_OUT_OF_RANGE("offset",`>= 0 and <= ${p}`,b)}const Ve=/[^+/0-9A-Za-z-_]/g;function Jt(b){if(b=b.split("=")[0],b=b.trim().replace(Ve,""),b.length<2)return"";for(;b.length%4!==0;)b=b+"=";return b}function St(b,p){p=p||1/0;let m;const S=b.length;let T=null;const M=[];for(let P=0;P<S;++P){if(m=b.charCodeAt(P),m>55295&&m<57344){if(!T){if(m>56319){(p-=3)>-1&&M.push(239,191,189);continue}else if(P+1===S){(p-=3)>-1&&M.push(239,191,189);continue}T=m;continue}if(m<56320){(p-=3)>-1&&M.push(239,191,189),T=m;continue}m=(T-55296<<10|m-56320)+65536}else T&&(p-=3)>-1&&M.push(239,191,189);if(T=null,m<128){if((p-=1)<0)break;M.push(m)}else if(m<2048){if((p-=2)<0)break;M.push(m>>6|192,m&63|128)}else if(m<65536){if((p-=3)<0)break;M.push(m>>12|224,m>>6&63|128,m&63|128)}else if(m<1114112){if((p-=4)<0)break;M.push(m>>18|240,m>>12&63|128,m>>6&63|128,m&63|128)}else throw new Error("Invalid code point")}return M}function fi(b){const p=[];for(let m=0;m<b.length;++m)p.push(b.charCodeAt(m)&255);return p}function Yi(b,p){let m,S,T;const M=[];for(let P=0;P<b.length&&!((p-=2)<0);++P)m=b.charCodeAt(P),S=m>>8,T=m%256,M.push(T),M.push(S);return M}function Ft(b){return e.toByteArray(Jt(b))}function ft(b,p,m,S){let T;for(T=0;T<S&&!(T+m>=p.length||T>=b.length);++T)p[T+m]=b[T];return T}function tt(b,p){return b instanceof p||b!=null&&b.constructor!=null&&b.constructor.name!=null&&b.constructor.name===p.name}function Ki(b){return b!==b}const wr=(function(){const b="0123456789abcdef",p=new Array(256);for(let m=0;m<16;++m){const S=m*16;for(let T=0;T<16;++T)p[S+T]=b[m]+b[T]}return p})();function pt(b){return typeof BigInt>"u"?Ir:b}function Ir(){throw new Error("BigInt not supported")}})(wo)),wo}var ux=hx();const dx="https://api.anam.ai",fx="/v1",Mu={client:"js-sdk",version:"4.12.0"};var px=function(s,e,t,i){function r(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(h){try{c(i.next(h))}catch(u){o(u)}}function l(h){try{c(i.throw(h))}catch(u){o(u)}}function c(h){h.done?n(h.value):r(h.value).then(a,l)}c((i=i.apply(s,e||[])).next())})};const Pu="https://api.anam.ai",Io="/v1";var Nt;(function(s){s.CLIENT_METRIC_MEASUREMENT_ERROR="client_error",s.CLIENT_METRIC_MEASUREMENT_CONNECTION_CLOSED="client_connection_closed",s.CLIENT_METRIC_MEASUREMENT_CONNECTION_ESTABLISHED="client_connection_established",s.CLIENT_METRIC_MEASUREMENT_SESSION_ATTEMPT="client_session_attempt",s.CLIENT_METRIC_MEASUREMENT_SESSION_SUCCESS="client_session_success"})(Nt||(Nt={}));let Ao=Pu,ku=Io,jt,Bu=!1;const mx=(s,e=Io)=>{Ao=s,ku=e},gx=s=>{jt=s},_x=s=>{Bu=s};let Xt={sessionId:null,organizationId:null,attemptCorrelationId:null};const Li=s=>{Xt=Object.assign(Object.assign({},Xt),s)},ui=(s,e,t)=>px(void 0,void 0,void 0,function*(){if(!Bu)try{const i=Object.assign(Object.assign({},Mu),t);Xt.sessionId&&(i.sessionId=Xt.sessionId),Xt.organizationId&&(i.organizationId=Xt.organizationId),Xt.attemptCorrelationId&&(i.attemptCorrelationId=Xt.attemptCorrelationId);const r=`${ku}/metrics/client`;let n,o={"Content-Type":"application/json"};jt!=null&&jt.enabled&&(jt!=null&&jt.baseUrl)?(n=`${jt.baseUrl}${r}`,o["X-Anam-Target-Url"]=`${Ao}${r}`):n=`${Ao}${r}`,yield fetch(n,{method:"POST",headers:o,body:JSON.stringify({name:s,value:e,tags:i})})}catch(i){console.error("Failed to send error metric:",i)}}),yx=(s,e="console")=>{var t,i,r;const n={};s.forEach(u=>{n[u.type]||(n[u.type]=[]),n[u.type].push(u)});const o={issues:[]},a=((t=n["inbound-rtp"])===null||t===void 0?void 0:t.filter(u=>u.kind==="video"))||[];a.length>0&&(o.personaVideoStream=[],a.forEach(u=>{var f,d,g,_,y;const x={framesReceived:(f=u.framesReceived)!==null&&f!==void 0?f:"unknown",framesDropped:(d=u.framesDropped)!==null&&d!==void 0?d:"unknown",framesPerSecond:(g=u.framesPerSecond)!==null&&g!==void 0?g:"unknown",packetsReceived:(_=u.packetsReceived)!==null&&_!==void 0?_:"unknown",packetsLost:(y=u.packetsLost)!==null&&y!==void 0?y:"unknown",resolution:u.frameWidth&&u.frameHeight?`${u.frameWidth}x${u.frameHeight}`:void 0,jitter:u.jitter!==void 0?u.jitter:void 0};o.personaVideoStream.push(x)}));const l=((i=n["inbound-rtp"])===null||i===void 0?void 0:i.filter(u=>u.kind==="audio"))||[];l.length>0&&(o.personaAudioStream=[],l.forEach(u=>{var f,d,g;const _={packetsReceived:(f=u.packetsReceived)!==null&&f!==void 0?f:"unknown",packetsLost:(d=u.packetsLost)!==null&&d!==void 0?d:"unknown",audioLevel:(g=u.audioLevel)!==null&&g!==void 0?g:"unknown",jitter:u.jitter!==void 0?u.jitter:void 0,totalAudioEnergy:u.totalAudioEnergy!==void 0?u.totalAudioEnergy:void 0};o.personaAudioStream.push(_)}));const c=((r=n["outbound-rtp"])===null||r===void 0?void 0:r.filter(u=>u.kind==="audio"))||[];c.length>0&&(o.userAudioInput=[],c.forEach(u=>{var f,d;const g={packetsSent:(f=u.packetsSent)!==null&&f!==void 0?f:"unknown",retransmittedPackets:(d=u.retransmittedPacketsSent)!==null&&d!==void 0?d:void 0,avgPacketSendDelay:u.totalPacketSendDelay!==void 0?u.totalPacketSendDelay/(u.packetsSent||1)*1e3:void 0};o.userAudioInput.push(g)})),n.codec&&(o.codecs=[],n.codec.forEach(u=>{const f={status:u.payloadType?"Active":"Available",mimeType:u.mimeType||"Unknown",payloadType:u.payloadType||"N/A",clockRate:u.clockRate||void 0,channels:u.channels||void 0};o.codecs.push(f)})),n.transport&&(o.transportLayer=[],n.transport.forEach(u=>{const f={dtlsState:u.dtlsState||"unknown",iceState:u.iceState||"unknown",bytesSent:u.bytesSent||void 0,bytesReceived:u.bytesReceived||void 0};o.transportLayer.push(f)}));const h=[];if(a.forEach(u=>{typeof u.framesDropped=="number"&&u.framesDropped>0&&h.push(`Video: ${u.framesDropped} frames dropped`),typeof u.packetsLost=="number"&&u.packetsLost>0&&h.push(`Video: ${u.packetsLost} packets lost`),typeof u.framesPerSecond=="number"&&u.framesPerSecond<23&&h.push(`Video: Low frame rate (${u.framesPerSecond} fps)`)}),l.forEach(u=>{typeof u.packetsLost=="number"&&u.packetsLost>0&&h.push(`Audio: ${u.packetsLost} packets lost`),typeof u.jitter=="number"&&u.jitter>.1&&h.push(`Audio: High jitter (${(u.jitter*1e3).toFixed(1)}ms)`)}),o.issues=h,e==="json")return o;console.group("📊 WebRTC Session Statistics Report"),o.personaVideoStream&&o.personaVideoStream.length>0&&(console.group("📹 Persona Video Stream (Inbound)"),o.personaVideoStream.forEach(u=>{console.log(`Frames Received: ${u.framesReceived}`),console.log(`Frames Dropped: ${u.framesDropped}`),console.log(`Frames Per Second: ${u.framesPerSecond}`),console.log(`Packets Received: ${typeof u.packetsReceived=="number"?u.packetsReceived.toLocaleString():u.packetsReceived}`),console.log(`Packets Lost: ${u.packetsLost}`),u.resolution&&console.log(`Resolution: ${u.resolution}`),u.jitter!==void 0&&console.log(`Jitter: ${u.jitter.toFixed(5)}ms`)}),console.groupEnd()),o.personaAudioStream&&o.personaAudioStream.length>0&&(console.group("🔊 Persona Audio Stream (Inbound)"),o.personaAudioStream.forEach(u=>{console.log(`Packets Received: ${typeof u.packetsReceived=="number"?u.packetsReceived.toLocaleString():u.packetsReceived}`),console.log(`Packets Lost: ${u.packetsLost}`),console.log(`Audio Level: ${u.audioLevel}`),u.jitter!==void 0&&console.log(`Jitter: ${u.jitter.toFixed(5)}ms`),u.totalAudioEnergy!==void 0&&console.log(`Total Audio Energy: ${u.totalAudioEnergy.toFixed(6)}`)}),console.groupEnd()),o.userAudioInput&&o.userAudioInput.length>0&&(console.group("🎤 User Audio Input (Outbound)"),o.userAudioInput.forEach(u=>{console.log(`Packets Sent: ${typeof u.packetsSent=="number"?u.packetsSent.toLocaleString():u.packetsSent}`),u.retransmittedPackets&&console.log(`Retransmitted Packets: ${u.retransmittedPackets}`),u.avgPacketSendDelay!==void 0&&console.log(`Avg Packet Send Delay: ${u.avgPacketSendDelay.toFixed(5)}ms`)}),console.groupEnd()),o.codecs&&o.codecs.length>0&&(console.group("🔧 Codecs Used"),o.codecs.forEach(u=>{console.log(`${u.status} ${u.mimeType} - Payload Type: ${u.payloadType}`),u.clockRate&&console.log(` Clock Rate: ${u.clockRate}Hz`),u.channels&&console.log(` Channels: ${u.channels}`)}),console.groupEnd()),o.transportLayer&&o.transportLayer.length>0&&(console.group("🚚 Transport Layer"),o.transportLayer.forEach(u=>{console.log(`DTLS State: ${u.dtlsState}`),console.log(`ICE State: ${u.iceState}`),(u.bytesReceived||u.bytesSent)&&console.log(`Data Transfer (bytes) - Sent: ${(u.bytesSent||0).toLocaleString()}, Received: ${(u.bytesReceived||0).toLocaleString()}`)}),console.groupEnd()),o.issues.length>0?(console.group("⚠️ Potential Issues Detected"),o.issues.forEach(u=>console.warn(u)),console.groupEnd()):console.log("✅ No significant issues detected"),console.groupEnd()};var $e;(function(s){s.CLIENT_ERROR_CODE_USAGE_LIMIT_REACHED="CLIENT_ERROR_CODE_USAGE_LIMIT_REACHED",s.CLIENT_ERROR_CODE_SPEND_CAP_REACHED="CLIENT_ERROR_CODE_SPEND_CAP_REACHED",s.CLIENT_ERROR_CODE_VALIDATION_ERROR="CLIENT_ERROR_CODE_VALIDATION_ERROR",s.CLIENT_ERROR_CODE_AUTHENTICATION_ERROR="CLIENT_ERROR_CODE_AUTHENTICATION_ERROR",s.CLIENT_ERROR_CODE_SERVER_ERROR="CLIENT_ERROR_CODE_SERVER_ERROR",s.CLIENT_ERROR_CODE_MAX_CONCURRENT_SESSIONS_REACHED="CLIENT_ERROR_CODE_MAX_CONCURRENT_SESSIONS_REACHED",s.CLIENT_ERROR_CODE_SERVICE_BUSY="CLIENT_ERROR_CODE_SERVICE_BUSY",s.CLIENT_ERROR_CODE_NO_PLAN_FOUND="CLIENT_ERROR_CODE_NO_PLAN_FOUND",s.CLIENT_ERROR_CODE_UNKNOWN_ERROR="CLIENT_ERROR_CODE_UNKNOWN_ERROR",s.CLIENT_ERROR_CODE_CONFIGURATION_ERROR="CLIENT_ERROR_CODE_CONFIGURATION_ERROR"})($e||($e={}));class Ne extends Error{constructor(e,t,i=500,r){super(e),this.name="ClientError",this.code=t,this.statusCode=i,this.details=r,Object.setPrototypeOf(this,Ne.prototype),ui(Nt.CLIENT_METRIC_MEASUREMENT_ERROR,t,{details:r,statusCode:i})}}function Ou(){return typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID():Date.now().toString(36)+Math.random().toString(36).substr(2,9)}function bx(s){if(!(!s||!s.enabled)){if(!s.baseUrl)return"API Gateway baseUrl is required when enabled";try{const e=new URL(s.baseUrl);if(!["http:","https:","ws:","wss:"].includes(e.protocol))return`Invalid API Gateway baseUrl protocol: ${e.protocol}. Must be http:, https:, ws:, or wss:`}catch{return`Invalid API Gateway baseUrl: ${s.baseUrl}`}if(s.wsPath&&!s.wsPath.startsWith("/"))return"API Gateway wsPath must start with /"}}var Ye;(function(s){s.OFFER="offer",s.ANSWER="answer",s.ICE_CANDIDATE="icecandidate",s.END_SESSION="endsession",s.HEARTBEAT="heartbeat",s.WARNING="warning",s.TALK_STREAM_INTERRUPTED="talkinputstreaminterrupted",s.TALK_STREAM_INPUT="talkstream",s.SESSION_READY="sessionready",s.AGENT_AUDIO_INPUT="agentaudioinput",s.AGENT_AUDIO_INPUT_END="agentaudioinputend"})(Ye||(Ye={}));var vt;(function(s){s.SPEECH_TEXT="speechText",s.CLIENT_TOOL_EVENT="clientToolEvent",s.TOOL_CALL_STARTED_EVENT="toolCallStarted",s.TOOL_CALL_COMPLETED_EVENT="toolCallCompleted",s.TOOL_CALL_FAILED_EVENT="toolCallFailed",s.REASONING_TEXT="reasoningText",s.USER_SPEECH_STARTED="userSpeechStarted",s.USER_SPEECH_ENDED="userSpeechEnded"})(vt||(vt={}));var Yt;(function(s){s.PENDING="pending",s.GRANTED="granted",s.DENIED="denied",s.NOT_REQUESTED="not_requested"})(Yt||(Yt={}));var _r;(function(s){s.USER="user",s.PERSONA="persona"})(_r||(_r={}));var oe;(function(s){s.MESSAGE_HISTORY_UPDATED="MESSAGE_HISTORY_UPDATED",s.MESSAGE_STREAM_EVENT_RECEIVED="MESSAGE_STREAM_EVENT_RECEIVED",s.CONNECTION_ESTABLISHED="CONNECTION_ESTABLISHED",s.CONNECTION_CLOSED="CONNECTION_CLOSED",s.INPUT_AUDIO_STREAM_STARTED="INPUT_AUDIO_STREAM_STARTED",s.VIDEO_STREAM_STARTED="VIDEO_STREAM_STARTED",s.VIDEO_PLAY_STARTED="VIDEO_PLAY_STARTED",s.AUDIO_STREAM_STARTED="AUDIO_STREAM_STARTED",s.TALK_STREAM_INTERRUPTED="TALK_STREAM_INTERRUPTED",s.SESSION_READY="SESSION_READY",s.SERVER_WARNING="SERVER_WARNING",s.MIC_PERMISSION_PENDING="MIC_PERMISSION_PENDING",s.MIC_PERMISSION_GRANTED="MIC_PERMISSION_GRANTED",s.MIC_PERMISSION_DENIED="MIC_PERMISSION_DENIED",s.INPUT_AUDIO_DEVICE_CHANGED="INPUT_AUDIO_DEVICE_CHANGED",s.CLIENT_TOOL_EVENT_RECEIVED="CLIENT_TOOL_EVENT_RECEIVED",s.TOOL_CALL_STARTED="TOOL_CALL_STARTED",s.TOOL_CALL_COMPLETED="TOOL_CALL_COMPLETED",s.TOOL_CALL_FAILED="TOOL_CALL_FAILED",s.REASONING_HISTORY_UPDATED="REASONING_HISTORY_UPDATED",s.REASONING_STREAM_EVENT_RECEIVED="REASONING_STREAM_EVENT_RECEIVED",s.USER_SPEECH_STARTED="USER_SPEECH_STARTED",s.USER_SPEECH_ENDED="USER_SPEECH_ENDED"})(oe||(oe={}));var Fe;(function(s){s.WEB_SOCKET_OPEN="WEB_SOCKET_OPEN",s.SIGNAL_MESSAGE_RECEIVED="SIGNAL_MESSAGE_RECEIVED",s.WEBRTC_CHAT_MESSAGE_RECEIVED="WEBRTC_CHAT_MESSAGE_RECEIVED",s.WEBRTC_CLIENT_TOOL_EVENT_RECEIVED="WEBRTC_CLIENT_TOOL_EVENT_RECEIVED",s.WEBRTC_TOOL_CALL_STARTED_EVENT_RECEIVED="WEBRTC_TOOL_CALL_STARTED_EVENT_RECEIVED",s.WEBRTC_TOOL_CALL_COMPLETED_EVENT_RECEIVED="WEBRTC_TOOL_CALL_COMPLETED_EVENT_RECEIVED",s.WEBRTC_TOOL_CALL_FAILED_EVENT_RECEIVED="WEBRTC_TOOL_CALL_FAILED_EVENT_RECEIVED",s.WEBRTC_REASONING_TEXT_MESSAGE_RECEIVED="WEBRTC_REASONING_TEXT_MESSAGE_RECEIVED"})(Fe||(Fe={}));var Kt;(function(s){s.NORMAL="CONNECTION_CLOSED_CODE_NORMAL",s.MICROPHONE_PERMISSION_DENIED="CONNECTION_CLOSED_CODE_MICROPHONE_PERMISSION_DENIED",s.SIGNALLING_CLIENT_CONNECTION_FAILURE="CONNECTION_CLOSED_CODE_SIGNALLING_CLIENT_CONNECTION_FAILURE",s.WEBRTC_FAILURE="CONNECTION_CLOSED_CODE_WEBRTC_FAILURE",s.SERVER_CLOSED_CONNECTION="CONNECTION_CLOSED_CODE_SERVER_CLOSED_CONNECTION"})(Kt||(Kt={}));class xx{constructor(e,t){this.sequenceNumber=0,this.config=e,this.signallingClient=t}sendAudioChunk(e){const i={audioData:typeof e=="string"?e:this.arrayBufferToBase64(e),encoding:this.config.encoding,sampleRate:this.config.sampleRate,channels:this.config.channels,sequenceNumber:this.sequenceNumber++};this.signallingClient.sendAgentAudioInput(i)}endSequence(){this.signallingClient.sendAgentAudioInputEnd(),this.sequenceNumber=0}getSequenceNumber(){return this.sequenceNumber}getConfig(){return this.config}arrayBufferToBase64(e){const t=e instanceof Uint8Array?e:new Uint8Array(e),i=Array.from(t,r=>String.fromCharCode(r)).join("");return btoa(i)}}var Gi=function(s,e,t,i){function r(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(h){try{c(i.next(h))}catch(u){o(u)}}function l(h){try{c(i.throw(h))}catch(u){o(u)}}function c(h){h.done?n(h.value):r(h.value).then(a,l)}c((i=i.apply(s,e||[])).next())})};const vx=5,Sx=5;class Cx{constructor(e,t,i,r,n){var o,a,l,c,h;if(this.stopSignal=!1,this.sendingBuffer=[],this.wsConnectionAttempts=0,this.socket=null,this.heartBeatIntervalRef=null,this.publicEventEmitter=i,this.internalEventEmitter=r,this.apiGatewayConfig=n,!e)throw new Error("Signalling Client: sessionId is required");this.sessionId=e;const{heartbeatIntervalSeconds:u,maxWsReconnectionAttempts:f,url:d}=t;if(this.heartbeatIntervalSeconds=u||vx,this.maxWsReconnectionAttempts=f||Sx,!d.baseUrl)throw new Error("Signalling Client: baseUrl is required");if(!((o=this.apiGatewayConfig)===null||o===void 0)&&o.enabled&&(!((a=this.apiGatewayConfig)===null||a===void 0)&&a.baseUrl)){const g=new URL(this.apiGatewayConfig.baseUrl),_=(l=this.apiGatewayConfig.wsPath)!==null&&l!==void 0?l:"/ws";g.protocol=g.protocol.replace("http","ws"),g.pathname=_,this.url=g;const y=d.protocol||"https",x=y==="http"?"ws":"wss",v=`${y}://${d.baseUrl}`,C=(c=d.signallingPath)!==null&&c!==void 0?c:"/ws",E=new URL(v);E.protocol=x==="ws"?"ws:":"wss:",d.port&&(E.port=d.port),E.pathname=C,E.searchParams.append("session_id",e),this.url.searchParams.append("target_url",E.href)}else{const _=`${d.protocol||"https"}://${d.baseUrl}`;this.url=new URL(_),this.url.protocol=d.protocol==="http"?"ws:":"wss:",d.port&&(this.url.port=d.port),this.url.pathname=(h=d.signallingPath)!==null&&h!==void 0?h:"/ws",this.url.searchParams.append("session_id",e)}}stop(){this.stopSignal=!0,this.closeSocket()}connect(){return this.socket=new WebSocket(this.url.href),this.socket.onopen=this.onOpen.bind(this),this.socket.onclose=this.onClose.bind(this),this.socket.onerror=this.onError.bind(this),this.socket}sendOffer(e){return Gi(this,void 0,void 0,function*(){const t={connectionDescription:e,userUid:this.sessionId},i={actionType:Ye.OFFER,sessionId:this.sessionId,payload:t};this.sendSignalMessage(i)})}sendIceCandidate(e){return Gi(this,void 0,void 0,function*(){const t={actionType:Ye.ICE_CANDIDATE,sessionId:this.sessionId,payload:e.toJSON()};this.sendSignalMessage(t)})}sendSignalMessage(e){var t;if(((t=this.socket)===null||t===void 0?void 0:t.readyState)===WebSocket.OPEN)try{this.socket.send(JSON.stringify(e))}catch(i){console.error("SignallingClient - sendSignalMessage: error sending message",i)}else this.sendingBuffer.push(e)}sendTalkMessage(e){return Gi(this,void 0,void 0,function*(){const t={actionType:Ye.TALK_STREAM_INPUT,sessionId:this.sessionId,payload:e};this.sendSignalMessage(t)})}sendAgentAudioInput(e){const t={actionType:Ye.AGENT_AUDIO_INPUT,sessionId:this.sessionId,payload:e};this.sendSignalMessage(t)}sendAgentAudioInputEnd(){const e={actionType:Ye.AGENT_AUDIO_INPUT_END,sessionId:this.sessionId,payload:{}};this.sendSignalMessage(e)}closeSocket(){this.socket&&(this.socket.close(),this.socket=null),this.heartBeatIntervalRef&&(clearInterval(this.heartBeatIntervalRef),this.heartBeatIntervalRef=null)}onOpen(){return Gi(this,void 0,void 0,function*(){if(!this.socket)throw new Error("SignallingClient - onOpen: socket is null");try{this.wsConnectionAttempts=0,this.flushSendingBuffer(),this.socket.onmessage=this.onMessage.bind(this),this.startSendingHeartBeats(),this.internalEventEmitter.emit(Fe.WEB_SOCKET_OPEN)}catch(e){console.error("SignallingClient - onOpen: error in onOpen",e),this.publicEventEmitter.emit(oe.CONNECTION_CLOSED,Kt.SIGNALLING_CLIENT_CONNECTION_FAILURE)}})}onClose(){return Gi(this,void 0,void 0,function*(){this.wsConnectionAttempts+=1,!this.stopSignal&&(this.wsConnectionAttempts<=this.maxWsReconnectionAttempts?(this.socket=null,setTimeout(()=>{this.connect()},100*this.wsConnectionAttempts)):(this.heartBeatIntervalRef&&(clearInterval(this.heartBeatIntervalRef),this.heartBeatIntervalRef=null),this.publicEventEmitter.emit(oe.CONNECTION_CLOSED,Kt.SIGNALLING_CLIENT_CONNECTION_FAILURE)))})}onError(e){this.stopSignal||console.error("SignallingClient - onError: ",e)}flushSendingBuffer(){const e=[];this.sendingBuffer.length>0&&this.sendingBuffer.forEach(t=>{var i;((i=this.socket)===null||i===void 0?void 0:i.readyState)===WebSocket.OPEN?this.socket.send(JSON.stringify(t)):e.push(t)}),this.sendingBuffer=e}onMessage(e){return Gi(this,void 0,void 0,function*(){const t=JSON.parse(e.data);this.internalEventEmitter.emit(Fe.SIGNAL_MESSAGE_RECEIVED,t)})}startSendingHeartBeats(){if(!this.socket)throw new Error("SignallingClient - startSendingHeartBeats: socket is null");this.heartBeatIntervalRef&&console.warn("SignallingClient - startSendingHeartBeats: heartbeat interval already set");const e=this.heartbeatIntervalSeconds*1e3,t={actionType:Ye.HEARTBEAT,sessionId:this.sessionId,payload:""},i=JSON.stringify(t);this.heartBeatIntervalRef=setInterval(()=>{var r;this.stopSignal||((r=this.socket)===null||r===void 0?void 0:r.readyState)===WebSocket.OPEN&&this.socket.send(i)},e)}}function Ex(s){return"brainType"in s||"llmId"in s}var Du=function(s,e,t,i){function r(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(h){try{c(i.next(h))}catch(u){o(u)}}function l(h){try{c(i.throw(h))}catch(u){o(u)}}function c(h){h.done?n(h.value):r(h.value).then(a,l)}c((i=i.apply(s,e||[])).next())})};class Tx{constructor(e,t,i){if(!e&&!t)throw new Error("Either sessionToken or apiKey must be provided");this.sessionToken=e||null,this.apiKey=t||null,this.baseUrl=(i==null?void 0:i.baseUrl)||dx,this.apiVersion=(i==null?void 0:i.apiVersion)||fx,this.apiGatewayConfig=(i==null?void 0:i.apiGateway)||void 0}buildGatewayUrlAndHeaders(e,t){var i,r;if(!((i=this.apiGatewayConfig)===null||i===void 0)&&i.enabled&&(!((r=this.apiGatewayConfig)===null||r===void 0)&&r.baseUrl)){const n=`${this.apiGatewayConfig.baseUrl}${e}`,o=new URL(`${this.baseUrl}${e}`),a=Object.assign(Object.assign({},t),{"X-Anam-Target-Url":o.href});return{url:n,headers:a}}else return{url:`${this.baseUrl}${e}`,headers:t}}startSession(e,t){return Du(this,void 0,void 0,function*(){if(!this.sessionToken){if(!e)throw new Ne("Persona configuration must be provided when using apiKey",$e.CLIENT_ERROR_CODE_VALIDATION_ERROR,400);this.sessionToken=yield this.unsafe_getSessionToken(e)}e&&"brainType"in e&&console.warn("Warning: brainType is deprecated and will be removed in a future version. Please use llmId instead.");try{const i=`${this.apiVersion}/engine/session`,{url:r,headers:n}=this.buildGatewayUrlAndHeaders(i,{"Content-Type":"application/json",Authorization:`Bearer ${this.sessionToken}`}),o=yield fetch(r,{method:"POST",headers:n,body:JSON.stringify({personaConfig:e,sessionOptions:t,clientMetadata:Mu})}),a=yield o.json(),l=a.error;switch(o.status){case 200:case 201:return a;case 400:throw new Ne("Invalid request to start session",$e.CLIENT_ERROR_CODE_VALIDATION_ERROR,400,{cause:a.message});case 401:throw new Ne("Authentication failed when starting session",$e.CLIENT_ERROR_CODE_AUTHENTICATION_ERROR,401,{cause:a.message});case 402:throw new Ne("Please sign up for a plan to start a session",$e.CLIENT_ERROR_CODE_NO_PLAN_FOUND,402,{cause:a.message});case 403:throw new Ne("Authentication failed when starting session",$e.CLIENT_ERROR_CODE_AUTHENTICATION_ERROR,403,{cause:a.message});case 429:throw l==="Concurrent session limit reached"?new Ne("Concurrency limit reached, please upgrade your plan",$e.CLIENT_ERROR_CODE_MAX_CONCURRENT_SESSIONS_REACHED,429,{cause:a.message}):l==="Spend cap reached"?new Ne("Spend cap reached, please upgrade your plan",$e.CLIENT_ERROR_CODE_SPEND_CAP_REACHED,429,{cause:a.message}):new Ne("Usage limit reached, please upgrade your plan",$e.CLIENT_ERROR_CODE_USAGE_LIMIT_REACHED,429,{cause:a.message});case 503:throw new Ne("There are no available personas, please try again later",$e.CLIENT_ERROR_CODE_SERVICE_BUSY,503,{cause:a.message});default:throw new Ne("Unknown error when starting session",$e.CLIENT_ERROR_CODE_SERVER_ERROR,500,{cause:a.message})}}catch(i){throw i instanceof Ne?i:new Ne("Failed to start session",$e.CLIENT_ERROR_CODE_SERVER_ERROR,500,{cause:i instanceof Error?i.message:String(i)})}})}unsafe_getSessionToken(e){return Du(this,void 0,void 0,function*(){if(console.warn("Using unsecure method. This method should not be used in production."),!this.apiKey)throw new Error("No apiKey provided");e&&"brainType"in e&&console.warn("Warning: brainType is deprecated and will be removed in a future version. Please use llmId instead.");let t={clientLabel:"js-sdk-api-key"};Ex(e)&&(t=Object.assign(Object.assign({},t),{personaConfig:e}));try{const i=`${this.apiVersion}/auth/session-token`,{url:r,headers:n}=this.buildGatewayUrlAndHeaders(i,{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`});return(yield(yield fetch(r,{method:"POST",headers:n,body:JSON.stringify(t)})).json()).sessionToken}catch{throw new Error("Failed to get session token")}})}getApiUrl(){return`${this.baseUrl}${this.apiVersion}`}}var wx=function(s,e,t,i){function r(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(h){try{c(i.next(h))}catch(u){o(u)}}function l(h){try{c(i.throw(h))}catch(u){o(u)}}function c(h){h.done?n(h.value):r(h.value).then(a,l)}c((i=i.apply(s,e||[])).next())})};class Ix{constructor(e,t,i){this.baseUrl=e,this.sessionId=t,this.apiGatewayConfig=i}sendTalkCommand(e){return wx(this,void 0,void 0,function*(){var t,i;try{let r,n={"Content-Type":"application/json"};const o="/talk",a=`?session_id=${this.sessionId}`;if(!((t=this.apiGatewayConfig)===null||t===void 0)&&t.enabled&&(!((i=this.apiGatewayConfig)===null||i===void 0)&&i.baseUrl)){r=`${this.apiGatewayConfig.baseUrl}${o}${a}`;const c=new URL(`${this.baseUrl}${o}${a}`);n["X-Anam-Target-Url"]=c.href}else r=`${this.baseUrl}${o}${a}`;const l=yield fetch(r,{method:"POST",headers:n,body:JSON.stringify({content:e})});if(!l.ok)throw new Error(`Failed to send talk command: ${l.status} ${l.statusText}`)}catch(r){throw console.error(r),new Error("EngineApiRestClient - sendTalkCommand: Failed to send talk command")}})}}class Ax{constructor(){this.listeners={}}addListener(e,t){this.listeners[e]||(this.listeners[e]=new Set),this.listeners[e].add(t)}removeListener(e,t){this.listeners[e]&&this.listeners[e].delete(t)}emit(e,...t){this.listeners[e]&&this.listeners[e].forEach(i=>{i(...t)})}}class Rx{constructor(e,t){this.messages=[],this.publicEventEmitter=e,this.internalEventEmitter=t,this.internalEventEmitter.addListener(Fe.WEBRTC_CHAT_MESSAGE_RECEIVED,this.processWebRtcTextMessageEvent.bind(this))}webRtcTextMessageEventToMessageStreamEvent(e){return{id:`${e.role}::${e.message_id}`,content:e.content,role:e.role,endOfSpeech:e.end_of_speech,interrupted:e.interrupted}}processUserMessage(e){const t={id:e.id,content:e.content,role:e.role};this.messages.push(t)}processPersonaMessage(e){const t={id:e.id,content:e.content,role:e.role,interrupted:e.interrupted},i=this.messages.findIndex(r=>r.id===t.id);if(i!==-1){const r=this.messages[i];this.messages[i]=Object.assign(Object.assign({},r),{content:r.content+t.content,interrupted:r.interrupted||t.interrupted})}else this.messages.push(t)}processWebRtcTextMessageEvent(e){const t=this.webRtcTextMessageEventToMessageStreamEvent(e);switch(this.publicEventEmitter.emit(oe.MESSAGE_STREAM_EVENT_RECEIVED,t),t.role){case _r.USER:this.processUserMessage(t);break;case _r.PERSONA:this.processPersonaMessage(t);break}t.endOfSpeech&&this.publicEventEmitter.emit(oe.MESSAGE_HISTORY_UPDATED,this.messages)}}class Mx{constructor(){this.listeners={}}addListener(e,t){this.listeners[e]||(this.listeners[e]=new Set),this.listeners[e].add(t)}removeListener(e,t){this.listeners[e]&&this.listeners[e].delete(t)}emit(e,...t){if(e===oe.CONNECTION_ESTABLISHED&&ui(Nt.CLIENT_METRIC_MEASUREMENT_CONNECTION_ESTABLISHED,"1"),e===oe.CONNECTION_CLOSED){const[i,r]=t;ui(Nt.CLIENT_METRIC_MEASUREMENT_CONNECTION_CLOSED,i,r?{details:r}:void 0)}this.listeners[e]&&this.listeners[e].forEach(i=>{i(...t)})}}var qe;(function(s){s[s.UNSTARTED=0]="UNSTARTED",s[s.STREAMING=1]="STREAMING",s[s.INTERRUPTED=2]="INTERRUPTED",s[s.ENDED=3]="ENDED"})(qe||(qe={}));var Ro=function(s,e,t,i){function r(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(h){try{c(i.next(h))}catch(u){o(u)}}function l(h){try{c(i.throw(h))}catch(u){o(u)}}function c(h){h.done?n(h.value):r(h.value).then(a,l)}c((i=i.apply(s,e||[])).next())})};class Px{constructor(e,t,i){this.state=qe.UNSTARTED,this.correlationId=e,this.internalEventEmitter=t,this.signallingClient=i,this.internalEventEmitter.addListener(Fe.SIGNAL_MESSAGE_RECEIVED,this.onSignalMessage.bind(this))}onDeactivate(){this.internalEventEmitter.removeListener(Fe.SIGNAL_MESSAGE_RECEIVED,this.onSignalMessage.bind(this))}onSignalMessage(e){return Ro(this,void 0,void 0,function*(){e.actionType===Ye.TALK_STREAM_INTERRUPTED&&e.payload.correlationId===this.correlationId&&(this.state=qe.INTERRUPTED,this.onDeactivate())})}endMessage(){return Ro(this,void 0,void 0,function*(){if(this.state===qe.ENDED){console.warn("Talk stream is already ended via end of speech. No need to call endMessage.");return}if(this.state!==qe.STREAMING){console.warn("Talk stream is not active state: "+this.state);return}const e={content:"",startOfSpeech:!1,endOfSpeech:!0,correlationId:this.correlationId};yield this.signallingClient.sendTalkMessage(e),this.state=qe.ENDED,this.onDeactivate()})}streamMessageChunk(e,t){return Ro(this,void 0,void 0,function*(){if(this.state!==qe.STREAMING&&this.state!==qe.UNSTARTED)throw new Error("Talk stream is not in an active state: "+this.state);const i={content:e,startOfSpeech:this.state===qe.UNSTARTED,endOfSpeech:t,correlationId:this.correlationId};this.state=t?qe.ENDED:qe.STREAMING,this.state===qe.ENDED&&this.onDeactivate(),yield this.signallingClient.sendTalkMessage(i)})}getCorrelationId(){return this.correlationId}isActive(){return this.state===qe.STREAMING||this.state===qe.UNSTARTED}getState(){return this.state}}var Mo=function(s,e,t,i){function r(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(h){try{c(i.next(h))}catch(u){o(u)}}function l(h){try{c(i.throw(h))}catch(u){o(u)}}function c(h){h.done?n(h.value):r(h.value).then(a,l)}c((i=i.apply(s,e||[])).next())})};const Nu=(s,e)=>{if(isNaN(s)||isNaN(e))return 0;const t=e-s;return t>0?t:0};class Fu{constructor(e){this.handlers=Object.create(null),this.pendingCalls=Object.create(null),this.publicEventEmitter=e}clearPendingCalls(){this.pendingCalls=Object.create(null)}registerHandler(e,t){return this.handlers[e]=t,()=>{delete this.handlers[e]}}processToolCallStartedEvent(e){return Mo(this,void 0,void 0,function*(){const{tool_name:t,timestamp:i}=e,r=this.WebRTCToolCallStartedEventToToolCallStartedPayload(e),n=new Date(i);if(this.pendingCalls[e.tool_call_id]={payload:r,timestamp:n.getTime()},!(t in this.handlers))return;const o=this.handlers[t];if(o.onStart)try{let a=yield o.onStart(r);if(e.tool_type==="client"){yield this.processToolCallCompletedEvent(Object.assign(Object.assign({},e),{result:a,timestamp:new Date().toISOString()}));return}}catch(a){a instanceof Error?yield this.processToolCallFailedEvent(Object.assign(Object.assign({},e),{error_message:`Error in onStart handler: ${a.message}`,timestamp:new Date().toISOString()})):yield this.processToolCallFailedEvent(Object.assign(Object.assign({},e),{error_message:`Error in onStart handler: ${String(a)}`,timestamp:new Date().toISOString()}));return}})}processToolCallCompletedEvent(e){return Mo(this,void 0,void 0,function*(){const{tool_name:t,tool_call_id:i,timestamp:r}=e,n=this.webRTCToolCallCompletedEventToToolCallCompletedPayload(e);if(i in this.pendingCalls&&delete this.pendingCalls[i],!(t in this.handlers))return;const o=this.handlers[t];if(o.onComplete){e.tool_type==="client"&&this.publicEventEmitter.emit(oe.TOOL_CALL_COMPLETED,n);try{yield o.onComplete(n)}catch(a){console.error(`Error in onComplete handler for tool ${t}:`,a);return}}})}processToolCallFailedEvent(e){return Mo(this,void 0,void 0,function*(){const{tool_name:t,tool_call_id:i,timestamp:r}=e,n=this.webRTCToolCallFailedEventToToolCallFailedPayload(e);if(i in this.pendingCalls&&delete this.pendingCalls[i],!(t in this.handlers))return;const o=this.handlers[t];if(o.onFail){e.tool_type==="client"&&this.publicEventEmitter.emit(oe.TOOL_CALL_FAILED,n);try{yield o.onFail(n)}catch(a){console.error(`Error in onFail handler for tool ${t}:`,a);return}}})}static WebRTCClientToolEventToClientToolEvent(e){return{eventUid:e.event_uid,sessionId:e.session_id,eventName:e.event_name,eventData:e.event_data,timestamp:e.timestamp,timestampUserAction:e.timestamp_user_action,userActionCorrelationId:e.user_action_correlation_id}}static WebRTCToolCallStartedEventToClientToolEvent(e){return{eventUid:e.event_uid,sessionId:e.session_id,eventName:e.tool_name,eventData:e.arguments,timestamp:e.timestamp,timestampUserAction:e.timestamp_user_action,userActionCorrelationId:e.user_action_correlation_id}}WebRTCToolCallStartedEventToToolCallStartedPayload(e){return{eventUid:e.event_uid,toolCallId:e.tool_call_id,toolName:e.tool_name,toolType:e.tool_type,toolSubtype:e.tool_subtype,arguments:e.arguments,timestamp:e.timestamp,timestampUserAction:e.timestamp_user_action,userActionCorrelationId:e.user_action_correlation_id}}webRTCToolCallCompletedEventToToolCallCompletedPayload(e){const t=new Date(e.timestamp),i=this.pendingCalls[e.tool_call_id],r=i?Nu(i.timestamp,t.getTime()):0;return{eventUid:e.event_uid,toolCallId:e.tool_call_id,toolName:e.tool_name,toolType:e.tool_type,toolSubtype:e.tool_subtype,result:e.result,executionTime:r>0?r:0,timestamp:e.timestamp,documentsAccessed:e.documents_accessed,timestampUserAction:e.timestamp_user_action,userActionCorrelationId:e.user_action_correlation_id}}webRTCToolCallFailedEventToToolCallFailedPayload(e){const t=new Date(e.timestamp),i=this.pendingCalls[e.tool_call_id],r=i?Nu(i.timestamp,t.getTime()):0;return{eventUid:e.event_uid,toolCallId:e.tool_call_id,toolName:e.tool_name,toolType:e.tool_type,toolSubtype:e.tool_subtype,errorMessage:e.error_message,executionTime:r>0?r:0,timestamp:e.timestamp,timestampUserAction:e.timestamp_user_action,userActionCorrelationId:e.user_action_correlation_id}}}var st=function(s,e,t,i){function r(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(h){try{c(i.next(h))}catch(u){o(u)}}function l(h){try{c(i.throw(h))}catch(u){o(u)}}function c(h){h.done?n(h.value):r(h.value).then(a,l)}c((i=i.apply(s,e||[])).next())})};const kx=15e3,Bx=5e3,Ox=2;class Dx{constructor(e,t,i,r,n){var o,a,l,c;this.peerConnection=null,this.connectionReceivedAnswer=!1,this.remoteIceCandidateBuffer=[],this.inputAudioStream=null,this.dataChannel=null,this.videoElement=null,this.videoStream=null,this.audioStream=null,this.inputAudioState={isMuted:!1,permissionState:Yt.NOT_REQUESTED},this.successMetricPoller=null,this.successMetricFired=!1,this.showPeerConnectionStatsReport=!1,this.peerConnectionStatsReportOutputFormat="console",this.statsCollectionInterval=null,this.agentAudioInputStream=null,this.publicEventEmitter=i,this.internalEventEmitter=r,this.toolCallManager=n,this.apiGatewayConfig=t.apiGateway;const{inputAudio:h}=t;this.inputAudioState=h.inputAudioState,t.inputAudio.userProvidedMediaStream&&(this.inputAudioStream=t.inputAudio.userProvidedMediaStream),this.disableInputAudio=t.inputAudio.disableInputAudio===!0,this.internalEventEmitter.addListener(Fe.WEB_SOCKET_OPEN,this.onSignallingClientConnected.bind(this)),this.internalEventEmitter.addListener(Fe.SIGNAL_MESSAGE_RECEIVED,this.onSignalMessage.bind(this)),this.internalEventEmitter.addListener(Fe.WEBRTC_TOOL_CALL_STARTED_EVENT_RECEIVED,this.toolCallManager.processToolCallStartedEvent.bind(this.toolCallManager)),this.internalEventEmitter.addListener(Fe.WEBRTC_TOOL_CALL_COMPLETED_EVENT_RECEIVED,this.toolCallManager.processToolCallCompletedEvent.bind(this.toolCallManager)),this.internalEventEmitter.addListener(Fe.WEBRTC_TOOL_CALL_FAILED_EVENT_RECEIVED,this.toolCallManager.processToolCallFailedEvent.bind(this.toolCallManager)),this.iceServers=t.iceServers,this.signallingClient=new Cx(e,t.signalling,this.publicEventEmitter,this.internalEventEmitter,this.apiGatewayConfig),this.engineApiRestClient=new Ix(t.engine.baseUrl,e,this.apiGatewayConfig),this.audioDeviceId=t.inputAudio.audioDeviceId,this.showPeerConnectionStatsReport=(a=(o=t.metrics)===null||o===void 0?void 0:o.showPeerConnectionStatsReport)!==null&&a!==void 0?a:!1,this.peerConnectionStatsReportOutputFormat=(c=(l=t.metrics)===null||l===void 0?void 0:l.peerConnectionStatsReportOutputFormat)!==null&&c!==void 0?c:"console"}onInputAudioStateChange(e,t){e.isMuted!==t.isMuted&&(t.isMuted?this.muteAllAudioTracks():this.unmuteAllAudioTracks())}muteAllAudioTracks(){var e;(e=this.inputAudioStream)===null||e===void 0||e.getAudioTracks().forEach(t=>{t.enabled=!1})}unmuteAllAudioTracks(){var e;(e=this.inputAudioStream)===null||e===void 0||e.getAudioTracks().forEach(t=>{t.enabled=!0})}startStatsCollection(){this.statsCollectionInterval||(this.statsCollectionInterval=setInterval(()=>st(this,void 0,void 0,function*(){if(!(!this.peerConnection||!this.dataChannel||this.dataChannel.readyState!=="open"))try{const e=yield this.peerConnection.getStats();this.sendClientSideMetrics(e)}catch(e){console.error("Failed to collect and send stats:",e)}}),Bx))}sendClientSideMetrics(e){e.forEach(t=>{if(t.type==="inbound-rtp"){const i={message_type:"remote_rtp_stats",data:t};this.dataChannel&&this.dataChannel.readyState==="open"&&this.dataChannel.send(JSON.stringify(i))}})}startSuccessMetricPolling(){if(this.successMetricPoller||this.successMetricFired)return;const e=setTimeout(()=>{this.successMetricPoller&&(console.warn("No video frames received, there is a problem with the connection."),clearInterval(this.successMetricPoller),this.successMetricPoller=null)},kx);this.successMetricPoller=setInterval(()=>st(this,void 0,void 0,function*(){if(!this.peerConnection||this.successMetricFired){this.successMetricPoller&&clearInterval(this.successMetricPoller),clearTimeout(e);return}try{const t=yield this.peerConnection.getStats();let i=!1,r=null;t.forEach(n=>{n.type==="inbound-rtp"&&n.kind==="video"&&(n.framesDecoded!==void 0&&n.framesDecoded>0?(i=!0,r="framesDecoded"):n.framesReceived!==void 0&&n.framesReceived>0?(i=!0,r="framesReceived"):n.bytesReceived>0&&n.packetsReceived>0&&n.bytesReceived>1e5&&(i=!0,r="bytesReceived"))}),i&&!this.successMetricFired&&(this.successMetricFired=!0,ui(Nt.CLIENT_METRIC_MEASUREMENT_SESSION_SUCCESS,"1",r?{detectionMethod:r}:void 0),this.successMetricPoller&&clearInterval(this.successMetricPoller),clearTimeout(e),this.successMetricPoller=null)}catch{}}),500)}muteInputAudio(){const e=this.inputAudioState,t=Object.assign(Object.assign({},this.inputAudioState),{isMuted:!0});return this.inputAudioState=t,this.onInputAudioStateChange(e,t),this.inputAudioState}unmuteInputAudio(){const e=this.inputAudioState,t=Object.assign(Object.assign({},this.inputAudioState),{isMuted:!1});return this.inputAudioState=t,this.onInputAudioStateChange(e,t),this.inputAudioState}getInputAudioState(){return this.inputAudioState}getPeerConnection(){return this.peerConnection}changeAudioInputDevice(e){return st(this,void 0,void 0,function*(){if(!this.peerConnection)throw new Error("StreamingClient - changeAudioInputDevice: peer connection is not initialized. Start streaming first.");if(e==null)throw new Error("StreamingClient - changeAudioInputDevice: deviceId is required");const t=this.inputAudioState.isMuted;try{this.inputAudioStream&&this.inputAudioStream.getAudioTracks().forEach(r=>{r.stop()});const i={echoCancellation:!0,deviceId:{exact:e}};this.inputAudioStream=yield navigator.mediaDevices.getUserMedia({audio:i}),this.audioDeviceId=e,yield this.setupAudioTrack(),t&&this.muteAllAudioTracks(),this.publicEventEmitter.emit(oe.INPUT_AUDIO_DEVICE_CHANGED,e)}catch(i){throw console.error("Failed to change audio input device:",i),new Error(`StreamingClient - changeAudioInputDevice: ${i instanceof Error?i.message:String(i)}`)}})}getInputAudioStream(){return this.inputAudioStream}getVideoStream(){return this.videoStream}getAudioStream(){return this.audioStream}sendDataMessage(e){this.dataChannel&&this.dataChannel.readyState==="open"&&this.dataChannel.send(e)}setMediaStreamTargetById(e){if(e){const t=document.getElementById(e);if(!t)throw new Error(`StreamingClient: video element with id ${e} not found`);this.videoElement=t}}startConnection(){try{if(this.peerConnection){console.error("StreamingClient - startConnection: peer connection already exists");return}this.signallingClient.connect()}catch(e){console.error("StreamingClient - startConnection: error",e),this.handleWebrtcFailure(e)}}stopConnection(){return st(this,void 0,void 0,function*(){yield this.shutdown()})}sendTalkCommand(e){return st(this,void 0,void 0,function*(){if(!this.peerConnection)throw new Error("StreamingClient - sendTalkCommand: peer connection is null");yield this.engineApiRestClient.sendTalkCommand(e)})}startTalkMessageStream(e){return e||(e=Math.random().toString(36).substring(2,15)),new Px(e,this.internalEventEmitter,this.signallingClient)}createAgentAudioInputStream(e){return this.agentAudioInputStream=new xx(e,this.signallingClient),this.agentAudioInputStream}getAgentAudioInputStream(){return this.agentAudioInputStream}initPeerConnection(){return st(this,void 0,void 0,function*(){this.peerConnection=new RTCPeerConnection({iceServers:this.iceServers,iceCandidatePoolSize:Ox}),this.peerConnection.onicecandidate=this.onIceCandidate.bind(this),this.peerConnection.oniceconnectionstatechange=this.onIceConnectionStateChange.bind(this),this.peerConnection.onconnectionstatechange=this.onConnectionStateChange.bind(this),this.peerConnection.addEventListener("track",this.onTrackEventHandler.bind(this)),yield this.setupDataChannels(),this.peerConnection.addTransceiver("video",{direction:"recvonly"}),this.disableInputAudio?this.peerConnection.addTransceiver("audio",{direction:"recvonly"}):(this.peerConnection.addTransceiver("audio",{direction:"sendrecv"}),this.inputAudioStream?yield this.setupAudioTrack():this.requestMicrophonePermissionAsync().catch(e=>{console.error("Async microphone permission request failed:",e)}))})}onSignalMessage(e){return st(this,void 0,void 0,function*(){if(!this.peerConnection){console.error("StreamingClient - onSignalMessage: peerConnection is not initialized");return}switch(e.actionType){case Ye.ANSWER:const t=e.payload;yield this.peerConnection.setRemoteDescription(t),this.connectionReceivedAnswer=!0,this.flushRemoteIceCandidateBuffer();break;case Ye.ICE_CANDIDATE:const i=e.payload,r=new RTCIceCandidate(i);this.connectionReceivedAnswer?yield this.peerConnection.addIceCandidate(r):this.remoteIceCandidateBuffer.push(r);break;case Ye.END_SESSION:const n=e.payload;this.publicEventEmitter.emit(oe.CONNECTION_CLOSED,Kt.SERVER_CLOSED_CONNECTION,n),this.shutdown();break;case Ye.WARNING:const o=e.payload;console.warn("Warning received from server: "+o),this.publicEventEmitter.emit(oe.SERVER_WARNING,o);break;case Ye.TALK_STREAM_INTERRUPTED:const a=e.payload;this.publicEventEmitter.emit(oe.TALK_STREAM_INTERRUPTED,a.correlationId);break;case Ye.SESSION_READY:const l=e.sessionId;this.publicEventEmitter.emit(oe.SESSION_READY,l);break;case Ye.HEARTBEAT:break;default:console.warn("StreamingClient - onSignalMessage: unknown signal message action type. Is your anam-sdk version up to date?",e)}})}onSignallingClientConnected(){return st(this,void 0,void 0,function*(){if(!this.peerConnection)try{yield this.initPeerConnectionAndSendOffer()}catch(e){console.error("StreamingClient - onSignallingClientConnected: Error initializing peer connection",e),this.handleWebrtcFailure(e)}})}flushRemoteIceCandidateBuffer(){this.remoteIceCandidateBuffer.forEach(e=>{var t;(t=this.peerConnection)===null||t===void 0||t.addIceCandidate(e)}),this.remoteIceCandidateBuffer=[]}onIceCandidate(e){e.candidate&&this.signallingClient.sendIceCandidate(e.candidate)}onIceConnectionStateChange(){var e,t;(((e=this.peerConnection)===null||e===void 0?void 0:e.iceConnectionState)==="connected"||((t=this.peerConnection)===null||t===void 0?void 0:t.iceConnectionState)==="completed")&&(this.publicEventEmitter.emit(oe.CONNECTION_ESTABLISHED),this.startStatsCollection())}onConnectionStateChange(){var e;((e=this.peerConnection)===null||e===void 0?void 0:e.connectionState)==="closed"&&(console.error("StreamingClient - onConnectionStateChange: Connection closed"),this.handleWebrtcFailure("The connection to our servers was lost. Please try again."))}handleWebrtcFailure(e){console.error({message:"StreamingClient - handleWebrtcFailure: ",err:e}),e.name==="NotAllowedError"&&e.message==="Permission denied"?this.publicEventEmitter.emit(oe.CONNECTION_CLOSED,Kt.MICROPHONE_PERMISSION_DENIED):this.publicEventEmitter.emit(oe.CONNECTION_CLOSED,Kt.WEBRTC_FAILURE);try{this.stopConnection()}catch(t){console.error("StreamingClient - handleWebrtcFailure: error stopping connection",t)}}onTrackEventHandler(e){if(e.track.kind==="video"){if(this.startSuccessMetricPolling(),this.videoStream=e.streams[0],this.publicEventEmitter.emit(oe.VIDEO_STREAM_STARTED,this.videoStream),this.videoElement){this.videoElement.srcObject=this.videoStream;const t=this.videoElement.requestVideoFrameCallback(()=>{var i;(i=this.videoElement)===null||i===void 0||i.cancelVideoFrameCallback(t),this.publicEventEmitter.emit(oe.VIDEO_PLAY_STARTED),this.successMetricFired||(this.successMetricFired=!0,ui(Nt.CLIENT_METRIC_MEASUREMENT_SESSION_SUCCESS,"1",{detectionMethod:"videoElement"}))})}}else e.track.kind==="audio"&&(this.audioStream=e.streams[0],this.publicEventEmitter.emit(oe.AUDIO_STREAM_STARTED,this.audioStream))}setupDataChannels(){return st(this,void 0,void 0,function*(){if(!this.peerConnection){console.error("StreamingClient - setupDataChannels: peer connection is not initialized");return}if(!this.disableInputAudio&&this.inputAudioStream&&!this.inputAudioStream.getAudioTracks().length)throw new Error("StreamingClient - setupDataChannels: user provided stream does not have audio tracks");const e=this.peerConnection.createDataChannel("session",{ordered:!0});e.onopen=()=>{this.dataChannel=e??null},e.onclose=()=>{},e.onmessage=t=>{var i,r,n,o;try{const a=JSON.parse(t.data);switch(a.messageType){case vt.SPEECH_TEXT:this.internalEventEmitter.emit(Fe.WEBRTC_CHAT_MESSAGE_RECEIVED,a.data);break;case vt.CLIENT_TOOL_EVENT:const l=a.data;this.internalEventEmitter.emit(Fe.WEBRTC_CLIENT_TOOL_EVENT_RECEIVED,l);const c=Fu.WebRTCClientToolEventToClientToolEvent(l);this.publicEventEmitter.emit(oe.CLIENT_TOOL_EVENT_RECEIVED,c);break;case vt.TOOL_CALL_STARTED_EVENT:const h=a.data;this.publicEventEmitter.emit(oe.TOOL_CALL_STARTED,this.toolCallManager.WebRTCToolCallStartedEventToToolCallStartedPayload(h)),this.internalEventEmitter.emit(Fe.WEBRTC_TOOL_CALL_STARTED_EVENT_RECEIVED,h);break;case vt.TOOL_CALL_COMPLETED_EVENT:const u=a.data;this.publicEventEmitter.emit(oe.TOOL_CALL_COMPLETED,this.toolCallManager.webRTCToolCallCompletedEventToToolCallCompletedPayload(u)),this.internalEventEmitter.emit(Fe.WEBRTC_TOOL_CALL_COMPLETED_EVENT_RECEIVED,u);break;case vt.TOOL_CALL_FAILED_EVENT:const f=a.data;this.publicEventEmitter.emit(oe.TOOL_CALL_FAILED,this.toolCallManager.webRTCToolCallFailedEventToToolCallFailedPayload(f)),this.internalEventEmitter.emit(Fe.WEBRTC_TOOL_CALL_FAILED_EVENT_RECEIVED,f);break;case vt.REASONING_TEXT:this.internalEventEmitter.emit(Fe.WEBRTC_REASONING_TEXT_MESSAGE_RECEIVED,a.data);break;case vt.USER_SPEECH_STARTED:this.publicEventEmitter.emit(oe.USER_SPEECH_STARTED,(r=(i=a.data)===null||i===void 0?void 0:i.user_action_correlation_id)!==null&&r!==void 0?r:"unknown");break;case vt.USER_SPEECH_ENDED:this.publicEventEmitter.emit(oe.USER_SPEECH_ENDED,(o=(n=a.data)===null||n===void 0?void 0:n.user_action_correlation_id)!==null&&o!==void 0?o:"unknown");break;default:break}}catch(a){console.error("Failed to parse data channel message:",a)}}})}requestMicrophonePermissionAsync(){return st(this,void 0,void 0,function*(){if(this.inputAudioState.permissionState!==Yt.PENDING){this.inputAudioState=Object.assign(Object.assign({},this.inputAudioState),{permissionState:Yt.PENDING}),this.publicEventEmitter.emit(oe.MIC_PERMISSION_PENDING);try{const e={echoCancellation:!0};this.audioDeviceId&&(e.deviceId={exact:this.audioDeviceId}),this.inputAudioStream=yield navigator.mediaDevices.getUserMedia({audio:e}),this.inputAudioState=Object.assign(Object.assign({},this.inputAudioState),{permissionState:Yt.GRANTED}),this.publicEventEmitter.emit(oe.MIC_PERMISSION_GRANTED),yield this.setupAudioTrack()}catch(e){console.error("Failed to get microphone permission:",e),this.inputAudioState=Object.assign(Object.assign({},this.inputAudioState),{permissionState:Yt.DENIED});const t=e instanceof Error?e.message:String(e);this.publicEventEmitter.emit(oe.MIC_PERMISSION_DENIED,t)}}})}setupAudioTrack(){return st(this,void 0,void 0,function*(){if(!this.peerConnection||!this.inputAudioStream)return;if(!this.inputAudioStream.getAudioTracks().length){console.error("StreamingClient - setupAudioTrack: stream does not have audio tracks");return}this.inputAudioState.isMuted&&this.muteAllAudioTracks();const e=this.inputAudioStream.getAudioTracks()[0],i=this.peerConnection.getSenders().find(r=>{var n;return((n=r.track)===null||n===void 0?void 0:n.kind)==="audio"||r.track===null&&r.dtmf!==null});if(i)try{yield i.replaceTrack(e)}catch(r){console.error("Failed to replace audio track:",r),this.peerConnection.addTrack(e,this.inputAudioStream)}else this.peerConnection.addTrack(e,this.inputAudioStream);this.publicEventEmitter.emit(oe.INPUT_AUDIO_STREAM_STARTED,this.inputAudioStream)})}initPeerConnectionAndSendOffer(){return st(this,void 0,void 0,function*(){if(yield this.initPeerConnection(),!this.peerConnection){console.error("StreamingClient - initPeerConnectionAndSendOffer: peer connection is not initialized");return}try{const e=yield this.peerConnection.createOffer();yield this.peerConnection.setLocalDescription(e)}catch(e){console.error("StreamingClient - initPeerConnectionAndSendOffer: error creating offer",e)}if(!this.peerConnection.localDescription)throw new Error("StreamingClient - initPeerConnectionAndSendOffer: local description is null");yield this.signallingClient.sendOffer(this.peerConnection.localDescription)})}shutdown(){return st(this,void 0,void 0,function*(){var e;if(this.showPeerConnectionStatsReport){const t=yield(e=this.peerConnection)===null||e===void 0?void 0:e.getStats();if(t){const i=yx(t,this.peerConnectionStatsReportOutputFormat);i&&console.log(i,void 0,2)}}this.statsCollectionInterval&&(clearInterval(this.statsCollectionInterval),this.statsCollectionInterval=null),this.successMetricPoller&&(clearInterval(this.successMetricPoller),this.successMetricPoller=null),this.successMetricFired=!1;try{this.inputAudioStream&&this.inputAudioStream.getTracks().forEach(t=>{t.stop()}),this.inputAudioStream=null}catch(t){console.error("StreamingClient - shutdown: error stopping input audio stream",t)}try{this.signallingClient.stop()}catch(t){console.error("StreamingClient - shutdown: error stopping signallilng",t)}this.toolCallManager.clearPendingCalls();try{this.peerConnection&&this.peerConnection.connectionState!=="closed"&&(this.peerConnection.onconnectionstatechange=null,this.peerConnection.close(),this.peerConnection=null)}catch(t){console.error("StreamingClient - shutdown: error closing peer connection",t)}})}}class Nx{constructor(e,t){this.reasoning_messages=[],this.publicEventEmitter=e,this.internalEventEmitter=t,this.internalEventEmitter.addListener(Fe.WEBRTC_REASONING_TEXT_MESSAGE_RECEIVED,this.processWebRtcReasoningTextMessageEvent.bind(this))}webRtcTextMessageEventToReasoningStreamEvent(e){return{id:`${e.role}::${e.message_id}`,content:e.content,endOfThought:e.end_of_thought,role:e.role}}processWebRtcReasoningTextMessageEvent(e){const t=this.webRtcTextMessageEventToReasoningStreamEvent(e);this.publicEventEmitter.emit(oe.REASONING_STREAM_EVENT_RECEIVED,t);const i={id:t.id,content:t.content,role:t.role},r=this.reasoning_messages.findIndex(n=>n.id===i.id);if(r!==-1){const n=this.reasoning_messages[r];n.content+=i.content,this.reasoning_messages[r]=n}else this.reasoning_messages.push(i);t.endOfThought&&this.publicEventEmitter.emit(oe.REASONING_HISTORY_UPDATED,this.reasoning_messages)}}var qt=function(s,e,t,i){function r(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(h){try{c(i.next(h))}catch(u){o(u)}}function l(h){try{c(i.throw(h))}catch(u){o(u)}}function c(h){h.done?n(h.value):r(h.value).then(a,l)}c((i=i.apply(s,e||[])).next())})};class Fx{constructor(e,t,i){var r,n,o,a,l;this.inputAudioState={isMuted:!1,permissionState:Yt.NOT_REQUESTED},this.sessionId=null,this.organizationId=null,this.streamingClient=null,this._isStreaming=!1;const c=this.validateClientConfig(e,t,i);if(c)throw new Ne(c,$e.CLIENT_ERROR_CODE_CONFIGURATION_ERROR,400);this.personaConfig=t,this.clientOptions=i,(!((r=i==null?void 0:i.api)===null||r===void 0)&&r.baseUrl||!((n=i==null?void 0:i.api)===null||n===void 0)&&n.apiVersion)&&mx(i.api.baseUrl||Pu,i.api.apiVersion||Io),!((a=(o=i==null?void 0:i.api)===null||o===void 0?void 0:o.apiGateway)===null||a===void 0)&&a.enabled&&gx(i.api.apiGateway),!((l=i==null?void 0:i.metrics)===null||l===void 0)&&l.disableClientMetrics&&_x(!0),this.publicEventEmitter=new Mx,this.internalEventEmitter=new Ax,this.toolCallManager=new Fu(this.publicEventEmitter),this.apiClient=new Tx(e,i==null?void 0:i.apiKey,i==null?void 0:i.api),this.messageHistoryClient=new Rx(this.publicEventEmitter,this.internalEventEmitter),this.reasoningHistoryClient=new Nx(this.publicEventEmitter,this.internalEventEmitter)}decodeJwt(e){try{const t=e.split(".")[1],i=ux.Buffer.from(t,"base64").toString("utf8");return JSON.parse(i)}catch{throw new Error("Invalid session token format")}}validateClientConfig(e,t,i){var r,n;if(!e&&!(i!=null&&i.apiKey))return"Either sessionToken or apiKey must be provided";if(i!=null&&i.apiKey&&e)return"Only one of sessionToken or apiKey should be used";const o=bx((r=i==null?void 0:i.api)===null||r===void 0?void 0:r.apiGateway);if(o)return o;if(e){const a=this.decodeJwt(e);this.organizationId=a.accountId,Li({organizationId:this.organizationId});const l=(n=a.type)===null||n===void 0?void 0:n.toLowerCase();if(l==="legacy")return"Legacy session tokens are no longer supported. Please define your persona when creating your session token. See https://docs.anam.ai/resources/migrating-legacy for more information.";if((l==="ephemeral"||l==="stateful")&&t)return"This session token already contains a persona configuration. Please remove the personaConfig parameter."}else if(!t)return"Missing persona config. Persona configuration must be provided when using apiKey";if(i!=null&&i.voiceDetection){if(i.disableInputAudio)return"Voice detection is disabled because input audio is disabled. Please set disableInputAudio to false to enable voice detection.";if(i.voiceDetection.endOfSpeechSensitivity!==void 0){if(typeof i.voiceDetection.endOfSpeechSensitivity!="number")return"End of speech sensitivity must be a number";if(i.voiceDetection.endOfSpeechSensitivity<0||i.voiceDetection.endOfSpeechSensitivity>1)return"End of speech sensitivity must be between 0 and 1"}}}buildStartSessionOptionsForClient(){var e;const t={};if(!((e=this.clientOptions)===null||e===void 0)&&e.voiceDetection&&(t.voiceDetection=this.clientOptions.voiceDetection),Object.keys(t).length!==0)return t}startSession(e){return qt(this,void 0,void 0,function*(){var t,i,r,n,o,a,l,c,h,u,f,d;const g=this.personaConfig,_=this.buildStartSessionOptionsForClient(),y=yield this.apiClient.startSession(g,_),{sessionId:x,clientConfig:v,engineHost:C,engineProtocol:E,signallingEndpoint:A}=y,{heartbeatIntervalSeconds:w,maxWsReconnectionAttempts:R,iceServers:D}=v;this.sessionId=x,Li({sessionId:this.sessionId});const B=!((t=this.clientOptions)===null||t===void 0)&&t.iceServers?this.clientOptions.iceServers:D;try{this.streamingClient=new Dx(x,{engine:{baseUrl:`${E}://${C}`},signalling:{heartbeatIntervalSeconds:w,maxWsReconnectionAttempts:R,url:{baseUrl:C,protocol:E,signallingPath:A}},iceServers:B,inputAudio:{inputAudioState:this.inputAudioState,userProvidedMediaStream:!((i=this.clientOptions)===null||i===void 0)&&i.disableInputAudio?void 0:e,audioDeviceId:(r=this.clientOptions)===null||r===void 0?void 0:r.audioDeviceId,disableInputAudio:(n=this.clientOptions)===null||n===void 0?void 0:n.disableInputAudio},apiGateway:(a=(o=this.clientOptions)===null||o===void 0?void 0:o.api)===null||a===void 0?void 0:a.apiGateway,metrics:{showPeerConnectionStatsReport:(h=(c=(l=this.clientOptions)===null||l===void 0?void 0:l.metrics)===null||c===void 0?void 0:c.showPeerConnectionStatsReport)!==null&&h!==void 0?h:!1,peerConnectionStatsReportOutputFormat:(d=(f=(u=this.clientOptions)===null||u===void 0?void 0:u.metrics)===null||f===void 0?void 0:f.peerConnectionStatsReportOutputFormat)!==null&&d!==void 0?d:"console"}},this.publicEventEmitter,this.internalEventEmitter,this.toolCallManager)}catch(k){throw Li({sessionId:null}),new Ne("Failed to initialize streaming client",$e.CLIENT_ERROR_CODE_SERVER_ERROR,500,{cause:k instanceof Error?k.message:String(k),sessionId:x})}return x})}startSessionIfNeeded(e){return qt(this,void 0,void 0,function*(){if((!this.sessionId||!this.streamingClient)&&(yield this.startSession(e),!this.sessionId||!this.streamingClient))throw new Ne("Session ID or streaming client is not available after starting session",$e.CLIENT_ERROR_CODE_SERVER_ERROR,500,{cause:"Failed to initialize session properly"})})}stream(e){return qt(this,void 0,void 0,function*(){var t;if(this._isStreaming)throw new Error("Already streaming");const i=Ou();return Li({attemptCorrelationId:i,sessionId:null}),ui(Nt.CLIENT_METRIC_MEASUREMENT_SESSION_ATTEMPT,"1"),!((t=this.clientOptions)===null||t===void 0)&&t.disableInputAudio&&e&&console.warn("AnamClient:Input audio is disabled. User provided audio stream will be ignored."),yield this.startSessionIfNeeded(e),this._isStreaming=!0,new Promise(r=>{var n;const o=[];let a=!1,l=!1;this.publicEventEmitter.addListener(oe.VIDEO_STREAM_STARTED,c=>{o.push(c),a=!0,l&&r(o)}),this.publicEventEmitter.addListener(oe.AUDIO_STREAM_STARTED,c=>{o.push(c),l=!0,a&&r(o)}),(n=this.streamingClient)===null||n===void 0||n.startConnection()})})}streamToVideoAndAudioElements(e,t,i){return qt(this,void 0,void 0,function*(){console.warn("AnamClient: streamToVideoAndAudioElements is deprecated. To avoid possible audio issues, please use streamToVideoElement instead."),yield this.streamToVideoElement(e,i)})}streamToVideoElement(e,t){return qt(this,void 0,void 0,function*(){var i;const r=Ou();Li({attemptCorrelationId:r,sessionId:null}),ui(Nt.CLIENT_METRIC_MEASUREMENT_SESSION_ATTEMPT,"1"),!((i=this.clientOptions)===null||i===void 0)&&i.disableInputAudio&&t&&console.warn("AnamClient:Input audio is disabled. User provided audio stream will be ignored.");try{yield this.startSessionIfNeeded(t)}catch(n){throw n instanceof Ne?n:new Ne("Failed to start session",$e.CLIENT_ERROR_CODE_SERVER_ERROR,500,{cause:n instanceof Error?n.message:String(n),sessionId:this.sessionId})}if(this._isStreaming)throw new Error("Already streaming");if(this._isStreaming=!0,!this.streamingClient)throw new Error("Failed to stream: streaming client is not available");this.streamingClient.setMediaStreamTargetById(e),this.streamingClient.startConnection()})}talk(e){return qt(this,void 0,void 0,function*(){if(!this.streamingClient)throw new Error("Failed to send talk command: session is not started. Have you called startSession?");if(!this._isStreaming)throw new Error("Failed to send talk command: not currently streaming. Have you called stream?");yield this.streamingClient.sendTalkCommand(e)})}sendDataMessage(e){if(this.streamingClient)this.streamingClient.sendDataMessage(e);else throw new Error("Failed to send message: session is not started.")}sendUserMessage(e){if(!this._isStreaming)throw console.warn("AnamClient: Not currently streaming. User message will not be sent."),new Error("Failed to send user message: not currently streaming");const t=this.getActiveSessionId();if(!t)throw new Error("Failed to send user message: no active session");const i=new Date().toISOString().replace("Z",""),r=JSON.stringify({content:e,timestamp:i,session_id:t,message_type:"speech"});this.sendDataMessage(r)}interruptPersona(){if(!this._isStreaming)throw new Error("Failed to send interrupt command: not currently streaming");const e=this.getActiveSessionId();if(!e)throw new Error("Failed to send interrupt command: no active session");const t=JSON.stringify({message_type:"interrupt",session_id:e,timestamp:new Date().toISOString()});this.sendDataMessage(t)}addContext(e){if(!this._isStreaming)throw new Error("Failed to add context: not currently streaming");const t=this.getActiveSessionId();if(!t)throw new Error("Failed to add context: no active session");const i=JSON.stringify({message_type:"context",session_id:t,content:e});this.sendDataMessage(i)}stopStreaming(){return qt(this,void 0,void 0,function*(){this.streamingClient&&(this.publicEventEmitter.emit(oe.CONNECTION_CLOSED,Kt.NORMAL),yield this.streamingClient.stopConnection(),this.streamingClient=null,this.sessionId=null,Li({attemptCorrelationId:null,sessionId:null,organizationId:this.organizationId}),this._isStreaming=!1)})}isStreaming(){return this._isStreaming}setPersonaConfig(e){this.personaConfig=e}getPersonaConfig(){return this.personaConfig}getInputAudioState(){var e;return!((e=this.clientOptions)===null||e===void 0)&&e.disableInputAudio&&console.warn("AnamClient: Audio state will not be used because input audio is disabled."),this.streamingClient&&(this.inputAudioState=this.streamingClient.getInputAudioState()),this.inputAudioState}muteInputAudio(){var e,t;return!((e=this.clientOptions)===null||e===void 0)&&e.disableInputAudio&&console.warn("AnamClient: Input audio is disabled. Muting input audio will have no effect."),this.streamingClient&&!(!((t=this.clientOptions)===null||t===void 0)&&t.disableInputAudio)?this.inputAudioState=this.streamingClient.muteInputAudio():this.inputAudioState=Object.assign(Object.assign({},this.inputAudioState),{isMuted:!0}),this.inputAudioState}unmuteInputAudio(){var e,t;return!((e=this.clientOptions)===null||e===void 0)&&e.disableInputAudio&&console.warn("AnamClient: Input audio is disabled. Unmuting input audio will have no effect."),this.streamingClient&&!(!((t=this.clientOptions)===null||t===void 0)&&t.disableInputAudio)?this.inputAudioState=this.streamingClient.unmuteInputAudio():this.inputAudioState=Object.assign(Object.assign({},this.inputAudioState),{isMuted:!1}),this.inputAudioState}changeAudioInputDevice(e){return qt(this,void 0,void 0,function*(){var t;if(!((t=this.clientOptions)===null||t===void 0)&&t.disableInputAudio)throw new Error("AnamClient: Cannot change audio input device because input audio is disabled.");if(!this._isStreaming)throw new Error("AnamClient: Cannot change audio input device while not streaming. Start streaming first.");if(!this.streamingClient)throw new Error("AnamClient: Cannot change audio input device because streaming client is not available. Start streaming first.");yield this.streamingClient.changeAudioInputDevice(e)})}createTalkMessageStream(e){if(!this.streamingClient)throw new Error("Failed to start talk message stream: session is not started.");if(e&&e.trim()==="")throw new Error("Failed to start talk message stream: correlationId is empty");return this.streamingClient.startTalkMessageStream(e)}createAgentAudioInputStream(e){if(!this.streamingClient)throw new Error("Failed to create agent audio input stream: session is not started.");return this.streamingClient.createAgentAudioInputStream(e)}addListener(e,t){this.publicEventEmitter.addListener(e,t)}removeListener(e,t){this.publicEventEmitter.removeListener(e,t)}getActiveSessionId(){return this.sessionId}registerToolCallHandler(e,t){return this.toolCallManager.registerHandler(e,t)}}const Lx=(s,e)=>new Fx(s,void 0,e);let Lu=0;class Gx{constructor(e){this.onVideoReady=null,this.onConnected=null,this.onDisconnected=null,this.onTalkStreamInterrupted=null,this.onError=null,this.audioInputStream=null,this.videoElement=null,this.videoWrapper=null,this._clipPathInterval=null,this._connected=!1,this._closing=!1,this.client=Lx(e.sessionToken,{disableInputAudio:!0,metrics:{disableClientMetrics:!0}})}get isConnected(){return this._connected}get videoEl(){return this.videoElement}async connect(){var e;try{const t=`anam-avatar-video-${++Lu}`;this.videoWrapper=document.createElement("div"),this.videoWrapper.id=`anam-avatar-wrapper-${Lu}`,this.videoWrapper.style.cssText=`
|
|
938
938
|
position: fixed;
|
|
939
939
|
bottom: 0;
|
|
940
940
|
left: 50%;
|
|
@@ -947,8 +947,8 @@ registerProcessor('pcm-buffer-processor', PcmBufferProcessor)
|
|
|
947
947
|
width: 100%;
|
|
948
948
|
height: auto;
|
|
949
949
|
display: block;
|
|
950
|
-
clip-path:
|
|
951
|
-
`,this.videoWrapper.appendChild(this.videoElement),document.body.appendChild(this.videoWrapper),this.client.addListener(oe.CONNECTION_ESTABLISHED,()=>{var
|
|
950
|
+
clip-path: inset(0 round 16px 16px 0 0);
|
|
951
|
+
`,this.videoWrapper.appendChild(this.videoElement),document.body.appendChild(this.videoWrapper);const i=()=>{this.videoElement&&(this.videoElement.style.clipPath="inset(0 round 16px 16px 0 0)")};this._clipPathInterval=setInterval(i,500),this.client.addListener(oe.CONNECTION_ESTABLISHED,()=>{var r;console.log("[AnamSession] Connection established"),this._connected=!0,(r=this.onConnected)==null||r.call(this)}),this.client.addListener(oe.VIDEO_PLAY_STARTED,()=>{var r;console.log("[AnamSession] Video playing"),this.videoElement&&(this.videoWrapper&&(this.videoWrapper.style.display=""),this.videoElement&&(this.videoElement.style.clipPath="inset(0 round 16px 16px 0 0)"),(r=this.onVideoReady)==null||r.call(this,this.videoElement))}),this.client.addListener(oe.TALK_STREAM_INTERRUPTED,()=>{var r;console.log("[AnamSession] Talk stream interrupted"),(r=this.onTalkStreamInterrupted)==null||r.call(this)}),this.client.addListener(oe.CONNECTION_CLOSED,r=>{var n;console.log("[AnamSession] Connection closed:",r),this._connected=!1,(n=this.onDisconnected)==null||n.call(this,String(r))}),await this.client.streamToVideoElement(t),this.audioInputStream=this.client.createAgentAudioInputStream({encoding:"pcm_s16le",sampleRate:24e3,channels:1}),console.log("[AnamSession] BYO audio input stream ready")}catch(t){const i=t instanceof Error?t:new Error(String(t));throw console.error("[AnamSession] Connection failed:",i.message),(e=this.onError)==null||e.call(this,i),this.close(),i}}sendAudioChunk(e){var t;(t=this.audioInputStream)==null||t.sendAudioChunk(e)}endSequence(){var e;(e=this.audioInputStream)==null||e.endSequence()}interrupt(){this.client.interruptPersona()}close(){if(!this._closing){this._closing=!0,console.log("[AnamSession] Closing..."),this._clipPathInterval&&(clearInterval(this._clipPathInterval),this._clipPathInterval=null);try{this.client.stopStreaming()}catch{}this.videoElement&&(this.videoElement.pause(),this.videoElement.srcObject=null,this.videoElement=null),this.videoWrapper&&(this.videoWrapper.remove(),this.videoWrapper=null),document.querySelectorAll('[id^="anam-avatar-wrapper"]').forEach(e=>e.remove()),document.querySelectorAll('video[id^="anam-avatar-video"]').forEach(e=>{e.pause(),e.remove()}),this.audioInputStream=null,this._connected=!1}}}const Ux=new Set(["a","button","input","select","textarea","details","summary","label","option"]),Wx=new Set(["button","link","menuitem","menuitemcheckbox","menuitemradio","tab","switch","slider","combobox","listbox","option","radio","checkbox","textbox","searchbox","scrollbar"]),Hx=new Set(["h1","h2","h3","h4","h5","h6"]),Vx=["type","role","aria-label","placeholder","value","href","alt","title","name","checked","aria-expanded"];class zx{constructor(){this.elementMap=new Map}analyze(){this.elementMap.clear();let e=0;const t=[];t.push(`Page: ${document.title}`),t.push(`URL: ${location.href}`),t.push("");const i=r=>{if(r.nodeType===Node.TEXT_NODE){const c=(r.textContent??"").trim();c&&c.length>1&&t.push(c);return}if(r.nodeType!==Node.ELEMENT_NODE)return;const n=r,o=n.tagName.toLowerCase();if(!this.isVisible(n)||["script","style","svg","noscript","link","meta"].includes(o)||n.id==="holostaff-widget-root"||n.closest("#holostaff-widget-root"))return;const a=this.isInteractive(n),l=Hx.has(o);if(a||l){const c=e++;this.elementMap.set(c,n);const h=this.getUsefulAttrs(n),u=h?" "+h:"",f=this.getDirectText(n).slice(0,200);if(l){const d=parseInt(o[1]),g="#".repeat(d);t.push(""),t.push(`${g} [${c}]${f}`)}else t.push(`[${c}]<${o}${u}>${f}</${o}>`);return}for(const c of n.childNodes)i(c)};return i(document.body),{text:t.join(`
|
|
952
952
|
`),elementMap:this.elementMap}}getElementByIndex(e){return this.elementMap.get(e)??null}isVisible(e){if(e.offsetWidth===0&&e.offsetHeight===0){const i=e.getBoundingClientRect();if(i.width===0&&i.height===0)return!1}const t=getComputedStyle(e);return!(t.display==="none"||t.visibility==="hidden"||t.opacity==="0")}isInteractive(e){const t=e.tagName.toLowerCase();if(Ux.has(t))return!e.disabled;const i=e.getAttribute("role");if(i&&Wx.has(i))return!0;try{if(getComputedStyle(e).cursor==="pointer")return!0}catch{}return!!(e.hasAttribute("tabindex")&&e.getAttribute("tabindex")!=="-1"||e.isContentEditable&&e.getAttribute("contenteditable")!=="false")}getDirectText(e){return(e.textContent??"").replace(/\s+/g," ").trim()}getUsefulAttrs(e){const t=[];for(const i of Vx){const r=e.getAttribute(i);r&&r.length>0&&r.length<100&&t.push(`${i}="${r}"`)}return t.join(" ")}}const $x=new Set(["scroll_to","click","highlight"]);class jx{constructor(e){this.onToolCall=null,this.fnArgBufs=new Map,this.fnNames=new Map,this.fnCallIds=new Map,this.realtimeSession=e.realtimeSession,this.domAnalyzer=e.domAnalyzer,this.pageActions=e.pageActions,this.overlayActions=e.overlayActions,this.confirmationPrompt=e.confirmationPrompt,this.staffId=e.staffId,this.backendUrl=e.backendUrl}handleMessage(e){var i;switch(e.type){case"response.output_item.added":if(((i=e.item)==null?void 0:i.type)==="function_call"){const r=e.item.id,n=e.item.name,o=e.item.call_id||e.item.id;return this.fnNames.set(r,n),this.fnCallIds.set(r,o),this.fnArgBufs.set(r,""),console.log(`[ToolHandler] Function call started: ${n} (${r})`),!0}return!1;case"response.function_call_arguments.delta":if(e.item_id&&this.fnArgBufs.has(e.item_id)){const r=this.fnArgBufs.get(e.item_id)??"";return this.fnArgBufs.set(e.item_id,r+(e.delta??"")),!0}return!1;case"response.function_call_arguments.done":return e.item_id&&this.fnArgBufs.has(e.item_id)?(this.handleFunctionCallDone(e.item_id),!0):!1;default:return!1}}async handleFunctionCallDone(e){var a;const t=this.fnNames.get(e)??"unknown",i=this.fnCallIds.get(e)??e,r=this.fnArgBufs.get(e)??"{}";this.fnArgBufs.delete(e),this.fnNames.delete(e),this.fnCallIds.delete(e);let n;try{n=JSON.parse(r)}catch{console.warn(`[ToolHandler] Failed to parse args for ${t}:`,r),this.sendToolResult(i,{error:"Malformed JSON in function call arguments"});return}console.log(`[ToolHandler] Executing: ${t}`,n),(a=this.onToolCall)==null||a.call(this,t,n);let o=null;switch(t){case"page_action":await this.handlePageAction(i,n.instruction??"");return;case"show_text_card":o=this.overlayActions.showTextCard(n.title??"",n.body??"");break;case"show_image_card":o=this.overlayActions.showImageCard(n.image_url??"",n.caption);break;case"show_bullet_list":o=this.overlayActions.showBulletList(n.title??"",n.items??[]);break;case"dismiss_overlays":o=this.overlayActions.dismissAll();break;default:console.warn(`[ToolHandler] Unknown tool: ${t}`),o={error:`Unknown tool: ${t}`}}this.sendToolResult(i,o)}async handlePageAction(e,t){try{const{text:i}=this.domAnalyzer.analyze();console.log(`[ToolHandler] DOM snapshot: ${i.length} chars, instruction: "${t}"`);const n=(await Zd(this.staffId,i,t,this.backendUrl)).actions??[];console.log(`[ToolHandler] Page agent returned ${n.length} actions:`,n);const o=[];for(const a of n){if(a.action==="describe"){o.push({action:"describe",status:"ok",description:a.description});continue}if($x.has(a.action)&&!await this.confirmationPrompt.ask(`${a.description}?`)){o.push({action:a.action,status:"declined",description:"Visitor declined"});continue}let l;switch(a.action){case"scroll_to":l=this.pageActions.scrollTo(a.index);break;case"highlight":l=this.pageActions.highlight(a.index);break;case"click":l=this.pageActions.click(a.index);break;case"fill":l=this.pageActions.fill(a.index,a.value??"");break;default:l={status:"error",description:`Unknown action: ${a.action}`}}o.push({action:a.action,...l})}this.sendToolResult(e,{results:o})}catch(i){const r=i instanceof Error?i.message:String(i);console.error("[ToolHandler] Page action failed:",r),this.sendToolResult(e,{error:r})}}sendToolResult(e,t){this.realtimeSession.sendJSON({type:"conversation.item.create",item:{type:"function_call_output",call_id:e,output:JSON.stringify(t)}}),this.realtimeSession.sendJSON({type:"response.create"})}}class Xx{constructor(e,t){this.analyzer=e,this.highlightRenderer=t}scrollTo(e){const t=this.analyzer.getElementByIndex(e);if(!t)return{status:"error",description:`Element [${e}] not found`};t.scrollIntoView({behavior:"smooth",block:"center"});const i=this.describeElement(t);return console.log(`[PageActions] Scrolled to [${e}] ${i}`),{status:"scrolled",description:i}}highlight(e,t=3e3){const i=this.analyzer.getElementByIndex(e);if(!i)return{status:"error",description:`Element [${e}] not found`};this.highlightRenderer.highlight(i,t);const r=this.describeElement(i);return console.log(`[PageActions] Highlighting [${e}] ${r} for ${t}ms`),{status:"highlighted",description:r}}click(e){const t=this.analyzer.getElementByIndex(e);if(!t)return{status:"error",description:`Element [${e}] not found`};t.click();const i=this.describeElement(t);return console.log(`[PageActions] Clicked [${e}] ${i}`),{status:"clicked",description:i}}fill(e,t){var a,l;const i=this.analyzer.getElementByIndex(e);if(!i)return{status:"error",description:`Element [${e}] not found`};const r=i.tagName.toLowerCase(),n=(a=i.type)==null?void 0:a.toLowerCase();if(r==="select"){const c=i,h=Array.from(c.options).find(u=>u.text.toLowerCase().includes(t.toLowerCase())||u.value.toLowerCase()===t.toLowerCase());if(h)c.value=h.value,c.dispatchEvent(new Event("change",{bubbles:!0}));else return{status:"error",description:`No option matching "${t}"`}}else if(n==="checkbox"||n==="radio"){const c=i;c.checked=t==="true"||t==="1",c.dispatchEvent(new Event("change",{bubbles:!0}))}else{const c=(l=Object.getOwnPropertyDescriptor(r==="textarea"?HTMLTextAreaElement.prototype:HTMLInputElement.prototype,"value"))==null?void 0:l.set;c?c.call(i,t):i.value=t,i.dispatchEvent(new Event("input",{bubbles:!0})),i.dispatchEvent(new Event("change",{bubbles:!0}))}const o=this.describeElement(i);return console.log(`[PageActions] Filled [${e}] ${o} with "${t}"`),{status:"filled",description:`${o} = "${t}"`}}describeElement(e){const t=e.tagName.toLowerCase(),i=(e.textContent??"").trim().slice(0,50),r=e.getAttribute("aria-label")||e.getAttribute("placeholder")||i;return`<${t}>${r}</${t}>`}}class Yx{constructor(e){this.renderer=e}showTextCard(e,t){return this.renderer.showTextCard(e,t),console.log(`[OverlayActions] Showing text card: "${e}"`),{status:"shown"}}showImageCard(e,t){return this.renderer.showImageCard(e,t),console.log(`[OverlayActions] Showing image card: "${t??e}"`),{status:"shown"}}showBulletList(e,t){return this.renderer.showBulletList(e,t),console.log(`[OverlayActions] Showing bullet list: "${e}" (${t.length} items)`),{status:"shown"}}dismissAll(){return this.renderer.dismissAll(),console.log("[OverlayActions] Dismissed all overlays"),{status:"dismissed"}}}class Kx{constructor(){this.activeHighlights=[]}highlight(e,t=3e3){const i=e.getBoundingClientRect(),r=document.createElement("div");Object.assign(r.style,{position:"fixed",left:`${i.left-4}px`,top:`${i.top-4}px`,width:`${i.width+8}px`,height:`${i.height+8}px`,border:"3px solid #4a6fa5",borderRadius:"8px",boxShadow:"0 0 12px rgba(74, 111, 165, 0.5)",pointerEvents:"none",zIndex:"2147483645",animation:"hs-highlight-pulse 1.2s ease-in-out infinite",transition:"opacity 0.3s ease"}),this.ensureKeyframes(),document.body.appendChild(r),this.activeHighlights.push(r);const n=()=>{const o=e.getBoundingClientRect();r.style.left=`${o.left-4}px`,r.style.top=`${o.top-4}px`,r.style.width=`${o.width+8}px`,r.style.height=`${o.height+8}px`};window.addEventListener("scroll",n,{passive:!0}),setTimeout(()=>{r.style.opacity="0",setTimeout(()=>{r.remove(),window.removeEventListener("scroll",n),this.activeHighlights=this.activeHighlights.filter(o=>o!==r)},300)},t)}clearAll(){for(const e of this.activeHighlights)e.remove();this.activeHighlights=[]}ensureKeyframes(){if(document.getElementById("hs-highlight-keyframes"))return;const e=document.createElement("style");e.id="hs-highlight-keyframes",e.textContent=`
|
|
953
953
|
@keyframes hs-highlight-pulse {
|
|
954
954
|
0%, 100% { box-shadow: 0 0 8px rgba(74, 111, 165, 0.4); border-color: #4a6fa5; }
|