ttp-agent-sdk 2.4.21 → 2.4.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/agent-widget.js +1 -1
- package/dist/agent-widget.js.map +1 -1
- package/package.json +1 -1
package/dist/agent-widget.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
/*! For license information please see agent-widget.js.LICENSE.txt */
|
|
2
|
-
!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.TTPAgentSDK=t():e.TTPAgentSDK=t()}(window,()=>(()=>{"use strict";var e={540:(e,t,n)=>{e.exports=n(869)},698:(e,t)=>{var n=Symbol.for("react.transitional.element");function o(e,t,o){var r=null;if(void 0!==o&&(r=""+o),void 0!==t.key&&(r=""+t.key),"key"in t)for(var i in o={},t)"key"!==i&&(o[i]=t[i]);else o=t;return t=o.ref,{$$typeof:n,type:e,key:r,ref:void 0!==t?t:null,props:o}}Symbol.for("react.fragment"),t.jsx=o,t.jsxs=o},848:(e,t,n)=>{e.exports=n(698)},869:(e,t)=>{Symbol.for("react.transitional.element"),Symbol.for("react.portal"),Symbol.for("react.fragment"),Symbol.for("react.strict_mode"),Symbol.for("react.profiler"),Symbol.for("react.consumer"),Symbol.for("react.context"),Symbol.for("react.forward_ref"),Symbol.for("react.suspense"),Symbol.for("react.memo"),Symbol.for("react.lazy"),Symbol.for("react.activity"),Symbol.iterator;var n={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},o=Object.assign,r={};function i(e,t,o){this.props=e,this.context=t,this.refs=r,this.updater=o||n}function a(){}function c(e,t,o){this.props=e,this.context=t,this.refs=r,this.updater=o||n}i.prototype.isReactComponent={},i.prototype.setState=function(e,t){if("object"!=typeof e&&"function"!=typeof e&&null!=e)throw Error("takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,e,t,"setState")},i.prototype.forceUpdate=function(e){this.updater.enqueueForceUpdate(this,e,"forceUpdate")},a.prototype=i.prototype;var s=c.prototype=new a;s.constructor=c,o(s,i.prototype),s.isPureReactComponent=!0;Array.isArray;var u={H:null,A:null,T:null,S:null};Object.prototype.hasOwnProperty;"function"==typeof reportError&&reportError;t.useEffect=function(e,t){return u.H.useEffect(e,t)},t.useRef=function(e){return u.H.useRef(e)},t.useState=function(e){return u.H.useState(e)}}},t={};function n(o){var r=t[o];if(void 0!==r)return r.exports;var i=t[o]={exports:{}};return e[o](i,i.exports,n),i.exports}n.d=(e,t)=>{for(var o in t)n.o(t,o)&&!n.o(e,o)&&Object.defineProperty(e,o,{enumerable:!0,get:t[o]})},n.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),n.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};var o={};function r(e){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},r(e)}function i(e,t){for(var n=0;n<t.length;n++){var o=t[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(e,a(o.key),o)}}function a(e){var t=function(e){if("object"!=r(e)||!e)return e;var t=e[Symbol.toPrimitive];if(void 0!==t){var n=t.call(e,"string");if("object"!=r(n))return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}(e);return"symbol"==r(t)?t:t+""}n.r(o),n.d(o,{AgentSDK:()=>Kn,AudioPlayer:()=>ee,AudioRecorder:()=>z,EventEmitter:()=>c,TTPChatWidget:()=>yo,TextChatSDK:()=>pn,VERSION:()=>mo,VanillaVoiceButton:()=>Bn,VoiceButton:()=>kn,VoiceSDK:()=>he,VoiceSDK_v2:()=>Xt,WebSocketManager:()=>j,default:()=>bo});var c=function(){return e=function e(){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),this.events={}},t=[{key:"on",value:function(e,t){this.events[e]||(this.events[e]=[]),this.events[e].push(t)}},{key:"off",value:function(e,t){this.events[e]&&(this.events[e]=this.events[e].filter(function(e){return e!==t}))}},{key:"emit",value:function(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),o=1;o<t;o++)n[o-1]=arguments[o];this.events[e]&&this.events[e].forEach(function(t){try{t.apply(void 0,n)}catch(t){console.error("Error in event listener for ".concat(e,":"),t)}})}},{key:"removeAllListeners",value:function(e){e?delete this.events[e]:this.events={}}}],t&&i(e.prototype,t),Object.defineProperty(e,"prototype",{writable:!1}),e;var e,t}();function s(e){return s="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},s(e)}function u(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var n=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=n){var o,r,i,a,c=[],s=!0,u=!1;try{if(i=(n=n.call(e)).next,0===t){if(Object(n)!==n)return;s=!1}else for(;!(s=(o=i.call(n)).done)&&(c.push(o.value),c.length!==t);s=!0);}catch(e){u=!0,r=e}finally{try{if(!s&&null!=n.return&&(a=n.return(),Object(a)!==a))return}finally{if(u)throw r}}return c}}(e,t)||d(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function l(e,t){var n="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!n){if(Array.isArray(e)||(n=d(e))||t&&e&&"number"==typeof e.length){n&&(e=n);var o=0,r=function(){};return{s:r,n:function(){return o>=e.length?{done:!0}:{done:!1,value:e[o++]}},e:function(e){throw e},f:r}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var i,a=!0,c=!1;return{s:function(){n=n.call(e)},n:function(){var e=n.next();return a=e.done,e},e:function(e){c=!0,i=e},f:function(){try{a||null==n.return||n.return()}finally{if(c)throw i}}}}function d(e,t){if(e){if("string"==typeof e)return p(e,t);var n={}.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?p(e,t):void 0}}function p(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,o=Array(t);n<t;n++)o[n]=e[n];return o}function f(){var e,t,n="function"==typeof Symbol?Symbol:{},o=n.iterator||"@@iterator",r=n.toStringTag||"@@toStringTag";function i(n,o,r,i){var s=o&&o.prototype instanceof c?o:c,u=Object.create(s.prototype);return h(u,"_invoke",function(n,o,r){var i,c,s,u=0,l=r||[],d=!1,p={p:0,n:0,v:e,a:f,f:f.bind(e,4),d:function(t,n){return i=t,c=0,s=e,p.n=n,a}};function f(n,o){for(c=n,s=o,t=0;!d&&u&&!r&&t<l.length;t++){var r,i=l[t],f=p.p,h=i[2];n>3?(r=h===o)&&(s=i[(c=i[4])?5:(c=3,3)],i[4]=i[5]=e):i[0]<=f&&((r=n<2&&f<i[1])?(c=0,p.v=o,p.n=i[1]):f<h&&(r=n<3||i[0]>o||o>h)&&(i[4]=n,i[5]=o,p.n=h,c=0))}if(r||n>1)return a;throw d=!0,o}return function(r,l,h){if(u>1)throw TypeError("Generator is already running");for(d&&1===l&&f(l,h),c=l,s=h;(t=c<2?e:s)||!d;){i||(c?c<3?(c>1&&(p.n=-1),f(c,s)):p.n=s:p.v=s);try{if(u=2,i){if(c||(r="next"),t=i[r]){if(!(t=t.call(i,s)))throw TypeError("iterator result is not an object");if(!t.done)return t;s=t.value,c<2&&(c=0)}else 1===c&&(t=i.return)&&t.call(i),c<2&&(s=TypeError("The iterator does not provide a '"+r+"' method"),c=1);i=e}else if((t=(d=p.n<0)?s:n.call(o,p))!==a)break}catch(t){i=e,c=1,s=t}finally{u=1}}return{value:t,done:d}}}(n,r,i),!0),u}var a={};function c(){}function s(){}function u(){}t=Object.getPrototypeOf;var l=[][o]?t(t([][o]())):(h(t={},o,function(){return this}),t),d=u.prototype=c.prototype=Object.create(l);function p(e){return Object.setPrototypeOf?Object.setPrototypeOf(e,u):(e.__proto__=u,h(e,r,"GeneratorFunction")),e.prototype=Object.create(d),e}return s.prototype=u,h(d,"constructor",u),h(u,"constructor",s),s.displayName="GeneratorFunction",h(u,r,"GeneratorFunction"),h(d),h(d,r,"Generator"),h(d,o,function(){return this}),h(d,"toString",function(){return"[object Generator]"}),(f=function(){return{w:i,m:p}})()}function h(e,t,n,o){var r=Object.defineProperty;try{r({},"",{})}catch(e){r=0}h=function(e,t,n,o){function i(t,n){h(e,t,function(e){return this._invoke(t,n,e)})}t?r?r(e,t,{value:n,enumerable:!o,configurable:!o,writable:!o}):e[t]=n:(i("next",0),i("throw",1),i("return",2))},h(e,t,n,o)}function v(e,t,n,o,r,i,a){try{var c=e[i](a),s=c.value}catch(e){return void n(e)}c.done?t(s):Promise.resolve(s).then(o,r)}function g(e,t){for(var n=0;n<t.length;n++){var o=t[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(e,y(o.key),o)}}function y(e){var t=function(e){if("object"!=s(e)||!e)return e;var t=e[Symbol.toPrimitive];if(void 0!==t){var n=t.call(e,"string");if("object"!=s(n))return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}(e);return"symbol"==s(t)?t:t+""}function m(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(e){}return(m=function(){return!!e})()}function b(e){return b=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(e){return e.__proto__||Object.getPrototypeOf(e)},b(e)}function S(e,t){return S=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,t){return e.__proto__=t,e},S(e,t)}const w=new(function(e){function t(){var e;return function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,t),(e=function(e,t,n){return t=b(t),function(e,t){if(t&&("object"==s(t)||"function"==typeof t))return t;if(void 0!==t)throw new TypeError("Derived constructors may only return object or undefined");return function(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}(e)}(e,m()?Reflect.construct(t,n||[],b(e).constructor):t.apply(e,n))}(this,t)).connections=new Map,e.connectionCounts=new Map,e.creatingConnections=new Set,e}return function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&S(e,t)}(t,e),n=t,o=[{key:"getConnection",value:(r=f().m(function e(t){var n,o,r=this;return f().w(function(e){for(;;)switch(e.n){case 0:if(!this.connections.has(t)){e.n=1;break}return n=this.connections.get(t),this.connectionCounts.set(t,(this.connectionCounts.get(t)||0)+1),e.a(2,n);case 1:if(!this.creatingConnections||!this.creatingConnections.has(t)){e.n=2;break}return e.a(2,new Promise(function(e){var n=function(){if(r.connections.has(t)){var o=r.connections.get(t);r.connectionCounts.set(t,(r.connectionCounts.get(t)||0)+1),e(o)}else setTimeout(n,50)};n()}));case 2:return this.creatingConnections.add(t),o=new WebSocket(t),this.connections.set(t,o),this.connectionCounts.set(t,1),o.addEventListener("open",function(e){r.creatingConnections.delete(t),r.emit("open",e,t)}),o.addEventListener("close",function(e){r.creatingConnections.delete(t),r.connections.delete(t),r.connectionCounts.delete(t),r.emit("close",e,t)}),o.addEventListener("error",function(e){r.creatingConnections.delete(t),r.emit("error",e,t)}),o.addEventListener("message",function(e){r.emit("message",e,t)}),e.a(2,o)}},e,this)}),i=function(){var e=this,t=arguments;return new Promise(function(n,o){var i=r.apply(e,t);function a(e){v(i,n,o,a,c,"next",e)}function c(e){v(i,n,o,a,c,"throw",e)}a(void 0)})},function(e){return i.apply(this,arguments)})},{key:"releaseConnection",value:function(e){if(this.connections.has(e)){var t=this.connectionCounts.get(e)||0,n=Math.max(0,t-1);if(this.connectionCounts.set(e,n),0===n){var o=this.connections.get(e);o&&o.readyState===WebSocket.OPEN&&o.close(1e3,"No more subscribers"),this.connections.delete(e),this.connectionCounts.delete(e)}}}},{key:"forceClose",value:function(e){if(this.connections.has(e)){var t=this.connections.get(e);t&&t.readyState===WebSocket.OPEN&&t.close(1e3,"Force close"),this.connections.delete(e),this.connectionCounts.delete(e)}}},{key:"getConnectionStatus",value:function(e){return this.connections.has(e)?{exists:!0,readyState:this.connections.get(e).readyState,subscribers:this.connectionCounts.get(e)||0}:{exists:!1,readyState:null,subscribers:0}}},{key:"getAllConnections",value:function(){var e,t={},n=l(this.connections.entries());try{for(n.s();!(e=n.n()).done;){var o=u(e.value,2),r=o[0],i=o[1];t[r]={readyState:i.readyState,subscribers:this.connectionCounts.get(r)||0}}}catch(e){n.e(e)}finally{n.f()}return t}},{key:"clearAll",value:function(){var e,t=l(this.connections.entries());try{for(t.s();!(e=t.n()).done;){var n=u(e.value,2),o=(n[0],n[1]);o&&o.readyState===WebSocket.OPEN&&o.close(1e3,"Clear all")}}catch(e){t.e(e)}finally{t.f()}this.connections.clear(),this.connectionCounts.clear(),this.creatingConnections.clear()}}],o&&g(n.prototype,o),Object.defineProperty(n,"prototype",{writable:!1}),n;var n,o,r,i}(c));function x(e){return x="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},x(e)}function C(){var e,t,n="function"==typeof Symbol?Symbol:{},o=n.iterator||"@@iterator",r=n.toStringTag||"@@toStringTag";function i(n,o,r,i){var s=o&&o.prototype instanceof c?o:c,u=Object.create(s.prototype);return k(u,"_invoke",function(n,o,r){var i,c,s,u=0,l=r||[],d=!1,p={p:0,n:0,v:e,a:f,f:f.bind(e,4),d:function(t,n){return i=t,c=0,s=e,p.n=n,a}};function f(n,o){for(c=n,s=o,t=0;!d&&u&&!r&&t<l.length;t++){var r,i=l[t],f=p.p,h=i[2];n>3?(r=h===o)&&(s=i[(c=i[4])?5:(c=3,3)],i[4]=i[5]=e):i[0]<=f&&((r=n<2&&f<i[1])?(c=0,p.v=o,p.n=i[1]):f<h&&(r=n<3||i[0]>o||o>h)&&(i[4]=n,i[5]=o,p.n=h,c=0))}if(r||n>1)return a;throw d=!0,o}return function(r,l,h){if(u>1)throw TypeError("Generator is already running");for(d&&1===l&&f(l,h),c=l,s=h;(t=c<2?e:s)||!d;){i||(c?c<3?(c>1&&(p.n=-1),f(c,s)):p.n=s:p.v=s);try{if(u=2,i){if(c||(r="next"),t=i[r]){if(!(t=t.call(i,s)))throw TypeError("iterator result is not an object");if(!t.done)return t;s=t.value,c<2&&(c=0)}else 1===c&&(t=i.return)&&t.call(i),c<2&&(s=TypeError("The iterator does not provide a '"+r+"' method"),c=1);i=e}else if((t=(d=p.n<0)?s:n.call(o,p))!==a)break}catch(t){i=e,c=1,s=t}finally{u=1}}return{value:t,done:d}}}(n,r,i),!0),u}var a={};function c(){}function s(){}function u(){}t=Object.getPrototypeOf;var l=[][o]?t(t([][o]())):(k(t={},o,function(){return this}),t),d=u.prototype=c.prototype=Object.create(l);function p(e){return Object.setPrototypeOf?Object.setPrototypeOf(e,u):(e.__proto__=u,k(e,r,"GeneratorFunction")),e.prototype=Object.create(d),e}return s.prototype=u,k(d,"constructor",u),k(u,"constructor",s),s.displayName="GeneratorFunction",k(u,r,"GeneratorFunction"),k(d),k(d,r,"Generator"),k(d,o,function(){return this}),k(d,"toString",function(){return"[object Generator]"}),(C=function(){return{w:i,m:p}})()}function k(e,t,n,o){var r=Object.defineProperty;try{r({},"",{})}catch(e){r=0}k=function(e,t,n,o){function i(t,n){k(e,t,function(e){return this._invoke(t,n,e)})}t?r?r(e,t,{value:n,enumerable:!o,configurable:!o,writable:!o}):e[t]=n:(i("next",0),i("throw",1),i("return",2))},k(e,t,n,o)}function P(e,t,n,o,r,i,a){try{var c=e[i](a),s=c.value}catch(e){return void n(e)}c.done?t(s):Promise.resolve(s).then(o,r)}function O(e,t){for(var n=0;n<t.length;n++){var o=t[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(e,E(o.key),o)}}function E(e){var t=function(e){if("object"!=x(e)||!e)return e;var t=e[Symbol.toPrimitive];if(void 0!==t){var n=t.call(e,"string");if("object"!=x(n))return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}(e);return"symbol"==x(t)?t:t+""}function T(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(e){}return(T=function(){return!!e})()}function A(e){return A=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(e){return e.__proto__||Object.getPrototypeOf(e)},A(e)}function I(e,t){return I=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,t){return e.__proto__=t,e},I(e,t)}var j=function(e){function t(e){var n;return function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,t),(n=function(e,t,n){return t=A(t),function(e,t){if(t&&("object"==x(t)||"function"==typeof t))return t;if(void 0!==t)throw new TypeError("Derived constructors may only return object or undefined");return function(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}(e)}(e,T()?Reflect.construct(t,n||[],A(e).constructor):t.apply(e,n))}(this,t)).config=e,n.ws=null,n.isConnected=!1,n.connectionId=null,n}return function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&I(e,t)}(t,e),n=t,o=[{key:"connect",value:(i=C().m(function e(){var t=this;return C().w(function(e){for(;;)if(0===e.n)return e.a(2,new Promise(function(e,n){try{t.connectionId=Date.now()+"_"+Math.random().toString(36).substr(2,9),t.connectResolve=e,t.connectReject=n,w.getConnection(t.config.websocketUrl,t.config).then(function(n){t.ws=n,t.setupEventListeners(),n.readyState===WebSocket.OPEN&&(t.isConnected=!0,t.emit("connected"),e(),t.connectResolve=null,t.connectReject=null)}).catch(function(e){console.error("🔌 WebSocketManager: Connection failed ".concat(t.connectionId),e),n(e),t.connectResolve=null,t.connectReject=null})}catch(e){console.error("🔌 WebSocketManager: Connection error ".concat(t.connectionId),e),n(e),t.connectResolve=null,t.connectReject=null}}))},e)}),a=function(){var e=this,t=arguments;return new Promise(function(n,o){var r=i.apply(e,t);function a(e){P(r,n,o,a,c,"next",e)}function c(e){P(r,n,o,a,c,"throw",e)}a(void 0)})},function(){return a.apply(this,arguments)})},{key:"setupEventListeners",value:function(){var e=this;if(this.ws){var t=function(t,n){n===e.config.websocketUrl&&(e.isConnected=!0,e.emit("connected"),e.connectResolve&&(e.connectResolve(),e.connectResolve=null,e.connectReject=null))},n=function(t,n){n===e.config.websocketUrl&&(e.isConnected=!1,e.emit("disconnected",t))},o=function(t,n){n===e.config.websocketUrl&&(e.emit("error",t),e.connectReject&&(e.connectReject(t),e.connectResolve=null,e.connectReject=null))},r=function(t,n){n===e.config.websocketUrl&&e.handleMessage(t)};w.on("open",t),w.on("close",n),w.on("error",o),w.on("message",r),this.eventHandlers={open:t,close:n,error:o,message:r}}}},{key:"disconnect",value:function(){this.eventHandlers&&(w.off("open",this.eventHandlers.open),w.off("close",this.eventHandlers.close),w.off("error",this.eventHandlers.error),w.off("message",this.eventHandlers.message)),this.config.websocketUrl&&w.releaseConnection(this.config.websocketUrl),this.ws=null,this.isConnected=!1}},{key:"sendMessage",value:function(e){if(this.isConnected&&this.ws)try{this.ws.send(JSON.stringify(e))}catch(e){console.warn("🔌 WebSocketManager: Failed to send message:",e.message)}}},{key:"sendBinary",value:function(e){if(this.isConnected&&this.ws)try{this.ws.send(e)}catch(e){console.warn("🔌 WebSocketManager: Failed to send binary data:",e.message)}}},{key:"handleMessage",value:function(e){var t=this;if(e.data instanceof ArrayBuffer)this.emit("binaryAudio",e.data);else if(e.data instanceof Blob)e.data.arrayBuffer().then(function(e){t.emit("binaryAudio",e)}).catch(function(e){console.error("🔌 WebSocketManager: Error converting Blob to ArrayBuffer:",e)});else try{var n=JSON.parse(e.data);"barge_in_ack"!==n.t&&"stop_sending"!==n.t||this.emit("bargeIn",n),"stop_playing"===n.t&&this.emit("stopPlaying",n),this.emit("message",n)}catch(e){this.emit("error",e)}}},{key:"getStatus",value:function(){return{isConnected:this.isConnected,readyState:this.ws?this.ws.readyState:null,connectionId:this.connectionId}}}],r=[{key:"getSingletonStatus",value:function(){return w.getAllConnections()}},{key:"clearAllConnections",value:function(){w.clearAll()}}],o&&O(n.prototype,o),r&&O(n,r),Object.defineProperty(n,"prototype",{writable:!1}),n;var n,o,r,i,a}(c);function D(e){return D="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},D(e)}function F(){var e,t,n="function"==typeof Symbol?Symbol:{},o=n.iterator||"@@iterator",r=n.toStringTag||"@@toStringTag";function i(n,o,r,i){var s=o&&o.prototype instanceof c?o:c,u=Object.create(s.prototype);return B(u,"_invoke",function(n,o,r){var i,c,s,u=0,l=r||[],d=!1,p={p:0,n:0,v:e,a:f,f:f.bind(e,4),d:function(t,n){return i=t,c=0,s=e,p.n=n,a}};function f(n,o){for(c=n,s=o,t=0;!d&&u&&!r&&t<l.length;t++){var r,i=l[t],f=p.p,h=i[2];n>3?(r=h===o)&&(s=i[(c=i[4])?5:(c=3,3)],i[4]=i[5]=e):i[0]<=f&&((r=n<2&&f<i[1])?(c=0,p.v=o,p.n=i[1]):f<h&&(r=n<3||i[0]>o||o>h)&&(i[4]=n,i[5]=o,p.n=h,c=0))}if(r||n>1)return a;throw d=!0,o}return function(r,l,h){if(u>1)throw TypeError("Generator is already running");for(d&&1===l&&f(l,h),c=l,s=h;(t=c<2?e:s)||!d;){i||(c?c<3?(c>1&&(p.n=-1),f(c,s)):p.n=s:p.v=s);try{if(u=2,i){if(c||(r="next"),t=i[r]){if(!(t=t.call(i,s)))throw TypeError("iterator result is not an object");if(!t.done)return t;s=t.value,c<2&&(c=0)}else 1===c&&(t=i.return)&&t.call(i),c<2&&(s=TypeError("The iterator does not provide a '"+r+"' method"),c=1);i=e}else if((t=(d=p.n<0)?s:n.call(o,p))!==a)break}catch(t){i=e,c=1,s=t}finally{u=1}}return{value:t,done:d}}}(n,r,i),!0),u}var a={};function c(){}function s(){}function u(){}t=Object.getPrototypeOf;var l=[][o]?t(t([][o]())):(B(t={},o,function(){return this}),t),d=u.prototype=c.prototype=Object.create(l);function p(e){return Object.setPrototypeOf?Object.setPrototypeOf(e,u):(e.__proto__=u,B(e,r,"GeneratorFunction")),e.prototype=Object.create(d),e}return s.prototype=u,B(d,"constructor",u),B(u,"constructor",s),s.displayName="GeneratorFunction",B(u,r,"GeneratorFunction"),B(d),B(d,r,"Generator"),B(d,o,function(){return this}),B(d,"toString",function(){return"[object Generator]"}),(F=function(){return{w:i,m:p}})()}function B(e,t,n,o){var r=Object.defineProperty;try{r({},"",{})}catch(e){r=0}B=function(e,t,n,o){function i(t,n){B(e,t,function(e){return this._invoke(t,n,e)})}t?r?r(e,t,{value:n,enumerable:!o,configurable:!o,writable:!o}):e[t]=n:(i("next",0),i("throw",1),i("return",2))},B(e,t,n,o)}function R(e,t,n,o,r,i,a){try{var c=e[i](a),s=c.value}catch(e){return void n(e)}c.done?t(s):Promise.resolve(s).then(o,r)}function _(e){return function(){var t=this,n=arguments;return new Promise(function(o,r){var i=e.apply(t,n);function a(e){R(i,o,r,a,c,"next",e)}function c(e){R(i,o,r,a,c,"throw",e)}a(void 0)})}}function U(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,o=Array(t);n<t;n++)o[n]=e[n];return o}function M(e,t){for(var n=0;n<t.length;n++){var o=t[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(e,N(o.key),o)}}function N(e){var t=function(e){if("object"!=D(e)||!e)return e;var t=e[Symbol.toPrimitive];if(void 0!==t){var n=t.call(e,"string");if("object"!=D(n))return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}(e);return"symbol"==D(t)?t:t+""}function V(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(e){}return(V=function(){return!!e})()}function L(e){return L=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(e){return e.__proto__||Object.getPrototypeOf(e)},L(e)}function K(e,t){return K=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,t){return e.__proto__=t,e},K(e,t)}var z=function(e){function t(e){var n;return function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,t),(n=function(e,t,n){return t=L(t),function(e,t){if(t&&("object"==D(t)||"function"==typeof t))return t;if(void 0!==t)throw new TypeError("Derived constructors may only return object or undefined");return function(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}(e)}(e,V()?Reflect.construct(t,n||[],L(e).constructor):t.apply(e,n))}(this,t)).config=e,n.audioContext=null,n.audioWorkletNode=null,n.mediaStream=null,n.isRecording=!1,n}return function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&K(e,t)}(t,e),n=t,o=[{key:"getAudioProcessorPath",value:function(){if(this.config.audioProcessorPath)return this.config.audioProcessorPath;var e,t=function(e,t){var n="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!n){if(Array.isArray(e)||(n=function(e,t){if(e){if("string"==typeof e)return U(e,t);var n={}.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?U(e,t):void 0}}(e))||t&&e&&"number"==typeof e.length){n&&(e=n);var o=0,r=function(){};return{s:r,n:function(){return o>=e.length?{done:!0}:{done:!1,value:e[o++]}},e:function(e){throw e},f:r}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var i,a=!0,c=!1;return{s:function(){n=n.call(e)},n:function(){var e=n.next();return a=e.done,e},e:function(e){c=!0,i=e},f:function(){try{a||null==n.return||n.return()}finally{if(c)throw i}}}}(document.getElementsByTagName("script"));try{for(t.s();!(e=t.n()).done;){var n=e.value.src;if(n&&(n.includes("agent-widget.js")||n.includes("ttp-agent-sdk")))try{new URL(n);var o=n.substring(0,n.lastIndexOf("/"));return"".concat(o,"/audio-processor.js")}catch(e){var r=n.substring(0,n.lastIndexOf("/"));return"".concat(r,"/audio-processor.js")}}}catch(e){t.e(e)}finally{t.f()}return"https://cdn.talktopc.com/audio-processor.js"}},{key:"start",value:(i=_(F().m(function e(){var t,n,o=this;return F().w(function(e){for(;;)switch(e.p=e.n){case 0:return e.p=0,e.n=1,navigator.mediaDevices.getUserMedia({audio:{sampleRate:this.config.sampleRate,channelCount:1,echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0}});case 1:if(this.mediaStream=e.v,this.audioContext=new(window.AudioContext||window.webkitAudioContext)({sampleRate:this.config.sampleRate}),"suspended"!==this.audioContext.state){e.n=2;break}return e.n=2,this.audioContext.resume();case 2:return t=this.getAudioProcessorPath(),e.n=3,this.audioContext.audioWorklet.addModule(t);case 3:this.audioWorkletNode=new AudioWorkletNode(this.audioContext,"audio-processor"),this.audioContext.createMediaStreamSource(this.mediaStream).connect(this.audioWorkletNode),this.audioWorkletNode.port.onmessage=function(e){var t=e.data,n=t.type,r=t.data;"pcm_audio_data"===n&&o.emit("audioData",r)},this.audioWorkletNode.port.postMessage({type:"setForceContinuous",data:{enabled:!0}}),this.isRecording=!0,this.emit("recordingStarted"),e.n=5;break;case 4:throw e.p=4,n=e.v,this.emit("error",n),n;case 5:return e.a(2)}},e,this,[[0,4]])})),function(){return i.apply(this,arguments)})},{key:"stop",value:(r=_(F().m(function e(){var t;return F().w(function(e){for(;;)switch(e.p=e.n){case 0:if(this.isRecording){e.n=1;break}return e.a(2);case 1:if(e.p=1,!this.audioWorkletNode){e.n=2;break}return this.audioWorkletNode.port.postMessage({type:"flush"}),e.n=2,new Promise(function(e){return setTimeout(e,100)});case 2:if(this.mediaStream&&(this.mediaStream.getTracks().forEach(function(e){return e.stop()}),this.mediaStream=null),!this.audioContext||"closed"===this.audioContext.state){e.n=4;break}return e.n=3,this.audioContext.close();case 3:this.audioContext=null;case 4:this.audioWorkletNode=null,this.isRecording=!1,this.emit("recordingStopped"),e.n=6;break;case 5:throw e.p=5,t=e.v,this.emit("error",t),t;case 6:return e.a(2)}},e,this,[[1,5]])})),function(){return r.apply(this,arguments)})},{key:"getStatus",value:function(){return{isRecording:this.isRecording,audioContextState:this.audioContext?this.audioContext.state:"closed"}}},{key:"destroy",value:function(){this.stop()}}],o&&M(n.prototype,o),Object.defineProperty(n,"prototype",{writable:!1}),n;var n,o,r,i}(c);function H(e){return H="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},H(e)}function W(){var e,t,n="function"==typeof Symbol?Symbol:{},o=n.iterator||"@@iterator",r=n.toStringTag||"@@toStringTag";function i(n,o,r,i){var s=o&&o.prototype instanceof c?o:c,u=Object.create(s.prototype);return G(u,"_invoke",function(n,o,r){var i,c,s,u=0,l=r||[],d=!1,p={p:0,n:0,v:e,a:f,f:f.bind(e,4),d:function(t,n){return i=t,c=0,s=e,p.n=n,a}};function f(n,o){for(c=n,s=o,t=0;!d&&u&&!r&&t<l.length;t++){var r,i=l[t],f=p.p,h=i[2];n>3?(r=h===o)&&(s=i[(c=i[4])?5:(c=3,3)],i[4]=i[5]=e):i[0]<=f&&((r=n<2&&f<i[1])?(c=0,p.v=o,p.n=i[1]):f<h&&(r=n<3||i[0]>o||o>h)&&(i[4]=n,i[5]=o,p.n=h,c=0))}if(r||n>1)return a;throw d=!0,o}return function(r,l,h){if(u>1)throw TypeError("Generator is already running");for(d&&1===l&&f(l,h),c=l,s=h;(t=c<2?e:s)||!d;){i||(c?c<3?(c>1&&(p.n=-1),f(c,s)):p.n=s:p.v=s);try{if(u=2,i){if(c||(r="next"),t=i[r]){if(!(t=t.call(i,s)))throw TypeError("iterator result is not an object");if(!t.done)return t;s=t.value,c<2&&(c=0)}else 1===c&&(t=i.return)&&t.call(i),c<2&&(s=TypeError("The iterator does not provide a '"+r+"' method"),c=1);i=e}else if((t=(d=p.n<0)?s:n.call(o,p))!==a)break}catch(t){i=e,c=1,s=t}finally{u=1}}return{value:t,done:d}}}(n,r,i),!0),u}var a={};function c(){}function s(){}function u(){}t=Object.getPrototypeOf;var l=[][o]?t(t([][o]())):(G(t={},o,function(){return this}),t),d=u.prototype=c.prototype=Object.create(l);function p(e){return Object.setPrototypeOf?Object.setPrototypeOf(e,u):(e.__proto__=u,G(e,r,"GeneratorFunction")),e.prototype=Object.create(d),e}return s.prototype=u,G(d,"constructor",u),G(u,"constructor",s),s.displayName="GeneratorFunction",G(u,r,"GeneratorFunction"),G(d),G(d,r,"Generator"),G(d,o,function(){return this}),G(d,"toString",function(){return"[object Generator]"}),(W=function(){return{w:i,m:p}})()}function G(e,t,n,o){var r=Object.defineProperty;try{r({},"",{})}catch(e){r=0}G=function(e,t,n,o){function i(t,n){G(e,t,function(e){return this._invoke(t,n,e)})}t?r?r(e,t,{value:n,enumerable:!o,configurable:!o,writable:!o}):e[t]=n:(i("next",0),i("throw",1),i("return",2))},G(e,t,n,o)}function q(e,t,n,o,r,i,a){try{var c=e[i](a),s=c.value}catch(e){return void n(e)}c.done?t(s):Promise.resolve(s).then(o,r)}function Q(e){return function(){var t=this,n=arguments;return new Promise(function(o,r){var i=e.apply(t,n);function a(e){q(i,o,r,a,c,"next",e)}function c(e){q(i,o,r,a,c,"throw",e)}a(void 0)})}}function J(e,t){for(var n=0;n<t.length;n++){var o=t[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(e,Y(o.key),o)}}function Y(e){var t=function(e){if("object"!=H(e)||!e)return e;var t=e[Symbol.toPrimitive];if(void 0!==t){var n=t.call(e,"string");if("object"!=H(n))return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}(e);return"symbol"==H(t)?t:t+""}function $(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(e){}return($=function(){return!!e})()}function X(e){return X=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(e){return e.__proto__||Object.getPrototypeOf(e)},X(e)}function Z(e,t){return Z=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,t){return e.__proto__=t,e},Z(e,t)}var ee=function(e){function t(e){var n;return function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,t),(n=function(e,t,n){return t=X(t),function(e,t){if(t&&("object"==H(t)||"function"==typeof t))return t;if(void 0!==t)throw new TypeError("Derived constructors may only return object or undefined");return function(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}(e)}(e,$()?Reflect.construct(t,n||[],X(e).constructor):t.apply(e,n))}(this,t)).config=e,n.audioContext=null,n.audioQueue=[],n.isPlaying=!1,n.isProcessingQueue=!1,n.currentSource=null,n.audioContextReady=!1,n.initializeAudioContext().catch(function(){}),n}return function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&Z(e,t)}(t,e),n=t,o=[{key:"initializeAudioContext",value:(i=Q(W().m(function e(){var t,n,o,r,i;return W().w(function(e){for(;;)switch(e.p=e.n){case 0:if(!this.audioContext||"closed"===this.audioContext.state){e.n=1;break}return e.a(2);case 1:if(e.p=1,t=this.config.sampleRate?{sampleRate:this.config.sampleRate}:{},this.audioContext=new(window.AudioContext||window.webkitAudioContext)(t),"suspended"!==this.audioContext.state){e.n=2;break}return e.n=2,this.audioContext.resume();case 2:if("running"===this.audioContext.state)try{n=this.audioContext.sampleRate,o=this.audioContext.createBuffer(1,.01*n,n),(r=this.audioContext.createBufferSource()).buffer=o,r.connect(this.audioContext.destination),r.start(0),r.stop(this.audioContext.currentTime+.01)}catch(e){console.debug("AudioPlayer: AudioContext warmup skipped:",e)}this.audioContextReady=!0,e.n=4;break;case 3:e.p=3,i=e.v,console.warn("AudioPlayer: Failed to pre-initialize AudioContext:",i),this.audioContextReady=!1;case 4:return e.a(2)}},e,this,[[1,3]])})),function(){return i.apply(this,arguments)})},{key:"playAudio",value:function(e){var t=this;try{var n=this.createAudioBlob(e);if(this.audioQueue.push(n),!this.isPlaying&&!this.isProcessingQueue&&!this.currentSource){var o=this.audioContextReady?0:50;setTimeout(function(){return t.processQueue()},o)}}catch(e){this.emit("playbackError",e)}}},{key:"createAudioBlob",value:function(e){var t=new Uint8Array(e);if(t.length>=4){if(82===t[0]&&73===t[1]&&70===t[2]&&70===t[3])return new Blob([e],{type:"audio/wav"});if(255===t[0]&&!(224&~t[1]))return new Blob([e],{type:"audio/mpeg"});if(79===t[0]&&103===t[1]&&103===t[2]&&83===t[3])return new Blob([e],{type:"audio/ogg"})}return new Blob([e],{type:"audio/wav"})}},{key:"processQueue",value:(r=Q(W().m(function e(){var t,n,o,r,i,a,c,s,u=this;return W().w(function(e){for(;;)switch(e.p=e.n){case 0:if(!this.isProcessingQueue&&0!==this.audioQueue.length){e.n=1;break}return e.a(2);case 1:if(this.isProcessingQueue=!0,t=this.audioQueue.shift()){e.n=2;break}return this.isProcessingQueue=!1,e.a(2);case 2:if(e.p=2,n=!this.isPlaying&&null===this.currentSource,this.audioContext&&"closed"!==this.audioContext.state){e.n=3;break}return e.n=3,this.initializeAudioContext();case 3:if("suspended"!==(o=this.audioContext).state){e.n=5;break}return e.n=4,o.resume();case 4:if(!n){e.n=5;break}return e.n=5,new Promise(function(e){return setTimeout(e,10)});case 5:if("running"===o.state){e.n=7;break}if(console.warn("AudioPlayer: AudioContext not in running state:",o.state),"suspended"!==o.state){e.n=7;break}return e.n=6,o.resume();case 6:return e.n=7,new Promise(function(e){return setTimeout(e,10)});case 7:return e.n=8,t.arrayBuffer();case 8:return r=e.v,e.n=9,o.decodeAudioData(r);case 9:i=e.v,a=n&&!this.isPlaying&&null===this.currentSource,(c=o.createBufferSource()).buffer=i,c.connect(o.destination),this.currentSource=c,this.isPlaying=!0,a&&this.emit("playbackStarted"),c.onended=function(){u.currentSource=null,u.isProcessingQueue=!1,u.audioQueue.length>0?setTimeout(function(){return u.processQueue()},0):setTimeout(function(){0!==u.audioQueue.length||u.currentSource||(u.isPlaying=!1,u.emit("playbackStopped"))},100)},c.start(),e.n=11;break;case 10:e.p=10,s=e.v,this.currentSource=null,this.emit("playbackError",s),this.audioQueue.length>0?(this.isProcessingQueue=!1,setTimeout(function(){return u.processQueue()},100)):(this.isPlaying=!1,this.isProcessingQueue=!1,this.emit("playbackStopped"));case 11:return e.a(2)}},e,this,[[2,10]])})),function(){return r.apply(this,arguments)})},{key:"stop",value:function(){this.stopImmediate()}},{key:"stopImmediate",value:function(){var e=this.isPlaying||null!==this.currentSource;if(this.currentSource){try{this.currentSource.stop()}catch(e){}this.currentSource=null}this.isPlaying=!1,this.isProcessingQueue=!1,this.audioQueue=[],e&&this.emit("playbackStopped")}},{key:"getStatus",value:function(){return{isPlaying:this.isPlaying,isProcessingQueue:this.isProcessingQueue,queueLength:this.audioQueue.length,audioContextState:this.audioContext?this.audioContext.state:"closed"}}},{key:"destroy",value:function(){this.stop(),this.audioContext&&"closed"!==this.audioContext.state&&(this.audioContext.close(),this.audioContext=null),this.audioContextReady=!1}}],o&&J(n.prototype,o),Object.defineProperty(n,"prototype",{writable:!1}),n;var n,o,r,i}(c);function te(e){return te="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},te(e)}function ne(){var e,t,n="function"==typeof Symbol?Symbol:{},o=n.iterator||"@@iterator",r=n.toStringTag||"@@toStringTag";function i(n,o,r,i){var s=o&&o.prototype instanceof c?o:c,u=Object.create(s.prototype);return oe(u,"_invoke",function(n,o,r){var i,c,s,u=0,l=r||[],d=!1,p={p:0,n:0,v:e,a:f,f:f.bind(e,4),d:function(t,n){return i=t,c=0,s=e,p.n=n,a}};function f(n,o){for(c=n,s=o,t=0;!d&&u&&!r&&t<l.length;t++){var r,i=l[t],f=p.p,h=i[2];n>3?(r=h===o)&&(s=i[(c=i[4])?5:(c=3,3)],i[4]=i[5]=e):i[0]<=f&&((r=n<2&&f<i[1])?(c=0,p.v=o,p.n=i[1]):f<h&&(r=n<3||i[0]>o||o>h)&&(i[4]=n,i[5]=o,p.n=h,c=0))}if(r||n>1)return a;throw d=!0,o}return function(r,l,h){if(u>1)throw TypeError("Generator is already running");for(d&&1===l&&f(l,h),c=l,s=h;(t=c<2?e:s)||!d;){i||(c?c<3?(c>1&&(p.n=-1),f(c,s)):p.n=s:p.v=s);try{if(u=2,i){if(c||(r="next"),t=i[r]){if(!(t=t.call(i,s)))throw TypeError("iterator result is not an object");if(!t.done)return t;s=t.value,c<2&&(c=0)}else 1===c&&(t=i.return)&&t.call(i),c<2&&(s=TypeError("The iterator does not provide a '"+r+"' method"),c=1);i=e}else if((t=(d=p.n<0)?s:n.call(o,p))!==a)break}catch(t){i=e,c=1,s=t}finally{u=1}}return{value:t,done:d}}}(n,r,i),!0),u}var a={};function c(){}function s(){}function u(){}t=Object.getPrototypeOf;var l=[][o]?t(t([][o]())):(oe(t={},o,function(){return this}),t),d=u.prototype=c.prototype=Object.create(l);function p(e){return Object.setPrototypeOf?Object.setPrototypeOf(e,u):(e.__proto__=u,oe(e,r,"GeneratorFunction")),e.prototype=Object.create(d),e}return s.prototype=u,oe(d,"constructor",u),oe(u,"constructor",s),s.displayName="GeneratorFunction",oe(u,r,"GeneratorFunction"),oe(d),oe(d,r,"Generator"),oe(d,o,function(){return this}),oe(d,"toString",function(){return"[object Generator]"}),(ne=function(){return{w:i,m:p}})()}function oe(e,t,n,o){var r=Object.defineProperty;try{r({},"",{})}catch(e){r=0}oe=function(e,t,n,o){function i(t,n){oe(e,t,function(e){return this._invoke(t,n,e)})}t?r?r(e,t,{value:n,enumerable:!o,configurable:!o,writable:!o}):e[t]=n:(i("next",0),i("throw",1),i("return",2))},oe(e,t,n,o)}function re(e,t,n,o,r,i,a){try{var c=e[i](a),s=c.value}catch(e){return void n(e)}c.done?t(s):Promise.resolve(s).then(o,r)}function ie(e){return function(){var t=this,n=arguments;return new Promise(function(o,r){var i=e.apply(t,n);function a(e){re(i,o,r,a,c,"next",e)}function c(e){re(i,o,r,a,c,"throw",e)}a(void 0)})}}function ae(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(e);t&&(o=o.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,o)}return n}function ce(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?ae(Object(n),!0).forEach(function(t){se(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):ae(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}function se(e,t,n){return(t=le(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function ue(e,t){for(var n=0;n<t.length;n++){var o=t[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(e,le(o.key),o)}}function le(e){var t=function(e){if("object"!=te(e)||!e)return e;var t=e[Symbol.toPrimitive];if(void 0!==t){var n=t.call(e,"string");if("object"!=te(n))return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}(e);return"symbol"==te(t)?t:t+""}function de(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(e){}return(de=function(){return!!e})()}function pe(e){return pe=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(e){return e.__proto__||Object.getPrototypeOf(e)},pe(e)}function fe(e,t){return fe=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,t){return e.__proto__=t,e},fe(e,t)}var he=function(e){function t(){var e,n=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,t),(e=function(e,t,n){return t=pe(t),function(e,t){if(t&&("object"==te(t)||"function"==typeof t))return t;if(void 0!==t)throw new TypeError("Derived constructors may only return object or undefined");return function(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}(e)}(e,de()?Reflect.construct(t,n||[],pe(e).constructor):t.apply(e,n))}(this,t)).config=ce({websocketUrl:n.websocketUrl||"wss://speech.talktopc.com/ws/conv",agentId:n.agentId,appId:n.appId,ttpId:n.ttpId,voice:n.voice||"default",language:n.language||"en",sampleRate:n.sampleRate||16e3,agentSettingsOverride:n.agentSettingsOverride||null,onStartConversation:n.onStartConversation||null,onEndConversation:n.onEndConversation||null},n),e.isConnected=!1,e.isRecording=!1,e.isPlaying=!1,e.isDestroyed=!1,e.conversationStarted=!1,e.webSocketManager=new j(ce(ce({},e.config),{},{autoReconnect:!1!==e.config.autoReconnect})),e.audioRecorder=new z(e.config),e.audioPlayer=new ee(e.config),e.setupEventHandlers(),e}return function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&fe(e,t)}(t,e),n=t,o=[{key:"setupEventHandlers",value:function(){var e=this;this.webSocketManager.on("connected",function(){e.isConnected=!0,e.sendHelloMessage(),e.emit("connected")}),this.webSocketManager.on("disconnected",function(t){if(e.isConnected=!1,e.conversationStarted&&(e.conversationStarted=!1,console.log("🏁 VoiceSDK: Conversation ended (connection closed)"),e.emit("conversationEnded",{}),e.config.onEndConversation))try{e.config.onEndConversation({})}catch(e){console.error("VoiceSDK: Error in onEndConversation hook:",e)}if(t&&1008===t.code&&t.reason&&(t.reason.includes("Domain not whitelisted")||t.reason.includes("domain")||t.reason.includes("whitelist"))){var n=new Error("DOMAIN_NOT_WHITELISTED");n.reason=t.reason,n.code=t.code,e.emit("domainError",n),e.emit("error",n)}e.isRecording&&e.stopRecording().catch(function(e){console.error("VoiceSDK: Error stopping recording on disconnect:",e)}),e.emit("disconnected",t)}),this.webSocketManager.on("error",function(t){e.emit("error",t)}),this.webSocketManager.on("message",function(t){if(("hello_ack"===t.t||"hello_ack"===t.type)&&!e.conversationStarted&&(e.conversationStarted=!0,console.log("🎬 VoiceSDK: Conversation started"),e.emit("conversationStarted",{conversationId:t.conversationId}),e.config.onStartConversation))try{e.config.onStartConversation({conversationId:t.conversationId})}catch(e){console.error("VoiceSDK: Error in onStartConversation hook:",e)}if("greeting_audio"===t.t&&t.data)try{for(var n=atob(t.data),o=new Uint8Array(n.length),r=0;r<n.length;r++)o[r]=n.charCodeAt(r);e.audioPlayer.playAudio(o),e.emit("greetingStarted")}catch(e){console.error("VoiceSDK: Error playing greeting audio:",e)}else e.emit("message",t)}),this.webSocketManager.on("binaryAudio",function(t){e.audioPlayer.playAudio(t)}),this.webSocketManager.on("bargeIn",function(t){e.emit("bargeIn",t)}),this.webSocketManager.on("stopPlaying",function(t){e.emit("stopPlaying",t),e.audioPlayer.stopImmediate()}),this.audioRecorder.on("recordingStarted",function(){if(e.isRecording=!0,!e.conversationStarted&&(e.conversationStarted=!0,console.log("🎬 VoiceSDK: Conversation started (recording)"),e.emit("conversationStarted",{}),e.config.onStartConversation))try{e.config.onStartConversation({})}catch(e){console.error("VoiceSDK: Error in onStartConversation hook:",e)}e.isPlaying&&(e.audioPlayer.stopImmediate(),e.isConnected&&e.webSocketManager.sendMessage({t:"barge_in"})),e.emit("recordingStarted")}),this.audioRecorder.on("recordingStopped",function(){e.isRecording=!1,e.emit("recordingStopped")}),this.audioRecorder.on("audioData",function(t){e.isConnected&&e.webSocketManager.sendBinary(t)}),this.audioPlayer.on("playbackStarted",function(){e.isPlaying=!0,e.emit("playbackStarted"),e.isConnected&&e.webSocketManager.sendMessage({t:"audio_started_playing"})}),this.audioPlayer.on("playbackStopped",function(){e.isPlaying=!1,e.emit("playbackStopped"),e.isConnected&&e.webSocketManager.sendMessage({t:"audio_stopped_playing"})}),this.audioPlayer.on("playbackError",function(t){e.emit("playbackError",t)})}},{key:"connect",value:(u=ie(ne().m(function e(){var t,n;return ne().w(function(e){for(;;)switch(e.p=e.n){case 0:if(!this.isDestroyed){e.n=1;break}return console.warn("VoiceSDK: Cannot connect - SDK is destroyed"),e.a(2,!1);case 1:return e.p=1,t=this.buildWebSocketUrl(),this.webSocketManager.config.websocketUrl=t,e.n=2,this.webSocketManager.connect();case 2:return e.a(2,!0);case 3:return e.p=3,n=e.v,console.error("🔌 VoiceSDK: Connection failed with error:",n),this.emit("error",n),e.a(2,!1)}},e,this,[[1,3]])})),function(){return u.apply(this,arguments)})},{key:"buildWebSocketUrl",value:function(){var e=this.config.websocketUrl,t=new URLSearchParams;if(this.config.agentId&&t.append("agentId",this.config.agentId),this.config.appId&&t.append("appId",this.config.appId),this.config.voice&&"default"!==this.config.voice&&t.append("voice",this.config.voice),this.config.language&&"en"!==this.config.language&&t.append("language",this.config.language),t.toString()){var n=e.includes("?")?"&":"?";e+=n+t.toString()}return e}},{key:"disconnect",value:function(){if(!this.isDestroyed){if(this.conversationStarted&&(this.conversationStarted=!1,console.log("🏁 VoiceSDK: Conversation ended"),this.emit("conversationEnded",{}),this.config.onEndConversation))try{this.config.onEndConversation({})}catch(e){console.error("VoiceSDK: Error in onEndConversation hook:",e)}this.stopRecording(),this.webSocketManager.disconnect()}}},{key:"resetReconnectionAttempts",value:function(){this.isDestroyed||this.webSocketManager.resetReconnectionAttempts()}},{key:"reconnect",value:(s=ie(ne().m(function e(){return ne().w(function(e){for(;;)switch(e.n){case 0:if(!this.isDestroyed){e.n=1;break}return e.a(2,!1);case 1:return this.disconnect(),this.resetReconnectionAttempts(),e.n=2,this.connect();case 2:return e.a(2,e.v)}},e,this)})),function(){return s.apply(this,arguments)})},{key:"startRecording",value:(c=ie(ne().m(function e(){var t;return ne().w(function(e){for(;;)switch(e.p=e.n){case 0:if(this.isConnected){e.n=1;break}throw new Error("Not connected to voice server");case 1:return e.p=1,this.webSocketManager.sendMessage({t:"start_continuous_mode",ttpId:this.generateTtpId(),voice:this.config.voice,language:this.config.language}),e.n=2,this.audioRecorder.start();case 2:return e.a(2,!0);case 3:return e.p=3,t=e.v,console.error("❌ VoiceSDK: Failed to start recording:",t),this.emit("error",t),e.a(2,!1)}},e,this,[[1,3]])})),function(){return c.apply(this,arguments)})},{key:"stopRecording",value:(a=ie(ne().m(function e(){var t;return ne().w(function(e){for(;;)switch(e.p=e.n){case 0:if(this.isRecording){e.n=1;break}return e.a(2);case 1:return e.p=1,this.webSocketManager.sendMessage({t:"stop_continuous_mode",ttpId:this.generateTtpId()}),e.n=2,this.audioRecorder.stop();case 2:return this.audioPlayer.stopImmediate(),e.a(2,!0);case 3:return e.p=3,t=e.v,this.emit("error",t),e.a(2,!1)}},e,this,[[1,3]])})),function(){return a.apply(this,arguments)})},{key:"toggleRecording",value:(i=ie(ne().m(function e(){return ne().w(function(e){for(;;)switch(e.n){case 0:if(!this.isRecording){e.n=2;break}return e.n=1,this.stopRecording();case 1:case 3:return e.a(2,e.v);case 2:return e.n=3,this.startRecording();case 4:return e.a(2)}},e,this)})),function(){return i.apply(this,arguments)})},{key:"stopAudioPlayback",value:function(){this.audioPlayer.stopImmediate()}},{key:"handleBargeIn",value:(r=ie(ne().m(function e(){return ne().w(function(e){for(;;)switch(e.n){case 0:if(this.stopAudioPlayback(),this.isRecording){e.n=1;break}return e.n=1,this.startRecording();case 1:return e.a(2)}},e,this)})),function(){return r.apply(this,arguments)})},{key:"getStatus",value:function(){return{isConnected:this.isConnected,isRecording:this.isRecording,isPlaying:this.isPlaying}}},{key:"updateConfig",value:function(e){this.config=ce(ce({},this.config),e)}},{key:"generateTtpId",value:function(){return"sdk_"+Math.random().toString(36).substr(2,9)+"_"+Date.now()}},{key:"sendHelloMessage",value:function(){if(this.isConnected){var e={t:"hello"};if(!this.config.appId){var t=new Error("appId is required for connection");return console.error("VoiceSDK: Failed to send hello message:",t),void this.emit("error",t)}e.appId=this.config.appId,this.config.agentSettingsOverride&&Object.keys(this.config.agentSettingsOverride).length>0&&(e.agentSettingsOverride=this.config.agentSettingsOverride,console.log("🔧 VoiceSDK: Sending agent settings override:",Object.keys(this.config.agentSettingsOverride)));try{this.webSocketManager.sendMessage(e)}catch(t){console.error("VoiceSDK: Failed to send hello message:",t),this.emit("error",t)}}else console.warn("VoiceSDK: Cannot send hello message - not connected")}},{key:"destroy",value:function(){this.isDestroyed||(this.disconnect(),this.isDestroyed=!0,this.audioRecorder.destroy(),this.audioPlayer.destroy(),this.removeAllListeners())}}],o&&ue(n.prototype,o),Object.defineProperty(n,"prototype",{writable:!1}),n;var n,o,r,i,a,c,s,u}(c);function ve(e){return ve="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},ve(e)}function ge(e,t){for(var n=0;n<t.length;n++){var o=t[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(e,ye(o.key),o)}}function ye(e){var t=function(e){if("object"!=ve(e)||!e)return e;var t=e[Symbol.toPrimitive];if(void 0!==t){var n=t.call(e,"string");if("object"!=ve(n))return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}(e);return"symbol"==ve(t)?t:t+""}var me=function(){return e=function e(){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),this.events={}},t=[{key:"on",value:function(e,t){return this.events[e]||(this.events[e]=[]),this.events[e].push(t),this}},{key:"off",value:function(e,t){return this.events[e]?(this.events[e]=this.events[e].filter(function(e){return e!==t}),this):this}},{key:"emit",value:function(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),o=1;o<t;o++)n[o-1]=arguments[o];return!!this.events[e]&&(this.events[e].forEach(function(e){e.apply(void 0,n)}),!0)}},{key:"once",value:function(e,t){var n=this,o=function(){t.apply(void 0,arguments),n.off(e,o)};return this.on(e,o)}},{key:"removeAllListeners",value:function(e){return e?delete this.events[e]:this.events={},this}}],t&&ge(e.prototype,t),Object.defineProperty(e,"prototype",{writable:!1}),e;var e,t}();const be=me;function Se(e){return Se="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},Se(e)}function we(e,t){for(var n=0;n<t.length;n++){var o=t[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(e,xe(o.key),o)}}function xe(e){var t=function(e){if("object"!=Se(e)||!e)return e;var t=e[Symbol.toPrimitive];if(void 0!==t){var n=t.call(e,"string");if("object"!=Se(n))return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}(e);return"symbol"==Se(t)?t:t+""}const Ce=function(){return e=function e(){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),this.name="PCM"},(t=[{key:"decode",value:function(e){if(e instanceof ArrayBuffer)return e;if(e instanceof Uint8Array)return e.buffer;throw new Error("Invalid PCM data type")}},{key:"encode",value:function(e){return e}}])&&we(e.prototype,t),Object.defineProperty(e,"prototype",{writable:!1}),e;var e,t}();function ke(e){return ke="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},ke(e)}function Pe(e,t){for(var n=0;n<t.length;n++){var o=t[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(e,Oe(o.key),o)}}function Oe(e){var t=function(e){if("object"!=ke(e)||!e)return e;var t=e[Symbol.toPrimitive];if(void 0!==t){var n=t.call(e,"string");if("object"!=ke(n))return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}(e);return"symbol"==ke(t)?t:t+""}const Ee=function(){return e=function e(){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),this.name="PCMU"},(t=[{key:"decode",value:function(e){for(var t=e instanceof Uint8Array?e:new Uint8Array(e),n=new Int16Array(t.length),o=0;o<t.length;o++)n[o]=this.mulawToLinear(t[o]);return n.buffer}},{key:"encode",value:function(e){for(var t=e instanceof Int16Array?e:new Int16Array(e),n=new Uint8Array(t.length),o=0;o<t.length;o++)n[o]=this.linearToMulaw(t[o]);return n}},{key:"mulawToLinear",value:function(e){var t=1<<3+(e>>4&7);return(128&e?-1:1)*(132+(15&e)*t+(t>>1)-4)}},{key:"linearToMulaw",value:function(e){var t=e>>8&128;t&&(e=-e),e>32635&&(e=32635),e+=132;for(var n=7,o=16384;0===(e&o)&&n>0;n--,o>>=1);return 255&~(t|n<<4|e>>n+3&15)}}])&&Pe(e.prototype,t),Object.defineProperty(e,"prototype",{writable:!1}),e;var e,t}();function Te(e){return Te="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},Te(e)}function Ae(e,t){for(var n=0;n<t.length;n++){var o=t[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(e,Ie(o.key),o)}}function Ie(e){var t=function(e){if("object"!=Te(e)||!e)return e;var t=e[Symbol.toPrimitive];if(void 0!==t){var n=t.call(e,"string");if("object"!=Te(n))return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}(e);return"symbol"==Te(t)?t:t+""}const je=function(){return e=function e(){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),this.name="PCMA"},(t=[{key:"decode",value:function(e){for(var t=e instanceof Uint8Array?e:new Uint8Array(e),n=new Int16Array(t.length),o=0;o<t.length;o++)n[o]=this.alawToLinear(t[o]);return n.buffer}},{key:"encode",value:function(e){for(var t=e instanceof Int16Array?e:new Int16Array(e),n=new Uint8Array(t.length),o=0;o<t.length;o++)n[o]=this.linearToAlaw(t[o]);return n}},{key:"alawToLinear",value:function(e){var t=(e^=85)>>4&7,n=15&e;return(128&e?-1:1)*(0===t?8+(n<<4):264+(n<<4)<<t-1)}},{key:"linearToAlaw",value:function(e){var t,n,o=e>>8&128;if(o&&(e=-e),e>32635&&(e=32635),e<256)t=0,n=e>>4;else{t=7;for(var r=16384;0===(e&r)&&t>0;t--,r>>=1);n=e>>t+3&15}return 85^(o|t<<4|n)}}])&&Ae(e.prototype,t),Object.defineProperty(e,"prototype",{writable:!1}),e;var e,t}();function De(e){return De="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},De(e)}function Fe(e,t){var n="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!n){if(Array.isArray(e)||(n=function(e,t){if(e){if("string"==typeof e)return Be(e,t);var n={}.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?Be(e,t):void 0}}(e))||t&&e&&"number"==typeof e.length){n&&(e=n);var o=0,r=function(){};return{s:r,n:function(){return o>=e.length?{done:!0}:{done:!1,value:e[o++]}},e:function(e){throw e},f:r}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var i,a=!0,c=!1;return{s:function(){n=n.call(e)},n:function(){var e=n.next();return a=e.done,e},e:function(e){c=!0,i=e},f:function(){try{a||null==n.return||n.return()}finally{if(c)throw i}}}}function Be(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,o=Array(t);n<t;n++)o[n]=e[n];return o}function Re(e){if(null!=e){var t=e["function"==typeof Symbol&&Symbol.iterator||"@@iterator"],n=0;if(t)return t.call(e);if("function"==typeof e.next)return e;if(!isNaN(e.length))return{next:function(){return e&&n>=e.length&&(e=void 0),{value:e&&e[n++],done:!e}}}}throw new TypeError(De(e)+" is not iterable")}function _e(){var e,t,n="function"==typeof Symbol?Symbol:{},o=n.iterator||"@@iterator",r=n.toStringTag||"@@toStringTag";function i(n,o,r,i){var s=o&&o.prototype instanceof c?o:c,u=Object.create(s.prototype);return Ue(u,"_invoke",function(n,o,r){var i,c,s,u=0,l=r||[],d=!1,p={p:0,n:0,v:e,a:f,f:f.bind(e,4),d:function(t,n){return i=t,c=0,s=e,p.n=n,a}};function f(n,o){for(c=n,s=o,t=0;!d&&u&&!r&&t<l.length;t++){var r,i=l[t],f=p.p,h=i[2];n>3?(r=h===o)&&(s=i[(c=i[4])?5:(c=3,3)],i[4]=i[5]=e):i[0]<=f&&((r=n<2&&f<i[1])?(c=0,p.v=o,p.n=i[1]):f<h&&(r=n<3||i[0]>o||o>h)&&(i[4]=n,i[5]=o,p.n=h,c=0))}if(r||n>1)return a;throw d=!0,o}return function(r,l,h){if(u>1)throw TypeError("Generator is already running");for(d&&1===l&&f(l,h),c=l,s=h;(t=c<2?e:s)||!d;){i||(c?c<3?(c>1&&(p.n=-1),f(c,s)):p.n=s:p.v=s);try{if(u=2,i){if(c||(r="next"),t=i[r]){if(!(t=t.call(i,s)))throw TypeError("iterator result is not an object");if(!t.done)return t;s=t.value,c<2&&(c=0)}else 1===c&&(t=i.return)&&t.call(i),c<2&&(s=TypeError("The iterator does not provide a '"+r+"' method"),c=1);i=e}else if((t=(d=p.n<0)?s:n.call(o,p))!==a)break}catch(t){i=e,c=1,s=t}finally{u=1}}return{value:t,done:d}}}(n,r,i),!0),u}var a={};function c(){}function s(){}function u(){}t=Object.getPrototypeOf;var l=[][o]?t(t([][o]())):(Ue(t={},o,function(){return this}),t),d=u.prototype=c.prototype=Object.create(l);function p(e){return Object.setPrototypeOf?Object.setPrototypeOf(e,u):(e.__proto__=u,Ue(e,r,"GeneratorFunction")),e.prototype=Object.create(d),e}return s.prototype=u,Ue(d,"constructor",u),Ue(u,"constructor",s),s.displayName="GeneratorFunction",Ue(u,r,"GeneratorFunction"),Ue(d),Ue(d,r,"Generator"),Ue(d,o,function(){return this}),Ue(d,"toString",function(){return"[object Generator]"}),(_e=function(){return{w:i,m:p}})()}function Ue(e,t,n,o){var r=Object.defineProperty;try{r({},"",{})}catch(e){r=0}Ue=function(e,t,n,o){function i(t,n){Ue(e,t,function(e){return this._invoke(t,n,e)})}t?r?r(e,t,{value:n,enumerable:!o,configurable:!o,writable:!o}):e[t]=n:(i("next",0),i("throw",1),i("return",2))},Ue(e,t,n,o)}function Me(e,t,n,o,r,i,a){try{var c=e[i](a),s=c.value}catch(e){return void n(e)}c.done?t(s):Promise.resolve(s).then(o,r)}function Ne(e){return function(){var t=this,n=arguments;return new Promise(function(o,r){var i=e.apply(t,n);function a(e){Me(i,o,r,a,c,"next",e)}function c(e){Me(i,o,r,a,c,"throw",e)}a(void 0)})}}function Ve(e,t){for(var n=0;n<t.length;n++){var o=t[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(e,Le(o.key),o)}}function Le(e){var t=function(e){if("object"!=De(e)||!e)return e;var t=e[Symbol.toPrimitive];if(void 0!==t){var n=t.call(e,"string");if("object"!=De(n))return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}(e);return"symbol"==De(t)?t:t+""}function Ke(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(e){}return(Ke=function(){return!!e})()}function ze(e){return ze=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(e){return e.__proto__||Object.getPrototypeOf(e)},ze(e)}function He(e,t){return He=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,t){return e.__proto__=t,e},He(e,t)}var We=function(e){function t(){var e,n=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,t),(e=function(e,t,n){return t=ze(t),function(e,t){if(t&&("object"==De(t)||"function"==typeof t))return t;if(void 0!==t)throw new TypeError("Derived constructors may only return object or undefined");return function(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}(e)}(e,Ke()?Reflect.construct(t,n||[],ze(e).constructor):t.apply(e,n))}(this,t)).config=n,e.audioContext=null,e._audioContextStateChangeHandler=null,e.audioQueue=[],e.isPlaying=!1,e.isProcessingQueue=!1,e.currentSource=null,e.outputFormat=null,e.nextStartTime=0,e.scheduledBuffers=0,e.scheduledSources=new Set,e.pcmChunkQueue=[],e.preparedBuffer=[],e.isProcessingPcmQueue=!1,e.isSchedulingFrames=!1,e.MAX_LOOKAHEAD_SECONDS=.02,e.pendingSentenceText=null,e.sentenceTimings=[],e.isCheckingTranscripts=!1,e.codecs={pcm:new Ce,pcmu:new Ee,pcma:new je},e.SUPPORTED_CONTAINERS=["wav","raw"],e.SUPPORTED_ENCODINGS=["pcm","pcmu","pcma"],e.SUPPORTED_SAMPLE_RATES=[8e3,16e3,22050,24e3,44100,48e3],e.SUPPORTED_BIT_DEPTHS=[8,16,24],e.SUPPORTED_CHANNELS=[1],console.log("🎵 AudioPlayer v2 initialized"),e}return function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&He(e,t)}(t,e),n=t,o=[{key:"setOutputFormat",value:function(e){var t;this.validateFormat(e)||(console.warn("⚠️ AudioPlayer: Invalid format, using defaults:",e),e=this.getDefaultFormat());var n=null===(t=this.outputFormat)||void 0===t?void 0:t.sampleRate,o=e.sampleRate;this.outputFormat=e,console.log("✅ AudioPlayer v2: Format set:",e),this.audioContext&&n&&n!==o&&(console.warn("⚠️ AudioPlayer: Sample rate changed, recreating AudioContext"),console.warn(" Old: ".concat(n,"Hz → New: ").concat(o,"Hz")),this.stopImmediate(),"closed"!==this.audioContext.state&&this.audioContext.close(),this.audioContext=null,console.log("ℹ️ AudioContext will be recreated on next audio chunk with correct sample rate")),this.audioContext||(this.initializeAudioContext(),this.audioContext&&"suspended"===this.audioContext.state&&this.audioContext.resume().then(function(){console.log("✅ AudioPlayer v2: AudioContext resumed and ready")}).catch(function(e){console.warn("⚠️ AudioPlayer v2: Could not resume AudioContext:",e)}))}},{key:"validateFormat",value:function(e){var t,n;if(!e)return!1;var o=null===(t=e.container)||void 0===t?void 0:t.toLowerCase(),r=null===(n=e.encoding)||void 0===n?void 0:n.toLowerCase();return o&&r&&this.SUPPORTED_CONTAINERS.includes(o)&&this.SUPPORTED_ENCODINGS.includes(r)&&this.SUPPORTED_SAMPLE_RATES.includes(e.sampleRate)&&this.SUPPORTED_BIT_DEPTHS.includes(e.bitDepth)&&(!e.channels||this.SUPPORTED_CHANNELS.includes(e.channels))}},{key:"getDefaultFormat",value:function(){return{container:"raw",encoding:"pcm",sampleRate:16e3,channels:1,bitDepth:16}}},{key:"playAudio",value:function(e){var t=this;try{var n=this.createAudioBlob(e);this.audioQueue.push(n),this.isPlaying||this.isProcessingQueue||this.currentSource||setTimeout(function(){return t.processQueue()},50)}catch(e){console.error("❌ AudioPlayer v2: Playback error:",e),this.emit("playbackError",e)}}},{key:"playChunk",value:(c=Ne(_e().m(function e(t){var n,o,r=this;return _e().w(function(e){for(;;)switch(e.n){case 0:(n=this.prepareChunk(t))?(this.preparedBuffer.push(n),(this.preparedBuffer.length<=3||this.preparedBuffer.length%10==0)&&console.log("📥 AudioPlayer: Frame received, queued: ".concat(this.preparedBuffer.length,", scheduled: ").concat(this.scheduledBuffers,", isScheduling: ").concat(this.isSchedulingFrames)),this.isSchedulingFrames?setTimeout(function(){r.preparedBuffer.length>0&&!r.isSchedulingFrames&&r.schedulePreparedFrames()},5):this.schedulePreparedFrames(),this.pcmChunkQueue.length>0&&!this.isProcessingPcmQueue&&this.processPcmQueue()):(console.error("❌ AudioPlayer: playChunk failed - prepareChunk returned null"),console.error(" pcmData length:",(null==t?void 0:t.byteLength)||"undefined"),console.error(" outputFormat:",this.outputFormat),console.error(" audioContext:",this.audioContext?"initialized":"not initialized"),console.error(" audioContext state:",(null===(o=this.audioContext)||void 0===o?void 0:o.state)||"N/A"),this.emit("playbackError",new Error("Failed to prepare PCM chunk for playback")));case 1:return e.a(2)}},e,this)})),function(e){return c.apply(this,arguments)})},{key:"prepareChunk",value:function(e){try{var t;if(!this.outputFormat)return console.error("❌ AudioPlayer: Cannot prepare chunk - outputFormat not set"),console.error(" Call setOutputFormat() before playing audio chunks"),null;if(this.audioContext||this.initializeAudioContext(),!this.audioContext)return console.error("❌ AudioPlayer: Cannot prepare chunk - AudioContext not available"),null;var n=e;if(e.byteLength%2!=0){console.warn("⚠️ Odd PCM chunk size, padding:",e.byteLength);var o=new Uint8Array(e.byteLength+1);o.set(new Uint8Array(e),0),o[e.byteLength]=0,n=o.buffer}for(var r=new Int16Array(n),i=new Float32Array(r.length),a=1/32768,c=r.length,s=0;s<c;s++)i[s]=r[s]*a;var u=(null===(t=this.outputFormat)||void 0===t?void 0:t.sampleRate)||this.audioContext.sampleRate,l=this.audioContext.sampleRate,d=this.audioContext.createBuffer(1,i.length,u);d.getChannelData(0).set(i);var p=d.duration,f=i.length,h=p;return l!==u&&(h=f/l),{buffer:d,duration:h,sampleRate:u,contextSampleRate:l}}catch(e){return console.error("❌ AudioPlayer: Error preparing chunk:",e),null}}},{key:"applyFadeOut",value:function(e){return e}},{key:"schedulePreparedFrames",value:(a=Ne(_e().m(function e(){var t,n,o,r,i,a=this;return _e().w(function(e){for(;;)switch(e.p=e.n){case 0:if(!this.isSchedulingFrames){e.n=1;break}return e.a(2);case 1:if(this.isSchedulingFrames=!0,t=this.preparedBuffer.length,0===(n=Math.min(t,5))&&t>0&&(n=1),e.p=2,this.audioContext||this.initializeAudioContext(),"suspended"!==this.audioContext.state){e.n=3;break}return e.n=3,this.audioContext.resume();case 3:o=0,r=_e().m(function e(){var t,n,r,i,c;return _e().w(function(e){for(;;)switch(e.n){case 0:if(t=a.preparedBuffer.shift()){e.n=1;break}return e.a(2,1);case 1:(n=a.audioContext.createBufferSource()).buffer=t.buffer,n.connect(a.audioContext.destination),a.scheduledSources.add(n),r=a.audioContext.currentTime,0===a.scheduledBuffers?(a.nextStartTime<r&&(a.nextStartTime=r+a.MAX_LOOKAHEAD_SECONDS),console.log("🎵 Starting playback with minimal delay:",a.nextStartTime)):(i=r+a.MAX_LOOKAHEAD_SECONDS,a.nextStartTime<i&&(a.nextStartTime=i,console.warn("⚠️ AudioPlayer: Fell behind schedule, adjusting nextStartTime to ".concat(a.nextStartTime.toFixed(4),"s")))),a.pendingSentenceText&&(a.sentenceTimings.push({startTime:a.nextStartTime,text:a.pendingSentenceText,displayed:!1}),console.log("📝 AudioPlayer: Sentence scheduled at ".concat(a.nextStartTime.toFixed(3),'s: "').concat(a.pendingSentenceText.substring(0,40),'..."')),a.pendingSentenceText=null,a.isCheckingTranscripts||a.startTranscriptChecker()),n.start(a.nextStartTime),a.nextStartTime+=t.duration,a.nextStartTime=Math.round(1e6*a.nextStartTime)/1e6,c=a.nextStartTime-t.duration,a.scheduledBuffers<5&&(console.log("🎵 AudioPlayer: Scheduled frame ".concat(a.scheduledBuffers+1," at ").concat(c.toFixed(4),"s, next at ").concat(a.nextStartTime.toFixed(4),"s")),console.log(" Duration: ".concat(t.duration.toFixed(4),"s (").concat((1e3*t.duration).toFixed(2),"ms), Queued: ").concat(a.preparedBuffer.length,", Scheduled: ").concat(a.scheduledBuffers))),a.scheduledBuffers++,o++,n.onended=function(){if(a.scheduledSources.delete(n),a.scheduledBuffers--,0===a.scheduledBuffers&&0===a.preparedBuffer.length&&0===a.pcmChunkQueue.length)a.isPlaying=!1,a.isSchedulingFrames=!1,console.log("🛑 AudioPlayer: Emitting playbackStopped event (all buffers finished)"),a.emit("playbackStopped");else if(a.preparedBuffer.length>0)setTimeout(function(){a.preparedBuffer.length>0&&!a.isSchedulingFrames&&a.schedulePreparedFrames()},0);else if(a.scheduledBuffers>0){var e=function(){a.preparedBuffer.length>0&&!a.isSchedulingFrames&&a.scheduledBuffers>0?a.schedulePreparedFrames():a.scheduledBuffers>0&&setTimeout(e,10)};setTimeout(e,10)}},a.isPlaying||(a.isPlaying=!0,console.log("🎵 AudioPlayer: Emitting playbackStarted event"),a.emit("playbackStarted"));case 2:return e.a(2)}},e)});case 4:if(!(this.preparedBuffer.length>0&&o<n)){e.n=7;break}return e.d(Re(r()),5);case 5:if(!e.v){e.n=6;break}return e.a(3,7);case 6:e.n=4;break;case 7:this.isSchedulingFrames=!1,this.preparedBuffer.length>0&&requestAnimationFrame(function(){a.preparedBuffer.length>0&&!a.isSchedulingFrames&&a.schedulePreparedFrames()}),this.scheduledBuffers>0&&setTimeout(function(){a.preparedBuffer.length>0&&!a.isSchedulingFrames&&a.scheduledBuffers>0?a.schedulePreparedFrames():a.scheduledBuffers>0&&setTimeout(function(){a.preparedBuffer.length>0&&!a.isSchedulingFrames&&a.scheduledBuffers>0&&a.schedulePreparedFrames()},10)},10),e.n=9;break;case 8:e.p=8,i=e.v,console.error("❌ AudioPlayer v2: Error scheduling frames:",i),this.emit("playbackError",i),this.isSchedulingFrames=!1;case 9:return e.a(2)}},e,this,[[2,8]])})),function(){return a.apply(this,arguments)})},{key:"processPcmQueue",value:(i=Ne(_e().m(function e(){var t,n,o,r,i,a,c,s,u,l,d,p,f,h,v,g,y,m,b,S,w=this;return _e().w(function(e){for(;;)switch(e.p=e.n){case 0:if(!this.isProcessingPcmQueue){e.n=1;break}return e.a(2);case 1:if(this.isProcessingPcmQueue=!0,e.p=2,this.audioContext||this.initializeAudioContext(),"suspended"!==this.audioContext.state){e.n=3;break}return e.n=3,this.audioContext.resume();case 3:if(!(this.pcmChunkQueue.length>0)){e.n=5;break}if(o=this.pcmChunkQueue.shift()){e.n=4;break}return e.a(3,3);case 4:for(r=o,o.byteLength%2!=0&&(console.warn("⚠️ Odd PCM chunk size, padding:",o.byteLength),(i=new Uint8Array(o.byteLength+1)).set(new Uint8Array(o),0),i[o.byteLength]=0,r=i.buffer),a=new Int16Array(r),c=new Float32Array(a.length),s=1/32768,u=a.length,l=0;l<u;l++)c[l]=a[l]*s;d=(null===(t=this.outputFormat)||void 0===t?void 0:t.sampleRate)||this.audioContext.sampleRate,p=this.audioContext.sampleRate,null!==(n=this.outputFormat)&&void 0!==n&&n.sampleRate?this.scheduledBuffers<3&&console.log("🎵 AudioPlayer: Creating buffer at ".concat(d,"Hz (AudioContext: ").concat(p,"Hz)")):console.warn("⚠️ AudioPlayer: outputFormat.sampleRate not set! Using AudioContext sample rate:",p),(f=this.audioContext.createBuffer(1,c.length,d)).getChannelData(0).set(c),(h=this.audioContext.createBufferSource()).buffer=f,h.connect(this.audioContext.destination),v=this.audioContext.currentTime,this.nextStartTime<v&&(this.nextStartTime=v,0===this.scheduledBuffers&&console.log("🎵 Starting playback at current time:",v)),g=f.duration,y=c.length,m=g,p!==d&&(m=y/p,this.scheduledBuffers<3&&(console.log("🔄 Resampling detected: ".concat(d,"Hz → ").concat(p,"Hz")),console.log(" Buffer duration: ".concat(g.toFixed(4),"s, Calculated: ").concat(m.toFixed(4),"s")))),h.start(this.nextStartTime),this.nextStartTime+=m,this.nextStartTime=Math.round(1e6*this.nextStartTime)/1e6,this.scheduledBuffers<3&&(b=this.nextStartTime-m,console.log("🎵 AudioPlayer: Scheduled chunk ".concat(this.scheduledBuffers+1," at ").concat(b.toFixed(4),"s, next at ").concat(this.nextStartTime.toFixed(4),"s")),console.log(" Duration: ".concat(m.toFixed(4),"s (").concat((1e3*m).toFixed(2),"ms)"))),this.scheduledBuffers++,h.onended=function(){w.scheduledBuffers--,0===w.scheduledBuffers&&0===w.pcmChunkQueue.length&&(w.isPlaying=!1,w.isProcessingPcmQueue=!1,w.emit("playbackStopped"))},this.isPlaying||(this.isPlaying=!0,this.emit("playbackStarted")),e.n=3;break;case 5:this.isProcessingPcmQueue=!1,e.n=7;break;case 6:e.p=6,S=e.v,console.error("❌ AudioPlayer v2: Error playing chunk:",S),this.emit("playbackError",S),this.isProcessingPcmQueue=!1;case 7:return e.a(2)}},e,this,[[2,6]])})),function(){return i.apply(this,arguments)})},{key:"createAudioBlob",value:function(e){var t=new Uint8Array(e);console.log("🎵 AudioPlayer: Processing ".concat(t.length," bytes")),console.log("🎵 AudioPlayer: Negotiated format:",this.outputFormat);var n=this.outputFormat&&this.outputFormat.container&&"wav"===this.outputFormat.container.toLowerCase(),o=this.outputFormat&&this.outputFormat.container&&"raw"===this.outputFormat.container.toLowerCase(),r=this.isWavFile(t);if(r&&console.log("🎵 AudioPlayer: Data has WAV header (RIFF)"),o&&r)return console.error("❌ AudioPlayer: CRITICAL MISMATCH!"),console.error(" Negotiated format: RAW"),console.error(" Actual data: WAV (RIFF header detected)"),console.error(" Backend is ignoring format request and sending WAV anyway."),console.warn("⚠️ AudioPlayer: Processing as WAV to avoid playback failure, but UI configuration was bypassed."),this.handleWavFile(t);if(o&&!r)console.log("🎵 AudioPlayer: Processing as RAW data (as negotiated)");else{if(n&&r)return console.log("✅ AudioPlayer: Processing as WAV file (matches negotiation)"),this.handleWavFile(t);if(n&&!r)return console.warn("⚠️ AudioPlayer: Negotiated WAV but data lacks WAV header. Attempting WAV processing anyway."),this.handleWavFile(t);if(!this.outputFormat&&r)return console.log("🎵 AudioPlayer: No format negotiated, auto-detecting WAV"),this.handleWavFile(t);this.outputFormat||r||(console.warn("⚠️ AudioPlayer: No format negotiated and data not WAV, using defaults"),this.outputFormat=this.getDefaultFormat())}return this.outputFormat||(console.warn("⚠️ AudioPlayer: No format set, using defaults"),this.outputFormat=this.getDefaultFormat()),console.log("🎵 AudioPlayer: Processing as RAW data with encoding:",this.outputFormat.encoding),this.handleRawData(t)}},{key:"isWavFile",value:function(e){return e.length>=44&&82===e[0]&&73===e[1]&&70===e[2]&&70===e[3]}},{key:"handleWavFile",value:function(e){var t=this.parseWavHeader(e);if(console.log("🎵 WAV file detected:",{format:t.audioFormat,encoding:this.getEncodingName(t.audioFormat),sampleRate:t.sampleRate,channels:t.channels,bitDepth:t.bitsPerSample}),1===t.audioFormat)return console.log("✅ PCM WAV - using directly"),new Blob([e],{type:"audio/wav"});var n=this.getCodecForWavFormat(t.audioFormat);if(!n)throw new Error("Unsupported WAV format code: ".concat(t.audioFormat));console.log("🔄 Non-PCM WAV - converting to PCM WAV");var o=e.slice(44),r=n.decode(o),i=this.createWavHeader(r.byteLength,t.sampleRate,t.channels,16);return new Blob([i,r],{type:"audio/wav"})}},{key:"handleRawData",value:function(e){var t,n,o=this.outputFormat.encoding.toLowerCase(),r=this.getCodec(o);if(!r)throw new Error("No codec found for encoding: ".concat(o));if(console.log("🎵 AudioPlayer: Decoding ".concat(o.toUpperCase()," to PCM")),console.log("🎵 AudioPlayer: Input format - bitDepth: ".concat(this.outputFormat.bitDepth,", sampleRate: ").concat(this.outputFormat.sampleRate)),"pcm"===o){var i=this.outputFormat.bitDepth||16;e.length,24===i?(console.warn("⚠️ AudioPlayer: Format says 24-bit PCM, but browser support is limited."),console.warn(" Treating as 16-bit PCM. If audio sounds wrong, backend should send 16-bit instead."),t=this.convert24BitTo16Bit(e),n=16):8===i?(console.log("🔄 AudioPlayer: Converting 8-bit PCM to 16-bit PCM"),t=this.convert8BitTo16Bit(e),n=16):(t=e.buffer,n=i,console.log("✅ AudioPlayer: Using native ".concat(i,"-bit PCM (no conversion needed)")))}else t=r.decode(e),n=16,console.log("🔄 AudioPlayer: Decoded ".concat(o.toUpperCase()," to 16-bit PCM"));var a=this.createWavHeader(t.byteLength,this.outputFormat.sampleRate,this.outputFormat.channels,n);return new Blob([a,t],{type:"audio/wav"})}},{key:"convert24BitTo16Bit",value:function(e){for(var t=Math.floor(e.length/3),n=new Int16Array(t),o=0;o<t;o++){var r=e[3*o],i=e[3*o+1],a=e[3*o+2],c=r|i<<8|(255&a)<<16;128&a&&(c|=4278190080),n[o]=Math.max(-32768,Math.min(32767,Math.round(c/256)))}return n.buffer}},{key:"convert8BitTo16Bit",value:function(e){for(var t=e.length,n=new Int16Array(t),o=0;o<t;o++){var r=e[o];n[o]=256*(r-128)}return n.buffer}},{key:"getCodec",value:function(e){var t={pcm:"pcm",linear:"pcm",l16:"pcm",pcmu:"pcmu",ulaw:"pcmu",mulaw:"pcmu",g711u:"pcmu",pcma:"pcma",alaw:"pcma",g711a:"pcma"}[e.toLowerCase()];return this.codecs[t]}},{key:"getCodecForWavFormat",value:function(e){switch(e){case 1:return this.codecs.pcm;case 6:return this.codecs.pcma;case 7:return this.codecs.pcmu;default:return null}}},{key:"getEncodingName",value:function(e){switch(e){case 1:return"PCM";case 6:return"A-law";case 7:return"μ-law";default:return"Unknown (".concat(e,")")}}},{key:"parseWavHeader",value:function(e){var t=new DataView(e.buffer,e.byteOffset,e.byteLength);return{audioFormat:t.getUint16(20,!0),channels:t.getUint16(22,!0),sampleRate:t.getUint32(24,!0),byteRate:t.getUint32(28,!0),blockAlign:t.getUint16(32,!0),bitsPerSample:t.getUint16(34,!0)}}},{key:"createWavHeader",value:function(e,t,n,o){var r=new ArrayBuffer(44),i=new DataView(r);return i.setUint32(0,1380533830,!1),i.setUint32(4,36+e,!0),i.setUint32(8,1463899717,!1),i.setUint32(12,1718449184,!1),i.setUint32(16,16,!0),i.setUint16(20,1,!0),i.setUint16(22,n,!0),i.setUint32(24,t,!0),i.setUint32(28,t*n*o/8,!0),i.setUint16(32,n*o/8,!0),i.setUint16(34,o,!0),i.setUint32(36,1684108385,!1),i.setUint32(40,e,!0),r}},{key:"initializeAudioContext",value:function(){var e,t,n=this,o=(null===(e=this.outputFormat)||void 0===e?void 0:e.sampleRate)||48e3;if(48e3!==o&&44100!==o&&(console.log("ℹ️ AudioPlayer: Backend requested ".concat(o,"Hz, but browser may resample to 48kHz")),console.log(" Consider requesting 48kHz from backend to avoid resampling and improve quality")),this.audioContext){var r=this.audioContext.sampleRate;if(!(Math.abs(r-o)>100))return;console.warn("⚠️ AudioPlayer: AudioContext sample rate (".concat(r,"Hz) doesn't match format (").concat(o,"Hz), recreating...")),this.stopImmediate(),"closed"!==this.audioContext.state&&this.audioContext.close(),this.audioContext=null}console.log("🎵 AudioPlayer: Creating AudioContext at ".concat(o,"Hz (from outputFormat: ").concat((null===(t=this.outputFormat)||void 0===t?void 0:t.sampleRate)||"not set",")"));try{this.audioContext=new(window.AudioContext||window.webkitAudioContext)({sampleRate:o,latencyHint:"playback"}),console.log("✅ AudioContext created at ".concat(this.audioContext.sampleRate,"Hz (requested: ").concat(o,"Hz)")),Math.abs(this.audioContext.sampleRate-o)>100?(console.error("❌ CRITICAL: Browser sample rate mismatch!"),console.error(" Requested: ".concat(o,"Hz")),console.error(" Got: ".concat(this.audioContext.sampleRate,"Hz")),console.error(" This WILL cause audio distortion/noise!"),console.error(" Solution: Backend should send ".concat(this.audioContext.sampleRate,"Hz audio instead"))):this.audioContext.sampleRate!==o&&(console.warn("⚠️ Browser adjusted sample rate: ".concat(o,"Hz → ").concat(this.audioContext.sampleRate,"Hz")),console.warn(" Browser will automatically resample audio.")),this._audioContextStateChangeHandler||(this._audioContextStateChangeHandler=Ne(_e().m(function e(){var t;return _e().w(function(e){for(;;)switch(e.p=e.n){case 0:if(!n.audioContext||"suspended"!==n.audioContext.state){e.n=4;break}if(!(n.scheduledSources.size>0||null!==n.currentSource||n.isPlaying)){e.n=4;break}return console.log("🛑 AudioPlayer: AudioContext was suspended during getUserMedia! Resuming immediately to prevent audio cut-off..."),e.p=1,e.n=2,n.audioContext.resume();case 2:console.log("✅ AudioPlayer: AudioContext resumed successfully"),e.n=4;break;case 3:e.p=3,t=e.v,console.error("❌ AudioPlayer: Failed to resume AudioContext:",t);case 4:return e.a(2)}},e,null,[[1,3]])})),this.audioContext.addEventListener("statechange",this._audioContextStateChangeHandler),console.log("🎵 AudioPlayer: Added AudioContext state change listener to prevent suspension"))}catch(e){console.error("❌ Failed to create AudioContext:",e),this.audioContext=new(window.AudioContext||window.webkitAudioContext),console.log("ℹ️ Using browser default: ".concat(this.audioContext.sampleRate,"Hz"))}}},{key:"processQueue",value:(r=Ne(_e().m(function e(){var t,n,o,r,i,a,c,s,u=this;return _e().w(function(e){for(;;)switch(e.p=e.n){case 0:if(!this.isProcessingQueue&&0!==this.audioQueue.length){e.n=1;break}return e.a(2);case 1:if(this.isProcessingQueue=!0,t=this.audioQueue.shift()){e.n=2;break}return this.isProcessingQueue=!1,e.a(2);case 2:if(e.p=2,n=!this.isPlaying&&null===this.currentSource,this.audioContext||this.initializeAudioContext(),"suspended"!==(o=this.audioContext).state){e.n=4;break}return e.n=3,o.resume();case 3:if(!n){e.n=4;break}return e.n=4,new Promise(function(e){return setTimeout(e,50)});case 4:if("running"===o.state){e.n=8;break}if(console.warn("AudioPlayer v2: AudioContext not in running state:",o.state),"suspended"!==o.state){e.n=8;break}return e.n=5,o.resume();case 5:if(!n){e.n=7;break}return e.n=6,new Promise(function(e){return setTimeout(e,50)});case 6:e.n=8;break;case 7:return e.n=8,new Promise(function(e){return setTimeout(e,10)});case 8:return e.n=9,t.arrayBuffer();case 9:return r=e.v,e.n=10,o.decodeAudioData(r);case 10:i=e.v,a=n&&!this.isPlaying&&null===this.currentSource,(c=o.createBufferSource()).buffer=i,c.connect(o.destination),this.currentSource=c,this.isPlaying=!0,a&&this.emit("playbackStarted"),c.onended=function(){u.currentSource=null,u.isProcessingQueue=!1,u.audioQueue.length>0?setTimeout(function(){return u.processQueue()},50):setTimeout(function(){0!==u.audioQueue.length||u.currentSource||(u.isPlaying=!1,u.emit("playbackStopped"))},100)},c.start(),e.n=12;break;case 11:e.p=11,s=e.v,console.error("❌ AudioPlayer v2: Error processing queue:",s),this.currentSource=null,this.emit("playbackError",s),this.audioQueue.length>0?(this.isProcessingQueue=!1,setTimeout(function(){return u.processQueue()},100)):(this.isPlaying=!1,this.isProcessingQueue=!1,this.emit("playbackStopped"));case 12:return e.a(2)}},e,this,[[2,11]])})),function(){return r.apply(this,arguments)})},{key:"stop",value:function(){this.stopImmediate()}},{key:"reset",value:function(){this.stop(),this.audioQueue=[],this.pcmChunkQueue=[]}},{key:"stopImmediate",value:function(){var e=this.isPlaying||null!==this.currentSource||this.scheduledSources.size>0;if(console.log("🛑 AudioPlayer.stopImmediate() called"),console.log(" isPlaying:",this.isPlaying),console.log(" currentSource:",null!==this.currentSource),console.log(" scheduledSources.size:",this.scheduledSources.size),console.log(" scheduledBuffers:",this.scheduledBuffers),this.currentSource){try{console.log(" Stopping currentSource..."),this.currentSource.stop()}catch(e){console.log(" currentSource already stopped or error:",e.message)}this.currentSource=null}if(this.scheduledSources.size>0){console.log(" Stopping ".concat(this.scheduledSources.size," scheduled sources..."));var t,n=0,o=Fe(this.scheduledSources);try{for(o.s();!(t=o.n()).done;){var r=t.value;try{r.stop(),n++}catch(e){console.log(" Source already stopped or not started:",e.message)}}}catch(e){o.e(e)}finally{o.f()}console.log(" Stopped ".concat(n," sources")),this.scheduledSources.clear()}this.isPlaying=!1,this.isProcessingQueue=!1,this.audioQueue=[],this.pcmChunkQueue=[],this.preparedBuffer=[],this.isProcessingPcmQueue=!1,this.isSchedulingFrames=!1,this.nextStartTime=0,this.scheduledBuffers=0,this.clearTranscriptState(),e&&(console.log("🛑 AudioPlayer: Emitting playbackStopped event (stopImmediate called)"),this.emit("playbackStopped"))}},{key:"markNewSentence",value:function(e){this.pendingSentenceText=e,console.log('📝 AudioPlayer: New sentence marked: "'.concat(e.substring(0,40),'..."'))}},{key:"startTranscriptChecker",value:function(){var e=this;if(!this.isCheckingTranscripts){this.isCheckingTranscripts=!0,console.log("📝 AudioPlayer: Transcript checker started");var t=function(){if(e.isCheckingTranscripts&&e.audioContext){var n,o=e.audioContext.currentTime,r=Fe(e.sentenceTimings);try{for(r.s();!(n=r.n()).done;){var i=n.value;!i.displayed&&o>=i.startTime&&(i.displayed=!0,console.log("📝 AudioPlayer: Display transcript at ".concat(o.toFixed(3),'s: "').concat(i.text.substring(0,40),'..."')),e.emit("transcriptDisplay",{text:i.text}))}}catch(e){r.e(e)}finally{r.f()}e.isPlaying||e.scheduledBuffers>0?requestAnimationFrame(t):(e.isCheckingTranscripts=!1,console.log("📝 AudioPlayer: Transcript checker stopped"))}};requestAnimationFrame(t)}}},{key:"clearTranscriptState",value:function(){this.pendingSentenceText=null,this.sentenceTimings=[],this.isCheckingTranscripts=!1,console.log("📝 AudioPlayer: Transcript state cleared")}},{key:"getStatus",value:function(){return{isPlaying:this.isPlaying,isProcessingQueue:this.isProcessingQueue,queueLength:this.audioQueue.length,audioContextState:this.audioContext?this.audioContext.state:"closed",outputFormat:this.outputFormat,scheduledBuffers:this.scheduledBuffers,preparedBufferLength:this.preparedBuffer.length,scheduledSourcesCount:this.scheduledSources.size}}},{key:"destroy",value:function(){this.stop(),this._audioContextStateChangeHandler&&this.audioContext&&(this.audioContext.removeEventListener("statechange",this._audioContextStateChangeHandler),this._audioContextStateChangeHandler=null),this.audioContext&&"closed"!==this.audioContext.state&&(this.audioContext.close(),this.audioContext=null),this.removeAllListeners()}}],o&&Ve(n.prototype,o),Object.defineProperty(n,"prototype",{writable:!1}),n;var n,o,r,i,a,c}(be);const Ge=We;function qe(e){return qe="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},qe(e)}function Qe(){var e,t,n="function"==typeof Symbol?Symbol:{},o=n.iterator||"@@iterator",r=n.toStringTag||"@@toStringTag";function i(n,o,r,i){var s=o&&o.prototype instanceof c?o:c,u=Object.create(s.prototype);return Je(u,"_invoke",function(n,o,r){var i,c,s,u=0,l=r||[],d=!1,p={p:0,n:0,v:e,a:f,f:f.bind(e,4),d:function(t,n){return i=t,c=0,s=e,p.n=n,a}};function f(n,o){for(c=n,s=o,t=0;!d&&u&&!r&&t<l.length;t++){var r,i=l[t],f=p.p,h=i[2];n>3?(r=h===o)&&(s=i[(c=i[4])?5:(c=3,3)],i[4]=i[5]=e):i[0]<=f&&((r=n<2&&f<i[1])?(c=0,p.v=o,p.n=i[1]):f<h&&(r=n<3||i[0]>o||o>h)&&(i[4]=n,i[5]=o,p.n=h,c=0))}if(r||n>1)return a;throw d=!0,o}return function(r,l,h){if(u>1)throw TypeError("Generator is already running");for(d&&1===l&&f(l,h),c=l,s=h;(t=c<2?e:s)||!d;){i||(c?c<3?(c>1&&(p.n=-1),f(c,s)):p.n=s:p.v=s);try{if(u=2,i){if(c||(r="next"),t=i[r]){if(!(t=t.call(i,s)))throw TypeError("iterator result is not an object");if(!t.done)return t;s=t.value,c<2&&(c=0)}else 1===c&&(t=i.return)&&t.call(i),c<2&&(s=TypeError("The iterator does not provide a '"+r+"' method"),c=1);i=e}else if((t=(d=p.n<0)?s:n.call(o,p))!==a)break}catch(t){i=e,c=1,s=t}finally{u=1}}return{value:t,done:d}}}(n,r,i),!0),u}var a={};function c(){}function s(){}function u(){}t=Object.getPrototypeOf;var l=[][o]?t(t([][o]())):(Je(t={},o,function(){return this}),t),d=u.prototype=c.prototype=Object.create(l);function p(e){return Object.setPrototypeOf?Object.setPrototypeOf(e,u):(e.__proto__=u,Je(e,r,"GeneratorFunction")),e.prototype=Object.create(d),e}return s.prototype=u,Je(d,"constructor",u),Je(u,"constructor",s),s.displayName="GeneratorFunction",Je(u,r,"GeneratorFunction"),Je(d),Je(d,r,"Generator"),Je(d,o,function(){return this}),Je(d,"toString",function(){return"[object Generator]"}),(Qe=function(){return{w:i,m:p}})()}function Je(e,t,n,o){var r=Object.defineProperty;try{r({},"",{})}catch(e){r=0}Je=function(e,t,n,o){function i(t,n){Je(e,t,function(e){return this._invoke(t,n,e)})}t?r?r(e,t,{value:n,enumerable:!o,configurable:!o,writable:!o}):e[t]=n:(i("next",0),i("throw",1),i("return",2))},Je(e,t,n,o)}function Ye(e,t,n,o,r,i,a){try{var c=e[i](a),s=c.value}catch(e){return void n(e)}c.done?t(s):Promise.resolve(s).then(o,r)}function $e(e){return function(){var t=this,n=arguments;return new Promise(function(o,r){var i=e.apply(t,n);function a(e){Ye(i,o,r,a,c,"next",e)}function c(e){Ye(i,o,r,a,c,"throw",e)}a(void 0)})}}function Xe(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,o=Array(t);n<t;n++)o[n]=e[n];return o}function Ze(e,t){for(var n=0;n<t.length;n++){var o=t[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(e,et(o.key),o)}}function et(e){var t=function(e){if("object"!=qe(e)||!e)return e;var t=e[Symbol.toPrimitive];if(void 0!==t){var n=t.call(e,"string");if("object"!=qe(n))return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}(e);return"symbol"==qe(t)?t:t+""}function tt(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(e){}return(tt=function(){return!!e})()}function nt(e){return nt=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(e){return e.__proto__||Object.getPrototypeOf(e)},nt(e)}function ot(e,t){return ot=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,t){return e.__proto__=t,e},ot(e,t)}var rt=function(e){function t(e){var n;return function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,t),(n=function(e,t,n){return t=nt(t),function(e,t){if(t&&("object"==qe(t)||"function"==typeof t))return t;if(void 0!==t)throw new TypeError("Derived constructors may only return object or undefined");return function(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}(e)}(e,tt()?Reflect.construct(t,n||[],nt(e).constructor):t.apply(e,n))}(this,t)).config=e,n.audioContext=null,n.isSharedAudioContext=!1,n.audioWorkletNode=null,n.mediaStream=null,n.isRecording=!1,n._keepAliveOscillator=null,n}return function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&ot(e,t)}(t,e),n=t,o=[{key:"getAudioProcessorPath",value:function(){if(this.config.audioProcessorPath)return this.config.audioProcessorPath;var e,t=function(e,t){var n="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!n){if(Array.isArray(e)||(n=function(e,t){if(e){if("string"==typeof e)return Xe(e,t);var n={}.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?Xe(e,t):void 0}}(e))||t&&e&&"number"==typeof e.length){n&&(e=n);var o=0,r=function(){};return{s:r,n:function(){return o>=e.length?{done:!0}:{done:!1,value:e[o++]}},e:function(e){throw e},f:r}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var i,a=!0,c=!1;return{s:function(){n=n.call(e)},n:function(){var e=n.next();return a=e.done,e},e:function(e){c=!0,i=e},f:function(){try{a||null==n.return||n.return()}finally{if(c)throw i}}}}(document.getElementsByTagName("script"));try{for(t.s();!(e=t.n()).done;){var n=e.value.src;if(n&&(n.includes("agent-widget.js")||n.includes("ttp-agent-sdk")))try{var o=n.substring(0,n.lastIndexOf("/"));return"".concat(o,"/audio-processor.js")}catch(e){var r=n.substring(0,n.lastIndexOf("/"));return"".concat(r,"/audio-processor.js")}}}catch(e){t.e(e)}finally{t.f()}return"https://cdn.talktopc.com/audio-processor.js"}},{key:"start",value:(i=$e(Qe().m(function e(){var t,n,o,r,i,a,c,s,u,l=this,d=arguments;return Qe().w(function(e){for(;;)switch(e.p=e.n){case 0:if(t=d.length>0&&void 0!==d[0]?d[0]:null,e.p=1,"https:"===location.protocol||"localhost"===location.hostname||"127.0.0.1"===location.hostname){e.n=2;break}throw n=new Error("Microphone access requires HTTPS. Please use https:// or test on localhost."),console.error("❌ AudioRecorder:",n.message),this.emit("error",n),n;case 2:if(navigator.mediaDevices&&navigator.mediaDevices.getUserMedia){e.n=3;break}throw o=new Error("getUserMedia is not supported in this browser. Please use a modern browser."),console.error("❌ AudioRecorder:",o.message),this.emit("error",o),o;case 3:return console.log("🎤 AudioRecorder: Requesting microphone access..."),e.n=4,navigator.mediaDevices.getUserMedia({audio:{sampleRate:this.config.sampleRate,channelCount:1,echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0}});case 4:if(this.mediaStream=e.v,console.log("✅ AudioRecorder: Microphone access granted"),!t||"closed"===t.state){e.n=7;break}if(console.log("🎤 AudioRecorder: Using shared AudioContext from AudioPlayer"),this.audioContext=t,this.isSharedAudioContext=!0,"suspended"!==this.audioContext.state){e.n=5;break}return console.log("🎤 AudioRecorder: Resuming shared AudioContext before use"),e.n=5,this.audioContext.resume();case 5:if("running"===this.audioContext.state){e.n=6;break}return console.log('🎤 AudioRecorder: AudioContext state is "'.concat(this.audioContext.state,'", resuming to prevent interruption...')),e.n=6,this.audioContext.resume();case 6:this._audioContextStateChangeHandler=$e(Qe().m(function e(){var t;return Qe().w(function(e){for(;;)switch(e.p=e.n){case 0:if(!l.audioContext||"suspended"!==l.audioContext.state){e.n=4;break}return console.log("🎤 AudioRecorder: AudioContext was suspended, resuming immediately to prevent playback interruption..."),e.p=1,e.n=2,l.audioContext.resume();case 2:e.n=4;break;case 3:e.p=3,t=e.v,console.warn("⚠️ AudioRecorder: Failed to resume AudioContext:",t);case 4:return e.a(2)}},e,null,[[1,3]])})),this.audioContext.addEventListener("statechange",this._audioContextStateChangeHandler);try{r=this.audioContext.createOscillator(),(i=this.audioContext.createGain()).gain.value=0,r.connect(i),i.connect(this.audioContext.destination),r.start(),this._keepAliveOscillator=r,console.log("🎤 AudioRecorder: Created silent oscillator to keep AudioContext alive during getUserMedia")}catch(e){console.warn("⚠️ AudioRecorder: Failed to create keep-alive oscillator:",e)}e.n=8;break;case 7:if(this.audioContext=new(window.AudioContext||window.webkitAudioContext)({sampleRate:this.config.sampleRate}),this.isSharedAudioContext=!1,"suspended"!==this.audioContext.state){e.n=8;break}return e.n=8,this.audioContext.resume();case 8:return a=this.getAudioProcessorPath(),e.n=9,this.audioContext.audioWorklet.addModule(a);case 9:if(!this.isSharedAudioContext||"running"===this.audioContext.state){e.n=10;break}return console.log("🎤 AudioRecorder: AudioContext suspended after AudioWorklet load, resuming..."),e.n=10,this.audioContext.resume();case 10:if(this.audioWorkletNode=new AudioWorkletNode(this.audioContext,"audio-processor"),!this.isSharedAudioContext||"running"===this.audioContext.state){e.n=11;break}return console.log("🎤 AudioRecorder: AudioContext suspended before MediaStreamSource, resuming..."),e.n=11,this.audioContext.resume();case 11:if(this.audioContext.createMediaStreamSource(this.mediaStream).connect(this.audioWorkletNode),!this.isSharedAudioContext||"running"===this.audioContext.state){e.n=12;break}return console.log("🎤 AudioRecorder: AudioContext suspended after MediaStreamSource, resuming immediately..."),e.n=12,this.audioContext.resume();case 12:if(this._keepAliveOscillator)try{this._keepAliveOscillator.stop(),this._keepAliveOscillator.disconnect(),this._keepAliveOscillator=null,console.log("🎤 AudioRecorder: Stopped keep-alive oscillator (MediaStreamSource will keep context alive)")}catch(e){console.warn("⚠️ AudioRecorder: Failed to stop keep-alive oscillator:",e)}this.audioWorkletNode.port.onmessage=function(e){var t=e.data,n=t.type,o=t.data;"pcm_audio_data"===n&&l.emit("audioData",o)},this.audioWorkletNode.port.postMessage({type:"setForceContinuous",data:{enabled:!0}}),this.isRecording=!0,this.emit("recordingStarted"),e.n=14;break;case 13:throw e.p=13,u=e.v,c=u.message,"NotAllowedError"===u.name||"PermissionDeniedError"===u.name?(c="Microphone permission denied. Please allow microphone access in your browser settings and try again.",console.error("❌ AudioRecorder: Permission denied. User needs to grant microphone access.")):"NotFoundError"===u.name||"DevicesNotFoundError"===u.name?(c="No microphone found. Please connect a microphone and try again.",console.error("❌ AudioRecorder: No microphone device found.")):"NotReadableError"===u.name||"TrackStartError"===u.name?(c="Microphone is already in use by another application. Please close other apps using the microphone and try again.",console.error("❌ AudioRecorder: Microphone is busy or not readable.")):u.message&&u.message.includes("not allowed by the user agent")&&(c="Microphone access blocked. On mobile devices, please tap the recording button directly (not from an iframe or popup).",console.error("❌ AudioRecorder: User agent blocked microphone access. This often happens on mobile when not called from direct user interaction.")),(s=new Error(c)).name=u.name,s.originalError=u,console.error("❌ AudioRecorder: Failed to start recording:",s),this.emit("error",s),s;case 14:return e.a(2)}},e,this,[[1,13]])})),function(){return i.apply(this,arguments)})},{key:"stop",value:(r=$e(Qe().m(function e(){var t;return Qe().w(function(e){for(;;)switch(e.p=e.n){case 0:if(this.isRecording){e.n=1;break}return e.a(2);case 1:if(e.p=1,!this.audioWorkletNode){e.n=2;break}return this.audioWorkletNode.port.postMessage({type:"flush"}),e.n=2,new Promise(function(e){return setTimeout(e,100)});case 2:if(this.mediaStream&&(this.mediaStream.getTracks().forEach(function(e){return e.stop()}),this.mediaStream=null),this.audioWorkletNode&&(this.audioWorkletNode.disconnect(),this.audioWorkletNode=null),this._audioContextStateChangeHandler&&this.audioContext&&(this.audioContext.removeEventListener("statechange",this._audioContextStateChangeHandler),this._audioContextStateChangeHandler=null),!this.audioContext||this.isSharedAudioContext||"closed"===this.audioContext.state){e.n=4;break}return e.n=3,this.audioContext.close();case 3:this.audioContext=null,e.n=5;break;case 4:this.isSharedAudioContext&&(this.audioContext=null,this.isSharedAudioContext=!1);case 5:this.isRecording=!1,this.emit("recordingStopped"),e.n=7;break;case 6:throw e.p=6,t=e.v,this.emit("error",t),t;case 7:return e.a(2)}},e,this,[[1,6]])})),function(){return r.apply(this,arguments)})},{key:"getStatus",value:function(){return{isRecording:this.isRecording,audioContextState:this.audioContext?this.audioContext.state:"closed"}}},{key:"destroy",value:function(){this.stop()}}],o&&Ze(n.prototype,o),Object.defineProperty(n,"prototype",{writable:!1}),n;var n,o,r,i}(be);function it(e){return it="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},it(e)}function at(e,t){for(var n=0;n<t.length;n++){var o=t[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(e,ct(o.key),o)}}function ct(e){var t=function(e){if("object"!=it(e)||!e)return e;var t=e[Symbol.toPrimitive];if(void 0!==t){var n=t.call(e,"string");if("object"!=it(n))return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}(e);return"symbol"==it(t)?t:t+""}const st=function(){function e(){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e)}return t=e,n=[{key:"extractPcmFromWav",value:function(e){var t=e instanceof Uint8Array?e:new Uint8Array(e);if(t.length<44)throw new Error("WAV data too short (< 44 bytes)");if("RIFF"!==String.fromCharCode(t[0],t[1],t[2],t[3]))throw new Error("Not a valid WAV file - missing RIFF header");if("WAVE"!==String.fromCharCode(t[8],t[9],t[10],t[11]))throw new Error("Not a valid WAV file - missing WAVE format");for(var n=t[22]|t[23]<<8,o=t[24]|t[25]<<8|t[26]<<16|t[27]<<24,r=t[34]|t[35]<<8,i=-1,a=12;a<t.length-8;a+=4){if("data"===String.fromCharCode(t[a],t[a+1],t[a+2],t[a+3])){i=a;break}a+=4+(t[a+4]|t[a+5]<<8|t[a+6]<<16|t[a+7]<<24)}if(-1===i)throw new Error("No data chunk found in WAV");var c=t[i+4]|t[i+5]<<8|t[i+6]<<16|t[i+7]<<24,s=i+8,u=Math.min(c,t.length-s);return{pcmData:t.slice(s,s+u).buffer,format:{sampleRate:o,channels:n,bitDepth:r}}}},{key:"isWavFile",value:function(e){return e.length>=44&&82===e[0]&&73===e[1]&&70===e[2]&&70===e[3]}},{key:"createWavHeader",value:function(e,t,n,o){var r=new ArrayBuffer(44),i=new DataView(r);return i.setUint32(0,1380533830,!1),i.setUint32(4,36+e,!0),i.setUint32(8,1463899717,!1),i.setUint32(12,1718449184,!1),i.setUint32(16,16,!0),i.setUint16(20,1,!0),i.setUint16(22,n,!0),i.setUint32(24,t,!0),i.setUint32(28,t*n*o/8,!0),i.setUint16(32,n*o/8,!0),i.setUint16(34,o,!0),i.setUint32(36,1684108385,!1),i.setUint32(40,e,!0),r}},{key:"wrapPcmInWav",value:function(t,n){var o=e.createWavHeader(t.byteLength,n.sampleRate,n.channels||1,n.bitDepth||16),r=new Uint8Array(o.byteLength+t.byteLength);return r.set(new Uint8Array(o),0),r.set(new Uint8Array(t),o.byteLength),r.buffer}}],null&&at(t.prototype,null),n&&at(t,n),Object.defineProperty(t,"prototype",{writable:!1}),t;var t,n}();function ut(e){return ut="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},ut(e)}function lt(e,t){for(var n=0;n<t.length;n++){var o=t[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(e,dt(o.key),o)}}function dt(e){var t=function(e){if("object"!=ut(e)||!e)return e;var t=e[Symbol.toPrimitive];if(void 0!==t){var n=t.call(e,"string");if("object"!=ut(n))return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}(e);return"symbol"==ut(t)?t:t+""}const pt=function(){return e=function e(){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),this.codecs={pcm:new Ce,pcmu:new Ee,pcma:new je}},(t=[{key:"decodeToPcm",value:function(e,t){var n=null==t?void 0:t.toLowerCase();if(!n||"pcm"===n)return e instanceof ArrayBuffer?e:e instanceof Uint8Array?e.buffer:e;var o=this.codecs[n];if(!o)throw new Error("Unsupported encoding: ".concat(t));var r=e instanceof Uint8Array?e:new Uint8Array(e);return o.decode(r)}},{key:"encodeFromPcm",value:function(e,t){var n=null==t?void 0:t.toLowerCase();if(!n||"pcm"===n)return e;var o=this.codecs[n];if(!o)throw new Error("Unsupported target encoding: ".concat(t));var r=o.encode(e);return r instanceof Uint8Array?r.buffer:r}},{key:"getCodec",value:function(e){var t=null==e?void 0:e.toLowerCase();return this.codecs[t]||null}}])&<(e.prototype,t),Object.defineProperty(e,"prototype",{writable:!1}),e;var e,t}();function ft(e){return ft="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},ft(e)}function ht(e,t){for(var n=0;n<t.length;n++){var o=t[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(e,vt(o.key),o)}}function vt(e){var t=function(e){if("object"!=ft(e)||!e)return e;var t=e[Symbol.toPrimitive];if(void 0!==t){var n=t.call(e,"string");if("object"!=ft(n))return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}(e);return"symbol"==ft(t)?t:t+""}const gt=function(){function e(){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e)}return t=e,n=[{key:"convert",value:function(t,n,o){if(n===o)return t;if(8===n)throw new Error("Source bit depth cannot be 8-bit (only 16-bit or 24-bit supported)");var r=n/8,i=o/8,a=t.byteLength/r;if(new ArrayBuffer(a*i),16===n&&16===o)return t;if(24===n&&16===o)return e.convert24To16(t);if(16===n&&24===o)return e.convert16To24(t);if(16===n&&8===o)return e.convert16To8(t);if(24===n&&8===o)return e.convert24To8(t);throw new Error("Unsupported bit depth conversion: ".concat(n,"-bit → ").concat(o,"-bit"))}},{key:"convert24To16",value:function(e){for(var t=new Uint8Array(e),n=Math.floor(t.length/3),o=new Int16Array(n),r=0;r<n;r++){var i=t[3*r],a=t[3*r+1],c=t[3*r+2],s=i|a<<8|(255&c)<<16;128&c&&(s|=4278190080),o[r]=Math.max(-32768,Math.min(32767,Math.round(s/256)))}return o.buffer}},{key:"convert16To24",value:function(e){for(var t=new Int16Array(e),n=new Uint8Array(3*t.length),o=0;o<t.length;o++){var r=256*t[o];n[3*o]=255&r,n[3*o+1]=r>>8&255,n[3*o+2]=r>>16&255}return n.buffer}},{key:"convert16To8",value:function(e){for(var t=new Int16Array(e),n=new Uint8Array(t.length),o=0;o<t.length;o++){var r=t[o];n[o]=Math.max(0,Math.min(255,Math.round(r/256+128)))}return n.buffer}},{key:"convert24To8",value:function(t){var n=e.convert24To16(t);return e.convert16To8(n)}}],null&&ht(t.prototype,null),n&&ht(t,n),Object.defineProperty(t,"prototype",{writable:!1}),t;var t,n}();function yt(e){return yt="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},yt(e)}function mt(){var e,t,n="function"==typeof Symbol?Symbol:{},o=n.iterator||"@@iterator",r=n.toStringTag||"@@toStringTag";function i(n,o,r,i){var s=o&&o.prototype instanceof c?o:c,u=Object.create(s.prototype);return bt(u,"_invoke",function(n,o,r){var i,c,s,u=0,l=r||[],d=!1,p={p:0,n:0,v:e,a:f,f:f.bind(e,4),d:function(t,n){return i=t,c=0,s=e,p.n=n,a}};function f(n,o){for(c=n,s=o,t=0;!d&&u&&!r&&t<l.length;t++){var r,i=l[t],f=p.p,h=i[2];n>3?(r=h===o)&&(s=i[(c=i[4])?5:(c=3,3)],i[4]=i[5]=e):i[0]<=f&&((r=n<2&&f<i[1])?(c=0,p.v=o,p.n=i[1]):f<h&&(r=n<3||i[0]>o||o>h)&&(i[4]=n,i[5]=o,p.n=h,c=0))}if(r||n>1)return a;throw d=!0,o}return function(r,l,h){if(u>1)throw TypeError("Generator is already running");for(d&&1===l&&f(l,h),c=l,s=h;(t=c<2?e:s)||!d;){i||(c?c<3?(c>1&&(p.n=-1),f(c,s)):p.n=s:p.v=s);try{if(u=2,i){if(c||(r="next"),t=i[r]){if(!(t=t.call(i,s)))throw TypeError("iterator result is not an object");if(!t.done)return t;s=t.value,c<2&&(c=0)}else 1===c&&(t=i.return)&&t.call(i),c<2&&(s=TypeError("The iterator does not provide a '"+r+"' method"),c=1);i=e}else if((t=(d=p.n<0)?s:n.call(o,p))!==a)break}catch(t){i=e,c=1,s=t}finally{u=1}}return{value:t,done:d}}}(n,r,i),!0),u}var a={};function c(){}function s(){}function u(){}t=Object.getPrototypeOf;var l=[][o]?t(t([][o]())):(bt(t={},o,function(){return this}),t),d=u.prototype=c.prototype=Object.create(l);function p(e){return Object.setPrototypeOf?Object.setPrototypeOf(e,u):(e.__proto__=u,bt(e,r,"GeneratorFunction")),e.prototype=Object.create(d),e}return s.prototype=u,bt(d,"constructor",u),bt(u,"constructor",s),s.displayName="GeneratorFunction",bt(u,r,"GeneratorFunction"),bt(d),bt(d,r,"Generator"),bt(d,o,function(){return this}),bt(d,"toString",function(){return"[object Generator]"}),(mt=function(){return{w:i,m:p}})()}function bt(e,t,n,o){var r=Object.defineProperty;try{r({},"",{})}catch(e){r=0}bt=function(e,t,n,o){function i(t,n){bt(e,t,function(e){return this._invoke(t,n,e)})}t?r?r(e,t,{value:n,enumerable:!o,configurable:!o,writable:!o}):e[t]=n:(i("next",0),i("throw",1),i("return",2))},bt(e,t,n,o)}function St(e,t,n,o,r,i,a){try{var c=e[i](a),s=c.value}catch(e){return void n(e)}c.done?t(s):Promise.resolve(s).then(o,r)}function wt(e,t){for(var n=0;n<t.length;n++){var o=t[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(e,xt(o.key),o)}}function xt(e){var t=function(e){if("object"!=yt(e)||!e)return e;var t=e[Symbol.toPrimitive];if(void 0!==t){var n=t.call(e,"string");if("object"!=yt(n))return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}(e);return"symbol"==yt(t)?t:t+""}const Ct=function(){return e=function e(){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e)},t=[{key:"resample",value:(n=mt().m(function e(t,n,o){var r,i,a,c,s,u,l,d,p,f,h,v,g;return mt().w(function(e){for(;;)switch(e.n){case 0:if(n!==o){e.n=1;break}return e.a(2,t);case 1:for(r=new Int16Array(t),i=new Float32Array(r.length),a=1/32768,c=0;c<r.length;c++)i[c]=r[c]*a;return s=Math.ceil(i.length*o/n),u=new OfflineAudioContext(1,s,o),(l=u.createBuffer(1,i.length,n)).getChannelData(0).set(i),(d=u.createBufferSource()).buffer=l,d.connect(u.destination),d.start(),e.n=2,u.startRendering();case 2:for(p=e.v,f=p.getChannelData(0),h=new Int16Array(f.length),v=0;v<f.length;v++)g=Math.max(-1,Math.min(1,f[v])),h[v]=Math.round(32767*g);return e.a(2,h.buffer)}},e)}),o=function(){var e=this,t=arguments;return new Promise(function(o,r){var i=n.apply(e,t);function a(e){St(i,o,r,a,c,"next",e)}function c(e){St(i,o,r,a,c,"throw",e)}a(void 0)})},function(e,t,n){return o.apply(this,arguments)})}],t&&wt(e,t),Object.defineProperty(e,"prototype",{writable:!1}),e;var e,t,n,o}();function kt(e){return kt="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},kt(e)}function Pt(e,t){for(var n=0;n<t.length;n++){var o=t[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(e,Ot(o.key),o)}}function Ot(e){var t=function(e){if("object"!=kt(e)||!e)return e;var t=e[Symbol.toPrimitive];if(void 0!==t){var n=t.call(e,"string");if("object"!=kt(n))return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}(e);return"symbol"==kt(t)?t:t+""}const Et=function(){function e(){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e)}return t=e,n=[{key:"convert",value:function(t,n,o){var r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:16;if(n===o)return t;if(1===n&&1===o)return t;if(1===n&&2===o)return e.monoToStereo(t,r);if(2===n&&1===o)return e.stereoToMono(t,r);throw new Error("Unsupported channel conversion: ".concat(n," → ").concat(o))}},{key:"monoToStereo",value:function(e,t){for(var n=t/8,o=e.byteLength/n,r=new ArrayBuffer(o*n*2),i=new Uint8Array(e),a=new Uint8Array(r),c=0;c<o;c++)for(var s=c*n,u=c*n*2,l=0;l<n;l++)a[u+l]=i[s+l],a[u+n+l]=i[s+l];return r}},{key:"stereoToMono",value:function(e,t){var n=t/8,o=e.byteLength/(2*n),r=new ArrayBuffer(o*n),i=new Uint8Array(e),a=new Uint8Array(r);if(16===t)for(var c=0;c<o;c++){var s=c*n*2,u=s+n,l=(i[s]|i[s+1]<<8)<<16>>16,d=(i[u]|i[u+1]<<8)<<16>>16,p=Math.round((l+d)/2),f=c*n;a[f]=255&p,a[f+1]=p>>8&255}else for(var h=0;h<o;h++)for(var v=h*n*2,g=h*n,y=0;y<n;y++)a[g+y]=i[v+y];return r}}],null&&Pt(t.prototype,null),n&&Pt(t,n),Object.defineProperty(t,"prototype",{writable:!1}),t;var t,n}();function Tt(e){return Tt="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},Tt(e)}function At(){var e,t,n="function"==typeof Symbol?Symbol:{},o=n.iterator||"@@iterator",r=n.toStringTag||"@@toStringTag";function i(n,o,r,i){var s=o&&o.prototype instanceof c?o:c,u=Object.create(s.prototype);return It(u,"_invoke",function(n,o,r){var i,c,s,u=0,l=r||[],d=!1,p={p:0,n:0,v:e,a:f,f:f.bind(e,4),d:function(t,n){return i=t,c=0,s=e,p.n=n,a}};function f(n,o){for(c=n,s=o,t=0;!d&&u&&!r&&t<l.length;t++){var r,i=l[t],f=p.p,h=i[2];n>3?(r=h===o)&&(s=i[(c=i[4])?5:(c=3,3)],i[4]=i[5]=e):i[0]<=f&&((r=n<2&&f<i[1])?(c=0,p.v=o,p.n=i[1]):f<h&&(r=n<3||i[0]>o||o>h)&&(i[4]=n,i[5]=o,p.n=h,c=0))}if(r||n>1)return a;throw d=!0,o}return function(r,l,h){if(u>1)throw TypeError("Generator is already running");for(d&&1===l&&f(l,h),c=l,s=h;(t=c<2?e:s)||!d;){i||(c?c<3?(c>1&&(p.n=-1),f(c,s)):p.n=s:p.v=s);try{if(u=2,i){if(c||(r="next"),t=i[r]){if(!(t=t.call(i,s)))throw TypeError("iterator result is not an object");if(!t.done)return t;s=t.value,c<2&&(c=0)}else 1===c&&(t=i.return)&&t.call(i),c<2&&(s=TypeError("The iterator does not provide a '"+r+"' method"),c=1);i=e}else if((t=(d=p.n<0)?s:n.call(o,p))!==a)break}catch(t){i=e,c=1,s=t}finally{u=1}}return{value:t,done:d}}}(n,r,i),!0),u}var a={};function c(){}function s(){}function u(){}t=Object.getPrototypeOf;var l=[][o]?t(t([][o]())):(It(t={},o,function(){return this}),t),d=u.prototype=c.prototype=Object.create(l);function p(e){return Object.setPrototypeOf?Object.setPrototypeOf(e,u):(e.__proto__=u,It(e,r,"GeneratorFunction")),e.prototype=Object.create(d),e}return s.prototype=u,It(d,"constructor",u),It(u,"constructor",s),s.displayName="GeneratorFunction",It(u,r,"GeneratorFunction"),It(d),It(d,r,"Generator"),It(d,o,function(){return this}),It(d,"toString",function(){return"[object Generator]"}),(At=function(){return{w:i,m:p}})()}function It(e,t,n,o){var r=Object.defineProperty;try{r({},"",{})}catch(e){r=0}It=function(e,t,n,o){function i(t,n){It(e,t,function(e){return this._invoke(t,n,e)})}t?r?r(e,t,{value:n,enumerable:!o,configurable:!o,writable:!o}):e[t]=n:(i("next",0),i("throw",1),i("return",2))},It(e,t,n,o)}function jt(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(e);t&&(o=o.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,o)}return n}function Dt(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?jt(Object(n),!0).forEach(function(t){Ft(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):jt(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}function Ft(e,t,n){return(t=_t(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function Bt(e,t,n,o,r,i,a){try{var c=e[i](a),s=c.value}catch(e){return void n(e)}c.done?t(s):Promise.resolve(s).then(o,r)}function Rt(e,t){for(var n=0;n<t.length;n++){var o=t[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(e,_t(o.key),o)}}function _t(e){var t=function(e){if("object"!=Tt(e)||!e)return e;var t=e[Symbol.toPrimitive];if(void 0!==t){var n=t.call(e,"string");if("object"!=Tt(n))return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}(e);return"symbol"==Tt(t)?t:t+""}const Ut=function(){return e=function e(t,n){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),this.requestedFormat=t,this.actualFormat=n,this.encodingConverter=new pt,this.conversionSteps=[],this._analyzeConversions()},t=[{key:"_analyzeConversions",value:function(){this.conversionSteps=[],this.actualFormat.container!==this.requestedFormat.container&&("wav"===this.actualFormat.container?this.conversionSteps.push("extract_wav"):"wav"===this.requestedFormat.container&&this.conversionSteps.push("wrap_wav")),this.actualFormat.encoding!==this.requestedFormat.encoding&&("pcm"!==this.actualFormat.encoding&&this.conversionSteps.push("decode_encoding"),"pcm"!==this.requestedFormat.encoding&&this.conversionSteps.push("encode_encoding")),this.actualFormat.sampleRate!==this.requestedFormat.sampleRate&&this.conversionSteps.push("resample"),this.actualFormat.bitDepth!==this.requestedFormat.bitDepth&&this.conversionSteps.push("convert_bitdepth"),this.actualFormat.channels!==this.requestedFormat.channels&&this.conversionSteps.push("convert_channels")}},{key:"needsConversion",value:function(){return this.conversionSteps.length>0}},{key:"getConversionSteps",value:function(){var e=[];return this.conversionSteps.includes("extract_wav")&&e.push("Extract PCM from WAV (".concat(this.actualFormat.container," → raw)")),this.conversionSteps.includes("decode_encoding")&&e.push("Decode ".concat(this.actualFormat.encoding.toUpperCase()," → PCM")),this.conversionSteps.includes("resample")&&e.push("Resample ".concat(this.actualFormat.sampleRate,"Hz → ").concat(this.requestedFormat.sampleRate,"Hz")),this.conversionSteps.includes("convert_bitdepth")&&e.push("Convert bit depth ".concat(this.actualFormat.bitDepth,"-bit → ").concat(this.requestedFormat.bitDepth,"-bit")),this.conversionSteps.includes("convert_channels")&&e.push("Convert channels ".concat(this.actualFormat.channels," → ").concat(this.requestedFormat.channels)),this.conversionSteps.includes("encode_encoding")&&e.push("Encode PCM → ".concat(this.requestedFormat.encoding.toUpperCase())),this.conversionSteps.includes("wrap_wav")&&e.push("Wrap in WAV container (raw → ".concat(this.requestedFormat.container,")")),e}},{key:"convert",value:(n=At().m(function e(t){var n,o,r,i;return At().w(function(e){for(;;)switch(e.n){case 0:if(this.needsConversion()){e.n=1;break}return e.a(2,t instanceof ArrayBuffer?t:t.buffer);case 1:if(n=t instanceof ArrayBuffer?t:t.buffer,o=Dt({},this.actualFormat),this.conversionSteps.includes("extract_wav")&&(r=st.extractPcmFromWav(n),n=r.pcmData,o=Dt(Dt({},o),{},{container:"raw",sampleRate:r.format.sampleRate,channels:r.format.channels,bitDepth:r.format.bitDepth}),console.log("🔄 AudioFormatConverter: Extracted PCM from WAV",r.format)),this.conversionSteps.includes("decode_encoding")&&(n=this.encodingConverter.decodeToPcm(n,o.encoding),o.encoding="pcm",o.bitDepth=16,console.log("🔄 AudioFormatConverter: Decoded ".concat(this.actualFormat.encoding.toUpperCase()," → PCM"))),24===o.bitDepth&&o.bitDepth!==this.requestedFormat.bitDepth&&(this.conversionSteps.includes("resample")||this.conversionSteps.includes("convert_channels")||24!==this.requestedFormat.bitDepth)&&(n=gt.convert(n,24,16),o.bitDepth=16,console.log("🔄 AudioFormatConverter: Normalized 24-bit → 16-bit PCM")),!this.conversionSteps.includes("resample")){e.n=3;break}return e.n=2,Ct.resample(n,o.sampleRate,this.requestedFormat.sampleRate);case 2:n=e.v,o.sampleRate=this.requestedFormat.sampleRate,console.log("🔄 AudioFormatConverter: Resampled ".concat(this.actualFormat.sampleRate,"Hz → ").concat(this.requestedFormat.sampleRate,"Hz"));case 3:return this.conversionSteps.includes("convert_channels")&&(n=Et.convert(n,o.channels,this.requestedFormat.channels,o.bitDepth),o.channels=this.requestedFormat.channels,console.log("🔄 AudioFormatConverter: Converted channels ".concat(this.actualFormat.channels," → ").concat(this.requestedFormat.channels))),this.conversionSteps.includes("convert_bitdepth")&&(n=gt.convert(n,o.bitDepth,this.requestedFormat.bitDepth),o.bitDepth=this.requestedFormat.bitDepth,console.log("🔄 AudioFormatConverter: Converted bit depth ".concat(this.actualFormat.bitDepth,"-bit → ").concat(this.requestedFormat.bitDepth,"-bit"))),this.conversionSteps.includes("encode_encoding")&&(i=this.encodingConverter.encodeFromPcm(n,this.requestedFormat.encoding),n=i instanceof ArrayBuffer?i:i.buffer,o.encoding=this.requestedFormat.encoding,console.log("🔄 AudioFormatConverter: Encoded PCM → ".concat(this.requestedFormat.encoding.toUpperCase()))),this.conversionSteps.includes("wrap_wav")&&(n=st.wrapPcmInWav(n,o),o.container="wav",console.log("🔄 AudioFormatConverter: Wrapped in WAV container")),console.log("✅ AudioFormatConverter: Conversion complete"),e.a(2,n)}},e,this)}),o=function(){var e=this,t=arguments;return new Promise(function(o,r){var i=n.apply(e,t);function a(e){Bt(i,o,r,a,c,"next",e)}function c(e){Bt(i,o,r,a,c,"throw",e)}a(void 0)})},function(e){return o.apply(this,arguments)})}],t&&Rt(e.prototype,t),Object.defineProperty(e,"prototype",{writable:!1}),e;var e,t,n,o}();function Mt(e){return Mt="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},Mt(e)}function Nt(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(e);t&&(o=o.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,o)}return n}function Vt(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?Nt(Object(n),!0).forEach(function(t){Jt(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):Nt(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}function Lt(){var e,t,n="function"==typeof Symbol?Symbol:{},o=n.iterator||"@@iterator",r=n.toStringTag||"@@toStringTag";function i(n,o,r,i){var s=o&&o.prototype instanceof c?o:c,u=Object.create(s.prototype);return Kt(u,"_invoke",function(n,o,r){var i,c,s,u=0,l=r||[],d=!1,p={p:0,n:0,v:e,a:f,f:f.bind(e,4),d:function(t,n){return i=t,c=0,s=e,p.n=n,a}};function f(n,o){for(c=n,s=o,t=0;!d&&u&&!r&&t<l.length;t++){var r,i=l[t],f=p.p,h=i[2];n>3?(r=h===o)&&(s=i[(c=i[4])?5:(c=3,3)],i[4]=i[5]=e):i[0]<=f&&((r=n<2&&f<i[1])?(c=0,p.v=o,p.n=i[1]):f<h&&(r=n<3||i[0]>o||o>h)&&(i[4]=n,i[5]=o,p.n=h,c=0))}if(r||n>1)return a;throw d=!0,o}return function(r,l,h){if(u>1)throw TypeError("Generator is already running");for(d&&1===l&&f(l,h),c=l,s=h;(t=c<2?e:s)||!d;){i||(c?c<3?(c>1&&(p.n=-1),f(c,s)):p.n=s:p.v=s);try{if(u=2,i){if(c||(r="next"),t=i[r]){if(!(t=t.call(i,s)))throw TypeError("iterator result is not an object");if(!t.done)return t;s=t.value,c<2&&(c=0)}else 1===c&&(t=i.return)&&t.call(i),c<2&&(s=TypeError("The iterator does not provide a '"+r+"' method"),c=1);i=e}else if((t=(d=p.n<0)?s:n.call(o,p))!==a)break}catch(t){i=e,c=1,s=t}finally{u=1}}return{value:t,done:d}}}(n,r,i),!0),u}var a={};function c(){}function s(){}function u(){}t=Object.getPrototypeOf;var l=[][o]?t(t([][o]())):(Kt(t={},o,function(){return this}),t),d=u.prototype=c.prototype=Object.create(l);function p(e){return Object.setPrototypeOf?Object.setPrototypeOf(e,u):(e.__proto__=u,Kt(e,r,"GeneratorFunction")),e.prototype=Object.create(d),e}return s.prototype=u,Kt(d,"constructor",u),Kt(u,"constructor",s),s.displayName="GeneratorFunction",Kt(u,r,"GeneratorFunction"),Kt(d),Kt(d,r,"Generator"),Kt(d,o,function(){return this}),Kt(d,"toString",function(){return"[object Generator]"}),(Lt=function(){return{w:i,m:p}})()}function Kt(e,t,n,o){var r=Object.defineProperty;try{r({},"",{})}catch(e){r=0}Kt=function(e,t,n,o){function i(t,n){Kt(e,t,function(e){return this._invoke(t,n,e)})}t?r?r(e,t,{value:n,enumerable:!o,configurable:!o,writable:!o}):e[t]=n:(i("next",0),i("throw",1),i("return",2))},Kt(e,t,n,o)}function zt(e,t,n,o,r,i,a){try{var c=e[i](a),s=c.value}catch(e){return void n(e)}c.done?t(s):Promise.resolve(s).then(o,r)}function Ht(e){return function(){var t=this,n=arguments;return new Promise(function(o,r){var i=e.apply(t,n);function a(e){zt(i,o,r,a,c,"next",e)}function c(e){zt(i,o,r,a,c,"throw",e)}a(void 0)})}}function Wt(e,t){for(var n=0;n<t.length;n++){var o=t[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(e,Yt(o.key),o)}}function Gt(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(e){}return(Gt=function(){return!!e})()}function qt(e){return qt=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(e){return e.__proto__||Object.getPrototypeOf(e)},qt(e)}function Qt(e,t){return Qt=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,t){return e.__proto__=t,e},Qt(e,t)}function Jt(e,t,n){return(t=Yt(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function Yt(e){var t=function(e){if("object"!=Mt(e)||!e)return e;var t=e[Symbol.toPrimitive];if(void 0!==t){var n=t.call(e,"string");if("object"!=Mt(n))return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}(e);return"symbol"==Mt(t)?t:t+""}var $t=function(e){function t(){var e,n=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,t),(e=function(e,t,n){return t=qt(t),function(e,t){if(t&&("object"==Mt(t)||"function"==typeof t))return t;if(void 0!==t)throw new TypeError("Derived constructors may only return object or undefined");return function(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}(e)}(e,Gt()?Reflect.construct(t,n||[],qt(e).constructor):t.apply(e,n))}(this,t)).version="2.0.0",e.config={websocketUrl:n.websocketUrl||"wss://speech.talktopc.com/ws/conv",agentId:n.agentId,appId:n.appId,sampleRate:n.sampleRate||16e3,channels:n.channels||1,bitDepth:n.bitDepth||16,audioProcessorPath:n.audioProcessorPath,outputContainer:n.outputContainer||e.getDefaultContainer(n),outputEncoding:n.outputEncoding||n.outputCodec||"pcm",outputSampleRate:n.outputSampleRate||16e3,outputChannels:n.outputChannels||1,outputBitDepth:n.outputBitDepth||16,outputFrameDurationMs:n.outputFrameDurationMs||600,outputCodec:n.outputCodec,agentSettingsOverride:n.agentSettingsOverride||null,variables:n.variables||null,autoReconnect:!1!==n.autoReconnect,protocolVersion:n.protocolVersion||2},e.isConnected=!1,e.hasEverConnected=!1,e.isRecording=!1,e.isPlaying=!1,e.isDestroyed=!1,e.outputAudioFormat=null,e.requestedOutputFormat=null,e.formatConverter=null,e.websocket=null,e.conversationId=null,e.transcriptQueue=[],e.currentPlayingSentenceId=null,e.audioFrameCount=0,e.audioPlayer=new Ge(e.config),e.audioRecorder=new rt(e.config),e.setupAudioPlayerEvents(),e.setupAudioRecorderEvents(),e.validateConfig(),console.log("🎵 VoiceSDK v2 initialized:",{version:e.version,outputContainer:e.config.outputContainer,outputEncoding:e.config.outputEncoding,outputSampleRate:e.config.outputSampleRate}),e}return function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&Qt(e,t)}(t,e),n=t,o=[{key:"getDefaultContainer",value:function(e){return"wav"===e.outputCodec?"wav":"raw"}},{key:"validateInputFormat",value:function(e){var n;if(!e)return"Input format is required";var o=null===(n=e.encoding)||void 0===n?void 0:n.toLowerCase();return o&&t.SUPPORTED_INPUT_ENCODINGS.includes(o)?e.sampleRate&&t.SUPPORTED_INPUT_SAMPLE_RATES.includes(e.sampleRate)?e.bitDepth&&t.SUPPORTED_INPUT_BIT_DEPTHS.includes(e.bitDepth)?e.channels&&t.SUPPORTED_INPUT_CHANNELS.includes(e.channels)?null:"Unsupported input channels: ".concat(e.channels,". Supported: ").concat(t.SUPPORTED_INPUT_CHANNELS.join(", ")):"Unsupported input bit depth: ".concat(e.bitDepth,". Supported: ").concat(t.SUPPORTED_INPUT_BIT_DEPTHS.join(", ")):"Unsupported input sample rate: ".concat(e.sampleRate,". Supported: ").concat(t.SUPPORTED_INPUT_SAMPLE_RATES.join(", ")):"Unsupported input encoding: ".concat(e.encoding,". Supported: ").concat(t.SUPPORTED_INPUT_ENCODINGS.join(", "))}},{key:"validateOutputFormat",value:function(e){var n,o;if(!e)return"Output format is required";var r=null===(n=e.encoding)||void 0===n?void 0:n.toLowerCase();if(!r||!t.SUPPORTED_OUTPUT_ENCODINGS.includes(r))return"Unsupported output encoding: ".concat(e.encoding,". Supported: ").concat(t.SUPPORTED_OUTPUT_ENCODINGS.join(", "));if(!e.sampleRate||!t.SUPPORTED_OUTPUT_SAMPLE_RATES.includes(e.sampleRate))return"Unsupported output sample rate: ".concat(e.sampleRate,". Supported: ").concat(t.SUPPORTED_OUTPUT_SAMPLE_RATES.join(", "));if(!e.bitDepth||!t.SUPPORTED_OUTPUT_BIT_DEPTHS.includes(e.bitDepth))return"Unsupported output bit depth: ".concat(e.bitDepth,". Supported: ").concat(t.SUPPORTED_OUTPUT_BIT_DEPTHS.join(", "));if(!e.channels||!t.SUPPORTED_OUTPUT_CHANNELS.includes(e.channels))return"Unsupported output channels: ".concat(e.channels,". Supported: ").concat(t.SUPPORTED_OUTPUT_CHANNELS.join(", "));var i=null===(o=e.container)||void 0===o?void 0:o.toLowerCase();return i&&t.SUPPORTED_OUTPUT_CONTAINERS.includes(i)?null:"Unsupported output container: ".concat(e.container,". Supported: ").concat(t.SUPPORTED_OUTPUT_CONTAINERS.join(", "))}},{key:"validateConfig",value:function(){var e={encoding:"pcm",sampleRate:this.config.sampleRate,channels:this.config.channels,bitDepth:this.config.bitDepth},t=this.validateInputFormat(e);if(t)return console.error("❌ VoiceSDK v2: Invalid input format:",t),void this.emit("error",new Error(t));var n={encoding:this.config.outputEncoding,sampleRate:this.config.outputSampleRate,channels:this.config.outputChannels,bitDepth:this.config.outputBitDepth,container:this.config.outputContainer},o=this.validateOutputFormat(n);if(o)return console.error("❌ VoiceSDK v2: Invalid output format:",o),void this.emit("error",new Error(o));console.log("✅ VoiceSDK v2: Format validation passed")}},{key:"setupAudioPlayerEvents",value:function(){var e=this;this.audioPlayer.on("playbackStarted",function(){e.isPlaying=!0,e.emit("playbackStarted"),e.isConnected?(console.log("📤 VoiceSDK v2: Sending audio_started_playing message to server"),e.sendMessage({t:"audio_started_playing"})):console.warn("⚠️ VoiceSDK v2: Cannot send audio_started_playing - not connected")}),this.audioPlayer.on("transcriptDisplay",function(t){var n=e.currentPlayingSentenceId?e.currentPlayingSentenceId+1:1;e.currentPlayingSentenceId=n;var o={text:t.text,role:"assistant",sentenceId:n,final:!0,timestamp:Date.now()};console.log("📝 VoiceSDK v2: Emitting synced transcriptDisplay from AudioPlayer:",o),e.emit("transcriptDisplay",o),e.emit("transcript",o)}),this.audioPlayer.on("playbackStopped",function(){e.isPlaying=!1,e.emit("playbackStopped"),e.isConnected?(console.log("📤 VoiceSDK v2: Sending audio_stopped_playing message to server"),e.sendMessage({t:"audio_stopped_playing"})):console.warn("⚠️ VoiceSDK v2: Cannot send audio_stopped_playing - not connected")}),this.audioPlayer.on("playbackError",function(t){e.emit("playbackError",t),e.emit("error",t)})}},{key:"setupAudioRecorderEvents",value:function(){var e=this;this.audioRecorder.on("recordingStarted",function(){e.isRecording=!0;var t=e.audioPlayer.getStatus(),n=t.scheduledBuffers&&t.scheduledBuffers>0||t.scheduledSourcesCount&&t.scheduledSourcesCount>0,o=e.isPlaying||t.isPlaying||n;console.log("🎤 VoiceSDK v2: Recording started - checking for barge-in..."),console.log(" VoiceSDK.isPlaying:",e.isPlaying),console.log(" AudioPlayer.isPlaying:",t.isPlaying),console.log(" scheduledBuffers:",t.scheduledBuffers||0),console.log(" scheduledSourcesCount:",t.scheduledSourcesCount||0),console.log(" preparedBufferLength:",t.preparedBufferLength||0),console.log(" isActuallyPlaying:",o),o?(console.log("🛑 VoiceSDK v2: Barge-in detected! Stopping audio playback..."),e.stopAudioPlayback(),console.log("✅ VoiceSDK v2: Audio playback stopped"),e.isConnected?(e.sendMessage({t:"barge_in"}),console.log("📤 VoiceSDK v2: Sent barge_in message to server")):console.warn("⚠️ VoiceSDK v2: Cannot send barge_in - not connected")):console.log("ℹ️ VoiceSDK v2: No audio playing, normal recording start"),e.emit("recordingStarted")}),this.audioRecorder.on("recordingStopped",function(){e.isRecording&&(e.isRecording=!1,e._bargeInChecked=!1,e.emit("recordingStopped"),console.log("🛑 VoiceSDK v2: Recording stopped (from audioRecorder event)"))}),this.audioRecorder.on("audioData",function(t){if(!e._bargeInChecked&&e.isRecording){e._bargeInChecked=!0;var n=e.audioPlayer.getStatus(),o=n.scheduledBuffers&&n.scheduledBuffers>0||n.scheduledSourcesCount&&n.scheduledSourcesCount>0;(e.isPlaying||n.isPlaying||o)&&(console.log("🛑 VoiceSDK v2: Barge-in detected on first audio data! Stopping audio playback..."),console.log(" VoiceSDK.isPlaying:",e.isPlaying),console.log(" AudioPlayer.isPlaying:",n.isPlaying),console.log(" scheduledBuffers:",n.scheduledBuffers||0),console.log(" scheduledSourcesCount:",n.scheduledSourcesCount||0),e.stopAudioPlayback(),console.log("✅ VoiceSDK v2: Audio playback stopped"),e.isConnected&&(e.sendMessage({t:"barge_in"}),console.log("📤 VoiceSDK v2: Sent barge_in message to server")))}e.isConnected&&e.sendBinary(t)}),this.audioRecorder.on("error",function(t){console.error("❌ AudioRecorder error:",t),e.emit("error",t)})}},{key:"buildWebSocketUrl",value:function(){var e=this.config.websocketUrl,t=new URLSearchParams;if(this.config.agentId&&t.append("agentId",this.config.agentId),this.config.appId&&t.append("appId",this.config.appId),t.toString()){var n=e.includes("?")?"&":"?";return"".concat(e).concat(n).concat(t.toString())}return e}},{key:"connect",value:(u=Ht(Lt().m(function e(){var t,n,o=this;return Lt().w(function(e){for(;;)switch(e.p=e.n){case 0:if(!this.isDestroyed){e.n=1;break}return console.warn("VoiceSDK v2: Cannot connect - SDK is destroyed"),e.a(2,!1);case 1:if(!this.isConnected){e.n=2;break}return console.warn("VoiceSDK v2: Already connected"),e.a(2,!0);case 2:return e.p=2,t=this.buildWebSocketUrl(),console.log("🔌 VoiceSDK v2: Connecting to",t),e.n=3,new Promise(function(e,n){o.websocket=new WebSocket(t),o.websocket.onopen=function(){console.log("✅ VoiceSDK v2: WebSocket connected"),o.isConnected=!0,o.hasEverConnected=!0,o.sendHelloMessage(),o.emit("connected"),e(!0)},o.websocket.onerror=function(e){console.error("❌ VoiceSDK v2: WebSocket error:",e),n(e)},o.websocket.onclose=function(e){console.log("🔌 VoiceSDK v2: WebSocket closed:",e.code,e.reason),o.isConnected=!1,o.isRecording&&o.stopRecording().catch(function(e){return console.error("Error stopping recording:",e)}),o.emit("disconnected",e),o.config.autoReconnect&&!o.isDestroyed&&o.hasEverConnected?(console.log("🔄 VoiceSDK v2: Auto-reconnecting in 3s..."),setTimeout(function(){o.isDestroyed||o.isConnected||o.connect()},3e3)):o.config.autoReconnect&&!o.hasEverConnected&&console.log("⚠️ VoiceSDK v2: Initial connection failed. Auto-reconnect disabled to prevent retry loop.")},o.websocket.onmessage=function(e){o.handleMessage(e)}});case 3:return e.a(2,e.v);case 4:return e.p=4,n=e.v,console.error("🔌 VoiceSDK v2: Connection failed:",n),this.emit("error",n),e.a(2,!1)}},e,this,[[2,4]])})),function(){return u.apply(this,arguments)})},{key:"sendHelloMessage",value:function(){if(this.isConnected){var e={encoding:"pcm",sampleRate:this.config.sampleRate,channels:this.config.channels,bitDepth:this.config.bitDepth},t={encoding:this.config.outputEncoding,sampleRate:this.config.outputSampleRate,channels:this.config.outputChannels,bitDepth:this.config.outputBitDepth,container:this.config.outputContainer},n=this.validateInputFormat(e);if(n)return console.error("❌ VoiceSDK v2: Cannot send hello - invalid input format:",n),void this.emit("error",new Error("Invalid input format: ".concat(n)));var o=this.validateOutputFormat(t);if(o)return console.error("❌ VoiceSDK v2: Cannot send hello - invalid output format:",o),void this.emit("error",new Error("Invalid output format: ".concat(o)));var r={t:"hello",v:this.config.protocolVersion,inputFormat:e,requestedOutputFormat:t,outputFrameDurationMs:this.config.outputFrameDurationMs};this.config.agentSettingsOverride&&(r.agentSettingsOverride=this.config.agentSettingsOverride),console.log("🔍 VoiceSDK v2: Checking variables:",{hasVariables:!!this.config.variables,variables:this.config.variables,keys:this.config.variables?Object.keys(this.config.variables):[]}),this.config.variables&&Object.keys(this.config.variables).length>0?(r.variables=this.config.variables,console.log("📝 VoiceSDK v2: Including variables in hello:",Object.keys(this.config.variables))):console.log("⚠️ VoiceSDK v2: Variables NOT included - condition failed"),console.log("📤 VoiceSDK v2: Sending hello:",{version:r.v,requestedFormat:r.requestedOutputFormat,variables:r.variables?Object.keys(r.variables):void 0}),console.log("📤 VoiceSDK v2: Requested output format:",{container:r.requestedOutputFormat.container,encoding:r.requestedOutputFormat.encoding,sampleRate:r.requestedOutputFormat.sampleRate,bitDepth:r.requestedOutputFormat.bitDepth}),console.log("📤 VoiceSDK v2: Full hello message being sent:",JSON.stringify(r,null,2));try{this.sendMessage(r)}catch(e){console.error("VoiceSDK v2: Failed to send hello:",e),this.emit("error",e)}}else console.warn("VoiceSDK v2: Cannot send hello - not connected")}},{key:"handleMessage",value:function(e){if(e.data instanceof ArrayBuffer||e.data instanceof Blob)this.handleBinaryMessage(e.data);else try{var t=JSON.parse(e.data);switch("audio"!==t.t&&console.log("📥 VoiceSDK v2: Received message type:",t.t,"Full message:",JSON.stringify(t).substring(0,200)),!this.conversationId&&t.conversationId&&(this.conversationId=t.conversationId,console.log("🔍 VoiceSDK v2: Captured conversationId from message:",this.conversationId),this.emit("conversationIdChanged",this.conversationId)),"audio"!==t.t&&console.log("📨 VoiceSDK v2: Received message type:",t.t,t),t.t){case"hello_ack":this.handleHelloAck(t);break;case"transcript":console.log("📝 VoiceSDK v2: Processing transcript message:",t),this.handleTranscript(t);break;case"user_transcript":console.log("📝 VoiceSDK v2: Received user_transcript:",t),this.emit("message",t);break;case"agent_response":if(console.log("📝 VoiceSDK v2: Received agent_response:",t),(t.text||t.transcript)&&(console.log("📝 VoiceSDK v2: agent_response contains transcript data:",t.text||t.transcript),t.sentenceId&&(t.text||t.transcript))){var n={t:"transcript",sentenceId:t.sentenceId,text:t.text||t.transcript,role:t.role||"assistant",final:!1!==t.final,timestamp:t.timestamp||Date.now()};console.log("📝 VoiceSDK v2: Converting agent_response to transcript:",n),this.handleTranscript(n)}this.emit("message",t);break;case"error":this.emit("message",t);break;case"barge_in":this.emit("bargeIn",t),this.stopAudioPlayback();break;case"stop_playing":this.emit("stopPlaying",t),this.stopAudioPlayback();break;case"audio_start":console.log("📝 VoiceSDK v2: Received audio_start with text:",t.text),t.text&&this.audioPlayer&&this.audioPlayer.markNewSentence(t.text),this.emit("message",t);break;default:if(console.log("VoiceSDK v2: Unknown message type:",t.t,"Full message:",JSON.stringify(t).substring(0,300)),(t.text||t.transcript||t.transcription)&&(console.log("📝 VoiceSDK v2: Unknown message contains transcript-like data:",{text:t.text,transcript:t.transcript,transcription:t.transcription,sentenceId:t.sentenceId,role:t.role}),t.sentenceId&&(t.text||t.transcript||t.transcription))){var o={t:"transcript",sentenceId:t.sentenceId,text:t.text||t.transcript||t.transcription,role:t.role||"assistant",final:!1!==t.final,timestamp:t.timestamp||Date.now()};console.log("📝 VoiceSDK v2: Attempting to process unknown message as transcript:",o),this.handleTranscript(o)}this.emit("message",t)}}catch(e){console.error("VoiceSDK v2: Error parsing message:",e)}}},{key:"handleHelloAck",value:function(e){if(console.log("📥 VoiceSDK v2: Received hello_ack:",{hasOutputFormat:!!e.outputAudioFormat,outputFormat:e.outputAudioFormat,hasConversationId:!!e.conversationId,messageType:e.t}),e.conversationId&&(this.conversationId=e.conversationId,console.log("🔍 VoiceSDK v2: Received conversationId:",this.conversationId),this.emit("conversationIdChanged",this.conversationId)),e.outputAudioFormat){this.outputAudioFormat=e.outputAudioFormat,this.audioPlayer.setOutputFormat(e.outputAudioFormat),console.log("✅ VoiceSDK v2: Format negotiated by server:",this.outputAudioFormat),this.requestedOutputFormat={container:this.config.outputContainer||"wav",encoding:this.config.outputEncoding||"pcm",sampleRate:this.config.outputSampleRate||16e3,bitDepth:this.config.outputBitDepth||16,channels:this.config.outputChannels||1};var t={container:this.outputAudioFormat.container||"unknown",encoding:this.outputAudioFormat.encoding||"unknown",sampleRate:this.outputAudioFormat.sampleRate||0,bitDepth:this.outputAudioFormat.bitDepth||0,channels:this.outputAudioFormat.channels||0},n=[];if(this.requestedOutputFormat.container!==t.container&&n.push('container: "'.concat(this.requestedOutputFormat.container,'" → "').concat(t.container,'"')),this.requestedOutputFormat.encoding!==t.encoding&&n.push('encoding: "'.concat(this.requestedOutputFormat.encoding,'" → "').concat(t.encoding,'"')),this.requestedOutputFormat.sampleRate!==t.sampleRate&&n.push("sampleRate: ".concat(this.requestedOutputFormat.sampleRate,"Hz → ").concat(t.sampleRate,"Hz")),this.requestedOutputFormat.bitDepth!==t.bitDepth&&n.push("bitDepth: ".concat(this.requestedOutputFormat.bitDepth,"-bit → ").concat(t.bitDepth,"-bit")),this.requestedOutputFormat.channels!==t.channels&&n.push("channels: ".concat(this.requestedOutputFormat.channels," → ").concat(t.channels)),n.length>0){console.warn("⚠️ VoiceSDK v2: Format negotiation mismatch!"),console.warn(" Requested:",this.requestedOutputFormat),console.warn(" Negotiated:",t),console.warn(" Differences:",n.join(", "));try{if(this.formatConverter=new Ut(this.requestedOutputFormat,t),this.formatConverter.needsConversion()){var o=this.formatConverter.getConversionSteps();console.log("🔄 VoiceSDK v2: Format conversion enabled"),console.log(" Conversion steps:",o.join(", ")),console.log(" Audio will be automatically converted to requested format")}}catch(e){console.error("❌ VoiceSDK v2: Failed to create format converter:",e),console.warn(" Will use backend format without conversion"),this.formatConverter=null}}else console.log("✅ VoiceSDK v2: Format perfectly matched!",t),this.formatConverter=null;this.emit("formatNegotiated",this.outputAudioFormat)}else{this.config.protocolVersion>=2?(console.warn("⚠️ VoiceSDK v2: hello_ack received but no outputAudioFormat in response."),console.warn(" This may happen if:"),console.warn(" 1. Backend is not sending outputAudioFormat (check backend logs)"),console.warn(" 2. Hello message missing v2 fields (v, inputFormat, requestedOutputFormat)"),console.warn(" 3. Backend validation failed (check backend error logs)"),console.warn(" Using default format from config...")):console.log("✅ VoiceSDK v2: Connected (v1 legacy mode)");var r={container:this.config.outputContainer||"wav",encoding:this.config.outputEncoding||"pcm",sampleRate:this.config.outputSampleRate||16e3,channels:this.config.outputChannels||1,bitDepth:this.config.outputBitDepth||16};this.outputAudioFormat=r,this.requestedOutputFormat=r,this.audioPlayer.setOutputFormat(r),this.formatConverter=null}}},{key:"handleTranscript",value:function(e){if(e.sentenceId&&e.text){var t=e.sentenceId,n={text:e.text,role:e.role||"assistant",sentenceId:t,final:!1!==e.final,timestamp:e.timestamp||Date.now()};this.transcriptQueue.push(n),console.log("📝 VoiceSDK v2: Received transcript for sentence",t,":",n.text),console.log(" Transcript queue length:",this.transcriptQueue.length),console.log(" Current playing sentence:",this.currentPlayingSentenceId),console.log("📝 VoiceSDK v2: Displaying transcript for completed sentence",t),this.emit("transcriptDisplay",n),this.currentPlayingSentenceId=t,this.emit("transcript",n)}else console.warn("⚠️ VoiceSDK v2: Invalid transcript message:",e)}},{key:"handleBinaryMessage",value:(s=Ht(Lt().m(function e(t){var n,o,r,i,a,c,s,u,l,d;return Lt().w(function(e){for(;;)switch(e.p=e.n){case 0:if(!(t instanceof Blob)){e.n=2;break}return e.n=1,t.arrayBuffer();case 1:o=e.v,e.n=3;break;case 2:o=t;case 3:if(console.log("📥 VoiceSDK v2: Received audio:",o.byteLength,"bytes"),console.log(" Current outputFormat:",this.outputAudioFormat),console.log(" AudioPlayer outputFormat:",null===(n=this.audioPlayer)||void 0===n?void 0:n.outputFormat),console.log(" Format converter:",this.formatConverter?"active":"none"),r=o,!this.formatConverter||!this.formatConverter.needsConversion()){e.n=7;break}return e.p=4,e.n=5,this.formatConverter.convert(o);case 5:r=e.v,console.log("✅ VoiceSDK v2: Audio converted to requested format"),e.n=7;break;case 6:e.p=6,d=e.v,console.error("❌ VoiceSDK v2: Format conversion failed:",d),console.warn(" Using backend format without conversion"),r=o;case 7:i=this.formatConverter&&this.formatConverter.needsConversion()?this.requestedOutputFormat:this.outputAudioFormat||{container:this.config.outputContainer||"raw",encoding:this.config.outputEncoding||"pcm",sampleRate:this.config.outputSampleRate||16e3,bitDepth:this.config.outputBitDepth||16,channels:this.config.outputChannels||1},a=i.container||"raw",c=(i.encoding||"pcm").toLowerCase(),"raw"===a?(s=r,"pcm"!==c&&((u=this.audioPlayer.getCodec(c))?(l=u.decode(new Uint8Array(r)),s=l.buffer,console.log("🔄 VoiceSDK v2: Decoded ".concat(c.toUpperCase()," to PCM (").concat(l.byteLength," bytes)"))):console.warn("⚠️ VoiceSDK v2: No codec for ".concat(c,", treating as PCM"))),this.audioPlayer.outputFormat||(console.warn("⚠️ VoiceSDK v2: outputFormat not set on AudioPlayer, setting from playbackFormat"),this.audioPlayer.setOutputFormat(i)),this.audioFrameCount++,this.audioPlayer.playChunk(s)):(this.audioFrameCount++,this.audioPlayer.playAudio(r));case 8:return e.a(2)}},e,this,[[4,6]])})),function(e){return s.apply(this,arguments)})},{key:"sendMessage",value:function(e){if(!this.websocket||this.websocket.readyState!==WebSocket.OPEN)return console.warn("VoiceSDK v2: Cannot send message - not connected"),!1;try{return this.websocket.send(JSON.stringify(e)),!0}catch(e){return console.error("VoiceSDK v2: Error sending message:",e),this.emit("error",e),!1}}},{key:"sendBinary",value:function(e){if(!this.websocket||this.websocket.readyState!==WebSocket.OPEN)return console.warn("VoiceSDK v2: Cannot send audio - not connected"),!1;try{return this.websocket.send(e),!0}catch(e){return console.error("VoiceSDK v2: Error sending audio:",e),this.emit("error",e),!1}}},{key:"disconnect",value:function(){this.isDestroyed||(console.log("🔌 VoiceSDK v2: Disconnecting..."),this.stopRecording(),this.audioPlayer&&this.stopAudioPlayback(),this.websocket&&(this.websocket.close(),this.websocket=null),this.isConnected=!1)}},{key:"startRecording",value:(c=Ht(Lt().m(function e(){var t,n,o,r,i,a,c;return Lt().w(function(e){for(;;)switch(e.p=e.n){case 0:if(this.isConnected){e.n=1;break}throw t=new Error("Not connected to voice server"),this.emit("error",t),t;case 1:if(!this.isRecording){e.n=2;break}return console.warn("VoiceSDK v2: Already recording"),e.a(2,!0);case 2:if(console.log("🎤 VoiceSDK v2: Starting recording..."),e.p=3,console.log("🎤 VoiceSDK v2: Requesting microphone permission (mobile-friendly)..."),n=this.audioPlayer?this.audioPlayer.getStatus():null,o=this.isPlaying||n&&(n.isPlaying||n.scheduledBuffers&&n.scheduledBuffers>0||n.scheduledSourcesCount&&n.scheduledSourcesCount>0),r=null,o||!this.audioPlayer||!this.audioPlayer.audioContext||"closed"===this.audioPlayer.audioContext.state){e.n=5;break}if(r=this.audioPlayer.audioContext,console.log("🎤 VoiceSDK v2: Sharing AudioPlayer AudioContext with AudioRecorder (no audio playing)"),"suspended"!==r.state){e.n=4;break}return console.log("🎤 VoiceSDK v2: Resuming AudioPlayer AudioContext before recording starts"),e.n=4,r.resume();case 4:e.n=7;break;case 5:if(!o){e.n=7;break}if(console.log("🎤 VoiceSDK v2: Audio is currently playing - using separate AudioContext for recording to prevent interruption"),!this.audioPlayer||!this.audioPlayer.audioContext||"closed"===this.audioPlayer.audioContext.state){e.n=7;break}if("running"===(i=this.audioPlayer.audioContext).state){e.n=6;break}return console.log("🎤 VoiceSDK v2: Ensuring playback AudioContext is running before getUserMedia..."),e.n=6,i.resume();case 6:if("running"===i.state){e.n=7;break}return console.warn("⚠️ VoiceSDK v2: Playback AudioContext is not running, attempting to resume again..."),e.n=7,i.resume();case 7:return e.n=8,this.audioRecorder.start(r);case 8:if(!(o&&this.audioPlayer&&this.audioPlayer.audioContext&&"closed"!==this.audioPlayer.audioContext.state)){e.n=10;break}if("suspended"!==(a=this.audioPlayer.audioContext).state){e.n=9;break}return console.log("🛑 VoiceSDK v2: Playback AudioContext was suspended after getUserMedia! Resuming immediately..."),e.n=9,a.resume();case 9:setTimeout(Ht(Lt().m(function e(){return Lt().w(function(e){for(;;)switch(e.n){case 0:if(!a||"suspended"!==a.state){e.n=1;break}return console.log("🛑 VoiceSDK v2: Playback AudioContext was suspended after delay! Resuming..."),e.n=1,a.resume();case 1:return e.a(2)}},e)})),10);case 10:return this.sendMessage({t:"start_continuous_mode",ttpId:this.generateTtpId()}),e.a(2,!0);case 11:return e.p=11,c=e.v,console.error("❌ VoiceSDK v2: Failed to start recording:",c),this.emit("error",c),e.a(2,!1)}},e,this,[[3,11]])})),function(){return c.apply(this,arguments)})},{key:"stopRecording",value:(a=Ht(Lt().m(function e(){var t;return Lt().w(function(e){for(;;)switch(e.p=e.n){case 0:if(this.isRecording){e.n=1;break}return console.warn("VoiceSDK v2: Not recording"),e.a(2,!0);case 1:return console.log("🛑 VoiceSDK v2: Stopping recording..."),e.p=2,this.sendMessage({t:"stop_continuous_mode",ttpId:this.generateTtpId()}),this.isRecording=!1,this._bargeInChecked=!1,this.emit("recordingStopped"),console.log("🛑 VoiceSDK v2: Recording stopped (emitted before audioRecorder.stop())"),e.n=3,this.audioRecorder.stop();case 3:return this.stopAudioPlayback(),e.a(2,!0);case 4:return e.p=4,t=e.v,console.error("VoiceSDK v2: Error stopping recording:",t),this.emit("error",t),e.a(2,!1)}},e,this,[[2,4]])})),function(){return a.apply(this,arguments)})},{key:"toggleRecording",value:(i=Ht(Lt().m(function e(){return Lt().w(function(e){for(;;)switch(e.n){case 0:if(!this.isRecording){e.n=2;break}return e.n=1,this.stopRecording();case 1:case 3:return e.a(2,e.v);case 2:return e.n=3,this.startRecording();case 4:return e.a(2)}},e,this)})),function(){return i.apply(this,arguments)})},{key:"clearTranscriptState",value:function(){this.currentPlayingSentenceId=null,console.log("📝 VoiceSDK v2: Cleared transcript state")}},{key:"stopAudioPlayback",value:function(){this.audioPlayer.stopImmediate(),this.clearTranscriptState()}},{key:"handleBargeIn",value:(r=Ht(Lt().m(function e(){return Lt().w(function(e){for(;;)switch(e.n){case 0:if(this.stopAudioPlayback(),this.isRecording){e.n=1;break}return e.n=1,this.startRecording();case 1:return e.a(2)}},e,this)})),function(){return r.apply(this,arguments)})},{key:"getStatus",value:function(){return{version:this.version,isConnected:this.isConnected,isRecording:this.isRecording,isPlaying:this.isPlaying,outputFormat:this.outputAudioFormat,conversationId:this.conversationId,audioPlayer:this.audioPlayer.getStatus(),audioRecorder:this.audioRecorder.getStatus()}}},{key:"updateConfig",value:function(e){this.config=Vt(Vt({},this.config),e)}},{key:"generateTtpId",value:function(){return"sdk_"+Math.random().toString(36).substr(2,9)+"_"+Date.now()}},{key:"destroy",value:function(){this.isDestroyed||(console.log("🗑️ VoiceSDK v2: Destroying..."),this.disconnect(),this.isDestroyed=!0,this.audioPlayer&&this.audioPlayer.destroy(),this.audioRecorder&&this.audioRecorder.destroy(),this.removeAllListeners())}}],o&&Wt(n.prototype,o),Object.defineProperty(n,"prototype",{writable:!1}),n;var n,o,r,i,a,c,s,u}(be);Jt($t,"SUPPORTED_INPUT_ENCODINGS",["pcm","pcmu","pcma"]),Jt($t,"SUPPORTED_INPUT_SAMPLE_RATES",[8e3,16e3,22050,24e3,44100,48e3]),Jt($t,"SUPPORTED_INPUT_BIT_DEPTHS",[8,16,24]),Jt($t,"SUPPORTED_INPUT_CHANNELS",[1]),Jt($t,"SUPPORTED_OUTPUT_ENCODINGS",["pcm","pcmu","pcma"]),Jt($t,"SUPPORTED_OUTPUT_SAMPLE_RATES",[8e3,16e3,22050,24e3,44100,48e3]),Jt($t,"SUPPORTED_OUTPUT_BIT_DEPTHS",[8,16,24]),Jt($t,"SUPPORTED_OUTPUT_CHANNELS",[1]),Jt($t,"SUPPORTED_OUTPUT_CONTAINERS",["raw","wav"]);const Xt=$t;function Zt(e){return Zt="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},Zt(e)}function en(){var e,t,n="function"==typeof Symbol?Symbol:{},o=n.iterator||"@@iterator",r=n.toStringTag||"@@toStringTag";function i(n,o,r,i){var s=o&&o.prototype instanceof c?o:c,u=Object.create(s.prototype);return tn(u,"_invoke",function(n,o,r){var i,c,s,u=0,l=r||[],d=!1,p={p:0,n:0,v:e,a:f,f:f.bind(e,4),d:function(t,n){return i=t,c=0,s=e,p.n=n,a}};function f(n,o){for(c=n,s=o,t=0;!d&&u&&!r&&t<l.length;t++){var r,i=l[t],f=p.p,h=i[2];n>3?(r=h===o)&&(s=i[(c=i[4])?5:(c=3,3)],i[4]=i[5]=e):i[0]<=f&&((r=n<2&&f<i[1])?(c=0,p.v=o,p.n=i[1]):f<h&&(r=n<3||i[0]>o||o>h)&&(i[4]=n,i[5]=o,p.n=h,c=0))}if(r||n>1)return a;throw d=!0,o}return function(r,l,h){if(u>1)throw TypeError("Generator is already running");for(d&&1===l&&f(l,h),c=l,s=h;(t=c<2?e:s)||!d;){i||(c?c<3?(c>1&&(p.n=-1),f(c,s)):p.n=s:p.v=s);try{if(u=2,i){if(c||(r="next"),t=i[r]){if(!(t=t.call(i,s)))throw TypeError("iterator result is not an object");if(!t.done)return t;s=t.value,c<2&&(c=0)}else 1===c&&(t=i.return)&&t.call(i),c<2&&(s=TypeError("The iterator does not provide a '"+r+"' method"),c=1);i=e}else if((t=(d=p.n<0)?s:n.call(o,p))!==a)break}catch(t){i=e,c=1,s=t}finally{u=1}}return{value:t,done:d}}}(n,r,i),!0),u}var a={};function c(){}function s(){}function u(){}t=Object.getPrototypeOf;var l=[][o]?t(t([][o]())):(tn(t={},o,function(){return this}),t),d=u.prototype=c.prototype=Object.create(l);function p(e){return Object.setPrototypeOf?Object.setPrototypeOf(e,u):(e.__proto__=u,tn(e,r,"GeneratorFunction")),e.prototype=Object.create(d),e}return s.prototype=u,tn(d,"constructor",u),tn(u,"constructor",s),s.displayName="GeneratorFunction",tn(u,r,"GeneratorFunction"),tn(d),tn(d,r,"Generator"),tn(d,o,function(){return this}),tn(d,"toString",function(){return"[object Generator]"}),(en=function(){return{w:i,m:p}})()}function tn(e,t,n,o){var r=Object.defineProperty;try{r({},"",{})}catch(e){r=0}tn=function(e,t,n,o){function i(t,n){tn(e,t,function(e){return this._invoke(t,n,e)})}t?r?r(e,t,{value:n,enumerable:!o,configurable:!o,writable:!o}):e[t]=n:(i("next",0),i("throw",1),i("return",2))},tn(e,t,n,o)}function nn(e,t,n,o,r,i,a){try{var c=e[i](a),s=c.value}catch(e){return void n(e)}c.done?t(s):Promise.resolve(s).then(o,r)}function on(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(e);t&&(o=o.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,o)}return n}function rn(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?on(Object(n),!0).forEach(function(t){an(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):on(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}function an(e,t,n){return(t=sn(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function cn(e,t){for(var n=0;n<t.length;n++){var o=t[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(e,sn(o.key),o)}}function sn(e){var t=function(e){if("object"!=Zt(e)||!e)return e;var t=e[Symbol.toPrimitive];if(void 0!==t){var n=t.call(e,"string");if("object"!=Zt(n))return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}(e);return"symbol"==Zt(t)?t:t+""}function un(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(e){}return(un=function(){return!!e})()}function ln(e){return ln=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(e){return e.__proto__||Object.getPrototypeOf(e)},ln(e)}function dn(e,t){return dn=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,t){return e.__proto__=t,e},dn(e,t)}var pn=function(e){function t(){var e,n=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,t);var o=(e=function(e,t,n){return t=ln(t),function(e,t){if(t&&("object"==Zt(t)||"function"==typeof t))return t;if(void 0!==t)throw new TypeError("Derived constructors may only return object or undefined");return function(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}(e)}(e,un()?Reflect.construct(t,n||[],ln(e).constructor):t.apply(e,n))}(this,t)).readScriptTagConfig();return e.config=rn({baseWsUrl:"wss://backend.talktopc.com/chat/websocket",appId:n.appId||o.appId,agentId:n.agentId||o.agentId,conversationId:void 0!==n.conversationId?n.conversationId:e.getPersistedConversationId(),forceConversationId:n.forceConversationId,queue:[],inFlight:!1},n),e.fullResponseBuffer="",e}return function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&dn(e,t)}(t,e),n=t,o=[{key:"readScriptTagConfig",value:function(){try{var e=Array.from(document.getElementsByTagName("script")).reverse().find(function(e){return e.dataset&&(e.dataset.appId||e.dataset.agentId)||e.src&&e.src.includes("agent-widget")});return e?{appId:e.dataset.appId,agentId:e.dataset.agentId}:{}}catch(e){return{}}}},{key:"buildWebSocketUrl",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:this.config.baseWsUrl,t=new URLSearchParams;return this.config.appId&&t.append("appId",this.config.appId),this.config.agentId&&t.append("agentId",this.config.agentId),this.config.conversationId&&t.append("conversationId",this.config.conversationId),"".concat(e,"?").concat(t.toString())}},{key:"sendMessage",value:(r=en().m(function e(t){var n=this;return en().w(function(e){for(;;)if(0===e.n)return e.a(2,new Promise(function(e,o){if(t&&t.trim())if(n.config.appId&&n.config.agentId){var r={text:t,resolve:e,reject:o};n.config.inFlight?n.config.queue.push(r):n.executeTask(r)}else o(new Error("Missing appId or agentId"));else o(new Error("Message is empty"))}))},e)}),i=function(){var e=this,t=arguments;return new Promise(function(n,o){var i=r.apply(e,t);function a(e){nn(i,n,o,a,c,"next",e)}function c(e){nn(i,n,o,a,c,"throw",e)}a(void 0)})},function(e){return i.apply(this,arguments)})},{key:"executeTask",value:function(e){var t=this;if(this.config.inFlight=!0,this.fullResponseBuffer="",!this.config.conversationId){var n=this.getPersistedConversationId();n&&(this.config.conversationId=n,console.log("🔍 TextChatSDK hydrated conversationId from storage:",n))}var o,r=this.buildWebSocketUrl(this.config.baseWsUrl),i=this.config.baseWsUrl.endsWith("/websocket")?this.config.baseWsUrl.replace(/\/websocket$/,""):"".concat(this.config.baseWsUrl,"/websocket"),a=this.buildWebSocketUrl(i),c=!1,s=!1,u=null,l=function(n){if(!s)try{var o={message:e.text},r=t.config.forceConversationId||t.config.conversationId;r&&(o.conversationId=r,t.config.forceConversationId&&!t.config.conversationId&&(t.config.conversationId=r,t.persistConversationId(r))),console.log("🔍 TextChatSDK sending payload:",o,"conversationId in config:",t.config.conversationId),n.send(JSON.stringify(o)),s=!0}catch(o){e.reject(o),t.emit("error",o);try{n.close()}catch(e){}}},d=function(e){return function(){t.config.conversationId?l(e):u=setTimeout(function(){return l(e)},200)}},p=function(n){return function(o){try{try{console.log("🔎 [TextChatSDK] WS <= raw:",o.data)}catch(e){}var r=JSON.parse(o.data);try{console.log("🔎 [TextChatSDK] WS <= parsed:",r)}catch(e){}if("hello"===r.type&&r.conversationId){if(console.log("🔍 TextChatSDK received conversationId:",r.conversationId),t.config.conversationId=r.conversationId,t.persistConversationId(r.conversationId),t.emit&&t.emit("conversationIdChanged",r.conversationId),!s&&n&&1===n.readyState){if(u)try{clearTimeout(u)}catch(e){}l(n)}return}if(!t.config.conversationId&&r.conversationId&&(console.log("🔍 TextChatSDK captured conversationId from message:",r.conversationId),t.config.conversationId=r.conversationId,t.persistConversationId(r.conversationId)),"chunk"===r.type&&"string"==typeof r.content)t.fullResponseBuffer+=r.content,t.emit("chunk",r.content);else if("done"===r.type){try{var i=r.text||r.content||r.answer||r.message||"";i&&!t.fullResponseBuffer&&(t.fullResponseBuffer=i)}catch(e){}!t.config.conversationId&&r.conversationId&&(console.log("🔍 TextChatSDK captured conversationId from done:",r.conversationId),t.config.conversationId=r.conversationId),t.persistConversationId(t.config.conversationId),t.emit("done",{text:t.fullResponseBuffer}),e.resolve({conversationId:t.config.conversationId,fullText:t.fullResponseBuffer});try{n.close()}catch(e){}}else if("error"===r.type){var a=new Error(r.message||"Server error");t.emit("error",a),e.reject(a);try{n.close()}catch(e){}}}catch(e){}}},f=function(n){if(1008===n.code&&n.reason&&(n.reason.includes("Domain not whitelisted")||n.reason.includes("domain")||n.reason.includes("whitelist"))){var o=new Error("DOMAIN_NOT_WHITELISTED");return o.reason=n.reason,o.code=n.code,t.emit("domainError",o),e.reject(o),t.config.inFlight=!1,void t.drainQueue()}t.config.inFlight=!1,t.drainQueue()},h=new WebSocket(r);h.onopen=d(h),h.onmessage=p(h),h.onerror=(o=h,function(n){if(!c){c=!0;try{o.close()}catch(e){}var r=new WebSocket(a);return r.onopen=d(r),r.onmessage=p(r),r.onerror=function(n){t.emit("error",n),e.reject(n)},void(r.onclose=f)}t.emit("error",n),e.reject(n)}),h.onclose=f}},{key:"drainQueue",value:function(){if(0!==this.config.queue.length&&!this.config.inFlight){var e=this.config.queue.shift();this.executeTask(e)}}},{key:"persistConversationId",value:function(e){try{e&&localStorage.setItem("ttp_text_chat_conversation_id",e)}catch(e){}}},{key:"getPersistedConversationId",value:function(){try{return localStorage.getItem("ttp_text_chat_conversation_id")||null}catch(e){return null}}},{key:"updateConfig",value:function(e){this.config=rn(rn({},this.config),e)}},{key:"destroy",value:function(){this.config.queue=[],this.config.inFlight=!1,this.removeAllListeners()}}],o&&cn(n.prototype,o),Object.defineProperty(n,"prototype",{writable:!1}),n;var n,o,r,i}(c),fn=n(540),hn=n(848);function vn(e){return vn="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},vn(e)}function gn(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(e);t&&(o=o.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,o)}return n}function yn(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?gn(Object(n),!0).forEach(function(t){mn(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):gn(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}function mn(e,t,n){return(t=function(e){var t=function(e){if("object"!=vn(e)||!e)return e;var t=e[Symbol.toPrimitive];if(void 0!==t){var n=t.call(e,"string");if("object"!=vn(n))return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}(e);return"symbol"==vn(t)?t:t+""}(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function bn(){var e,t,n="function"==typeof Symbol?Symbol:{},o=n.iterator||"@@iterator",r=n.toStringTag||"@@toStringTag";function i(n,o,r,i){var s=o&&o.prototype instanceof c?o:c,u=Object.create(s.prototype);return Sn(u,"_invoke",function(n,o,r){var i,c,s,u=0,l=r||[],d=!1,p={p:0,n:0,v:e,a:f,f:f.bind(e,4),d:function(t,n){return i=t,c=0,s=e,p.n=n,a}};function f(n,o){for(c=n,s=o,t=0;!d&&u&&!r&&t<l.length;t++){var r,i=l[t],f=p.p,h=i[2];n>3?(r=h===o)&&(s=i[(c=i[4])?5:(c=3,3)],i[4]=i[5]=e):i[0]<=f&&((r=n<2&&f<i[1])?(c=0,p.v=o,p.n=i[1]):f<h&&(r=n<3||i[0]>o||o>h)&&(i[4]=n,i[5]=o,p.n=h,c=0))}if(r||n>1)return a;throw d=!0,o}return function(r,l,h){if(u>1)throw TypeError("Generator is already running");for(d&&1===l&&f(l,h),c=l,s=h;(t=c<2?e:s)||!d;){i||(c?c<3?(c>1&&(p.n=-1),f(c,s)):p.n=s:p.v=s);try{if(u=2,i){if(c||(r="next"),t=i[r]){if(!(t=t.call(i,s)))throw TypeError("iterator result is not an object");if(!t.done)return t;s=t.value,c<2&&(c=0)}else 1===c&&(t=i.return)&&t.call(i),c<2&&(s=TypeError("The iterator does not provide a '"+r+"' method"),c=1);i=e}else if((t=(d=p.n<0)?s:n.call(o,p))!==a)break}catch(t){i=e,c=1,s=t}finally{u=1}}return{value:t,done:d}}}(n,r,i),!0),u}var a={};function c(){}function s(){}function u(){}t=Object.getPrototypeOf;var l=[][o]?t(t([][o]())):(Sn(t={},o,function(){return this}),t),d=u.prototype=c.prototype=Object.create(l);function p(e){return Object.setPrototypeOf?Object.setPrototypeOf(e,u):(e.__proto__=u,Sn(e,r,"GeneratorFunction")),e.prototype=Object.create(d),e}return s.prototype=u,Sn(d,"constructor",u),Sn(u,"constructor",s),s.displayName="GeneratorFunction",Sn(u,r,"GeneratorFunction"),Sn(d),Sn(d,r,"Generator"),Sn(d,o,function(){return this}),Sn(d,"toString",function(){return"[object Generator]"}),(bn=function(){return{w:i,m:p}})()}function Sn(e,t,n,o){var r=Object.defineProperty;try{r({},"",{})}catch(e){r=0}Sn=function(e,t,n,o){function i(t,n){Sn(e,t,function(e){return this._invoke(t,n,e)})}t?r?r(e,t,{value:n,enumerable:!o,configurable:!o,writable:!o}):e[t]=n:(i("next",0),i("throw",1),i("return",2))},Sn(e,t,n,o)}function wn(e,t,n,o,r,i,a){try{var c=e[i](a),s=c.value}catch(e){return void n(e)}c.done?t(s):Promise.resolve(s).then(o,r)}function xn(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var n=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=n){var o,r,i,a,c=[],s=!0,u=!1;try{if(i=(n=n.call(e)).next,0===t){if(Object(n)!==n)return;s=!1}else for(;!(s=(o=i.call(n)).done)&&(c.push(o.value),c.length!==t);s=!0);}catch(e){u=!0,r=e}finally{try{if(!s&&null!=n.return&&(a=n.return(),Object(a)!==a))return}finally{if(u)throw r}}return c}}(e,t)||function(e,t){if(e){if("string"==typeof e)return Cn(e,t);var n={}.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?Cn(e,t):void 0}}(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function Cn(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,o=Array(t);n<t;n++)o[n]=e[n];return o}const kn=function(e){var t=e.websocketUrl,n=e.agentId,o=e.appId,r=e.voice,i=void 0===r?"default":r,a=e.language,c=void 0===a?"en":a,s=e.autoReconnect,u=void 0===s||s,l=e.agentSettingsOverride,d=void 0===l?null:l,p=e.onConnected,f=e.onDisconnected,h=e.onRecordingStarted,v=e.onRecordingStopped,g=e.onPlaybackStarted,y=e.onPlaybackStopped,m=e.onError,b=e.onMessage,S=e.onBargeIn,w=e.onStopPlaying,x=e.onStartConversation,C=e.onEndConversation,k=e.className,P=void 0===k?"":k,O=e.style,E=void 0===O?{}:O,T=e.children,A=xn((0,fn.useState)(!1),2),I=A[0],j=A[1],D=xn((0,fn.useState)(!1),2),F=D[0],B=D[1],R=xn((0,fn.useState)(!1),2),_=(R[0],R[1]),U=xn((0,fn.useState)("Disconnected"),2),M=(U[0],U[1]),N=(0,fn.useRef)(null);(0,fn.useEffect)(function(){console.log("🎙️ VoiceButton: Creating VoiceSDK instance for ".concat(t)),N.current&&(console.log("🎙️ VoiceButton: Destroying existing VoiceSDK instance"),N.current.destroy(),N.current=null);var e=new he({websocketUrl:t,agentId:n,appId:o,voice:i,language:c,autoReconnect:u,agentSettingsOverride:d,onStartConversation:x,onEndConversation:C});return e.on("connected",function(){j(!0),M("Connected"),null==p||p()}),e.on("disconnected",function(){j(!1),M("Disconnected"),null==f||f()}),e.on("recordingStarted",function(){B(!0),null==h||h()}),e.on("recordingStopped",function(){B(!1),null==v||v()}),e.on("playbackStarted",function(){_(!0),null==g||g()}),e.on("playbackStopped",function(){_(!1),null==y||y()}),e.on("error",function(e){null==m||m(e)}),e.on("message",function(e){null==b||b(e)}),e.on("bargeIn",function(e){null==S||S(e)}),e.on("stopPlaying",function(e){null==w||w(e)}),N.current=e,e.connect(),function(){console.log("🎙️ VoiceButton: Cleaning up VoiceSDK instance for ".concat(t)),N.current&&(N.current.destroy(),N.current=null)}},[t,n,o,i,c,d]);var V=function(){var e,t=(e=bn().m(function e(){var t;return bn().w(function(e){for(;;)switch(e.p=e.n){case 0:if(N.current){e.n=1;break}return e.a(2);case 1:return e.p=1,e.n=2,N.current.toggleRecording();case 2:e.n=4;break;case 3:e.p=3,t=e.v,console.error("Error toggling recording:",t);case 4:return e.a(2)}},e,null,[[1,3]])}),function(){var t=this,n=arguments;return new Promise(function(o,r){var i=e.apply(t,n);function a(e){wn(i,o,r,a,c,"next",e)}function c(e){wn(i,o,r,a,c,"throw",e)}a(void 0)})});return function(){return t.apply(this,arguments)}}(),L=(0,hn.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[(0,hn.jsx)("div",{style:{fontSize:"20px"},children:F?"🔴":"🎤"}),(0,hn.jsx)("div",{children:F?"Stop Listening":"Start Listening"})]});return(0,hn.jsx)("button",{className:"voice-button ".concat(F?"recording":""," ").concat(P),style:yn({padding:"12px 24px",border:"none",borderRadius:"8px",backgroundColor:F?"#dc3545":"#007bff",color:"white",cursor:"pointer",fontSize:"16px",fontWeight:"500",transition:"all 0.2s ease"},E),onClick:V,disabled:!I,children:T||L})};function Pn(e){return Pn="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},Pn(e)}function On(){var e,t,n="function"==typeof Symbol?Symbol:{},o=n.iterator||"@@iterator",r=n.toStringTag||"@@toStringTag";function i(n,o,r,i){var s=o&&o.prototype instanceof c?o:c,u=Object.create(s.prototype);return En(u,"_invoke",function(n,o,r){var i,c,s,u=0,l=r||[],d=!1,p={p:0,n:0,v:e,a:f,f:f.bind(e,4),d:function(t,n){return i=t,c=0,s=e,p.n=n,a}};function f(n,o){for(c=n,s=o,t=0;!d&&u&&!r&&t<l.length;t++){var r,i=l[t],f=p.p,h=i[2];n>3?(r=h===o)&&(s=i[(c=i[4])?5:(c=3,3)],i[4]=i[5]=e):i[0]<=f&&((r=n<2&&f<i[1])?(c=0,p.v=o,p.n=i[1]):f<h&&(r=n<3||i[0]>o||o>h)&&(i[4]=n,i[5]=o,p.n=h,c=0))}if(r||n>1)return a;throw d=!0,o}return function(r,l,h){if(u>1)throw TypeError("Generator is already running");for(d&&1===l&&f(l,h),c=l,s=h;(t=c<2?e:s)||!d;){i||(c?c<3?(c>1&&(p.n=-1),f(c,s)):p.n=s:p.v=s);try{if(u=2,i){if(c||(r="next"),t=i[r]){if(!(t=t.call(i,s)))throw TypeError("iterator result is not an object");if(!t.done)return t;s=t.value,c<2&&(c=0)}else 1===c&&(t=i.return)&&t.call(i),c<2&&(s=TypeError("The iterator does not provide a '"+r+"' method"),c=1);i=e}else if((t=(d=p.n<0)?s:n.call(o,p))!==a)break}catch(t){i=e,c=1,s=t}finally{u=1}}return{value:t,done:d}}}(n,r,i),!0),u}var a={};function c(){}function s(){}function u(){}t=Object.getPrototypeOf;var l=[][o]?t(t([][o]())):(En(t={},o,function(){return this}),t),d=u.prototype=c.prototype=Object.create(l);function p(e){return Object.setPrototypeOf?Object.setPrototypeOf(e,u):(e.__proto__=u,En(e,r,"GeneratorFunction")),e.prototype=Object.create(d),e}return s.prototype=u,En(d,"constructor",u),En(u,"constructor",s),s.displayName="GeneratorFunction",En(u,r,"GeneratorFunction"),En(d),En(d,r,"Generator"),En(d,o,function(){return this}),En(d,"toString",function(){return"[object Generator]"}),(On=function(){return{w:i,m:p}})()}function En(e,t,n,o){var r=Object.defineProperty;try{r({},"",{})}catch(e){r=0}En=function(e,t,n,o){function i(t,n){En(e,t,function(e){return this._invoke(t,n,e)})}t?r?r(e,t,{value:n,enumerable:!o,configurable:!o,writable:!o}):e[t]=n:(i("next",0),i("throw",1),i("return",2))},En(e,t,n,o)}function Tn(e,t,n,o,r,i,a){try{var c=e[i](a),s=c.value}catch(e){return void n(e)}c.done?t(s):Promise.resolve(s).then(o,r)}function An(e){return function(){var t=this,n=arguments;return new Promise(function(o,r){var i=e.apply(t,n);function a(e){Tn(i,o,r,a,c,"next",e)}function c(e){Tn(i,o,r,a,c,"throw",e)}a(void 0)})}}function In(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(e);t&&(o=o.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,o)}return n}function jn(e,t,n){return(t=Fn(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function Dn(e,t){for(var n=0;n<t.length;n++){var o=t[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(e,Fn(o.key),o)}}function Fn(e){var t=function(e){if("object"!=Pn(e)||!e)return e;var t=e[Symbol.toPrimitive];if(void 0!==t){var n=t.call(e,"string");if("object"!=Pn(n))return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}(e);return"symbol"==Pn(t)?t:t+""}var Bn=function(){return e=function e(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),this.options=function(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?In(Object(n),!0).forEach(function(t){jn(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):In(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}({websocketUrl:t.websocketUrl||"wss://speech.talktopc.com/ws/conv",agentId:t.agentId,voice:t.voice||"default",language:t.language||"en",container:t.container||document.body,buttonText:t.buttonText||"Start Listening",buttonClass:t.buttonClass||"voice-button"},t),this.isConnected=!1,this.isRecording=!1,this.isPlaying=!1,this.voiceSDK=new he({websocketUrl:this.options.websocketUrl,agentId:this.options.agentId,voice:this.options.voice,language:this.options.language}),this.setupEventListeners(),this.createButton(),this.connect()},t=[{key:"setupEventListeners",value:function(){var e=this;this.voiceSDK.on("connected",function(){var t,n;e.isConnected=!0,e.updateButton(),null===(t=(n=e.options).onConnected)||void 0===t||t.call(n)}),this.voiceSDK.on("disconnected",function(){var t,n;e.isConnected=!1,e.updateButton(),null===(t=(n=e.options).onDisconnected)||void 0===t||t.call(n)}),this.voiceSDK.on("recordingStarted",function(){var t,n;e.isRecording=!0,e.updateButton(),null===(t=(n=e.options).onRecordingStarted)||void 0===t||t.call(n)}),this.voiceSDK.on("recordingStopped",function(){var t,n;e.isRecording=!1,e.updateButton(),null===(t=(n=e.options).onRecordingStopped)||void 0===t||t.call(n)}),this.voiceSDK.on("playbackStarted",function(){var t,n;e.isPlaying=!0,null===(t=(n=e.options).onPlaybackStarted)||void 0===t||t.call(n)}),this.voiceSDK.on("playbackStopped",function(){var t,n;e.isPlaying=!1,null===(t=(n=e.options).onPlaybackStopped)||void 0===t||t.call(n)}),this.voiceSDK.on("error",function(t){var n,o;null===(n=(o=e.options).onError)||void 0===n||n.call(o,t)}),this.voiceSDK.on("message",function(t){var n,o;null===(n=(o=e.options).onMessage)||void 0===n||n.call(o,t)}),this.voiceSDK.on("bargeIn",function(t){var n,o;null===(n=(o=e.options).onBargeIn)||void 0===n||n.call(o,t)}),this.voiceSDK.on("stopPlaying",function(t){var n,o;null===(n=(o=e.options).onStopPlaying)||void 0===n||n.call(o,t)})}},{key:"createButton",value:function(){var e=this;this.button=document.createElement("button"),this.button.className=this.options.buttonClass,this.button.style.cssText="\n padding: 12px 24px;\n border: none;\n border-radius: 8px;\n background-color: #6c757d;\n color: white;\n cursor: pointer;\n font-size: 16px;\n font-weight: 500;\n transition: all 0.2s ease;\n display: flex;\n align-items: center;\n gap: 8px;\n ",this.button.addEventListener("click",function(){return e.toggleRecording()}),this.options.container.appendChild(this.button),this.updateButton()}},{key:"updateButton",value:function(){if(this.button){var e=this.isRecording?"🔴":"🎤",t=this.isRecording?"Stop Listening":"Start Listening";this.button.innerHTML='\n <span style="font-size: 20px;">'.concat(e,"</span>\n <span>").concat(t,"</span>\n "),this.button.disabled=!this.isConnected,this.button.style.backgroundColor=this.isRecording?"#dc3545":this.isConnected?"#007bff":"#6c757d"}}},{key:"connect",value:(o=An(On().m(function e(){var t;return On().w(function(e){for(;;)switch(e.p=e.n){case 0:return e.p=0,e.n=1,this.voiceSDK.connect();case 1:e.n=3;break;case 2:e.p=2,t=e.v,console.error("Failed to connect:",t);case 3:return e.a(2)}},e,this,[[0,2]])})),function(){return o.apply(this,arguments)})},{key:"toggleRecording",value:(n=An(On().m(function e(){var t;return On().w(function(e){for(;;)switch(e.p=e.n){case 0:if(this.voiceSDK){e.n=1;break}return e.a(2);case 1:return e.p=1,e.n=2,this.voiceSDK.toggleRecording();case 2:e.n=4;break;case 3:e.p=3,t=e.v,console.error("Error toggling recording:",t);case 4:return e.a(2)}},e,this,[[1,3]])})),function(){return n.apply(this,arguments)})},{key:"getStatus",value:function(){return{isConnected:this.isConnected,isRecording:this.isRecording,isPlaying:this.isPlaying}}},{key:"updateConfig",value:function(e){this.voiceSDK.updateConfig(e)}},{key:"destroy",value:function(){this.button&&this.button.parentNode&&this.button.parentNode.removeChild(this.button),this.voiceSDK&&this.voiceSDK.destroy()}}],t&&Dn(e.prototype,t),Object.defineProperty(e,"prototype",{writable:!1}),e;var e,t,n,o}();function Rn(){var e,t,n="function"==typeof Symbol?Symbol:{},o=n.iterator||"@@iterator",r=n.toStringTag||"@@toStringTag";function i(n,o,r,i){var s=o&&o.prototype instanceof c?o:c,u=Object.create(s.prototype);return _n(u,"_invoke",function(n,o,r){var i,c,s,u=0,l=r||[],d=!1,p={p:0,n:0,v:e,a:f,f:f.bind(e,4),d:function(t,n){return i=t,c=0,s=e,p.n=n,a}};function f(n,o){for(c=n,s=o,t=0;!d&&u&&!r&&t<l.length;t++){var r,i=l[t],f=p.p,h=i[2];n>3?(r=h===o)&&(s=i[(c=i[4])?5:(c=3,3)],i[4]=i[5]=e):i[0]<=f&&((r=n<2&&f<i[1])?(c=0,p.v=o,p.n=i[1]):f<h&&(r=n<3||i[0]>o||o>h)&&(i[4]=n,i[5]=o,p.n=h,c=0))}if(r||n>1)return a;throw d=!0,o}return function(r,l,h){if(u>1)throw TypeError("Generator is already running");for(d&&1===l&&f(l,h),c=l,s=h;(t=c<2?e:s)||!d;){i||(c?c<3?(c>1&&(p.n=-1),f(c,s)):p.n=s:p.v=s);try{if(u=2,i){if(c||(r="next"),t=i[r]){if(!(t=t.call(i,s)))throw TypeError("iterator result is not an object");if(!t.done)return t;s=t.value,c<2&&(c=0)}else 1===c&&(t=i.return)&&t.call(i),c<2&&(s=TypeError("The iterator does not provide a '"+r+"' method"),c=1);i=e}else if((t=(d=p.n<0)?s:n.call(o,p))!==a)break}catch(t){i=e,c=1,s=t}finally{u=1}}return{value:t,done:d}}}(n,r,i),!0),u}var a={};function c(){}function s(){}function u(){}t=Object.getPrototypeOf;var l=[][o]?t(t([][o]())):(_n(t={},o,function(){return this}),t),d=u.prototype=c.prototype=Object.create(l);function p(e){return Object.setPrototypeOf?Object.setPrototypeOf(e,u):(e.__proto__=u,_n(e,r,"GeneratorFunction")),e.prototype=Object.create(d),e}return s.prototype=u,_n(d,"constructor",u),_n(u,"constructor",s),s.displayName="GeneratorFunction",_n(u,r,"GeneratorFunction"),_n(d),_n(d,r,"Generator"),_n(d,o,function(){return this}),_n(d,"toString",function(){return"[object Generator]"}),(Rn=function(){return{w:i,m:p}})()}function _n(e,t,n,o){var r=Object.defineProperty;try{r({},"",{})}catch(e){r=0}_n=function(e,t,n,o){function i(t,n){_n(e,t,function(e){return this._invoke(t,n,e)})}t?r?r(e,t,{value:n,enumerable:!o,configurable:!o,writable:!o}):e[t]=n:(i("next",0),i("throw",1),i("return",2))},_n(e,t,n,o)}function Un(e){return Un="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},Un(e)}function Mn(e,t,n,o,r,i,a){try{var c=e[i](a),s=c.value}catch(e){return void n(e)}c.done?t(s):Promise.resolve(s).then(o,r)}function Nn(e){return function(){var t=this,n=arguments;return new Promise(function(o,r){var i=e.apply(t,n);function a(e){Mn(i,o,r,a,c,"next",e)}function c(e){Mn(i,o,r,a,c,"throw",e)}a(void 0)})}}function Vn(e,t){for(var n=0;n<t.length;n++){var o=t[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(e,Ln(o.key),o)}}function Ln(e){var t=function(e){if("object"!=Un(e)||!e)return e;var t=e[Symbol.toPrimitive];if(void 0!==t){var n=t.call(e,"string");if("object"!=Un(n))return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}(e);return"symbol"==Un(t)?t:t+""}var Kn=function(){return e=function e(t){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),console.log("🚀 AgentSDK v2.1.8 initialized with config:",t),this.config=t,this.voiceSDK=null,this.isConnected=!1,this.isListening=!1,this.wasListening=!1,this.onConnected=function(){},this.onDisconnected=function(){},this.onError=function(e){return console.error("SDK Error:",e)},this.onTranscript=function(e){},this.onAgentSpeaking=function(e){},this.onConversationStart=t.onConversationStart||function(){},this.onConversationEnd=t.onConversationEnd||function(){},this.onBargeIn=t.onBargeIn||function(){},this.onAudioStartPlaying=t.onAudioStartPlaying||function(){},this.onAudioStoppedPlaying=t.onAudioStoppedPlaying||function(){},this.onSubtitleDisplay=t.onSubtitleDisplay||function(){}},t=[{key:"connect",value:(o=Nn(Rn().m(function e(t){var n,o=this;return Rn().w(function(e){for(;;)switch(e.p=e.n){case 0:if(e.p=0,t){e.n=1;break}throw new Error("signedUrl is required");case 1:return this.voiceSDK&&(console.log("🔌 AgentSDK: Cleaning up existing connection"),this.voiceSDK.destroy(),this.voiceSDK=null),this.voiceSDK=new Xt({websocketUrl:t,autoReconnect:!1,agentId:this.config.agentId,appId:this.config.appId,language:this.config.language||"en",protocolVersion:2,outputContainer:this.config.outputContainer||"raw",outputEncoding:this.config.outputEncoding||"pcm",outputSampleRate:this.config.outputSampleRate||44100,outputChannels:this.config.outputChannels||1,outputBitDepth:this.config.outputBitDepth||16}),this.voiceSDK.on("connected",function(){o.isConnected=!0,o.onConnected()}),this.voiceSDK.on("disconnected",function(e){if(o.isConnected=!1,e&&1008===e.code&&e.reason&&(e.reason.includes("Domain not whitelisted")||e.reason.includes("domain")||e.reason.includes("whitelist"))){var t=new Error("DOMAIN_NOT_WHITELISTED");t.reason=e.reason,t.code=e.code,o.onError(t)}if((o.isListening||o.wasListening)&&(console.log("🎤 [AGENT SDK] disconnected event - calling onConversationEnd hook (isListening:",o.isListening,", wasListening:",o.wasListening,")"),o.onConversationEnd&&"function"==typeof o.onConversationEnd))try{o.onConversationEnd(),console.log("🎤 [AGENT SDK] ✅ onConversationEnd hook called from disconnected event"),o.wasListening=!1}catch(e){console.error("🎤 [AGENT SDK] ❌ Error calling onConversationEnd from disconnected:",e)}o.onDisconnected()}),this.voiceSDK.on("domainError",function(e){o.onError(e)}),this.voiceSDK.on("error",function(e){o.onError(e)}),this.voiceSDK.on("message",function(e){o.handleWebSocketMessage(e)}),this.voiceSDK.on("recordingStarted",function(){if(o.isListening=!0,o.wasListening=!0,o.onConversationStart&&"function"==typeof o.onConversationStart)try{o.onConversationStart()}catch(e){console.error("🎤 [AGENT SDK] ❌ Error calling onConversationStart:",e)}}),this.voiceSDK.on("recordingStopped",function(){console.log("🎤 [AGENT SDK] recordingStopped event received");var e=o.isListening;if(o.isListening=!1,e&&o.onConversationEnd&&"function"==typeof o.onConversationEnd)try{console.log("🎤 [AGENT SDK] ✅ Calling onConversationEnd hook from recordingStopped"),o.onConversationEnd(),console.log("🎤 [AGENT SDK] ✅ onConversationEnd hook called successfully"),o.wasListening=!1}catch(e){console.error("🎤 [AGENT SDK] ❌ Error calling onConversationEnd:",e)}}),this.voiceSDK.on("playbackStarted",function(){o.onAgentSpeaking(!0),o.onAudioStartPlaying()}),this.voiceSDK.on("playbackStopped",function(){o.onAgentSpeaking(!1),o.onAudioStoppedPlaying()}),this.voiceSDK.on("bargeIn",function(e){o.onBargeIn(e)}),this.voiceSDK.on("transcriptDisplay",function(e){console.log("📝 [AGENT SDK] transcriptDisplay event received:",e),e&&e.text&&(console.log("📝 [AGENT SDK] Calling onTranscript with text:",e.text),o.onTranscript&&"function"==typeof o.onTranscript?o.onTranscript(e.text):console.warn("📝 [AGENT SDK] ⚠️ onTranscript is not a function!",Un(o.onTranscript))),o.onSubtitleDisplay(e)}),e.n=2,this.voiceSDK.connect();case 2:e.n=4;break;case 3:throw e.p=3,n=e.v,this.onError(n),n;case 4:return e.a(2)}},e,this,[[0,3]])})),function(e){return o.apply(this,arguments)})},{key:"handleWebSocketMessage",value:function(e){switch(e.t||e.type){case"connected":case"hello_ack":console.log("Session started successfully");break;case"user_transcript":this.onTranscript(e.user_transcription||e.text||e.transcript);break;case"agent_response":case"barge_in":case"stop_playing":default:break;case"error":this.onError(new Error(e.message||e.error||"Unknown error"))}}},{key:"startListening",value:(n=Nn(Rn().m(function e(){var t;return Rn().w(function(e){for(;;)switch(e.p=e.n){case 0:if(console.log("🎤 AgentSDK: startListening() called"),!this.voiceSDK){e.n=5;break}return e.p=1,console.log("🎤 AgentSDK: Starting recording..."),e.n=2,this.voiceSDK.startRecording();case 2:console.log("✅ AgentSDK: Recording started successfully"),e.n=4;break;case 3:throw e.p=3,t=e.v,console.error("❌ AgentSDK: Failed to start recording:",t),t;case 4:e.n=6;break;case 5:throw console.error("❌ AgentSDK: No voiceSDK instance available"),new Error("No voiceSDK instance available");case 6:return e.a(2)}},e,this,[[1,3]])})),function(){return n.apply(this,arguments)})},{key:"stopListening",value:function(){this.voiceSDK&&this.voiceSDK.stopRecording()}},{key:"updateVariables",value:function(e){this.voiceSDK&&this.isConnected&&this.voiceSDK.sendMessage({t:"update_variables",variables:e})}},{key:"disconnect",value:function(){this.voiceSDK&&(this.voiceSDK.destroy(),this.voiceSDK=null),this.isConnected=!1,this.isListening=!1}}],t&&Vn(e.prototype,t),Object.defineProperty(e,"prototype",{writable:!1}),e;var e,t,n,o}();function zn(e){return zn="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},zn(e)}function Hn(){var e,t,n="function"==typeof Symbol?Symbol:{},o=n.iterator||"@@iterator",r=n.toStringTag||"@@toStringTag";function i(n,o,r,i){var s=o&&o.prototype instanceof c?o:c,u=Object.create(s.prototype);return Wn(u,"_invoke",function(n,o,r){var i,c,s,u=0,l=r||[],d=!1,p={p:0,n:0,v:e,a:f,f:f.bind(e,4),d:function(t,n){return i=t,c=0,s=e,p.n=n,a}};function f(n,o){for(c=n,s=o,t=0;!d&&u&&!r&&t<l.length;t++){var r,i=l[t],f=p.p,h=i[2];n>3?(r=h===o)&&(s=i[(c=i[4])?5:(c=3,3)],i[4]=i[5]=e):i[0]<=f&&((r=n<2&&f<i[1])?(c=0,p.v=o,p.n=i[1]):f<h&&(r=n<3||i[0]>o||o>h)&&(i[4]=n,i[5]=o,p.n=h,c=0))}if(r||n>1)return a;throw d=!0,o}return function(r,l,h){if(u>1)throw TypeError("Generator is already running");for(d&&1===l&&f(l,h),c=l,s=h;(t=c<2?e:s)||!d;){i||(c?c<3?(c>1&&(p.n=-1),f(c,s)):p.n=s:p.v=s);try{if(u=2,i){if(c||(r="next"),t=i[r]){if(!(t=t.call(i,s)))throw TypeError("iterator result is not an object");if(!t.done)return t;s=t.value,c<2&&(c=0)}else 1===c&&(t=i.return)&&t.call(i),c<2&&(s=TypeError("The iterator does not provide a '"+r+"' method"),c=1);i=e}else if((t=(d=p.n<0)?s:n.call(o,p))!==a)break}catch(t){i=e,c=1,s=t}finally{u=1}}return{value:t,done:d}}}(n,r,i),!0),u}var a={};function c(){}function s(){}function u(){}t=Object.getPrototypeOf;var l=[][o]?t(t([][o]())):(Wn(t={},o,function(){return this}),t),d=u.prototype=c.prototype=Object.create(l);function p(e){return Object.setPrototypeOf?Object.setPrototypeOf(e,u):(e.__proto__=u,Wn(e,r,"GeneratorFunction")),e.prototype=Object.create(d),e}return s.prototype=u,Wn(d,"constructor",u),Wn(u,"constructor",s),s.displayName="GeneratorFunction",Wn(u,r,"GeneratorFunction"),Wn(d),Wn(d,r,"Generator"),Wn(d,o,function(){return this}),Wn(d,"toString",function(){return"[object Generator]"}),(Hn=function(){return{w:i,m:p}})()}function Wn(e,t,n,o){var r=Object.defineProperty;try{r({},"",{})}catch(e){r=0}Wn=function(e,t,n,o){function i(t,n){Wn(e,t,function(e){return this._invoke(t,n,e)})}t?r?r(e,t,{value:n,enumerable:!o,configurable:!o,writable:!o}):e[t]=n:(i("next",0),i("throw",1),i("return",2))},Wn(e,t,n,o)}function Gn(e,t,n,o,r,i,a){try{var c=e[i](a),s=c.value}catch(e){return void n(e)}c.done?t(s):Promise.resolve(s).then(o,r)}function qn(e){return function(){var t=this,n=arguments;return new Promise(function(o,r){var i=e.apply(t,n);function a(e){Gn(i,o,r,a,c,"next",e)}function c(e){Gn(i,o,r,a,c,"throw",e)}a(void 0)})}}function Qn(e,t){for(var n=0;n<t.length;n++){var o=t[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(e,Jn(o.key),o)}}function Jn(e){var t=function(e){if("object"!=zn(e)||!e)return e;var t=e[Symbol.toPrimitive];if(void 0!==t){var n=t.call(e,"string");if("object"!=zn(n))return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}(e);return"symbol"==zn(t)?t:t+""}var Yn=function(){return e=function e(t){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),this.config=t,this.audioStream=null,this.callStartTime=null,this.callTimerInterval=null,this.sdk=null,this.isActive=!1,this.sdk=new Kn({agentId:t.agentId,appId:t.appId,getSessionUrl:t.getSessionUrl,websocketUrl:t.websocketUrl,variables:t.variables||{},language:t.language||"en",outputContainer:t.outputContainer,outputEncoding:t.outputEncoding,outputSampleRate:t.outputSampleRate,outputChannels:t.outputChannels,outputBitDepth:t.outputBitDepth,onConversationStart:t.onConversationStart,onConversationEnd:t.onConversationEnd,onBargeIn:t.onBargeIn,onAudioStartPlaying:t.onAudioStartPlaying,onAudioStoppedPlaying:t.onAudioStoppedPlaying,onSubtitleDisplay:t.onSubtitleDisplay}),this.setupSDKEventHandlers()},t=[{key:"setupSDKEventHandlers",value:function(){var e=this;this.sdk.onTranscript=function(t){console.log("📝 [VOICE INTERFACE] onTranscript called with text:",t),e.updateTranscript(t)},this.sdk.onAgentSpeaking=function(e){var t=document.getElementById("voiceAvatarActive");t&&(e?t.classList.add("speaking"):t.classList.remove("speaking"))},this.sdk.onDisconnected=function(){console.log("🔌 WebSocket disconnected, hanging up call..."),e.isActive&&(e.isActive=!1,e.endVoiceCall())},this.sdk.onError=function(t){console.error("❌ Voice SDK Error:",t),t&&("DOMAIN_NOT_WHITELISTED"===t.message||t.message&&t.message.includes("Domain not whitelisted"))?e.showDomainError():e.showError(t.message||t)}}},{key:"t",value:function(e){var t,n,o=this.config.language||"en";return((null===(t=this.config.translations)||void 0===t?void 0:t[o])||(null===(n=this.config.translations)||void 0===n?void 0:n.en)||{})[e]||e}},{key:"getTooltip",value:function(e){var t,n=null===(t=this.config.tooltips)||void 0===t?void 0:t[e];return null!=n?n:{mute:this.t("mute"),speaker:this.t("speaker"),endCall:this.t("endCall")}[e]||""}},{key:"generateHTML",value:function(){return'<div class="voice-interface" id="voiceInterface">\n \x3c!-- Before Call State --\x3e\n <div id="voiceIdleState">\n <div class="voice-avatar" id="voiceAvatar">🤖</div>\n <div class="voice-status">\n <div class="voice-status-title">'.concat(this.t("clickToStartCall"),'</div>\n <div class="voice-status-subtitle">').concat(this.t("realTimeVoice"),'</div>\n </div>\n <button class="start-call-btn" id="startCallBtn">\n <svg width="32" height="32" viewBox="0 0 24 24" fill="currentColor">\n <path d="M20.01 15.38c-1.23 0-2.42-.2-3.53-.56-.35-.12-.74-.03-1.01.24l-1.57 1.97c-2.83-1.35-5.48-3.9-6.89-6.83l1.95-1.66c.27-.28.35-.67.24-1.02-.37-1.11-.56-2.3-.56-3.53 0-.54-.45-.99-.99-.99H4.19C3.65 3 3 3.24 3 3.99 3 13.28 10.73 21 20.01 21c.71 0 .99-.63.99-1.18v-3.45c0-.54-.45-.99-.99-.99z"/>\n </svg>\n <span>').concat(this.t("startCall"),'</span>\n </button>\n </div>\n \x3c!-- During Call State --\x3e\n <div id="voiceActiveState" style="display: none;">\n <div class="voice-avatar-active" id="voiceAvatarActive">\n <div class="voice-rings">\n <div class="voice-ring"></div>\n <div class="voice-ring"></div>\n <div class="voice-ring"></div>\n </div>\n 🤖\n </div>\n <div class="voice-status">\n <div class="voice-status-title" id="voiceStatusTitleActive">').concat(this.t("listening"),'</div>\n <div class="voice-status-subtitle" id="voiceStatusSubtitleActive">').concat(this.t("speakFreely"),'</div>\n </div>\n <div class="voice-transcript">\n <div class="transcript-label">').concat(this.t("liveTranscript"),'</div>\n <div class="transcript-text empty" id="transcriptText">\n ').concat(this.t("transcriptWillAppear"),'\n </div>\n </div>\n <div class="voice-controls">\n <button class="voice-control-btn secondary" id="muteBtn" title="').concat(this.getTooltip("mute"),'">\n <svg width="64" height="64" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round" class="mute-icon">\n <path d="M12 1a3 3 0 0 0-3 3v8a3 3 0 0 0 6 0V4a3 3 0 0 0-3-3z"/>\n <path d="M19 10v2a7 7 0 0 1-14 0v-2"/>\n <line x1="12" y1="19" x2="12" y2="23"/>\n <line x1="8" y1="23" x2="16" y2="23"/>\n <line x1="2" y1="2" x2="22" y2="22" class="mute-cross" style="display: none; stroke: #ef4444; stroke-width: 3.5;"/>\n </svg>\n </button>\n <button class="voice-control-btn primary active" id="endCallBtn" title="').concat(this.getTooltip("endCall"),'">\n <svg width="56" height="56" viewBox="0 0 24 24" fill="#ef4444">\n <rect x="6" y="6" width="12" height="12" rx="2"/>\n </svg>\n <div class="voice-timer" id="voiceTimer">00:00</div>\n </button>\n <button class="voice-control-btn secondary" id="speakerBtn" title="').concat(this.getTooltip("speaker"),'">\n <svg width="64" height="64" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round">\n <polygon points="11 5 6 9 2 9 2 15 6 15 11 19 11 5"/>\n <path d="M19.07 4.93a10 10 0 0 1 0 14.14"/>\n <path d="M15.54 8.46a5 5 0 0 1 0 7.07"/>\n </svg>\n </button>\n </div>\n </div>\n </div>')}},{key:"generateCSS",value:function(){var e=this.config.avatarBackgroundColor||"#667eea",t=this.config.avatarActiveBackgroundColor||this.config.avatarBackgroundColor||"#667eea",n=this.config.statusTitleColor||"#1e293b",o=this.config.statusSubtitleColor||"#64748b",r=this.config.startCallButtonColor||"#667eea",i=this.config.startCallButtonTextColor||"#FFFFFF",a=this.config.transcriptBackgroundColor||"#FFFFFF",c=this.config.transcriptTextColor||"#1e293b",s=this.config.transcriptLabelColor||"#94a3b8",u=this.config.controlButtonColor||"#FFFFFF",l=this.config.controlButtonSecondaryColor||"#64748b";return this.config.endCallButtonColor,'\n /* Voice Interface Styles - Ultra-compact for Wix iframes */\n .voice-interface { \n display: none; \n flex: 1; \n flex-direction: column;\n align-items: center; \n justify-content: center; \n padding: 6px 10px 6px 10px; \n background: linear-gradient(180deg, #f8fafc 0%, #e0e7ff 100%);\n overflow: hidden;\n min-height: 0;\n height: 100%;\n width: 100%;\n box-sizing: border-box;\n }\n .voice-interface.active { display: flex; }\n \n /* Voice States - Better scaling gaps */\n #voiceIdleState,\n #voiceActiveState {\n display: flex;\n flex-direction: column;\n align-items: center;\n width: 100%;\n height: 100%;\n min-height: 0;\n justify-content: center;\n overflow: hidden;\n flex: 1;\n box-sizing: border-box;\n gap: clamp(6px, 1.5vh, 12px);\n }\n \n #voiceActiveState[style*="display: none"] {\n display: none !important;\n }\n \n /* Voice Avatar - Scales better from small to large */\n .voice-avatar,\n .voice-avatar-active {\n width: clamp(80px, 18vh, 160px);\n height: clamp(80px, 18vh, 160px);\n aspect-ratio: 1;\n border-radius: 50%;\n background: linear-gradient(135deg, '.concat(e," 0%, ").concat(t," 100%);\n display: flex;\n align-items: center;\n justify-content: center;\n font-size: clamp(40px, 9vh, 80px);\n margin: 0;\n box-shadow: 0 8px 30px rgba(102, 126, 234, 0.3);\n transition: all 0.3s ease;\n flex-shrink: 1;\n position: relative;\n }\n \n .voice-avatar-active {\n animation: avatarPulse 2s ease-in-out infinite;\n }\n \n @keyframes avatarPulse {\n 0%, 100% { \n transform: scale(1);\n }\n 50% { \n transform: scale(1.05);\n }\n }\n \n .voice-avatar-active.speaking {\n animation: avatarSpeak 0.5s ease-in-out infinite;\n }\n \n @keyframes avatarSpeak {\n 0%, 100% { transform: scale(1); }\n 50% { transform: scale(1.08); }\n }\n \n /* Voice Rings Animation */\n .voice-rings {\n position: absolute;\n width: 100%;\n height: 100%;\n border-radius: 50%;\n }\n \n .voice-ring {\n position: absolute;\n top: 50%;\n left: 50%;\n transform: translate(-50%, -50%);\n border: 2px solid rgba(102, 126, 234, 0.3);\n border-radius: 50%;\n opacity: 0;\n animation: ringExpand 2s ease-out infinite;\n }\n \n .voice-ring:nth-child(2) { animation-delay: 0.5s; }\n .voice-ring:nth-child(3) { animation-delay: 1s; }\n \n @keyframes ringExpand {\n 0% {\n width: 100%;\n height: 100%;\n opacity: 0.6;\n }\n 100% {\n width: 160%;\n height: 160%;\n opacity: 0;\n }\n }\n \n /* Voice Status - Scales with container */\n .voice-status {\n text-align: center;\n margin: 0;\n flex-shrink: 1;\n min-height: 0;\n }\n \n .voice-status-title {\n font-size: clamp(12px, 3vh, 20px);\n font-weight: 600;\n color: ").concat(n,";\n margin-bottom: clamp(2px, 0.5vh, 4px);\n line-height: 1.2;\n }\n \n .voice-status-subtitle {\n font-size: clamp(10px, 2vh, 14px);\n color: ").concat(o,";\n line-height: 1.2;\n }\n \n /* Start Call Button - Scales with container */\n .start-call-btn {\n margin: 0;\n width: min(280px, 70vw);\n height: clamp(48px, 8vh, 64px);\n border-radius: clamp(24px, 4vh, 32px);\n border: none;\n background: ").concat(r,";\n color: ").concat(i,";\n font-size: clamp(14px, 2.5vh, 18px);\n font-weight: 600;\n cursor: pointer;\n display: flex;\n align-items: center;\n justify-content: center;\n gap: clamp(8px, 1.5vh, 12px);\n box-shadow: 0 12px 30px rgba(102, 126, 234, 0.4);\n transition: all 0.3s ease;\n flex-shrink: 0;\n }\n \n .start-call-btn svg {\n width: clamp(22px, 4vh, 32px);\n height: clamp(22px, 4vh, 32px);\n }\n \n .start-call-btn:hover {\n transform: translateY(-2px);\n box-shadow: 0 12px 28px rgba(102, 126, 234, 0.5);\n }\n \n .start-call-btn:active {\n transform: translateY(-1px);\n }\n \n /* Voice Transcript - Scales with container */\n .voice-transcript {\n background: ").concat(a,";\n padding: clamp(6px, 1.5vh, 12px);\n border-radius: 10px;\n width: min(360px, calc(100% - 40px));\n margin: 0;\n min-height: clamp(100px, 18vh, 140px);\n max-height: clamp(120px, 22vh, 160px);\n box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);\n flex-shrink: 1;\n overflow-y: auto;\n overflow-x: hidden;\n display: flex;\n flex-direction: column;\n box-sizing: border-box;\n }\n \n .transcript-label {\n font-size: clamp(8px, 1.4vh, 11px);\n color: ").concat(s,";\n font-weight: 600;\n text-transform: uppercase;\n letter-spacing: 0.3px;\n margin-bottom: clamp(3px, 0.6vh, 6px);\n flex-shrink: 0;\n word-wrap: break-word;\n }\n \n .transcript-text {\n font-size: clamp(11px, 2vh, 15px);\n color: ").concat(c,";\n line-height: 1.4;\n flex: 1;\n overflow-y: auto;\n overflow-x: hidden;\n word-wrap: break-word;\n overflow-wrap: break-word;\n }\n \n .transcript-text.empty {\n color: #cbd5e1;\n font-style: italic;\n }\n \n /* Voice Controls - Scales with container */\n .voice-controls {\n display: flex;\n gap: clamp(8px, 1.8vh, 14px);\n align-items: center;\n justify-content: center;\n flex-shrink: 0;\n margin: 0;\n padding-top: clamp(5px, 1.2vh, 10px);\n }\n \n .voice-control-btn {\n width: clamp(48px, 9vh, 72px);\n height: clamp(48px, 9vh, 72px);\n aspect-ratio: 1;\n border-radius: 50%;\n border: none;\n cursor: pointer;\n display: flex;\n align-items: center;\n justify-content: center;\n transition: all 0.2s;\n position: relative;\n flex-shrink: 0;\n }\n \n .voice-control-btn svg {\n width: 48%;\n height: 48%;\n }\n \n .voice-control-btn.primary {\n width: clamp(54px, 10vh, 80px);\n height: clamp(54px, 10vh, 80px);\n background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);\n color: white;\n box-shadow: 0 6px 18px rgba(102, 126, 234, 0.4);\n }\n \n .voice-control-btn.primary:hover {\n transform: scale(1.05);\n }\n \n .voice-control-btn.primary.active {\n background: white;\n animation: recordingPulse 1.5s ease-in-out infinite;\n }\n \n @keyframes recordingPulse {\n 0%, 100% { \n box-shadow: 0 6px 16px rgba(239, 68, 68, 0.4);\n }\n 50% { \n box-shadow: 0 6px 24px rgba(239, 68, 68, 0.7);\n }\n }\n \n .voice-control-btn.secondary {\n background: ").concat(u,";\n color: ").concat(l,";\n box-shadow: 0 3px 10px rgba(0, 0, 0, 0.1);\n }\n \n .voice-control-btn.secondary:hover {\n background: #f8fafc;\n transform: scale(1.05);\n }\n \n .voice-control-btn.secondary.muted {\n background: #f3f4f6;\n }\n \n .voice-control-btn.secondary.muted .mute-icon {\n stroke: #9ca3af !important;\n }\n \n .voice-timer {\n position: absolute;\n bottom: clamp(-18px, -3vh, -24px);\n font-size: clamp(9px, 1.6vh, 12px);\n color: #64748b;\n font-weight: 500;\n white-space: nowrap;\n }\n \n /* Mobile optimization */\n @media (max-width: 768px) {\n .voice-interface {\n padding: 6px 10px;\n }\n }\n \n @media (max-width: 480px) {\n .voice-interface {\n padding: 5px 8px;\n }\n }\n ")}},{key:"setupEventHandlers",value:function(e){var t=this,n=document.getElementById("startCallBtn"),o=document.getElementById("endCallBtn"),r=document.getElementById("muteBtn"),i=document.getElementById("speakerBtn");n&&(n.onclick=function(){return t.startVoiceCall()}),o&&(o.onclick=function(){return t.endVoiceCall()}),r&&(r.onclick=function(){return t.toggleMute()}),i&&(i.onclick=function(){return t.toggleSpeaker()});var a=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0,n=document.getElementById("voiceInterface");n&&n.classList.contains("active")&&n.clientHeight>100?(console.log("✅ Interface is active and has proper dimensions, adjusting sizes (attempt",e+1,")"),t.adjustSizesForContainer(),0===e&&setTimeout(function(){return t.adjustSizesForContainer()},500)):e<15?(console.log("⏳ Interface not ready yet (height:",null==n?void 0:n.clientHeight,"), retrying... (attempt",e+1,")"),setTimeout(function(){return a(e+1)},250)):(console.warn("⚠️ Interface never became fully ready, adjusting sizes anyway"),t.adjustSizesForContainer())};setTimeout(function(){return a()},200),window.addEventListener("resize",function(){console.log("🔄 Window resized, re-adjusting sizes"),t.adjustSizesForContainer()})}},{key:"getSignedUrl",value:(o=qn(Hn().m(function e(){var t,n,o,r,i,a,c;return Hn().w(function(e){for(;;)switch(e.n){case 0:if(this.config.getSessionUrl){e.n=2;break}if(this.config.agentId){e.n=1;break}throw new Error("agentId is required");case 1:return t=this.config.websocketUrl||"wss://speech.talktopc.com/ws/conv",(n=new URLSearchParams).append("agentId",this.config.agentId),this.config.appId&&n.append("appId",this.config.appId),!1!==this.config.demo&&n.append("demo","true"),e.a(2,"".concat(t,"?").concat(n.toString()));case 2:if("string"!=typeof this.config.getSessionUrl){e.n=6;break}return o={agentId:this.config.agentId,variables:this.config.variables||{}},this.config.appId&&(o.appId=this.config.appId),e.n=3,fetch(this.config.getSessionUrl,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)});case 3:if((r=e.v).ok){e.n=4;break}throw new Error("Failed to get session URL: ".concat(r.statusText));case 4:return e.n=5,r.json();case 5:return i=e.v,e.a(2,i.signedUrl||i.wsUrl||i.url);case 6:if("function"!=typeof this.config.getSessionUrl){e.n=8;break}return a={agentId:this.config.agentId,variables:this.config.variables||{}},this.config.appId&&(a.appId=this.config.appId),e.n=7,this.config.getSessionUrl(a);case 7:return c=e.v,e.a(2,"string"==typeof c?c:c.signedUrl||c.wsUrl||c.url);case 8:throw new Error("getSessionUrl must be a string (backend URL), a function, or omitted (for direct connection with agentId/appId)");case 9:return e.a(2)}},e,this)})),function(){return o.apply(this,arguments)})},{key:"adjustSizesForContainer",value:function(){var e=document.getElementById("voiceInterface");if(e){var t=e.clientHeight,n=e.clientWidth;console.log("📏 Container size:",t,"x",n);var o,r,i,a,c,s,u,l,d,p=document.getElementById("voiceIdleState"),f=document.getElementById("voiceActiveState"),h=p&&"none"!==p.style.display,v=f&&"none"!==f.style.display;console.log("👁️ Visible state - Idle:",h,"Active:",v),t<=350?(d=5,o=70,r=35,i=11,a=9,c=32,s=100,u=42,l=48):t<=450?(d=7,o=110,r=55,i=15,a=11,c=38,s=110,u=52,l=58):t<=550?(d=8,o=140,r=70,i=16,a=12,c=42,s=120,u=56,l=64):t<=700?(d=10,o=130,r=65,i=18,a=13,c=46,s=130,u=60,l=70):(d=12,o=150,r=75,i=20,a=14,c=50,s=140,u=66,l=76),document.querySelectorAll("#voiceIdleState, #voiceActiveState").forEach(function(e){e.style.gap="".concat(d,"px")});var g=document.querySelectorAll(".voice-avatar, .voice-avatar-active");console.log("🤖 Found",g.length,"avatars, setting size to",o,"px"),g.forEach(function(e){e.style.width="".concat(o,"px"),e.style.height="".concat(o,"px"),e.style.fontSize="".concat(r,"px")}),document.querySelectorAll(".voice-status-title").forEach(function(e){return e.style.fontSize="".concat(i,"px")}),document.querySelectorAll(".voice-status-subtitle").forEach(function(e){return e.style.fontSize="".concat(a,"px")});var y=document.querySelector(".voice-transcript");y&&(y.style.minHeight="".concat(s,"px"),y.style.maxHeight="".concat(s,"px"),y.style.height="".concat(s,"px"),y.style.width="min(360px, ".concat(n-40,"px)"),y.style.boxSizing="border-box");var m=document.querySelector(".transcript-label");m&&(m.style.fontSize="".concat(Math.max(8,i-4),"px"));var b=document.querySelector(".transcript-text");b&&(b.style.fontSize="".concat(Math.max(10,i-2),"px")),document.querySelectorAll(".voice-control-btn.secondary").forEach(function(e){e.style.width="".concat(u,"px"),e.style.height="".concat(u,"px");var t=e.querySelector("svg");if(t){var n=.65*u;t.style.setProperty("width","".concat(n,"px"),"important"),t.style.setProperty("height","".concat(n,"px"),"important"),t.style.setProperty("min-width","".concat(n,"px"),"important"),t.style.setProperty("min-height","".concat(n,"px"),"important")}});var S=document.querySelector(".voice-control-btn.primary");if(S){S.style.width="".concat(l,"px"),S.style.height="".concat(l,"px");var w=S.querySelector("svg");if(w){var x=.7*l;w.style.setProperty("width","".concat(x,"px"),"important"),w.style.setProperty("height","".concat(x,"px"),"important"),w.style.setProperty("min-width","".concat(x,"px"),"important"),w.style.setProperty("min-height","".concat(x,"px"),"important")}}var C=document.querySelector(".start-call-btn");if(C){var k,P;t<=350?(k=48,P=14):t<=450?(k=52,P=15):t<=550?(k=58,P=17):t<=700?(k=62,P=18):(k=64,P=18),C.style.height="".concat(k,"px"),C.style.fontSize="".concat(P,"px");var O=C.querySelector("svg");if(O){var E=Math.max(22,.5*k);O.style.width="".concat(E,"px"),O.style.height="".concat(E,"px")}}console.log("✅ Sizes adjusted - Avatar:",o,"Status:",c,"Transcript:",s,"Buttons:",u)}else console.warn("⚠️ voiceInterface not found, skipping size adjustment")}},{key:"startVoiceCall",value:(n=qn(Hn().m(function e(){var t,n,o,r,i,a,c,s,u,l=this;return Hn().w(function(e){for(;;)switch(e.p=e.n){case 0:if(!this.isActive){e.n=1;break}return console.log("⚠️ Voice call already active"),e.a(2);case 1:return console.log("🎤 Starting voice call..."),e.p=2,t=document.getElementById("voiceIdleState"),n=document.getElementById("voiceActiveState"),o=document.getElementById("voiceInterface"),t&&(t.style.display="none"),n&&(n.style.display="flex"),setTimeout(function(){return l.adjustSizesForContainer()},50),o&&(o.scrollTop=0),e.n=3,this.getSignedUrl();case 3:return r=e.v,console.log("🔗 Got signed URL:",r),e.n=4,this.sdk.connect(r);case 4:i=e.v,console.log("✅ Connected to WebSocket, connected:",i),a=0;case 5:if(this.sdk.isConnected||!(a<50)){e.n=7;break}return e.n=6,new Promise(function(e){return setTimeout(e,100)});case 6:a++,e.n=5;break;case 7:if(!this.sdk.isConnected){e.n=9;break}return console.log("✅ WebSocket ready, starting listening..."),e.n=8,this.sdk.startListening();case 8:console.log("🎤 Started listening"),this.isActive=!0,this.callStartTime=Date.now(),this.callTimerInterval=setInterval(function(){var e=Date.now()-l.callStartTime,t=Math.floor(e/6e4),n=Math.floor(e%6e4/1e3),o=document.getElementById("voiceTimer");o&&(o.textContent="".concat(t.toString().padStart(2,"0"),":").concat(n.toString().padStart(2,"0")))},1e3),e.n=11;break;case 9:return console.warn("⚠️ Connection not fully ready, but trying to start listening anyway..."),e.n=10,this.sdk.startListening();case 10:console.log("🎤 Started listening"),this.isActive=!0,this.callStartTime=Date.now(),this.callTimerInterval=setInterval(function(){var e=Date.now()-l.callStartTime,t=Math.floor(e/6e4),n=Math.floor(e%6e4/1e3),o=document.getElementById("voiceTimer");o&&(o.textContent="".concat(t.toString().padStart(2,"0"),":").concat(n.toString().padStart(2,"0")))},1e3);case 11:console.log("✅ Voice call started successfully"),e.n=13;break;case 12:e.p=12,u=e.v,console.error("❌ Error starting voice call:",u),this.showError(u.message||u),c=document.getElementById("voiceIdleState"),s=document.getElementById("voiceActiveState"),c&&(c.style.display="flex"),s&&(s.style.display="none");case 13:return e.a(2)}},e,this,[[2,12]])})),function(){return n.apply(this,arguments)})},{key:"endVoiceCall",value:function(){var e=this;console.log("🔴 Ending voice call..."),this.sdk&&this.isActive&&(this.sdk.stopListening(),this.sdk.disconnect(),this.isActive=!1),this.audioStream&&(this.audioStream.getTracks().forEach(function(e){return e.stop()}),this.audioStream=null),this.callTimerInterval&&(clearInterval(this.callTimerInterval),this.callTimerInterval=null);var t=document.getElementById("voiceIdleState"),n=document.getElementById("voiceActiveState");t&&(t.style.display="flex"),n&&(n.style.display="none"),setTimeout(function(){return e.adjustSizesForContainer()},50);var o=document.getElementById("transcriptText");o&&(o.textContent=this.t("transcriptWillAppear"),o.classList.add("empty"));var r=document.getElementById("voiceAvatarActive");r&&r.classList.remove("speaking"),console.log("✅ Voice call ended")}},{key:"updateTranscript",value:function(e){console.log("📝 [VOICE INTERFACE] updateTranscript called with text:",e);var t=document.getElementById("transcriptText");t?(console.log("📝 [VOICE INTERFACE] Found transcript element, updating text"),t.textContent=e,t.classList.remove("empty")):console.warn("📝 [VOICE INTERFACE] ⚠️ transcriptText element not found!")}},{key:"showError",value:function(e){var t=document.getElementById("transcriptText");t&&(t.textContent="".concat(this.t("error"),": ").concat(e),t.classList.remove("empty"))}},{key:"showDomainError",value:function(){var e=document.getElementById("transcriptText");if(e){var t=this.t("domainNotValidated"),n=this.t("domainErrorMessage");e.innerHTML='<div style="font-weight: 600; font-size: 16px; margin-bottom: 8px; color: #991B1B;">'.concat(t,'</div><div style="font-size: 14px; color: #991B1B; line-height: 1.5;">').concat(n,"</div>"),e.classList.remove("empty")}}},{key:"toggleMute",value:function(){if(this.sdk&&this.isActive){var e=null;if(this.sdk.voiceSDK&&this.sdk.voiceSDK.audioRecorder&&this.sdk.voiceSDK.audioRecorder.mediaStream&&(e=this.sdk.voiceSDK.audioRecorder.mediaStream.getAudioTracks()[0]),!e&&this.audioStream&&(e=this.audioStream.getAudioTracks()[0]),e){e.enabled=!e.enabled;var t=document.getElementById("muteBtn"),n=null==t?void 0:t.querySelector(".mute-icon"),o=null==t?void 0:t.querySelector(".mute-cross");t&&n&&o&&(e.enabled?(n.style.stroke="",o.style.display="none",t.classList.remove("muted")):(n.style.stroke="#9ca3af",o.style.display="block",t.classList.add("muted"))),console.log(e.enabled?"🔊 Unmuted":"🔇 Muted")}else console.warn("⚠️ No audio track available for mute toggle")}}},{key:"toggleSpeaker",value:function(){console.log("🔊 Speaker toggle")}},{key:"destroy",value:function(){this.isActive&&this.endVoiceCall(),this.audioStream&&(this.audioStream.getTracks().forEach(function(e){return e.stop()}),this.audioStream=null),this.callTimerInterval&&(clearInterval(this.callTimerInterval),this.callTimerInterval=null),this.sdk&&(this.sdk.disconnect(),this.sdk=null)}}],t&&Qn(e.prototype,t),Object.defineProperty(e,"prototype",{writable:!1}),e;var e,t,n,o}();function $n(e){return $n="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},$n(e)}function Xn(){var e,t,n="function"==typeof Symbol?Symbol:{},o=n.iterator||"@@iterator",r=n.toStringTag||"@@toStringTag";function i(n,o,r,i){var s=o&&o.prototype instanceof c?o:c,u=Object.create(s.prototype);return Zn(u,"_invoke",function(n,o,r){var i,c,s,u=0,l=r||[],d=!1,p={p:0,n:0,v:e,a:f,f:f.bind(e,4),d:function(t,n){return i=t,c=0,s=e,p.n=n,a}};function f(n,o){for(c=n,s=o,t=0;!d&&u&&!r&&t<l.length;t++){var r,i=l[t],f=p.p,h=i[2];n>3?(r=h===o)&&(s=i[(c=i[4])?5:(c=3,3)],i[4]=i[5]=e):i[0]<=f&&((r=n<2&&f<i[1])?(c=0,p.v=o,p.n=i[1]):f<h&&(r=n<3||i[0]>o||o>h)&&(i[4]=n,i[5]=o,p.n=h,c=0))}if(r||n>1)return a;throw d=!0,o}return function(r,l,h){if(u>1)throw TypeError("Generator is already running");for(d&&1===l&&f(l,h),c=l,s=h;(t=c<2?e:s)||!d;){i||(c?c<3?(c>1&&(p.n=-1),f(c,s)):p.n=s:p.v=s);try{if(u=2,i){if(c||(r="next"),t=i[r]){if(!(t=t.call(i,s)))throw TypeError("iterator result is not an object");if(!t.done)return t;s=t.value,c<2&&(c=0)}else 1===c&&(t=i.return)&&t.call(i),c<2&&(s=TypeError("The iterator does not provide a '"+r+"' method"),c=1);i=e}else if((t=(d=p.n<0)?s:n.call(o,p))!==a)break}catch(t){i=e,c=1,s=t}finally{u=1}}return{value:t,done:d}}}(n,r,i),!0),u}var a={};function c(){}function s(){}function u(){}t=Object.getPrototypeOf;var l=[][o]?t(t([][o]())):(Zn(t={},o,function(){return this}),t),d=u.prototype=c.prototype=Object.create(l);function p(e){return Object.setPrototypeOf?Object.setPrototypeOf(e,u):(e.__proto__=u,Zn(e,r,"GeneratorFunction")),e.prototype=Object.create(d),e}return s.prototype=u,Zn(d,"constructor",u),Zn(u,"constructor",s),s.displayName="GeneratorFunction",Zn(u,r,"GeneratorFunction"),Zn(d),Zn(d,r,"Generator"),Zn(d,o,function(){return this}),Zn(d,"toString",function(){return"[object Generator]"}),(Xn=function(){return{w:i,m:p}})()}function Zn(e,t,n,o){var r=Object.defineProperty;try{r({},"",{})}catch(e){r=0}Zn=function(e,t,n,o){function i(t,n){Zn(e,t,function(e){return this._invoke(t,n,e)})}t?r?r(e,t,{value:n,enumerable:!o,configurable:!o,writable:!o}):e[t]=n:(i("next",0),i("throw",1),i("return",2))},Zn(e,t,n,o)}function eo(e,t,n,o,r,i,a){try{var c=e[i](a),s=c.value}catch(e){return void n(e)}c.done?t(s):Promise.resolve(s).then(o,r)}function to(e){return function(){var t=this,n=arguments;return new Promise(function(o,r){var i=e.apply(t,n);function a(e){eo(i,o,r,a,c,"next",e)}function c(e){eo(i,o,r,a,c,"throw",e)}a(void 0)})}}function no(e,t){for(var n=0;n<t.length;n++){var o=t[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(e,oo(o.key),o)}}function oo(e){var t=function(e){if("object"!=$n(e)||!e)return e;var t=e[Symbol.toPrimitive];if(void 0!==t){var n=t.call(e,"string");if("object"!=$n(n))return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}(e);return"symbol"==$n(t)?t:t+""}var ro=function(){return e=function e(t,n){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),this.config=t,this.sdk=n,this.streamingEl=null,this.hasStartedStreaming=!1,this.isActive=!1,this.eventHandlers={autoResize:null,keydown:null},this.eventHandlersSetup=!1},t=[{key:"t",value:function(e){var t,n,o=this.config.language||"en";return((null===(t=this.config.translations)||void 0===t?void 0:t[o])||(null===(n=this.config.translations)||void 0===n?void 0:n.en)||{})[e]||e}},{key:"generateHTML",value:function(){var e,t,n,o,r,i,a,c,s,u=this.config.inputPlaceholder||(null===(e=this.config.panel)||void 0===e?void 0:e.inputPlaceholder)||this.t("typeMessage")||"Type your message...";return'<div class="text-interface" id="textInterface">\n <div class="messages-container" id="messagesContainer">\n <div class="empty-state">\n <div class="empty-state-icon">💬</div>\n <div class="empty-state-title">'.concat(this.t("hello"),'</div>\n <div class="empty-state-text">').concat(this.t("sendMessage"),'</div>\n </div>\n </div>\n <div class="input-container">\n <div class="input-wrapper" style="flex:1;">\n <textarea class="message-input" id="messageInput" placeholder="').concat(u,'" rows="1" dir="').concat(this.config.direction||"ltr",'"></textarea>\n </div>\n <button class="send-button" id="sendButton" aria-label="').concat(this.t("sendMessageAria"),'">').concat(this.config.sendButtonText||"➤","</button>\n ").concat(null!==(t=this.config.sendButtonHint)&&void 0!==t&&t.text||null!==(n=this.config.panel)&&void 0!==n&&null!==(n=n.sendButtonHint)&&void 0!==n&&n.text?'\n <div class="send-button-hint" style="color: '.concat((null===(o=this.config.sendButtonHint)||void 0===o?void 0:o.color)||(null===(r=this.config.panel)||void 0===r||null===(r=r.sendButtonHint)||void 0===r?void 0:r.color)||"#6B7280","; font-size: ").concat((null===(i=this.config.sendButtonHint)||void 0===i?void 0:i.fontSize)||(null===(a=this.config.panel)||void 0===a||null===(a=a.sendButtonHint)||void 0===a?void 0:a.fontSize)||"12px",'; text-align: center; margin-top: 4px;">\n ').concat((null===(c=this.config.sendButtonHint)||void 0===c?void 0:c.text)||(null===(s=this.config.panel)||void 0===s||null===(s=s.sendButtonHint)||void 0===s?void 0:s.text),"\n </div>\n "):"","\n </div>\n </div>")}},{key:"generateCSS",value:function(){var e,t,n,o,r,i,a,c,s,u,l,d,p,f=this.config.messages,h=(this.config.panel,this.config.animation,this.config.sendButtonColor||(null===(e=this.config.panel)||void 0===e?void 0:e.sendButtonColor)||"#7C3AED"),v=this.config.sendButtonHoverColor||(null===(t=this.config.panel)||void 0===t?void 0:t.sendButtonHoverColor)||"#6D28D9",g=this.config.sendButtonTextColor||(null===(n=this.config.panel)||void 0===n?void 0:n.sendButtonTextColor)||"#FFFFFF",y=(this.config.inputPlaceholder||null===(o=this.config.panel)||void 0===o||o.inputPlaceholder,this.config.inputBorderColor||(null===(r=this.config.panel)||void 0===r?void 0:r.inputBorderColor)||"#E5E7EB"),m=this.config.inputFocusColor||(null===(i=this.config.panel)||void 0===i?void 0:i.inputFocusColor)||"#7C3AED",b=this.config.inputBackgroundColor||(null===(a=this.config.panel)||void 0===a?void 0:a.inputBackgroundColor)||"#FFFFFF",S=this.config.inputTextColor||(null===(c=this.config.panel)||void 0===c?void 0:c.inputTextColor)||"#1F2937",w=this.config.inputFontSize||(null===(s=this.config.panel)||void 0===s?void 0:s.inputFontSize)||"14px",x=this.config.inputBorderRadius||(null===(u=this.config.panel)||void 0===u?void 0:u.inputBorderRadius)||20,C=this.config.inputPadding||(null===(l=this.config.panel)||void 0===l?void 0:l.inputPadding)||"6px 14px";return"\n /* Messages container using new classes */\n #messagesContainer { \n flex: 1; \n overflow-y: auto; \n overflow-x: hidden; \n padding: 20px; \n background: #f8fafc; \n display: flex; \n flex-direction: column; \n gap: 16px; \n min-height: 0; \n }\n .empty-state { \n flex: 1; \n display: flex; \n flex-direction: column; \n align-items: center; \n justify-content: center; \n gap: 12px; \n color: #64748b; \n text-align: center; \n padding: 20px; \n }\n .empty-state-icon { font-size: 48px; opacity: 0.3; }\n .empty-state-title { font-size: 20px; font-weight: 700; color: #334155; }\n .empty-state-text { font-size: 13px; max-width: 280px; }\n\n .text-interface { \n display: none; \n flex: 1; \n flex-direction: column; \n min-height: 0; \n overflow: hidden; \n }\n .text-interface.active { display: flex; }\n \n .message { \n display: flex; \n gap: 8px; \n padding: 4px 0; \n max-width: 100%; \n align-items: center; \n }\n .message.edge-left { flex-direction: row; }\n .message.edge-right { flex-direction: row-reverse; }\n .message-bubble { \n padding: 12px; \n border-radius: ".concat(f.borderRadius,"px; \n max-width: 80%; \n font-size: ").concat(f.fontSize,"; \n color: ").concat(f.textColor,"; \n word-wrap: break-word; \n text-align: ").concat("rtl"===this.config.direction?"right":"left","; \n direction: ").concat(this.config.direction||"ltr",";\n }\n .message.user { \n background: ").concat(f.userBackgroundColor,"; \n align-self: ").concat("rtl"===this.config.direction?"flex-start":"flex-end","; \n }\n .message.agent { \n background: ").concat(f.agentBackgroundColor,"; \n align-self: ").concat("rtl"===this.config.direction?"flex-end":"flex-start","; \n }\n .message .message-bubble { \n text-align: ").concat("rtl"===this.config.direction?"right":"left"," !important; \n }\n ").concat("rtl"===this.config.direction?"\n .message-bubble {\n text-align: right !important;\n }\n ":"","\n .message-avatar { \n width: 20px; \n height: 20px; \n display: flex; \n align-items: center; \n justify-content: center; \n flex-shrink: 0; \n color: inherit; \n font-size: 18px; \n line-height: 1; \n background: transparent; \n border: none; \n }\n .message-avatar.user { background: transparent; }\n .message-avatar.agent { background: transparent; }\n \n .message.system {\n background: ").concat(f.systemBackgroundColor,";\n align-self: flex-start;\n }\n .message.error {\n background: ").concat(f.errorBackgroundColor,";\n align-self: flex-start;\n }\n \n .input-container {\n display: flex;\n gap: 8px;\n padding: 12px 16px;\n background: #FFFFFF;\n border-top: 1px solid #E5E7EB;\n align-items: center;\n flex-shrink: 0;\n flex-direction: ").concat("rtl"===this.config.direction?"row-reverse":"row",";\n }\n \n .input-wrapper {\n position: relative;\n display: flex;\n align-items: center;\n }\n \n .message-input {\n width: 100%;\n min-height: 32px;\n max-height: 120px;\n padding: ").concat(C,";\n border: 1px solid ").concat(y,";\n border-radius: ").concat(x,"px;\n font-size: ").concat(w,";\n font-family: inherit;\n line-height: 1.3;\n resize: none;\n overflow-y: auto;\n background: ").concat(b,";\n color: ").concat(S,";\n vertical-align: top;\n margin: 0;\n display: block;\n white-space: pre-wrap;\n word-wrap: break-word;\n text-align: ").concat("rtl"===this.config.direction?"right":"left",";\n direction: ").concat(this.config.direction||"ltr",";\n -webkit-appearance: none;\n appearance: none;\n box-sizing: border-box;\n }\n \n .message-input:focus {\n outline: none;\n border-color: ").concat(m,";\n background: ").concat("#FFFFFF"===b?"#FFFFFF":b,";\n box-shadow: 0 0 0 3px ").concat(m,"33;\n }\n \n .message-input::placeholder {\n color: #9CA3AF;\n text-align: ").concat("rtl"===this.config.direction?"right":"left",";\n }\n \n .send-button {\n width: 40px;\n height: 40px;\n border-radius: 50%;\n border: none;\n background: ").concat(h,";\n color: ").concat(g,";\n font-size: ").concat(this.config.sendButtonFontSize||(null===(d=this.config.panel)||void 0===d?void 0:d.sendButtonFontSize)||"18px",";\n font-weight: ").concat(this.config.sendButtonFontWeight||(null===(p=this.config.panel)||void 0===p?void 0:p.sendButtonFontWeight)||"500",";\n cursor: pointer;\n display: flex;\n align-items: center;\n justify-content: center;\n flex-shrink: 0;\n transition: all 0.2s ease;\n box-shadow: 0 4px 12px rgba(124, 60, 237, 0.3);\n }\n \n .send-button:hover:not(:disabled) {\n background: ").concat(v,";\n transform: scale(1.05);\n box-shadow: 0 6px 16px rgba(124, 60, 237, 0.4);\n }\n \n .send-button-hint {\n width: 100%;\n text-align: center;\n margin-top: 4px;\n }\n \n .send-button:disabled {\n opacity: 0.5;\n cursor: not-allowed;\n }\n \n .typing-indicator {\n display: inline-flex;\n gap: 4px;\n align-items: center;\n }\n \n .typing-dot {\n width: 6px;\n height: 6px;\n border-radius: 50%;\n background: #64748b;\n animation: typingDot 1.4s ease-in-out infinite;\n }\n \n .typing-dot:nth-child(2) { animation-delay: 0.2s; }\n .typing-dot:nth-child(3) { animation-delay: 0.4s; }\n \n @keyframes typingDot {\n 0%, 60%, 100% { transform: translateY(0); opacity: 0.7; }\n 30% { transform: translateY(-8px); opacity: 1; }\n }\n \n .error-message {\n padding: 12px;\n background: ").concat(f.errorBackgroundColor,";\n border-radius: ").concat(f.borderRadius,"px;\n color: #991B1B;\n font-size: ").concat(f.fontSize,";\n margin: 8px 0;\n }\n \n @media (max-width: 768px) {\n #messagesContainer {\n padding: 12px;\n gap: 12px;\n }\n \n .message-bubble {\n max-width: 85%;\n font-size: 14px;\n padding: 10px;\n }\n \n .text-input-container {\n padding: 10px;\n gap: 8px;\n }\n \n #text-chat-input {\n font-size: 16px !important; /* Prevents iOS zoom on focus */\n padding: 10px 14px;\n min-height: 44px;\n }\n \n #text-chat-send {\n min-width: 56px;\n min-height: 44px;\n width: 56px;\n height: 44px;\n }\n \n .empty-state-icon {\n font-size: 40px;\n }\n \n .empty-state-title {\n font-size: 18px;\n }\n \n .empty-state-text {\n font-size: 12px;\n }\n }\n \n @media (max-width: 480px) {\n #messagesContainer {\n padding: 10px;\n gap: 10px;\n }\n \n .message-bubble {\n max-width: 90%;\n font-size: 13px;\n padding: 8px;\n }\n \n .text-input-container {\n padding: 8px;\n }\n \n #text-chat-input {\n font-size: 16px !important;\n padding: 8px 12px;\n }\n }\n ")}},{key:"setupEventHandlers",value:function(){var e=this,t=document.getElementById("sendButton"),n=document.getElementById("messageInput"),o=document.getElementById("newChatBtn");if(t&&(t.onclick=function(){return e.sendMessage()}),o&&(o.onclick=function(){return e.startNewChat()}),this.updateInputAttributes(),n){n.style.height="32px",n.style.overflow="hidden";var r=function(){n.style.height="auto";var e=Math.min(n.scrollHeight,120);n.style.height=e+"px",n.style.overflowY=e>=120?"auto":"hidden",e>=120&&setTimeout(function(){n.scrollTop=n.scrollHeight},0)};n.addEventListener("input",r),n.addEventListener("keydown",function(t){"Enter"!==t.key||t.shiftKey?"Enter"===t.key&&t.shiftKey&&setTimeout(r,0):(t.preventDefault(),e.sendMessage())})}}},{key:"startNewChat",value:function(){try{localStorage.removeItem("ttp_text_chat_conversation_id")}catch(e){}this.sdk&&(this.sdk.config.conversationId=null);var e=document.getElementById("messagesContainer");e&&(e.innerHTML='\n <div class="empty-state">\n <div class="empty-state-icon">💬</div>\n <div class="empty-state-title">'.concat(this.t("hello"),'</div>\n <div class="empty-state-text">').concat(this.t("sendMessage"),"</div>\n </div>"));var t=document.getElementById("messageInput");t&&t.focus()}},{key:"updateInputAttributes",value:function(){var e=document.getElementById("messageInput");if(e){var t,n=this.config.inputPlaceholder||(null===(t=this.config.panel)||void 0===t?void 0:t.inputPlaceholder)||this.t("typeMessage")||"Type your message...";e.placeholder=n,e.dir=this.config.direction||"ltr",e.style.textAlign="rtl"===this.config.direction?"right":"left"}}},{key:"show",value:function(){var e=document.getElementById("textInterface");e&&e.classList.add("active"),setTimeout(function(){var e=document.getElementById("messageInput");e&&e.focus()},50)}},{key:"hide",value:function(){var e=document.getElementById("textInterface");e&&e.classList.remove("active")}},{key:"startChat",value:(o=to(Xn().m(function e(){return Xn().w(function(e){for(;;)switch(e.n){case 0:this.isActive=!0,this.updateSendButtonState();case 1:return e.a(2)}},e,this)})),function(){return o.apply(this,arguments)})},{key:"sendMessage",value:(n=to(Xn().m(function e(){var t,n,o;return Xn().w(function(e){for(;;)switch(e.p=e.n){case 0:if(t=document.getElementById("messageInput"),n=t.value.trim()){e.n=1;break}return e.a(2);case 1:if(this.isActive){e.n=2;break}return e.n=2,this.startChat();case 2:return this.addMessage("user",n),t.value="",t.style.height="32px",t.style.overflow="hidden",e.p=3,this.beginStreaming(),e.n=4,this.sdk.sendMessage(n);case 4:e.n=6;break;case 5:e.p=5,o=e.v,console.error("❌ Failed to send message:",o),o&&("DOMAIN_NOT_WHITELISTED"===o.message||o.message&&o.message.includes("Domain not whitelisted"))||this.showError(o),this.stopStreamingState();case 6:return e.a(2)}},e,this,[[3,5]])})),function(){return n.apply(this,arguments)})},{key:"updateSendButtonState",value:function(){var e=document.getElementById("sendButton");e&&(e.disabled=!this.isActive)}},{key:"addMessage",value:function(e,t){var n=document.getElementById("messagesContainer");if(n){var o=n.querySelector(".empty-state");o&&o.remove();var r=document.createElement("div"),i="rtl"===this.config.direction?"user"===e?"edge-left":"edge-right":"user"===e?"edge-right":"edge-left";r.className="message ".concat(e," ").concat(i);var a=document.createElement("div");a.className="message-avatar ".concat(e),a.textContent="user"===e?"👤":"🤖";var c=document.createElement("div");c.className="message-bubble",c.textContent=t,r.appendChild(a),r.appendChild(c),n.appendChild(r),n.scrollTop=n.scrollHeight}}},{key:"beginStreaming",value:function(){var e=document.getElementById("messagesContainer");if(e){this.stopStreamingState();var t=document.createElement("div"),n="rtl"===this.config.direction?"edge-right":"edge-left";t.className="message agent ".concat(n),t.id="agent-streaming";var o=document.createElement("div");o.className="message-avatar agent",o.textContent="🤖";var r=document.createElement("div");r.className="message-bubble",r.innerHTML='<span class="typing-indicator"><span class="typing-dot"></span><span class="typing-dot"></span><span class="typing-dot"></span></span>',t.appendChild(o),t.appendChild(r),e.appendChild(t),this.streamingEl=r,this.hasStartedStreaming=!1,e.scrollTop=e.scrollHeight}}},{key:"appendStreamingChunk",value:function(e){if(this.streamingEl){this.hasStartedStreaming||(this.streamingEl.textContent="",this.hasStartedStreaming=!0),this.streamingEl.textContent+=e;var t=document.getElementById("messagesContainer");t&&(t.scrollTop=t.scrollHeight)}}},{key:"finalizeStreaming",value:function(e){if(this.streamingEl){this.streamingEl.textContent=e||this.streamingEl.textContent;var t=document.getElementById("agent-streaming");t&&(t.id=""),this.streamingEl=null}this.updateSendButtonState()}},{key:"stopStreamingState",value:function(){var e=document.getElementById("agent-streaming");e&&e.remove(),this.streamingEl=null,this.hasStartedStreaming=!1}},{key:"showError",value:function(e){var t=document.getElementById("messagesContainer");if(t){if(e&&("DOMAIN_NOT_WHITELISTED"===e.message||"string"==typeof e&&e.includes("DOMAIN_NOT_WHITELISTED")||e.message&&e.message.includes("Domain not whitelisted")||"string"==typeof e&&e.includes("Domain not whitelisted"))){var n,o=document.createElement("div");o.className="error-message",o.style.cssText="padding: 16px; margin: 12px; border-radius: 8px; background: "+((null===(n=this.config.messages)||void 0===n?void 0:n.errorBackgroundColor)||"#FEE2E2")+";";var r=document.createElement("div");r.style.cssText="font-weight: 600; font-size: 16px; margin-bottom: 8px; color: #991B1B;",r.textContent=this.t("domainNotValidated");var i=document.createElement("div");i.style.cssText="font-size: 14px; color: #991B1B; line-height: 1.5;",i.textContent=this.t("domainErrorMessage"),o.appendChild(r),o.appendChild(i),t.appendChild(o)}else{var a=document.createElement("div");a.className="error-message",a.textContent="string"==typeof e?e:(null==e?void 0:e.message)||e,t.appendChild(a)}t.scrollTop=t.scrollHeight}}},{key:"setActive",value:function(e){this.isActive=e,this.updateSendButtonState()}}],t&&no(e.prototype,t),Object.defineProperty(e,"prototype",{writable:!1}),e;var e,t,n,o}();const io={en:{landingTitle:"How would you like to communicate?",voiceCall:"Voice Call",textChat:"Text Chat",clickToStartCall:"Click to Start Call",realTimeVoice:"Real-time voice conversation",startCall:"Start Call",listening:"Listening...",speakFreely:"Speak freely",liveTranscript:"Live Transcript",transcriptWillAppear:"Transcript will appear here during the call...",mute:"Mute",speaker:"Speaker",endCall:"End Call",hello:"Hello! How can I help?",sendMessage:"Send a message to get started",online:"Online",newChat:"New Chat",back:"Back",close:"Close",error:"Error",typeMessage:"Type your message...",sendMessageAria:"Send message",domainNotValidated:"Domain not validated",domainErrorMessage:"This domain is not whitelisted. Please contact the administrator to whitelist your website URL."},he:{landingTitle:"איך תרצה לתקשר?",voiceCall:"שיחה קולית",textChat:"צ'אט טקסט",clickToStartCall:"לחץ להתחלת שיחה",realTimeVoice:"שיחה קולית בזמן אמת",startCall:"התחל שיחה",listening:"מקשיב...",speakFreely:"דבר בחופשיות",liveTranscript:"תמלול בזמן אמת",transcriptWillAppear:"התמלול יופיע כאן במהלך השיחה...",mute:"השתק",speaker:"רמקול",endCall:"סיים שיחה",hello:"שלום! איך אפשר לעזור?",sendMessage:"שלח הודעה או עבור למצב קולי לשיחה בזמן אמת",online:"מקוון",newChat:"צ'אט חדש",back:"חזור",close:"סגור",error:"שגיאה",typeMessage:"הקלד הודעה...",sendMessageAria:"שלח הודעה",domainNotValidated:"דומיין לא מאומת",domainErrorMessage:"דומיין זה לא ברשימת המורשים. אנא פנה למנהל המערכת כדי להוסיף את כתובת האתר שלך לרשימה."},ar:{landingTitle:"كيف تريد التواصل؟",voiceCall:"مكالمة صوتية",textChat:"دردشة نصية",clickToStartCall:"انقر لبدء المكالمة",realTimeVoice:"محادثة صوتية في الوقت الفعلي",startCall:"ابدأ المكالمة",listening:"الاستماع...",speakFreely:"تكلم بحرية",liveTranscript:"نص مباشر",transcriptWillAppear:"سيظهر النص هنا أثناء المكالمة...",mute:"كتم الصوت",speaker:"مكبر الصوت",endCall:"إنهاء المكالمة",hello:"مرحبا! كيف يمكنني المساعدة؟",sendMessage:"أرسل رسالة للبدء",online:"متصل",newChat:"محادثة جديدة",back:"رجوع",close:"إغلاق",error:"خطأ",typeMessage:"اكتب رسالة...",sendMessageAria:"إرسال رسالة",domainNotValidated:"النطاق غير معتمد",domainErrorMessage:"هذا النطاق غير مسموح به. يرجى الاتصال بالمسؤول لإضافة عنوان موقع الويب الخاص بك إلى القائمة."},ru:{landingTitle:"Как вы хотите общаться?",voiceCall:"Голосовой звонок",textChat:"Текстовый чат",clickToStartCall:"Нажмите, чтобы начать звонок",realTimeVoice:"Голосовой разговор в реальном времени",startCall:"Начать звонок",listening:"Слушаю...",speakFreely:"Говорите свободно",liveTranscript:"Живая транскрипция",transcriptWillAppear:"Транскрипция появится здесь во время звонка...",mute:"Отключить звук",speaker:"Динамик",endCall:"Завершить звонок",hello:"Привет! Как я могу помочь?",sendMessage:"Отправьте сообщение для начала",online:"В сети",newChat:"Новый чат",back:"Назад",close:"Закрыть",error:"Ошибка",typeMessage:"Введите сообщение...",sendMessageAria:"Отправить сообщение",domainNotValidated:"Домен не проверен",domainErrorMessage:"Этот домен не в белом списке. Пожалуйста, свяжитесь с администратором, чтобы добавить URL вашего веб-сайта в список."},es:{landingTitle:"¿Cómo te gustaría comunicarte?",voiceCall:"Llamada de voz",textChat:"Chat de texto",clickToStartCall:"Haz clic para iniciar la llamada",realTimeVoice:"Conversación de voz en tiempo real",startCall:"Iniciar llamada",listening:"Escuchando...",speakFreely:"Habla libremente",liveTranscript:"Transcripción en vivo",transcriptWillAppear:"La transcripción aparecerá aquí durante la llamada...",mute:"Silenciar",speaker:"Altavoz",endCall:"Terminar llamada",hello:"¡Hola! ¿Cómo puedo ayudarte?",sendMessage:"Envía un mensaje para comenzar",online:"En línea",newChat:"Nuevo chat",back:"Atrás",close:"Cerrar",error:"Error",typeMessage:"Escribe un mensaje...",sendMessageAria:"Enviar mensaje",domainNotValidated:"Dominio no validado",domainErrorMessage:"Este dominio no está en la lista blanca. Por favor, contacte al administrador para agregar la URL de su sitio web a la lista."},fr:{landingTitle:"Comment souhaitez-vous communiquer?",voiceCall:"Appel vocal",textChat:"Chat texte",clickToStartCall:"Cliquez pour démarrer l'appel",realTimeVoice:"Conversation vocale en temps réel",startCall:"Démarrer l'appel",listening:"Écoute...",speakFreely:"Parlez librement",liveTranscript:"Transcripción en direct",transcriptWillAppear:"La transcription apparaîtra ici pendant l'appel...",mute:"Muet",speaker:"Haut-parleur",endCall:"Terminer l'appel",hello:"Bonjour! Comment puis-je vous aider?",sendMessage:"Envoyez un message pour commencer",online:"En ligne",newChat:"Nouveau chat",back:"Retour",close:"Fermer",error:"Erreur",typeMessage:"Tapez votre message...",sendMessageAria:"Envoyer un message",domainNotValidated:"Domaine non validé",domainErrorMessage:"Ce domaine n'est pas sur la liste blanche. Veuillez contacter l'administrateur pour ajouter l'URL de votre site Web à la liste."},de:{landingTitle:"Wie möchten Sie kommunizieren?",voiceCall:"Sprachanruf",textChat:"Text-Chat",clickToStartCall:"Klicken Sie, um den Anruf zu starten",realTimeVoice:"Sprachanruf in Echtzeit",startCall:"Anruf starten",listening:"Hören...",speakFreely:"Sprechen Sie frei",liveTranscript:"Live-Transkription",transcriptWillAppear:"Die Transkription erscheint hier während des Anrufs...",mute:"Stumm",speaker:"Lautsprecher",endCall:"Anruf beenden",hello:"Hallo! Wie kann ich helfen?",sendMessage:"Senden Sie eine Nachricht zum Starten",online:"Online",newChat:"Neuer Chat",back:"Zurück",close:"Schließen",error:"Fehler",typeMessage:"Geben Sie eine Nachricht ein...",sendMessageAria:"Nachricht senden",domainNotValidated:"Domain nicht validiert",domainErrorMessage:"Diese Domain steht nicht auf der Whitelist. Bitte kontaktieren Sie den Administrator, um die URL Ihrer Website zur Liste hinzuzufügen."}};function ao(){var e,t,n="function"==typeof Symbol?Symbol:{},o=n.iterator||"@@iterator",r=n.toStringTag||"@@toStringTag";function i(n,o,r,i){var s=o&&o.prototype instanceof c?o:c,u=Object.create(s.prototype);return co(u,"_invoke",function(n,o,r){var i,c,s,u=0,l=r||[],d=!1,p={p:0,n:0,v:e,a:f,f:f.bind(e,4),d:function(t,n){return i=t,c=0,s=e,p.n=n,a}};function f(n,o){for(c=n,s=o,t=0;!d&&u&&!r&&t<l.length;t++){var r,i=l[t],f=p.p,h=i[2];n>3?(r=h===o)&&(s=i[(c=i[4])?5:(c=3,3)],i[4]=i[5]=e):i[0]<=f&&((r=n<2&&f<i[1])?(c=0,p.v=o,p.n=i[1]):f<h&&(r=n<3||i[0]>o||o>h)&&(i[4]=n,i[5]=o,p.n=h,c=0))}if(r||n>1)return a;throw d=!0,o}return function(r,l,h){if(u>1)throw TypeError("Generator is already running");for(d&&1===l&&f(l,h),c=l,s=h;(t=c<2?e:s)||!d;){i||(c?c<3?(c>1&&(p.n=-1),f(c,s)):p.n=s:p.v=s);try{if(u=2,i){if(c||(r="next"),t=i[r]){if(!(t=t.call(i,s)))throw TypeError("iterator result is not an object");if(!t.done)return t;s=t.value,c<2&&(c=0)}else 1===c&&(t=i.return)&&t.call(i),c<2&&(s=TypeError("The iterator does not provide a '"+r+"' method"),c=1);i=e}else if((t=(d=p.n<0)?s:n.call(o,p))!==a)break}catch(t){i=e,c=1,s=t}finally{u=1}}return{value:t,done:d}}}(n,r,i),!0),u}var a={};function c(){}function s(){}function u(){}t=Object.getPrototypeOf;var l=[][o]?t(t([][o]())):(co(t={},o,function(){return this}),t),d=u.prototype=c.prototype=Object.create(l);function p(e){return Object.setPrototypeOf?Object.setPrototypeOf(e,u):(e.__proto__=u,co(e,r,"GeneratorFunction")),e.prototype=Object.create(d),e}return s.prototype=u,co(d,"constructor",u),co(u,"constructor",s),s.displayName="GeneratorFunction",co(u,r,"GeneratorFunction"),co(d),co(d,r,"Generator"),co(d,o,function(){return this}),co(d,"toString",function(){return"[object Generator]"}),(ao=function(){return{w:i,m:p}})()}function co(e,t,n,o){var r=Object.defineProperty;try{r({},"",{})}catch(e){r=0}co=function(e,t,n,o){function i(t,n){co(e,t,function(e){return this._invoke(t,n,e)})}t?r?r(e,t,{value:n,enumerable:!o,configurable:!o,writable:!o}):e[t]=n:(i("next",0),i("throw",1),i("return",2))},co(e,t,n,o)}function so(e,t,n,o,r,i,a){try{var c=e[i](a),s=c.value}catch(e){return void n(e)}c.done?t(s):Promise.resolve(s).then(o,r)}function uo(e){return function(){var t=this,n=arguments;return new Promise(function(o,r){var i=e.apply(t,n);function a(e){so(i,o,r,a,c,"next",e)}function c(e){so(i,o,r,a,c,"throw",e)}a(void 0)})}}function lo(e){return lo="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},lo(e)}function po(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(e);t&&(o=o.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,o)}return n}function fo(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?po(Object(n),!0).forEach(function(t){ho(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):po(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}function ho(e,t,n){return(t=go(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function vo(e,t){for(var n=0;n<t.length;n++){var o=t[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(e,go(o.key),o)}}function go(e){var t=function(e){if("object"!=lo(e)||!e)return e;var t=e[Symbol.toPrimitive];if(void 0!==t){var n=t.call(e,"string");if("object"!=lo(n))return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}(e);return"symbol"==lo(t)?t:t+""}var yo=function(){return e=function e(){var t,n,o,r,i,a,c,s=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),this.config=this.mergeWithDefaults(s),this.sdk=new pn(this.config),this.isOpen=!1,this.isActive=!1,this.translations=io,this.currentView="landing";var u=fo(fo(fo({},this.config),this.config.voice),{},{language:(null===(t=this.config.voice)||void 0===t?void 0:t.language)||this.config.language||"en",websocketUrl:(null===(n=this.config.voice)||void 0===n?void 0:n.websocketUrl)||this.config.websocketUrl||"wss://speech.talktopc.com/ws/conv",translations:this.translations,outputContainer:(null===(o=this.config.voice)||void 0===o?void 0:o.outputContainer)||"raw",outputEncoding:(null===(r=this.config.voice)||void 0===r?void 0:r.outputEncoding)||"pcm",outputSampleRate:(null===(i=this.config.voice)||void 0===i?void 0:i.outputSampleRate)||44100,outputChannels:(null===(a=this.config.voice)||void 0===a?void 0:a.outputChannels)||1,outputBitDepth:(null===(c=this.config.voice)||void 0===c?void 0:c.outputBitDepth)||16,onConversationStart:this.config.onConversationStart,onConversationEnd:this.config.onConversationEnd,onBargeIn:this.config.onBargeIn,onAudioStartPlaying:this.config.onAudioStartPlaying,onAudioStoppedPlaying:this.config.onAudioStoppedPlaying,onSubtitleDisplay:this.config.onSubtitleDisplay});this.voiceInterface=new Yn(u);var l=fo(fo(fo({},this.config),this.config.text),{},{translations:this.translations});if(this.textInterface=new ro(l,this.sdk),this.setupEventHandlers(),this.createWidget(),this.config.behavior.startOpen||this.config.behavior.autoOpen){var d=document.getElementById("text-chat-panel");d&&(this.isOpen=!0,d.classList.add("open"))}},t=[{key:"mergeWithDefaults",value:function(e){var t,n,o,r,i,a,c,s,u,l,d,p,f,h,v,g,y,m,b,S,w,x,C,k,P,O,E,T,A,I,j,D,F,B,R,_,U,M,N,V,L,K,z,H,W,G,q,Q,J,Y,$,X,Z,ee,te,ne,oe,re,ie,ae,ce,se,ue,le,de,pe,fe,he,ve,ge,ye,me,be,Se,we,xe,Ce,ke,Pe,Oe,Ee,Te,Ae,Ie,je,De,Fe,Be,Re,_e,Ue,Me,Ne,Ve,Le,Ke,ze,He,We,Ge,qe,Qe,Je,Ye,$e,Xe,Ze,et,tt,nt,ot,rt,it,at,ct,st,ut,lt,dt,pt,ft,ht,vt,gt,yt,mt,bt,St,wt,xt,Ct,kt,Pt,Ot,Et=e.position||"bottom-right";if("string"==typeof Et){var Tt=Et.split("-");Et={vertical:Tt[0]||"bottom",horizontal:Tt[1]||"right",offset:e.positionOffset||{x:20,y:20}}}var At=e.primaryColor||(null===(t=e.button)||void 0===t?void 0:t.primaryColor)||(null===(n=e.button)||void 0===n?void 0:n.backgroundColor)||"#7C3AED",It=(null===(o=e.header)||void 0===o?void 0:o.backgroundColor)||(null===(r=e.button)||void 0===r?void 0:r.backgroundColor)||At;return fo({agentId:e.agentId,appId:e.appId,getSessionUrl:e.getSessionUrl,websocketUrl:e.websocketUrl,demo:!1!==e.demo,direction:e.direction||"ltr",language:e.language||"en",icon:fo({type:(null===(i=e.icon)||void 0===i?void 0:i.type)||"custom",customImage:(null===(a=e.icon)||void 0===a?void 0:a.customImage)||"https://talktopc.com/logo192.png",emoji:(null===(c=e.icon)||void 0===c?void 0:c.emoji)||"🎤",text:(null===(s=e.icon)||void 0===s?void 0:s.text)||"AI",size:(null===(u=e.icon)||void 0===u?void 0:u.size)||"medium",backgroundColor:(null===(l=e.icon)||void 0===l?void 0:l.backgroundColor)||"#FFFFFF"},e.icon),position:fo({vertical:Et.vertical||"bottom",horizontal:Et.horizontal||"right",offset:Et.offset||{x:20,y:20}},"object"===lo(e.position)?e.position:{}),button:fo({size:(null===(d=e.button)||void 0===d?void 0:d.size)||"medium",shape:(null===(p=e.button)||void 0===p?void 0:p.shape)||"circle",backgroundColor:(null===(f=e.button)||void 0===f?void 0:f.backgroundColor)||(null===(h=e.icon)||void 0===h?void 0:h.backgroundColor)||At,hoverColor:(null===(v=e.button)||void 0===v?void 0:v.hoverColor)||"#7C3AED",shadow:!1!==(null===(g=e.button)||void 0===g?void 0:g.shadow),shadowColor:(null===(y=e.button)||void 0===y?void 0:y.shadowColor)||"rgba(0,0,0,0.15)",primaryColor:(null===(m=e.button)||void 0===m?void 0:m.backgroundColor)||(null===(b=e.icon)||void 0===b?void 0:b.backgroundColor)||At},e.button),panel:fo({width:(null===(S=e.panel)||void 0===S?void 0:S.width)||350,height:(null===(w=e.panel)||void 0===w?void 0:w.height)||500,borderRadius:(null===(x=e.panel)||void 0===x?void 0:x.borderRadius)||12,backgroundColor:(null===(C=e.panel)||void 0===C?void 0:C.backgroundColor)||"#FFFFFF",backdropFilter:(null===(k=e.panel)||void 0===k?void 0:k.backdropFilter)||null,border:(null===(P=e.panel)||void 0===P?void 0:P.border)||"1px solid rgba(0,0,0,0.1)"},e.panel),voice:fo({micButtonColor:(null===(O=e.voice)||void 0===O?void 0:O.micButtonColor)||(null===(E=e.panel)||void 0===E?void 0:E.micButtonColor)||At,micButtonActiveColor:(null===(T=e.voice)||void 0===T?void 0:T.micButtonActiveColor)||(null===(A=e.panel)||void 0===A?void 0:A.micButtonActiveColor)||"#EF4444",micButtonHint:fo(fo({text:(null===(I=e.voice)||void 0===I||null===(I=I.micButtonHint)||void 0===I?void 0:I.text)||(null===(j=e.panel)||void 0===j||null===(j=j.micButtonHint)||void 0===j?void 0:j.text)||"Click the button to start voice conversation",color:(null===(D=e.voice)||void 0===D||null===(D=D.micButtonHint)||void 0===D?void 0:D.color)||(null===(F=e.panel)||void 0===F||null===(F=F.micButtonHint)||void 0===F?void 0:F.color)||"#6B7280",fontSize:(null===(B=e.voice)||void 0===B||null===(B=B.micButtonHint)||void 0===B?void 0:B.fontSize)||(null===(R=e.panel)||void 0===R||null===(R=R.micButtonHint)||void 0===R?void 0:R.fontSize)||"12px"},null===(_=e.voice)||void 0===_?void 0:_.micButtonHint),null===(U=e.panel)||void 0===U?void 0:U.micButtonHint),avatarBackgroundColor:(null===(M=e.voice)||void 0===M?void 0:M.avatarBackgroundColor)||"#667eea",avatarActiveBackgroundColor:(null===(N=e.voice)||void 0===N?void 0:N.avatarActiveBackgroundColor)||"#667eea",statusTitleColor:(null===(V=e.voice)||void 0===V?void 0:V.statusTitleColor)||"#1e293b",statusSubtitleColor:(null===(L=e.voice)||void 0===L?void 0:L.statusSubtitleColor)||"#64748b",startCallButtonColor:(null===(K=e.voice)||void 0===K?void 0:K.startCallButtonColor)||"#667eea",startCallButtonTextColor:(null===(z=e.voice)||void 0===z?void 0:z.startCallButtonTextColor)||"#FFFFFF",transcriptBackgroundColor:(null===(H=e.voice)||void 0===H?void 0:H.transcriptBackgroundColor)||"#FFFFFF",transcriptTextColor:(null===(W=e.voice)||void 0===W?void 0:W.transcriptTextColor)||"#1e293b",transcriptLabelColor:(null===(G=e.voice)||void 0===G?void 0:G.transcriptLabelColor)||"#94a3b8",controlButtonColor:(null===(q=e.voice)||void 0===q?void 0:q.controlButtonColor)||"#FFFFFF",controlButtonSecondaryColor:(null===(Q=e.voice)||void 0===Q?void 0:Q.controlButtonSecondaryColor)||"#64748b",endCallButtonColor:(null===(J=e.voice)||void 0===J?void 0:J.endCallButtonColor)||"#ef4444",language:(null===(Y=e.voice)||void 0===Y?void 0:Y.language)||e.language||"en",websocketUrl:(null===($=e.voice)||void 0===$?void 0:$.websocketUrl)||e.websocketUrl},e.voice),text:fo({sendButtonColor:(null===(X=e.text)||void 0===X?void 0:X.sendButtonColor)||(null===(Z=e.panel)||void 0===Z?void 0:Z.sendButtonColor)||"#7C3AED",sendButtonHoverColor:(null===(ee=e.text)||void 0===ee?void 0:ee.sendButtonHoverColor)||(null===(te=e.panel)||void 0===te?void 0:te.sendButtonHoverColor)||"#6D28D9",sendButtonActiveColor:(null===(ne=e.text)||void 0===ne?void 0:ne.sendButtonActiveColor)||(null===(oe=e.panel)||void 0===oe?void 0:oe.sendButtonActiveColor)||"#6D28D9",sendButtonText:(null===(re=e.text)||void 0===re?void 0:re.sendButtonText)||(null===(ie=e.panel)||void 0===ie?void 0:ie.sendButtonText)||"➤",sendButtonTextColor:(null===(ae=e.text)||void 0===ae?void 0:ae.sendButtonTextColor)||(null===(ce=e.panel)||void 0===ce?void 0:ce.sendButtonTextColor)||"#FFFFFF",sendButtonFontSize:(null===(se=e.text)||void 0===se?void 0:se.sendButtonFontSize)||(null===(ue=e.panel)||void 0===ue?void 0:ue.sendButtonFontSize)||"18px",sendButtonFontWeight:(null===(le=e.text)||void 0===le?void 0:le.sendButtonFontWeight)||(null===(de=e.panel)||void 0===de?void 0:de.sendButtonFontWeight)||"500",sendButtonHint:fo(fo({text:(null===(pe=e.text)||void 0===pe||null===(pe=pe.sendButtonHint)||void 0===pe?void 0:pe.text)||(null===(fe=e.panel)||void 0===fe||null===(fe=fe.sendButtonHint)||void 0===fe?void 0:fe.text)||"",color:(null===(he=e.text)||void 0===he||null===(he=he.sendButtonHint)||void 0===he?void 0:he.color)||(null===(ve=e.panel)||void 0===ve||null===(ve=ve.sendButtonHint)||void 0===ve?void 0:ve.color)||"#6B7280",fontSize:(null===(ge=e.text)||void 0===ge||null===(ge=ge.sendButtonHint)||void 0===ge?void 0:ge.fontSize)||(null===(ye=e.panel)||void 0===ye||null===(ye=ye.sendButtonHint)||void 0===ye?void 0:ye.fontSize)||"12px"},null===(me=e.text)||void 0===me?void 0:me.sendButtonHint),null===(be=e.panel)||void 0===be?void 0:be.sendButtonHint),inputPlaceholder:(null===(Se=e.text)||void 0===Se?void 0:Se.inputPlaceholder)||(null===(we=e.panel)||void 0===we?void 0:we.inputPlaceholder)||"Type your message...",inputBorderColor:(null===(xe=e.text)||void 0===xe?void 0:xe.inputBorderColor)||(null===(Ce=e.panel)||void 0===Ce?void 0:Ce.inputBorderColor)||"#E5E7EB",inputFocusColor:(null===(ke=e.text)||void 0===ke?void 0:ke.inputFocusColor)||(null===(Pe=e.panel)||void 0===Pe?void 0:Pe.inputFocusColor)||"#7C3AED",inputBackgroundColor:(null===(Oe=e.text)||void 0===Oe?void 0:Oe.inputBackgroundColor)||(null===(Ee=e.panel)||void 0===Ee?void 0:Ee.inputBackgroundColor)||"#FFFFFF",inputTextColor:(null===(Te=e.text)||void 0===Te?void 0:Te.inputTextColor)||(null===(Ae=e.panel)||void 0===Ae?void 0:Ae.inputTextColor)||"#1F2937",inputFontSize:(null===(Ie=e.text)||void 0===Ie?void 0:Ie.inputFontSize)||(null===(je=e.panel)||void 0===je?void 0:je.inputFontSize)||"14px",inputBorderRadius:(null===(De=e.text)||void 0===De?void 0:De.inputBorderRadius)||(null===(Fe=e.panel)||void 0===Fe?void 0:Fe.inputBorderRadius)||20,inputPadding:(null===(Be=e.text)||void 0===Be?void 0:Be.inputPadding)||(null===(Re=e.panel)||void 0===Re?void 0:Re.inputPadding)||"6px 14px"},e.text),landing:fo({backgroundColor:(null===(_e=e.landing)||void 0===_e?void 0:_e.backgroundColor)||"linear-gradient(180deg, #f8fafc 0%, #e0e7ff 100%)",logo:(null===(Ue=e.landing)||void 0===Ue?void 0:Ue.logo)||"🤖",title:(null===(Me=e.landing)||void 0===Me?void 0:Me.title)||null,titleColor:(null===(Ne=e.landing)||void 0===Ne?void 0:Ne.titleColor)||"#1e293b",modeCardBackgroundColor:(null===(Ve=e.landing)||void 0===Ve?void 0:Ve.modeCardBackgroundColor)||"#FFFFFF",modeCardBorderColor:(null===(Le=e.landing)||void 0===Le?void 0:Le.modeCardBorderColor)||"#E2E8F0",modeCardHoverBorderColor:(null===(Ke=e.landing)||void 0===Ke?void 0:Ke.modeCardHoverBorderColor)||It,modeCardIconBackgroundColor:(null===(ze=e.landing)||void 0===ze?void 0:ze.modeCardIconBackgroundColor)||It,modeCardTitleColor:(null===(He=e.landing)||void 0===He?void 0:He.modeCardTitleColor)||"#111827",voiceCardIcon:(null===(We=e.landing)||void 0===We?void 0:We.voiceCardIcon)||"🎤",textCardIcon:(null===(Ge=e.landing)||void 0===Ge?void 0:Ge.textCardIcon)||"💬"},e.landing),header:fo({title:(null===(qe=e.header)||void 0===qe?void 0:qe.title)||"Chat Assistant",showTitle:!1!==(null===(Qe=e.header)||void 0===Qe?void 0:Qe.showTitle),backgroundColor:(null===(Je=e.header)||void 0===Je?void 0:Je.backgroundColor)||(null===(Ye=e.button)||void 0===Ye?void 0:Ye.backgroundColor)||"#7C3AED",textColor:(null===($e=e.header)||void 0===$e?void 0:$e.textColor)||"#FFFFFF",showCloseButton:!1!==(null===(Xe=e.header)||void 0===Xe?void 0:Xe.showCloseButton)},e.header),tooltips:fo({newChat:(null===(Ze=e.tooltips)||void 0===Ze?void 0:Ze.newChat)||null,back:(null===(et=e.tooltips)||void 0===et?void 0:et.back)||null,close:(null===(tt=e.tooltips)||void 0===tt?void 0:tt.close)||null,mute:(null===(nt=e.tooltips)||void 0===nt?void 0:nt.mute)||null,speaker:(null===(ot=e.tooltips)||void 0===ot?void 0:ot.speaker)||null,endCall:(null===(rt=e.tooltips)||void 0===rt?void 0:rt.endCall)||null},e.tooltips),messages:fo({userBackgroundColor:(null===(it=e.messages)||void 0===it?void 0:it.userBackgroundColor)||"#E5E7EB",agentBackgroundColor:(null===(at=e.messages)||void 0===at?void 0:at.agentBackgroundColor)||"#F3F4F6",systemBackgroundColor:(null===(ct=e.messages)||void 0===ct?void 0:ct.systemBackgroundColor)||"#DCFCE7",errorBackgroundColor:(null===(st=e.messages)||void 0===st?void 0:st.errorBackgroundColor)||"#FEE2E2",textColor:(null===(ut=e.messages)||void 0===ut?void 0:ut.textColor)||"#1F2937",fontSize:(null===(lt=e.messages)||void 0===lt?void 0:lt.fontSize)||"14px",borderRadius:(null===(dt=e.messages)||void 0===dt?void 0:dt.borderRadius)||8},e.messages),animation:fo({enableHover:!1!==(null===(pt=e.animation)||void 0===pt?void 0:pt.enableHover),enablePulse:!1!==(null===(ft=e.animation)||void 0===ft?void 0:ft.enablePulse),enableSlide:!1!==(null===(ht=e.animation)||void 0===ht?void 0:ht.enableSlide),duration:(null===(vt=e.animation)||void 0===vt?void 0:vt.duration)||.3},e.animation),behavior:fo({autoOpen:(null===(gt=e.behavior)||void 0===gt?void 0:gt.autoOpen)||!1,startOpen:(null===(yt=e.behavior)||void 0===yt?void 0:yt.startOpen)||!1,hidden:(null===(mt=e.behavior)||void 0===mt?void 0:mt.hidden)||!1,autoConnect:(null===(bt=e.behavior)||void 0===bt?void 0:bt.autoConnect)||!1,showWelcomeMessage:!1!==(null===(St=e.behavior)||void 0===St?void 0:St.showWelcomeMessage),welcomeMessage:(null===(wt=e.behavior)||void 0===wt?void 0:wt.welcomeMessage)||"Hello! How can I help you today?",enableVoiceMode:void 0===(null===(xt=e.behavior)||void 0===xt?void 0:xt.enableVoiceMode)||e.behavior.enableVoiceMode,mode:(null===(Ct=e.behavior)||void 0===Ct?void 0:Ct.mode)||"unified"},e.behavior),accessibility:fo({ariaLabel:(null===(kt=e.accessibility)||void 0===kt?void 0:kt.ariaLabel)||"Chat Assistant",ariaDescription:(null===(Pt=e.accessibility)||void 0===Pt?void 0:Pt.ariaDescription)||"Click to open chat assistant",keyboardNavigation:!1!==(null===(Ot=e.accessibility)||void 0===Ot?void 0:Ot.keyboardNavigation)},e.accessibility),customStyles:e.customStyles||"",variables:e.variables||{},forceConversationId:e.forceConversationId,onConversationStart:e.onConversationStart,onConversationEnd:e.onConversationEnd,onBargeIn:e.onBargeIn,onAudioStartPlaying:e.onAudioStartPlaying,onAudioStoppedPlaying:e.onAudioStoppedPlaying,onSubtitleDisplay:e.onSubtitleDisplay,primaryColor:At},"string"==typeof e.position?{positionString:e.position}:{})}},{key:"setupEventHandlers",value:function(){var e=this;this.sdk.on("domainError",function(t){e.textInterface.showError(t),e.textInterface.stopStreamingState()}),this.sdk.on("error",function(t){t&&("DOMAIN_NOT_WHITELISTED"===t.message||t.message&&t.message.includes("Domain not whitelisted"))||(e.textInterface.showError(t.message||t),e.textInterface.stopStreamingState())}),this.sdk.on("chunk",function(t){e.textInterface.appendStreamingChunk(t)}),this.sdk.on("done",function(t){var n=t.text;e.textInterface.finalizeStreaming(n)})}},{key:"createWidget",value:function(){var e=document.getElementById("text-chat-widget");e&&e.remove();var t=document.createElement("div");if(t.id="text-chat-widget",t.innerHTML=this.generateWidgetHTML(),document.body.appendChild(t),this.setupWidgetEvents(),this.config.behavior.startOpen||this.config.behavior.autoOpen){var n=document.getElementById("text-chat-panel");n&&(this.isOpen=!0,n.classList.add("open"))}}},{key:"generateWidgetHTML",value:function(){var e=this,t=(this.config.position,this.config.button),n=this.config.icon,o=(this.config.panel,this.config.header),r=(this.config.animation,{small:50,medium:60,large:70,xl:80}[t.size]||60),i={small:20,medium:28,large:36,xl:44}[n.size]||28,a=this.generatePositionStyles(),c=this.generateIconHTML(i),s=this.config.behavior.mode||"unified",u="unified"===s,l="unified"===s||"voice-only"===s,d="unified"===s||"text-only"===s,p=function(t){var n=e.config.language||"en";return(e.translations[n]||e.translations.en)[t]||t},f=function(t){var n,o=null===(n=e.config.tooltips)||void 0===n?void 0:n[t];return null!=o?o:{newChat:p("newChat"),back:p("back"),close:p("close"),mute:p("mute"),speaker:p("speaker"),endCall:p("endCall")}[t]||""};return"\n <style>\n ".concat(this.generateCSS(a,r,i),"\n ").concat(this.config.customStyles,"\n </style>\n \n ").concat(this.config.behavior.hidden?"":'\n <button id="text-chat-button" \n aria-label="'.concat(this.config.accessibility.ariaLabel,'"\n aria-description="').concat(this.config.accessibility.ariaDescription,'">\n ').concat(c,"\n </button>\n "),'\n \n <div id="text-chat-panel">\n <div class="widget-shell">\n <div class="panel-inner widget-container" style="direction: ').concat(this.config.direction,';">\n <div class="widget-header" style="background: ').concat(o.backgroundColor,"; color: ").concat(o.textColor,';">\n <div>\n ').concat(o.showTitle?'<div class="header-title">'.concat(o.title,"</div>"):"",'\n <div class="header-status">\n <span class="status-dot"></span>\n <span>').concat(p("online"),'</span>\n </div>\n </div>\n \n <div style="display: flex; gap: 12px; align-items: center;">\n \x3c!-- New Chat Button (hide on landing screen, show otherwise) --\x3e\n <button class="header-icon new-chat-btn" id="newChatBtn" title="').concat(f("newChat"),'" style="').concat(u?"display: none;":"",'">\n <span style="font-size: 18px; font-weight: bold;">+</span>\n </button>\n \n \x3c!-- Back Button (only show in unified mode) --\x3e\n ').concat("unified"===s?'<button class="header-icon back-btn" id="backBtn" title="'.concat(f("back"),'" style="display: none;">\n <span style="font-size: 16px;">‹</span>\n </button>'):"","\n \n \x3c!-- Close Button --\x3e\n ").concat(o.showCloseButton?'<button class="header-icon close-btn" id="closeBtn" title="'+f("close")+'"><span style="font-size: 18px; font-weight: bold;">×</span></button>':"","\n </div>\n </div>\n\n ").concat(u?'\n <div class="landing-screen" id="landingScreen">\n <div class="landing-logo">🤖</div>\n <div class="landing-title">'.concat(p("landingTitle"),'</div>\n <div class="mode-selection">\n ').concat(l?'<div class="mode-card voice" id="mode-card-voice">\n <div class="mode-card-icon">🎤</div>\n <div class="mode-card-title">'.concat(p("voiceCall"),"</div>\n </div>"):"","\n ").concat(d?'<div class="mode-card text" id="mode-card-text">\n <div class="mode-card-icon">💬</div>\n <div class="mode-card-title">'.concat(p("textChat"),"</div>\n </div>"):"","\n </div>\n </div>"):"","\n\n ").concat(l?this.voiceInterface.generateHTML():"","\n ").concat(d?this.textInterface.generateHTML():"","\n </div>\n </div>\n </div>\n ")}},{key:"generatePositionStyles",value:function(){var e=this.config.position,t=e.offset||{x:20,y:20},n="";return"top"===e.vertical?n+="top: ".concat(t.y,"px;"):"bottom"===e.vertical?n+="bottom: ".concat(t.y,"px;"):"center"===e.vertical&&(n+="top: 50%; transform: translateY(-50%);"),"left"===e.horizontal?n+="left: ".concat(t.x,"px;"):"right"===e.horizontal?n+="right: ".concat(t.x,"px;"):"center"===e.horizontal&&(n+="left: 50%; transform: translateX(-50%);"),n}},{key:"generateIconHTML",value:function(e){var t=this.config.icon;switch(t.type){case"custom":return'<img src="'.concat(t.customImage,'" alt="Chat Assistant" style="width: ').concat(e,"px; height: ").concat(e,'px; object-fit: contain;" />');case"emoji":return'<span style="font-size: '.concat(e,'px; line-height: 1;">').concat(t.emoji,"</span>");case"text":return'<span style="font-size: '.concat(Math.floor(.6*e),'px; font-weight: bold; color: white;">').concat(t.text,"</span>");case"microphone":default:return'<svg viewBox="0 0 24 24" style="width: '.concat(e,"px; height: ").concat(e,'px; fill: white;">\n <path d="M12 14c1.66 0 3-1.34 3-3V5c0-1.66-1.34-3-3-3S9 3.34 9 5v6c0 1.66 1.34 3 3 3z"/>\n <path d="M17 11c0 2.76-2.24 5-5 5s-5-2.24-5-5H5c0 3.53 2.61 6.43 6 6.92V21h2v-3.08c3.39-.49 6-3.39 6-6.92h-2z"/>\n </svg>');case"chat":return'<svg viewBox="0 0 24 24" style="width: '.concat(e,"px; height: ").concat(e,'px; fill: white;">\n <path d="M20 2H4c-1.1 0-2 .9-2 2v18l4-4h14c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2zm0 14H6l-2 2V4h16v12z"/>\n </svg>')}}},{key:"generateCSS",value:function(e,t,n){var o,r,i,a,c,s,u,l=this.config.button,d=this.config.icon,p=this.config.panel,f=this.config.header,h=(this.config.messages,this.config.animation),v=this.config.behavior.mode||"unified",g="unified"===v||"voice-only"===v,y="unified"===v||"text-only"===v,m=f.backgroundColor;return'\n /* MOBILE FIRST - Default styles for all devices */\n #text-chat-widget {\n position: fixed !important;\n z-index: 10000;\n font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;\n /* Mobile defaults */\n right: 10px;\n bottom: 10px;\n left: auto;\n top: auto;\n }\n \n /* Desktop positioning (only on larger screens) */\n @media (min-width: 769px) {\n #text-chat-widget {\n '.concat(e,"\n right: ").concat("right"===this.config.position.horizontal?"20px":"auto",";\n left: ").concat("left"===this.config.position.horizontal?"20px":"auto",";\n bottom: ").concat("bottom"===this.config.position.vertical?"20px":"auto",";\n top: ").concat("top"===this.config.position.vertical?"20px":"auto",";\n }\n }\n \n /* Mobile override (force mobile positioning) */\n @media (max-width: 768px) {\n #text-chat-widget {\n right: 10px !important;\n bottom: 10px !important;\n left: auto !important;\n top: auto !important;\n transform: none !important;\n }\n }\n \n @media (max-width: 480px) {\n #text-chat-widget {\n right: 8px !important;\n bottom: 8px !important;\n left: auto !important;\n top: auto !important;\n }\n }\n \n #text-chat-button {\n width: ").concat(t,"px;\n height: ").concat(t,"px;\n border-radius: ").concat("circle"===l.shape?"50%":"square"===l.shape?"0":"12px",";\n background: ").concat(l.backgroundColor||d.backgroundColor||"#7C3AED",";\n border: none;\n cursor: pointer;\n display: flex;\n align-items: center;\n justify-content: center;\n transition: all ").concat(h.duration,"s ease;\n box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4);\n touch-action: manipulation;\n -webkit-tap-highlight-color: transparent;\n -webkit-touch-callout: none;\n user-select: none;\n min-width: 44px;\n min-height: 44px;\n }\n \n @media (max-width: 768px) {\n #text-chat-widget {\n right: 10px !important;\n bottom: 10px !important;\n left: auto !important;\n top: auto !important;\n transform: none !important;\n }\n \n #text-chat-button {\n width: 56px !important;\n height: 56px !important;\n min-width: 56px !important;\n min-height: 56px !important;\n max-width: 56px !important;\n max-height: 56px !important;\n }\n \n #text-chat-panel {\n position: fixed !important;\n left: 10px !important;\n right: 10px !important;\n bottom: 76px !important; /* 56px button + 20px gap */\n top: 60px !important; /* Add top spacing */\n width: auto !important;\n max-width: none !important;\n height: auto !important; /* Change from max-height to auto */\n max-height: none !important; /* Remove max-height */\n transform: none !important;\n margin: 0 !important;\n }\n \n #text-chat-panel .widget-header {\n padding: 10px 14px;\n min-height: 56px;\n }\n \n #text-chat-panel .header-title {\n font-size: 15px;\n }\n \n #text-chat-panel .header-icon {\n width: 40px;\n height: 40px;\n min-width: 40px;\n min-height: 40px;\n }\n \n #text-chat-input {\n font-size: 16px !important; /* Prevents iOS zoom on focus */\n padding: 12px 16px !important;\n min-height: 48px !important;\n }\n \n #text-chat-send {\n min-width: 48px !important;\n min-height: 48px !important;\n width: 48px !important;\n height: 48px !important;\n }\n \n .landing-screen {\n padding: 16px;\n }\n \n .landing-logo {\n font-size: 40px;\n }\n \n .landing-title {\n font-size: 18px;\n margin-bottom: 16px;\n }\n \n .mode-selection {\n flex-direction: column;\n gap: 12px;\n align-items: center;\n }\n \n .mode-card {\n max-width: 100%;\n width: 100%;\n padding: 16px;\n }\n \n .mode-card-icon {\n width: 50px;\n height: 50px;\n font-size: 28px;\n }\n \n .mode-card-title {\n font-size: 14px;\n }\n }\n \n @media (max-width: 480px) {\n #text-chat-widget {\n right: 8px !important;\n bottom: 8px !important;\n left: auto !important;\n top: auto !important;\n }\n \n #text-chat-button {\n width: 54px !important;\n height: 54px !important;\n min-width: 54px !important;\n min-height: 54px !important;\n }\n \n #text-chat-panel {\n left: 8px !important;\n right: 8px !important;\n bottom: 70px !important;\n top: 50px !important; /* Add top spacing for very small screens */\n height: auto !important;\n max-height: none !important;\n }\n \n #text-chat-panel .widget-header {\n padding: 8px 12px;\n min-height: 52px;\n }\n \n #text-chat-panel .header-title {\n font-size: 14px;\n }\n \n .landing-logo {\n font-size: 36px;\n }\n \n .landing-title {\n font-size: 16px;\n }\n }\n \n ").concat(h.enableHover?"\n #text-chat-button:hover {\n background: linear-gradient(135deg, #764ba2 0%, #667eea 100%);\n transform: scale(1.05);\n box-shadow: 0 8px 20px rgba(102, 126, 234, 0.5);\n }\n ":"","\n \n #text-chat-panel {\n display: none;\n position: fixed;\n bottom: calc(").concat(t,"px + 20px);\n ").concat("right"===this.config.position.horizontal?"right: 20px;":"left: 20px;","\n width: ").concat(p.width,"px;\n max-width: calc(100vw - 40px);\n height: ").concat(p.height,"px;\n max-height: calc(100vh - ").concat(t,"px - 40px);\n background: transparent;\n border-radius: ").concat(p.borderRadius,"px;\n border: none;\n flex-direction: column;\n overflow: hidden;\n ").concat(p.backdropFilter?"backdrop-filter: ".concat(p.backdropFilter,";"):"","\n ").concat(h.enableSlide?"transition: all ".concat(h.duration,"s ease;"):"","\n box-sizing: border-box;\n }\n \n #text-chat-panel.open {\n display: flex;\n ").concat(h.enableSlide?"transform: translateY(0); opacity: 1;":"","\n }\n\n /* Shell for gradient border/background */\n .widget-shell { width: 100%; height: 100%; padding: 0; border-radius: ").concat(p.borderRadius,"px; background: transparent; box-shadow: 0 20px 60px rgba(0,0,0,0.15); overflow: hidden; display: flex; flex-direction: column; box-sizing: border-box; }\n .panel-inner { width: 100%; height: 100%; background: #ffffff; border-radius: ").concat(p.borderRadius,"px; overflow: hidden; display:flex; flex-direction: column; padding: 0; box-sizing: border-box; max-width: 100%; }\n\n /* New structure styles matching provided design */\n #text-chat-panel .widget-container {\n width: 100%; height: 100%; min-height: 0; background: #FFFFFF; overflow: hidden; display: flex; flex-direction: column; border-radius: ").concat(p.borderRadius,"px;\n container-type: size;\n }\n \n /* Ensure content areas can scroll when height is constrained */\n #text-chat-panel .widget-container > .landing-screen,\n #text-chat-panel .widget-container > .voice-interface,\n #text-chat-panel .widget-container > .text-interface {\n flex: 1;\n min-height: 0;\n overflow-y: auto;\n overflow-x: hidden;\n }\n \n /* Header should not scroll */\n #text-chat-panel .widget-header {\n padding: 12px 16px;\n display: flex;\n justify-content: space-between;\n align-items: center;\n border-top-left-radius: ").concat(p.borderRadius,"px;\n border-top-right-radius: ").concat(p.borderRadius,"px;\n flex-shrink: 0;\n min-height: 60px;\n box-sizing: border-box;\n }\n #text-chat-panel .header-title { font-size: 16px; font-weight: 600; }\n #text-chat-panel .header-status { display: flex; align-items: center; gap: 8px; font-size: 12px; opacity: 0.9; }\n #text-chat-panel .status-dot { width: 8px; height: 8px; background: #4ade80; border-radius: 50%; animation: pulse 2s ease-in-out infinite; }\n @keyframes pulse { 0%, 100% { opacity: 1; } 50% { opacity: 0.5; } }\n /* Header icon buttons */\n .header-icon {\n background: rgba(255, 255, 255, 0.2);\n border: none;\n color: white;\n width: 36px;\n height: 36px;\n min-width: 36px;\n min-height: 36px;\n border-radius: 50%;\n cursor: pointer;\n display: flex;\n align-items: center;\n justify-content: center;\n transition: background 0.2s;\n flex-shrink: 0;\n font-size: 16px;\n padding: 0;\n box-sizing: border-box;\n }\n \n .header-icon:hover {\n background: rgba(255, 255, 255, 0.3);\n }\n \n .header-icon svg {\n pointer-events: none;\n stroke: white;\n fill: none;\n }\n \n .back-btn.visible {\n display: flex !important;\n }\n\n /* Landing and mode selection (shown only if voice enabled) */\n .landing-screen { \n display: none; \n flex: 1; \n padding: 20px; \n background: ").concat((null===(o=this.config.landing)||void 0===o?void 0:o.backgroundColor)||"linear-gradient(180deg, #f8fafc 0%, #e0e7ff 100%)","; \n align-items: center; \n justify-content: flex-start; \n flex-direction: column; \n gap: 16px; \n overflow-y: auto; \n min-height: 0; \n }\n .landing-screen.active { display: flex; }\n .landing-logo { font-size: 48px; }\n .landing-title { \n font-size: 20px; \n color: ").concat((null===(r=this.config.landing)||void 0===r?void 0:r.titleColor)||"#1e293b","; \n font-weight: 700; \n margin-bottom: 20px; \n text-align: center;\n width: 100%;\n }\n .mode-selection { display: flex; gap: 16px; width: 100%; justify-content: center; }\n .mode-card { \n flex: 1; \n max-width: 180px; \n background: ").concat((null===(i=this.config.landing)||void 0===i?void 0:i.modeCardBackgroundColor)||"#FFFFFF","; \n border: 2px solid ").concat((null===(a=this.config.landing)||void 0===a?void 0:a.modeCardBorderColor)||"#E2E8F0","; \n border-radius: 20px; \n padding: 20px 12px; \n cursor: pointer; \n display: flex; \n flex-direction: column; \n align-items: center; \n gap: 8px; \n transition: transform ").concat(h.duration,"s ease, box-shadow ").concat(h.duration,"s ease, border-color ").concat(h.duration,"s ease; \n box-shadow: 0 4px 12px rgba(0,0,0,0.05); \n }\n .mode-card:hover { \n transform: translateY(-6px); \n box-shadow: 0 12px 24px rgba(102, 126, 234, 0.2); \n border-color: ").concat((null===(c=this.config.landing)||void 0===c?void 0:c.modeCardHoverBorderColor)||m,"; \n }\n .mode-card-icon { \n width: 60px; \n height: 60px; \n display: flex; \n align-items: center; \n justify-content: center; \n border-radius: 50%; \n background: ").concat((null===(s=this.config.landing)||void 0===s?void 0:s.modeCardIconBackgroundColor)||m,"; \n color: #fff; \n font-size: 32px; \n }\n .mode-card-title { \n color: ").concat((null===(u=this.config.landing)||void 0===u?void 0:u.modeCardTitleColor)||"#111827","; \n font-weight: 600; \n text-align: center;\n width: 100%;\n }\n\n ").concat(g?this.voiceInterface.generateCSS():"","\n ").concat(y?this.textInterface.generateCSS():"","\n \n #text-chat-send-hint {\n text-align: center;\n line-height: 1.4;\n }\n \n .agent-thinking {\n font-style: italic;\n color: #6B7280;\n }\n ")}},{key:"setupWidgetEvents",value:function(){var e=this,t=document.getElementById("text-chat-button");t&&(t.onclick=function(){return e.togglePanel()});var n=document.getElementById("closeBtn");n&&(n.onclick=function(){return e.togglePanel()});var o=this.config.behavior.mode||"unified",r="unified"===o,i="unified"===o||"voice-only"===o,a="unified"===o||"text-only"===o,c=document.getElementById("backBtn"),s=document.getElementById("landingScreen"),u=document.getElementById("mode-card-voice"),l=document.getElementById("mode-card-text"),d=document.getElementById("textInterface"),p=document.getElementById("voiceInterface");c&&(c.onclick=function(){return e.showLanding()}),r?(u&&(u.onclick=function(){return e.showVoice()}),l&&(l.onclick=function(){return e.showText()}),"text"===this.currentView?(s&&s.classList.remove("active"),d&&d.classList.add("active"),p&&p.classList.remove("active"),c&&"unified"===o&&c.classList.add("visible"),f&&(f.style.display="")):"voice"===this.currentView?(s&&s.classList.remove("active"),d&&d.classList.remove("active"),p&&p.classList.add("active"),c&&"unified"===o&&c.classList.add("visible"),f&&(f.style.display="none")):(this.currentView="landing",s&&s.classList.add("active"),d&&d.classList.remove("active"),p&&p.classList.remove("active"),c&&"unified"===o&&c.classList.remove("visible"))):"voice-only"===o?(p&&p.classList.add("active"),d&&d.classList.remove("active"),s&&s.classList.remove("active")):"text-only"===o&&(d&&d.classList.add("active"),p&&p.classList.remove("active"),s&&s.classList.remove("active")),i&&(console.log("⚙️ Setting up voice interface event handlers"),this.voiceInterface.setupEventHandlers()),a&&(console.log("⚙️ Setting up text interface event handlers"),this.textInterface.setupEventHandlers());var f=document.getElementById("newChatBtn");f&&(f.onclick=function(){return e.textInterface.startNewChat()},r&&(f.style.display="none")),this.config.accessibility.keyboardNavigation&&this.setupKeyboardNavigation()}},{key:"startNewChat",value:function(){this.textInterface.startNewChat()}},{key:"showLanding",value:function(){if("unified"===(this.config.behavior.mode||"unified")){this.currentView="landing";var e=document.getElementById("landingScreen"),t=document.getElementById("textInterface"),n=document.getElementById("voiceInterface"),o=document.getElementById("backBtn"),r=document.getElementById("newChatBtn");e&&e.classList.add("active"),t&&t.classList.remove("active"),n&&n.classList.remove("active"),o&&o.classList.remove("visible"),r&&(r.style.display="none")}}},{key:"showText",value:function(){this.currentView="text";var e=document.getElementById("landingScreen"),t=document.getElementById("voiceInterface"),n=document.getElementById("backBtn"),o=document.getElementById("newChatBtn");e&&e.classList.remove("active"),t&&t.classList.remove("active"),this.textInterface.show();var r=this.config.behavior.mode||"unified";n&&"unified"===r&&n.classList.add("visible"),o&&(o.style.display="")}},{key:"showVoice",value:function(){this.currentView="voice";var e=document.getElementById("landingScreen"),t=document.getElementById("textInterface"),n=document.getElementById("voiceInterface"),o=document.getElementById("backBtn"),r=document.getElementById("newChatBtn");e&&e.classList.remove("active"),t&&t.classList.remove("active"),n&&n.classList.add("active");var i=this.config.behavior.mode||"unified";o&&"unified"===i&&o.classList.add("visible"),r&&(r.style.display="none")}},{key:"setupKeyboardNavigation",value:function(){var e=this;document.addEventListener("keydown",function(t){"Escape"===t.key&&e.isOpen&&e.togglePanel()})}},{key:"togglePanel",value:function(){this.isOpen=!this.isOpen,document.getElementById("text-chat-panel").classList.toggle("open"),this.isOpen&&setTimeout(function(){var e=document.getElementById("messageInput");e&&e.focus()},100),this.isOpen&&!this.isActive&&this.config.behavior.autoConnect&&this.startChat()}},{key:"startChat",value:(i=uo(ao().m(function e(){return ao().w(function(e){for(;;)switch(e.n){case 0:this.isActive=!0,this.textInterface.setActive(!0);case 1:return e.a(2)}},e,this)})),function(){return i.apply(this,arguments)})},{key:"sendMessage",value:(r=uo(ao().m(function e(){return ao().w(function(e){for(;;)switch(e.n){case 0:return e.n=1,this.textInterface.sendMessage();case 1:return e.a(2)}},e,this)})),function(){return r.apply(this,arguments)})},{key:"updateSendButtonState",value:function(){this.textInterface.updateSendButtonState()}},{key:"getSignedUrl",value:(o=uo(ao().m(function e(){var t,n,o,r,i,a,c;return ao().w(function(e){for(;;)switch(e.n){case 0:if(this.config.getSessionUrl){e.n=2;break}if(this.config.agentId){e.n=1;break}throw new Error("agentId is required");case 1:return t=this.config.websocketUrl||"wss://backend.talktopc.com/ws/conv",(n=new URLSearchParams).append("agentId",this.config.agentId),this.config.appId&&n.append("appId",this.config.appId),!1!==this.config.demo&&n.append("demo","true"),e.a(2,"".concat(t,"?").concat(n.toString()));case 2:if("string"!=typeof this.config.getSessionUrl){e.n=6;break}return o={agentId:this.config.agentId,variables:this.config.variables||{}},this.config.appId&&(o.appId=this.config.appId),e.n=3,fetch(this.config.getSessionUrl,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)});case 3:if((r=e.v).ok){e.n=4;break}throw new Error("Failed to get session URL: ".concat(r.statusText));case 4:return e.n=5,r.json();case 5:return i=e.v,e.a(2,i.signedUrl||i.wsUrl||i.url);case 6:if("function"!=typeof this.config.getSessionUrl){e.n=8;break}return a={agentId:this.config.agentId,variables:this.config.variables||{}},this.config.appId&&(a.appId=this.config.appId),e.n=7,this.config.getSessionUrl(a);case 7:return c=e.v,e.a(2,"string"==typeof c?c:c.signedUrl||c.wsUrl||c.url);case 8:throw new Error("getSessionUrl must be a string (backend URL), a function, or omitted (for direct connection with agentId/appId)");case 9:return e.a(2)}},e,this)})),function(){return o.apply(this,arguments)})},{key:"addMessage",value:function(e,t){this.textInterface.addMessage(e,t)}},{key:"beginStreaming",value:function(){this.textInterface.beginStreaming()}},{key:"appendStreamingChunk",value:function(e){this.textInterface.appendStreamingChunk(e)}},{key:"finalizeStreaming",value:function(e){this.textInterface.finalizeStreaming(e)}},{key:"stopStreamingState",value:function(){this.textInterface.stopStreamingState()}},{key:"showError",value:function(e){this.textInterface.showError(e)}},{key:"updateStatus",value:function(e){}},{key:"updateConfig",value:function(e){var t,n,o,r,i,a,c,s,u,l=fo({},this.config);e.panel&&(l.panel=fo(fo({},this.config.panel),e.panel)),e.voice&&(l.voice=fo(fo({},this.config.voice),e.voice),e.voice.micButtonHint&&(l.voice.micButtonHint=fo(fo({},null===(s=this.config.voice)||void 0===s?void 0:s.micButtonHint),e.voice.micButtonHint))),e.text&&(l.text=fo(fo({},this.config.text),e.text),e.text.sendButtonHint&&(l.text.sendButtonHint=fo(fo({},null===(u=this.config.text)||void 0===u?void 0:u.sendButtonHint),e.text.sendButtonHint))),void 0!==e.language&&(l.language=e.language),void 0!==e.language&&(["he","ar"].includes(e.language)?l.direction="rtl":void 0===e.direction&&(l.direction="ltr")),e.translations&&(l.translations=e.translations,this.translations=e.translations),e.button&&(l.button=fo(fo({},this.config.button),e.button)),e.header&&(l.header=fo(fo({},this.config.header),e.header)),e.icon&&(l.icon=fo(fo({},this.config.icon),e.icon)),e.messages&&(l.messages=fo(fo({},this.config.messages),e.messages)),e.animation&&(l.animation=fo(fo({},this.config.animation),e.animation)),e.behavior&&(l.behavior=fo(fo({},this.config.behavior),e.behavior)),e.accessibility&&(l.accessibility=fo(fo({},this.config.accessibility),e.accessibility)),e.tooltips&&(l.tooltips=fo(fo({},this.config.tooltips),e.tooltips)),e.landing&&(l.landing=fo(fo({},this.config.landing),e.landing)),void 0!==e.direction&&void 0===l.direction&&(l.direction=e.direction),void 0!==e.primaryColor&&(l.primaryColor=e.primaryColor),l.onConversationStart=void 0!==e.onConversationStart?e.onConversationStart:this.config.onConversationStart,l.onConversationEnd=void 0!==e.onConversationEnd?e.onConversationEnd:this.config.onConversationEnd,l.onBargeIn=void 0!==e.onBargeIn?e.onBargeIn:this.config.onBargeIn,l.onAudioStartPlaying=void 0!==e.onAudioStartPlaying?e.onAudioStartPlaying:this.config.onAudioStartPlaying,l.onAudioStoppedPlaying=void 0!==e.onAudioStoppedPlaying?e.onAudioStoppedPlaying:this.config.onAudioStoppedPlaying,l.onSubtitleDisplay=void 0!==e.onSubtitleDisplay?e.onSubtitleDisplay:this.config.onSubtitleDisplay,Object.keys(e).forEach(function(t){["panel","button","header","icon","messages","direction","voice","text","animation","behavior","accessibility","language","tooltips","landing","primaryColor","onConversationStart","onConversationEnd","onBargeIn","onAudioStartPlaying","onAudioStoppedPlaying","onSubtitleDisplay"].includes(t)||(l[t]=e[t])}),null===(t=this.config)||void 0===t||t.language,this.config=this.mergeWithDefaults(l);var d=this.config.language||"en",p=fo(fo(fo({},this.config),this.config.voice),{},{language:d,websocketUrl:(null===(n=this.config.voice)||void 0===n?void 0:n.websocketUrl)||this.config.websocketUrl||"wss://speech.talktopc.com/ws/conv",translations:this.translations,outputContainer:(null===(o=this.config.voice)||void 0===o?void 0:o.outputContainer)||"raw",outputEncoding:(null===(r=this.config.voice)||void 0===r?void 0:r.outputEncoding)||"pcm",outputSampleRate:(null===(i=this.config.voice)||void 0===i?void 0:i.outputSampleRate)||44100,outputChannels:(null===(a=this.config.voice)||void 0===a?void 0:a.outputChannels)||1,outputBitDepth:(null===(c=this.config.voice)||void 0===c?void 0:c.outputBitDepth)||16,onConversationStart:this.config.onConversationStart,onConversationEnd:this.config.onConversationEnd,onBargeIn:this.config.onBargeIn,onAudioStartPlaying:this.config.onAudioStartPlaying,onAudioStoppedPlaying:this.config.onAudioStoppedPlaying,onSubtitleDisplay:this.config.onSubtitleDisplay});this.voiceInterface=new Yn(p);var f=fo(fo(fo({},this.config),this.config.text),{},{language:d,translations:this.translations});this.textInterface=new ro(f,this.sdk);var h=document.getElementById("text-chat-widget");h&&h.remove(),this.createWidget(),this.textInterface&&this.textInterface.updateInputAttributes&&this.textInterface.updateInputAttributes()}},{key:"destroy",value:function(){var e=document.getElementById("text-chat-widget");e&&e.remove(),this.sdk&&this.sdk.destroy(),this.voiceInterface&&this.voiceInterface.destroy()}},{key:"startVoiceCall",value:(n=uo(ao().m(function e(){return ao().w(function(e){for(;;)switch(e.n){case 0:return e.n=1,this.voiceInterface.startVoiceCall();case 1:return e.a(2)}},e,this)})),function(){return n.apply(this,arguments)})},{key:"endVoiceCall",value:function(){this.voiceInterface.endVoiceCall()}},{key:"toggleMute",value:function(){this.voiceInterface.toggleMute()}},{key:"toggleSpeaker",value:function(){this.voiceInterface.toggleSpeaker()}}],t&&vo(e.prototype,t),Object.defineProperty(e,"prototype",{writable:!1}),e;var e,t,n,o,r,i}(),mo="2.4.20";const bo={VoiceSDK:he,VoiceSDK_v2:Xt,TextChatSDK:pn,WebSocketManager:j,AudioRecorder:z,AudioPlayer:ee,EventEmitter:c,VoiceButton:kn,VanillaVoiceButton:Bn,AgentSDK:Kn,TTPChatWidget:yo,VERSION:mo};return o})());
|
|
2
|
+
!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.TTPAgentSDK=t():e.TTPAgentSDK=t()}(window,()=>(()=>{"use strict";var e={540:(e,t,n)=>{e.exports=n(869)},698:(e,t)=>{var n=Symbol.for("react.transitional.element");function o(e,t,o){var r=null;if(void 0!==o&&(r=""+o),void 0!==t.key&&(r=""+t.key),"key"in t)for(var i in o={},t)"key"!==i&&(o[i]=t[i]);else o=t;return t=o.ref,{$$typeof:n,type:e,key:r,ref:void 0!==t?t:null,props:o}}Symbol.for("react.fragment"),t.jsx=o,t.jsxs=o},848:(e,t,n)=>{e.exports=n(698)},869:(e,t)=>{Symbol.for("react.transitional.element"),Symbol.for("react.portal"),Symbol.for("react.fragment"),Symbol.for("react.strict_mode"),Symbol.for("react.profiler"),Symbol.for("react.consumer"),Symbol.for("react.context"),Symbol.for("react.forward_ref"),Symbol.for("react.suspense"),Symbol.for("react.memo"),Symbol.for("react.lazy"),Symbol.for("react.activity"),Symbol.iterator;var n={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},o=Object.assign,r={};function i(e,t,o){this.props=e,this.context=t,this.refs=r,this.updater=o||n}function a(){}function c(e,t,o){this.props=e,this.context=t,this.refs=r,this.updater=o||n}i.prototype.isReactComponent={},i.prototype.setState=function(e,t){if("object"!=typeof e&&"function"!=typeof e&&null!=e)throw Error("takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,e,t,"setState")},i.prototype.forceUpdate=function(e){this.updater.enqueueForceUpdate(this,e,"forceUpdate")},a.prototype=i.prototype;var s=c.prototype=new a;s.constructor=c,o(s,i.prototype),s.isPureReactComponent=!0;Array.isArray;var u={H:null,A:null,T:null,S:null};Object.prototype.hasOwnProperty;"function"==typeof reportError&&reportError;t.useEffect=function(e,t){return u.H.useEffect(e,t)},t.useRef=function(e){return u.H.useRef(e)},t.useState=function(e){return u.H.useState(e)}}},t={};function n(o){var r=t[o];if(void 0!==r)return r.exports;var i=t[o]={exports:{}};return e[o](i,i.exports,n),i.exports}n.d=(e,t)=>{for(var o in t)n.o(t,o)&&!n.o(e,o)&&Object.defineProperty(e,o,{enumerable:!0,get:t[o]})},n.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),n.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};var o={};function r(e){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},r(e)}function i(e,t){for(var n=0;n<t.length;n++){var o=t[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(e,a(o.key),o)}}function a(e){var t=function(e){if("object"!=r(e)||!e)return e;var t=e[Symbol.toPrimitive];if(void 0!==t){var n=t.call(e,"string");if("object"!=r(n))return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}(e);return"symbol"==r(t)?t:t+""}n.r(o),n.d(o,{AgentSDK:()=>Ln,AudioPlayer:()=>ee,AudioRecorder:()=>z,EventEmitter:()=>c,TTPChatWidget:()=>yo,TextChatSDK:()=>pn,VERSION:()=>mo,VanillaVoiceButton:()=>Bn,VoiceButton:()=>kn,VoiceSDK:()=>he,VoiceSDK_v2:()=>Xt,WebSocketManager:()=>j,default:()=>bo});var c=function(){return e=function e(){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),this.events={}},t=[{key:"on",value:function(e,t){this.events[e]||(this.events[e]=[]),this.events[e].push(t)}},{key:"off",value:function(e,t){this.events[e]&&(this.events[e]=this.events[e].filter(function(e){return e!==t}))}},{key:"emit",value:function(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),o=1;o<t;o++)n[o-1]=arguments[o];this.events[e]&&this.events[e].forEach(function(t){try{t.apply(void 0,n)}catch(t){console.error("Error in event listener for ".concat(e,":"),t)}})}},{key:"removeAllListeners",value:function(e){e?delete this.events[e]:this.events={}}}],t&&i(e.prototype,t),Object.defineProperty(e,"prototype",{writable:!1}),e;var e,t}();function s(e){return s="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},s(e)}function u(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var n=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=n){var o,r,i,a,c=[],s=!0,u=!1;try{if(i=(n=n.call(e)).next,0===t){if(Object(n)!==n)return;s=!1}else for(;!(s=(o=i.call(n)).done)&&(c.push(o.value),c.length!==t);s=!0);}catch(e){u=!0,r=e}finally{try{if(!s&&null!=n.return&&(a=n.return(),Object(a)!==a))return}finally{if(u)throw r}}return c}}(e,t)||d(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function l(e,t){var n="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!n){if(Array.isArray(e)||(n=d(e))||t&&e&&"number"==typeof e.length){n&&(e=n);var o=0,r=function(){};return{s:r,n:function(){return o>=e.length?{done:!0}:{done:!1,value:e[o++]}},e:function(e){throw e},f:r}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var i,a=!0,c=!1;return{s:function(){n=n.call(e)},n:function(){var e=n.next();return a=e.done,e},e:function(e){c=!0,i=e},f:function(){try{a||null==n.return||n.return()}finally{if(c)throw i}}}}function d(e,t){if(e){if("string"==typeof e)return p(e,t);var n={}.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?p(e,t):void 0}}function p(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,o=Array(t);n<t;n++)o[n]=e[n];return o}function f(){var e,t,n="function"==typeof Symbol?Symbol:{},o=n.iterator||"@@iterator",r=n.toStringTag||"@@toStringTag";function i(n,o,r,i){var s=o&&o.prototype instanceof c?o:c,u=Object.create(s.prototype);return h(u,"_invoke",function(n,o,r){var i,c,s,u=0,l=r||[],d=!1,p={p:0,n:0,v:e,a:f,f:f.bind(e,4),d:function(t,n){return i=t,c=0,s=e,p.n=n,a}};function f(n,o){for(c=n,s=o,t=0;!d&&u&&!r&&t<l.length;t++){var r,i=l[t],f=p.p,h=i[2];n>3?(r=h===o)&&(s=i[(c=i[4])?5:(c=3,3)],i[4]=i[5]=e):i[0]<=f&&((r=n<2&&f<i[1])?(c=0,p.v=o,p.n=i[1]):f<h&&(r=n<3||i[0]>o||o>h)&&(i[4]=n,i[5]=o,p.n=h,c=0))}if(r||n>1)return a;throw d=!0,o}return function(r,l,h){if(u>1)throw TypeError("Generator is already running");for(d&&1===l&&f(l,h),c=l,s=h;(t=c<2?e:s)||!d;){i||(c?c<3?(c>1&&(p.n=-1),f(c,s)):p.n=s:p.v=s);try{if(u=2,i){if(c||(r="next"),t=i[r]){if(!(t=t.call(i,s)))throw TypeError("iterator result is not an object");if(!t.done)return t;s=t.value,c<2&&(c=0)}else 1===c&&(t=i.return)&&t.call(i),c<2&&(s=TypeError("The iterator does not provide a '"+r+"' method"),c=1);i=e}else if((t=(d=p.n<0)?s:n.call(o,p))!==a)break}catch(t){i=e,c=1,s=t}finally{u=1}}return{value:t,done:d}}}(n,r,i),!0),u}var a={};function c(){}function s(){}function u(){}t=Object.getPrototypeOf;var l=[][o]?t(t([][o]())):(h(t={},o,function(){return this}),t),d=u.prototype=c.prototype=Object.create(l);function p(e){return Object.setPrototypeOf?Object.setPrototypeOf(e,u):(e.__proto__=u,h(e,r,"GeneratorFunction")),e.prototype=Object.create(d),e}return s.prototype=u,h(d,"constructor",u),h(u,"constructor",s),s.displayName="GeneratorFunction",h(u,r,"GeneratorFunction"),h(d),h(d,r,"Generator"),h(d,o,function(){return this}),h(d,"toString",function(){return"[object Generator]"}),(f=function(){return{w:i,m:p}})()}function h(e,t,n,o){var r=Object.defineProperty;try{r({},"",{})}catch(e){r=0}h=function(e,t,n,o){function i(t,n){h(e,t,function(e){return this._invoke(t,n,e)})}t?r?r(e,t,{value:n,enumerable:!o,configurable:!o,writable:!o}):e[t]=n:(i("next",0),i("throw",1),i("return",2))},h(e,t,n,o)}function v(e,t,n,o,r,i,a){try{var c=e[i](a),s=c.value}catch(e){return void n(e)}c.done?t(s):Promise.resolve(s).then(o,r)}function g(e,t){for(var n=0;n<t.length;n++){var o=t[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(e,y(o.key),o)}}function y(e){var t=function(e){if("object"!=s(e)||!e)return e;var t=e[Symbol.toPrimitive];if(void 0!==t){var n=t.call(e,"string");if("object"!=s(n))return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}(e);return"symbol"==s(t)?t:t+""}function m(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(e){}return(m=function(){return!!e})()}function b(e){return b=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(e){return e.__proto__||Object.getPrototypeOf(e)},b(e)}function S(e,t){return S=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,t){return e.__proto__=t,e},S(e,t)}const w=new(function(e){function t(){var e;return function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,t),(e=function(e,t,n){return t=b(t),function(e,t){if(t&&("object"==s(t)||"function"==typeof t))return t;if(void 0!==t)throw new TypeError("Derived constructors may only return object or undefined");return function(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}(e)}(e,m()?Reflect.construct(t,n||[],b(e).constructor):t.apply(e,n))}(this,t)).connections=new Map,e.connectionCounts=new Map,e.creatingConnections=new Set,e}return function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&S(e,t)}(t,e),n=t,o=[{key:"getConnection",value:(r=f().m(function e(t){var n,o,r=this;return f().w(function(e){for(;;)switch(e.n){case 0:if(!this.connections.has(t)){e.n=1;break}return n=this.connections.get(t),this.connectionCounts.set(t,(this.connectionCounts.get(t)||0)+1),e.a(2,n);case 1:if(!this.creatingConnections||!this.creatingConnections.has(t)){e.n=2;break}return e.a(2,new Promise(function(e){var n=function(){if(r.connections.has(t)){var o=r.connections.get(t);r.connectionCounts.set(t,(r.connectionCounts.get(t)||0)+1),e(o)}else setTimeout(n,50)};n()}));case 2:return this.creatingConnections.add(t),o=new WebSocket(t),this.connections.set(t,o),this.connectionCounts.set(t,1),o.addEventListener("open",function(e){r.creatingConnections.delete(t),r.emit("open",e,t)}),o.addEventListener("close",function(e){r.creatingConnections.delete(t),r.connections.delete(t),r.connectionCounts.delete(t),r.emit("close",e,t)}),o.addEventListener("error",function(e){r.creatingConnections.delete(t),r.emit("error",e,t)}),o.addEventListener("message",function(e){r.emit("message",e,t)}),e.a(2,o)}},e,this)}),i=function(){var e=this,t=arguments;return new Promise(function(n,o){var i=r.apply(e,t);function a(e){v(i,n,o,a,c,"next",e)}function c(e){v(i,n,o,a,c,"throw",e)}a(void 0)})},function(e){return i.apply(this,arguments)})},{key:"releaseConnection",value:function(e){if(this.connections.has(e)){var t=this.connectionCounts.get(e)||0,n=Math.max(0,t-1);if(this.connectionCounts.set(e,n),0===n){var o=this.connections.get(e);o&&o.readyState===WebSocket.OPEN&&o.close(1e3,"No more subscribers"),this.connections.delete(e),this.connectionCounts.delete(e)}}}},{key:"forceClose",value:function(e){if(this.connections.has(e)){var t=this.connections.get(e);t&&t.readyState===WebSocket.OPEN&&t.close(1e3,"Force close"),this.connections.delete(e),this.connectionCounts.delete(e)}}},{key:"getConnectionStatus",value:function(e){return this.connections.has(e)?{exists:!0,readyState:this.connections.get(e).readyState,subscribers:this.connectionCounts.get(e)||0}:{exists:!1,readyState:null,subscribers:0}}},{key:"getAllConnections",value:function(){var e,t={},n=l(this.connections.entries());try{for(n.s();!(e=n.n()).done;){var o=u(e.value,2),r=o[0],i=o[1];t[r]={readyState:i.readyState,subscribers:this.connectionCounts.get(r)||0}}}catch(e){n.e(e)}finally{n.f()}return t}},{key:"clearAll",value:function(){var e,t=l(this.connections.entries());try{for(t.s();!(e=t.n()).done;){var n=u(e.value,2),o=(n[0],n[1]);o&&o.readyState===WebSocket.OPEN&&o.close(1e3,"Clear all")}}catch(e){t.e(e)}finally{t.f()}this.connections.clear(),this.connectionCounts.clear(),this.creatingConnections.clear()}}],o&&g(n.prototype,o),Object.defineProperty(n,"prototype",{writable:!1}),n;var n,o,r,i}(c));function x(e){return x="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},x(e)}function C(){var e,t,n="function"==typeof Symbol?Symbol:{},o=n.iterator||"@@iterator",r=n.toStringTag||"@@toStringTag";function i(n,o,r,i){var s=o&&o.prototype instanceof c?o:c,u=Object.create(s.prototype);return k(u,"_invoke",function(n,o,r){var i,c,s,u=0,l=r||[],d=!1,p={p:0,n:0,v:e,a:f,f:f.bind(e,4),d:function(t,n){return i=t,c=0,s=e,p.n=n,a}};function f(n,o){for(c=n,s=o,t=0;!d&&u&&!r&&t<l.length;t++){var r,i=l[t],f=p.p,h=i[2];n>3?(r=h===o)&&(s=i[(c=i[4])?5:(c=3,3)],i[4]=i[5]=e):i[0]<=f&&((r=n<2&&f<i[1])?(c=0,p.v=o,p.n=i[1]):f<h&&(r=n<3||i[0]>o||o>h)&&(i[4]=n,i[5]=o,p.n=h,c=0))}if(r||n>1)return a;throw d=!0,o}return function(r,l,h){if(u>1)throw TypeError("Generator is already running");for(d&&1===l&&f(l,h),c=l,s=h;(t=c<2?e:s)||!d;){i||(c?c<3?(c>1&&(p.n=-1),f(c,s)):p.n=s:p.v=s);try{if(u=2,i){if(c||(r="next"),t=i[r]){if(!(t=t.call(i,s)))throw TypeError("iterator result is not an object");if(!t.done)return t;s=t.value,c<2&&(c=0)}else 1===c&&(t=i.return)&&t.call(i),c<2&&(s=TypeError("The iterator does not provide a '"+r+"' method"),c=1);i=e}else if((t=(d=p.n<0)?s:n.call(o,p))!==a)break}catch(t){i=e,c=1,s=t}finally{u=1}}return{value:t,done:d}}}(n,r,i),!0),u}var a={};function c(){}function s(){}function u(){}t=Object.getPrototypeOf;var l=[][o]?t(t([][o]())):(k(t={},o,function(){return this}),t),d=u.prototype=c.prototype=Object.create(l);function p(e){return Object.setPrototypeOf?Object.setPrototypeOf(e,u):(e.__proto__=u,k(e,r,"GeneratorFunction")),e.prototype=Object.create(d),e}return s.prototype=u,k(d,"constructor",u),k(u,"constructor",s),s.displayName="GeneratorFunction",k(u,r,"GeneratorFunction"),k(d),k(d,r,"Generator"),k(d,o,function(){return this}),k(d,"toString",function(){return"[object Generator]"}),(C=function(){return{w:i,m:p}})()}function k(e,t,n,o){var r=Object.defineProperty;try{r({},"",{})}catch(e){r=0}k=function(e,t,n,o){function i(t,n){k(e,t,function(e){return this._invoke(t,n,e)})}t?r?r(e,t,{value:n,enumerable:!o,configurable:!o,writable:!o}):e[t]=n:(i("next",0),i("throw",1),i("return",2))},k(e,t,n,o)}function P(e,t,n,o,r,i,a){try{var c=e[i](a),s=c.value}catch(e){return void n(e)}c.done?t(s):Promise.resolve(s).then(o,r)}function O(e,t){for(var n=0;n<t.length;n++){var o=t[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(e,E(o.key),o)}}function E(e){var t=function(e){if("object"!=x(e)||!e)return e;var t=e[Symbol.toPrimitive];if(void 0!==t){var n=t.call(e,"string");if("object"!=x(n))return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}(e);return"symbol"==x(t)?t:t+""}function T(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(e){}return(T=function(){return!!e})()}function A(e){return A=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(e){return e.__proto__||Object.getPrototypeOf(e)},A(e)}function I(e,t){return I=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,t){return e.__proto__=t,e},I(e,t)}var j=function(e){function t(e){var n;return function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,t),(n=function(e,t,n){return t=A(t),function(e,t){if(t&&("object"==x(t)||"function"==typeof t))return t;if(void 0!==t)throw new TypeError("Derived constructors may only return object or undefined");return function(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}(e)}(e,T()?Reflect.construct(t,n||[],A(e).constructor):t.apply(e,n))}(this,t)).config=e,n.ws=null,n.isConnected=!1,n.connectionId=null,n}return function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&I(e,t)}(t,e),n=t,o=[{key:"connect",value:(i=C().m(function e(){var t=this;return C().w(function(e){for(;;)if(0===e.n)return e.a(2,new Promise(function(e,n){try{t.connectionId=Date.now()+"_"+Math.random().toString(36).substr(2,9),t.connectResolve=e,t.connectReject=n,w.getConnection(t.config.websocketUrl,t.config).then(function(n){t.ws=n,t.setupEventListeners(),n.readyState===WebSocket.OPEN&&(t.isConnected=!0,t.emit("connected"),e(),t.connectResolve=null,t.connectReject=null)}).catch(function(e){console.error("🔌 WebSocketManager: Connection failed ".concat(t.connectionId),e),n(e),t.connectResolve=null,t.connectReject=null})}catch(e){console.error("🔌 WebSocketManager: Connection error ".concat(t.connectionId),e),n(e),t.connectResolve=null,t.connectReject=null}}))},e)}),a=function(){var e=this,t=arguments;return new Promise(function(n,o){var r=i.apply(e,t);function a(e){P(r,n,o,a,c,"next",e)}function c(e){P(r,n,o,a,c,"throw",e)}a(void 0)})},function(){return a.apply(this,arguments)})},{key:"setupEventListeners",value:function(){var e=this;if(this.ws){var t=function(t,n){n===e.config.websocketUrl&&(e.isConnected=!0,e.emit("connected"),e.connectResolve&&(e.connectResolve(),e.connectResolve=null,e.connectReject=null))},n=function(t,n){n===e.config.websocketUrl&&(e.isConnected=!1,e.emit("disconnected",t))},o=function(t,n){n===e.config.websocketUrl&&(e.emit("error",t),e.connectReject&&(e.connectReject(t),e.connectResolve=null,e.connectReject=null))},r=function(t,n){n===e.config.websocketUrl&&e.handleMessage(t)};w.on("open",t),w.on("close",n),w.on("error",o),w.on("message",r),this.eventHandlers={open:t,close:n,error:o,message:r}}}},{key:"disconnect",value:function(){this.eventHandlers&&(w.off("open",this.eventHandlers.open),w.off("close",this.eventHandlers.close),w.off("error",this.eventHandlers.error),w.off("message",this.eventHandlers.message)),this.config.websocketUrl&&w.releaseConnection(this.config.websocketUrl),this.ws=null,this.isConnected=!1}},{key:"sendMessage",value:function(e){if(this.isConnected&&this.ws)try{this.ws.send(JSON.stringify(e))}catch(e){console.warn("🔌 WebSocketManager: Failed to send message:",e.message)}}},{key:"sendBinary",value:function(e){if(this.isConnected&&this.ws)try{this.ws.send(e)}catch(e){console.warn("🔌 WebSocketManager: Failed to send binary data:",e.message)}}},{key:"handleMessage",value:function(e){var t=this;if(e.data instanceof ArrayBuffer)this.emit("binaryAudio",e.data);else if(e.data instanceof Blob)e.data.arrayBuffer().then(function(e){t.emit("binaryAudio",e)}).catch(function(e){console.error("🔌 WebSocketManager: Error converting Blob to ArrayBuffer:",e)});else try{var n=JSON.parse(e.data);"barge_in_ack"!==n.t&&"stop_sending"!==n.t||this.emit("bargeIn",n),"stop_playing"===n.t&&this.emit("stopPlaying",n),this.emit("message",n)}catch(e){this.emit("error",e)}}},{key:"getStatus",value:function(){return{isConnected:this.isConnected,readyState:this.ws?this.ws.readyState:null,connectionId:this.connectionId}}}],r=[{key:"getSingletonStatus",value:function(){return w.getAllConnections()}},{key:"clearAllConnections",value:function(){w.clearAll()}}],o&&O(n.prototype,o),r&&O(n,r),Object.defineProperty(n,"prototype",{writable:!1}),n;var n,o,r,i,a}(c);function D(e){return D="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},D(e)}function F(){var e,t,n="function"==typeof Symbol?Symbol:{},o=n.iterator||"@@iterator",r=n.toStringTag||"@@toStringTag";function i(n,o,r,i){var s=o&&o.prototype instanceof c?o:c,u=Object.create(s.prototype);return B(u,"_invoke",function(n,o,r){var i,c,s,u=0,l=r||[],d=!1,p={p:0,n:0,v:e,a:f,f:f.bind(e,4),d:function(t,n){return i=t,c=0,s=e,p.n=n,a}};function f(n,o){for(c=n,s=o,t=0;!d&&u&&!r&&t<l.length;t++){var r,i=l[t],f=p.p,h=i[2];n>3?(r=h===o)&&(s=i[(c=i[4])?5:(c=3,3)],i[4]=i[5]=e):i[0]<=f&&((r=n<2&&f<i[1])?(c=0,p.v=o,p.n=i[1]):f<h&&(r=n<3||i[0]>o||o>h)&&(i[4]=n,i[5]=o,p.n=h,c=0))}if(r||n>1)return a;throw d=!0,o}return function(r,l,h){if(u>1)throw TypeError("Generator is already running");for(d&&1===l&&f(l,h),c=l,s=h;(t=c<2?e:s)||!d;){i||(c?c<3?(c>1&&(p.n=-1),f(c,s)):p.n=s:p.v=s);try{if(u=2,i){if(c||(r="next"),t=i[r]){if(!(t=t.call(i,s)))throw TypeError("iterator result is not an object");if(!t.done)return t;s=t.value,c<2&&(c=0)}else 1===c&&(t=i.return)&&t.call(i),c<2&&(s=TypeError("The iterator does not provide a '"+r+"' method"),c=1);i=e}else if((t=(d=p.n<0)?s:n.call(o,p))!==a)break}catch(t){i=e,c=1,s=t}finally{u=1}}return{value:t,done:d}}}(n,r,i),!0),u}var a={};function c(){}function s(){}function u(){}t=Object.getPrototypeOf;var l=[][o]?t(t([][o]())):(B(t={},o,function(){return this}),t),d=u.prototype=c.prototype=Object.create(l);function p(e){return Object.setPrototypeOf?Object.setPrototypeOf(e,u):(e.__proto__=u,B(e,r,"GeneratorFunction")),e.prototype=Object.create(d),e}return s.prototype=u,B(d,"constructor",u),B(u,"constructor",s),s.displayName="GeneratorFunction",B(u,r,"GeneratorFunction"),B(d),B(d,r,"Generator"),B(d,o,function(){return this}),B(d,"toString",function(){return"[object Generator]"}),(F=function(){return{w:i,m:p}})()}function B(e,t,n,o){var r=Object.defineProperty;try{r({},"",{})}catch(e){r=0}B=function(e,t,n,o){function i(t,n){B(e,t,function(e){return this._invoke(t,n,e)})}t?r?r(e,t,{value:n,enumerable:!o,configurable:!o,writable:!o}):e[t]=n:(i("next",0),i("throw",1),i("return",2))},B(e,t,n,o)}function R(e,t,n,o,r,i,a){try{var c=e[i](a),s=c.value}catch(e){return void n(e)}c.done?t(s):Promise.resolve(s).then(o,r)}function _(e){return function(){var t=this,n=arguments;return new Promise(function(o,r){var i=e.apply(t,n);function a(e){R(i,o,r,a,c,"next",e)}function c(e){R(i,o,r,a,c,"throw",e)}a(void 0)})}}function U(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,o=Array(t);n<t;n++)o[n]=e[n];return o}function M(e,t){for(var n=0;n<t.length;n++){var o=t[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(e,N(o.key),o)}}function N(e){var t=function(e){if("object"!=D(e)||!e)return e;var t=e[Symbol.toPrimitive];if(void 0!==t){var n=t.call(e,"string");if("object"!=D(n))return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}(e);return"symbol"==D(t)?t:t+""}function V(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(e){}return(V=function(){return!!e})()}function K(e){return K=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(e){return e.__proto__||Object.getPrototypeOf(e)},K(e)}function L(e,t){return L=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,t){return e.__proto__=t,e},L(e,t)}var z=function(e){function t(e){var n;return function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,t),(n=function(e,t,n){return t=K(t),function(e,t){if(t&&("object"==D(t)||"function"==typeof t))return t;if(void 0!==t)throw new TypeError("Derived constructors may only return object or undefined");return function(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}(e)}(e,V()?Reflect.construct(t,n||[],K(e).constructor):t.apply(e,n))}(this,t)).config=e,n.audioContext=null,n.audioWorkletNode=null,n.mediaStream=null,n.isRecording=!1,n}return function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&L(e,t)}(t,e),n=t,o=[{key:"getAudioProcessorPath",value:function(){if(this.config.audioProcessorPath)return this.config.audioProcessorPath;var e,t=function(e,t){var n="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!n){if(Array.isArray(e)||(n=function(e,t){if(e){if("string"==typeof e)return U(e,t);var n={}.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?U(e,t):void 0}}(e))||t&&e&&"number"==typeof e.length){n&&(e=n);var o=0,r=function(){};return{s:r,n:function(){return o>=e.length?{done:!0}:{done:!1,value:e[o++]}},e:function(e){throw e},f:r}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var i,a=!0,c=!1;return{s:function(){n=n.call(e)},n:function(){var e=n.next();return a=e.done,e},e:function(e){c=!0,i=e},f:function(){try{a||null==n.return||n.return()}finally{if(c)throw i}}}}(document.getElementsByTagName("script"));try{for(t.s();!(e=t.n()).done;){var n=e.value.src;if(n&&(n.includes("agent-widget.js")||n.includes("ttp-agent-sdk")))try{new URL(n);var o=n.substring(0,n.lastIndexOf("/"));return"".concat(o,"/audio-processor.js")}catch(e){var r=n.substring(0,n.lastIndexOf("/"));return"".concat(r,"/audio-processor.js")}}}catch(e){t.e(e)}finally{t.f()}return"https://cdn.talktopc.com/audio-processor.js"}},{key:"start",value:(i=_(F().m(function e(){var t,n,o=this;return F().w(function(e){for(;;)switch(e.p=e.n){case 0:return e.p=0,e.n=1,navigator.mediaDevices.getUserMedia({audio:{sampleRate:this.config.sampleRate,channelCount:1,echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0}});case 1:if(this.mediaStream=e.v,this.audioContext=new(window.AudioContext||window.webkitAudioContext)({sampleRate:this.config.sampleRate}),"suspended"!==this.audioContext.state){e.n=2;break}return e.n=2,this.audioContext.resume();case 2:return t=this.getAudioProcessorPath(),e.n=3,this.audioContext.audioWorklet.addModule(t);case 3:this.audioWorkletNode=new AudioWorkletNode(this.audioContext,"audio-processor"),this.audioContext.createMediaStreamSource(this.mediaStream).connect(this.audioWorkletNode),this.audioWorkletNode.port.onmessage=function(e){var t=e.data,n=t.type,r=t.data;"pcm_audio_data"===n&&o.emit("audioData",r)},this.audioWorkletNode.port.postMessage({type:"setForceContinuous",data:{enabled:!0}}),this.isRecording=!0,this.emit("recordingStarted"),e.n=5;break;case 4:throw e.p=4,n=e.v,this.emit("error",n),n;case 5:return e.a(2)}},e,this,[[0,4]])})),function(){return i.apply(this,arguments)})},{key:"stop",value:(r=_(F().m(function e(){var t;return F().w(function(e){for(;;)switch(e.p=e.n){case 0:if(this.isRecording){e.n=1;break}return e.a(2);case 1:if(e.p=1,!this.audioWorkletNode){e.n=2;break}return this.audioWorkletNode.port.postMessage({type:"flush"}),e.n=2,new Promise(function(e){return setTimeout(e,100)});case 2:if(this.mediaStream&&(this.mediaStream.getTracks().forEach(function(e){return e.stop()}),this.mediaStream=null),!this.audioContext||"closed"===this.audioContext.state){e.n=4;break}return e.n=3,this.audioContext.close();case 3:this.audioContext=null;case 4:this.audioWorkletNode=null,this.isRecording=!1,this.emit("recordingStopped"),e.n=6;break;case 5:throw e.p=5,t=e.v,this.emit("error",t),t;case 6:return e.a(2)}},e,this,[[1,5]])})),function(){return r.apply(this,arguments)})},{key:"getStatus",value:function(){return{isRecording:this.isRecording,audioContextState:this.audioContext?this.audioContext.state:"closed"}}},{key:"destroy",value:function(){this.stop()}}],o&&M(n.prototype,o),Object.defineProperty(n,"prototype",{writable:!1}),n;var n,o,r,i}(c);function H(e){return H="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},H(e)}function W(){var e,t,n="function"==typeof Symbol?Symbol:{},o=n.iterator||"@@iterator",r=n.toStringTag||"@@toStringTag";function i(n,o,r,i){var s=o&&o.prototype instanceof c?o:c,u=Object.create(s.prototype);return G(u,"_invoke",function(n,o,r){var i,c,s,u=0,l=r||[],d=!1,p={p:0,n:0,v:e,a:f,f:f.bind(e,4),d:function(t,n){return i=t,c=0,s=e,p.n=n,a}};function f(n,o){for(c=n,s=o,t=0;!d&&u&&!r&&t<l.length;t++){var r,i=l[t],f=p.p,h=i[2];n>3?(r=h===o)&&(s=i[(c=i[4])?5:(c=3,3)],i[4]=i[5]=e):i[0]<=f&&((r=n<2&&f<i[1])?(c=0,p.v=o,p.n=i[1]):f<h&&(r=n<3||i[0]>o||o>h)&&(i[4]=n,i[5]=o,p.n=h,c=0))}if(r||n>1)return a;throw d=!0,o}return function(r,l,h){if(u>1)throw TypeError("Generator is already running");for(d&&1===l&&f(l,h),c=l,s=h;(t=c<2?e:s)||!d;){i||(c?c<3?(c>1&&(p.n=-1),f(c,s)):p.n=s:p.v=s);try{if(u=2,i){if(c||(r="next"),t=i[r]){if(!(t=t.call(i,s)))throw TypeError("iterator result is not an object");if(!t.done)return t;s=t.value,c<2&&(c=0)}else 1===c&&(t=i.return)&&t.call(i),c<2&&(s=TypeError("The iterator does not provide a '"+r+"' method"),c=1);i=e}else if((t=(d=p.n<0)?s:n.call(o,p))!==a)break}catch(t){i=e,c=1,s=t}finally{u=1}}return{value:t,done:d}}}(n,r,i),!0),u}var a={};function c(){}function s(){}function u(){}t=Object.getPrototypeOf;var l=[][o]?t(t([][o]())):(G(t={},o,function(){return this}),t),d=u.prototype=c.prototype=Object.create(l);function p(e){return Object.setPrototypeOf?Object.setPrototypeOf(e,u):(e.__proto__=u,G(e,r,"GeneratorFunction")),e.prototype=Object.create(d),e}return s.prototype=u,G(d,"constructor",u),G(u,"constructor",s),s.displayName="GeneratorFunction",G(u,r,"GeneratorFunction"),G(d),G(d,r,"Generator"),G(d,o,function(){return this}),G(d,"toString",function(){return"[object Generator]"}),(W=function(){return{w:i,m:p}})()}function G(e,t,n,o){var r=Object.defineProperty;try{r({},"",{})}catch(e){r=0}G=function(e,t,n,o){function i(t,n){G(e,t,function(e){return this._invoke(t,n,e)})}t?r?r(e,t,{value:n,enumerable:!o,configurable:!o,writable:!o}):e[t]=n:(i("next",0),i("throw",1),i("return",2))},G(e,t,n,o)}function q(e,t,n,o,r,i,a){try{var c=e[i](a),s=c.value}catch(e){return void n(e)}c.done?t(s):Promise.resolve(s).then(o,r)}function Q(e){return function(){var t=this,n=arguments;return new Promise(function(o,r){var i=e.apply(t,n);function a(e){q(i,o,r,a,c,"next",e)}function c(e){q(i,o,r,a,c,"throw",e)}a(void 0)})}}function J(e,t){for(var n=0;n<t.length;n++){var o=t[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(e,Y(o.key),o)}}function Y(e){var t=function(e){if("object"!=H(e)||!e)return e;var t=e[Symbol.toPrimitive];if(void 0!==t){var n=t.call(e,"string");if("object"!=H(n))return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}(e);return"symbol"==H(t)?t:t+""}function $(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(e){}return($=function(){return!!e})()}function X(e){return X=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(e){return e.__proto__||Object.getPrototypeOf(e)},X(e)}function Z(e,t){return Z=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,t){return e.__proto__=t,e},Z(e,t)}var ee=function(e){function t(e){var n;return function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,t),(n=function(e,t,n){return t=X(t),function(e,t){if(t&&("object"==H(t)||"function"==typeof t))return t;if(void 0!==t)throw new TypeError("Derived constructors may only return object or undefined");return function(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}(e)}(e,$()?Reflect.construct(t,n||[],X(e).constructor):t.apply(e,n))}(this,t)).config=e,n.audioContext=null,n.audioQueue=[],n.isPlaying=!1,n.isProcessingQueue=!1,n.currentSource=null,n.audioContextReady=!1,n.initializeAudioContext().catch(function(){}),n}return function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&Z(e,t)}(t,e),n=t,o=[{key:"initializeAudioContext",value:(i=Q(W().m(function e(){var t,n,o,r,i;return W().w(function(e){for(;;)switch(e.p=e.n){case 0:if(!this.audioContext||"closed"===this.audioContext.state){e.n=1;break}return e.a(2);case 1:if(e.p=1,t=this.config.sampleRate?{sampleRate:this.config.sampleRate}:{},this.audioContext=new(window.AudioContext||window.webkitAudioContext)(t),"suspended"!==this.audioContext.state){e.n=2;break}return e.n=2,this.audioContext.resume();case 2:if("running"===this.audioContext.state)try{n=this.audioContext.sampleRate,o=this.audioContext.createBuffer(1,.01*n,n),(r=this.audioContext.createBufferSource()).buffer=o,r.connect(this.audioContext.destination),r.start(0),r.stop(this.audioContext.currentTime+.01)}catch(e){console.debug("AudioPlayer: AudioContext warmup skipped:",e)}this.audioContextReady=!0,e.n=4;break;case 3:e.p=3,i=e.v,console.warn("AudioPlayer: Failed to pre-initialize AudioContext:",i),this.audioContextReady=!1;case 4:return e.a(2)}},e,this,[[1,3]])})),function(){return i.apply(this,arguments)})},{key:"playAudio",value:function(e){var t=this;try{var n=this.createAudioBlob(e);if(this.audioQueue.push(n),!this.isPlaying&&!this.isProcessingQueue&&!this.currentSource){var o=this.audioContextReady?0:50;setTimeout(function(){return t.processQueue()},o)}}catch(e){this.emit("playbackError",e)}}},{key:"createAudioBlob",value:function(e){var t=new Uint8Array(e);if(t.length>=4){if(82===t[0]&&73===t[1]&&70===t[2]&&70===t[3])return new Blob([e],{type:"audio/wav"});if(255===t[0]&&!(224&~t[1]))return new Blob([e],{type:"audio/mpeg"});if(79===t[0]&&103===t[1]&&103===t[2]&&83===t[3])return new Blob([e],{type:"audio/ogg"})}return new Blob([e],{type:"audio/wav"})}},{key:"processQueue",value:(r=Q(W().m(function e(){var t,n,o,r,i,a,c,s,u=this;return W().w(function(e){for(;;)switch(e.p=e.n){case 0:if(!this.isProcessingQueue&&0!==this.audioQueue.length){e.n=1;break}return e.a(2);case 1:if(this.isProcessingQueue=!0,t=this.audioQueue.shift()){e.n=2;break}return this.isProcessingQueue=!1,e.a(2);case 2:if(e.p=2,n=!this.isPlaying&&null===this.currentSource,this.audioContext&&"closed"!==this.audioContext.state){e.n=3;break}return e.n=3,this.initializeAudioContext();case 3:if("suspended"!==(o=this.audioContext).state){e.n=5;break}return e.n=4,o.resume();case 4:if(!n){e.n=5;break}return e.n=5,new Promise(function(e){return setTimeout(e,10)});case 5:if("running"===o.state){e.n=7;break}if(console.warn("AudioPlayer: AudioContext not in running state:",o.state),"suspended"!==o.state){e.n=7;break}return e.n=6,o.resume();case 6:return e.n=7,new Promise(function(e){return setTimeout(e,10)});case 7:return e.n=8,t.arrayBuffer();case 8:return r=e.v,e.n=9,o.decodeAudioData(r);case 9:i=e.v,a=n&&!this.isPlaying&&null===this.currentSource,(c=o.createBufferSource()).buffer=i,c.connect(o.destination),this.currentSource=c,this.isPlaying=!0,a&&this.emit("playbackStarted"),c.onended=function(){u.currentSource=null,u.isProcessingQueue=!1,u.audioQueue.length>0?setTimeout(function(){return u.processQueue()},0):setTimeout(function(){0!==u.audioQueue.length||u.currentSource||(u.isPlaying=!1,u.emit("playbackStopped"))},100)},c.start(),e.n=11;break;case 10:e.p=10,s=e.v,this.currentSource=null,this.emit("playbackError",s),this.audioQueue.length>0?(this.isProcessingQueue=!1,setTimeout(function(){return u.processQueue()},100)):(this.isPlaying=!1,this.isProcessingQueue=!1,this.emit("playbackStopped"));case 11:return e.a(2)}},e,this,[[2,10]])})),function(){return r.apply(this,arguments)})},{key:"stop",value:function(){this.stopImmediate()}},{key:"stopImmediate",value:function(){var e=this.isPlaying||null!==this.currentSource;if(this.currentSource){try{this.currentSource.stop()}catch(e){}this.currentSource=null}this.isPlaying=!1,this.isProcessingQueue=!1,this.audioQueue=[],e&&this.emit("playbackStopped")}},{key:"getStatus",value:function(){return{isPlaying:this.isPlaying,isProcessingQueue:this.isProcessingQueue,queueLength:this.audioQueue.length,audioContextState:this.audioContext?this.audioContext.state:"closed"}}},{key:"destroy",value:function(){this.stop(),this.audioContext&&"closed"!==this.audioContext.state&&(this.audioContext.close(),this.audioContext=null),this.audioContextReady=!1}}],o&&J(n.prototype,o),Object.defineProperty(n,"prototype",{writable:!1}),n;var n,o,r,i}(c);function te(e){return te="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},te(e)}function ne(){var e,t,n="function"==typeof Symbol?Symbol:{},o=n.iterator||"@@iterator",r=n.toStringTag||"@@toStringTag";function i(n,o,r,i){var s=o&&o.prototype instanceof c?o:c,u=Object.create(s.prototype);return oe(u,"_invoke",function(n,o,r){var i,c,s,u=0,l=r||[],d=!1,p={p:0,n:0,v:e,a:f,f:f.bind(e,4),d:function(t,n){return i=t,c=0,s=e,p.n=n,a}};function f(n,o){for(c=n,s=o,t=0;!d&&u&&!r&&t<l.length;t++){var r,i=l[t],f=p.p,h=i[2];n>3?(r=h===o)&&(s=i[(c=i[4])?5:(c=3,3)],i[4]=i[5]=e):i[0]<=f&&((r=n<2&&f<i[1])?(c=0,p.v=o,p.n=i[1]):f<h&&(r=n<3||i[0]>o||o>h)&&(i[4]=n,i[5]=o,p.n=h,c=0))}if(r||n>1)return a;throw d=!0,o}return function(r,l,h){if(u>1)throw TypeError("Generator is already running");for(d&&1===l&&f(l,h),c=l,s=h;(t=c<2?e:s)||!d;){i||(c?c<3?(c>1&&(p.n=-1),f(c,s)):p.n=s:p.v=s);try{if(u=2,i){if(c||(r="next"),t=i[r]){if(!(t=t.call(i,s)))throw TypeError("iterator result is not an object");if(!t.done)return t;s=t.value,c<2&&(c=0)}else 1===c&&(t=i.return)&&t.call(i),c<2&&(s=TypeError("The iterator does not provide a '"+r+"' method"),c=1);i=e}else if((t=(d=p.n<0)?s:n.call(o,p))!==a)break}catch(t){i=e,c=1,s=t}finally{u=1}}return{value:t,done:d}}}(n,r,i),!0),u}var a={};function c(){}function s(){}function u(){}t=Object.getPrototypeOf;var l=[][o]?t(t([][o]())):(oe(t={},o,function(){return this}),t),d=u.prototype=c.prototype=Object.create(l);function p(e){return Object.setPrototypeOf?Object.setPrototypeOf(e,u):(e.__proto__=u,oe(e,r,"GeneratorFunction")),e.prototype=Object.create(d),e}return s.prototype=u,oe(d,"constructor",u),oe(u,"constructor",s),s.displayName="GeneratorFunction",oe(u,r,"GeneratorFunction"),oe(d),oe(d,r,"Generator"),oe(d,o,function(){return this}),oe(d,"toString",function(){return"[object Generator]"}),(ne=function(){return{w:i,m:p}})()}function oe(e,t,n,o){var r=Object.defineProperty;try{r({},"",{})}catch(e){r=0}oe=function(e,t,n,o){function i(t,n){oe(e,t,function(e){return this._invoke(t,n,e)})}t?r?r(e,t,{value:n,enumerable:!o,configurable:!o,writable:!o}):e[t]=n:(i("next",0),i("throw",1),i("return",2))},oe(e,t,n,o)}function re(e,t,n,o,r,i,a){try{var c=e[i](a),s=c.value}catch(e){return void n(e)}c.done?t(s):Promise.resolve(s).then(o,r)}function ie(e){return function(){var t=this,n=arguments;return new Promise(function(o,r){var i=e.apply(t,n);function a(e){re(i,o,r,a,c,"next",e)}function c(e){re(i,o,r,a,c,"throw",e)}a(void 0)})}}function ae(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(e);t&&(o=o.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,o)}return n}function ce(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?ae(Object(n),!0).forEach(function(t){se(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):ae(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}function se(e,t,n){return(t=le(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function ue(e,t){for(var n=0;n<t.length;n++){var o=t[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(e,le(o.key),o)}}function le(e){var t=function(e){if("object"!=te(e)||!e)return e;var t=e[Symbol.toPrimitive];if(void 0!==t){var n=t.call(e,"string");if("object"!=te(n))return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}(e);return"symbol"==te(t)?t:t+""}function de(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(e){}return(de=function(){return!!e})()}function pe(e){return pe=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(e){return e.__proto__||Object.getPrototypeOf(e)},pe(e)}function fe(e,t){return fe=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,t){return e.__proto__=t,e},fe(e,t)}var he=function(e){function t(){var e,n=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,t),(e=function(e,t,n){return t=pe(t),function(e,t){if(t&&("object"==te(t)||"function"==typeof t))return t;if(void 0!==t)throw new TypeError("Derived constructors may only return object or undefined");return function(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}(e)}(e,de()?Reflect.construct(t,n||[],pe(e).constructor):t.apply(e,n))}(this,t)).config=ce({websocketUrl:n.websocketUrl||"wss://speech.talktopc.com/ws/conv",agentId:n.agentId,appId:n.appId,ttpId:n.ttpId,voice:n.voice||"default",language:n.language||"en",sampleRate:n.sampleRate||16e3,agentSettingsOverride:n.agentSettingsOverride||null,onStartConversation:n.onStartConversation||null,onEndConversation:n.onEndConversation||null},n),e.isConnected=!1,e.isRecording=!1,e.isPlaying=!1,e.isDestroyed=!1,e.conversationStarted=!1,e.webSocketManager=new j(ce(ce({},e.config),{},{autoReconnect:!1!==e.config.autoReconnect})),e.audioRecorder=new z(e.config),e.audioPlayer=new ee(e.config),e.setupEventHandlers(),e}return function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&fe(e,t)}(t,e),n=t,o=[{key:"setupEventHandlers",value:function(){var e=this;this.webSocketManager.on("connected",function(){e.isConnected=!0,e.sendHelloMessage(),e.emit("connected")}),this.webSocketManager.on("disconnected",function(t){if(e.isConnected=!1,e.conversationStarted&&(e.conversationStarted=!1,console.log("🏁 VoiceSDK: Conversation ended (connection closed)"),e.emit("conversationEnded",{}),e.config.onEndConversation))try{e.config.onEndConversation({})}catch(e){console.error("VoiceSDK: Error in onEndConversation hook:",e)}if(t&&1008===t.code&&t.reason&&(t.reason.includes("Domain not whitelisted")||t.reason.includes("domain")||t.reason.includes("whitelist"))){var n=new Error("DOMAIN_NOT_WHITELISTED");n.reason=t.reason,n.code=t.code,e.emit("domainError",n),e.emit("error",n)}e.isRecording&&e.stopRecording().catch(function(e){console.error("VoiceSDK: Error stopping recording on disconnect:",e)}),e.emit("disconnected",t)}),this.webSocketManager.on("error",function(t){e.emit("error",t)}),this.webSocketManager.on("message",function(t){if(("hello_ack"===t.t||"hello_ack"===t.type)&&!e.conversationStarted&&(e.conversationStarted=!0,console.log("🎬 VoiceSDK: Conversation started"),e.emit("conversationStarted",{conversationId:t.conversationId}),e.config.onStartConversation))try{e.config.onStartConversation({conversationId:t.conversationId})}catch(e){console.error("VoiceSDK: Error in onStartConversation hook:",e)}if("greeting_audio"===t.t&&t.data)try{for(var n=atob(t.data),o=new Uint8Array(n.length),r=0;r<n.length;r++)o[r]=n.charCodeAt(r);e.audioPlayer.playAudio(o),e.emit("greetingStarted")}catch(e){console.error("VoiceSDK: Error playing greeting audio:",e)}else e.emit("message",t)}),this.webSocketManager.on("binaryAudio",function(t){e.audioPlayer.playAudio(t)}),this.webSocketManager.on("bargeIn",function(t){e.emit("bargeIn",t)}),this.webSocketManager.on("stopPlaying",function(t){e.emit("stopPlaying",t),e.audioPlayer.stopImmediate()}),this.audioRecorder.on("recordingStarted",function(){if(e.isRecording=!0,!e.conversationStarted&&(e.conversationStarted=!0,console.log("🎬 VoiceSDK: Conversation started (recording)"),e.emit("conversationStarted",{}),e.config.onStartConversation))try{e.config.onStartConversation({})}catch(e){console.error("VoiceSDK: Error in onStartConversation hook:",e)}e.isPlaying&&(e.audioPlayer.stopImmediate(),e.isConnected&&e.webSocketManager.sendMessage({t:"barge_in"})),e.emit("recordingStarted")}),this.audioRecorder.on("recordingStopped",function(){e.isRecording=!1,e.emit("recordingStopped")}),this.audioRecorder.on("audioData",function(t){e.isConnected&&e.webSocketManager.sendBinary(t)}),this.audioPlayer.on("playbackStarted",function(){e.isPlaying=!0,e.emit("playbackStarted"),e.isConnected&&e.webSocketManager.sendMessage({t:"audio_started_playing"})}),this.audioPlayer.on("playbackStopped",function(){e.isPlaying=!1,e.emit("playbackStopped"),e.isConnected&&e.webSocketManager.sendMessage({t:"audio_stopped_playing"})}),this.audioPlayer.on("playbackError",function(t){e.emit("playbackError",t)})}},{key:"connect",value:(u=ie(ne().m(function e(){var t,n;return ne().w(function(e){for(;;)switch(e.p=e.n){case 0:if(!this.isDestroyed){e.n=1;break}return console.warn("VoiceSDK: Cannot connect - SDK is destroyed"),e.a(2,!1);case 1:return e.p=1,t=this.buildWebSocketUrl(),this.webSocketManager.config.websocketUrl=t,e.n=2,this.webSocketManager.connect();case 2:return e.a(2,!0);case 3:return e.p=3,n=e.v,console.error("🔌 VoiceSDK: Connection failed with error:",n),this.emit("error",n),e.a(2,!1)}},e,this,[[1,3]])})),function(){return u.apply(this,arguments)})},{key:"buildWebSocketUrl",value:function(){var e=this.config.websocketUrl,t=new URLSearchParams;if(this.config.agentId&&t.append("agentId",this.config.agentId),this.config.appId&&t.append("appId",this.config.appId),this.config.voice&&"default"!==this.config.voice&&t.append("voice",this.config.voice),this.config.language&&"en"!==this.config.language&&t.append("language",this.config.language),t.toString()){var n=e.includes("?")?"&":"?";e+=n+t.toString()}return e}},{key:"disconnect",value:function(){if(!this.isDestroyed){if(this.conversationStarted&&(this.conversationStarted=!1,console.log("🏁 VoiceSDK: Conversation ended"),this.emit("conversationEnded",{}),this.config.onEndConversation))try{this.config.onEndConversation({})}catch(e){console.error("VoiceSDK: Error in onEndConversation hook:",e)}this.stopRecording(),this.webSocketManager.disconnect()}}},{key:"resetReconnectionAttempts",value:function(){this.isDestroyed||this.webSocketManager.resetReconnectionAttempts()}},{key:"reconnect",value:(s=ie(ne().m(function e(){return ne().w(function(e){for(;;)switch(e.n){case 0:if(!this.isDestroyed){e.n=1;break}return e.a(2,!1);case 1:return this.disconnect(),this.resetReconnectionAttempts(),e.n=2,this.connect();case 2:return e.a(2,e.v)}},e,this)})),function(){return s.apply(this,arguments)})},{key:"startRecording",value:(c=ie(ne().m(function e(){var t;return ne().w(function(e){for(;;)switch(e.p=e.n){case 0:if(this.isConnected){e.n=1;break}throw new Error("Not connected to voice server");case 1:return e.p=1,this.webSocketManager.sendMessage({t:"start_continuous_mode",ttpId:this.generateTtpId(),voice:this.config.voice,language:this.config.language}),e.n=2,this.audioRecorder.start();case 2:return e.a(2,!0);case 3:return e.p=3,t=e.v,console.error("❌ VoiceSDK: Failed to start recording:",t),this.emit("error",t),e.a(2,!1)}},e,this,[[1,3]])})),function(){return c.apply(this,arguments)})},{key:"stopRecording",value:(a=ie(ne().m(function e(){var t;return ne().w(function(e){for(;;)switch(e.p=e.n){case 0:if(this.isRecording){e.n=1;break}return e.a(2);case 1:return e.p=1,this.webSocketManager.sendMessage({t:"stop_continuous_mode",ttpId:this.generateTtpId()}),e.n=2,this.audioRecorder.stop();case 2:return this.audioPlayer.stopImmediate(),e.a(2,!0);case 3:return e.p=3,t=e.v,this.emit("error",t),e.a(2,!1)}},e,this,[[1,3]])})),function(){return a.apply(this,arguments)})},{key:"toggleRecording",value:(i=ie(ne().m(function e(){return ne().w(function(e){for(;;)switch(e.n){case 0:if(!this.isRecording){e.n=2;break}return e.n=1,this.stopRecording();case 1:case 3:return e.a(2,e.v);case 2:return e.n=3,this.startRecording();case 4:return e.a(2)}},e,this)})),function(){return i.apply(this,arguments)})},{key:"stopAudioPlayback",value:function(){this.audioPlayer.stopImmediate()}},{key:"handleBargeIn",value:(r=ie(ne().m(function e(){return ne().w(function(e){for(;;)switch(e.n){case 0:if(this.stopAudioPlayback(),this.isRecording){e.n=1;break}return e.n=1,this.startRecording();case 1:return e.a(2)}},e,this)})),function(){return r.apply(this,arguments)})},{key:"getStatus",value:function(){return{isConnected:this.isConnected,isRecording:this.isRecording,isPlaying:this.isPlaying}}},{key:"updateConfig",value:function(e){this.config=ce(ce({},this.config),e)}},{key:"generateTtpId",value:function(){return"sdk_"+Math.random().toString(36).substr(2,9)+"_"+Date.now()}},{key:"sendHelloMessage",value:function(){if(this.isConnected){var e={t:"hello"};if(!this.config.appId){var t=new Error("appId is required for connection");return console.error("VoiceSDK: Failed to send hello message:",t),void this.emit("error",t)}e.appId=this.config.appId,this.config.agentSettingsOverride&&Object.keys(this.config.agentSettingsOverride).length>0&&(e.agentSettingsOverride=this.config.agentSettingsOverride,console.log("🔧 VoiceSDK: Sending agent settings override:",Object.keys(this.config.agentSettingsOverride)));try{this.webSocketManager.sendMessage(e)}catch(t){console.error("VoiceSDK: Failed to send hello message:",t),this.emit("error",t)}}else console.warn("VoiceSDK: Cannot send hello message - not connected")}},{key:"destroy",value:function(){this.isDestroyed||(this.disconnect(),this.isDestroyed=!0,this.audioRecorder.destroy(),this.audioPlayer.destroy(),this.removeAllListeners())}}],o&&ue(n.prototype,o),Object.defineProperty(n,"prototype",{writable:!1}),n;var n,o,r,i,a,c,s,u}(c);function ve(e){return ve="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},ve(e)}function ge(e,t){for(var n=0;n<t.length;n++){var o=t[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(e,ye(o.key),o)}}function ye(e){var t=function(e){if("object"!=ve(e)||!e)return e;var t=e[Symbol.toPrimitive];if(void 0!==t){var n=t.call(e,"string");if("object"!=ve(n))return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}(e);return"symbol"==ve(t)?t:t+""}var me=function(){return e=function e(){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),this.events={}},t=[{key:"on",value:function(e,t){return this.events[e]||(this.events[e]=[]),this.events[e].push(t),this}},{key:"off",value:function(e,t){return this.events[e]?(this.events[e]=this.events[e].filter(function(e){return e!==t}),this):this}},{key:"emit",value:function(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),o=1;o<t;o++)n[o-1]=arguments[o];return!!this.events[e]&&(this.events[e].forEach(function(e){e.apply(void 0,n)}),!0)}},{key:"once",value:function(e,t){var n=this,o=function(){t.apply(void 0,arguments),n.off(e,o)};return this.on(e,o)}},{key:"removeAllListeners",value:function(e){return e?delete this.events[e]:this.events={},this}}],t&&ge(e.prototype,t),Object.defineProperty(e,"prototype",{writable:!1}),e;var e,t}();const be=me;function Se(e){return Se="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},Se(e)}function we(e,t){for(var n=0;n<t.length;n++){var o=t[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(e,xe(o.key),o)}}function xe(e){var t=function(e){if("object"!=Se(e)||!e)return e;var t=e[Symbol.toPrimitive];if(void 0!==t){var n=t.call(e,"string");if("object"!=Se(n))return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}(e);return"symbol"==Se(t)?t:t+""}const Ce=function(){return e=function e(){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),this.name="PCM"},(t=[{key:"decode",value:function(e){if(e instanceof ArrayBuffer)return e;if(e instanceof Uint8Array)return e.buffer;throw new Error("Invalid PCM data type")}},{key:"encode",value:function(e){return e}}])&&we(e.prototype,t),Object.defineProperty(e,"prototype",{writable:!1}),e;var e,t}();function ke(e){return ke="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},ke(e)}function Pe(e,t){for(var n=0;n<t.length;n++){var o=t[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(e,Oe(o.key),o)}}function Oe(e){var t=function(e){if("object"!=ke(e)||!e)return e;var t=e[Symbol.toPrimitive];if(void 0!==t){var n=t.call(e,"string");if("object"!=ke(n))return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}(e);return"symbol"==ke(t)?t:t+""}const Ee=function(){return e=function e(){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),this.name="PCMU"},(t=[{key:"decode",value:function(e){for(var t=e instanceof Uint8Array?e:new Uint8Array(e),n=new Int16Array(t.length),o=0;o<t.length;o++)n[o]=this.mulawToLinear(t[o]);return n.buffer}},{key:"encode",value:function(e){for(var t=e instanceof Int16Array?e:new Int16Array(e),n=new Uint8Array(t.length),o=0;o<t.length;o++)n[o]=this.linearToMulaw(t[o]);return n}},{key:"mulawToLinear",value:function(e){var t=1<<3+(e>>4&7);return(128&e?-1:1)*(132+(15&e)*t+(t>>1)-4)}},{key:"linearToMulaw",value:function(e){var t=e>>8&128;t&&(e=-e),e>32635&&(e=32635),e+=132;for(var n=7,o=16384;0===(e&o)&&n>0;n--,o>>=1);return 255&~(t|n<<4|e>>n+3&15)}}])&&Pe(e.prototype,t),Object.defineProperty(e,"prototype",{writable:!1}),e;var e,t}();function Te(e){return Te="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},Te(e)}function Ae(e,t){for(var n=0;n<t.length;n++){var o=t[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(e,Ie(o.key),o)}}function Ie(e){var t=function(e){if("object"!=Te(e)||!e)return e;var t=e[Symbol.toPrimitive];if(void 0!==t){var n=t.call(e,"string");if("object"!=Te(n))return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}(e);return"symbol"==Te(t)?t:t+""}const je=function(){return e=function e(){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),this.name="PCMA"},(t=[{key:"decode",value:function(e){for(var t=e instanceof Uint8Array?e:new Uint8Array(e),n=new Int16Array(t.length),o=0;o<t.length;o++)n[o]=this.alawToLinear(t[o]);return n.buffer}},{key:"encode",value:function(e){for(var t=e instanceof Int16Array?e:new Int16Array(e),n=new Uint8Array(t.length),o=0;o<t.length;o++)n[o]=this.linearToAlaw(t[o]);return n}},{key:"alawToLinear",value:function(e){var t=(e^=85)>>4&7,n=15&e;return(128&e?-1:1)*(0===t?8+(n<<4):264+(n<<4)<<t-1)}},{key:"linearToAlaw",value:function(e){var t,n,o=e>>8&128;if(o&&(e=-e),e>32635&&(e=32635),e<256)t=0,n=e>>4;else{t=7;for(var r=16384;0===(e&r)&&t>0;t--,r>>=1);n=e>>t+3&15}return 85^(o|t<<4|n)}}])&&Ae(e.prototype,t),Object.defineProperty(e,"prototype",{writable:!1}),e;var e,t}();function De(e){return De="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},De(e)}function Fe(e,t){var n="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!n){if(Array.isArray(e)||(n=function(e,t){if(e){if("string"==typeof e)return Be(e,t);var n={}.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?Be(e,t):void 0}}(e))||t&&e&&"number"==typeof e.length){n&&(e=n);var o=0,r=function(){};return{s:r,n:function(){return o>=e.length?{done:!0}:{done:!1,value:e[o++]}},e:function(e){throw e},f:r}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var i,a=!0,c=!1;return{s:function(){n=n.call(e)},n:function(){var e=n.next();return a=e.done,e},e:function(e){c=!0,i=e},f:function(){try{a||null==n.return||n.return()}finally{if(c)throw i}}}}function Be(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,o=Array(t);n<t;n++)o[n]=e[n];return o}function Re(e){if(null!=e){var t=e["function"==typeof Symbol&&Symbol.iterator||"@@iterator"],n=0;if(t)return t.call(e);if("function"==typeof e.next)return e;if(!isNaN(e.length))return{next:function(){return e&&n>=e.length&&(e=void 0),{value:e&&e[n++],done:!e}}}}throw new TypeError(De(e)+" is not iterable")}function _e(){var e,t,n="function"==typeof Symbol?Symbol:{},o=n.iterator||"@@iterator",r=n.toStringTag||"@@toStringTag";function i(n,o,r,i){var s=o&&o.prototype instanceof c?o:c,u=Object.create(s.prototype);return Ue(u,"_invoke",function(n,o,r){var i,c,s,u=0,l=r||[],d=!1,p={p:0,n:0,v:e,a:f,f:f.bind(e,4),d:function(t,n){return i=t,c=0,s=e,p.n=n,a}};function f(n,o){for(c=n,s=o,t=0;!d&&u&&!r&&t<l.length;t++){var r,i=l[t],f=p.p,h=i[2];n>3?(r=h===o)&&(s=i[(c=i[4])?5:(c=3,3)],i[4]=i[5]=e):i[0]<=f&&((r=n<2&&f<i[1])?(c=0,p.v=o,p.n=i[1]):f<h&&(r=n<3||i[0]>o||o>h)&&(i[4]=n,i[5]=o,p.n=h,c=0))}if(r||n>1)return a;throw d=!0,o}return function(r,l,h){if(u>1)throw TypeError("Generator is already running");for(d&&1===l&&f(l,h),c=l,s=h;(t=c<2?e:s)||!d;){i||(c?c<3?(c>1&&(p.n=-1),f(c,s)):p.n=s:p.v=s);try{if(u=2,i){if(c||(r="next"),t=i[r]){if(!(t=t.call(i,s)))throw TypeError("iterator result is not an object");if(!t.done)return t;s=t.value,c<2&&(c=0)}else 1===c&&(t=i.return)&&t.call(i),c<2&&(s=TypeError("The iterator does not provide a '"+r+"' method"),c=1);i=e}else if((t=(d=p.n<0)?s:n.call(o,p))!==a)break}catch(t){i=e,c=1,s=t}finally{u=1}}return{value:t,done:d}}}(n,r,i),!0),u}var a={};function c(){}function s(){}function u(){}t=Object.getPrototypeOf;var l=[][o]?t(t([][o]())):(Ue(t={},o,function(){return this}),t),d=u.prototype=c.prototype=Object.create(l);function p(e){return Object.setPrototypeOf?Object.setPrototypeOf(e,u):(e.__proto__=u,Ue(e,r,"GeneratorFunction")),e.prototype=Object.create(d),e}return s.prototype=u,Ue(d,"constructor",u),Ue(u,"constructor",s),s.displayName="GeneratorFunction",Ue(u,r,"GeneratorFunction"),Ue(d),Ue(d,r,"Generator"),Ue(d,o,function(){return this}),Ue(d,"toString",function(){return"[object Generator]"}),(_e=function(){return{w:i,m:p}})()}function Ue(e,t,n,o){var r=Object.defineProperty;try{r({},"",{})}catch(e){r=0}Ue=function(e,t,n,o){function i(t,n){Ue(e,t,function(e){return this._invoke(t,n,e)})}t?r?r(e,t,{value:n,enumerable:!o,configurable:!o,writable:!o}):e[t]=n:(i("next",0),i("throw",1),i("return",2))},Ue(e,t,n,o)}function Me(e,t,n,o,r,i,a){try{var c=e[i](a),s=c.value}catch(e){return void n(e)}c.done?t(s):Promise.resolve(s).then(o,r)}function Ne(e){return function(){var t=this,n=arguments;return new Promise(function(o,r){var i=e.apply(t,n);function a(e){Me(i,o,r,a,c,"next",e)}function c(e){Me(i,o,r,a,c,"throw",e)}a(void 0)})}}function Ve(e,t){for(var n=0;n<t.length;n++){var o=t[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(e,Ke(o.key),o)}}function Ke(e){var t=function(e){if("object"!=De(e)||!e)return e;var t=e[Symbol.toPrimitive];if(void 0!==t){var n=t.call(e,"string");if("object"!=De(n))return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}(e);return"symbol"==De(t)?t:t+""}function Le(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(e){}return(Le=function(){return!!e})()}function ze(e){return ze=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(e){return e.__proto__||Object.getPrototypeOf(e)},ze(e)}function He(e,t){return He=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,t){return e.__proto__=t,e},He(e,t)}var We=function(e){function t(){var e,n=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,t),(e=function(e,t,n){return t=ze(t),function(e,t){if(t&&("object"==De(t)||"function"==typeof t))return t;if(void 0!==t)throw new TypeError("Derived constructors may only return object or undefined");return function(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}(e)}(e,Le()?Reflect.construct(t,n||[],ze(e).constructor):t.apply(e,n))}(this,t)).config=n,e.audioContext=null,e._audioContextStateChangeHandler=null,e._keepAliveOscillator=null,e.audioQueue=[],e.isPlaying=!1,e.isProcessingQueue=!1,e.currentSource=null,e.outputFormat=null,e.nextStartTime=0,e.scheduledBuffers=0,e.scheduledSources=new Set,e.pcmChunkQueue=[],e.preparedBuffer=[],e.isProcessingPcmQueue=!1,e.isSchedulingFrames=!1,e.MAX_LOOKAHEAD_SECONDS=.02,e.pendingSentenceText=null,e.sentenceTimings=[],e.isCheckingTranscripts=!1,e.codecs={pcm:new Ce,pcmu:new Ee,pcma:new je},e.SUPPORTED_CONTAINERS=["wav","raw"],e.SUPPORTED_ENCODINGS=["pcm","pcmu","pcma"],e.SUPPORTED_SAMPLE_RATES=[8e3,16e3,22050,24e3,44100,48e3],e.SUPPORTED_BIT_DEPTHS=[8,16,24],e.SUPPORTED_CHANNELS=[1],console.log("🎵 AudioPlayer v2 initialized"),e}return function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&He(e,t)}(t,e),n=t,o=[{key:"setOutputFormat",value:function(e){var t;this.validateFormat(e)||(console.warn("⚠️ AudioPlayer: Invalid format, using defaults:",e),e=this.getDefaultFormat());var n=null===(t=this.outputFormat)||void 0===t?void 0:t.sampleRate,o=e.sampleRate;this.outputFormat=e,console.log("✅ AudioPlayer v2: Format set:",e),this.audioContext&&n&&n!==o&&(console.warn("⚠️ AudioPlayer: Sample rate changed, recreating AudioContext"),console.warn(" Old: ".concat(n,"Hz → New: ").concat(o,"Hz")),this.stopImmediate(),"closed"!==this.audioContext.state&&this.audioContext.close(),this.audioContext=null,console.log("ℹ️ AudioContext will be recreated on next audio chunk with correct sample rate")),this.audioContext||(this.initializeAudioContext(),this.audioContext&&"suspended"===this.audioContext.state&&this.audioContext.resume().then(function(){console.log("✅ AudioPlayer v2: AudioContext resumed and ready")}).catch(function(e){console.warn("⚠️ AudioPlayer v2: Could not resume AudioContext:",e)}))}},{key:"validateFormat",value:function(e){var t,n;if(!e)return!1;var o=null===(t=e.container)||void 0===t?void 0:t.toLowerCase(),r=null===(n=e.encoding)||void 0===n?void 0:n.toLowerCase();return o&&r&&this.SUPPORTED_CONTAINERS.includes(o)&&this.SUPPORTED_ENCODINGS.includes(r)&&this.SUPPORTED_SAMPLE_RATES.includes(e.sampleRate)&&this.SUPPORTED_BIT_DEPTHS.includes(e.bitDepth)&&(!e.channels||this.SUPPORTED_CHANNELS.includes(e.channels))}},{key:"getDefaultFormat",value:function(){return{container:"raw",encoding:"pcm",sampleRate:16e3,channels:1,bitDepth:16}}},{key:"playAudio",value:function(e){var t=this;try{var n=this.createAudioBlob(e);this.audioQueue.push(n),this.isPlaying||this.isProcessingQueue||this.currentSource||setTimeout(function(){return t.processQueue()},50)}catch(e){console.error("❌ AudioPlayer v2: Playback error:",e),this.emit("playbackError",e)}}},{key:"playChunk",value:(c=Ne(_e().m(function e(t){var n,o,r=this;return _e().w(function(e){for(;;)switch(e.n){case 0:(n=this.prepareChunk(t))?(this.preparedBuffer.push(n),(this.preparedBuffer.length<=3||this.preparedBuffer.length%10==0)&&console.log("📥 AudioPlayer: Frame received, queued: ".concat(this.preparedBuffer.length,", scheduled: ").concat(this.scheduledBuffers,", isScheduling: ").concat(this.isSchedulingFrames)),this.isSchedulingFrames?setTimeout(function(){r.preparedBuffer.length>0&&!r.isSchedulingFrames&&r.schedulePreparedFrames()},5):this.schedulePreparedFrames(),this.pcmChunkQueue.length>0&&!this.isProcessingPcmQueue&&this.processPcmQueue()):(console.error("❌ AudioPlayer: playChunk failed - prepareChunk returned null"),console.error(" pcmData length:",(null==t?void 0:t.byteLength)||"undefined"),console.error(" outputFormat:",this.outputFormat),console.error(" audioContext:",this.audioContext?"initialized":"not initialized"),console.error(" audioContext state:",(null===(o=this.audioContext)||void 0===o?void 0:o.state)||"N/A"),this.emit("playbackError",new Error("Failed to prepare PCM chunk for playback")));case 1:return e.a(2)}},e,this)})),function(e){return c.apply(this,arguments)})},{key:"prepareChunk",value:function(e){try{var t;if(!this.outputFormat)return console.error("❌ AudioPlayer: Cannot prepare chunk - outputFormat not set"),console.error(" Call setOutputFormat() before playing audio chunks"),null;if(this.audioContext||this.initializeAudioContext(),!this.audioContext)return console.error("❌ AudioPlayer: Cannot prepare chunk - AudioContext not available"),null;var n=e;if(e.byteLength%2!=0){console.warn("⚠️ Odd PCM chunk size, padding:",e.byteLength);var o=new Uint8Array(e.byteLength+1);o.set(new Uint8Array(e),0),o[e.byteLength]=0,n=o.buffer}for(var r=new Int16Array(n),i=new Float32Array(r.length),a=1/32768,c=r.length,s=0;s<c;s++)i[s]=r[s]*a;var u=(null===(t=this.outputFormat)||void 0===t?void 0:t.sampleRate)||this.audioContext.sampleRate,l=this.audioContext.sampleRate,d=this.audioContext.createBuffer(1,i.length,u);d.getChannelData(0).set(i);var p=d.duration,f=i.length,h=p;return l!==u&&(h=f/l),{buffer:d,duration:h,sampleRate:u,contextSampleRate:l}}catch(e){return console.error("❌ AudioPlayer: Error preparing chunk:",e),null}}},{key:"applyFadeOut",value:function(e){return e}},{key:"schedulePreparedFrames",value:(a=Ne(_e().m(function e(){var t,n,o,r,i,a=this;return _e().w(function(e){for(;;)switch(e.p=e.n){case 0:if(!this.isSchedulingFrames){e.n=1;break}return e.a(2);case 1:if(this.isSchedulingFrames=!0,t=this.preparedBuffer.length,0===(n=Math.min(t,5))&&t>0&&(n=1),e.p=2,this.audioContext||this.initializeAudioContext(),"suspended"!==this.audioContext.state){e.n=3;break}return e.n=3,this.audioContext.resume();case 3:o=0,r=_e().m(function e(){var t,n,r,i,c;return _e().w(function(e){for(;;)switch(e.n){case 0:if(t=a.preparedBuffer.shift()){e.n=1;break}return e.a(2,1);case 1:(n=a.audioContext.createBufferSource()).buffer=t.buffer,n.connect(a.audioContext.destination),a.scheduledSources.add(n),r=a.audioContext.currentTime,0===a.scheduledBuffers?(a.nextStartTime<r&&(a.nextStartTime=r+a.MAX_LOOKAHEAD_SECONDS),console.log("🎵 Starting playback with minimal delay:",a.nextStartTime)):(i=r+a.MAX_LOOKAHEAD_SECONDS,a.nextStartTime<i&&(a.nextStartTime=i,console.warn("⚠️ AudioPlayer: Fell behind schedule, adjusting nextStartTime to ".concat(a.nextStartTime.toFixed(4),"s")))),a.pendingSentenceText&&(a.sentenceTimings.push({startTime:a.nextStartTime,text:a.pendingSentenceText,displayed:!1}),console.log("📝 AudioPlayer: Sentence scheduled at ".concat(a.nextStartTime.toFixed(3),'s: "').concat(a.pendingSentenceText.substring(0,40),'..."')),a.pendingSentenceText=null,a.isCheckingTranscripts||a.startTranscriptChecker()),n.start(a.nextStartTime),a.nextStartTime+=t.duration,a.nextStartTime=Math.round(1e6*a.nextStartTime)/1e6,c=a.nextStartTime-t.duration,a.scheduledBuffers<5&&(console.log("🎵 AudioPlayer: Scheduled frame ".concat(a.scheduledBuffers+1," at ").concat(c.toFixed(4),"s, next at ").concat(a.nextStartTime.toFixed(4),"s")),console.log(" Duration: ".concat(t.duration.toFixed(4),"s (").concat((1e3*t.duration).toFixed(2),"ms), Queued: ").concat(a.preparedBuffer.length,", Scheduled: ").concat(a.scheduledBuffers))),a.scheduledBuffers++,o++,n.onended=function(){if(a.scheduledSources.delete(n),a.scheduledBuffers--,0===a.scheduledBuffers&&0===a.preparedBuffer.length&&0===a.pcmChunkQueue.length)a.isPlaying=!1,a.isSchedulingFrames=!1,console.log("🛑 AudioPlayer: Emitting playbackStopped event (all buffers finished)"),a.emit("playbackStopped");else if(a.preparedBuffer.length>0)setTimeout(function(){a.preparedBuffer.length>0&&!a.isSchedulingFrames&&a.schedulePreparedFrames()},0);else if(a.scheduledBuffers>0){var e=function(){a.preparedBuffer.length>0&&!a.isSchedulingFrames&&a.scheduledBuffers>0?a.schedulePreparedFrames():a.scheduledBuffers>0&&setTimeout(e,10)};setTimeout(e,10)}},a.isPlaying||(a.isPlaying=!0,console.log("🎵 AudioPlayer: Emitting playbackStarted event"),a.emit("playbackStarted"));case 2:return e.a(2)}},e)});case 4:if(!(this.preparedBuffer.length>0&&o<n)){e.n=7;break}return e.d(Re(r()),5);case 5:if(!e.v){e.n=6;break}return e.a(3,7);case 6:e.n=4;break;case 7:this.isSchedulingFrames=!1,this.preparedBuffer.length>0&&requestAnimationFrame(function(){a.preparedBuffer.length>0&&!a.isSchedulingFrames&&a.schedulePreparedFrames()}),this.scheduledBuffers>0&&setTimeout(function(){a.preparedBuffer.length>0&&!a.isSchedulingFrames&&a.scheduledBuffers>0?a.schedulePreparedFrames():a.scheduledBuffers>0&&setTimeout(function(){a.preparedBuffer.length>0&&!a.isSchedulingFrames&&a.scheduledBuffers>0&&a.schedulePreparedFrames()},10)},10),e.n=9;break;case 8:e.p=8,i=e.v,console.error("❌ AudioPlayer v2: Error scheduling frames:",i),this.emit("playbackError",i),this.isSchedulingFrames=!1;case 9:return e.a(2)}},e,this,[[2,8]])})),function(){return a.apply(this,arguments)})},{key:"processPcmQueue",value:(i=Ne(_e().m(function e(){var t,n,o,r,i,a,c,s,u,l,d,p,f,h,v,g,y,m,b,S,w=this;return _e().w(function(e){for(;;)switch(e.p=e.n){case 0:if(!this.isProcessingPcmQueue){e.n=1;break}return e.a(2);case 1:if(this.isProcessingPcmQueue=!0,e.p=2,this.audioContext||this.initializeAudioContext(),"suspended"!==this.audioContext.state){e.n=3;break}return e.n=3,this.audioContext.resume();case 3:if(!(this.pcmChunkQueue.length>0)){e.n=5;break}if(o=this.pcmChunkQueue.shift()){e.n=4;break}return e.a(3,3);case 4:for(r=o,o.byteLength%2!=0&&(console.warn("⚠️ Odd PCM chunk size, padding:",o.byteLength),(i=new Uint8Array(o.byteLength+1)).set(new Uint8Array(o),0),i[o.byteLength]=0,r=i.buffer),a=new Int16Array(r),c=new Float32Array(a.length),s=1/32768,u=a.length,l=0;l<u;l++)c[l]=a[l]*s;d=(null===(t=this.outputFormat)||void 0===t?void 0:t.sampleRate)||this.audioContext.sampleRate,p=this.audioContext.sampleRate,null!==(n=this.outputFormat)&&void 0!==n&&n.sampleRate?this.scheduledBuffers<3&&console.log("🎵 AudioPlayer: Creating buffer at ".concat(d,"Hz (AudioContext: ").concat(p,"Hz)")):console.warn("⚠️ AudioPlayer: outputFormat.sampleRate not set! Using AudioContext sample rate:",p),(f=this.audioContext.createBuffer(1,c.length,d)).getChannelData(0).set(c),(h=this.audioContext.createBufferSource()).buffer=f,h.connect(this.audioContext.destination),v=this.audioContext.currentTime,this.nextStartTime<v&&(this.nextStartTime=v,0===this.scheduledBuffers&&console.log("🎵 Starting playback at current time:",v)),g=f.duration,y=c.length,m=g,p!==d&&(m=y/p,this.scheduledBuffers<3&&(console.log("🔄 Resampling detected: ".concat(d,"Hz → ").concat(p,"Hz")),console.log(" Buffer duration: ".concat(g.toFixed(4),"s, Calculated: ").concat(m.toFixed(4),"s")))),h.start(this.nextStartTime),this.nextStartTime+=m,this.nextStartTime=Math.round(1e6*this.nextStartTime)/1e6,this.scheduledBuffers<3&&(b=this.nextStartTime-m,console.log("🎵 AudioPlayer: Scheduled chunk ".concat(this.scheduledBuffers+1," at ").concat(b.toFixed(4),"s, next at ").concat(this.nextStartTime.toFixed(4),"s")),console.log(" Duration: ".concat(m.toFixed(4),"s (").concat((1e3*m).toFixed(2),"ms)"))),this.scheduledBuffers++,h.onended=function(){w.scheduledBuffers--,0===w.scheduledBuffers&&0===w.pcmChunkQueue.length&&(w.isPlaying=!1,w.isProcessingPcmQueue=!1,w.emit("playbackStopped"))},this.isPlaying||(this.isPlaying=!0,this.emit("playbackStarted")),e.n=3;break;case 5:this.isProcessingPcmQueue=!1,e.n=7;break;case 6:e.p=6,S=e.v,console.error("❌ AudioPlayer v2: Error playing chunk:",S),this.emit("playbackError",S),this.isProcessingPcmQueue=!1;case 7:return e.a(2)}},e,this,[[2,6]])})),function(){return i.apply(this,arguments)})},{key:"createAudioBlob",value:function(e){var t=new Uint8Array(e);console.log("🎵 AudioPlayer: Processing ".concat(t.length," bytes")),console.log("🎵 AudioPlayer: Negotiated format:",this.outputFormat);var n=this.outputFormat&&this.outputFormat.container&&"wav"===this.outputFormat.container.toLowerCase(),o=this.outputFormat&&this.outputFormat.container&&"raw"===this.outputFormat.container.toLowerCase(),r=this.isWavFile(t);if(r&&console.log("🎵 AudioPlayer: Data has WAV header (RIFF)"),o&&r)return console.error("❌ AudioPlayer: CRITICAL MISMATCH!"),console.error(" Negotiated format: RAW"),console.error(" Actual data: WAV (RIFF header detected)"),console.error(" Backend is ignoring format request and sending WAV anyway."),console.warn("⚠️ AudioPlayer: Processing as WAV to avoid playback failure, but UI configuration was bypassed."),this.handleWavFile(t);if(o&&!r)console.log("🎵 AudioPlayer: Processing as RAW data (as negotiated)");else{if(n&&r)return console.log("✅ AudioPlayer: Processing as WAV file (matches negotiation)"),this.handleWavFile(t);if(n&&!r)return console.warn("⚠️ AudioPlayer: Negotiated WAV but data lacks WAV header. Attempting WAV processing anyway."),this.handleWavFile(t);if(!this.outputFormat&&r)return console.log("🎵 AudioPlayer: No format negotiated, auto-detecting WAV"),this.handleWavFile(t);this.outputFormat||r||(console.warn("⚠️ AudioPlayer: No format negotiated and data not WAV, using defaults"),this.outputFormat=this.getDefaultFormat())}return this.outputFormat||(console.warn("⚠️ AudioPlayer: No format set, using defaults"),this.outputFormat=this.getDefaultFormat()),console.log("🎵 AudioPlayer: Processing as RAW data with encoding:",this.outputFormat.encoding),this.handleRawData(t)}},{key:"isWavFile",value:function(e){return e.length>=44&&82===e[0]&&73===e[1]&&70===e[2]&&70===e[3]}},{key:"handleWavFile",value:function(e){var t=this.parseWavHeader(e);if(console.log("🎵 WAV file detected:",{format:t.audioFormat,encoding:this.getEncodingName(t.audioFormat),sampleRate:t.sampleRate,channels:t.channels,bitDepth:t.bitsPerSample}),1===t.audioFormat)return console.log("✅ PCM WAV - using directly"),new Blob([e],{type:"audio/wav"});var n=this.getCodecForWavFormat(t.audioFormat);if(!n)throw new Error("Unsupported WAV format code: ".concat(t.audioFormat));console.log("🔄 Non-PCM WAV - converting to PCM WAV");var o=e.slice(44),r=n.decode(o),i=this.createWavHeader(r.byteLength,t.sampleRate,t.channels,16);return new Blob([i,r],{type:"audio/wav"})}},{key:"handleRawData",value:function(e){var t,n,o=this.outputFormat.encoding.toLowerCase(),r=this.getCodec(o);if(!r)throw new Error("No codec found for encoding: ".concat(o));if(console.log("🎵 AudioPlayer: Decoding ".concat(o.toUpperCase()," to PCM")),console.log("🎵 AudioPlayer: Input format - bitDepth: ".concat(this.outputFormat.bitDepth,", sampleRate: ").concat(this.outputFormat.sampleRate)),"pcm"===o){var i=this.outputFormat.bitDepth||16;e.length,24===i?(console.warn("⚠️ AudioPlayer: Format says 24-bit PCM, but browser support is limited."),console.warn(" Treating as 16-bit PCM. If audio sounds wrong, backend should send 16-bit instead."),t=this.convert24BitTo16Bit(e),n=16):8===i?(console.log("🔄 AudioPlayer: Converting 8-bit PCM to 16-bit PCM"),t=this.convert8BitTo16Bit(e),n=16):(t=e.buffer,n=i,console.log("✅ AudioPlayer: Using native ".concat(i,"-bit PCM (no conversion needed)")))}else t=r.decode(e),n=16,console.log("🔄 AudioPlayer: Decoded ".concat(o.toUpperCase()," to 16-bit PCM"));var a=this.createWavHeader(t.byteLength,this.outputFormat.sampleRate,this.outputFormat.channels,n);return new Blob([a,t],{type:"audio/wav"})}},{key:"convert24BitTo16Bit",value:function(e){for(var t=Math.floor(e.length/3),n=new Int16Array(t),o=0;o<t;o++){var r=e[3*o],i=e[3*o+1],a=e[3*o+2],c=r|i<<8|(255&a)<<16;128&a&&(c|=4278190080),n[o]=Math.max(-32768,Math.min(32767,Math.round(c/256)))}return n.buffer}},{key:"convert8BitTo16Bit",value:function(e){for(var t=e.length,n=new Int16Array(t),o=0;o<t;o++){var r=e[o];n[o]=256*(r-128)}return n.buffer}},{key:"getCodec",value:function(e){var t={pcm:"pcm",linear:"pcm",l16:"pcm",pcmu:"pcmu",ulaw:"pcmu",mulaw:"pcmu",g711u:"pcmu",pcma:"pcma",alaw:"pcma",g711a:"pcma"}[e.toLowerCase()];return this.codecs[t]}},{key:"getCodecForWavFormat",value:function(e){switch(e){case 1:return this.codecs.pcm;case 6:return this.codecs.pcma;case 7:return this.codecs.pcmu;default:return null}}},{key:"getEncodingName",value:function(e){switch(e){case 1:return"PCM";case 6:return"A-law";case 7:return"μ-law";default:return"Unknown (".concat(e,")")}}},{key:"parseWavHeader",value:function(e){var t=new DataView(e.buffer,e.byteOffset,e.byteLength);return{audioFormat:t.getUint16(20,!0),channels:t.getUint16(22,!0),sampleRate:t.getUint32(24,!0),byteRate:t.getUint32(28,!0),blockAlign:t.getUint16(32,!0),bitsPerSample:t.getUint16(34,!0)}}},{key:"createWavHeader",value:function(e,t,n,o){var r=new ArrayBuffer(44),i=new DataView(r);return i.setUint32(0,1380533830,!1),i.setUint32(4,36+e,!0),i.setUint32(8,1463899717,!1),i.setUint32(12,1718449184,!1),i.setUint32(16,16,!0),i.setUint16(20,1,!0),i.setUint16(22,n,!0),i.setUint32(24,t,!0),i.setUint32(28,t*n*o/8,!0),i.setUint16(32,n*o/8,!0),i.setUint16(34,o,!0),i.setUint32(36,1684108385,!1),i.setUint32(40,e,!0),r}},{key:"initializeAudioContext",value:function(){var e,t,n=this,o=(null===(e=this.outputFormat)||void 0===e?void 0:e.sampleRate)||48e3;if(48e3!==o&&44100!==o&&(console.log("ℹ️ AudioPlayer: Backend requested ".concat(o,"Hz, but browser may resample to 48kHz")),console.log(" Consider requesting 48kHz from backend to avoid resampling and improve quality")),this.audioContext){var r=this.audioContext.sampleRate;if(!(Math.abs(r-o)>100))return;console.warn("⚠️ AudioPlayer: AudioContext sample rate (".concat(r,"Hz) doesn't match format (").concat(o,"Hz), recreating...")),this.stopImmediate(),"closed"!==this.audioContext.state&&this.audioContext.close(),this.audioContext=null}console.log("🎵 AudioPlayer: Creating AudioContext at ".concat(o,"Hz (from outputFormat: ").concat((null===(t=this.outputFormat)||void 0===t?void 0:t.sampleRate)||"not set",")"));try{this.audioContext=new(window.AudioContext||window.webkitAudioContext)({sampleRate:o,latencyHint:"playback"}),console.log("✅ AudioContext created at ".concat(this.audioContext.sampleRate,"Hz (requested: ").concat(o,"Hz)")),Math.abs(this.audioContext.sampleRate-o)>100?(console.error("❌ CRITICAL: Browser sample rate mismatch!"),console.error(" Requested: ".concat(o,"Hz")),console.error(" Got: ".concat(this.audioContext.sampleRate,"Hz")),console.error(" This WILL cause audio distortion/noise!"),console.error(" Solution: Backend should send ".concat(this.audioContext.sampleRate,"Hz audio instead"))):this.audioContext.sampleRate!==o&&(console.warn("⚠️ Browser adjusted sample rate: ".concat(o,"Hz → ").concat(this.audioContext.sampleRate,"Hz")),console.warn(" Browser will automatically resample audio.")),this._audioContextStateChangeHandler||(this._audioContextStateChangeHandler=Ne(_e().m(function e(){var t;return _e().w(function(e){for(;;)switch(e.p=e.n){case 0:if(!n.audioContext||"suspended"!==n.audioContext.state){e.n=4;break}if(!(n.scheduledSources.size>0||null!==n.currentSource||n.isPlaying)){e.n=4;break}return console.log("🛑 AudioPlayer: AudioContext was suspended during getUserMedia! Resuming immediately to prevent audio cut-off..."),e.p=1,e.n=2,n.audioContext.resume();case 2:console.log("✅ AudioPlayer: AudioContext resumed successfully"),e.n=4;break;case 3:e.p=3,t=e.v,console.error("❌ AudioPlayer: Failed to resume AudioContext:",t);case 4:return e.a(2)}},e,null,[[1,3]])})),this.audioContext.addEventListener("statechange",this._audioContextStateChangeHandler),console.log("🎵 AudioPlayer: Added AudioContext state change listener to prevent suspension"))}catch(e){console.error("❌ Failed to create AudioContext:",e),this.audioContext=new(window.AudioContext||window.webkitAudioContext),console.log("ℹ️ Using browser default: ".concat(this.audioContext.sampleRate,"Hz"))}}},{key:"processQueue",value:(r=Ne(_e().m(function e(){var t,n,o,r,i,a,c,s,u=this;return _e().w(function(e){for(;;)switch(e.p=e.n){case 0:if(!this.isProcessingQueue&&0!==this.audioQueue.length){e.n=1;break}return e.a(2);case 1:if(this.isProcessingQueue=!0,t=this.audioQueue.shift()){e.n=2;break}return this.isProcessingQueue=!1,e.a(2);case 2:if(e.p=2,n=!this.isPlaying&&null===this.currentSource,this.audioContext||this.initializeAudioContext(),"suspended"!==(o=this.audioContext).state){e.n=4;break}return e.n=3,o.resume();case 3:if(!n){e.n=4;break}return e.n=4,new Promise(function(e){return setTimeout(e,50)});case 4:if("running"===o.state){e.n=8;break}if(console.warn("AudioPlayer v2: AudioContext not in running state:",o.state),"suspended"!==o.state){e.n=8;break}return e.n=5,o.resume();case 5:if(!n){e.n=7;break}return e.n=6,new Promise(function(e){return setTimeout(e,50)});case 6:e.n=8;break;case 7:return e.n=8,new Promise(function(e){return setTimeout(e,10)});case 8:return e.n=9,t.arrayBuffer();case 9:return r=e.v,e.n=10,o.decodeAudioData(r);case 10:i=e.v,a=n&&!this.isPlaying&&null===this.currentSource,(c=o.createBufferSource()).buffer=i,c.connect(o.destination),this.currentSource=c,this.isPlaying=!0,a&&this.emit("playbackStarted"),c.onended=function(){u.currentSource=null,u.isProcessingQueue=!1,u.audioQueue.length>0?setTimeout(function(){return u.processQueue()},50):setTimeout(function(){0!==u.audioQueue.length||u.currentSource||(u.isPlaying=!1,u.emit("playbackStopped"))},100)},c.start(),e.n=12;break;case 11:e.p=11,s=e.v,console.error("❌ AudioPlayer v2: Error processing queue:",s),this.currentSource=null,this.emit("playbackError",s),this.audioQueue.length>0?(this.isProcessingQueue=!1,setTimeout(function(){return u.processQueue()},100)):(this.isPlaying=!1,this.isProcessingQueue=!1,this.emit("playbackStopped"));case 12:return e.a(2)}},e,this,[[2,11]])})),function(){return r.apply(this,arguments)})},{key:"stop",value:function(){this.stopImmediate()}},{key:"reset",value:function(){this.stop(),this.audioQueue=[],this.pcmChunkQueue=[]}},{key:"stopImmediate",value:function(){var e=this.isPlaying||null!==this.currentSource||this.scheduledSources.size>0;if(console.log("🛑 AudioPlayer.stopImmediate() called"),console.log(" isPlaying:",this.isPlaying),console.log(" currentSource:",null!==this.currentSource),console.log(" scheduledSources.size:",this.scheduledSources.size),console.log(" scheduledBuffers:",this.scheduledBuffers),this.currentSource){try{console.log(" Stopping currentSource..."),this.currentSource.stop()}catch(e){console.log(" currentSource already stopped or error:",e.message)}this.currentSource=null}if(this.scheduledSources.size>0){console.log(" Stopping ".concat(this.scheduledSources.size," scheduled sources..."));var t,n=0,o=Fe(this.scheduledSources);try{for(o.s();!(t=o.n()).done;){var r=t.value;try{r.stop(),n++}catch(e){console.log(" Source already stopped or not started:",e.message)}}}catch(e){o.e(e)}finally{o.f()}console.log(" Stopped ".concat(n," sources")),this.scheduledSources.clear()}this.isPlaying=!1,this.isProcessingQueue=!1,this.audioQueue=[],this.pcmChunkQueue=[],this.preparedBuffer=[],this.isProcessingPcmQueue=!1,this.isSchedulingFrames=!1,this.nextStartTime=0,this.scheduledBuffers=0,this.clearTranscriptState(),e&&(console.log("🛑 AudioPlayer: Emitting playbackStopped event (stopImmediate called)"),this.emit("playbackStopped"))}},{key:"markNewSentence",value:function(e){this.pendingSentenceText=e,console.log('📝 AudioPlayer: New sentence marked: "'.concat(e.substring(0,40),'..."'))}},{key:"startTranscriptChecker",value:function(){var e=this;if(!this.isCheckingTranscripts){this.isCheckingTranscripts=!0,console.log("📝 AudioPlayer: Transcript checker started");var t=function(){if(e.isCheckingTranscripts&&e.audioContext){var n,o=e.audioContext.currentTime,r=Fe(e.sentenceTimings);try{for(r.s();!(n=r.n()).done;){var i=n.value;!i.displayed&&o>=i.startTime&&(i.displayed=!0,console.log("📝 AudioPlayer: Display transcript at ".concat(o.toFixed(3),'s: "').concat(i.text.substring(0,40),'..."')),e.emit("transcriptDisplay",{text:i.text}))}}catch(e){r.e(e)}finally{r.f()}e.isPlaying||e.scheduledBuffers>0?requestAnimationFrame(t):(e.isCheckingTranscripts=!1,console.log("📝 AudioPlayer: Transcript checker stopped"))}};requestAnimationFrame(t)}}},{key:"clearTranscriptState",value:function(){this.pendingSentenceText=null,this.sentenceTimings=[],this.isCheckingTranscripts=!1,console.log("📝 AudioPlayer: Transcript state cleared")}},{key:"getStatus",value:function(){return{isPlaying:this.isPlaying,isProcessingQueue:this.isProcessingQueue,queueLength:this.audioQueue.length,audioContextState:this.audioContext?this.audioContext.state:"closed",outputFormat:this.outputFormat,scheduledBuffers:this.scheduledBuffers,preparedBufferLength:this.preparedBuffer.length,scheduledSourcesCount:this.scheduledSources.size}}},{key:"destroy",value:function(){this.stop(),this.stopKeepAliveOscillator(),this._audioContextStateChangeHandler&&this.audioContext&&(this.audioContext.removeEventListener("statechange",this._audioContextStateChangeHandler),this._audioContextStateChangeHandler=null),this.audioContext&&"closed"!==this.audioContext.state&&(this.audioContext.close(),this.audioContext=null),this.removeAllListeners()}}],o&&Ve(n.prototype,o),Object.defineProperty(n,"prototype",{writable:!1}),n;var n,o,r,i,a,c}(be);const Ge=We;function qe(e){return qe="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},qe(e)}function Qe(){var e,t,n="function"==typeof Symbol?Symbol:{},o=n.iterator||"@@iterator",r=n.toStringTag||"@@toStringTag";function i(n,o,r,i){var s=o&&o.prototype instanceof c?o:c,u=Object.create(s.prototype);return Je(u,"_invoke",function(n,o,r){var i,c,s,u=0,l=r||[],d=!1,p={p:0,n:0,v:e,a:f,f:f.bind(e,4),d:function(t,n){return i=t,c=0,s=e,p.n=n,a}};function f(n,o){for(c=n,s=o,t=0;!d&&u&&!r&&t<l.length;t++){var r,i=l[t],f=p.p,h=i[2];n>3?(r=h===o)&&(s=i[(c=i[4])?5:(c=3,3)],i[4]=i[5]=e):i[0]<=f&&((r=n<2&&f<i[1])?(c=0,p.v=o,p.n=i[1]):f<h&&(r=n<3||i[0]>o||o>h)&&(i[4]=n,i[5]=o,p.n=h,c=0))}if(r||n>1)return a;throw d=!0,o}return function(r,l,h){if(u>1)throw TypeError("Generator is already running");for(d&&1===l&&f(l,h),c=l,s=h;(t=c<2?e:s)||!d;){i||(c?c<3?(c>1&&(p.n=-1),f(c,s)):p.n=s:p.v=s);try{if(u=2,i){if(c||(r="next"),t=i[r]){if(!(t=t.call(i,s)))throw TypeError("iterator result is not an object");if(!t.done)return t;s=t.value,c<2&&(c=0)}else 1===c&&(t=i.return)&&t.call(i),c<2&&(s=TypeError("The iterator does not provide a '"+r+"' method"),c=1);i=e}else if((t=(d=p.n<0)?s:n.call(o,p))!==a)break}catch(t){i=e,c=1,s=t}finally{u=1}}return{value:t,done:d}}}(n,r,i),!0),u}var a={};function c(){}function s(){}function u(){}t=Object.getPrototypeOf;var l=[][o]?t(t([][o]())):(Je(t={},o,function(){return this}),t),d=u.prototype=c.prototype=Object.create(l);function p(e){return Object.setPrototypeOf?Object.setPrototypeOf(e,u):(e.__proto__=u,Je(e,r,"GeneratorFunction")),e.prototype=Object.create(d),e}return s.prototype=u,Je(d,"constructor",u),Je(u,"constructor",s),s.displayName="GeneratorFunction",Je(u,r,"GeneratorFunction"),Je(d),Je(d,r,"Generator"),Je(d,o,function(){return this}),Je(d,"toString",function(){return"[object Generator]"}),(Qe=function(){return{w:i,m:p}})()}function Je(e,t,n,o){var r=Object.defineProperty;try{r({},"",{})}catch(e){r=0}Je=function(e,t,n,o){function i(t,n){Je(e,t,function(e){return this._invoke(t,n,e)})}t?r?r(e,t,{value:n,enumerable:!o,configurable:!o,writable:!o}):e[t]=n:(i("next",0),i("throw",1),i("return",2))},Je(e,t,n,o)}function Ye(e,t,n,o,r,i,a){try{var c=e[i](a),s=c.value}catch(e){return void n(e)}c.done?t(s):Promise.resolve(s).then(o,r)}function $e(e){return function(){var t=this,n=arguments;return new Promise(function(o,r){var i=e.apply(t,n);function a(e){Ye(i,o,r,a,c,"next",e)}function c(e){Ye(i,o,r,a,c,"throw",e)}a(void 0)})}}function Xe(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,o=Array(t);n<t;n++)o[n]=e[n];return o}function Ze(e,t){for(var n=0;n<t.length;n++){var o=t[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(e,et(o.key),o)}}function et(e){var t=function(e){if("object"!=qe(e)||!e)return e;var t=e[Symbol.toPrimitive];if(void 0!==t){var n=t.call(e,"string");if("object"!=qe(n))return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}(e);return"symbol"==qe(t)?t:t+""}function tt(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(e){}return(tt=function(){return!!e})()}function nt(e){return nt=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(e){return e.__proto__||Object.getPrototypeOf(e)},nt(e)}function ot(e,t){return ot=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,t){return e.__proto__=t,e},ot(e,t)}var rt=function(e){function t(e){var n;return function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,t),(n=function(e,t,n){return t=nt(t),function(e,t){if(t&&("object"==qe(t)||"function"==typeof t))return t;if(void 0!==t)throw new TypeError("Derived constructors may only return object or undefined");return function(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}(e)}(e,tt()?Reflect.construct(t,n||[],nt(e).constructor):t.apply(e,n))}(this,t)).config=e,n.audioContext=null,n.isSharedAudioContext=!1,n.audioWorkletNode=null,n.mediaStream=null,n.isRecording=!1,n._keepAliveOscillator=null,n}return function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&ot(e,t)}(t,e),n=t,o=[{key:"getAudioProcessorPath",value:function(){if(this.config.audioProcessorPath)return this.config.audioProcessorPath;var e,t=function(e,t){var n="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!n){if(Array.isArray(e)||(n=function(e,t){if(e){if("string"==typeof e)return Xe(e,t);var n={}.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?Xe(e,t):void 0}}(e))||t&&e&&"number"==typeof e.length){n&&(e=n);var o=0,r=function(){};return{s:r,n:function(){return o>=e.length?{done:!0}:{done:!1,value:e[o++]}},e:function(e){throw e},f:r}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var i,a=!0,c=!1;return{s:function(){n=n.call(e)},n:function(){var e=n.next();return a=e.done,e},e:function(e){c=!0,i=e},f:function(){try{a||null==n.return||n.return()}finally{if(c)throw i}}}}(document.getElementsByTagName("script"));try{for(t.s();!(e=t.n()).done;){var n=e.value.src;if(n&&(n.includes("agent-widget.js")||n.includes("ttp-agent-sdk")))try{var o=n.substring(0,n.lastIndexOf("/"));return"".concat(o,"/audio-processor.js")}catch(e){var r=n.substring(0,n.lastIndexOf("/"));return"".concat(r,"/audio-processor.js")}}}catch(e){t.e(e)}finally{t.f()}return"https://cdn.talktopc.com/audio-processor.js"}},{key:"start",value:(i=$e(Qe().m(function e(){var t,n,o,r,i,a,c,s,u,l=this,d=arguments;return Qe().w(function(e){for(;;)switch(e.p=e.n){case 0:if(t=d.length>0&&void 0!==d[0]?d[0]:null,e.p=1,"https:"===location.protocol||"localhost"===location.hostname||"127.0.0.1"===location.hostname){e.n=2;break}throw n=new Error("Microphone access requires HTTPS. Please use https:// or test on localhost."),console.error("❌ AudioRecorder:",n.message),this.emit("error",n),n;case 2:if(navigator.mediaDevices&&navigator.mediaDevices.getUserMedia){e.n=3;break}throw o=new Error("getUserMedia is not supported in this browser. Please use a modern browser."),console.error("❌ AudioRecorder:",o.message),this.emit("error",o),o;case 3:return console.log("🎤 AudioRecorder: Requesting microphone access..."),e.n=4,navigator.mediaDevices.getUserMedia({audio:{sampleRate:this.config.sampleRate,channelCount:1,echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0}});case 4:if(this.mediaStream=e.v,console.log("✅ AudioRecorder: Microphone access granted"),!t||"closed"===t.state){e.n=7;break}if(console.log("🎤 AudioRecorder: Using shared AudioContext from AudioPlayer"),this.audioContext=t,this.isSharedAudioContext=!0,"suspended"!==this.audioContext.state){e.n=5;break}return console.log("🎤 AudioRecorder: Resuming shared AudioContext before use"),e.n=5,this.audioContext.resume();case 5:if("running"===this.audioContext.state){e.n=6;break}return console.log('🎤 AudioRecorder: AudioContext state is "'.concat(this.audioContext.state,'", resuming to prevent interruption...')),e.n=6,this.audioContext.resume();case 6:this._audioContextStateChangeHandler=$e(Qe().m(function e(){var t;return Qe().w(function(e){for(;;)switch(e.p=e.n){case 0:if(!l.audioContext||"suspended"!==l.audioContext.state){e.n=4;break}return console.log("🎤 AudioRecorder: AudioContext was suspended, resuming immediately to prevent playback interruption..."),e.p=1,e.n=2,l.audioContext.resume();case 2:e.n=4;break;case 3:e.p=3,t=e.v,console.warn("⚠️ AudioRecorder: Failed to resume AudioContext:",t);case 4:return e.a(2)}},e,null,[[1,3]])})),this.audioContext.addEventListener("statechange",this._audioContextStateChangeHandler);try{r=this.audioContext.createOscillator(),(i=this.audioContext.createGain()).gain.value=0,r.connect(i),i.connect(this.audioContext.destination),r.start(),this._keepAliveOscillator=r,console.log("🎤 AudioRecorder: Created silent oscillator to keep AudioContext alive during getUserMedia")}catch(e){console.warn("⚠️ AudioRecorder: Failed to create keep-alive oscillator:",e)}e.n=8;break;case 7:if(this.audioContext=new(window.AudioContext||window.webkitAudioContext)({sampleRate:this.config.sampleRate}),this.isSharedAudioContext=!1,"suspended"!==this.audioContext.state){e.n=8;break}return e.n=8,this.audioContext.resume();case 8:return a=this.getAudioProcessorPath(),e.n=9,this.audioContext.audioWorklet.addModule(a);case 9:if(!this.isSharedAudioContext||"running"===this.audioContext.state){e.n=10;break}return console.log("🎤 AudioRecorder: AudioContext suspended after AudioWorklet load, resuming..."),e.n=10,this.audioContext.resume();case 10:if(this.audioWorkletNode=new AudioWorkletNode(this.audioContext,"audio-processor"),!this.isSharedAudioContext||"running"===this.audioContext.state){e.n=11;break}return console.log("🎤 AudioRecorder: AudioContext suspended before MediaStreamSource, resuming..."),e.n=11,this.audioContext.resume();case 11:if(this.audioContext.createMediaStreamSource(this.mediaStream).connect(this.audioWorkletNode),!this.isSharedAudioContext||"running"===this.audioContext.state){e.n=12;break}return console.log("🎤 AudioRecorder: AudioContext suspended after MediaStreamSource, resuming immediately..."),e.n=12,this.audioContext.resume();case 12:if(this._keepAliveOscillator)try{this._keepAliveOscillator.stop(),this._keepAliveOscillator.disconnect(),this._keepAliveOscillator=null,console.log("🎤 AudioRecorder: Stopped keep-alive oscillator (MediaStreamSource will keep context alive)")}catch(e){console.warn("⚠️ AudioRecorder: Failed to stop keep-alive oscillator:",e)}this.audioWorkletNode.port.onmessage=function(e){var t=e.data,n=t.type,o=t.data;"pcm_audio_data"===n&&l.emit("audioData",o)},this.audioWorkletNode.port.postMessage({type:"setForceContinuous",data:{enabled:!0}}),this.isRecording=!0,this.emit("recordingStarted"),e.n=14;break;case 13:throw e.p=13,u=e.v,c=u.message,"NotAllowedError"===u.name||"PermissionDeniedError"===u.name?(c="Microphone permission denied. Please allow microphone access in your browser settings and try again.",console.error("❌ AudioRecorder: Permission denied. User needs to grant microphone access.")):"NotFoundError"===u.name||"DevicesNotFoundError"===u.name?(c="No microphone found. Please connect a microphone and try again.",console.error("❌ AudioRecorder: No microphone device found.")):"NotReadableError"===u.name||"TrackStartError"===u.name?(c="Microphone is already in use by another application. Please close other apps using the microphone and try again.",console.error("❌ AudioRecorder: Microphone is busy or not readable.")):u.message&&u.message.includes("not allowed by the user agent")&&(c="Microphone access blocked. On mobile devices, please tap the recording button directly (not from an iframe or popup).",console.error("❌ AudioRecorder: User agent blocked microphone access. This often happens on mobile when not called from direct user interaction.")),(s=new Error(c)).name=u.name,s.originalError=u,console.error("❌ AudioRecorder: Failed to start recording:",s),this.emit("error",s),s;case 14:return e.a(2)}},e,this,[[1,13]])})),function(){return i.apply(this,arguments)})},{key:"stop",value:(r=$e(Qe().m(function e(){var t;return Qe().w(function(e){for(;;)switch(e.p=e.n){case 0:if(this.isRecording){e.n=1;break}return e.a(2);case 1:if(e.p=1,!this.audioWorkletNode){e.n=2;break}return this.audioWorkletNode.port.postMessage({type:"flush"}),e.n=2,new Promise(function(e){return setTimeout(e,100)});case 2:if(this.mediaStream&&(this.mediaStream.getTracks().forEach(function(e){return e.stop()}),this.mediaStream=null),this.audioWorkletNode&&(this.audioWorkletNode.disconnect(),this.audioWorkletNode=null),this._audioContextStateChangeHandler&&this.audioContext&&(this.audioContext.removeEventListener("statechange",this._audioContextStateChangeHandler),this._audioContextStateChangeHandler=null),!this.audioContext||this.isSharedAudioContext||"closed"===this.audioContext.state){e.n=4;break}return e.n=3,this.audioContext.close();case 3:this.audioContext=null,e.n=5;break;case 4:this.isSharedAudioContext&&(this.audioContext=null,this.isSharedAudioContext=!1);case 5:this.isRecording=!1,this.emit("recordingStopped"),e.n=7;break;case 6:throw e.p=6,t=e.v,this.emit("error",t),t;case 7:return e.a(2)}},e,this,[[1,6]])})),function(){return r.apply(this,arguments)})},{key:"getStatus",value:function(){return{isRecording:this.isRecording,audioContextState:this.audioContext?this.audioContext.state:"closed"}}},{key:"destroy",value:function(){this.stop()}}],o&&Ze(n.prototype,o),Object.defineProperty(n,"prototype",{writable:!1}),n;var n,o,r,i}(be);function it(e){return it="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},it(e)}function at(e,t){for(var n=0;n<t.length;n++){var o=t[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(e,ct(o.key),o)}}function ct(e){var t=function(e){if("object"!=it(e)||!e)return e;var t=e[Symbol.toPrimitive];if(void 0!==t){var n=t.call(e,"string");if("object"!=it(n))return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}(e);return"symbol"==it(t)?t:t+""}const st=function(){function e(){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e)}return t=e,n=[{key:"extractPcmFromWav",value:function(e){var t=e instanceof Uint8Array?e:new Uint8Array(e);if(t.length<44)throw new Error("WAV data too short (< 44 bytes)");if("RIFF"!==String.fromCharCode(t[0],t[1],t[2],t[3]))throw new Error("Not a valid WAV file - missing RIFF header");if("WAVE"!==String.fromCharCode(t[8],t[9],t[10],t[11]))throw new Error("Not a valid WAV file - missing WAVE format");for(var n=t[22]|t[23]<<8,o=t[24]|t[25]<<8|t[26]<<16|t[27]<<24,r=t[34]|t[35]<<8,i=-1,a=12;a<t.length-8;a+=4){if("data"===String.fromCharCode(t[a],t[a+1],t[a+2],t[a+3])){i=a;break}a+=4+(t[a+4]|t[a+5]<<8|t[a+6]<<16|t[a+7]<<24)}if(-1===i)throw new Error("No data chunk found in WAV");var c=t[i+4]|t[i+5]<<8|t[i+6]<<16|t[i+7]<<24,s=i+8,u=Math.min(c,t.length-s);return{pcmData:t.slice(s,s+u).buffer,format:{sampleRate:o,channels:n,bitDepth:r}}}},{key:"isWavFile",value:function(e){return e.length>=44&&82===e[0]&&73===e[1]&&70===e[2]&&70===e[3]}},{key:"createWavHeader",value:function(e,t,n,o){var r=new ArrayBuffer(44),i=new DataView(r);return i.setUint32(0,1380533830,!1),i.setUint32(4,36+e,!0),i.setUint32(8,1463899717,!1),i.setUint32(12,1718449184,!1),i.setUint32(16,16,!0),i.setUint16(20,1,!0),i.setUint16(22,n,!0),i.setUint32(24,t,!0),i.setUint32(28,t*n*o/8,!0),i.setUint16(32,n*o/8,!0),i.setUint16(34,o,!0),i.setUint32(36,1684108385,!1),i.setUint32(40,e,!0),r}},{key:"wrapPcmInWav",value:function(t,n){var o=e.createWavHeader(t.byteLength,n.sampleRate,n.channels||1,n.bitDepth||16),r=new Uint8Array(o.byteLength+t.byteLength);return r.set(new Uint8Array(o),0),r.set(new Uint8Array(t),o.byteLength),r.buffer}}],null&&at(t.prototype,null),n&&at(t,n),Object.defineProperty(t,"prototype",{writable:!1}),t;var t,n}();function ut(e){return ut="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},ut(e)}function lt(e,t){for(var n=0;n<t.length;n++){var o=t[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(e,dt(o.key),o)}}function dt(e){var t=function(e){if("object"!=ut(e)||!e)return e;var t=e[Symbol.toPrimitive];if(void 0!==t){var n=t.call(e,"string");if("object"!=ut(n))return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}(e);return"symbol"==ut(t)?t:t+""}const pt=function(){return e=function e(){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),this.codecs={pcm:new Ce,pcmu:new Ee,pcma:new je}},(t=[{key:"decodeToPcm",value:function(e,t){var n=null==t?void 0:t.toLowerCase();if(!n||"pcm"===n)return e instanceof ArrayBuffer?e:e instanceof Uint8Array?e.buffer:e;var o=this.codecs[n];if(!o)throw new Error("Unsupported encoding: ".concat(t));var r=e instanceof Uint8Array?e:new Uint8Array(e);return o.decode(r)}},{key:"encodeFromPcm",value:function(e,t){var n=null==t?void 0:t.toLowerCase();if(!n||"pcm"===n)return e;var o=this.codecs[n];if(!o)throw new Error("Unsupported target encoding: ".concat(t));var r=o.encode(e);return r instanceof Uint8Array?r.buffer:r}},{key:"getCodec",value:function(e){var t=null==e?void 0:e.toLowerCase();return this.codecs[t]||null}}])&<(e.prototype,t),Object.defineProperty(e,"prototype",{writable:!1}),e;var e,t}();function ft(e){return ft="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},ft(e)}function ht(e,t){for(var n=0;n<t.length;n++){var o=t[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(e,vt(o.key),o)}}function vt(e){var t=function(e){if("object"!=ft(e)||!e)return e;var t=e[Symbol.toPrimitive];if(void 0!==t){var n=t.call(e,"string");if("object"!=ft(n))return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}(e);return"symbol"==ft(t)?t:t+""}const gt=function(){function e(){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e)}return t=e,n=[{key:"convert",value:function(t,n,o){if(n===o)return t;if(8===n)throw new Error("Source bit depth cannot be 8-bit (only 16-bit or 24-bit supported)");var r=n/8,i=o/8,a=t.byteLength/r;if(new ArrayBuffer(a*i),16===n&&16===o)return t;if(24===n&&16===o)return e.convert24To16(t);if(16===n&&24===o)return e.convert16To24(t);if(16===n&&8===o)return e.convert16To8(t);if(24===n&&8===o)return e.convert24To8(t);throw new Error("Unsupported bit depth conversion: ".concat(n,"-bit → ").concat(o,"-bit"))}},{key:"convert24To16",value:function(e){for(var t=new Uint8Array(e),n=Math.floor(t.length/3),o=new Int16Array(n),r=0;r<n;r++){var i=t[3*r],a=t[3*r+1],c=t[3*r+2],s=i|a<<8|(255&c)<<16;128&c&&(s|=4278190080),o[r]=Math.max(-32768,Math.min(32767,Math.round(s/256)))}return o.buffer}},{key:"convert16To24",value:function(e){for(var t=new Int16Array(e),n=new Uint8Array(3*t.length),o=0;o<t.length;o++){var r=256*t[o];n[3*o]=255&r,n[3*o+1]=r>>8&255,n[3*o+2]=r>>16&255}return n.buffer}},{key:"convert16To8",value:function(e){for(var t=new Int16Array(e),n=new Uint8Array(t.length),o=0;o<t.length;o++){var r=t[o];n[o]=Math.max(0,Math.min(255,Math.round(r/256+128)))}return n.buffer}},{key:"convert24To8",value:function(t){var n=e.convert24To16(t);return e.convert16To8(n)}}],null&&ht(t.prototype,null),n&&ht(t,n),Object.defineProperty(t,"prototype",{writable:!1}),t;var t,n}();function yt(e){return yt="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},yt(e)}function mt(){var e,t,n="function"==typeof Symbol?Symbol:{},o=n.iterator||"@@iterator",r=n.toStringTag||"@@toStringTag";function i(n,o,r,i){var s=o&&o.prototype instanceof c?o:c,u=Object.create(s.prototype);return bt(u,"_invoke",function(n,o,r){var i,c,s,u=0,l=r||[],d=!1,p={p:0,n:0,v:e,a:f,f:f.bind(e,4),d:function(t,n){return i=t,c=0,s=e,p.n=n,a}};function f(n,o){for(c=n,s=o,t=0;!d&&u&&!r&&t<l.length;t++){var r,i=l[t],f=p.p,h=i[2];n>3?(r=h===o)&&(s=i[(c=i[4])?5:(c=3,3)],i[4]=i[5]=e):i[0]<=f&&((r=n<2&&f<i[1])?(c=0,p.v=o,p.n=i[1]):f<h&&(r=n<3||i[0]>o||o>h)&&(i[4]=n,i[5]=o,p.n=h,c=0))}if(r||n>1)return a;throw d=!0,o}return function(r,l,h){if(u>1)throw TypeError("Generator is already running");for(d&&1===l&&f(l,h),c=l,s=h;(t=c<2?e:s)||!d;){i||(c?c<3?(c>1&&(p.n=-1),f(c,s)):p.n=s:p.v=s);try{if(u=2,i){if(c||(r="next"),t=i[r]){if(!(t=t.call(i,s)))throw TypeError("iterator result is not an object");if(!t.done)return t;s=t.value,c<2&&(c=0)}else 1===c&&(t=i.return)&&t.call(i),c<2&&(s=TypeError("The iterator does not provide a '"+r+"' method"),c=1);i=e}else if((t=(d=p.n<0)?s:n.call(o,p))!==a)break}catch(t){i=e,c=1,s=t}finally{u=1}}return{value:t,done:d}}}(n,r,i),!0),u}var a={};function c(){}function s(){}function u(){}t=Object.getPrototypeOf;var l=[][o]?t(t([][o]())):(bt(t={},o,function(){return this}),t),d=u.prototype=c.prototype=Object.create(l);function p(e){return Object.setPrototypeOf?Object.setPrototypeOf(e,u):(e.__proto__=u,bt(e,r,"GeneratorFunction")),e.prototype=Object.create(d),e}return s.prototype=u,bt(d,"constructor",u),bt(u,"constructor",s),s.displayName="GeneratorFunction",bt(u,r,"GeneratorFunction"),bt(d),bt(d,r,"Generator"),bt(d,o,function(){return this}),bt(d,"toString",function(){return"[object Generator]"}),(mt=function(){return{w:i,m:p}})()}function bt(e,t,n,o){var r=Object.defineProperty;try{r({},"",{})}catch(e){r=0}bt=function(e,t,n,o){function i(t,n){bt(e,t,function(e){return this._invoke(t,n,e)})}t?r?r(e,t,{value:n,enumerable:!o,configurable:!o,writable:!o}):e[t]=n:(i("next",0),i("throw",1),i("return",2))},bt(e,t,n,o)}function St(e,t,n,o,r,i,a){try{var c=e[i](a),s=c.value}catch(e){return void n(e)}c.done?t(s):Promise.resolve(s).then(o,r)}function wt(e,t){for(var n=0;n<t.length;n++){var o=t[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(e,xt(o.key),o)}}function xt(e){var t=function(e){if("object"!=yt(e)||!e)return e;var t=e[Symbol.toPrimitive];if(void 0!==t){var n=t.call(e,"string");if("object"!=yt(n))return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}(e);return"symbol"==yt(t)?t:t+""}const Ct=function(){return e=function e(){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e)},t=[{key:"resample",value:(n=mt().m(function e(t,n,o){var r,i,a,c,s,u,l,d,p,f,h,v,g;return mt().w(function(e){for(;;)switch(e.n){case 0:if(n!==o){e.n=1;break}return e.a(2,t);case 1:for(r=new Int16Array(t),i=new Float32Array(r.length),a=1/32768,c=0;c<r.length;c++)i[c]=r[c]*a;return s=Math.ceil(i.length*o/n),u=new OfflineAudioContext(1,s,o),(l=u.createBuffer(1,i.length,n)).getChannelData(0).set(i),(d=u.createBufferSource()).buffer=l,d.connect(u.destination),d.start(),e.n=2,u.startRendering();case 2:for(p=e.v,f=p.getChannelData(0),h=new Int16Array(f.length),v=0;v<f.length;v++)g=Math.max(-1,Math.min(1,f[v])),h[v]=Math.round(32767*g);return e.a(2,h.buffer)}},e)}),o=function(){var e=this,t=arguments;return new Promise(function(o,r){var i=n.apply(e,t);function a(e){St(i,o,r,a,c,"next",e)}function c(e){St(i,o,r,a,c,"throw",e)}a(void 0)})},function(e,t,n){return o.apply(this,arguments)})}],t&&wt(e,t),Object.defineProperty(e,"prototype",{writable:!1}),e;var e,t,n,o}();function kt(e){return kt="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},kt(e)}function Pt(e,t){for(var n=0;n<t.length;n++){var o=t[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(e,Ot(o.key),o)}}function Ot(e){var t=function(e){if("object"!=kt(e)||!e)return e;var t=e[Symbol.toPrimitive];if(void 0!==t){var n=t.call(e,"string");if("object"!=kt(n))return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}(e);return"symbol"==kt(t)?t:t+""}const Et=function(){function e(){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e)}return t=e,n=[{key:"convert",value:function(t,n,o){var r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:16;if(n===o)return t;if(1===n&&1===o)return t;if(1===n&&2===o)return e.monoToStereo(t,r);if(2===n&&1===o)return e.stereoToMono(t,r);throw new Error("Unsupported channel conversion: ".concat(n," → ").concat(o))}},{key:"monoToStereo",value:function(e,t){for(var n=t/8,o=e.byteLength/n,r=new ArrayBuffer(o*n*2),i=new Uint8Array(e),a=new Uint8Array(r),c=0;c<o;c++)for(var s=c*n,u=c*n*2,l=0;l<n;l++)a[u+l]=i[s+l],a[u+n+l]=i[s+l];return r}},{key:"stereoToMono",value:function(e,t){var n=t/8,o=e.byteLength/(2*n),r=new ArrayBuffer(o*n),i=new Uint8Array(e),a=new Uint8Array(r);if(16===t)for(var c=0;c<o;c++){var s=c*n*2,u=s+n,l=(i[s]|i[s+1]<<8)<<16>>16,d=(i[u]|i[u+1]<<8)<<16>>16,p=Math.round((l+d)/2),f=c*n;a[f]=255&p,a[f+1]=p>>8&255}else for(var h=0;h<o;h++)for(var v=h*n*2,g=h*n,y=0;y<n;y++)a[g+y]=i[v+y];return r}}],null&&Pt(t.prototype,null),n&&Pt(t,n),Object.defineProperty(t,"prototype",{writable:!1}),t;var t,n}();function Tt(e){return Tt="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},Tt(e)}function At(){var e,t,n="function"==typeof Symbol?Symbol:{},o=n.iterator||"@@iterator",r=n.toStringTag||"@@toStringTag";function i(n,o,r,i){var s=o&&o.prototype instanceof c?o:c,u=Object.create(s.prototype);return It(u,"_invoke",function(n,o,r){var i,c,s,u=0,l=r||[],d=!1,p={p:0,n:0,v:e,a:f,f:f.bind(e,4),d:function(t,n){return i=t,c=0,s=e,p.n=n,a}};function f(n,o){for(c=n,s=o,t=0;!d&&u&&!r&&t<l.length;t++){var r,i=l[t],f=p.p,h=i[2];n>3?(r=h===o)&&(s=i[(c=i[4])?5:(c=3,3)],i[4]=i[5]=e):i[0]<=f&&((r=n<2&&f<i[1])?(c=0,p.v=o,p.n=i[1]):f<h&&(r=n<3||i[0]>o||o>h)&&(i[4]=n,i[5]=o,p.n=h,c=0))}if(r||n>1)return a;throw d=!0,o}return function(r,l,h){if(u>1)throw TypeError("Generator is already running");for(d&&1===l&&f(l,h),c=l,s=h;(t=c<2?e:s)||!d;){i||(c?c<3?(c>1&&(p.n=-1),f(c,s)):p.n=s:p.v=s);try{if(u=2,i){if(c||(r="next"),t=i[r]){if(!(t=t.call(i,s)))throw TypeError("iterator result is not an object");if(!t.done)return t;s=t.value,c<2&&(c=0)}else 1===c&&(t=i.return)&&t.call(i),c<2&&(s=TypeError("The iterator does not provide a '"+r+"' method"),c=1);i=e}else if((t=(d=p.n<0)?s:n.call(o,p))!==a)break}catch(t){i=e,c=1,s=t}finally{u=1}}return{value:t,done:d}}}(n,r,i),!0),u}var a={};function c(){}function s(){}function u(){}t=Object.getPrototypeOf;var l=[][o]?t(t([][o]())):(It(t={},o,function(){return this}),t),d=u.prototype=c.prototype=Object.create(l);function p(e){return Object.setPrototypeOf?Object.setPrototypeOf(e,u):(e.__proto__=u,It(e,r,"GeneratorFunction")),e.prototype=Object.create(d),e}return s.prototype=u,It(d,"constructor",u),It(u,"constructor",s),s.displayName="GeneratorFunction",It(u,r,"GeneratorFunction"),It(d),It(d,r,"Generator"),It(d,o,function(){return this}),It(d,"toString",function(){return"[object Generator]"}),(At=function(){return{w:i,m:p}})()}function It(e,t,n,o){var r=Object.defineProperty;try{r({},"",{})}catch(e){r=0}It=function(e,t,n,o){function i(t,n){It(e,t,function(e){return this._invoke(t,n,e)})}t?r?r(e,t,{value:n,enumerable:!o,configurable:!o,writable:!o}):e[t]=n:(i("next",0),i("throw",1),i("return",2))},It(e,t,n,o)}function jt(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(e);t&&(o=o.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,o)}return n}function Dt(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?jt(Object(n),!0).forEach(function(t){Ft(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):jt(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}function Ft(e,t,n){return(t=_t(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function Bt(e,t,n,o,r,i,a){try{var c=e[i](a),s=c.value}catch(e){return void n(e)}c.done?t(s):Promise.resolve(s).then(o,r)}function Rt(e,t){for(var n=0;n<t.length;n++){var o=t[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(e,_t(o.key),o)}}function _t(e){var t=function(e){if("object"!=Tt(e)||!e)return e;var t=e[Symbol.toPrimitive];if(void 0!==t){var n=t.call(e,"string");if("object"!=Tt(n))return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}(e);return"symbol"==Tt(t)?t:t+""}const Ut=function(){return e=function e(t,n){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),this.requestedFormat=t,this.actualFormat=n,this.encodingConverter=new pt,this.conversionSteps=[],this._analyzeConversions()},t=[{key:"_analyzeConversions",value:function(){this.conversionSteps=[],this.actualFormat.container!==this.requestedFormat.container&&("wav"===this.actualFormat.container?this.conversionSteps.push("extract_wav"):"wav"===this.requestedFormat.container&&this.conversionSteps.push("wrap_wav")),this.actualFormat.encoding!==this.requestedFormat.encoding&&("pcm"!==this.actualFormat.encoding&&this.conversionSteps.push("decode_encoding"),"pcm"!==this.requestedFormat.encoding&&this.conversionSteps.push("encode_encoding")),this.actualFormat.sampleRate!==this.requestedFormat.sampleRate&&this.conversionSteps.push("resample"),this.actualFormat.bitDepth!==this.requestedFormat.bitDepth&&this.conversionSteps.push("convert_bitdepth"),this.actualFormat.channels!==this.requestedFormat.channels&&this.conversionSteps.push("convert_channels")}},{key:"needsConversion",value:function(){return this.conversionSteps.length>0}},{key:"getConversionSteps",value:function(){var e=[];return this.conversionSteps.includes("extract_wav")&&e.push("Extract PCM from WAV (".concat(this.actualFormat.container," → raw)")),this.conversionSteps.includes("decode_encoding")&&e.push("Decode ".concat(this.actualFormat.encoding.toUpperCase()," → PCM")),this.conversionSteps.includes("resample")&&e.push("Resample ".concat(this.actualFormat.sampleRate,"Hz → ").concat(this.requestedFormat.sampleRate,"Hz")),this.conversionSteps.includes("convert_bitdepth")&&e.push("Convert bit depth ".concat(this.actualFormat.bitDepth,"-bit → ").concat(this.requestedFormat.bitDepth,"-bit")),this.conversionSteps.includes("convert_channels")&&e.push("Convert channels ".concat(this.actualFormat.channels," → ").concat(this.requestedFormat.channels)),this.conversionSteps.includes("encode_encoding")&&e.push("Encode PCM → ".concat(this.requestedFormat.encoding.toUpperCase())),this.conversionSteps.includes("wrap_wav")&&e.push("Wrap in WAV container (raw → ".concat(this.requestedFormat.container,")")),e}},{key:"convert",value:(n=At().m(function e(t){var n,o,r,i;return At().w(function(e){for(;;)switch(e.n){case 0:if(this.needsConversion()){e.n=1;break}return e.a(2,t instanceof ArrayBuffer?t:t.buffer);case 1:if(n=t instanceof ArrayBuffer?t:t.buffer,o=Dt({},this.actualFormat),this.conversionSteps.includes("extract_wav")&&(r=st.extractPcmFromWav(n),n=r.pcmData,o=Dt(Dt({},o),{},{container:"raw",sampleRate:r.format.sampleRate,channels:r.format.channels,bitDepth:r.format.bitDepth}),console.log("🔄 AudioFormatConverter: Extracted PCM from WAV",r.format)),this.conversionSteps.includes("decode_encoding")&&(n=this.encodingConverter.decodeToPcm(n,o.encoding),o.encoding="pcm",o.bitDepth=16,console.log("🔄 AudioFormatConverter: Decoded ".concat(this.actualFormat.encoding.toUpperCase()," → PCM"))),24===o.bitDepth&&o.bitDepth!==this.requestedFormat.bitDepth&&(this.conversionSteps.includes("resample")||this.conversionSteps.includes("convert_channels")||24!==this.requestedFormat.bitDepth)&&(n=gt.convert(n,24,16),o.bitDepth=16,console.log("🔄 AudioFormatConverter: Normalized 24-bit → 16-bit PCM")),!this.conversionSteps.includes("resample")){e.n=3;break}return e.n=2,Ct.resample(n,o.sampleRate,this.requestedFormat.sampleRate);case 2:n=e.v,o.sampleRate=this.requestedFormat.sampleRate,console.log("🔄 AudioFormatConverter: Resampled ".concat(this.actualFormat.sampleRate,"Hz → ").concat(this.requestedFormat.sampleRate,"Hz"));case 3:return this.conversionSteps.includes("convert_channels")&&(n=Et.convert(n,o.channels,this.requestedFormat.channels,o.bitDepth),o.channels=this.requestedFormat.channels,console.log("🔄 AudioFormatConverter: Converted channels ".concat(this.actualFormat.channels," → ").concat(this.requestedFormat.channels))),this.conversionSteps.includes("convert_bitdepth")&&(n=gt.convert(n,o.bitDepth,this.requestedFormat.bitDepth),o.bitDepth=this.requestedFormat.bitDepth,console.log("🔄 AudioFormatConverter: Converted bit depth ".concat(this.actualFormat.bitDepth,"-bit → ").concat(this.requestedFormat.bitDepth,"-bit"))),this.conversionSteps.includes("encode_encoding")&&(i=this.encodingConverter.encodeFromPcm(n,this.requestedFormat.encoding),n=i instanceof ArrayBuffer?i:i.buffer,o.encoding=this.requestedFormat.encoding,console.log("🔄 AudioFormatConverter: Encoded PCM → ".concat(this.requestedFormat.encoding.toUpperCase()))),this.conversionSteps.includes("wrap_wav")&&(n=st.wrapPcmInWav(n,o),o.container="wav",console.log("🔄 AudioFormatConverter: Wrapped in WAV container")),console.log("✅ AudioFormatConverter: Conversion complete"),e.a(2,n)}},e,this)}),o=function(){var e=this,t=arguments;return new Promise(function(o,r){var i=n.apply(e,t);function a(e){Bt(i,o,r,a,c,"next",e)}function c(e){Bt(i,o,r,a,c,"throw",e)}a(void 0)})},function(e){return o.apply(this,arguments)})}],t&&Rt(e.prototype,t),Object.defineProperty(e,"prototype",{writable:!1}),e;var e,t,n,o}();function Mt(e){return Mt="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},Mt(e)}function Nt(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(e);t&&(o=o.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,o)}return n}function Vt(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?Nt(Object(n),!0).forEach(function(t){Jt(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):Nt(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}function Kt(){var e,t,n="function"==typeof Symbol?Symbol:{},o=n.iterator||"@@iterator",r=n.toStringTag||"@@toStringTag";function i(n,o,r,i){var s=o&&o.prototype instanceof c?o:c,u=Object.create(s.prototype);return Lt(u,"_invoke",function(n,o,r){var i,c,s,u=0,l=r||[],d=!1,p={p:0,n:0,v:e,a:f,f:f.bind(e,4),d:function(t,n){return i=t,c=0,s=e,p.n=n,a}};function f(n,o){for(c=n,s=o,t=0;!d&&u&&!r&&t<l.length;t++){var r,i=l[t],f=p.p,h=i[2];n>3?(r=h===o)&&(s=i[(c=i[4])?5:(c=3,3)],i[4]=i[5]=e):i[0]<=f&&((r=n<2&&f<i[1])?(c=0,p.v=o,p.n=i[1]):f<h&&(r=n<3||i[0]>o||o>h)&&(i[4]=n,i[5]=o,p.n=h,c=0))}if(r||n>1)return a;throw d=!0,o}return function(r,l,h){if(u>1)throw TypeError("Generator is already running");for(d&&1===l&&f(l,h),c=l,s=h;(t=c<2?e:s)||!d;){i||(c?c<3?(c>1&&(p.n=-1),f(c,s)):p.n=s:p.v=s);try{if(u=2,i){if(c||(r="next"),t=i[r]){if(!(t=t.call(i,s)))throw TypeError("iterator result is not an object");if(!t.done)return t;s=t.value,c<2&&(c=0)}else 1===c&&(t=i.return)&&t.call(i),c<2&&(s=TypeError("The iterator does not provide a '"+r+"' method"),c=1);i=e}else if((t=(d=p.n<0)?s:n.call(o,p))!==a)break}catch(t){i=e,c=1,s=t}finally{u=1}}return{value:t,done:d}}}(n,r,i),!0),u}var a={};function c(){}function s(){}function u(){}t=Object.getPrototypeOf;var l=[][o]?t(t([][o]())):(Lt(t={},o,function(){return this}),t),d=u.prototype=c.prototype=Object.create(l);function p(e){return Object.setPrototypeOf?Object.setPrototypeOf(e,u):(e.__proto__=u,Lt(e,r,"GeneratorFunction")),e.prototype=Object.create(d),e}return s.prototype=u,Lt(d,"constructor",u),Lt(u,"constructor",s),s.displayName="GeneratorFunction",Lt(u,r,"GeneratorFunction"),Lt(d),Lt(d,r,"Generator"),Lt(d,o,function(){return this}),Lt(d,"toString",function(){return"[object Generator]"}),(Kt=function(){return{w:i,m:p}})()}function Lt(e,t,n,o){var r=Object.defineProperty;try{r({},"",{})}catch(e){r=0}Lt=function(e,t,n,o){function i(t,n){Lt(e,t,function(e){return this._invoke(t,n,e)})}t?r?r(e,t,{value:n,enumerable:!o,configurable:!o,writable:!o}):e[t]=n:(i("next",0),i("throw",1),i("return",2))},Lt(e,t,n,o)}function zt(e,t,n,o,r,i,a){try{var c=e[i](a),s=c.value}catch(e){return void n(e)}c.done?t(s):Promise.resolve(s).then(o,r)}function Ht(e){return function(){var t=this,n=arguments;return new Promise(function(o,r){var i=e.apply(t,n);function a(e){zt(i,o,r,a,c,"next",e)}function c(e){zt(i,o,r,a,c,"throw",e)}a(void 0)})}}function Wt(e,t){for(var n=0;n<t.length;n++){var o=t[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(e,Yt(o.key),o)}}function Gt(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(e){}return(Gt=function(){return!!e})()}function qt(e){return qt=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(e){return e.__proto__||Object.getPrototypeOf(e)},qt(e)}function Qt(e,t){return Qt=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,t){return e.__proto__=t,e},Qt(e,t)}function Jt(e,t,n){return(t=Yt(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function Yt(e){var t=function(e){if("object"!=Mt(e)||!e)return e;var t=e[Symbol.toPrimitive];if(void 0!==t){var n=t.call(e,"string");if("object"!=Mt(n))return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}(e);return"symbol"==Mt(t)?t:t+""}var $t=function(e){function t(){var e,n=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,t),(e=function(e,t,n){return t=qt(t),function(e,t){if(t&&("object"==Mt(t)||"function"==typeof t))return t;if(void 0!==t)throw new TypeError("Derived constructors may only return object or undefined");return function(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}(e)}(e,Gt()?Reflect.construct(t,n||[],qt(e).constructor):t.apply(e,n))}(this,t)).version="2.0.0",e.config={websocketUrl:n.websocketUrl||"wss://speech.talktopc.com/ws/conv",agentId:n.agentId,appId:n.appId,sampleRate:n.sampleRate||16e3,channels:n.channels||1,bitDepth:n.bitDepth||16,audioProcessorPath:n.audioProcessorPath,outputContainer:n.outputContainer||e.getDefaultContainer(n),outputEncoding:n.outputEncoding||n.outputCodec||"pcm",outputSampleRate:n.outputSampleRate||16e3,outputChannels:n.outputChannels||1,outputBitDepth:n.outputBitDepth||16,outputFrameDurationMs:n.outputFrameDurationMs||600,outputCodec:n.outputCodec,agentSettingsOverride:n.agentSettingsOverride||null,variables:n.variables||null,autoReconnect:!1!==n.autoReconnect,protocolVersion:n.protocolVersion||2},e.isConnected=!1,e.hasEverConnected=!1,e.isRecording=!1,e.isPlaying=!1,e.isDestroyed=!1,e.outputAudioFormat=null,e.requestedOutputFormat=null,e.formatConverter=null,e.websocket=null,e.conversationId=null,e.transcriptQueue=[],e.currentPlayingSentenceId=null,e.audioFrameCount=0,e.audioPlayer=new Ge(e.config),e.audioRecorder=new rt(e.config),e.setupAudioPlayerEvents(),e.setupAudioRecorderEvents(),e.validateConfig(),console.log("🎵 VoiceSDK v2 initialized:",{version:e.version,outputContainer:e.config.outputContainer,outputEncoding:e.config.outputEncoding,outputSampleRate:e.config.outputSampleRate}),e}return function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&Qt(e,t)}(t,e),n=t,o=[{key:"getDefaultContainer",value:function(e){return"wav"===e.outputCodec?"wav":"raw"}},{key:"validateInputFormat",value:function(e){var n;if(!e)return"Input format is required";var o=null===(n=e.encoding)||void 0===n?void 0:n.toLowerCase();return o&&t.SUPPORTED_INPUT_ENCODINGS.includes(o)?e.sampleRate&&t.SUPPORTED_INPUT_SAMPLE_RATES.includes(e.sampleRate)?e.bitDepth&&t.SUPPORTED_INPUT_BIT_DEPTHS.includes(e.bitDepth)?e.channels&&t.SUPPORTED_INPUT_CHANNELS.includes(e.channels)?null:"Unsupported input channels: ".concat(e.channels,". Supported: ").concat(t.SUPPORTED_INPUT_CHANNELS.join(", ")):"Unsupported input bit depth: ".concat(e.bitDepth,". Supported: ").concat(t.SUPPORTED_INPUT_BIT_DEPTHS.join(", ")):"Unsupported input sample rate: ".concat(e.sampleRate,". Supported: ").concat(t.SUPPORTED_INPUT_SAMPLE_RATES.join(", ")):"Unsupported input encoding: ".concat(e.encoding,". Supported: ").concat(t.SUPPORTED_INPUT_ENCODINGS.join(", "))}},{key:"validateOutputFormat",value:function(e){var n,o;if(!e)return"Output format is required";var r=null===(n=e.encoding)||void 0===n?void 0:n.toLowerCase();if(!r||!t.SUPPORTED_OUTPUT_ENCODINGS.includes(r))return"Unsupported output encoding: ".concat(e.encoding,". Supported: ").concat(t.SUPPORTED_OUTPUT_ENCODINGS.join(", "));if(!e.sampleRate||!t.SUPPORTED_OUTPUT_SAMPLE_RATES.includes(e.sampleRate))return"Unsupported output sample rate: ".concat(e.sampleRate,". Supported: ").concat(t.SUPPORTED_OUTPUT_SAMPLE_RATES.join(", "));if(!e.bitDepth||!t.SUPPORTED_OUTPUT_BIT_DEPTHS.includes(e.bitDepth))return"Unsupported output bit depth: ".concat(e.bitDepth,". Supported: ").concat(t.SUPPORTED_OUTPUT_BIT_DEPTHS.join(", "));if(!e.channels||!t.SUPPORTED_OUTPUT_CHANNELS.includes(e.channels))return"Unsupported output channels: ".concat(e.channels,". Supported: ").concat(t.SUPPORTED_OUTPUT_CHANNELS.join(", "));var i=null===(o=e.container)||void 0===o?void 0:o.toLowerCase();return i&&t.SUPPORTED_OUTPUT_CONTAINERS.includes(i)?null:"Unsupported output container: ".concat(e.container,". Supported: ").concat(t.SUPPORTED_OUTPUT_CONTAINERS.join(", "))}},{key:"validateConfig",value:function(){var e={encoding:"pcm",sampleRate:this.config.sampleRate,channels:this.config.channels,bitDepth:this.config.bitDepth},t=this.validateInputFormat(e);if(t)return console.error("❌ VoiceSDK v2: Invalid input format:",t),void this.emit("error",new Error(t));var n={encoding:this.config.outputEncoding,sampleRate:this.config.outputSampleRate,channels:this.config.outputChannels,bitDepth:this.config.outputBitDepth,container:this.config.outputContainer},o=this.validateOutputFormat(n);if(o)return console.error("❌ VoiceSDK v2: Invalid output format:",o),void this.emit("error",new Error(o));console.log("✅ VoiceSDK v2: Format validation passed")}},{key:"setupAudioPlayerEvents",value:function(){var e=this;this.audioPlayer.on("playbackStarted",function(){e.isPlaying=!0,e.emit("playbackStarted"),e.isConnected?(console.log("📤 VoiceSDK v2: Sending audio_started_playing message to server"),e.sendMessage({t:"audio_started_playing"})):console.warn("⚠️ VoiceSDK v2: Cannot send audio_started_playing - not connected")}),this.audioPlayer.on("transcriptDisplay",function(t){var n=e.currentPlayingSentenceId?e.currentPlayingSentenceId+1:1;e.currentPlayingSentenceId=n;var o={text:t.text,role:"assistant",sentenceId:n,final:!0,timestamp:Date.now()};console.log("📝 VoiceSDK v2: Emitting synced transcriptDisplay from AudioPlayer:",o),e.emit("transcriptDisplay",o),e.emit("transcript",o)}),this.audioPlayer.on("playbackStopped",function(){e.isPlaying=!1,e.emit("playbackStopped"),e.isConnected?(console.log("📤 VoiceSDK v2: Sending audio_stopped_playing message to server"),e.sendMessage({t:"audio_stopped_playing"})):console.warn("⚠️ VoiceSDK v2: Cannot send audio_stopped_playing - not connected")}),this.audioPlayer.on("playbackError",function(t){e.emit("playbackError",t),e.emit("error",t)})}},{key:"setupAudioRecorderEvents",value:function(){var e=this;this.audioRecorder.on("recordingStarted",function(){e.isRecording=!0;var t=e.audioPlayer.getStatus(),n=t.scheduledBuffers&&t.scheduledBuffers>0||t.scheduledSourcesCount&&t.scheduledSourcesCount>0,o=e.isPlaying||t.isPlaying||n;console.log("🎤 VoiceSDK v2: Recording started - checking for barge-in..."),console.log(" VoiceSDK.isPlaying:",e.isPlaying),console.log(" AudioPlayer.isPlaying:",t.isPlaying),console.log(" scheduledBuffers:",t.scheduledBuffers||0),console.log(" scheduledSourcesCount:",t.scheduledSourcesCount||0),console.log(" preparedBufferLength:",t.preparedBufferLength||0),console.log(" isActuallyPlaying:",o),o?(console.log("🛑 VoiceSDK v2: Barge-in detected! Stopping audio playback..."),e.stopAudioPlayback(),console.log("✅ VoiceSDK v2: Audio playback stopped"),e.isConnected?(e.sendMessage({t:"barge_in"}),console.log("📤 VoiceSDK v2: Sent barge_in message to server")):console.warn("⚠️ VoiceSDK v2: Cannot send barge_in - not connected")):console.log("ℹ️ VoiceSDK v2: No audio playing, normal recording start"),e.emit("recordingStarted")}),this.audioRecorder.on("recordingStopped",function(){e.isRecording&&(e.isRecording=!1,e._bargeInChecked=!1,e.emit("recordingStopped"),console.log("🛑 VoiceSDK v2: Recording stopped (from audioRecorder event)"))}),this.audioRecorder.on("audioData",function(t){if(!e._bargeInChecked&&e.isRecording){e._bargeInChecked=!0;var n=e.audioPlayer.getStatus(),o=n.scheduledBuffers&&n.scheduledBuffers>0||n.scheduledSourcesCount&&n.scheduledSourcesCount>0;(e.isPlaying||n.isPlaying||o)&&(console.log("🛑 VoiceSDK v2: Barge-in detected on first audio data! Stopping audio playback..."),console.log(" VoiceSDK.isPlaying:",e.isPlaying),console.log(" AudioPlayer.isPlaying:",n.isPlaying),console.log(" scheduledBuffers:",n.scheduledBuffers||0),console.log(" scheduledSourcesCount:",n.scheduledSourcesCount||0),e.stopAudioPlayback(),console.log("✅ VoiceSDK v2: Audio playback stopped"),e.isConnected&&(e.sendMessage({t:"barge_in"}),console.log("📤 VoiceSDK v2: Sent barge_in message to server")))}e.isConnected&&e.sendBinary(t)}),this.audioRecorder.on("error",function(t){console.error("❌ AudioRecorder error:",t),e.emit("error",t)})}},{key:"buildWebSocketUrl",value:function(){var e=this.config.websocketUrl,t=new URLSearchParams;if(this.config.agentId&&t.append("agentId",this.config.agentId),this.config.appId&&t.append("appId",this.config.appId),t.toString()){var n=e.includes("?")?"&":"?";return"".concat(e).concat(n).concat(t.toString())}return e}},{key:"connect",value:(u=Ht(Kt().m(function e(){var t,n,o=this;return Kt().w(function(e){for(;;)switch(e.p=e.n){case 0:if(!this.isDestroyed){e.n=1;break}return console.warn("VoiceSDK v2: Cannot connect - SDK is destroyed"),e.a(2,!1);case 1:if(!this.isConnected){e.n=2;break}return console.warn("VoiceSDK v2: Already connected"),e.a(2,!0);case 2:return e.p=2,t=this.buildWebSocketUrl(),console.log("🔌 VoiceSDK v2: Connecting to",t),e.n=3,new Promise(function(e,n){o.websocket=new WebSocket(t),o.websocket.onopen=function(){console.log("✅ VoiceSDK v2: WebSocket connected"),o.isConnected=!0,o.hasEverConnected=!0,o.sendHelloMessage(),o.emit("connected"),e(!0)},o.websocket.onerror=function(e){console.error("❌ VoiceSDK v2: WebSocket error:",e),n(e)},o.websocket.onclose=function(e){console.log("🔌 VoiceSDK v2: WebSocket closed:",e.code,e.reason),o.isConnected=!1,o.isRecording&&o.stopRecording().catch(function(e){return console.error("Error stopping recording:",e)}),o.emit("disconnected",e),o.config.autoReconnect&&!o.isDestroyed&&o.hasEverConnected?(console.log("🔄 VoiceSDK v2: Auto-reconnecting in 3s..."),setTimeout(function(){o.isDestroyed||o.isConnected||o.connect()},3e3)):o.config.autoReconnect&&!o.hasEverConnected&&console.log("⚠️ VoiceSDK v2: Initial connection failed. Auto-reconnect disabled to prevent retry loop.")},o.websocket.onmessage=function(e){o.handleMessage(e)}});case 3:return e.a(2,e.v);case 4:return e.p=4,n=e.v,console.error("🔌 VoiceSDK v2: Connection failed:",n),this.emit("error",n),e.a(2,!1)}},e,this,[[2,4]])})),function(){return u.apply(this,arguments)})},{key:"sendHelloMessage",value:function(){if(this.isConnected){var e={encoding:"pcm",sampleRate:this.config.sampleRate,channels:this.config.channels,bitDepth:this.config.bitDepth},t={encoding:this.config.outputEncoding,sampleRate:this.config.outputSampleRate,channels:this.config.outputChannels,bitDepth:this.config.outputBitDepth,container:this.config.outputContainer},n=this.validateInputFormat(e);if(n)return console.error("❌ VoiceSDK v2: Cannot send hello - invalid input format:",n),void this.emit("error",new Error("Invalid input format: ".concat(n)));var o=this.validateOutputFormat(t);if(o)return console.error("❌ VoiceSDK v2: Cannot send hello - invalid output format:",o),void this.emit("error",new Error("Invalid output format: ".concat(o)));var r={t:"hello",v:this.config.protocolVersion,inputFormat:e,requestedOutputFormat:t,outputFrameDurationMs:this.config.outputFrameDurationMs};this.config.agentSettingsOverride&&(r.agentSettingsOverride=this.config.agentSettingsOverride),console.log("🔍 VoiceSDK v2: Checking variables:",{hasVariables:!!this.config.variables,variables:this.config.variables,keys:this.config.variables?Object.keys(this.config.variables):[]}),this.config.variables&&Object.keys(this.config.variables).length>0?(r.variables=this.config.variables,console.log("📝 VoiceSDK v2: Including variables in hello:",Object.keys(this.config.variables))):console.log("⚠️ VoiceSDK v2: Variables NOT included - condition failed"),console.log("📤 VoiceSDK v2: Sending hello:",{version:r.v,requestedFormat:r.requestedOutputFormat,variables:r.variables?Object.keys(r.variables):void 0}),console.log("📤 VoiceSDK v2: Requested output format:",{container:r.requestedOutputFormat.container,encoding:r.requestedOutputFormat.encoding,sampleRate:r.requestedOutputFormat.sampleRate,bitDepth:r.requestedOutputFormat.bitDepth}),console.log("📤 VoiceSDK v2: Full hello message being sent:",JSON.stringify(r,null,2));try{this.sendMessage(r)}catch(e){console.error("VoiceSDK v2: Failed to send hello:",e),this.emit("error",e)}}else console.warn("VoiceSDK v2: Cannot send hello - not connected")}},{key:"handleMessage",value:function(e){if(e.data instanceof ArrayBuffer||e.data instanceof Blob)this.handleBinaryMessage(e.data);else try{var t=JSON.parse(e.data);switch("audio"!==t.t&&console.log("📥 VoiceSDK v2: Received message type:",t.t,"Full message:",JSON.stringify(t).substring(0,200)),!this.conversationId&&t.conversationId&&(this.conversationId=t.conversationId,console.log("🔍 VoiceSDK v2: Captured conversationId from message:",this.conversationId),this.emit("conversationIdChanged",this.conversationId)),"audio"!==t.t&&console.log("📨 VoiceSDK v2: Received message type:",t.t,t),t.t){case"hello_ack":this.handleHelloAck(t);break;case"transcript":console.log("📝 VoiceSDK v2: Processing transcript message:",t),this.handleTranscript(t);break;case"user_transcript":console.log("📝 VoiceSDK v2: Received user_transcript:",t),this.emit("message",t);break;case"agent_response":if(console.log("📝 VoiceSDK v2: Received agent_response:",t),(t.text||t.transcript)&&(console.log("📝 VoiceSDK v2: agent_response contains transcript data:",t.text||t.transcript),t.sentenceId&&(t.text||t.transcript))){var n={t:"transcript",sentenceId:t.sentenceId,text:t.text||t.transcript,role:t.role||"assistant",final:!1!==t.final,timestamp:t.timestamp||Date.now()};console.log("📝 VoiceSDK v2: Converting agent_response to transcript:",n),this.handleTranscript(n)}this.emit("message",t);break;case"error":this.emit("message",t);break;case"barge_in":this.emit("bargeIn",t),this.stopAudioPlayback();break;case"stop_playing":this.emit("stopPlaying",t),this.stopAudioPlayback();break;case"audio_start":console.log("📝 VoiceSDK v2: Received audio_start with text:",t.text),t.text&&this.audioPlayer&&this.audioPlayer.markNewSentence(t.text),this.emit("message",t);break;default:if(console.log("VoiceSDK v2: Unknown message type:",t.t,"Full message:",JSON.stringify(t).substring(0,300)),(t.text||t.transcript||t.transcription)&&(console.log("📝 VoiceSDK v2: Unknown message contains transcript-like data:",{text:t.text,transcript:t.transcript,transcription:t.transcription,sentenceId:t.sentenceId,role:t.role}),t.sentenceId&&(t.text||t.transcript||t.transcription))){var o={t:"transcript",sentenceId:t.sentenceId,text:t.text||t.transcript||t.transcription,role:t.role||"assistant",final:!1!==t.final,timestamp:t.timestamp||Date.now()};console.log("📝 VoiceSDK v2: Attempting to process unknown message as transcript:",o),this.handleTranscript(o)}this.emit("message",t)}}catch(e){console.error("VoiceSDK v2: Error parsing message:",e)}}},{key:"handleHelloAck",value:function(e){if(console.log("📥 VoiceSDK v2: Received hello_ack:",{hasOutputFormat:!!e.outputAudioFormat,outputFormat:e.outputAudioFormat,hasConversationId:!!e.conversationId,messageType:e.t}),e.conversationId&&(this.conversationId=e.conversationId,console.log("🔍 VoiceSDK v2: Received conversationId:",this.conversationId),this.emit("conversationIdChanged",this.conversationId)),e.outputAudioFormat){this.outputAudioFormat=e.outputAudioFormat,this.audioPlayer.setOutputFormat(e.outputAudioFormat),console.log("✅ VoiceSDK v2: Format negotiated by server:",this.outputAudioFormat),this.requestedOutputFormat={container:this.config.outputContainer||"wav",encoding:this.config.outputEncoding||"pcm",sampleRate:this.config.outputSampleRate||16e3,bitDepth:this.config.outputBitDepth||16,channels:this.config.outputChannels||1};var t={container:this.outputAudioFormat.container||"unknown",encoding:this.outputAudioFormat.encoding||"unknown",sampleRate:this.outputAudioFormat.sampleRate||0,bitDepth:this.outputAudioFormat.bitDepth||0,channels:this.outputAudioFormat.channels||0},n=[];if(this.requestedOutputFormat.container!==t.container&&n.push('container: "'.concat(this.requestedOutputFormat.container,'" → "').concat(t.container,'"')),this.requestedOutputFormat.encoding!==t.encoding&&n.push('encoding: "'.concat(this.requestedOutputFormat.encoding,'" → "').concat(t.encoding,'"')),this.requestedOutputFormat.sampleRate!==t.sampleRate&&n.push("sampleRate: ".concat(this.requestedOutputFormat.sampleRate,"Hz → ").concat(t.sampleRate,"Hz")),this.requestedOutputFormat.bitDepth!==t.bitDepth&&n.push("bitDepth: ".concat(this.requestedOutputFormat.bitDepth,"-bit → ").concat(t.bitDepth,"-bit")),this.requestedOutputFormat.channels!==t.channels&&n.push("channels: ".concat(this.requestedOutputFormat.channels," → ").concat(t.channels)),n.length>0){console.warn("⚠️ VoiceSDK v2: Format negotiation mismatch!"),console.warn(" Requested:",this.requestedOutputFormat),console.warn(" Negotiated:",t),console.warn(" Differences:",n.join(", "));try{if(this.formatConverter=new Ut(this.requestedOutputFormat,t),this.formatConverter.needsConversion()){var o=this.formatConverter.getConversionSteps();console.log("🔄 VoiceSDK v2: Format conversion enabled"),console.log(" Conversion steps:",o.join(", ")),console.log(" Audio will be automatically converted to requested format")}}catch(e){console.error("❌ VoiceSDK v2: Failed to create format converter:",e),console.warn(" Will use backend format without conversion"),this.formatConverter=null}}else console.log("✅ VoiceSDK v2: Format perfectly matched!",t),this.formatConverter=null;this.emit("formatNegotiated",this.outputAudioFormat)}else{this.config.protocolVersion>=2?(console.warn("⚠️ VoiceSDK v2: hello_ack received but no outputAudioFormat in response."),console.warn(" This may happen if:"),console.warn(" 1. Backend is not sending outputAudioFormat (check backend logs)"),console.warn(" 2. Hello message missing v2 fields (v, inputFormat, requestedOutputFormat)"),console.warn(" 3. Backend validation failed (check backend error logs)"),console.warn(" Using default format from config...")):console.log("✅ VoiceSDK v2: Connected (v1 legacy mode)");var r={container:this.config.outputContainer||"wav",encoding:this.config.outputEncoding||"pcm",sampleRate:this.config.outputSampleRate||16e3,channels:this.config.outputChannels||1,bitDepth:this.config.outputBitDepth||16};this.outputAudioFormat=r,this.requestedOutputFormat=r,this.audioPlayer.setOutputFormat(r),this.formatConverter=null}}},{key:"handleTranscript",value:function(e){if(e.sentenceId&&e.text){var t=e.sentenceId,n={text:e.text,role:e.role||"assistant",sentenceId:t,final:!1!==e.final,timestamp:e.timestamp||Date.now()};this.transcriptQueue.push(n),console.log("📝 VoiceSDK v2: Received transcript for sentence",t,":",n.text),console.log(" Transcript queue length:",this.transcriptQueue.length),console.log(" Current playing sentence:",this.currentPlayingSentenceId),console.log("📝 VoiceSDK v2: Displaying transcript for completed sentence",t),this.emit("transcriptDisplay",n),this.currentPlayingSentenceId=t,this.emit("transcript",n)}else console.warn("⚠️ VoiceSDK v2: Invalid transcript message:",e)}},{key:"handleBinaryMessage",value:(s=Ht(Kt().m(function e(t){var n,o,r,i,a,c,s,u,l,d;return Kt().w(function(e){for(;;)switch(e.p=e.n){case 0:if(!(t instanceof Blob)){e.n=2;break}return e.n=1,t.arrayBuffer();case 1:o=e.v,e.n=3;break;case 2:o=t;case 3:if(console.log("📥 VoiceSDK v2: Received audio:",o.byteLength,"bytes"),console.log(" Current outputFormat:",this.outputAudioFormat),console.log(" AudioPlayer outputFormat:",null===(n=this.audioPlayer)||void 0===n?void 0:n.outputFormat),console.log(" Format converter:",this.formatConverter?"active":"none"),r=o,!this.formatConverter||!this.formatConverter.needsConversion()){e.n=7;break}return e.p=4,e.n=5,this.formatConverter.convert(o);case 5:r=e.v,console.log("✅ VoiceSDK v2: Audio converted to requested format"),e.n=7;break;case 6:e.p=6,d=e.v,console.error("❌ VoiceSDK v2: Format conversion failed:",d),console.warn(" Using backend format without conversion"),r=o;case 7:i=this.formatConverter&&this.formatConverter.needsConversion()?this.requestedOutputFormat:this.outputAudioFormat||{container:this.config.outputContainer||"raw",encoding:this.config.outputEncoding||"pcm",sampleRate:this.config.outputSampleRate||16e3,bitDepth:this.config.outputBitDepth||16,channels:this.config.outputChannels||1},a=i.container||"raw",c=(i.encoding||"pcm").toLowerCase(),"raw"===a?(s=r,"pcm"!==c&&((u=this.audioPlayer.getCodec(c))?(l=u.decode(new Uint8Array(r)),s=l.buffer,console.log("🔄 VoiceSDK v2: Decoded ".concat(c.toUpperCase()," to PCM (").concat(l.byteLength," bytes)"))):console.warn("⚠️ VoiceSDK v2: No codec for ".concat(c,", treating as PCM"))),this.audioPlayer.outputFormat||(console.warn("⚠️ VoiceSDK v2: outputFormat not set on AudioPlayer, setting from playbackFormat"),this.audioPlayer.setOutputFormat(i)),this.audioFrameCount++,this.audioPlayer.playChunk(s)):(this.audioFrameCount++,this.audioPlayer.playAudio(r));case 8:return e.a(2)}},e,this,[[4,6]])})),function(e){return s.apply(this,arguments)})},{key:"sendMessage",value:function(e){if(!this.websocket||this.websocket.readyState!==WebSocket.OPEN)return console.warn("VoiceSDK v2: Cannot send message - not connected"),!1;try{return this.websocket.send(JSON.stringify(e)),!0}catch(e){return console.error("VoiceSDK v2: Error sending message:",e),this.emit("error",e),!1}}},{key:"sendBinary",value:function(e){if(!this.websocket||this.websocket.readyState!==WebSocket.OPEN)return console.warn("VoiceSDK v2: Cannot send audio - not connected"),!1;try{return this.websocket.send(e),!0}catch(e){return console.error("VoiceSDK v2: Error sending audio:",e),this.emit("error",e),!1}}},{key:"disconnect",value:function(){this.isDestroyed||(console.log("🔌 VoiceSDK v2: Disconnecting..."),this.stopRecording(),this.audioPlayer&&this.stopAudioPlayback(),this.websocket&&(this.websocket.close(),this.websocket=null),this.isConnected=!1)}},{key:"startRecording",value:(c=Ht(Kt().m(function e(){var t,n,o,r,i,a,c,s,u=this;return Kt().w(function(e){for(;;)switch(e.p=e.n){case 0:if(this.isConnected){e.n=1;break}throw t=new Error("Not connected to voice server"),this.emit("error",t),t;case 1:if(!this.isRecording){e.n=2;break}return console.warn("VoiceSDK v2: Already recording"),e.a(2,!0);case 2:return console.log("🎤 VoiceSDK v2: Starting recording..."),e.p=3,console.log("🎤 VoiceSDK v2: Requesting microphone permission (mobile-friendly)..."),n=this.audioPlayer?this.audioPlayer.getStatus():null,o=this.isPlaying||n&&(n.isPlaying||n.scheduledBuffers&&n.scheduledBuffers>0||n.scheduledSourcesCount&&n.scheduledSourcesCount>0),r=null,!o&&this.audioPlayer&&this.audioPlayer.audioContext&&"closed"!==this.audioPlayer.audioContext.state?(r=this.audioPlayer.audioContext,console.log("🎤 VoiceSDK v2: Sharing AudioPlayer AudioContext with AudioRecorder (no audio playing)")):o&&console.log("🎤 VoiceSDK v2: Audio is playing - using separate AudioContext for recording"),i=null,o&&this.audioPlayer&&this.audioPlayer.audioContext&&"closed"!==this.audioPlayer.audioContext.state&&(a=this.audioPlayer.audioContext,this.audioPlayer.createKeepAliveOscillator(),i=setInterval(Ht(Kt().m(function e(){var t;return Kt().w(function(e){for(;;)switch(e.p=e.n){case 0:if(!a||"suspended"!==a.state){e.n=4;break}return console.log("🛑 VoiceSDK v2: Playback AudioContext suspended during getUserMedia! Resuming immediately..."),e.p=1,e.n=2,a.resume();case 2:console.log("✅ VoiceSDK v2: Playback AudioContext resumed"),e.n=4;break;case 3:e.p=3,t=e.v,console.warn("⚠️ VoiceSDK v2: Failed to resume playback AudioContext:",t);case 4:return e.a(2)}},e,null,[[1,3]])})),10),console.log("🎤 VoiceSDK v2: Started aggressive AudioContext monitoring and keep-alive oscillator")),e.n=4,this.audioRecorder.start(r);case 4:if(i&&setTimeout(function(){i&&(clearInterval(i),i=null,console.log("🎤 VoiceSDK v2: Stopped aggressive AudioContext monitoring")),o&&u.audioPlayer&&u.audioPlayer.stopKeepAliveOscillator()},1e3),!(o&&this.audioPlayer&&this.audioPlayer.audioContext&&"closed"!==this.audioPlayer.audioContext.state)){e.n=5;break}if("suspended"!==(c=this.audioPlayer.audioContext).state){e.n=5;break}return console.log("🛑 VoiceSDK v2: Final check - Playback AudioContext suspended, resuming..."),e.n=5,c.resume();case 5:return this.sendMessage({t:"start_continuous_mode",ttpId:this.generateTtpId()}),e.a(2,!0);case 6:return e.p=6,s=e.v,console.error("❌ VoiceSDK v2: Failed to start recording:",s),this.emit("error",s),e.a(2,!1)}},e,this,[[3,6]])})),function(){return c.apply(this,arguments)})},{key:"stopRecording",value:(a=Ht(Kt().m(function e(){var t;return Kt().w(function(e){for(;;)switch(e.p=e.n){case 0:if(this.isRecording){e.n=1;break}return console.warn("VoiceSDK v2: Not recording"),e.a(2,!0);case 1:return console.log("🛑 VoiceSDK v2: Stopping recording..."),e.p=2,this.sendMessage({t:"stop_continuous_mode",ttpId:this.generateTtpId()}),this.isRecording=!1,this._bargeInChecked=!1,this.emit("recordingStopped"),console.log("🛑 VoiceSDK v2: Recording stopped (emitted before audioRecorder.stop())"),e.n=3,this.audioRecorder.stop();case 3:return this.stopAudioPlayback(),e.a(2,!0);case 4:return e.p=4,t=e.v,console.error("VoiceSDK v2: Error stopping recording:",t),this.emit("error",t),e.a(2,!1)}},e,this,[[2,4]])})),function(){return a.apply(this,arguments)})},{key:"toggleRecording",value:(i=Ht(Kt().m(function e(){return Kt().w(function(e){for(;;)switch(e.n){case 0:if(!this.isRecording){e.n=2;break}return e.n=1,this.stopRecording();case 1:case 3:return e.a(2,e.v);case 2:return e.n=3,this.startRecording();case 4:return e.a(2)}},e,this)})),function(){return i.apply(this,arguments)})},{key:"clearTranscriptState",value:function(){this.currentPlayingSentenceId=null,console.log("📝 VoiceSDK v2: Cleared transcript state")}},{key:"stopAudioPlayback",value:function(){this.audioPlayer.stopImmediate(),this.clearTranscriptState()}},{key:"handleBargeIn",value:(r=Ht(Kt().m(function e(){return Kt().w(function(e){for(;;)switch(e.n){case 0:if(this.stopAudioPlayback(),this.isRecording){e.n=1;break}return e.n=1,this.startRecording();case 1:return e.a(2)}},e,this)})),function(){return r.apply(this,arguments)})},{key:"getStatus",value:function(){return{version:this.version,isConnected:this.isConnected,isRecording:this.isRecording,isPlaying:this.isPlaying,outputFormat:this.outputAudioFormat,conversationId:this.conversationId,audioPlayer:this.audioPlayer.getStatus(),audioRecorder:this.audioRecorder.getStatus()}}},{key:"updateConfig",value:function(e){this.config=Vt(Vt({},this.config),e)}},{key:"generateTtpId",value:function(){return"sdk_"+Math.random().toString(36).substr(2,9)+"_"+Date.now()}},{key:"destroy",value:function(){this.isDestroyed||(console.log("🗑️ VoiceSDK v2: Destroying..."),this.disconnect(),this.isDestroyed=!0,this.audioPlayer&&this.audioPlayer.destroy(),this.audioRecorder&&this.audioRecorder.destroy(),this.removeAllListeners())}}],o&&Wt(n.prototype,o),Object.defineProperty(n,"prototype",{writable:!1}),n;var n,o,r,i,a,c,s,u}(be);Jt($t,"SUPPORTED_INPUT_ENCODINGS",["pcm","pcmu","pcma"]),Jt($t,"SUPPORTED_INPUT_SAMPLE_RATES",[8e3,16e3,22050,24e3,44100,48e3]),Jt($t,"SUPPORTED_INPUT_BIT_DEPTHS",[8,16,24]),Jt($t,"SUPPORTED_INPUT_CHANNELS",[1]),Jt($t,"SUPPORTED_OUTPUT_ENCODINGS",["pcm","pcmu","pcma"]),Jt($t,"SUPPORTED_OUTPUT_SAMPLE_RATES",[8e3,16e3,22050,24e3,44100,48e3]),Jt($t,"SUPPORTED_OUTPUT_BIT_DEPTHS",[8,16,24]),Jt($t,"SUPPORTED_OUTPUT_CHANNELS",[1]),Jt($t,"SUPPORTED_OUTPUT_CONTAINERS",["raw","wav"]);const Xt=$t;function Zt(e){return Zt="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},Zt(e)}function en(){var e,t,n="function"==typeof Symbol?Symbol:{},o=n.iterator||"@@iterator",r=n.toStringTag||"@@toStringTag";function i(n,o,r,i){var s=o&&o.prototype instanceof c?o:c,u=Object.create(s.prototype);return tn(u,"_invoke",function(n,o,r){var i,c,s,u=0,l=r||[],d=!1,p={p:0,n:0,v:e,a:f,f:f.bind(e,4),d:function(t,n){return i=t,c=0,s=e,p.n=n,a}};function f(n,o){for(c=n,s=o,t=0;!d&&u&&!r&&t<l.length;t++){var r,i=l[t],f=p.p,h=i[2];n>3?(r=h===o)&&(s=i[(c=i[4])?5:(c=3,3)],i[4]=i[5]=e):i[0]<=f&&((r=n<2&&f<i[1])?(c=0,p.v=o,p.n=i[1]):f<h&&(r=n<3||i[0]>o||o>h)&&(i[4]=n,i[5]=o,p.n=h,c=0))}if(r||n>1)return a;throw d=!0,o}return function(r,l,h){if(u>1)throw TypeError("Generator is already running");for(d&&1===l&&f(l,h),c=l,s=h;(t=c<2?e:s)||!d;){i||(c?c<3?(c>1&&(p.n=-1),f(c,s)):p.n=s:p.v=s);try{if(u=2,i){if(c||(r="next"),t=i[r]){if(!(t=t.call(i,s)))throw TypeError("iterator result is not an object");if(!t.done)return t;s=t.value,c<2&&(c=0)}else 1===c&&(t=i.return)&&t.call(i),c<2&&(s=TypeError("The iterator does not provide a '"+r+"' method"),c=1);i=e}else if((t=(d=p.n<0)?s:n.call(o,p))!==a)break}catch(t){i=e,c=1,s=t}finally{u=1}}return{value:t,done:d}}}(n,r,i),!0),u}var a={};function c(){}function s(){}function u(){}t=Object.getPrototypeOf;var l=[][o]?t(t([][o]())):(tn(t={},o,function(){return this}),t),d=u.prototype=c.prototype=Object.create(l);function p(e){return Object.setPrototypeOf?Object.setPrototypeOf(e,u):(e.__proto__=u,tn(e,r,"GeneratorFunction")),e.prototype=Object.create(d),e}return s.prototype=u,tn(d,"constructor",u),tn(u,"constructor",s),s.displayName="GeneratorFunction",tn(u,r,"GeneratorFunction"),tn(d),tn(d,r,"Generator"),tn(d,o,function(){return this}),tn(d,"toString",function(){return"[object Generator]"}),(en=function(){return{w:i,m:p}})()}function tn(e,t,n,o){var r=Object.defineProperty;try{r({},"",{})}catch(e){r=0}tn=function(e,t,n,o){function i(t,n){tn(e,t,function(e){return this._invoke(t,n,e)})}t?r?r(e,t,{value:n,enumerable:!o,configurable:!o,writable:!o}):e[t]=n:(i("next",0),i("throw",1),i("return",2))},tn(e,t,n,o)}function nn(e,t,n,o,r,i,a){try{var c=e[i](a),s=c.value}catch(e){return void n(e)}c.done?t(s):Promise.resolve(s).then(o,r)}function on(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(e);t&&(o=o.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,o)}return n}function rn(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?on(Object(n),!0).forEach(function(t){an(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):on(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}function an(e,t,n){return(t=sn(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function cn(e,t){for(var n=0;n<t.length;n++){var o=t[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(e,sn(o.key),o)}}function sn(e){var t=function(e){if("object"!=Zt(e)||!e)return e;var t=e[Symbol.toPrimitive];if(void 0!==t){var n=t.call(e,"string");if("object"!=Zt(n))return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}(e);return"symbol"==Zt(t)?t:t+""}function un(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(e){}return(un=function(){return!!e})()}function ln(e){return ln=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(e){return e.__proto__||Object.getPrototypeOf(e)},ln(e)}function dn(e,t){return dn=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,t){return e.__proto__=t,e},dn(e,t)}var pn=function(e){function t(){var e,n=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,t);var o=(e=function(e,t,n){return t=ln(t),function(e,t){if(t&&("object"==Zt(t)||"function"==typeof t))return t;if(void 0!==t)throw new TypeError("Derived constructors may only return object or undefined");return function(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}(e)}(e,un()?Reflect.construct(t,n||[],ln(e).constructor):t.apply(e,n))}(this,t)).readScriptTagConfig();return e.config=rn({baseWsUrl:"wss://backend.talktopc.com/chat/websocket",appId:n.appId||o.appId,agentId:n.agentId||o.agentId,conversationId:void 0!==n.conversationId?n.conversationId:e.getPersistedConversationId(),forceConversationId:n.forceConversationId,queue:[],inFlight:!1},n),e.fullResponseBuffer="",e}return function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&dn(e,t)}(t,e),n=t,o=[{key:"readScriptTagConfig",value:function(){try{var e=Array.from(document.getElementsByTagName("script")).reverse().find(function(e){return e.dataset&&(e.dataset.appId||e.dataset.agentId)||e.src&&e.src.includes("agent-widget")});return e?{appId:e.dataset.appId,agentId:e.dataset.agentId}:{}}catch(e){return{}}}},{key:"buildWebSocketUrl",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:this.config.baseWsUrl,t=new URLSearchParams;return this.config.appId&&t.append("appId",this.config.appId),this.config.agentId&&t.append("agentId",this.config.agentId),this.config.conversationId&&t.append("conversationId",this.config.conversationId),"".concat(e,"?").concat(t.toString())}},{key:"sendMessage",value:(r=en().m(function e(t){var n=this;return en().w(function(e){for(;;)if(0===e.n)return e.a(2,new Promise(function(e,o){if(t&&t.trim())if(n.config.appId&&n.config.agentId){var r={text:t,resolve:e,reject:o};n.config.inFlight?n.config.queue.push(r):n.executeTask(r)}else o(new Error("Missing appId or agentId"));else o(new Error("Message is empty"))}))},e)}),i=function(){var e=this,t=arguments;return new Promise(function(n,o){var i=r.apply(e,t);function a(e){nn(i,n,o,a,c,"next",e)}function c(e){nn(i,n,o,a,c,"throw",e)}a(void 0)})},function(e){return i.apply(this,arguments)})},{key:"executeTask",value:function(e){var t=this;if(this.config.inFlight=!0,this.fullResponseBuffer="",!this.config.conversationId){var n=this.getPersistedConversationId();n&&(this.config.conversationId=n,console.log("🔍 TextChatSDK hydrated conversationId from storage:",n))}var o,r=this.buildWebSocketUrl(this.config.baseWsUrl),i=this.config.baseWsUrl.endsWith("/websocket")?this.config.baseWsUrl.replace(/\/websocket$/,""):"".concat(this.config.baseWsUrl,"/websocket"),a=this.buildWebSocketUrl(i),c=!1,s=!1,u=null,l=function(n){if(!s)try{var o={message:e.text},r=t.config.forceConversationId||t.config.conversationId;r&&(o.conversationId=r,t.config.forceConversationId&&!t.config.conversationId&&(t.config.conversationId=r,t.persistConversationId(r))),console.log("🔍 TextChatSDK sending payload:",o,"conversationId in config:",t.config.conversationId),n.send(JSON.stringify(o)),s=!0}catch(o){e.reject(o),t.emit("error",o);try{n.close()}catch(e){}}},d=function(e){return function(){t.config.conversationId?l(e):u=setTimeout(function(){return l(e)},200)}},p=function(n){return function(o){try{try{console.log("🔎 [TextChatSDK] WS <= raw:",o.data)}catch(e){}var r=JSON.parse(o.data);try{console.log("🔎 [TextChatSDK] WS <= parsed:",r)}catch(e){}if("hello"===r.type&&r.conversationId){if(console.log("🔍 TextChatSDK received conversationId:",r.conversationId),t.config.conversationId=r.conversationId,t.persistConversationId(r.conversationId),t.emit&&t.emit("conversationIdChanged",r.conversationId),!s&&n&&1===n.readyState){if(u)try{clearTimeout(u)}catch(e){}l(n)}return}if(!t.config.conversationId&&r.conversationId&&(console.log("🔍 TextChatSDK captured conversationId from message:",r.conversationId),t.config.conversationId=r.conversationId,t.persistConversationId(r.conversationId)),"chunk"===r.type&&"string"==typeof r.content)t.fullResponseBuffer+=r.content,t.emit("chunk",r.content);else if("done"===r.type){try{var i=r.text||r.content||r.answer||r.message||"";i&&!t.fullResponseBuffer&&(t.fullResponseBuffer=i)}catch(e){}!t.config.conversationId&&r.conversationId&&(console.log("🔍 TextChatSDK captured conversationId from done:",r.conversationId),t.config.conversationId=r.conversationId),t.persistConversationId(t.config.conversationId),t.emit("done",{text:t.fullResponseBuffer}),e.resolve({conversationId:t.config.conversationId,fullText:t.fullResponseBuffer});try{n.close()}catch(e){}}else if("error"===r.type){var a=new Error(r.message||"Server error");t.emit("error",a),e.reject(a);try{n.close()}catch(e){}}}catch(e){}}},f=function(n){if(1008===n.code&&n.reason&&(n.reason.includes("Domain not whitelisted")||n.reason.includes("domain")||n.reason.includes("whitelist"))){var o=new Error("DOMAIN_NOT_WHITELISTED");return o.reason=n.reason,o.code=n.code,t.emit("domainError",o),e.reject(o),t.config.inFlight=!1,void t.drainQueue()}t.config.inFlight=!1,t.drainQueue()},h=new WebSocket(r);h.onopen=d(h),h.onmessage=p(h),h.onerror=(o=h,function(n){if(!c){c=!0;try{o.close()}catch(e){}var r=new WebSocket(a);return r.onopen=d(r),r.onmessage=p(r),r.onerror=function(n){t.emit("error",n),e.reject(n)},void(r.onclose=f)}t.emit("error",n),e.reject(n)}),h.onclose=f}},{key:"drainQueue",value:function(){if(0!==this.config.queue.length&&!this.config.inFlight){var e=this.config.queue.shift();this.executeTask(e)}}},{key:"persistConversationId",value:function(e){try{e&&localStorage.setItem("ttp_text_chat_conversation_id",e)}catch(e){}}},{key:"getPersistedConversationId",value:function(){try{return localStorage.getItem("ttp_text_chat_conversation_id")||null}catch(e){return null}}},{key:"updateConfig",value:function(e){this.config=rn(rn({},this.config),e)}},{key:"destroy",value:function(){this.config.queue=[],this.config.inFlight=!1,this.removeAllListeners()}}],o&&cn(n.prototype,o),Object.defineProperty(n,"prototype",{writable:!1}),n;var n,o,r,i}(c),fn=n(540),hn=n(848);function vn(e){return vn="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},vn(e)}function gn(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(e);t&&(o=o.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,o)}return n}function yn(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?gn(Object(n),!0).forEach(function(t){mn(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):gn(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}function mn(e,t,n){return(t=function(e){var t=function(e){if("object"!=vn(e)||!e)return e;var t=e[Symbol.toPrimitive];if(void 0!==t){var n=t.call(e,"string");if("object"!=vn(n))return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}(e);return"symbol"==vn(t)?t:t+""}(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function bn(){var e,t,n="function"==typeof Symbol?Symbol:{},o=n.iterator||"@@iterator",r=n.toStringTag||"@@toStringTag";function i(n,o,r,i){var s=o&&o.prototype instanceof c?o:c,u=Object.create(s.prototype);return Sn(u,"_invoke",function(n,o,r){var i,c,s,u=0,l=r||[],d=!1,p={p:0,n:0,v:e,a:f,f:f.bind(e,4),d:function(t,n){return i=t,c=0,s=e,p.n=n,a}};function f(n,o){for(c=n,s=o,t=0;!d&&u&&!r&&t<l.length;t++){var r,i=l[t],f=p.p,h=i[2];n>3?(r=h===o)&&(s=i[(c=i[4])?5:(c=3,3)],i[4]=i[5]=e):i[0]<=f&&((r=n<2&&f<i[1])?(c=0,p.v=o,p.n=i[1]):f<h&&(r=n<3||i[0]>o||o>h)&&(i[4]=n,i[5]=o,p.n=h,c=0))}if(r||n>1)return a;throw d=!0,o}return function(r,l,h){if(u>1)throw TypeError("Generator is already running");for(d&&1===l&&f(l,h),c=l,s=h;(t=c<2?e:s)||!d;){i||(c?c<3?(c>1&&(p.n=-1),f(c,s)):p.n=s:p.v=s);try{if(u=2,i){if(c||(r="next"),t=i[r]){if(!(t=t.call(i,s)))throw TypeError("iterator result is not an object");if(!t.done)return t;s=t.value,c<2&&(c=0)}else 1===c&&(t=i.return)&&t.call(i),c<2&&(s=TypeError("The iterator does not provide a '"+r+"' method"),c=1);i=e}else if((t=(d=p.n<0)?s:n.call(o,p))!==a)break}catch(t){i=e,c=1,s=t}finally{u=1}}return{value:t,done:d}}}(n,r,i),!0),u}var a={};function c(){}function s(){}function u(){}t=Object.getPrototypeOf;var l=[][o]?t(t([][o]())):(Sn(t={},o,function(){return this}),t),d=u.prototype=c.prototype=Object.create(l);function p(e){return Object.setPrototypeOf?Object.setPrototypeOf(e,u):(e.__proto__=u,Sn(e,r,"GeneratorFunction")),e.prototype=Object.create(d),e}return s.prototype=u,Sn(d,"constructor",u),Sn(u,"constructor",s),s.displayName="GeneratorFunction",Sn(u,r,"GeneratorFunction"),Sn(d),Sn(d,r,"Generator"),Sn(d,o,function(){return this}),Sn(d,"toString",function(){return"[object Generator]"}),(bn=function(){return{w:i,m:p}})()}function Sn(e,t,n,o){var r=Object.defineProperty;try{r({},"",{})}catch(e){r=0}Sn=function(e,t,n,o){function i(t,n){Sn(e,t,function(e){return this._invoke(t,n,e)})}t?r?r(e,t,{value:n,enumerable:!o,configurable:!o,writable:!o}):e[t]=n:(i("next",0),i("throw",1),i("return",2))},Sn(e,t,n,o)}function wn(e,t,n,o,r,i,a){try{var c=e[i](a),s=c.value}catch(e){return void n(e)}c.done?t(s):Promise.resolve(s).then(o,r)}function xn(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var n=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=n){var o,r,i,a,c=[],s=!0,u=!1;try{if(i=(n=n.call(e)).next,0===t){if(Object(n)!==n)return;s=!1}else for(;!(s=(o=i.call(n)).done)&&(c.push(o.value),c.length!==t);s=!0);}catch(e){u=!0,r=e}finally{try{if(!s&&null!=n.return&&(a=n.return(),Object(a)!==a))return}finally{if(u)throw r}}return c}}(e,t)||function(e,t){if(e){if("string"==typeof e)return Cn(e,t);var n={}.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?Cn(e,t):void 0}}(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function Cn(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,o=Array(t);n<t;n++)o[n]=e[n];return o}const kn=function(e){var t=e.websocketUrl,n=e.agentId,o=e.appId,r=e.voice,i=void 0===r?"default":r,a=e.language,c=void 0===a?"en":a,s=e.autoReconnect,u=void 0===s||s,l=e.agentSettingsOverride,d=void 0===l?null:l,p=e.onConnected,f=e.onDisconnected,h=e.onRecordingStarted,v=e.onRecordingStopped,g=e.onPlaybackStarted,y=e.onPlaybackStopped,m=e.onError,b=e.onMessage,S=e.onBargeIn,w=e.onStopPlaying,x=e.onStartConversation,C=e.onEndConversation,k=e.className,P=void 0===k?"":k,O=e.style,E=void 0===O?{}:O,T=e.children,A=xn((0,fn.useState)(!1),2),I=A[0],j=A[1],D=xn((0,fn.useState)(!1),2),F=D[0],B=D[1],R=xn((0,fn.useState)(!1),2),_=(R[0],R[1]),U=xn((0,fn.useState)("Disconnected"),2),M=(U[0],U[1]),N=(0,fn.useRef)(null);(0,fn.useEffect)(function(){console.log("🎙️ VoiceButton: Creating VoiceSDK instance for ".concat(t)),N.current&&(console.log("🎙️ VoiceButton: Destroying existing VoiceSDK instance"),N.current.destroy(),N.current=null);var e=new he({websocketUrl:t,agentId:n,appId:o,voice:i,language:c,autoReconnect:u,agentSettingsOverride:d,onStartConversation:x,onEndConversation:C});return e.on("connected",function(){j(!0),M("Connected"),null==p||p()}),e.on("disconnected",function(){j(!1),M("Disconnected"),null==f||f()}),e.on("recordingStarted",function(){B(!0),null==h||h()}),e.on("recordingStopped",function(){B(!1),null==v||v()}),e.on("playbackStarted",function(){_(!0),null==g||g()}),e.on("playbackStopped",function(){_(!1),null==y||y()}),e.on("error",function(e){null==m||m(e)}),e.on("message",function(e){null==b||b(e)}),e.on("bargeIn",function(e){null==S||S(e)}),e.on("stopPlaying",function(e){null==w||w(e)}),N.current=e,e.connect(),function(){console.log("🎙️ VoiceButton: Cleaning up VoiceSDK instance for ".concat(t)),N.current&&(N.current.destroy(),N.current=null)}},[t,n,o,i,c,d]);var V=function(){var e,t=(e=bn().m(function e(){var t;return bn().w(function(e){for(;;)switch(e.p=e.n){case 0:if(N.current){e.n=1;break}return e.a(2);case 1:return e.p=1,e.n=2,N.current.toggleRecording();case 2:e.n=4;break;case 3:e.p=3,t=e.v,console.error("Error toggling recording:",t);case 4:return e.a(2)}},e,null,[[1,3]])}),function(){var t=this,n=arguments;return new Promise(function(o,r){var i=e.apply(t,n);function a(e){wn(i,o,r,a,c,"next",e)}function c(e){wn(i,o,r,a,c,"throw",e)}a(void 0)})});return function(){return t.apply(this,arguments)}}(),K=(0,hn.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[(0,hn.jsx)("div",{style:{fontSize:"20px"},children:F?"🔴":"🎤"}),(0,hn.jsx)("div",{children:F?"Stop Listening":"Start Listening"})]});return(0,hn.jsx)("button",{className:"voice-button ".concat(F?"recording":""," ").concat(P),style:yn({padding:"12px 24px",border:"none",borderRadius:"8px",backgroundColor:F?"#dc3545":"#007bff",color:"white",cursor:"pointer",fontSize:"16px",fontWeight:"500",transition:"all 0.2s ease"},E),onClick:V,disabled:!I,children:T||K})};function Pn(e){return Pn="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},Pn(e)}function On(){var e,t,n="function"==typeof Symbol?Symbol:{},o=n.iterator||"@@iterator",r=n.toStringTag||"@@toStringTag";function i(n,o,r,i){var s=o&&o.prototype instanceof c?o:c,u=Object.create(s.prototype);return En(u,"_invoke",function(n,o,r){var i,c,s,u=0,l=r||[],d=!1,p={p:0,n:0,v:e,a:f,f:f.bind(e,4),d:function(t,n){return i=t,c=0,s=e,p.n=n,a}};function f(n,o){for(c=n,s=o,t=0;!d&&u&&!r&&t<l.length;t++){var r,i=l[t],f=p.p,h=i[2];n>3?(r=h===o)&&(s=i[(c=i[4])?5:(c=3,3)],i[4]=i[5]=e):i[0]<=f&&((r=n<2&&f<i[1])?(c=0,p.v=o,p.n=i[1]):f<h&&(r=n<3||i[0]>o||o>h)&&(i[4]=n,i[5]=o,p.n=h,c=0))}if(r||n>1)return a;throw d=!0,o}return function(r,l,h){if(u>1)throw TypeError("Generator is already running");for(d&&1===l&&f(l,h),c=l,s=h;(t=c<2?e:s)||!d;){i||(c?c<3?(c>1&&(p.n=-1),f(c,s)):p.n=s:p.v=s);try{if(u=2,i){if(c||(r="next"),t=i[r]){if(!(t=t.call(i,s)))throw TypeError("iterator result is not an object");if(!t.done)return t;s=t.value,c<2&&(c=0)}else 1===c&&(t=i.return)&&t.call(i),c<2&&(s=TypeError("The iterator does not provide a '"+r+"' method"),c=1);i=e}else if((t=(d=p.n<0)?s:n.call(o,p))!==a)break}catch(t){i=e,c=1,s=t}finally{u=1}}return{value:t,done:d}}}(n,r,i),!0),u}var a={};function c(){}function s(){}function u(){}t=Object.getPrototypeOf;var l=[][o]?t(t([][o]())):(En(t={},o,function(){return this}),t),d=u.prototype=c.prototype=Object.create(l);function p(e){return Object.setPrototypeOf?Object.setPrototypeOf(e,u):(e.__proto__=u,En(e,r,"GeneratorFunction")),e.prototype=Object.create(d),e}return s.prototype=u,En(d,"constructor",u),En(u,"constructor",s),s.displayName="GeneratorFunction",En(u,r,"GeneratorFunction"),En(d),En(d,r,"Generator"),En(d,o,function(){return this}),En(d,"toString",function(){return"[object Generator]"}),(On=function(){return{w:i,m:p}})()}function En(e,t,n,o){var r=Object.defineProperty;try{r({},"",{})}catch(e){r=0}En=function(e,t,n,o){function i(t,n){En(e,t,function(e){return this._invoke(t,n,e)})}t?r?r(e,t,{value:n,enumerable:!o,configurable:!o,writable:!o}):e[t]=n:(i("next",0),i("throw",1),i("return",2))},En(e,t,n,o)}function Tn(e,t,n,o,r,i,a){try{var c=e[i](a),s=c.value}catch(e){return void n(e)}c.done?t(s):Promise.resolve(s).then(o,r)}function An(e){return function(){var t=this,n=arguments;return new Promise(function(o,r){var i=e.apply(t,n);function a(e){Tn(i,o,r,a,c,"next",e)}function c(e){Tn(i,o,r,a,c,"throw",e)}a(void 0)})}}function In(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(e);t&&(o=o.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,o)}return n}function jn(e,t,n){return(t=Fn(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function Dn(e,t){for(var n=0;n<t.length;n++){var o=t[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(e,Fn(o.key),o)}}function Fn(e){var t=function(e){if("object"!=Pn(e)||!e)return e;var t=e[Symbol.toPrimitive];if(void 0!==t){var n=t.call(e,"string");if("object"!=Pn(n))return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}(e);return"symbol"==Pn(t)?t:t+""}var Bn=function(){return e=function e(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),this.options=function(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?In(Object(n),!0).forEach(function(t){jn(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):In(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}({websocketUrl:t.websocketUrl||"wss://speech.talktopc.com/ws/conv",agentId:t.agentId,voice:t.voice||"default",language:t.language||"en",container:t.container||document.body,buttonText:t.buttonText||"Start Listening",buttonClass:t.buttonClass||"voice-button"},t),this.isConnected=!1,this.isRecording=!1,this.isPlaying=!1,this.voiceSDK=new he({websocketUrl:this.options.websocketUrl,agentId:this.options.agentId,voice:this.options.voice,language:this.options.language}),this.setupEventListeners(),this.createButton(),this.connect()},t=[{key:"setupEventListeners",value:function(){var e=this;this.voiceSDK.on("connected",function(){var t,n;e.isConnected=!0,e.updateButton(),null===(t=(n=e.options).onConnected)||void 0===t||t.call(n)}),this.voiceSDK.on("disconnected",function(){var t,n;e.isConnected=!1,e.updateButton(),null===(t=(n=e.options).onDisconnected)||void 0===t||t.call(n)}),this.voiceSDK.on("recordingStarted",function(){var t,n;e.isRecording=!0,e.updateButton(),null===(t=(n=e.options).onRecordingStarted)||void 0===t||t.call(n)}),this.voiceSDK.on("recordingStopped",function(){var t,n;e.isRecording=!1,e.updateButton(),null===(t=(n=e.options).onRecordingStopped)||void 0===t||t.call(n)}),this.voiceSDK.on("playbackStarted",function(){var t,n;e.isPlaying=!0,null===(t=(n=e.options).onPlaybackStarted)||void 0===t||t.call(n)}),this.voiceSDK.on("playbackStopped",function(){var t,n;e.isPlaying=!1,null===(t=(n=e.options).onPlaybackStopped)||void 0===t||t.call(n)}),this.voiceSDK.on("error",function(t){var n,o;null===(n=(o=e.options).onError)||void 0===n||n.call(o,t)}),this.voiceSDK.on("message",function(t){var n,o;null===(n=(o=e.options).onMessage)||void 0===n||n.call(o,t)}),this.voiceSDK.on("bargeIn",function(t){var n,o;null===(n=(o=e.options).onBargeIn)||void 0===n||n.call(o,t)}),this.voiceSDK.on("stopPlaying",function(t){var n,o;null===(n=(o=e.options).onStopPlaying)||void 0===n||n.call(o,t)})}},{key:"createButton",value:function(){var e=this;this.button=document.createElement("button"),this.button.className=this.options.buttonClass,this.button.style.cssText="\n padding: 12px 24px;\n border: none;\n border-radius: 8px;\n background-color: #6c757d;\n color: white;\n cursor: pointer;\n font-size: 16px;\n font-weight: 500;\n transition: all 0.2s ease;\n display: flex;\n align-items: center;\n gap: 8px;\n ",this.button.addEventListener("click",function(){return e.toggleRecording()}),this.options.container.appendChild(this.button),this.updateButton()}},{key:"updateButton",value:function(){if(this.button){var e=this.isRecording?"🔴":"🎤",t=this.isRecording?"Stop Listening":"Start Listening";this.button.innerHTML='\n <span style="font-size: 20px;">'.concat(e,"</span>\n <span>").concat(t,"</span>\n "),this.button.disabled=!this.isConnected,this.button.style.backgroundColor=this.isRecording?"#dc3545":this.isConnected?"#007bff":"#6c757d"}}},{key:"connect",value:(o=An(On().m(function e(){var t;return On().w(function(e){for(;;)switch(e.p=e.n){case 0:return e.p=0,e.n=1,this.voiceSDK.connect();case 1:e.n=3;break;case 2:e.p=2,t=e.v,console.error("Failed to connect:",t);case 3:return e.a(2)}},e,this,[[0,2]])})),function(){return o.apply(this,arguments)})},{key:"toggleRecording",value:(n=An(On().m(function e(){var t;return On().w(function(e){for(;;)switch(e.p=e.n){case 0:if(this.voiceSDK){e.n=1;break}return e.a(2);case 1:return e.p=1,e.n=2,this.voiceSDK.toggleRecording();case 2:e.n=4;break;case 3:e.p=3,t=e.v,console.error("Error toggling recording:",t);case 4:return e.a(2)}},e,this,[[1,3]])})),function(){return n.apply(this,arguments)})},{key:"getStatus",value:function(){return{isConnected:this.isConnected,isRecording:this.isRecording,isPlaying:this.isPlaying}}},{key:"updateConfig",value:function(e){this.voiceSDK.updateConfig(e)}},{key:"destroy",value:function(){this.button&&this.button.parentNode&&this.button.parentNode.removeChild(this.button),this.voiceSDK&&this.voiceSDK.destroy()}}],t&&Dn(e.prototype,t),Object.defineProperty(e,"prototype",{writable:!1}),e;var e,t,n,o}();function Rn(){var e,t,n="function"==typeof Symbol?Symbol:{},o=n.iterator||"@@iterator",r=n.toStringTag||"@@toStringTag";function i(n,o,r,i){var s=o&&o.prototype instanceof c?o:c,u=Object.create(s.prototype);return _n(u,"_invoke",function(n,o,r){var i,c,s,u=0,l=r||[],d=!1,p={p:0,n:0,v:e,a:f,f:f.bind(e,4),d:function(t,n){return i=t,c=0,s=e,p.n=n,a}};function f(n,o){for(c=n,s=o,t=0;!d&&u&&!r&&t<l.length;t++){var r,i=l[t],f=p.p,h=i[2];n>3?(r=h===o)&&(s=i[(c=i[4])?5:(c=3,3)],i[4]=i[5]=e):i[0]<=f&&((r=n<2&&f<i[1])?(c=0,p.v=o,p.n=i[1]):f<h&&(r=n<3||i[0]>o||o>h)&&(i[4]=n,i[5]=o,p.n=h,c=0))}if(r||n>1)return a;throw d=!0,o}return function(r,l,h){if(u>1)throw TypeError("Generator is already running");for(d&&1===l&&f(l,h),c=l,s=h;(t=c<2?e:s)||!d;){i||(c?c<3?(c>1&&(p.n=-1),f(c,s)):p.n=s:p.v=s);try{if(u=2,i){if(c||(r="next"),t=i[r]){if(!(t=t.call(i,s)))throw TypeError("iterator result is not an object");if(!t.done)return t;s=t.value,c<2&&(c=0)}else 1===c&&(t=i.return)&&t.call(i),c<2&&(s=TypeError("The iterator does not provide a '"+r+"' method"),c=1);i=e}else if((t=(d=p.n<0)?s:n.call(o,p))!==a)break}catch(t){i=e,c=1,s=t}finally{u=1}}return{value:t,done:d}}}(n,r,i),!0),u}var a={};function c(){}function s(){}function u(){}t=Object.getPrototypeOf;var l=[][o]?t(t([][o]())):(_n(t={},o,function(){return this}),t),d=u.prototype=c.prototype=Object.create(l);function p(e){return Object.setPrototypeOf?Object.setPrototypeOf(e,u):(e.__proto__=u,_n(e,r,"GeneratorFunction")),e.prototype=Object.create(d),e}return s.prototype=u,_n(d,"constructor",u),_n(u,"constructor",s),s.displayName="GeneratorFunction",_n(u,r,"GeneratorFunction"),_n(d),_n(d,r,"Generator"),_n(d,o,function(){return this}),_n(d,"toString",function(){return"[object Generator]"}),(Rn=function(){return{w:i,m:p}})()}function _n(e,t,n,o){var r=Object.defineProperty;try{r({},"",{})}catch(e){r=0}_n=function(e,t,n,o){function i(t,n){_n(e,t,function(e){return this._invoke(t,n,e)})}t?r?r(e,t,{value:n,enumerable:!o,configurable:!o,writable:!o}):e[t]=n:(i("next",0),i("throw",1),i("return",2))},_n(e,t,n,o)}function Un(e){return Un="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},Un(e)}function Mn(e,t,n,o,r,i,a){try{var c=e[i](a),s=c.value}catch(e){return void n(e)}c.done?t(s):Promise.resolve(s).then(o,r)}function Nn(e){return function(){var t=this,n=arguments;return new Promise(function(o,r){var i=e.apply(t,n);function a(e){Mn(i,o,r,a,c,"next",e)}function c(e){Mn(i,o,r,a,c,"throw",e)}a(void 0)})}}function Vn(e,t){for(var n=0;n<t.length;n++){var o=t[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(e,Kn(o.key),o)}}function Kn(e){var t=function(e){if("object"!=Un(e)||!e)return e;var t=e[Symbol.toPrimitive];if(void 0!==t){var n=t.call(e,"string");if("object"!=Un(n))return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}(e);return"symbol"==Un(t)?t:t+""}var Ln=function(){return e=function e(t){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),console.log("🚀 AgentSDK v2.1.8 initialized with config:",t),this.config=t,this.voiceSDK=null,this.isConnected=!1,this.isListening=!1,this.wasListening=!1,this.onConnected=function(){},this.onDisconnected=function(){},this.onError=function(e){return console.error("SDK Error:",e)},this.onTranscript=function(e){},this.onAgentSpeaking=function(e){},this.onConversationStart=t.onConversationStart||function(){},this.onConversationEnd=t.onConversationEnd||function(){},this.onBargeIn=t.onBargeIn||function(){},this.onAudioStartPlaying=t.onAudioStartPlaying||function(){},this.onAudioStoppedPlaying=t.onAudioStoppedPlaying||function(){},this.onSubtitleDisplay=t.onSubtitleDisplay||function(){}},t=[{key:"connect",value:(o=Nn(Rn().m(function e(t){var n,o=this;return Rn().w(function(e){for(;;)switch(e.p=e.n){case 0:if(e.p=0,t){e.n=1;break}throw new Error("signedUrl is required");case 1:return this.voiceSDK&&(console.log("🔌 AgentSDK: Cleaning up existing connection"),this.voiceSDK.destroy(),this.voiceSDK=null),this.voiceSDK=new Xt({websocketUrl:t,autoReconnect:!1,agentId:this.config.agentId,appId:this.config.appId,language:this.config.language||"en",protocolVersion:2,outputContainer:this.config.outputContainer||"raw",outputEncoding:this.config.outputEncoding||"pcm",outputSampleRate:this.config.outputSampleRate||44100,outputChannels:this.config.outputChannels||1,outputBitDepth:this.config.outputBitDepth||16}),this.voiceSDK.on("connected",function(){o.isConnected=!0,o.onConnected()}),this.voiceSDK.on("disconnected",function(e){if(o.isConnected=!1,e&&1008===e.code&&e.reason&&(e.reason.includes("Domain not whitelisted")||e.reason.includes("domain")||e.reason.includes("whitelist"))){var t=new Error("DOMAIN_NOT_WHITELISTED");t.reason=e.reason,t.code=e.code,o.onError(t)}if((o.isListening||o.wasListening)&&(console.log("🎤 [AGENT SDK] disconnected event - calling onConversationEnd hook (isListening:",o.isListening,", wasListening:",o.wasListening,")"),o.onConversationEnd&&"function"==typeof o.onConversationEnd))try{o.onConversationEnd(),console.log("🎤 [AGENT SDK] ✅ onConversationEnd hook called from disconnected event"),o.wasListening=!1}catch(e){console.error("🎤 [AGENT SDK] ❌ Error calling onConversationEnd from disconnected:",e)}o.onDisconnected()}),this.voiceSDK.on("domainError",function(e){o.onError(e)}),this.voiceSDK.on("error",function(e){o.onError(e)}),this.voiceSDK.on("message",function(e){o.handleWebSocketMessage(e)}),this.voiceSDK.on("recordingStarted",function(){if(o.isListening=!0,o.wasListening=!0,o.onConversationStart&&"function"==typeof o.onConversationStart)try{o.onConversationStart()}catch(e){console.error("🎤 [AGENT SDK] ❌ Error calling onConversationStart:",e)}}),this.voiceSDK.on("recordingStopped",function(){console.log("🎤 [AGENT SDK] recordingStopped event received");var e=o.isListening;if(o.isListening=!1,e&&o.onConversationEnd&&"function"==typeof o.onConversationEnd)try{console.log("🎤 [AGENT SDK] ✅ Calling onConversationEnd hook from recordingStopped"),o.onConversationEnd(),console.log("🎤 [AGENT SDK] ✅ onConversationEnd hook called successfully"),o.wasListening=!1}catch(e){console.error("🎤 [AGENT SDK] ❌ Error calling onConversationEnd:",e)}}),this.voiceSDK.on("playbackStarted",function(){o.onAgentSpeaking(!0),o.onAudioStartPlaying()}),this.voiceSDK.on("playbackStopped",function(){o.onAgentSpeaking(!1),o.onAudioStoppedPlaying()}),this.voiceSDK.on("bargeIn",function(e){o.onBargeIn(e)}),this.voiceSDK.on("transcriptDisplay",function(e){console.log("📝 [AGENT SDK] transcriptDisplay event received:",e),e&&e.text&&(console.log("📝 [AGENT SDK] Calling onTranscript with text:",e.text),o.onTranscript&&"function"==typeof o.onTranscript?o.onTranscript(e.text):console.warn("📝 [AGENT SDK] ⚠️ onTranscript is not a function!",Un(o.onTranscript))),o.onSubtitleDisplay(e)}),e.n=2,this.voiceSDK.connect();case 2:e.n=4;break;case 3:throw e.p=3,n=e.v,this.onError(n),n;case 4:return e.a(2)}},e,this,[[0,3]])})),function(e){return o.apply(this,arguments)})},{key:"handleWebSocketMessage",value:function(e){switch(e.t||e.type){case"connected":case"hello_ack":console.log("Session started successfully");break;case"user_transcript":this.onTranscript(e.user_transcription||e.text||e.transcript);break;case"agent_response":case"barge_in":case"stop_playing":default:break;case"error":this.onError(new Error(e.message||e.error||"Unknown error"))}}},{key:"startListening",value:(n=Nn(Rn().m(function e(){var t;return Rn().w(function(e){for(;;)switch(e.p=e.n){case 0:if(console.log("🎤 AgentSDK: startListening() called"),!this.voiceSDK){e.n=5;break}return e.p=1,console.log("🎤 AgentSDK: Starting recording..."),e.n=2,this.voiceSDK.startRecording();case 2:console.log("✅ AgentSDK: Recording started successfully"),e.n=4;break;case 3:throw e.p=3,t=e.v,console.error("❌ AgentSDK: Failed to start recording:",t),t;case 4:e.n=6;break;case 5:throw console.error("❌ AgentSDK: No voiceSDK instance available"),new Error("No voiceSDK instance available");case 6:return e.a(2)}},e,this,[[1,3]])})),function(){return n.apply(this,arguments)})},{key:"stopListening",value:function(){this.voiceSDK&&this.voiceSDK.stopRecording()}},{key:"updateVariables",value:function(e){this.voiceSDK&&this.isConnected&&this.voiceSDK.sendMessage({t:"update_variables",variables:e})}},{key:"disconnect",value:function(){this.voiceSDK&&(this.voiceSDK.destroy(),this.voiceSDK=null),this.isConnected=!1,this.isListening=!1}}],t&&Vn(e.prototype,t),Object.defineProperty(e,"prototype",{writable:!1}),e;var e,t,n,o}();function zn(e){return zn="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},zn(e)}function Hn(){var e,t,n="function"==typeof Symbol?Symbol:{},o=n.iterator||"@@iterator",r=n.toStringTag||"@@toStringTag";function i(n,o,r,i){var s=o&&o.prototype instanceof c?o:c,u=Object.create(s.prototype);return Wn(u,"_invoke",function(n,o,r){var i,c,s,u=0,l=r||[],d=!1,p={p:0,n:0,v:e,a:f,f:f.bind(e,4),d:function(t,n){return i=t,c=0,s=e,p.n=n,a}};function f(n,o){for(c=n,s=o,t=0;!d&&u&&!r&&t<l.length;t++){var r,i=l[t],f=p.p,h=i[2];n>3?(r=h===o)&&(s=i[(c=i[4])?5:(c=3,3)],i[4]=i[5]=e):i[0]<=f&&((r=n<2&&f<i[1])?(c=0,p.v=o,p.n=i[1]):f<h&&(r=n<3||i[0]>o||o>h)&&(i[4]=n,i[5]=o,p.n=h,c=0))}if(r||n>1)return a;throw d=!0,o}return function(r,l,h){if(u>1)throw TypeError("Generator is already running");for(d&&1===l&&f(l,h),c=l,s=h;(t=c<2?e:s)||!d;){i||(c?c<3?(c>1&&(p.n=-1),f(c,s)):p.n=s:p.v=s);try{if(u=2,i){if(c||(r="next"),t=i[r]){if(!(t=t.call(i,s)))throw TypeError("iterator result is not an object");if(!t.done)return t;s=t.value,c<2&&(c=0)}else 1===c&&(t=i.return)&&t.call(i),c<2&&(s=TypeError("The iterator does not provide a '"+r+"' method"),c=1);i=e}else if((t=(d=p.n<0)?s:n.call(o,p))!==a)break}catch(t){i=e,c=1,s=t}finally{u=1}}return{value:t,done:d}}}(n,r,i),!0),u}var a={};function c(){}function s(){}function u(){}t=Object.getPrototypeOf;var l=[][o]?t(t([][o]())):(Wn(t={},o,function(){return this}),t),d=u.prototype=c.prototype=Object.create(l);function p(e){return Object.setPrototypeOf?Object.setPrototypeOf(e,u):(e.__proto__=u,Wn(e,r,"GeneratorFunction")),e.prototype=Object.create(d),e}return s.prototype=u,Wn(d,"constructor",u),Wn(u,"constructor",s),s.displayName="GeneratorFunction",Wn(u,r,"GeneratorFunction"),Wn(d),Wn(d,r,"Generator"),Wn(d,o,function(){return this}),Wn(d,"toString",function(){return"[object Generator]"}),(Hn=function(){return{w:i,m:p}})()}function Wn(e,t,n,o){var r=Object.defineProperty;try{r({},"",{})}catch(e){r=0}Wn=function(e,t,n,o){function i(t,n){Wn(e,t,function(e){return this._invoke(t,n,e)})}t?r?r(e,t,{value:n,enumerable:!o,configurable:!o,writable:!o}):e[t]=n:(i("next",0),i("throw",1),i("return",2))},Wn(e,t,n,o)}function Gn(e,t,n,o,r,i,a){try{var c=e[i](a),s=c.value}catch(e){return void n(e)}c.done?t(s):Promise.resolve(s).then(o,r)}function qn(e){return function(){var t=this,n=arguments;return new Promise(function(o,r){var i=e.apply(t,n);function a(e){Gn(i,o,r,a,c,"next",e)}function c(e){Gn(i,o,r,a,c,"throw",e)}a(void 0)})}}function Qn(e,t){for(var n=0;n<t.length;n++){var o=t[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(e,Jn(o.key),o)}}function Jn(e){var t=function(e){if("object"!=zn(e)||!e)return e;var t=e[Symbol.toPrimitive];if(void 0!==t){var n=t.call(e,"string");if("object"!=zn(n))return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}(e);return"symbol"==zn(t)?t:t+""}var Yn=function(){return e=function e(t){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),this.config=t,this.audioStream=null,this.callStartTime=null,this.callTimerInterval=null,this.sdk=null,this.isActive=!1,this.sdk=new Ln({agentId:t.agentId,appId:t.appId,getSessionUrl:t.getSessionUrl,websocketUrl:t.websocketUrl,variables:t.variables||{},language:t.language||"en",outputContainer:t.outputContainer,outputEncoding:t.outputEncoding,outputSampleRate:t.outputSampleRate,outputChannels:t.outputChannels,outputBitDepth:t.outputBitDepth,onConversationStart:t.onConversationStart,onConversationEnd:t.onConversationEnd,onBargeIn:t.onBargeIn,onAudioStartPlaying:t.onAudioStartPlaying,onAudioStoppedPlaying:t.onAudioStoppedPlaying,onSubtitleDisplay:t.onSubtitleDisplay}),this.setupSDKEventHandlers()},t=[{key:"setupSDKEventHandlers",value:function(){var e=this;this.sdk.onTranscript=function(t){console.log("📝 [VOICE INTERFACE] onTranscript called with text:",t),e.updateTranscript(t)},this.sdk.onAgentSpeaking=function(e){var t=document.getElementById("voiceAvatarActive");t&&(e?t.classList.add("speaking"):t.classList.remove("speaking"))},this.sdk.onDisconnected=function(){console.log("🔌 WebSocket disconnected, hanging up call..."),e.isActive&&(e.isActive=!1,e.endVoiceCall())},this.sdk.onError=function(t){console.error("❌ Voice SDK Error:",t),t&&("DOMAIN_NOT_WHITELISTED"===t.message||t.message&&t.message.includes("Domain not whitelisted"))?e.showDomainError():e.showError(t.message||t)}}},{key:"t",value:function(e){var t,n,o=this.config.language||"en";return((null===(t=this.config.translations)||void 0===t?void 0:t[o])||(null===(n=this.config.translations)||void 0===n?void 0:n.en)||{})[e]||e}},{key:"getTooltip",value:function(e){var t,n=null===(t=this.config.tooltips)||void 0===t?void 0:t[e];return null!=n?n:{mute:this.t("mute"),speaker:this.t("speaker"),endCall:this.t("endCall")}[e]||""}},{key:"generateHTML",value:function(){return'<div class="voice-interface" id="voiceInterface">\n \x3c!-- Before Call State --\x3e\n <div id="voiceIdleState">\n <div class="voice-avatar" id="voiceAvatar">🤖</div>\n <div class="voice-status">\n <div class="voice-status-title">'.concat(this.t("clickToStartCall"),'</div>\n <div class="voice-status-subtitle">').concat(this.t("realTimeVoice"),'</div>\n </div>\n <button class="start-call-btn" id="startCallBtn">\n <svg width="32" height="32" viewBox="0 0 24 24" fill="currentColor">\n <path d="M20.01 15.38c-1.23 0-2.42-.2-3.53-.56-.35-.12-.74-.03-1.01.24l-1.57 1.97c-2.83-1.35-5.48-3.9-6.89-6.83l1.95-1.66c.27-.28.35-.67.24-1.02-.37-1.11-.56-2.3-.56-3.53 0-.54-.45-.99-.99-.99H4.19C3.65 3 3 3.24 3 3.99 3 13.28 10.73 21 20.01 21c.71 0 .99-.63.99-1.18v-3.45c0-.54-.45-.99-.99-.99z"/>\n </svg>\n <span>').concat(this.t("startCall"),'</span>\n </button>\n </div>\n \x3c!-- During Call State --\x3e\n <div id="voiceActiveState" style="display: none;">\n <div class="voice-avatar-active" id="voiceAvatarActive">\n <div class="voice-rings">\n <div class="voice-ring"></div>\n <div class="voice-ring"></div>\n <div class="voice-ring"></div>\n </div>\n 🤖\n </div>\n <div class="voice-status">\n <div class="voice-status-title" id="voiceStatusTitleActive">').concat(this.t("listening"),'</div>\n <div class="voice-status-subtitle" id="voiceStatusSubtitleActive">').concat(this.t("speakFreely"),'</div>\n </div>\n <div class="voice-transcript">\n <div class="transcript-label">').concat(this.t("liveTranscript"),'</div>\n <div class="transcript-text empty" id="transcriptText">\n ').concat(this.t("transcriptWillAppear"),'\n </div>\n </div>\n <div class="voice-controls">\n <button class="voice-control-btn secondary" id="muteBtn" title="').concat(this.getTooltip("mute"),'">\n <svg width="64" height="64" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round" class="mute-icon">\n <path d="M12 1a3 3 0 0 0-3 3v8a3 3 0 0 0 6 0V4a3 3 0 0 0-3-3z"/>\n <path d="M19 10v2a7 7 0 0 1-14 0v-2"/>\n <line x1="12" y1="19" x2="12" y2="23"/>\n <line x1="8" y1="23" x2="16" y2="23"/>\n <line x1="2" y1="2" x2="22" y2="22" class="mute-cross" style="display: none; stroke: #ef4444; stroke-width: 3.5;"/>\n </svg>\n </button>\n <button class="voice-control-btn primary active" id="endCallBtn" title="').concat(this.getTooltip("endCall"),'">\n <svg width="56" height="56" viewBox="0 0 24 24" fill="#ef4444">\n <rect x="6" y="6" width="12" height="12" rx="2"/>\n </svg>\n <div class="voice-timer" id="voiceTimer">00:00</div>\n </button>\n <button class="voice-control-btn secondary" id="speakerBtn" title="').concat(this.getTooltip("speaker"),'">\n <svg width="64" height="64" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round">\n <polygon points="11 5 6 9 2 9 2 15 6 15 11 19 11 5"/>\n <path d="M19.07 4.93a10 10 0 0 1 0 14.14"/>\n <path d="M15.54 8.46a5 5 0 0 1 0 7.07"/>\n </svg>\n </button>\n </div>\n </div>\n </div>')}},{key:"generateCSS",value:function(){var e=this.config.avatarBackgroundColor||"#667eea",t=this.config.avatarActiveBackgroundColor||this.config.avatarBackgroundColor||"#667eea",n=this.config.statusTitleColor||"#1e293b",o=this.config.statusSubtitleColor||"#64748b",r=this.config.startCallButtonColor||"#667eea",i=this.config.startCallButtonTextColor||"#FFFFFF",a=this.config.transcriptBackgroundColor||"#FFFFFF",c=this.config.transcriptTextColor||"#1e293b",s=this.config.transcriptLabelColor||"#94a3b8",u=this.config.controlButtonColor||"#FFFFFF",l=this.config.controlButtonSecondaryColor||"#64748b";return this.config.endCallButtonColor,'\n /* Voice Interface Styles - Ultra-compact for Wix iframes */\n .voice-interface { \n display: none; \n flex: 1; \n flex-direction: column;\n align-items: center; \n justify-content: center; \n padding: 6px 10px 6px 10px; \n background: linear-gradient(180deg, #f8fafc 0%, #e0e7ff 100%);\n overflow: hidden;\n min-height: 0;\n height: 100%;\n width: 100%;\n box-sizing: border-box;\n }\n .voice-interface.active { display: flex; }\n \n /* Voice States - Better scaling gaps */\n #voiceIdleState,\n #voiceActiveState {\n display: flex;\n flex-direction: column;\n align-items: center;\n width: 100%;\n height: 100%;\n min-height: 0;\n justify-content: center;\n overflow: hidden;\n flex: 1;\n box-sizing: border-box;\n gap: clamp(6px, 1.5vh, 12px);\n }\n \n #voiceActiveState[style*="display: none"] {\n display: none !important;\n }\n \n /* Voice Avatar - Scales better from small to large */\n .voice-avatar,\n .voice-avatar-active {\n width: clamp(80px, 18vh, 160px);\n height: clamp(80px, 18vh, 160px);\n aspect-ratio: 1;\n border-radius: 50%;\n background: linear-gradient(135deg, '.concat(e," 0%, ").concat(t," 100%);\n display: flex;\n align-items: center;\n justify-content: center;\n font-size: clamp(40px, 9vh, 80px);\n margin: 0;\n box-shadow: 0 8px 30px rgba(102, 126, 234, 0.3);\n transition: all 0.3s ease;\n flex-shrink: 1;\n position: relative;\n }\n \n .voice-avatar-active {\n animation: avatarPulse 2s ease-in-out infinite;\n }\n \n @keyframes avatarPulse {\n 0%, 100% { \n transform: scale(1);\n }\n 50% { \n transform: scale(1.05);\n }\n }\n \n .voice-avatar-active.speaking {\n animation: avatarSpeak 0.5s ease-in-out infinite;\n }\n \n @keyframes avatarSpeak {\n 0%, 100% { transform: scale(1); }\n 50% { transform: scale(1.08); }\n }\n \n /* Voice Rings Animation */\n .voice-rings {\n position: absolute;\n width: 100%;\n height: 100%;\n border-radius: 50%;\n }\n \n .voice-ring {\n position: absolute;\n top: 50%;\n left: 50%;\n transform: translate(-50%, -50%);\n border: 2px solid rgba(102, 126, 234, 0.3);\n border-radius: 50%;\n opacity: 0;\n animation: ringExpand 2s ease-out infinite;\n }\n \n .voice-ring:nth-child(2) { animation-delay: 0.5s; }\n .voice-ring:nth-child(3) { animation-delay: 1s; }\n \n @keyframes ringExpand {\n 0% {\n width: 100%;\n height: 100%;\n opacity: 0.6;\n }\n 100% {\n width: 160%;\n height: 160%;\n opacity: 0;\n }\n }\n \n /* Voice Status - Scales with container */\n .voice-status {\n text-align: center;\n margin: 0;\n flex-shrink: 1;\n min-height: 0;\n }\n \n .voice-status-title {\n font-size: clamp(12px, 3vh, 20px);\n font-weight: 600;\n color: ").concat(n,";\n margin-bottom: clamp(2px, 0.5vh, 4px);\n line-height: 1.2;\n }\n \n .voice-status-subtitle {\n font-size: clamp(10px, 2vh, 14px);\n color: ").concat(o,";\n line-height: 1.2;\n }\n \n /* Start Call Button - Scales with container */\n .start-call-btn {\n margin: 0;\n width: min(280px, 70vw);\n height: clamp(48px, 8vh, 64px);\n border-radius: clamp(24px, 4vh, 32px);\n border: none;\n background: ").concat(r,";\n color: ").concat(i,";\n font-size: clamp(14px, 2.5vh, 18px);\n font-weight: 600;\n cursor: pointer;\n display: flex;\n align-items: center;\n justify-content: center;\n gap: clamp(8px, 1.5vh, 12px);\n box-shadow: 0 12px 30px rgba(102, 126, 234, 0.4);\n transition: all 0.3s ease;\n flex-shrink: 0;\n }\n \n .start-call-btn svg {\n width: clamp(22px, 4vh, 32px);\n height: clamp(22px, 4vh, 32px);\n }\n \n .start-call-btn:hover {\n transform: translateY(-2px);\n box-shadow: 0 12px 28px rgba(102, 126, 234, 0.5);\n }\n \n .start-call-btn:active {\n transform: translateY(-1px);\n }\n \n /* Voice Transcript - Scales with container */\n .voice-transcript {\n background: ").concat(a,";\n padding: clamp(6px, 1.5vh, 12px);\n border-radius: 10px;\n width: min(360px, calc(100% - 40px));\n margin: 0;\n min-height: clamp(100px, 18vh, 140px);\n max-height: clamp(120px, 22vh, 160px);\n box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);\n flex-shrink: 1;\n overflow-y: auto;\n overflow-x: hidden;\n display: flex;\n flex-direction: column;\n box-sizing: border-box;\n }\n \n .transcript-label {\n font-size: clamp(8px, 1.4vh, 11px);\n color: ").concat(s,";\n font-weight: 600;\n text-transform: uppercase;\n letter-spacing: 0.3px;\n margin-bottom: clamp(3px, 0.6vh, 6px);\n flex-shrink: 0;\n word-wrap: break-word;\n }\n \n .transcript-text {\n font-size: clamp(11px, 2vh, 15px);\n color: ").concat(c,";\n line-height: 1.4;\n flex: 1;\n overflow-y: auto;\n overflow-x: hidden;\n word-wrap: break-word;\n overflow-wrap: break-word;\n }\n \n .transcript-text.empty {\n color: #cbd5e1;\n font-style: italic;\n }\n \n /* Voice Controls - Scales with container */\n .voice-controls {\n display: flex;\n gap: clamp(8px, 1.8vh, 14px);\n align-items: center;\n justify-content: center;\n flex-shrink: 0;\n margin: 0;\n padding-top: clamp(5px, 1.2vh, 10px);\n }\n \n .voice-control-btn {\n width: clamp(48px, 9vh, 72px);\n height: clamp(48px, 9vh, 72px);\n aspect-ratio: 1;\n border-radius: 50%;\n border: none;\n cursor: pointer;\n display: flex;\n align-items: center;\n justify-content: center;\n transition: all 0.2s;\n position: relative;\n flex-shrink: 0;\n }\n \n .voice-control-btn svg {\n width: 48%;\n height: 48%;\n }\n \n .voice-control-btn.primary {\n width: clamp(54px, 10vh, 80px);\n height: clamp(54px, 10vh, 80px);\n background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);\n color: white;\n box-shadow: 0 6px 18px rgba(102, 126, 234, 0.4);\n }\n \n .voice-control-btn.primary:hover {\n transform: scale(1.05);\n }\n \n .voice-control-btn.primary.active {\n background: white;\n animation: recordingPulse 1.5s ease-in-out infinite;\n }\n \n @keyframes recordingPulse {\n 0%, 100% { \n box-shadow: 0 6px 16px rgba(239, 68, 68, 0.4);\n }\n 50% { \n box-shadow: 0 6px 24px rgba(239, 68, 68, 0.7);\n }\n }\n \n .voice-control-btn.secondary {\n background: ").concat(u,";\n color: ").concat(l,";\n box-shadow: 0 3px 10px rgba(0, 0, 0, 0.1);\n }\n \n .voice-control-btn.secondary:hover {\n background: #f8fafc;\n transform: scale(1.05);\n }\n \n .voice-control-btn.secondary.muted {\n background: #f3f4f6;\n }\n \n .voice-control-btn.secondary.muted .mute-icon {\n stroke: #9ca3af !important;\n }\n \n .voice-timer {\n position: absolute;\n bottom: clamp(-18px, -3vh, -24px);\n font-size: clamp(9px, 1.6vh, 12px);\n color: #64748b;\n font-weight: 500;\n white-space: nowrap;\n }\n \n /* Mobile optimization */\n @media (max-width: 768px) {\n .voice-interface {\n padding: 6px 10px;\n }\n }\n \n @media (max-width: 480px) {\n .voice-interface {\n padding: 5px 8px;\n }\n }\n ")}},{key:"setupEventHandlers",value:function(e){var t=this,n=document.getElementById("startCallBtn"),o=document.getElementById("endCallBtn"),r=document.getElementById("muteBtn"),i=document.getElementById("speakerBtn");n&&(n.onclick=function(){return t.startVoiceCall()}),o&&(o.onclick=function(){return t.endVoiceCall()}),r&&(r.onclick=function(){return t.toggleMute()}),i&&(i.onclick=function(){return t.toggleSpeaker()});var a=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0,n=document.getElementById("voiceInterface");n&&n.classList.contains("active")&&n.clientHeight>100?(console.log("✅ Interface is active and has proper dimensions, adjusting sizes (attempt",e+1,")"),t.adjustSizesForContainer(),0===e&&setTimeout(function(){return t.adjustSizesForContainer()},500)):e<15?(console.log("⏳ Interface not ready yet (height:",null==n?void 0:n.clientHeight,"), retrying... (attempt",e+1,")"),setTimeout(function(){return a(e+1)},250)):(console.warn("⚠️ Interface never became fully ready, adjusting sizes anyway"),t.adjustSizesForContainer())};setTimeout(function(){return a()},200),window.addEventListener("resize",function(){console.log("🔄 Window resized, re-adjusting sizes"),t.adjustSizesForContainer()})}},{key:"getSignedUrl",value:(o=qn(Hn().m(function e(){var t,n,o,r,i,a,c;return Hn().w(function(e){for(;;)switch(e.n){case 0:if(this.config.getSessionUrl){e.n=2;break}if(this.config.agentId){e.n=1;break}throw new Error("agentId is required");case 1:return t=this.config.websocketUrl||"wss://speech.talktopc.com/ws/conv",(n=new URLSearchParams).append("agentId",this.config.agentId),this.config.appId&&n.append("appId",this.config.appId),!1!==this.config.demo&&n.append("demo","true"),e.a(2,"".concat(t,"?").concat(n.toString()));case 2:if("string"!=typeof this.config.getSessionUrl){e.n=6;break}return o={agentId:this.config.agentId,variables:this.config.variables||{}},this.config.appId&&(o.appId=this.config.appId),e.n=3,fetch(this.config.getSessionUrl,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)});case 3:if((r=e.v).ok){e.n=4;break}throw new Error("Failed to get session URL: ".concat(r.statusText));case 4:return e.n=5,r.json();case 5:return i=e.v,e.a(2,i.signedUrl||i.wsUrl||i.url);case 6:if("function"!=typeof this.config.getSessionUrl){e.n=8;break}return a={agentId:this.config.agentId,variables:this.config.variables||{}},this.config.appId&&(a.appId=this.config.appId),e.n=7,this.config.getSessionUrl(a);case 7:return c=e.v,e.a(2,"string"==typeof c?c:c.signedUrl||c.wsUrl||c.url);case 8:throw new Error("getSessionUrl must be a string (backend URL), a function, or omitted (for direct connection with agentId/appId)");case 9:return e.a(2)}},e,this)})),function(){return o.apply(this,arguments)})},{key:"adjustSizesForContainer",value:function(){var e=document.getElementById("voiceInterface");if(e){var t=e.clientHeight,n=e.clientWidth;console.log("📏 Container size:",t,"x",n);var o,r,i,a,c,s,u,l,d,p=document.getElementById("voiceIdleState"),f=document.getElementById("voiceActiveState"),h=p&&"none"!==p.style.display,v=f&&"none"!==f.style.display;console.log("👁️ Visible state - Idle:",h,"Active:",v),t<=350?(d=5,o=70,r=35,i=11,a=9,c=32,s=100,u=42,l=48):t<=450?(d=7,o=110,r=55,i=15,a=11,c=38,s=110,u=52,l=58):t<=550?(d=8,o=140,r=70,i=16,a=12,c=42,s=120,u=56,l=64):t<=700?(d=10,o=130,r=65,i=18,a=13,c=46,s=130,u=60,l=70):(d=12,o=150,r=75,i=20,a=14,c=50,s=140,u=66,l=76),document.querySelectorAll("#voiceIdleState, #voiceActiveState").forEach(function(e){e.style.gap="".concat(d,"px")});var g=document.querySelectorAll(".voice-avatar, .voice-avatar-active");console.log("🤖 Found",g.length,"avatars, setting size to",o,"px"),g.forEach(function(e){e.style.width="".concat(o,"px"),e.style.height="".concat(o,"px"),e.style.fontSize="".concat(r,"px")}),document.querySelectorAll(".voice-status-title").forEach(function(e){return e.style.fontSize="".concat(i,"px")}),document.querySelectorAll(".voice-status-subtitle").forEach(function(e){return e.style.fontSize="".concat(a,"px")});var y=document.querySelector(".voice-transcript");y&&(y.style.minHeight="".concat(s,"px"),y.style.maxHeight="".concat(s,"px"),y.style.height="".concat(s,"px"),y.style.width="min(360px, ".concat(n-40,"px)"),y.style.boxSizing="border-box");var m=document.querySelector(".transcript-label");m&&(m.style.fontSize="".concat(Math.max(8,i-4),"px"));var b=document.querySelector(".transcript-text");b&&(b.style.fontSize="".concat(Math.max(10,i-2),"px")),document.querySelectorAll(".voice-control-btn.secondary").forEach(function(e){e.style.width="".concat(u,"px"),e.style.height="".concat(u,"px");var t=e.querySelector("svg");if(t){var n=.65*u;t.style.setProperty("width","".concat(n,"px"),"important"),t.style.setProperty("height","".concat(n,"px"),"important"),t.style.setProperty("min-width","".concat(n,"px"),"important"),t.style.setProperty("min-height","".concat(n,"px"),"important")}});var S=document.querySelector(".voice-control-btn.primary");if(S){S.style.width="".concat(l,"px"),S.style.height="".concat(l,"px");var w=S.querySelector("svg");if(w){var x=.7*l;w.style.setProperty("width","".concat(x,"px"),"important"),w.style.setProperty("height","".concat(x,"px"),"important"),w.style.setProperty("min-width","".concat(x,"px"),"important"),w.style.setProperty("min-height","".concat(x,"px"),"important")}}var C=document.querySelector(".start-call-btn");if(C){var k,P;t<=350?(k=48,P=14):t<=450?(k=52,P=15):t<=550?(k=58,P=17):t<=700?(k=62,P=18):(k=64,P=18),C.style.height="".concat(k,"px"),C.style.fontSize="".concat(P,"px");var O=C.querySelector("svg");if(O){var E=Math.max(22,.5*k);O.style.width="".concat(E,"px"),O.style.height="".concat(E,"px")}}console.log("✅ Sizes adjusted - Avatar:",o,"Status:",c,"Transcript:",s,"Buttons:",u)}else console.warn("⚠️ voiceInterface not found, skipping size adjustment")}},{key:"startVoiceCall",value:(n=qn(Hn().m(function e(){var t,n,o,r,i,a,c,s,u,l=this;return Hn().w(function(e){for(;;)switch(e.p=e.n){case 0:if(!this.isActive){e.n=1;break}return console.log("⚠️ Voice call already active"),e.a(2);case 1:return console.log("🎤 Starting voice call..."),e.p=2,t=document.getElementById("voiceIdleState"),n=document.getElementById("voiceActiveState"),o=document.getElementById("voiceInterface"),t&&(t.style.display="none"),n&&(n.style.display="flex"),setTimeout(function(){return l.adjustSizesForContainer()},50),o&&(o.scrollTop=0),e.n=3,this.getSignedUrl();case 3:return r=e.v,console.log("🔗 Got signed URL:",r),e.n=4,this.sdk.connect(r);case 4:i=e.v,console.log("✅ Connected to WebSocket, connected:",i),a=0;case 5:if(this.sdk.isConnected||!(a<50)){e.n=7;break}return e.n=6,new Promise(function(e){return setTimeout(e,100)});case 6:a++,e.n=5;break;case 7:if(!this.sdk.isConnected){e.n=9;break}return console.log("✅ WebSocket ready, starting listening..."),e.n=8,this.sdk.startListening();case 8:console.log("🎤 Started listening"),this.isActive=!0,this.callStartTime=Date.now(),this.callTimerInterval=setInterval(function(){var e=Date.now()-l.callStartTime,t=Math.floor(e/6e4),n=Math.floor(e%6e4/1e3),o=document.getElementById("voiceTimer");o&&(o.textContent="".concat(t.toString().padStart(2,"0"),":").concat(n.toString().padStart(2,"0")))},1e3),e.n=11;break;case 9:return console.warn("⚠️ Connection not fully ready, but trying to start listening anyway..."),e.n=10,this.sdk.startListening();case 10:console.log("🎤 Started listening"),this.isActive=!0,this.callStartTime=Date.now(),this.callTimerInterval=setInterval(function(){var e=Date.now()-l.callStartTime,t=Math.floor(e/6e4),n=Math.floor(e%6e4/1e3),o=document.getElementById("voiceTimer");o&&(o.textContent="".concat(t.toString().padStart(2,"0"),":").concat(n.toString().padStart(2,"0")))},1e3);case 11:console.log("✅ Voice call started successfully"),e.n=13;break;case 12:e.p=12,u=e.v,console.error("❌ Error starting voice call:",u),this.showError(u.message||u),c=document.getElementById("voiceIdleState"),s=document.getElementById("voiceActiveState"),c&&(c.style.display="flex"),s&&(s.style.display="none");case 13:return e.a(2)}},e,this,[[2,12]])})),function(){return n.apply(this,arguments)})},{key:"endVoiceCall",value:function(){var e=this;console.log("🔴 Ending voice call..."),this.sdk&&this.isActive&&(this.sdk.stopListening(),this.sdk.disconnect(),this.isActive=!1),this.audioStream&&(this.audioStream.getTracks().forEach(function(e){return e.stop()}),this.audioStream=null),this.callTimerInterval&&(clearInterval(this.callTimerInterval),this.callTimerInterval=null);var t=document.getElementById("voiceIdleState"),n=document.getElementById("voiceActiveState");t&&(t.style.display="flex"),n&&(n.style.display="none"),setTimeout(function(){return e.adjustSizesForContainer()},50);var o=document.getElementById("transcriptText");o&&(o.textContent=this.t("transcriptWillAppear"),o.classList.add("empty"));var r=document.getElementById("voiceAvatarActive");r&&r.classList.remove("speaking"),console.log("✅ Voice call ended")}},{key:"updateTranscript",value:function(e){console.log("📝 [VOICE INTERFACE] updateTranscript called with text:",e);var t=document.getElementById("transcriptText");t?(console.log("📝 [VOICE INTERFACE] Found transcript element, updating text"),t.textContent=e,t.classList.remove("empty")):console.warn("📝 [VOICE INTERFACE] ⚠️ transcriptText element not found!")}},{key:"showError",value:function(e){var t=document.getElementById("transcriptText");t&&(t.textContent="".concat(this.t("error"),": ").concat(e),t.classList.remove("empty"))}},{key:"showDomainError",value:function(){var e=document.getElementById("transcriptText");if(e){var t=this.t("domainNotValidated"),n=this.t("domainErrorMessage");e.innerHTML='<div style="font-weight: 600; font-size: 16px; margin-bottom: 8px; color: #991B1B;">'.concat(t,'</div><div style="font-size: 14px; color: #991B1B; line-height: 1.5;">').concat(n,"</div>"),e.classList.remove("empty")}}},{key:"toggleMute",value:function(){if(this.sdk&&this.isActive){var e=null;if(this.sdk.voiceSDK&&this.sdk.voiceSDK.audioRecorder&&this.sdk.voiceSDK.audioRecorder.mediaStream&&(e=this.sdk.voiceSDK.audioRecorder.mediaStream.getAudioTracks()[0]),!e&&this.audioStream&&(e=this.audioStream.getAudioTracks()[0]),e){e.enabled=!e.enabled;var t=document.getElementById("muteBtn"),n=null==t?void 0:t.querySelector(".mute-icon"),o=null==t?void 0:t.querySelector(".mute-cross");t&&n&&o&&(e.enabled?(n.style.stroke="",o.style.display="none",t.classList.remove("muted")):(n.style.stroke="#9ca3af",o.style.display="block",t.classList.add("muted"))),console.log(e.enabled?"🔊 Unmuted":"🔇 Muted")}else console.warn("⚠️ No audio track available for mute toggle")}}},{key:"toggleSpeaker",value:function(){console.log("🔊 Speaker toggle")}},{key:"destroy",value:function(){this.isActive&&this.endVoiceCall(),this.audioStream&&(this.audioStream.getTracks().forEach(function(e){return e.stop()}),this.audioStream=null),this.callTimerInterval&&(clearInterval(this.callTimerInterval),this.callTimerInterval=null),this.sdk&&(this.sdk.disconnect(),this.sdk=null)}}],t&&Qn(e.prototype,t),Object.defineProperty(e,"prototype",{writable:!1}),e;var e,t,n,o}();function $n(e){return $n="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},$n(e)}function Xn(){var e,t,n="function"==typeof Symbol?Symbol:{},o=n.iterator||"@@iterator",r=n.toStringTag||"@@toStringTag";function i(n,o,r,i){var s=o&&o.prototype instanceof c?o:c,u=Object.create(s.prototype);return Zn(u,"_invoke",function(n,o,r){var i,c,s,u=0,l=r||[],d=!1,p={p:0,n:0,v:e,a:f,f:f.bind(e,4),d:function(t,n){return i=t,c=0,s=e,p.n=n,a}};function f(n,o){for(c=n,s=o,t=0;!d&&u&&!r&&t<l.length;t++){var r,i=l[t],f=p.p,h=i[2];n>3?(r=h===o)&&(s=i[(c=i[4])?5:(c=3,3)],i[4]=i[5]=e):i[0]<=f&&((r=n<2&&f<i[1])?(c=0,p.v=o,p.n=i[1]):f<h&&(r=n<3||i[0]>o||o>h)&&(i[4]=n,i[5]=o,p.n=h,c=0))}if(r||n>1)return a;throw d=!0,o}return function(r,l,h){if(u>1)throw TypeError("Generator is already running");for(d&&1===l&&f(l,h),c=l,s=h;(t=c<2?e:s)||!d;){i||(c?c<3?(c>1&&(p.n=-1),f(c,s)):p.n=s:p.v=s);try{if(u=2,i){if(c||(r="next"),t=i[r]){if(!(t=t.call(i,s)))throw TypeError("iterator result is not an object");if(!t.done)return t;s=t.value,c<2&&(c=0)}else 1===c&&(t=i.return)&&t.call(i),c<2&&(s=TypeError("The iterator does not provide a '"+r+"' method"),c=1);i=e}else if((t=(d=p.n<0)?s:n.call(o,p))!==a)break}catch(t){i=e,c=1,s=t}finally{u=1}}return{value:t,done:d}}}(n,r,i),!0),u}var a={};function c(){}function s(){}function u(){}t=Object.getPrototypeOf;var l=[][o]?t(t([][o]())):(Zn(t={},o,function(){return this}),t),d=u.prototype=c.prototype=Object.create(l);function p(e){return Object.setPrototypeOf?Object.setPrototypeOf(e,u):(e.__proto__=u,Zn(e,r,"GeneratorFunction")),e.prototype=Object.create(d),e}return s.prototype=u,Zn(d,"constructor",u),Zn(u,"constructor",s),s.displayName="GeneratorFunction",Zn(u,r,"GeneratorFunction"),Zn(d),Zn(d,r,"Generator"),Zn(d,o,function(){return this}),Zn(d,"toString",function(){return"[object Generator]"}),(Xn=function(){return{w:i,m:p}})()}function Zn(e,t,n,o){var r=Object.defineProperty;try{r({},"",{})}catch(e){r=0}Zn=function(e,t,n,o){function i(t,n){Zn(e,t,function(e){return this._invoke(t,n,e)})}t?r?r(e,t,{value:n,enumerable:!o,configurable:!o,writable:!o}):e[t]=n:(i("next",0),i("throw",1),i("return",2))},Zn(e,t,n,o)}function eo(e,t,n,o,r,i,a){try{var c=e[i](a),s=c.value}catch(e){return void n(e)}c.done?t(s):Promise.resolve(s).then(o,r)}function to(e){return function(){var t=this,n=arguments;return new Promise(function(o,r){var i=e.apply(t,n);function a(e){eo(i,o,r,a,c,"next",e)}function c(e){eo(i,o,r,a,c,"throw",e)}a(void 0)})}}function no(e,t){for(var n=0;n<t.length;n++){var o=t[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(e,oo(o.key),o)}}function oo(e){var t=function(e){if("object"!=$n(e)||!e)return e;var t=e[Symbol.toPrimitive];if(void 0!==t){var n=t.call(e,"string");if("object"!=$n(n))return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}(e);return"symbol"==$n(t)?t:t+""}var ro=function(){return e=function e(t,n){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),this.config=t,this.sdk=n,this.streamingEl=null,this.hasStartedStreaming=!1,this.isActive=!1,this.eventHandlers={autoResize:null,keydown:null},this.eventHandlersSetup=!1},t=[{key:"t",value:function(e){var t,n,o=this.config.language||"en";return((null===(t=this.config.translations)||void 0===t?void 0:t[o])||(null===(n=this.config.translations)||void 0===n?void 0:n.en)||{})[e]||e}},{key:"generateHTML",value:function(){var e,t,n,o,r,i,a,c,s,u=this.config.inputPlaceholder||(null===(e=this.config.panel)||void 0===e?void 0:e.inputPlaceholder)||this.t("typeMessage")||"Type your message...";return'<div class="text-interface" id="textInterface">\n <div class="messages-container" id="messagesContainer">\n <div class="empty-state">\n <div class="empty-state-icon">💬</div>\n <div class="empty-state-title">'.concat(this.t("hello"),'</div>\n <div class="empty-state-text">').concat(this.t("sendMessage"),'</div>\n </div>\n </div>\n <div class="input-container">\n <div class="input-wrapper" style="flex:1;">\n <textarea class="message-input" id="messageInput" placeholder="').concat(u,'" rows="1" dir="').concat(this.config.direction||"ltr",'"></textarea>\n </div>\n <button class="send-button" id="sendButton" aria-label="').concat(this.t("sendMessageAria"),'">').concat(this.config.sendButtonText||"➤","</button>\n ").concat(null!==(t=this.config.sendButtonHint)&&void 0!==t&&t.text||null!==(n=this.config.panel)&&void 0!==n&&null!==(n=n.sendButtonHint)&&void 0!==n&&n.text?'\n <div class="send-button-hint" style="color: '.concat((null===(o=this.config.sendButtonHint)||void 0===o?void 0:o.color)||(null===(r=this.config.panel)||void 0===r||null===(r=r.sendButtonHint)||void 0===r?void 0:r.color)||"#6B7280","; font-size: ").concat((null===(i=this.config.sendButtonHint)||void 0===i?void 0:i.fontSize)||(null===(a=this.config.panel)||void 0===a||null===(a=a.sendButtonHint)||void 0===a?void 0:a.fontSize)||"12px",'; text-align: center; margin-top: 4px;">\n ').concat((null===(c=this.config.sendButtonHint)||void 0===c?void 0:c.text)||(null===(s=this.config.panel)||void 0===s||null===(s=s.sendButtonHint)||void 0===s?void 0:s.text),"\n </div>\n "):"","\n </div>\n </div>")}},{key:"generateCSS",value:function(){var e,t,n,o,r,i,a,c,s,u,l,d,p,f=this.config.messages,h=(this.config.panel,this.config.animation,this.config.sendButtonColor||(null===(e=this.config.panel)||void 0===e?void 0:e.sendButtonColor)||"#7C3AED"),v=this.config.sendButtonHoverColor||(null===(t=this.config.panel)||void 0===t?void 0:t.sendButtonHoverColor)||"#6D28D9",g=this.config.sendButtonTextColor||(null===(n=this.config.panel)||void 0===n?void 0:n.sendButtonTextColor)||"#FFFFFF",y=(this.config.inputPlaceholder||null===(o=this.config.panel)||void 0===o||o.inputPlaceholder,this.config.inputBorderColor||(null===(r=this.config.panel)||void 0===r?void 0:r.inputBorderColor)||"#E5E7EB"),m=this.config.inputFocusColor||(null===(i=this.config.panel)||void 0===i?void 0:i.inputFocusColor)||"#7C3AED",b=this.config.inputBackgroundColor||(null===(a=this.config.panel)||void 0===a?void 0:a.inputBackgroundColor)||"#FFFFFF",S=this.config.inputTextColor||(null===(c=this.config.panel)||void 0===c?void 0:c.inputTextColor)||"#1F2937",w=this.config.inputFontSize||(null===(s=this.config.panel)||void 0===s?void 0:s.inputFontSize)||"14px",x=this.config.inputBorderRadius||(null===(u=this.config.panel)||void 0===u?void 0:u.inputBorderRadius)||20,C=this.config.inputPadding||(null===(l=this.config.panel)||void 0===l?void 0:l.inputPadding)||"6px 14px";return"\n /* Messages container using new classes */\n #messagesContainer { \n flex: 1; \n overflow-y: auto; \n overflow-x: hidden; \n padding: 20px; \n background: #f8fafc; \n display: flex; \n flex-direction: column; \n gap: 16px; \n min-height: 0; \n }\n .empty-state { \n flex: 1; \n display: flex; \n flex-direction: column; \n align-items: center; \n justify-content: center; \n gap: 12px; \n color: #64748b; \n text-align: center; \n padding: 20px; \n }\n .empty-state-icon { font-size: 48px; opacity: 0.3; }\n .empty-state-title { font-size: 20px; font-weight: 700; color: #334155; }\n .empty-state-text { font-size: 13px; max-width: 280px; }\n\n .text-interface { \n display: none; \n flex: 1; \n flex-direction: column; \n min-height: 0; \n overflow: hidden; \n }\n .text-interface.active { display: flex; }\n \n .message { \n display: flex; \n gap: 8px; \n padding: 4px 0; \n max-width: 100%; \n align-items: center; \n }\n .message.edge-left { flex-direction: row; }\n .message.edge-right { flex-direction: row-reverse; }\n .message-bubble { \n padding: 12px; \n border-radius: ".concat(f.borderRadius,"px; \n max-width: 80%; \n font-size: ").concat(f.fontSize,"; \n color: ").concat(f.textColor,"; \n word-wrap: break-word; \n text-align: ").concat("rtl"===this.config.direction?"right":"left","; \n direction: ").concat(this.config.direction||"ltr",";\n }\n .message.user { \n background: ").concat(f.userBackgroundColor,"; \n align-self: ").concat("rtl"===this.config.direction?"flex-start":"flex-end","; \n }\n .message.agent { \n background: ").concat(f.agentBackgroundColor,"; \n align-self: ").concat("rtl"===this.config.direction?"flex-end":"flex-start","; \n }\n .message .message-bubble { \n text-align: ").concat("rtl"===this.config.direction?"right":"left"," !important; \n }\n ").concat("rtl"===this.config.direction?"\n .message-bubble {\n text-align: right !important;\n }\n ":"","\n .message-avatar { \n width: 20px; \n height: 20px; \n display: flex; \n align-items: center; \n justify-content: center; \n flex-shrink: 0; \n color: inherit; \n font-size: 18px; \n line-height: 1; \n background: transparent; \n border: none; \n }\n .message-avatar.user { background: transparent; }\n .message-avatar.agent { background: transparent; }\n \n .message.system {\n background: ").concat(f.systemBackgroundColor,";\n align-self: flex-start;\n }\n .message.error {\n background: ").concat(f.errorBackgroundColor,";\n align-self: flex-start;\n }\n \n .input-container {\n display: flex;\n gap: 8px;\n padding: 12px 16px;\n background: #FFFFFF;\n border-top: 1px solid #E5E7EB;\n align-items: center;\n flex-shrink: 0;\n flex-direction: ").concat("rtl"===this.config.direction?"row-reverse":"row",";\n }\n \n .input-wrapper {\n position: relative;\n display: flex;\n align-items: center;\n }\n \n .message-input {\n width: 100%;\n min-height: 32px;\n max-height: 120px;\n padding: ").concat(C,";\n border: 1px solid ").concat(y,";\n border-radius: ").concat(x,"px;\n font-size: ").concat(w,";\n font-family: inherit;\n line-height: 1.3;\n resize: none;\n overflow-y: auto;\n background: ").concat(b,";\n color: ").concat(S,";\n vertical-align: top;\n margin: 0;\n display: block;\n white-space: pre-wrap;\n word-wrap: break-word;\n text-align: ").concat("rtl"===this.config.direction?"right":"left",";\n direction: ").concat(this.config.direction||"ltr",";\n -webkit-appearance: none;\n appearance: none;\n box-sizing: border-box;\n }\n \n .message-input:focus {\n outline: none;\n border-color: ").concat(m,";\n background: ").concat("#FFFFFF"===b?"#FFFFFF":b,";\n box-shadow: 0 0 0 3px ").concat(m,"33;\n }\n \n .message-input::placeholder {\n color: #9CA3AF;\n text-align: ").concat("rtl"===this.config.direction?"right":"left",";\n }\n \n .send-button {\n width: 40px;\n height: 40px;\n border-radius: 50%;\n border: none;\n background: ").concat(h,";\n color: ").concat(g,";\n font-size: ").concat(this.config.sendButtonFontSize||(null===(d=this.config.panel)||void 0===d?void 0:d.sendButtonFontSize)||"18px",";\n font-weight: ").concat(this.config.sendButtonFontWeight||(null===(p=this.config.panel)||void 0===p?void 0:p.sendButtonFontWeight)||"500",";\n cursor: pointer;\n display: flex;\n align-items: center;\n justify-content: center;\n flex-shrink: 0;\n transition: all 0.2s ease;\n box-shadow: 0 4px 12px rgba(124, 60, 237, 0.3);\n }\n \n .send-button:hover:not(:disabled) {\n background: ").concat(v,";\n transform: scale(1.05);\n box-shadow: 0 6px 16px rgba(124, 60, 237, 0.4);\n }\n \n .send-button-hint {\n width: 100%;\n text-align: center;\n margin-top: 4px;\n }\n \n .send-button:disabled {\n opacity: 0.5;\n cursor: not-allowed;\n }\n \n .typing-indicator {\n display: inline-flex;\n gap: 4px;\n align-items: center;\n }\n \n .typing-dot {\n width: 6px;\n height: 6px;\n border-radius: 50%;\n background: #64748b;\n animation: typingDot 1.4s ease-in-out infinite;\n }\n \n .typing-dot:nth-child(2) { animation-delay: 0.2s; }\n .typing-dot:nth-child(3) { animation-delay: 0.4s; }\n \n @keyframes typingDot {\n 0%, 60%, 100% { transform: translateY(0); opacity: 0.7; }\n 30% { transform: translateY(-8px); opacity: 1; }\n }\n \n .error-message {\n padding: 12px;\n background: ").concat(f.errorBackgroundColor,";\n border-radius: ").concat(f.borderRadius,"px;\n color: #991B1B;\n font-size: ").concat(f.fontSize,";\n margin: 8px 0;\n }\n \n @media (max-width: 768px) {\n #messagesContainer {\n padding: 12px;\n gap: 12px;\n }\n \n .message-bubble {\n max-width: 85%;\n font-size: 14px;\n padding: 10px;\n }\n \n .text-input-container {\n padding: 10px;\n gap: 8px;\n }\n \n #text-chat-input {\n font-size: 16px !important; /* Prevents iOS zoom on focus */\n padding: 10px 14px;\n min-height: 44px;\n }\n \n #text-chat-send {\n min-width: 56px;\n min-height: 44px;\n width: 56px;\n height: 44px;\n }\n \n .empty-state-icon {\n font-size: 40px;\n }\n \n .empty-state-title {\n font-size: 18px;\n }\n \n .empty-state-text {\n font-size: 12px;\n }\n }\n \n @media (max-width: 480px) {\n #messagesContainer {\n padding: 10px;\n gap: 10px;\n }\n \n .message-bubble {\n max-width: 90%;\n font-size: 13px;\n padding: 8px;\n }\n \n .text-input-container {\n padding: 8px;\n }\n \n #text-chat-input {\n font-size: 16px !important;\n padding: 8px 12px;\n }\n }\n ")}},{key:"setupEventHandlers",value:function(){var e=this,t=document.getElementById("sendButton"),n=document.getElementById("messageInput"),o=document.getElementById("newChatBtn");if(t&&(t.onclick=function(){return e.sendMessage()}),o&&(o.onclick=function(){return e.startNewChat()}),this.updateInputAttributes(),n){n.style.height="32px",n.style.overflow="hidden";var r=function(){n.style.height="auto";var e=Math.min(n.scrollHeight,120);n.style.height=e+"px",n.style.overflowY=e>=120?"auto":"hidden",e>=120&&setTimeout(function(){n.scrollTop=n.scrollHeight},0)};n.addEventListener("input",r),n.addEventListener("keydown",function(t){"Enter"!==t.key||t.shiftKey?"Enter"===t.key&&t.shiftKey&&setTimeout(r,0):(t.preventDefault(),e.sendMessage())})}}},{key:"startNewChat",value:function(){try{localStorage.removeItem("ttp_text_chat_conversation_id")}catch(e){}this.sdk&&(this.sdk.config.conversationId=null);var e=document.getElementById("messagesContainer");e&&(e.innerHTML='\n <div class="empty-state">\n <div class="empty-state-icon">💬</div>\n <div class="empty-state-title">'.concat(this.t("hello"),'</div>\n <div class="empty-state-text">').concat(this.t("sendMessage"),"</div>\n </div>"));var t=document.getElementById("messageInput");t&&t.focus()}},{key:"updateInputAttributes",value:function(){var e=document.getElementById("messageInput");if(e){var t,n=this.config.inputPlaceholder||(null===(t=this.config.panel)||void 0===t?void 0:t.inputPlaceholder)||this.t("typeMessage")||"Type your message...";e.placeholder=n,e.dir=this.config.direction||"ltr",e.style.textAlign="rtl"===this.config.direction?"right":"left"}}},{key:"show",value:function(){var e=document.getElementById("textInterface");e&&e.classList.add("active"),setTimeout(function(){var e=document.getElementById("messageInput");e&&e.focus()},50)}},{key:"hide",value:function(){var e=document.getElementById("textInterface");e&&e.classList.remove("active")}},{key:"startChat",value:(o=to(Xn().m(function e(){return Xn().w(function(e){for(;;)switch(e.n){case 0:this.isActive=!0,this.updateSendButtonState();case 1:return e.a(2)}},e,this)})),function(){return o.apply(this,arguments)})},{key:"sendMessage",value:(n=to(Xn().m(function e(){var t,n,o;return Xn().w(function(e){for(;;)switch(e.p=e.n){case 0:if(t=document.getElementById("messageInput"),n=t.value.trim()){e.n=1;break}return e.a(2);case 1:if(this.isActive){e.n=2;break}return e.n=2,this.startChat();case 2:return this.addMessage("user",n),t.value="",t.style.height="32px",t.style.overflow="hidden",e.p=3,this.beginStreaming(),e.n=4,this.sdk.sendMessage(n);case 4:e.n=6;break;case 5:e.p=5,o=e.v,console.error("❌ Failed to send message:",o),o&&("DOMAIN_NOT_WHITELISTED"===o.message||o.message&&o.message.includes("Domain not whitelisted"))||this.showError(o),this.stopStreamingState();case 6:return e.a(2)}},e,this,[[3,5]])})),function(){return n.apply(this,arguments)})},{key:"updateSendButtonState",value:function(){var e=document.getElementById("sendButton");e&&(e.disabled=!this.isActive)}},{key:"addMessage",value:function(e,t){var n=document.getElementById("messagesContainer");if(n){var o=n.querySelector(".empty-state");o&&o.remove();var r=document.createElement("div"),i="rtl"===this.config.direction?"user"===e?"edge-left":"edge-right":"user"===e?"edge-right":"edge-left";r.className="message ".concat(e," ").concat(i);var a=document.createElement("div");a.className="message-avatar ".concat(e),a.textContent="user"===e?"👤":"🤖";var c=document.createElement("div");c.className="message-bubble",c.textContent=t,r.appendChild(a),r.appendChild(c),n.appendChild(r),n.scrollTop=n.scrollHeight}}},{key:"beginStreaming",value:function(){var e=document.getElementById("messagesContainer");if(e){this.stopStreamingState();var t=document.createElement("div"),n="rtl"===this.config.direction?"edge-right":"edge-left";t.className="message agent ".concat(n),t.id="agent-streaming";var o=document.createElement("div");o.className="message-avatar agent",o.textContent="🤖";var r=document.createElement("div");r.className="message-bubble",r.innerHTML='<span class="typing-indicator"><span class="typing-dot"></span><span class="typing-dot"></span><span class="typing-dot"></span></span>',t.appendChild(o),t.appendChild(r),e.appendChild(t),this.streamingEl=r,this.hasStartedStreaming=!1,e.scrollTop=e.scrollHeight}}},{key:"appendStreamingChunk",value:function(e){if(this.streamingEl){this.hasStartedStreaming||(this.streamingEl.textContent="",this.hasStartedStreaming=!0),this.streamingEl.textContent+=e;var t=document.getElementById("messagesContainer");t&&(t.scrollTop=t.scrollHeight)}}},{key:"finalizeStreaming",value:function(e){if(this.streamingEl){this.streamingEl.textContent=e||this.streamingEl.textContent;var t=document.getElementById("agent-streaming");t&&(t.id=""),this.streamingEl=null}this.updateSendButtonState()}},{key:"stopStreamingState",value:function(){var e=document.getElementById("agent-streaming");e&&e.remove(),this.streamingEl=null,this.hasStartedStreaming=!1}},{key:"showError",value:function(e){var t=document.getElementById("messagesContainer");if(t){if(e&&("DOMAIN_NOT_WHITELISTED"===e.message||"string"==typeof e&&e.includes("DOMAIN_NOT_WHITELISTED")||e.message&&e.message.includes("Domain not whitelisted")||"string"==typeof e&&e.includes("Domain not whitelisted"))){var n,o=document.createElement("div");o.className="error-message",o.style.cssText="padding: 16px; margin: 12px; border-radius: 8px; background: "+((null===(n=this.config.messages)||void 0===n?void 0:n.errorBackgroundColor)||"#FEE2E2")+";";var r=document.createElement("div");r.style.cssText="font-weight: 600; font-size: 16px; margin-bottom: 8px; color: #991B1B;",r.textContent=this.t("domainNotValidated");var i=document.createElement("div");i.style.cssText="font-size: 14px; color: #991B1B; line-height: 1.5;",i.textContent=this.t("domainErrorMessage"),o.appendChild(r),o.appendChild(i),t.appendChild(o)}else{var a=document.createElement("div");a.className="error-message",a.textContent="string"==typeof e?e:(null==e?void 0:e.message)||e,t.appendChild(a)}t.scrollTop=t.scrollHeight}}},{key:"setActive",value:function(e){this.isActive=e,this.updateSendButtonState()}}],t&&no(e.prototype,t),Object.defineProperty(e,"prototype",{writable:!1}),e;var e,t,n,o}();const io={en:{landingTitle:"How would you like to communicate?",voiceCall:"Voice Call",textChat:"Text Chat",clickToStartCall:"Click to Start Call",realTimeVoice:"Real-time voice conversation",startCall:"Start Call",listening:"Listening...",speakFreely:"Speak freely",liveTranscript:"Live Transcript",transcriptWillAppear:"Transcript will appear here during the call...",mute:"Mute",speaker:"Speaker",endCall:"End Call",hello:"Hello! How can I help?",sendMessage:"Send a message to get started",online:"Online",newChat:"New Chat",back:"Back",close:"Close",error:"Error",typeMessage:"Type your message...",sendMessageAria:"Send message",domainNotValidated:"Domain not validated",domainErrorMessage:"This domain is not whitelisted. Please contact the administrator to whitelist your website URL."},he:{landingTitle:"איך תרצה לתקשר?",voiceCall:"שיחה קולית",textChat:"צ'אט טקסט",clickToStartCall:"לחץ להתחלת שיחה",realTimeVoice:"שיחה קולית בזמן אמת",startCall:"התחל שיחה",listening:"מקשיב...",speakFreely:"דבר בחופשיות",liveTranscript:"תמלול בזמן אמת",transcriptWillAppear:"התמלול יופיע כאן במהלך השיחה...",mute:"השתק",speaker:"רמקול",endCall:"סיים שיחה",hello:"שלום! איך אפשר לעזור?",sendMessage:"שלח הודעה או עבור למצב קולי לשיחה בזמן אמת",online:"מקוון",newChat:"צ'אט חדש",back:"חזור",close:"סגור",error:"שגיאה",typeMessage:"הקלד הודעה...",sendMessageAria:"שלח הודעה",domainNotValidated:"דומיין לא מאומת",domainErrorMessage:"דומיין זה לא ברשימת המורשים. אנא פנה למנהל המערכת כדי להוסיף את כתובת האתר שלך לרשימה."},ar:{landingTitle:"كيف تريد التواصل؟",voiceCall:"مكالمة صوتية",textChat:"دردشة نصية",clickToStartCall:"انقر لبدء المكالمة",realTimeVoice:"محادثة صوتية في الوقت الفعلي",startCall:"ابدأ المكالمة",listening:"الاستماع...",speakFreely:"تكلم بحرية",liveTranscript:"نص مباشر",transcriptWillAppear:"سيظهر النص هنا أثناء المكالمة...",mute:"كتم الصوت",speaker:"مكبر الصوت",endCall:"إنهاء المكالمة",hello:"مرحبا! كيف يمكنني المساعدة؟",sendMessage:"أرسل رسالة للبدء",online:"متصل",newChat:"محادثة جديدة",back:"رجوع",close:"إغلاق",error:"خطأ",typeMessage:"اكتب رسالة...",sendMessageAria:"إرسال رسالة",domainNotValidated:"النطاق غير معتمد",domainErrorMessage:"هذا النطاق غير مسموح به. يرجى الاتصال بالمسؤول لإضافة عنوان موقع الويب الخاص بك إلى القائمة."},ru:{landingTitle:"Как вы хотите общаться?",voiceCall:"Голосовой звонок",textChat:"Текстовый чат",clickToStartCall:"Нажмите, чтобы начать звонок",realTimeVoice:"Голосовой разговор в реальном времени",startCall:"Начать звонок",listening:"Слушаю...",speakFreely:"Говорите свободно",liveTranscript:"Живая транскрипция",transcriptWillAppear:"Транскрипция появится здесь во время звонка...",mute:"Отключить звук",speaker:"Динамик",endCall:"Завершить звонок",hello:"Привет! Как я могу помочь?",sendMessage:"Отправьте сообщение для начала",online:"В сети",newChat:"Новый чат",back:"Назад",close:"Закрыть",error:"Ошибка",typeMessage:"Введите сообщение...",sendMessageAria:"Отправить сообщение",domainNotValidated:"Домен не проверен",domainErrorMessage:"Этот домен не в белом списке. Пожалуйста, свяжитесь с администратором, чтобы добавить URL вашего веб-сайта в список."},es:{landingTitle:"¿Cómo te gustaría comunicarte?",voiceCall:"Llamada de voz",textChat:"Chat de texto",clickToStartCall:"Haz clic para iniciar la llamada",realTimeVoice:"Conversación de voz en tiempo real",startCall:"Iniciar llamada",listening:"Escuchando...",speakFreely:"Habla libremente",liveTranscript:"Transcripción en vivo",transcriptWillAppear:"La transcripción aparecerá aquí durante la llamada...",mute:"Silenciar",speaker:"Altavoz",endCall:"Terminar llamada",hello:"¡Hola! ¿Cómo puedo ayudarte?",sendMessage:"Envía un mensaje para comenzar",online:"En línea",newChat:"Nuevo chat",back:"Atrás",close:"Cerrar",error:"Error",typeMessage:"Escribe un mensaje...",sendMessageAria:"Enviar mensaje",domainNotValidated:"Dominio no validado",domainErrorMessage:"Este dominio no está en la lista blanca. Por favor, contacte al administrador para agregar la URL de su sitio web a la lista."},fr:{landingTitle:"Comment souhaitez-vous communiquer?",voiceCall:"Appel vocal",textChat:"Chat texte",clickToStartCall:"Cliquez pour démarrer l'appel",realTimeVoice:"Conversation vocale en temps réel",startCall:"Démarrer l'appel",listening:"Écoute...",speakFreely:"Parlez librement",liveTranscript:"Transcripción en direct",transcriptWillAppear:"La transcription apparaîtra ici pendant l'appel...",mute:"Muet",speaker:"Haut-parleur",endCall:"Terminer l'appel",hello:"Bonjour! Comment puis-je vous aider?",sendMessage:"Envoyez un message pour commencer",online:"En ligne",newChat:"Nouveau chat",back:"Retour",close:"Fermer",error:"Erreur",typeMessage:"Tapez votre message...",sendMessageAria:"Envoyer un message",domainNotValidated:"Domaine non validé",domainErrorMessage:"Ce domaine n'est pas sur la liste blanche. Veuillez contacter l'administrateur pour ajouter l'URL de votre site Web à la liste."},de:{landingTitle:"Wie möchten Sie kommunizieren?",voiceCall:"Sprachanruf",textChat:"Text-Chat",clickToStartCall:"Klicken Sie, um den Anruf zu starten",realTimeVoice:"Sprachanruf in Echtzeit",startCall:"Anruf starten",listening:"Hören...",speakFreely:"Sprechen Sie frei",liveTranscript:"Live-Transkription",transcriptWillAppear:"Die Transkription erscheint hier während des Anrufs...",mute:"Stumm",speaker:"Lautsprecher",endCall:"Anruf beenden",hello:"Hallo! Wie kann ich helfen?",sendMessage:"Senden Sie eine Nachricht zum Starten",online:"Online",newChat:"Neuer Chat",back:"Zurück",close:"Schließen",error:"Fehler",typeMessage:"Geben Sie eine Nachricht ein...",sendMessageAria:"Nachricht senden",domainNotValidated:"Domain nicht validiert",domainErrorMessage:"Diese Domain steht nicht auf der Whitelist. Bitte kontaktieren Sie den Administrator, um die URL Ihrer Website zur Liste hinzuzufügen."}};function ao(){var e,t,n="function"==typeof Symbol?Symbol:{},o=n.iterator||"@@iterator",r=n.toStringTag||"@@toStringTag";function i(n,o,r,i){var s=o&&o.prototype instanceof c?o:c,u=Object.create(s.prototype);return co(u,"_invoke",function(n,o,r){var i,c,s,u=0,l=r||[],d=!1,p={p:0,n:0,v:e,a:f,f:f.bind(e,4),d:function(t,n){return i=t,c=0,s=e,p.n=n,a}};function f(n,o){for(c=n,s=o,t=0;!d&&u&&!r&&t<l.length;t++){var r,i=l[t],f=p.p,h=i[2];n>3?(r=h===o)&&(s=i[(c=i[4])?5:(c=3,3)],i[4]=i[5]=e):i[0]<=f&&((r=n<2&&f<i[1])?(c=0,p.v=o,p.n=i[1]):f<h&&(r=n<3||i[0]>o||o>h)&&(i[4]=n,i[5]=o,p.n=h,c=0))}if(r||n>1)return a;throw d=!0,o}return function(r,l,h){if(u>1)throw TypeError("Generator is already running");for(d&&1===l&&f(l,h),c=l,s=h;(t=c<2?e:s)||!d;){i||(c?c<3?(c>1&&(p.n=-1),f(c,s)):p.n=s:p.v=s);try{if(u=2,i){if(c||(r="next"),t=i[r]){if(!(t=t.call(i,s)))throw TypeError("iterator result is not an object");if(!t.done)return t;s=t.value,c<2&&(c=0)}else 1===c&&(t=i.return)&&t.call(i),c<2&&(s=TypeError("The iterator does not provide a '"+r+"' method"),c=1);i=e}else if((t=(d=p.n<0)?s:n.call(o,p))!==a)break}catch(t){i=e,c=1,s=t}finally{u=1}}return{value:t,done:d}}}(n,r,i),!0),u}var a={};function c(){}function s(){}function u(){}t=Object.getPrototypeOf;var l=[][o]?t(t([][o]())):(co(t={},o,function(){return this}),t),d=u.prototype=c.prototype=Object.create(l);function p(e){return Object.setPrototypeOf?Object.setPrototypeOf(e,u):(e.__proto__=u,co(e,r,"GeneratorFunction")),e.prototype=Object.create(d),e}return s.prototype=u,co(d,"constructor",u),co(u,"constructor",s),s.displayName="GeneratorFunction",co(u,r,"GeneratorFunction"),co(d),co(d,r,"Generator"),co(d,o,function(){return this}),co(d,"toString",function(){return"[object Generator]"}),(ao=function(){return{w:i,m:p}})()}function co(e,t,n,o){var r=Object.defineProperty;try{r({},"",{})}catch(e){r=0}co=function(e,t,n,o){function i(t,n){co(e,t,function(e){return this._invoke(t,n,e)})}t?r?r(e,t,{value:n,enumerable:!o,configurable:!o,writable:!o}):e[t]=n:(i("next",0),i("throw",1),i("return",2))},co(e,t,n,o)}function so(e,t,n,o,r,i,a){try{var c=e[i](a),s=c.value}catch(e){return void n(e)}c.done?t(s):Promise.resolve(s).then(o,r)}function uo(e){return function(){var t=this,n=arguments;return new Promise(function(o,r){var i=e.apply(t,n);function a(e){so(i,o,r,a,c,"next",e)}function c(e){so(i,o,r,a,c,"throw",e)}a(void 0)})}}function lo(e){return lo="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},lo(e)}function po(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(e);t&&(o=o.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,o)}return n}function fo(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?po(Object(n),!0).forEach(function(t){ho(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):po(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}function ho(e,t,n){return(t=go(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function vo(e,t){for(var n=0;n<t.length;n++){var o=t[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(e,go(o.key),o)}}function go(e){var t=function(e){if("object"!=lo(e)||!e)return e;var t=e[Symbol.toPrimitive];if(void 0!==t){var n=t.call(e,"string");if("object"!=lo(n))return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}(e);return"symbol"==lo(t)?t:t+""}var yo=function(){return e=function e(){var t,n,o,r,i,a,c,s=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),this.config=this.mergeWithDefaults(s),this.sdk=new pn(this.config),this.isOpen=!1,this.isActive=!1,this.translations=io,this.currentView="landing";var u=fo(fo(fo({},this.config),this.config.voice),{},{language:(null===(t=this.config.voice)||void 0===t?void 0:t.language)||this.config.language||"en",websocketUrl:(null===(n=this.config.voice)||void 0===n?void 0:n.websocketUrl)||this.config.websocketUrl||"wss://speech.talktopc.com/ws/conv",translations:this.translations,outputContainer:(null===(o=this.config.voice)||void 0===o?void 0:o.outputContainer)||"raw",outputEncoding:(null===(r=this.config.voice)||void 0===r?void 0:r.outputEncoding)||"pcm",outputSampleRate:(null===(i=this.config.voice)||void 0===i?void 0:i.outputSampleRate)||44100,outputChannels:(null===(a=this.config.voice)||void 0===a?void 0:a.outputChannels)||1,outputBitDepth:(null===(c=this.config.voice)||void 0===c?void 0:c.outputBitDepth)||16,onConversationStart:this.config.onConversationStart,onConversationEnd:this.config.onConversationEnd,onBargeIn:this.config.onBargeIn,onAudioStartPlaying:this.config.onAudioStartPlaying,onAudioStoppedPlaying:this.config.onAudioStoppedPlaying,onSubtitleDisplay:this.config.onSubtitleDisplay});this.voiceInterface=new Yn(u);var l=fo(fo(fo({},this.config),this.config.text),{},{translations:this.translations});if(this.textInterface=new ro(l,this.sdk),this.setupEventHandlers(),this.createWidget(),this.config.behavior.startOpen||this.config.behavior.autoOpen){var d=document.getElementById("text-chat-panel");d&&(this.isOpen=!0,d.classList.add("open"))}},t=[{key:"mergeWithDefaults",value:function(e){var t,n,o,r,i,a,c,s,u,l,d,p,f,h,v,g,y,m,b,S,w,x,C,k,P,O,E,T,A,I,j,D,F,B,R,_,U,M,N,V,K,L,z,H,W,G,q,Q,J,Y,$,X,Z,ee,te,ne,oe,re,ie,ae,ce,se,ue,le,de,pe,fe,he,ve,ge,ye,me,be,Se,we,xe,Ce,ke,Pe,Oe,Ee,Te,Ae,Ie,je,De,Fe,Be,Re,_e,Ue,Me,Ne,Ve,Ke,Le,ze,He,We,Ge,qe,Qe,Je,Ye,$e,Xe,Ze,et,tt,nt,ot,rt,it,at,ct,st,ut,lt,dt,pt,ft,ht,vt,gt,yt,mt,bt,St,wt,xt,Ct,kt,Pt,Ot,Et=e.position||"bottom-right";if("string"==typeof Et){var Tt=Et.split("-");Et={vertical:Tt[0]||"bottom",horizontal:Tt[1]||"right",offset:e.positionOffset||{x:20,y:20}}}var At=e.primaryColor||(null===(t=e.button)||void 0===t?void 0:t.primaryColor)||(null===(n=e.button)||void 0===n?void 0:n.backgroundColor)||"#7C3AED",It=(null===(o=e.header)||void 0===o?void 0:o.backgroundColor)||(null===(r=e.button)||void 0===r?void 0:r.backgroundColor)||At;return fo({agentId:e.agentId,appId:e.appId,getSessionUrl:e.getSessionUrl,websocketUrl:e.websocketUrl,demo:!1!==e.demo,direction:e.direction||"ltr",language:e.language||"en",icon:fo({type:(null===(i=e.icon)||void 0===i?void 0:i.type)||"custom",customImage:(null===(a=e.icon)||void 0===a?void 0:a.customImage)||"https://talktopc.com/logo192.png",emoji:(null===(c=e.icon)||void 0===c?void 0:c.emoji)||"🎤",text:(null===(s=e.icon)||void 0===s?void 0:s.text)||"AI",size:(null===(u=e.icon)||void 0===u?void 0:u.size)||"medium",backgroundColor:(null===(l=e.icon)||void 0===l?void 0:l.backgroundColor)||"#FFFFFF"},e.icon),position:fo({vertical:Et.vertical||"bottom",horizontal:Et.horizontal||"right",offset:Et.offset||{x:20,y:20}},"object"===lo(e.position)?e.position:{}),button:fo({size:(null===(d=e.button)||void 0===d?void 0:d.size)||"medium",shape:(null===(p=e.button)||void 0===p?void 0:p.shape)||"circle",backgroundColor:(null===(f=e.button)||void 0===f?void 0:f.backgroundColor)||(null===(h=e.icon)||void 0===h?void 0:h.backgroundColor)||At,hoverColor:(null===(v=e.button)||void 0===v?void 0:v.hoverColor)||"#7C3AED",shadow:!1!==(null===(g=e.button)||void 0===g?void 0:g.shadow),shadowColor:(null===(y=e.button)||void 0===y?void 0:y.shadowColor)||"rgba(0,0,0,0.15)",primaryColor:(null===(m=e.button)||void 0===m?void 0:m.backgroundColor)||(null===(b=e.icon)||void 0===b?void 0:b.backgroundColor)||At},e.button),panel:fo({width:(null===(S=e.panel)||void 0===S?void 0:S.width)||350,height:(null===(w=e.panel)||void 0===w?void 0:w.height)||500,borderRadius:(null===(x=e.panel)||void 0===x?void 0:x.borderRadius)||12,backgroundColor:(null===(C=e.panel)||void 0===C?void 0:C.backgroundColor)||"#FFFFFF",backdropFilter:(null===(k=e.panel)||void 0===k?void 0:k.backdropFilter)||null,border:(null===(P=e.panel)||void 0===P?void 0:P.border)||"1px solid rgba(0,0,0,0.1)"},e.panel),voice:fo({micButtonColor:(null===(O=e.voice)||void 0===O?void 0:O.micButtonColor)||(null===(E=e.panel)||void 0===E?void 0:E.micButtonColor)||At,micButtonActiveColor:(null===(T=e.voice)||void 0===T?void 0:T.micButtonActiveColor)||(null===(A=e.panel)||void 0===A?void 0:A.micButtonActiveColor)||"#EF4444",micButtonHint:fo(fo({text:(null===(I=e.voice)||void 0===I||null===(I=I.micButtonHint)||void 0===I?void 0:I.text)||(null===(j=e.panel)||void 0===j||null===(j=j.micButtonHint)||void 0===j?void 0:j.text)||"Click the button to start voice conversation",color:(null===(D=e.voice)||void 0===D||null===(D=D.micButtonHint)||void 0===D?void 0:D.color)||(null===(F=e.panel)||void 0===F||null===(F=F.micButtonHint)||void 0===F?void 0:F.color)||"#6B7280",fontSize:(null===(B=e.voice)||void 0===B||null===(B=B.micButtonHint)||void 0===B?void 0:B.fontSize)||(null===(R=e.panel)||void 0===R||null===(R=R.micButtonHint)||void 0===R?void 0:R.fontSize)||"12px"},null===(_=e.voice)||void 0===_?void 0:_.micButtonHint),null===(U=e.panel)||void 0===U?void 0:U.micButtonHint),avatarBackgroundColor:(null===(M=e.voice)||void 0===M?void 0:M.avatarBackgroundColor)||"#667eea",avatarActiveBackgroundColor:(null===(N=e.voice)||void 0===N?void 0:N.avatarActiveBackgroundColor)||"#667eea",statusTitleColor:(null===(V=e.voice)||void 0===V?void 0:V.statusTitleColor)||"#1e293b",statusSubtitleColor:(null===(K=e.voice)||void 0===K?void 0:K.statusSubtitleColor)||"#64748b",startCallButtonColor:(null===(L=e.voice)||void 0===L?void 0:L.startCallButtonColor)||"#667eea",startCallButtonTextColor:(null===(z=e.voice)||void 0===z?void 0:z.startCallButtonTextColor)||"#FFFFFF",transcriptBackgroundColor:(null===(H=e.voice)||void 0===H?void 0:H.transcriptBackgroundColor)||"#FFFFFF",transcriptTextColor:(null===(W=e.voice)||void 0===W?void 0:W.transcriptTextColor)||"#1e293b",transcriptLabelColor:(null===(G=e.voice)||void 0===G?void 0:G.transcriptLabelColor)||"#94a3b8",controlButtonColor:(null===(q=e.voice)||void 0===q?void 0:q.controlButtonColor)||"#FFFFFF",controlButtonSecondaryColor:(null===(Q=e.voice)||void 0===Q?void 0:Q.controlButtonSecondaryColor)||"#64748b",endCallButtonColor:(null===(J=e.voice)||void 0===J?void 0:J.endCallButtonColor)||"#ef4444",language:(null===(Y=e.voice)||void 0===Y?void 0:Y.language)||e.language||"en",websocketUrl:(null===($=e.voice)||void 0===$?void 0:$.websocketUrl)||e.websocketUrl},e.voice),text:fo({sendButtonColor:(null===(X=e.text)||void 0===X?void 0:X.sendButtonColor)||(null===(Z=e.panel)||void 0===Z?void 0:Z.sendButtonColor)||"#7C3AED",sendButtonHoverColor:(null===(ee=e.text)||void 0===ee?void 0:ee.sendButtonHoverColor)||(null===(te=e.panel)||void 0===te?void 0:te.sendButtonHoverColor)||"#6D28D9",sendButtonActiveColor:(null===(ne=e.text)||void 0===ne?void 0:ne.sendButtonActiveColor)||(null===(oe=e.panel)||void 0===oe?void 0:oe.sendButtonActiveColor)||"#6D28D9",sendButtonText:(null===(re=e.text)||void 0===re?void 0:re.sendButtonText)||(null===(ie=e.panel)||void 0===ie?void 0:ie.sendButtonText)||"➤",sendButtonTextColor:(null===(ae=e.text)||void 0===ae?void 0:ae.sendButtonTextColor)||(null===(ce=e.panel)||void 0===ce?void 0:ce.sendButtonTextColor)||"#FFFFFF",sendButtonFontSize:(null===(se=e.text)||void 0===se?void 0:se.sendButtonFontSize)||(null===(ue=e.panel)||void 0===ue?void 0:ue.sendButtonFontSize)||"18px",sendButtonFontWeight:(null===(le=e.text)||void 0===le?void 0:le.sendButtonFontWeight)||(null===(de=e.panel)||void 0===de?void 0:de.sendButtonFontWeight)||"500",sendButtonHint:fo(fo({text:(null===(pe=e.text)||void 0===pe||null===(pe=pe.sendButtonHint)||void 0===pe?void 0:pe.text)||(null===(fe=e.panel)||void 0===fe||null===(fe=fe.sendButtonHint)||void 0===fe?void 0:fe.text)||"",color:(null===(he=e.text)||void 0===he||null===(he=he.sendButtonHint)||void 0===he?void 0:he.color)||(null===(ve=e.panel)||void 0===ve||null===(ve=ve.sendButtonHint)||void 0===ve?void 0:ve.color)||"#6B7280",fontSize:(null===(ge=e.text)||void 0===ge||null===(ge=ge.sendButtonHint)||void 0===ge?void 0:ge.fontSize)||(null===(ye=e.panel)||void 0===ye||null===(ye=ye.sendButtonHint)||void 0===ye?void 0:ye.fontSize)||"12px"},null===(me=e.text)||void 0===me?void 0:me.sendButtonHint),null===(be=e.panel)||void 0===be?void 0:be.sendButtonHint),inputPlaceholder:(null===(Se=e.text)||void 0===Se?void 0:Se.inputPlaceholder)||(null===(we=e.panel)||void 0===we?void 0:we.inputPlaceholder)||"Type your message...",inputBorderColor:(null===(xe=e.text)||void 0===xe?void 0:xe.inputBorderColor)||(null===(Ce=e.panel)||void 0===Ce?void 0:Ce.inputBorderColor)||"#E5E7EB",inputFocusColor:(null===(ke=e.text)||void 0===ke?void 0:ke.inputFocusColor)||(null===(Pe=e.panel)||void 0===Pe?void 0:Pe.inputFocusColor)||"#7C3AED",inputBackgroundColor:(null===(Oe=e.text)||void 0===Oe?void 0:Oe.inputBackgroundColor)||(null===(Ee=e.panel)||void 0===Ee?void 0:Ee.inputBackgroundColor)||"#FFFFFF",inputTextColor:(null===(Te=e.text)||void 0===Te?void 0:Te.inputTextColor)||(null===(Ae=e.panel)||void 0===Ae?void 0:Ae.inputTextColor)||"#1F2937",inputFontSize:(null===(Ie=e.text)||void 0===Ie?void 0:Ie.inputFontSize)||(null===(je=e.panel)||void 0===je?void 0:je.inputFontSize)||"14px",inputBorderRadius:(null===(De=e.text)||void 0===De?void 0:De.inputBorderRadius)||(null===(Fe=e.panel)||void 0===Fe?void 0:Fe.inputBorderRadius)||20,inputPadding:(null===(Be=e.text)||void 0===Be?void 0:Be.inputPadding)||(null===(Re=e.panel)||void 0===Re?void 0:Re.inputPadding)||"6px 14px"},e.text),landing:fo({backgroundColor:(null===(_e=e.landing)||void 0===_e?void 0:_e.backgroundColor)||"linear-gradient(180deg, #f8fafc 0%, #e0e7ff 100%)",logo:(null===(Ue=e.landing)||void 0===Ue?void 0:Ue.logo)||"🤖",title:(null===(Me=e.landing)||void 0===Me?void 0:Me.title)||null,titleColor:(null===(Ne=e.landing)||void 0===Ne?void 0:Ne.titleColor)||"#1e293b",modeCardBackgroundColor:(null===(Ve=e.landing)||void 0===Ve?void 0:Ve.modeCardBackgroundColor)||"#FFFFFF",modeCardBorderColor:(null===(Ke=e.landing)||void 0===Ke?void 0:Ke.modeCardBorderColor)||"#E2E8F0",modeCardHoverBorderColor:(null===(Le=e.landing)||void 0===Le?void 0:Le.modeCardHoverBorderColor)||It,modeCardIconBackgroundColor:(null===(ze=e.landing)||void 0===ze?void 0:ze.modeCardIconBackgroundColor)||It,modeCardTitleColor:(null===(He=e.landing)||void 0===He?void 0:He.modeCardTitleColor)||"#111827",voiceCardIcon:(null===(We=e.landing)||void 0===We?void 0:We.voiceCardIcon)||"🎤",textCardIcon:(null===(Ge=e.landing)||void 0===Ge?void 0:Ge.textCardIcon)||"💬"},e.landing),header:fo({title:(null===(qe=e.header)||void 0===qe?void 0:qe.title)||"Chat Assistant",showTitle:!1!==(null===(Qe=e.header)||void 0===Qe?void 0:Qe.showTitle),backgroundColor:(null===(Je=e.header)||void 0===Je?void 0:Je.backgroundColor)||(null===(Ye=e.button)||void 0===Ye?void 0:Ye.backgroundColor)||"#7C3AED",textColor:(null===($e=e.header)||void 0===$e?void 0:$e.textColor)||"#FFFFFF",showCloseButton:!1!==(null===(Xe=e.header)||void 0===Xe?void 0:Xe.showCloseButton)},e.header),tooltips:fo({newChat:(null===(Ze=e.tooltips)||void 0===Ze?void 0:Ze.newChat)||null,back:(null===(et=e.tooltips)||void 0===et?void 0:et.back)||null,close:(null===(tt=e.tooltips)||void 0===tt?void 0:tt.close)||null,mute:(null===(nt=e.tooltips)||void 0===nt?void 0:nt.mute)||null,speaker:(null===(ot=e.tooltips)||void 0===ot?void 0:ot.speaker)||null,endCall:(null===(rt=e.tooltips)||void 0===rt?void 0:rt.endCall)||null},e.tooltips),messages:fo({userBackgroundColor:(null===(it=e.messages)||void 0===it?void 0:it.userBackgroundColor)||"#E5E7EB",agentBackgroundColor:(null===(at=e.messages)||void 0===at?void 0:at.agentBackgroundColor)||"#F3F4F6",systemBackgroundColor:(null===(ct=e.messages)||void 0===ct?void 0:ct.systemBackgroundColor)||"#DCFCE7",errorBackgroundColor:(null===(st=e.messages)||void 0===st?void 0:st.errorBackgroundColor)||"#FEE2E2",textColor:(null===(ut=e.messages)||void 0===ut?void 0:ut.textColor)||"#1F2937",fontSize:(null===(lt=e.messages)||void 0===lt?void 0:lt.fontSize)||"14px",borderRadius:(null===(dt=e.messages)||void 0===dt?void 0:dt.borderRadius)||8},e.messages),animation:fo({enableHover:!1!==(null===(pt=e.animation)||void 0===pt?void 0:pt.enableHover),enablePulse:!1!==(null===(ft=e.animation)||void 0===ft?void 0:ft.enablePulse),enableSlide:!1!==(null===(ht=e.animation)||void 0===ht?void 0:ht.enableSlide),duration:(null===(vt=e.animation)||void 0===vt?void 0:vt.duration)||.3},e.animation),behavior:fo({autoOpen:(null===(gt=e.behavior)||void 0===gt?void 0:gt.autoOpen)||!1,startOpen:(null===(yt=e.behavior)||void 0===yt?void 0:yt.startOpen)||!1,hidden:(null===(mt=e.behavior)||void 0===mt?void 0:mt.hidden)||!1,autoConnect:(null===(bt=e.behavior)||void 0===bt?void 0:bt.autoConnect)||!1,showWelcomeMessage:!1!==(null===(St=e.behavior)||void 0===St?void 0:St.showWelcomeMessage),welcomeMessage:(null===(wt=e.behavior)||void 0===wt?void 0:wt.welcomeMessage)||"Hello! How can I help you today?",enableVoiceMode:void 0===(null===(xt=e.behavior)||void 0===xt?void 0:xt.enableVoiceMode)||e.behavior.enableVoiceMode,mode:(null===(Ct=e.behavior)||void 0===Ct?void 0:Ct.mode)||"unified"},e.behavior),accessibility:fo({ariaLabel:(null===(kt=e.accessibility)||void 0===kt?void 0:kt.ariaLabel)||"Chat Assistant",ariaDescription:(null===(Pt=e.accessibility)||void 0===Pt?void 0:Pt.ariaDescription)||"Click to open chat assistant",keyboardNavigation:!1!==(null===(Ot=e.accessibility)||void 0===Ot?void 0:Ot.keyboardNavigation)},e.accessibility),customStyles:e.customStyles||"",variables:e.variables||{},forceConversationId:e.forceConversationId,onConversationStart:e.onConversationStart,onConversationEnd:e.onConversationEnd,onBargeIn:e.onBargeIn,onAudioStartPlaying:e.onAudioStartPlaying,onAudioStoppedPlaying:e.onAudioStoppedPlaying,onSubtitleDisplay:e.onSubtitleDisplay,primaryColor:At},"string"==typeof e.position?{positionString:e.position}:{})}},{key:"setupEventHandlers",value:function(){var e=this;this.sdk.on("domainError",function(t){e.textInterface.showError(t),e.textInterface.stopStreamingState()}),this.sdk.on("error",function(t){t&&("DOMAIN_NOT_WHITELISTED"===t.message||t.message&&t.message.includes("Domain not whitelisted"))||(e.textInterface.showError(t.message||t),e.textInterface.stopStreamingState())}),this.sdk.on("chunk",function(t){e.textInterface.appendStreamingChunk(t)}),this.sdk.on("done",function(t){var n=t.text;e.textInterface.finalizeStreaming(n)})}},{key:"createWidget",value:function(){var e=document.getElementById("text-chat-widget");e&&e.remove();var t=document.createElement("div");if(t.id="text-chat-widget",t.innerHTML=this.generateWidgetHTML(),document.body.appendChild(t),this.setupWidgetEvents(),this.config.behavior.startOpen||this.config.behavior.autoOpen){var n=document.getElementById("text-chat-panel");n&&(this.isOpen=!0,n.classList.add("open"))}}},{key:"generateWidgetHTML",value:function(){var e=this,t=(this.config.position,this.config.button),n=this.config.icon,o=(this.config.panel,this.config.header),r=(this.config.animation,{small:50,medium:60,large:70,xl:80}[t.size]||60),i={small:20,medium:28,large:36,xl:44}[n.size]||28,a=this.generatePositionStyles(),c=this.generateIconHTML(i),s=this.config.behavior.mode||"unified",u="unified"===s,l="unified"===s||"voice-only"===s,d="unified"===s||"text-only"===s,p=function(t){var n=e.config.language||"en";return(e.translations[n]||e.translations.en)[t]||t},f=function(t){var n,o=null===(n=e.config.tooltips)||void 0===n?void 0:n[t];return null!=o?o:{newChat:p("newChat"),back:p("back"),close:p("close"),mute:p("mute"),speaker:p("speaker"),endCall:p("endCall")}[t]||""};return"\n <style>\n ".concat(this.generateCSS(a,r,i),"\n ").concat(this.config.customStyles,"\n </style>\n \n ").concat(this.config.behavior.hidden?"":'\n <button id="text-chat-button" \n aria-label="'.concat(this.config.accessibility.ariaLabel,'"\n aria-description="').concat(this.config.accessibility.ariaDescription,'">\n ').concat(c,"\n </button>\n "),'\n \n <div id="text-chat-panel">\n <div class="widget-shell">\n <div class="panel-inner widget-container" style="direction: ').concat(this.config.direction,';">\n <div class="widget-header" style="background: ').concat(o.backgroundColor,"; color: ").concat(o.textColor,';">\n <div>\n ').concat(o.showTitle?'<div class="header-title">'.concat(o.title,"</div>"):"",'\n <div class="header-status">\n <span class="status-dot"></span>\n <span>').concat(p("online"),'</span>\n </div>\n </div>\n \n <div style="display: flex; gap: 12px; align-items: center;">\n \x3c!-- New Chat Button (hide on landing screen, show otherwise) --\x3e\n <button class="header-icon new-chat-btn" id="newChatBtn" title="').concat(f("newChat"),'" style="').concat(u?"display: none;":"",'">\n <span style="font-size: 18px; font-weight: bold;">+</span>\n </button>\n \n \x3c!-- Back Button (only show in unified mode) --\x3e\n ').concat("unified"===s?'<button class="header-icon back-btn" id="backBtn" title="'.concat(f("back"),'" style="display: none;">\n <span style="font-size: 16px;">‹</span>\n </button>'):"","\n \n \x3c!-- Close Button --\x3e\n ").concat(o.showCloseButton?'<button class="header-icon close-btn" id="closeBtn" title="'+f("close")+'"><span style="font-size: 18px; font-weight: bold;">×</span></button>':"","\n </div>\n </div>\n\n ").concat(u?'\n <div class="landing-screen" id="landingScreen">\n <div class="landing-logo">🤖</div>\n <div class="landing-title">'.concat(p("landingTitle"),'</div>\n <div class="mode-selection">\n ').concat(l?'<div class="mode-card voice" id="mode-card-voice">\n <div class="mode-card-icon">🎤</div>\n <div class="mode-card-title">'.concat(p("voiceCall"),"</div>\n </div>"):"","\n ").concat(d?'<div class="mode-card text" id="mode-card-text">\n <div class="mode-card-icon">💬</div>\n <div class="mode-card-title">'.concat(p("textChat"),"</div>\n </div>"):"","\n </div>\n </div>"):"","\n\n ").concat(l?this.voiceInterface.generateHTML():"","\n ").concat(d?this.textInterface.generateHTML():"","\n </div>\n </div>\n </div>\n ")}},{key:"generatePositionStyles",value:function(){var e=this.config.position,t=e.offset||{x:20,y:20},n="";return"top"===e.vertical?n+="top: ".concat(t.y,"px;"):"bottom"===e.vertical?n+="bottom: ".concat(t.y,"px;"):"center"===e.vertical&&(n+="top: 50%; transform: translateY(-50%);"),"left"===e.horizontal?n+="left: ".concat(t.x,"px;"):"right"===e.horizontal?n+="right: ".concat(t.x,"px;"):"center"===e.horizontal&&(n+="left: 50%; transform: translateX(-50%);"),n}},{key:"generateIconHTML",value:function(e){var t=this.config.icon;switch(t.type){case"custom":return'<img src="'.concat(t.customImage,'" alt="Chat Assistant" style="width: ').concat(e,"px; height: ").concat(e,'px; object-fit: contain;" />');case"emoji":return'<span style="font-size: '.concat(e,'px; line-height: 1;">').concat(t.emoji,"</span>");case"text":return'<span style="font-size: '.concat(Math.floor(.6*e),'px; font-weight: bold; color: white;">').concat(t.text,"</span>");case"microphone":default:return'<svg viewBox="0 0 24 24" style="width: '.concat(e,"px; height: ").concat(e,'px; fill: white;">\n <path d="M12 14c1.66 0 3-1.34 3-3V5c0-1.66-1.34-3-3-3S9 3.34 9 5v6c0 1.66 1.34 3 3 3z"/>\n <path d="M17 11c0 2.76-2.24 5-5 5s-5-2.24-5-5H5c0 3.53 2.61 6.43 6 6.92V21h2v-3.08c3.39-.49 6-3.39 6-6.92h-2z"/>\n </svg>');case"chat":return'<svg viewBox="0 0 24 24" style="width: '.concat(e,"px; height: ").concat(e,'px; fill: white;">\n <path d="M20 2H4c-1.1 0-2 .9-2 2v18l4-4h14c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2zm0 14H6l-2 2V4h16v12z"/>\n </svg>')}}},{key:"generateCSS",value:function(e,t,n){var o,r,i,a,c,s,u,l=this.config.button,d=this.config.icon,p=this.config.panel,f=this.config.header,h=(this.config.messages,this.config.animation),v=this.config.behavior.mode||"unified",g="unified"===v||"voice-only"===v,y="unified"===v||"text-only"===v,m=f.backgroundColor;return'\n /* MOBILE FIRST - Default styles for all devices */\n #text-chat-widget {\n position: fixed !important;\n z-index: 10000;\n font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;\n /* Mobile defaults */\n right: 10px;\n bottom: 10px;\n left: auto;\n top: auto;\n }\n \n /* Desktop positioning (only on larger screens) */\n @media (min-width: 769px) {\n #text-chat-widget {\n '.concat(e,"\n right: ").concat("right"===this.config.position.horizontal?"20px":"auto",";\n left: ").concat("left"===this.config.position.horizontal?"20px":"auto",";\n bottom: ").concat("bottom"===this.config.position.vertical?"20px":"auto",";\n top: ").concat("top"===this.config.position.vertical?"20px":"auto",";\n }\n }\n \n /* Mobile override (force mobile positioning) */\n @media (max-width: 768px) {\n #text-chat-widget {\n right: 10px !important;\n bottom: 10px !important;\n left: auto !important;\n top: auto !important;\n transform: none !important;\n }\n }\n \n @media (max-width: 480px) {\n #text-chat-widget {\n right: 8px !important;\n bottom: 8px !important;\n left: auto !important;\n top: auto !important;\n }\n }\n \n #text-chat-button {\n width: ").concat(t,"px;\n height: ").concat(t,"px;\n border-radius: ").concat("circle"===l.shape?"50%":"square"===l.shape?"0":"12px",";\n background: ").concat(l.backgroundColor||d.backgroundColor||"#7C3AED",";\n border: none;\n cursor: pointer;\n display: flex;\n align-items: center;\n justify-content: center;\n transition: all ").concat(h.duration,"s ease;\n box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4);\n touch-action: manipulation;\n -webkit-tap-highlight-color: transparent;\n -webkit-touch-callout: none;\n user-select: none;\n min-width: 44px;\n min-height: 44px;\n }\n \n @media (max-width: 768px) {\n #text-chat-widget {\n right: 10px !important;\n bottom: 10px !important;\n left: auto !important;\n top: auto !important;\n transform: none !important;\n }\n \n #text-chat-button {\n width: 56px !important;\n height: 56px !important;\n min-width: 56px !important;\n min-height: 56px !important;\n max-width: 56px !important;\n max-height: 56px !important;\n }\n \n #text-chat-panel {\n position: fixed !important;\n left: 10px !important;\n right: 10px !important;\n bottom: 76px !important; /* 56px button + 20px gap */\n top: 60px !important; /* Add top spacing */\n width: auto !important;\n max-width: none !important;\n height: auto !important; /* Change from max-height to auto */\n max-height: none !important; /* Remove max-height */\n transform: none !important;\n margin: 0 !important;\n }\n \n #text-chat-panel .widget-header {\n padding: 10px 14px;\n min-height: 56px;\n }\n \n #text-chat-panel .header-title {\n font-size: 15px;\n }\n \n #text-chat-panel .header-icon {\n width: 40px;\n height: 40px;\n min-width: 40px;\n min-height: 40px;\n }\n \n #text-chat-input {\n font-size: 16px !important; /* Prevents iOS zoom on focus */\n padding: 12px 16px !important;\n min-height: 48px !important;\n }\n \n #text-chat-send {\n min-width: 48px !important;\n min-height: 48px !important;\n width: 48px !important;\n height: 48px !important;\n }\n \n .landing-screen {\n padding: 16px;\n }\n \n .landing-logo {\n font-size: 40px;\n }\n \n .landing-title {\n font-size: 18px;\n margin-bottom: 16px;\n }\n \n .mode-selection {\n flex-direction: column;\n gap: 12px;\n align-items: center;\n }\n \n .mode-card {\n max-width: 100%;\n width: 100%;\n padding: 16px;\n }\n \n .mode-card-icon {\n width: 50px;\n height: 50px;\n font-size: 28px;\n }\n \n .mode-card-title {\n font-size: 14px;\n }\n }\n \n @media (max-width: 480px) {\n #text-chat-widget {\n right: 8px !important;\n bottom: 8px !important;\n left: auto !important;\n top: auto !important;\n }\n \n #text-chat-button {\n width: 54px !important;\n height: 54px !important;\n min-width: 54px !important;\n min-height: 54px !important;\n }\n \n #text-chat-panel {\n left: 8px !important;\n right: 8px !important;\n bottom: 70px !important;\n top: 50px !important; /* Add top spacing for very small screens */\n height: auto !important;\n max-height: none !important;\n }\n \n #text-chat-panel .widget-header {\n padding: 8px 12px;\n min-height: 52px;\n }\n \n #text-chat-panel .header-title {\n font-size: 14px;\n }\n \n .landing-logo {\n font-size: 36px;\n }\n \n .landing-title {\n font-size: 16px;\n }\n }\n \n ").concat(h.enableHover?"\n #text-chat-button:hover {\n background: linear-gradient(135deg, #764ba2 0%, #667eea 100%);\n transform: scale(1.05);\n box-shadow: 0 8px 20px rgba(102, 126, 234, 0.5);\n }\n ":"","\n \n #text-chat-panel {\n display: none;\n position: fixed;\n bottom: calc(").concat(t,"px + 20px);\n ").concat("right"===this.config.position.horizontal?"right: 20px;":"left: 20px;","\n width: ").concat(p.width,"px;\n max-width: calc(100vw - 40px);\n height: ").concat(p.height,"px;\n max-height: calc(100vh - ").concat(t,"px - 40px);\n background: transparent;\n border-radius: ").concat(p.borderRadius,"px;\n border: none;\n flex-direction: column;\n overflow: hidden;\n ").concat(p.backdropFilter?"backdrop-filter: ".concat(p.backdropFilter,";"):"","\n ").concat(h.enableSlide?"transition: all ".concat(h.duration,"s ease;"):"","\n box-sizing: border-box;\n }\n \n #text-chat-panel.open {\n display: flex;\n ").concat(h.enableSlide?"transform: translateY(0); opacity: 1;":"","\n }\n\n /* Shell for gradient border/background */\n .widget-shell { width: 100%; height: 100%; padding: 0; border-radius: ").concat(p.borderRadius,"px; background: transparent; box-shadow: 0 20px 60px rgba(0,0,0,0.15); overflow: hidden; display: flex; flex-direction: column; box-sizing: border-box; }\n .panel-inner { width: 100%; height: 100%; background: #ffffff; border-radius: ").concat(p.borderRadius,"px; overflow: hidden; display:flex; flex-direction: column; padding: 0; box-sizing: border-box; max-width: 100%; }\n\n /* New structure styles matching provided design */\n #text-chat-panel .widget-container {\n width: 100%; height: 100%; min-height: 0; background: #FFFFFF; overflow: hidden; display: flex; flex-direction: column; border-radius: ").concat(p.borderRadius,"px;\n container-type: size;\n }\n \n /* Ensure content areas can scroll when height is constrained */\n #text-chat-panel .widget-container > .landing-screen,\n #text-chat-panel .widget-container > .voice-interface,\n #text-chat-panel .widget-container > .text-interface {\n flex: 1;\n min-height: 0;\n overflow-y: auto;\n overflow-x: hidden;\n }\n \n /* Header should not scroll */\n #text-chat-panel .widget-header {\n padding: 12px 16px;\n display: flex;\n justify-content: space-between;\n align-items: center;\n border-top-left-radius: ").concat(p.borderRadius,"px;\n border-top-right-radius: ").concat(p.borderRadius,"px;\n flex-shrink: 0;\n min-height: 60px;\n box-sizing: border-box;\n }\n #text-chat-panel .header-title { font-size: 16px; font-weight: 600; }\n #text-chat-panel .header-status { display: flex; align-items: center; gap: 8px; font-size: 12px; opacity: 0.9; }\n #text-chat-panel .status-dot { width: 8px; height: 8px; background: #4ade80; border-radius: 50%; animation: pulse 2s ease-in-out infinite; }\n @keyframes pulse { 0%, 100% { opacity: 1; } 50% { opacity: 0.5; } }\n /* Header icon buttons */\n .header-icon {\n background: rgba(255, 255, 255, 0.2);\n border: none;\n color: white;\n width: 36px;\n height: 36px;\n min-width: 36px;\n min-height: 36px;\n border-radius: 50%;\n cursor: pointer;\n display: flex;\n align-items: center;\n justify-content: center;\n transition: background 0.2s;\n flex-shrink: 0;\n font-size: 16px;\n padding: 0;\n box-sizing: border-box;\n }\n \n .header-icon:hover {\n background: rgba(255, 255, 255, 0.3);\n }\n \n .header-icon svg {\n pointer-events: none;\n stroke: white;\n fill: none;\n }\n \n .back-btn.visible {\n display: flex !important;\n }\n\n /* Landing and mode selection (shown only if voice enabled) */\n .landing-screen { \n display: none; \n flex: 1; \n padding: 20px; \n background: ").concat((null===(o=this.config.landing)||void 0===o?void 0:o.backgroundColor)||"linear-gradient(180deg, #f8fafc 0%, #e0e7ff 100%)","; \n align-items: center; \n justify-content: flex-start; \n flex-direction: column; \n gap: 16px; \n overflow-y: auto; \n min-height: 0; \n }\n .landing-screen.active { display: flex; }\n .landing-logo { font-size: 48px; }\n .landing-title { \n font-size: 20px; \n color: ").concat((null===(r=this.config.landing)||void 0===r?void 0:r.titleColor)||"#1e293b","; \n font-weight: 700; \n margin-bottom: 20px; \n text-align: center;\n width: 100%;\n }\n .mode-selection { display: flex; gap: 16px; width: 100%; justify-content: center; }\n .mode-card { \n flex: 1; \n max-width: 180px; \n background: ").concat((null===(i=this.config.landing)||void 0===i?void 0:i.modeCardBackgroundColor)||"#FFFFFF","; \n border: 2px solid ").concat((null===(a=this.config.landing)||void 0===a?void 0:a.modeCardBorderColor)||"#E2E8F0","; \n border-radius: 20px; \n padding: 20px 12px; \n cursor: pointer; \n display: flex; \n flex-direction: column; \n align-items: center; \n gap: 8px; \n transition: transform ").concat(h.duration,"s ease, box-shadow ").concat(h.duration,"s ease, border-color ").concat(h.duration,"s ease; \n box-shadow: 0 4px 12px rgba(0,0,0,0.05); \n }\n .mode-card:hover { \n transform: translateY(-6px); \n box-shadow: 0 12px 24px rgba(102, 126, 234, 0.2); \n border-color: ").concat((null===(c=this.config.landing)||void 0===c?void 0:c.modeCardHoverBorderColor)||m,"; \n }\n .mode-card-icon { \n width: 60px; \n height: 60px; \n display: flex; \n align-items: center; \n justify-content: center; \n border-radius: 50%; \n background: ").concat((null===(s=this.config.landing)||void 0===s?void 0:s.modeCardIconBackgroundColor)||m,"; \n color: #fff; \n font-size: 32px; \n }\n .mode-card-title { \n color: ").concat((null===(u=this.config.landing)||void 0===u?void 0:u.modeCardTitleColor)||"#111827","; \n font-weight: 600; \n text-align: center;\n width: 100%;\n }\n\n ").concat(g?this.voiceInterface.generateCSS():"","\n ").concat(y?this.textInterface.generateCSS():"","\n \n #text-chat-send-hint {\n text-align: center;\n line-height: 1.4;\n }\n \n .agent-thinking {\n font-style: italic;\n color: #6B7280;\n }\n ")}},{key:"setupWidgetEvents",value:function(){var e=this,t=document.getElementById("text-chat-button");t&&(t.onclick=function(){return e.togglePanel()});var n=document.getElementById("closeBtn");n&&(n.onclick=function(){return e.togglePanel()});var o=this.config.behavior.mode||"unified",r="unified"===o,i="unified"===o||"voice-only"===o,a="unified"===o||"text-only"===o,c=document.getElementById("backBtn"),s=document.getElementById("landingScreen"),u=document.getElementById("mode-card-voice"),l=document.getElementById("mode-card-text"),d=document.getElementById("textInterface"),p=document.getElementById("voiceInterface");c&&(c.onclick=function(){return e.showLanding()}),r?(u&&(u.onclick=function(){return e.showVoice()}),l&&(l.onclick=function(){return e.showText()}),"text"===this.currentView?(s&&s.classList.remove("active"),d&&d.classList.add("active"),p&&p.classList.remove("active"),c&&"unified"===o&&c.classList.add("visible"),f&&(f.style.display="")):"voice"===this.currentView?(s&&s.classList.remove("active"),d&&d.classList.remove("active"),p&&p.classList.add("active"),c&&"unified"===o&&c.classList.add("visible"),f&&(f.style.display="none")):(this.currentView="landing",s&&s.classList.add("active"),d&&d.classList.remove("active"),p&&p.classList.remove("active"),c&&"unified"===o&&c.classList.remove("visible"))):"voice-only"===o?(p&&p.classList.add("active"),d&&d.classList.remove("active"),s&&s.classList.remove("active")):"text-only"===o&&(d&&d.classList.add("active"),p&&p.classList.remove("active"),s&&s.classList.remove("active")),i&&(console.log("⚙️ Setting up voice interface event handlers"),this.voiceInterface.setupEventHandlers()),a&&(console.log("⚙️ Setting up text interface event handlers"),this.textInterface.setupEventHandlers());var f=document.getElementById("newChatBtn");f&&(f.onclick=function(){return e.textInterface.startNewChat()},r&&(f.style.display="none")),this.config.accessibility.keyboardNavigation&&this.setupKeyboardNavigation()}},{key:"startNewChat",value:function(){this.textInterface.startNewChat()}},{key:"showLanding",value:function(){if("unified"===(this.config.behavior.mode||"unified")){this.currentView="landing";var e=document.getElementById("landingScreen"),t=document.getElementById("textInterface"),n=document.getElementById("voiceInterface"),o=document.getElementById("backBtn"),r=document.getElementById("newChatBtn");e&&e.classList.add("active"),t&&t.classList.remove("active"),n&&n.classList.remove("active"),o&&o.classList.remove("visible"),r&&(r.style.display="none")}}},{key:"showText",value:function(){this.currentView="text";var e=document.getElementById("landingScreen"),t=document.getElementById("voiceInterface"),n=document.getElementById("backBtn"),o=document.getElementById("newChatBtn");e&&e.classList.remove("active"),t&&t.classList.remove("active"),this.textInterface.show();var r=this.config.behavior.mode||"unified";n&&"unified"===r&&n.classList.add("visible"),o&&(o.style.display="")}},{key:"showVoice",value:function(){this.currentView="voice";var e=document.getElementById("landingScreen"),t=document.getElementById("textInterface"),n=document.getElementById("voiceInterface"),o=document.getElementById("backBtn"),r=document.getElementById("newChatBtn");e&&e.classList.remove("active"),t&&t.classList.remove("active"),n&&n.classList.add("active");var i=this.config.behavior.mode||"unified";o&&"unified"===i&&o.classList.add("visible"),r&&(r.style.display="none")}},{key:"setupKeyboardNavigation",value:function(){var e=this;document.addEventListener("keydown",function(t){"Escape"===t.key&&e.isOpen&&e.togglePanel()})}},{key:"togglePanel",value:function(){this.isOpen=!this.isOpen,document.getElementById("text-chat-panel").classList.toggle("open"),this.isOpen&&setTimeout(function(){var e=document.getElementById("messageInput");e&&e.focus()},100),this.isOpen&&!this.isActive&&this.config.behavior.autoConnect&&this.startChat()}},{key:"startChat",value:(i=uo(ao().m(function e(){return ao().w(function(e){for(;;)switch(e.n){case 0:this.isActive=!0,this.textInterface.setActive(!0);case 1:return e.a(2)}},e,this)})),function(){return i.apply(this,arguments)})},{key:"sendMessage",value:(r=uo(ao().m(function e(){return ao().w(function(e){for(;;)switch(e.n){case 0:return e.n=1,this.textInterface.sendMessage();case 1:return e.a(2)}},e,this)})),function(){return r.apply(this,arguments)})},{key:"updateSendButtonState",value:function(){this.textInterface.updateSendButtonState()}},{key:"getSignedUrl",value:(o=uo(ao().m(function e(){var t,n,o,r,i,a,c;return ao().w(function(e){for(;;)switch(e.n){case 0:if(this.config.getSessionUrl){e.n=2;break}if(this.config.agentId){e.n=1;break}throw new Error("agentId is required");case 1:return t=this.config.websocketUrl||"wss://backend.talktopc.com/ws/conv",(n=new URLSearchParams).append("agentId",this.config.agentId),this.config.appId&&n.append("appId",this.config.appId),!1!==this.config.demo&&n.append("demo","true"),e.a(2,"".concat(t,"?").concat(n.toString()));case 2:if("string"!=typeof this.config.getSessionUrl){e.n=6;break}return o={agentId:this.config.agentId,variables:this.config.variables||{}},this.config.appId&&(o.appId=this.config.appId),e.n=3,fetch(this.config.getSessionUrl,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)});case 3:if((r=e.v).ok){e.n=4;break}throw new Error("Failed to get session URL: ".concat(r.statusText));case 4:return e.n=5,r.json();case 5:return i=e.v,e.a(2,i.signedUrl||i.wsUrl||i.url);case 6:if("function"!=typeof this.config.getSessionUrl){e.n=8;break}return a={agentId:this.config.agentId,variables:this.config.variables||{}},this.config.appId&&(a.appId=this.config.appId),e.n=7,this.config.getSessionUrl(a);case 7:return c=e.v,e.a(2,"string"==typeof c?c:c.signedUrl||c.wsUrl||c.url);case 8:throw new Error("getSessionUrl must be a string (backend URL), a function, or omitted (for direct connection with agentId/appId)");case 9:return e.a(2)}},e,this)})),function(){return o.apply(this,arguments)})},{key:"addMessage",value:function(e,t){this.textInterface.addMessage(e,t)}},{key:"beginStreaming",value:function(){this.textInterface.beginStreaming()}},{key:"appendStreamingChunk",value:function(e){this.textInterface.appendStreamingChunk(e)}},{key:"finalizeStreaming",value:function(e){this.textInterface.finalizeStreaming(e)}},{key:"stopStreamingState",value:function(){this.textInterface.stopStreamingState()}},{key:"showError",value:function(e){this.textInterface.showError(e)}},{key:"updateStatus",value:function(e){}},{key:"updateConfig",value:function(e){var t,n,o,r,i,a,c,s,u,l=fo({},this.config);e.panel&&(l.panel=fo(fo({},this.config.panel),e.panel)),e.voice&&(l.voice=fo(fo({},this.config.voice),e.voice),e.voice.micButtonHint&&(l.voice.micButtonHint=fo(fo({},null===(s=this.config.voice)||void 0===s?void 0:s.micButtonHint),e.voice.micButtonHint))),e.text&&(l.text=fo(fo({},this.config.text),e.text),e.text.sendButtonHint&&(l.text.sendButtonHint=fo(fo({},null===(u=this.config.text)||void 0===u?void 0:u.sendButtonHint),e.text.sendButtonHint))),void 0!==e.language&&(l.language=e.language),void 0!==e.language&&(["he","ar"].includes(e.language)?l.direction="rtl":void 0===e.direction&&(l.direction="ltr")),e.translations&&(l.translations=e.translations,this.translations=e.translations),e.button&&(l.button=fo(fo({},this.config.button),e.button)),e.header&&(l.header=fo(fo({},this.config.header),e.header)),e.icon&&(l.icon=fo(fo({},this.config.icon),e.icon)),e.messages&&(l.messages=fo(fo({},this.config.messages),e.messages)),e.animation&&(l.animation=fo(fo({},this.config.animation),e.animation)),e.behavior&&(l.behavior=fo(fo({},this.config.behavior),e.behavior)),e.accessibility&&(l.accessibility=fo(fo({},this.config.accessibility),e.accessibility)),e.tooltips&&(l.tooltips=fo(fo({},this.config.tooltips),e.tooltips)),e.landing&&(l.landing=fo(fo({},this.config.landing),e.landing)),void 0!==e.direction&&void 0===l.direction&&(l.direction=e.direction),void 0!==e.primaryColor&&(l.primaryColor=e.primaryColor),l.onConversationStart=void 0!==e.onConversationStart?e.onConversationStart:this.config.onConversationStart,l.onConversationEnd=void 0!==e.onConversationEnd?e.onConversationEnd:this.config.onConversationEnd,l.onBargeIn=void 0!==e.onBargeIn?e.onBargeIn:this.config.onBargeIn,l.onAudioStartPlaying=void 0!==e.onAudioStartPlaying?e.onAudioStartPlaying:this.config.onAudioStartPlaying,l.onAudioStoppedPlaying=void 0!==e.onAudioStoppedPlaying?e.onAudioStoppedPlaying:this.config.onAudioStoppedPlaying,l.onSubtitleDisplay=void 0!==e.onSubtitleDisplay?e.onSubtitleDisplay:this.config.onSubtitleDisplay,Object.keys(e).forEach(function(t){["panel","button","header","icon","messages","direction","voice","text","animation","behavior","accessibility","language","tooltips","landing","primaryColor","onConversationStart","onConversationEnd","onBargeIn","onAudioStartPlaying","onAudioStoppedPlaying","onSubtitleDisplay"].includes(t)||(l[t]=e[t])}),null===(t=this.config)||void 0===t||t.language,this.config=this.mergeWithDefaults(l);var d=this.config.language||"en",p=fo(fo(fo({},this.config),this.config.voice),{},{language:d,websocketUrl:(null===(n=this.config.voice)||void 0===n?void 0:n.websocketUrl)||this.config.websocketUrl||"wss://speech.talktopc.com/ws/conv",translations:this.translations,outputContainer:(null===(o=this.config.voice)||void 0===o?void 0:o.outputContainer)||"raw",outputEncoding:(null===(r=this.config.voice)||void 0===r?void 0:r.outputEncoding)||"pcm",outputSampleRate:(null===(i=this.config.voice)||void 0===i?void 0:i.outputSampleRate)||44100,outputChannels:(null===(a=this.config.voice)||void 0===a?void 0:a.outputChannels)||1,outputBitDepth:(null===(c=this.config.voice)||void 0===c?void 0:c.outputBitDepth)||16,onConversationStart:this.config.onConversationStart,onConversationEnd:this.config.onConversationEnd,onBargeIn:this.config.onBargeIn,onAudioStartPlaying:this.config.onAudioStartPlaying,onAudioStoppedPlaying:this.config.onAudioStoppedPlaying,onSubtitleDisplay:this.config.onSubtitleDisplay});this.voiceInterface=new Yn(p);var f=fo(fo(fo({},this.config),this.config.text),{},{language:d,translations:this.translations});this.textInterface=new ro(f,this.sdk);var h=document.getElementById("text-chat-widget");h&&h.remove(),this.createWidget(),this.textInterface&&this.textInterface.updateInputAttributes&&this.textInterface.updateInputAttributes()}},{key:"destroy",value:function(){var e=document.getElementById("text-chat-widget");e&&e.remove(),this.sdk&&this.sdk.destroy(),this.voiceInterface&&this.voiceInterface.destroy()}},{key:"startVoiceCall",value:(n=uo(ao().m(function e(){return ao().w(function(e){for(;;)switch(e.n){case 0:return e.n=1,this.voiceInterface.startVoiceCall();case 1:return e.a(2)}},e,this)})),function(){return n.apply(this,arguments)})},{key:"endVoiceCall",value:function(){this.voiceInterface.endVoiceCall()}},{key:"toggleMute",value:function(){this.voiceInterface.toggleMute()}},{key:"toggleSpeaker",value:function(){this.voiceInterface.toggleSpeaker()}}],t&&vo(e.prototype,t),Object.defineProperty(e,"prototype",{writable:!1}),e;var e,t,n,o,r,i}(),mo="2.4.23";const bo={VoiceSDK:he,VoiceSDK_v2:Xt,TextChatSDK:pn,WebSocketManager:j,AudioRecorder:z,AudioPlayer:ee,EventEmitter:c,VoiceButton:kn,VanillaVoiceButton:Bn,AgentSDK:Ln,TTPChatWidget:yo,VERSION:mo};return o})());
|
|
3
3
|
//# sourceMappingURL=agent-widget.js.map
|