@touchcastllc/napster-companion-api 1.0.0-alpha.21 → 1.0.0-alpha.22

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/lib/index.esm.js CHANGED
@@ -1 +1 @@
1
- import{createSlice as e,configureStore as t}from"@reduxjs/toolkit";class n extends Error{constructor(e,t,n){super(e),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"timestamp",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"context",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name="SDKError",this.code=t,this.timestamp=new Date,this.context=n,Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,message:this.message,code:this.code,timestamp:this.timestamp.toISOString(),context:this.context,stack:this.stack}}}class a extends n{constructor(e,t){super(e,"INITIALIZATION_ERROR",t),this.name="InitializationError"}}class i extends n{constructor(e,t){super(e,"TOKEN_ERROR",t),this.name="TokenError"}}class o extends n{constructor(e,t){super(e,"CONNECTION_ERROR",t),this.name="ConnectionError"}}class r extends n{constructor(e,t){super(e,"WEBRTC_ERROR",t),this.name="WebRTCError"}}var s,c;!function(e){e.ALREADY_INITIALIZED="ALREADY_INITIALIZED",e.INVALID_TOKEN="INVALID_TOKEN",e.REACT_VERSION_UNSUPPORTED="REACT_VERSION_UNSUPPORTED",e.CONTAINER_NOT_FOUND="CONTAINER_NOT_FOUND",e.CONNECTION_FAILED="CONNECTION_FAILED",e.TOKEN_GENERATION_FAILED="TOKEN_GENERATION_FAILED",e.MISSING_CREDENTIALS="MISSING_CREDENTIALS",e.WEBRTC_NOT_SUPPORTED="WEBRTC_NOT_SUPPORTED",e.PEER_CONNECTION_FAILED="PEER_CONNECTION_FAILED",e.DATA_CHANNEL_ERROR="DATA_CHANNEL_ERROR",e.API_REQUEST_FAILED="API_REQUEST_FAILED",e.INVALID_RESPONSE="INVALID_RESPONSE",e.RATE_LIMITED="RATE_LIMITED",e.INVALID_CONFIGURATION="INVALID_CONFIGURATION",e.MISSING_REQUIRED_CONFIG="MISSING_REQUIRED_CONFIG",e.FEATURE_NOT_SUPPORTED="FEATURE_NOT_SUPPORTED",e.FEATURE_DISABLED="FEATURE_DISABLED",e.MEDIA_ACCESS_DENIED="MEDIA_ACCESS_DENIED",e.MEDIA_DEVICE_ERROR="MEDIA_DEVICE_ERROR",e.VIDEO_LOAD_ERROR="VIDEO_LOAD_ERROR"}(s||(s={}));class d{static setErrorHandler(e){this.onError=e}static handle(e,t){let a;return function(e){return e instanceof n}(e)?(a=e,t&&(a.context={...a.context,...t})):a=e instanceof Error?new n(e.message,"UNKNOWN_ERROR",{originalError:e.name,...t}):new n("string"==typeof e?e:"Unknown error occurred","UNKNOWN_ERROR",{originalError:e,...t}),this.onError?.(a),a}}!function(e){e.BOTTOM_RIGHT="bottom-right",e.BOTTOM_CENTER="bottom-center",e.BOTTOM_LEFT="bottom-left",e.TOP_RIGHT="top-right",e.TOP_CENTER="top-center",e.TOP_LEFT="top-left",e.CENTER="center"}(c||(c={}));const l=e({name:"avatar",initialState:{avatarReady:!1,dataChannel:null,stopInteraction:!1,muted:!1,transcript:void 0,customVoiceId:void 0,defaultVoiceId:void 0,connectionToken:void 0,companionId:void 0,closeConnectionHandler:void 0},reducers:{setSessionId:(e,t)=>{e.sessionId=t.payload},setAvatarReady:(e,t)=>{e.avatarReady=t.payload},setDataChannel:(e,t)=>{e.dataChannel=t.payload},setAvatarId:(e,t)=>{e.avatarId=t.payload},setVideoId:(e,t)=>{e.videoId=t.payload},setStopInteraction:(e,t)=>{e.stopInteraction=t.payload},setMuted:(e,t)=>{e.muted=t.payload},addTranscript:(e,t)=>{e.transcript=t.payload},setCustomVoiceId:(e,t)=>{e.customVoiceId=t.payload},setDefaultVoiceId:(e,t)=>{e.defaultVoiceId=t.payload},setConnectionToken:(e,t)=>{e.connectionToken=t.payload},setCloseConnectionHandler:(e,t)=>{e.closeConnectionHandler=t.payload}}}),{setDataChannel:u,setStopInteraction:p,setMuted:h,setConnectionToken:m,setCloseConnectionHandler:f}=l.actions,v=l.reducer,g={features:{backgroundRemoval:{enabled:!0},waveform:{enabled:!0,color:"#ffffff"},inactiveTimeout:{enabled:!0,duration:6e4,countdown:30},disclaimer:{enabled:!0,text:"This is an AI avatar. Check important info."},showSDKLoader:{enabled:!0,bgColor:"rgb(222 222 222 / 60%)",color:"#585858ff",type:"spinner"}},position:void 0,showExperience:!1,debugMode:!1},C=e({name:"app",initialState:g,reducers:{setFeatures:(e,t)=>{const{feature:n,config:a}=t.payload,i=e.features[n];e.features[n]={...i,...a,enabled:a?.enabled??!!i?.enabled}},resetFeatures:e=>{e.features=g.features},setPosition:(e,t)=>{e.position=t.payload},setShowExperience:(e,t)=>{e.showExperience=t.payload},setDebugMode:(e,t)=>{e.debugMode=t.payload}}}),{setFeatures:b,resetFeatures:y,setPosition:E,setDebugMode:w}=C.actions;let _=null;const S=e=>{_=e},T=e=>t=>n=>{const a=e.getState().app.features,i=t(n),o=e.getState().app.features;return _&&a!==o&&JSON.stringify(a)!==JSON.stringify(o)&&_(o),i},I=t({reducer:{avatar:v,app:C.reducer},middleware:e=>e({serializableCheck:!1}).concat(T)});var N;!function(e){e.INFO="info",e.WARN="warn",e.ERROR="error",e.DEBUG="debug"}(N||(N={}));const k=new class{constructor(){Object.defineProperty(this,"prefix",{enumerable:!0,configurable:!0,writable:!0,value:"[Napster SDK]"})}isDebugEnabled(){try{return I.getState().app.debugMode||!1}catch{return!1}}log(e,...t){if(!this.isDebugEnabled())return;const n=[this.prefix,...t];switch(e){case N.INFO:console.info(...n);break;case N.WARN:console.warn(...n);break;case N.ERROR:console.error(...n);break;case N.DEBUG:console.debug(...n)}}info(...e){this.log(N.INFO,"ℹ️",...e)}debug(...e){this.log(N.DEBUG,"🐞",...e)}warn(...e){this.log(N.WARN,"⚠️",...e)}error(...e){this.log(N.ERROR,"❌",...e)}critical_warn(...e){console.warn(this.prefix,"⚠️",...e)}critical_error(...e){console.error(this.prefix,"❌",...e)}webrtc(...e){this.log(N.INFO,"📡 WebRTC:",...e)}avatar(...e){this.log(N.INFO,"🎭 Avatar:",...e)}connection(...e){this.log(N.INFO,"🔌 Connection:",...e)}features(...e){this.log(N.INFO,"🔄 Features:",...e)}data(...e){this.log(N.INFO,"📨 Data:",...e)}timer(...e){this.log(N.INFO,"⏱️ Timer:",...e)}cleanup(...e){this.log(N.INFO,"🗑️ Cleanup:",...e)}};function A(...e){const t=[];for(const n of e)if(n)if("string"==typeof n||"number"==typeof n)t.push(String(n));else if(Array.isArray(n)){const e=A(...n);e&&t.push(e)}else if("object"==typeof n)for(const[e,a]of Object.entries(n))a&&t.push(e);return t.join(" ")}const D={icon:"np_companion-action-btn-container-icon",persistFillColor:"np_companion-persist-fill-color",alignMiddle:"np_companion-align-middle",alignBetween:"np_companion-align-between",darkGreyBg:"np_companion-dark-grey-bg",callEnd:"np_companion-action-btn-container-call-end",container:"np_companion-action-btn-container-container",wrapper:"np_companion-action-btn-container-wrapper",canvas:"np_companion-action-btn-container-canvas",controls:"np_companion-action-btn-container-controls",left:"np_companion-action-btn-container-left",middle:"np_companion-action-btn-container-middle",right:"np_companion-action-btn-container-right",wave:"np_companion-action-btn-container-wave",stop:"np_companion-action-btn-container-stop",questionBar:"np_companion-chat-question-bar-container",muted:"muted",hidden:"np_companion-hidden",expanded:"np_companion-action-btn-container-expanded",collapse:"np_companion-action-btn-container-collapse",mobileMode:"np_companion-mobile-mode",displayNone:"np_companion__d-none",iconButton:()=>A(D.icon,D.alignMiddle,D.darkGreyBg),iconButtonEnd:()=>A(D.icon,D.alignMiddle,D.darkGreyBg,D.callEnd),iconButtonWithState:e=>A(D.icon,D.alignMiddle,D.darkGreyBg,{[D.muted]:e})};class O{static createElement(e,t){const n=document.createElement(e);return t?.className&&(n.className=t.className),t?.id&&(n.id=t.id),t?.attributes&&Object.entries(t.attributes).forEach(([e,t])=>{n.setAttribute(e,t)}),t?.styles&&Object.assign(n.style,t.styles),n}static createVideo(e){const t=this.createElement("video",{className:e.className});return t.autoplay=e.autoplay??!1,t.muted=e.muted??!1,t.loop=e.loop??!1,t.playsInline=e.playsInline??!1,e.crossOrigin&&(t.crossOrigin=e.crossOrigin),e.poster&&(t.poster=e.poster),e.src&&(t.src=e.src),t}static createAudio(e){const t=this.createElement("audio",{className:e.className});return t.autoplay=e.autoplay??!1,t}static createCanvas(e){const t=this.createElement("canvas",{className:e.className,styles:e.styles});return void 0!==e.width&&(t.width=e.width),void 0!==e.height&&(t.height=e.height),t}static createButton(e){const t=this.createElement("button",{className:e.className,attributes:e.attributes});return e.textContent&&(t.textContent=e.textContent),e.onClick&&t.addEventListener("click",e.onClick),t}static createDiv(e){return this.createElement("div",{className:e})}}class R{static process(e){const t=e.data;return this.hasGreenScreen(t)?(this.removeGreenScreen(t),e):e}static hasGreenScreen(e){for(let t=0;t<e.length;t+=4)if(this.isGreenPixel(e[t],e[t+1],e[t+2]))return!0;return!1}static isGreenPixel(e,t,n){return e>=0&&e<=120&&t>=150&&t<=255&&n>=0&&n<=120}static removeGreenScreen(e){for(let t=0;t<e.length;t+=4){const n=e[t],a=e[t+1],i=e[t+2];this.isGreenPixel(n,a,i)?e[t+3]=0:this.reduceGreenSpill(e,t,n,a,i)}}static reduceGreenSpill(e,t,n,a,i){const o=a-Math.max(n,i);if(o>0){const r=.5*o;e[t]=Math.min(255,n+.8*r),e[t+2]=Math.min(255,i+.8*r),e[t+1]=Math.max(0,a-r)}}}const L=new class{constructor(){Object.defineProperty(this,"svgNS",{enumerable:!0,configurable:!0,writable:!0,value:"http://www.w3.org/2000/svg"})}createElement(e){const t=document.createElementNS(this.svgNS,e.tag);return e.attributes&&Object.entries(e.attributes).forEach(([e,n])=>{t.setAttribute(e,String(n))}),e.textContent&&(t.textContent=e.textContent),e.children&&e.children.forEach(e=>{const n=this.createElement(e);t.appendChild(n)}),t}createSVG(e,t,n,a,i){const o=document.createElementNS(this.svgNS,"svg");return o.setAttribute("width",String(e)),o.setAttribute("height",String(t)),o.setAttribute("viewBox",n),o.setAttribute("fill","none"),o.setAttribute("xmlns",this.svgNS),i&&o.setAttribute("class",i),a.forEach(e=>{const t=this.createElement(e);o.appendChild(t)}),o}},M={micUnmuted:()=>L.createSVG(17,17,"0 0 17 17",[{tag:"g",attributes:{"clip-path":"url(#clip0_655_3824)"},children:[{tag:"path",attributes:{d:"M8.67241 11.8448C9.49524 11.844 10.2841 11.5167 10.8659 10.9349C11.4478 10.3531 11.775 9.5642 11.7759 8.74138V4.60345C11.7759 3.78036 11.4489 2.99099 10.8669 2.40898C10.2849 1.82697 9.4955 1.5 8.67241 1.5C7.84933 1.5 7.05995 1.82697 6.47794 2.40898C5.89594 2.99099 5.56897 3.78036 5.56897 4.60345V8.74138C5.56982 9.5642 5.89707 10.3531 6.47889 10.9349C7.06071 11.5167 7.84959 11.844 8.67241 11.8448ZM6.60345 4.60345C6.60345 4.05472 6.82143 3.52847 7.20943 3.14047C7.59744 2.75246 8.12369 2.53448 8.67241 2.53448C9.22114 2.53448 9.74739 2.75246 10.1354 3.14047C10.5234 3.52847 10.7414 4.05472 10.7414 4.60345V8.74138C10.7414 9.2901 10.5234 9.81635 10.1354 10.2044C9.74739 10.5924 9.22114 10.8103 8.67241 10.8103C8.12369 10.8103 7.59744 10.5924 7.20943 10.2044C6.82143 9.81635 6.60345 9.2901 6.60345 8.74138V4.60345ZM9.18965 13.8879V15.9828C9.18965 16.1199 9.13516 16.2515 9.03816 16.3485C8.94116 16.4455 8.80959 16.5 8.67241 16.5C8.53523 16.5 8.40367 16.4455 8.30667 16.3485C8.20967 16.2515 8.15517 16.1199 8.15517 15.9828V13.8879C6.87994 13.7582 5.69812 13.1601 4.83826 12.2095C3.9784 11.2589 3.50158 10.0232 3.5 8.74138C3.5 8.6042 3.5545 8.47264 3.6515 8.37563C3.7485 8.27863 3.88006 8.22414 4.01724 8.22414C4.15442 8.22414 4.28598 8.27863 4.38299 8.37563C4.47999 8.47264 4.53448 8.6042 4.53448 8.74138C4.53448 9.83883 4.97044 10.8913 5.74645 11.6673C6.52247 12.4434 7.57497 12.8793 8.67241 12.8793C9.76986 12.8793 10.8224 12.4434 11.5984 11.6673C12.3744 10.8913 12.8103 9.83883 12.8103 8.74138C12.8103 8.6042 12.8648 8.47264 12.9618 8.37563C13.0588 8.27863 13.1904 8.22414 13.3276 8.22414C13.4648 8.22414 13.5963 8.27863 13.6933 8.37563C13.7903 8.47264 13.8448 8.6042 13.8448 8.74138C13.8433 10.0232 13.3664 11.2589 12.5066 12.2095C11.6467 13.1601 10.4649 13.7582 9.18965 13.8879Z",fill:"white"}}]},{tag:"defs",children:[{tag:"clipPath",attributes:{id:"clip0_655_3824"},children:[{tag:"rect",attributes:{width:"16",height:"16",fill:"white",transform:"translate(0.5 0.5)"}}]}]}],"np_companion-mic-unmuted"),micMuted:()=>L.createSVG(22,22,"0 0 17 18",[{tag:"g",attributes:{"clip-path":"url(#clip0_655_4192)"},children:[{tag:"path",attributes:{d:"M14.2432 14.6L3.89604 3.21808C3.80327 3.11843 3.67498 3.05936 3.53896 3.05368C3.40294 3.048 3.27016 3.09616 3.16941 3.18772C3.06866 3.27928 3.00806 3.40686 3.00075 3.5428C2.99343 3.67874 3.04 3.81208 3.13034 3.91392L5.58263 6.61131V8.7396C5.58251 9.26661 5.71656 9.78497 5.97216 10.2458C6.22776 10.7067 6.59649 11.0949 7.04361 11.3739C7.49073 11.6529 8.00151 11.8134 8.52782 11.8404C9.05414 11.8674 9.57867 11.7599 10.052 11.5282L10.7698 12.3171C10.138 12.6868 9.41878 12.8806 8.68679 12.8785C7.58946 12.8773 6.53741 12.4408 5.76148 11.6649C4.98555 10.889 4.54911 9.83693 4.54791 8.7396C4.54791 8.60239 4.4934 8.47079 4.39638 8.37377C4.29935 8.27675 4.16776 8.22224 4.03055 8.22224C3.89334 8.22224 3.76174 8.27675 3.66472 8.37377C3.5677 8.47079 3.51319 8.60239 3.51319 8.7396C3.51476 10.0217 3.9917 11.2577 4.85176 12.2085C5.71182 13.1594 6.8939 13.7575 8.16943 13.8873V15.9826C8.16943 16.1199 8.22394 16.2514 8.32096 16.3485C8.41798 16.4455 8.54958 16.5 8.68679 16.5C8.824 16.5 8.95559 16.4455 9.05262 16.3485C9.14964 16.2514 9.20415 16.1199 9.20415 15.9826V13.8867C10.0143 13.8085 10.794 13.5376 11.4779 13.0964L13.4775 15.2952C13.523 15.3464 13.5781 15.3881 13.6398 15.4178C13.7015 15.4476 13.7684 15.4648 13.8368 15.4685C13.9051 15.4722 13.9735 15.4622 14.038 15.4393C14.1025 15.4163 14.1618 15.3808 14.2125 15.3347C14.2632 15.2887 14.3042 15.2331 14.3332 15.171C14.3622 15.109 14.3786 15.0419 14.3815 14.9735C14.3843 14.9051 14.3736 14.8368 14.3499 14.7725C14.3261 14.7083 14.2899 14.6495 14.2432 14.5993V14.6ZM8.68679 10.809C8.13794 10.809 7.61157 10.591 7.22347 10.2029C6.83538 9.81482 6.61735 9.28845 6.61735 8.7396V7.7495L9.3115 10.7127C9.10943 10.7766 8.89873 10.8091 8.68679 10.809ZM12.4066 10.5562C12.6841 9.99093 12.8275 9.36929 12.8257 8.7396C12.8257 8.60239 12.8802 8.47079 12.9772 8.37377C13.0742 8.27675 13.2058 8.22224 13.343 8.22224C13.4802 8.22224 13.6118 8.27675 13.7089 8.37377C13.8059 8.47079 13.8604 8.60239 13.8604 8.7396C13.8625 9.52693 13.6831 10.3041 13.3359 11.0108C13.2934 11.0979 13.2273 11.1713 13.145 11.2226C13.0628 11.274 12.9679 11.3012 12.8709 11.3012C12.7922 11.3013 12.7145 11.2831 12.6439 11.2481C12.5207 11.1878 12.4265 11.0811 12.382 10.9513C12.3375 10.8215 12.3463 10.6794 12.4066 10.5562ZM5.84131 3.36358C6.12624 2.71004 6.62746 2.1745 7.26073 1.84696C7.894 1.51943 8.62071 1.41987 9.31874 1.56501C10.0168 1.71015 10.6435 2.09116 11.0938 2.64398C11.544 3.19681 11.7902 3.88776 11.7909 4.60072V8.7396C11.7908 8.8476 11.7852 8.95552 11.7741 9.06295C11.7608 9.19066 11.7005 9.30885 11.6049 9.39455C11.5092 9.48025 11.3852 9.52733 11.2568 9.52663C11.2387 9.52757 11.2205 9.52757 11.2025 9.52663C11.066 9.51229 10.9409 9.44435 10.8545 9.33775C10.7682 9.23115 10.7277 9.09462 10.742 8.95818C10.7491 8.88705 10.753 8.81332 10.753 8.74089V4.60072C10.7516 4.12605 10.5871 3.66628 10.2871 3.29848C9.98701 2.93069 9.56963 2.67722 9.10491 2.58058C8.64018 2.48393 8.15636 2.54998 7.73454 2.76766C7.31273 2.98534 6.97857 3.34141 6.78808 3.77618C6.7639 3.84253 6.72639 3.90322 6.67786 3.95452C6.62934 4.00583 6.57082 4.04665 6.50592 4.07449C6.44102 4.10232 6.37111 4.11658 6.30049 4.11637C6.22987 4.11617 6.16005 4.10151 6.09531 4.07329C6.03057 4.04508 5.9723 4.00392 5.92407 3.95233C5.87584 3.90075 5.83869 3.83983 5.81489 3.77335C5.7911 3.70686 5.78117 3.6362 5.78571 3.56573C5.79025 3.49526 5.80917 3.42646 5.84131 3.36358Z",fill:"white"}}]},{tag:"defs",children:[{tag:"clipPath",attributes:{id:"clip0_655_4192"},children:[{tag:"rect",attributes:{width:"16",height:"16",fill:"white",transform:"translate(0.5 0.5)"}}]}]}],"tc-mic-muted"),stop:()=>L.createSVG(20,20,"0 0 32 32",[{tag:"path",attributes:{d:"M5.92 24.096q0 0.832 0.576 1.408t1.44 0.608h16.128q0.832 0 1.44-0.608t0.576-1.408v-16.16q0-0.832-0.576-1.44t-1.44-0.576h-16.128q-0.832 0-1.44 0.576t-0.576 1.44v16.16z",fill:"#ffffff"}}]),volumeHigh(e){const t=[{tag:"path",attributes:{d:"M80 416L128 416L262.1 535.2C268.5 540.9 276.7 544 285.2 544C304.4 544 320 528.4 320 509.2L320 130.8C320 111.6 304.4 96 285.2 96C276.7 96 268.5 99.1 262.1 104.8L128 224L80 224C53.5 224 32 245.5 32 272L32 368C32 394.5 53.5 416 80 416z",fill:"#ffffff"}}];return e>0&&t.push({tag:"path",attributes:{d:"M412.6 245.5C402.3 237.1 387.2 238.7 378.8 249C370.4 259.3 372 274.4 382.3 282.8C393.1 291.6 400 305 400 320C400 335 393.1 348.4 382.3 357.3C372 365.7 370.5 380.8 378.8 391.1C387.1 401.4 402.3 402.9 412.6 394.6C434.1 376.9 448 350.1 448 320C448 289.9 434.1 263.1 412.6 245.5z",fill:"#ffffff"}}),e>=25&&t.push({tag:"path",attributes:{d:"M473.1 171C462.8 162.6 447.7 164.2 439.3 174.5C430.9 184.8 432.5 199.9 442.8 208.3C475.3 234.7 496 274.9 496 320C496 365.1 475.3 405.3 442.8 431.8C432.5 440.2 431 455.3 439.3 465.6C447.6 475.9 462.8 477.4 473.1 469.1C516.3 433.9 544 380.2 544 320.1C544 260 516.3 206.3 473.1 171.1z",fill:"#ffffff"}}),e>=75&&t.push({tag:"path",attributes:{d:"M533.6 96.5C523.3 88.1 508.2 89.7 499.8 100C491.4 110.3 493 125.4 503.3 133.8C557.5 177.8 592 244.8 592 320C592 395.2 557.5 462.2 503.3 506.3C493 514.7 491.5 529.8 499.8 540.1C508.1 550.4 523.3 551.9 533.6 543.6C598.5 490.7 640 410.2 640 320C640 229.8 598.5 149.2 533.6 96.5z",fill:"#ffffff"}}),L.createSVG(16,16,"0 0 640 640",t)},volumeMuted:()=>L.createSVG(16,16,"0 0 640 640",[{tag:"path",attributes:{d:"M80 416L128 416L262.1 535.2C268.5 540.9 276.7 544 285.2 544C304.4 544 320 528.4 320 509.2L320 130.8C320 111.6 304.4 96 285.2 96C276.7 96 268.5 99.1 262.1 104.8L128 224L80 224C53.5 224 32 245.5 32 272L32 368C32 394.5 53.5 416 80 416zM399 239C389.6 248.4 389.6 263.6 399 272.9L446 319.9L399 366.9C389.6 376.3 389.6 391.5 399 400.8C408.4 410.1 423.6 410.2 432.9 400.8L479.9 353.8L526.9 400.8C536.3 410.2 551.5 410.2 560.8 400.8C570.1 391.4 570.2 376.2 560.8 366.9L513.8 319.9L560.8 272.9C570.2 263.5 570.2 248.3 560.8 239C551.4 229.7 536.2 229.6 526.9 239L479.9 286L432.9 239C423.5 229.6 408.3 229.6 399 239z",fill:"#ffffff"}}]),end:()=>L.createSVG(16,16,"0 0 21 16",[{tag:"path",attributes:{d:"M17.7226 12.2992C18.3148 12.5423 18.991 12.308 19.307 11.7578L19.3954 11.6031C20.434 9.78662 20.2705 7.18344 18.2308 5.85533C13.5438 2.80798 7.45789 2.80798 2.77085 5.85533C0.726753 7.18344 0.567646 9.78662 1.60627 11.6031L1.69466 11.7578C2.01066 12.3125 2.68908 12.5445 3.2769 12.3014L6.32204 11.0462C6.83914 10.8341 7.15515 10.3059 7.0999 9.74684L6.90986 7.85081C9.2346 7.06853 11.7759 7.10831 14.0785 7.97456L13.8973 9.74684C13.8399 10.3037 14.1581 10.8297 14.6752 11.0462L17.7226 12.2992Z",fill:"red"}}])},P=(e,t)=>{if("inactiveTimeout"===e){const e=t;return e?.enabled&&void 0!==e.duration&&e.duration>18e4&&(k.critical_warn(`Napster Companion API SDK: inactiveTimeout duration of ${e.duration}ms exceeds the recommended maximum of 180000ms. Setting maximum allowed value.`),delete e.duration),t}return t},x={enabled:!1,batchSize:10,flushInterval:5e3,enablePerformanceTracking:!0,enableErrorTracking:!0,enableUserInteractionTracking:!0};class V{constructor(e={}){Object.defineProperty(this,"config",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"eventQueue",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"performanceQueue",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"errorQueue",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"flushTimer",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"sessionId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"providers",{enumerable:!0,configurable:!0,writable:!0,value:[]}),this.config={...x,...e},this.sessionId=this.config.sessionId||this.generateSessionId(),this.setupProviders(),this.config.enabled&&(this.startFlushTimer(),this.setupErrorTracking(),this.setupPerformanceTracking())}setupProviders(){this.providers=[],this.config.providers&&(this.providers=[...this.config.providers]),this.config.provider&&this.providers.push(this.config.provider),0===this.providers.length&&this.providers.push({type:"custom"})}generateSessionId(){return`session_${Date.now()}_${Math.random().toString(36).substr(2,9)}`}startFlushTimer(){this.flushTimer&&clearInterval(this.flushTimer),this.flushTimer=setInterval(()=>{this.flush()},this.config.flushInterval)}setupErrorTracking(){this.config.enableErrorTracking&&(window.addEventListener("error",e=>{this.trackError(e.error,{source:"window.error",filename:e.filename,lineno:e.lineno,colno:e.colno})}),window.addEventListener("unhandledrejection",e=>{this.trackError(new Error(e.reason),{source:"unhandledrejection",reason:e.reason})}))}setupPerformanceTracking(){this.config.enablePerformanceTracking&&"undefined"!=typeof window&&"performance"in window&&window.addEventListener("load",()=>{setTimeout(()=>{const e=performance.getEntriesByType("navigation")[0];e&&(this.trackPerformance("page_load_time",e.loadEventEnd-e.fetchStart,"ms"),this.trackPerformance("dom_content_loaded",e.domContentLoadedEventEnd-e.fetchStart,"ms"),this.trackPerformance("first_paint",e.responseEnd-e.fetchStart,"ms"))},0)})}trackEvent(e,t){if(!this.config.enabled)return;const n={name:e,properties:t,timestamp:Date.now(),userId:this.config.userId,sessionId:this.sessionId};this.eventQueue.push(n),this.eventQueue.length>=(this.config.batchSize||10)&&this.flush()}trackPerformance(e,t,n,a){if(!this.config.enabled||!this.config.enablePerformanceTracking)return;const i={name:e,value:t,unit:n,timestamp:Date.now(),context:a};this.performanceQueue.push(i)}trackError(e,t){if(!this.config.enabled||!this.config.enableErrorTracking)return;const n={error:e,context:t,timestamp:Date.now(),userId:this.config.userId,sessionId:this.sessionId,stack:e.stack};this.errorQueue.push(n),this.flushErrors()}trackInteraction(e,t,n){this.config.enableUserInteractionTracking&&this.trackEvent("user_interaction",{action:e,target:t,...n})}flush(){this.flushEvents(),this.flushPerformance(),this.flushErrors()}flushEvents(){if(0===this.eventQueue.length)return;const e=[...this.eventQueue];this.eventQueue=[],this.sendData("events",e)}flushPerformance(){if(0===this.performanceQueue.length)return;const e=[...this.performanceQueue];this.performanceQueue=[],this.sendData("performance",e)}flushErrors(){if(0===this.errorQueue.length)return;const e=[...this.errorQueue];this.errorQueue=[],this.sendData("errors",e)}async sendData(e,t){const n=this.providers.map(n=>this.sendToProvider(n,e,t));await Promise.allSettled(n)}async sendToProvider(e,t,n){try{switch(e.type){case"google-analytics-4":await this.sendToGA4(e,n);break;case"mixpanel":await this.sendToMixpanel(e,n);break;case"segment":await this.sendToSegment(e,n);break;case"amplitude":await this.sendToAmplitude(e,n);break;case"posthog":await this.sendToPostHog(e,n);break;case"azure-insights":await this.sendToAzureInsights(e,n);break;default:await this.sendToCustomEndpoint(e,t,n)}}catch(t){k.critical_warn(`Failed to send data to ${e.type}:`,t)}}async sendToCustomEndpoint(e,t,n){const a=e.endpoint,i=e.apiKey;if(!a)return void("development"===process.env.NODE_ENV&&k.info(`Analytics [${t}]:`,n));const o=await fetch(`${a}/${t}`,{method:"POST",headers:{"Content-Type":"application/json",...i&&{Authorization:`Bearer ${i}`}},body:JSON.stringify({data:n,sessionId:this.sessionId,timestamp:Date.now()})});if(!o.ok)throw new Error(`HTTP ${o.status}`)}async sendToGA4(e,t){const n=e.measurementId||e.apiKey;if(!n)throw new Error("GA4 measurement ID required");const a=`https://www.google-analytics.com/mp/collect?measurement_id=${n}&api_secret=${e.apiKey||"default"}`,i=t.map(e=>({name:e.name,params:{...e.properties,session_id:this.sessionId}}));await fetch(a,{method:"POST",body:JSON.stringify({client_id:this.sessionId,user_id:this.config.userId,events:i})})}async sendToMixpanel(e,t){const n=e.projectToken||e.apiKey;if(!n)throw new Error("Mixpanel project token required");const a=e.endpoint||"https://api.mixpanel.com/batch",i=t.map(e=>{const t=e;return{event:t.name,properties:{token:n,distinct_id:this.config.userId||this.sessionId,time:t.timestamp||Date.now(),...t.properties}}});await fetch(a,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(i)})}async sendToSegment(e,t){const n=e.writeKey||e.apiKey;if(!n)throw new Error("Segment write key required");const a=e.endpoint||"https://api.segment.io/v1/batch",i=t.map(e=>({type:"track",userId:this.config.userId||this.sessionId,event:e.name,properties:e.properties,timestamp:new Date(e.timestamp||Date.now()).toISOString()}));await fetch(a,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Basic ${btoa(n+":")}`},body:JSON.stringify({batch:i})})}async sendToAmplitude(e,t){const n=e.apiKey;if(!n)throw new Error("Amplitude API key required");const a=e.endpoint||"https://api2.amplitude.com/2/httpapi",i=t.map(e=>({user_id:this.config.userId||this.sessionId,event_type:e.name,event_properties:e.properties,time:e.timestamp||Date.now()}));await fetch(a,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({api_key:n,events:i})})}async sendToPostHog(e,t){const n=e.apiKey,a=e.endpoint||"https://app.posthog.com";if(!n)throw new Error("PostHog API key required");const i=t.map(e=>({event:e.name,properties:{...e.properties,distinct_id:this.config.userId||this.sessionId},timestamp:new Date(e.timestamp||Date.now()).toISOString()}));await fetch(`${a}/batch/`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({api_key:n,batch:i})})}async sendToAzureInsights(e,t){const n=e.apiKey;if(!n)throw new Error("Azure Application Insights instrumentation key required");const a=e.endpoint||"https://dc.services.visualstudio.com/v2/track",i=t.map(e=>{const t=e;return{name:"Microsoft.ApplicationInsights.Event",time:new Date(t.timestamp||Date.now()).toISOString(),iKey:n,data:{baseType:"EventData",baseData:{name:t.name,properties:t.properties}}}});await fetch(a,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(i)})}updateConfig(e){this.config={...this.config,...e},this.setupProviders(),this.config.enabled&&!this.flushTimer?this.startFlushTimer():!this.config.enabled&&this.flushTimer&&(clearInterval(this.flushTimer),this.flushTimer=void 0)}destroy(){this.flushTimer&&clearInterval(this.flushTimer),this.flush()}}let F=null;const W=(e,t)=>{F?.trackEvent(e,t)},j=(e,t,n)=>{F?.trackInteraction(e,t,n)};function $(e,{content:t,placement:n="top"}){let a=!1,i=null,o=null;const r=e=>"left"===e?"start":"right"===e?"end":e,s=()=>{if(!i)return;const t=e.getBoundingClientRect(),a=i.getBoundingClientRect();let o=0,r=0;switch(n){case"top":o=t.top-a.height-8,r=t.left+(t.width-a.width)/2;break;case"bottom":o=t.bottom+8,r=t.left+(t.width-a.width)/2;break;case"left":o=t.top+(t.height-a.height)/2,r=t.left-a.width-8;break;case"right":o=t.top+(t.height-a.height)/2,r=t.right+8}i.style.top=`${o}px`,i.style.left=`${r}px`},c=()=>s(),d=()=>{if(a)return;const e=(()=>{if(i)return i;const e=document.createElement("div");e.className=`tooltip styled-tooltip bs-tooltip-${r(n)} show`,e.setAttribute("role","tooltip"),Object.assign(e.style,{position:"fixed",top:"0px",left:"0px",zIndex:String(2147483647),opacity:"0",visibility:"hidden",pointerEvents:"none",transition:"opacity 80ms ease"});const a=document.createElement("div");a.className="tooltip-arrow";const o=document.createElement("div");return o.className="tooltip-inner","string"==typeof t?o.textContent=t:o.appendChild(t),e.appendChild(a),e.appendChild(o),document.body.appendChild(e),i=e,e})();a=!0,s(),o=window.setTimeout(s,10),e.style.opacity="1",e.style.visibility="visible",window.addEventListener("scroll",c,!0),window.addEventListener("resize",c)},l=()=>{a&&(a=!1,null!=o&&(window.clearTimeout(o),o=null),i&&(i.style.opacity="0",i.style.visibility="hidden"),window.removeEventListener("scroll",c,!0),window.removeEventListener("resize",c))},u=()=>d(),p=()=>l();return e.addEventListener("mouseenter",u),e.addEventListener("mouseleave",p),e.matches?.(":hover")&&d(),{update:e=>{if(void 0!==e.content&&i){const t=i.querySelector(".tooltip-inner");t&&(t.innerHTML="","string"==typeof e.content?t.textContent=e.content:t.appendChild(e.content))}void 0!==e.placement&&(n=e.placement,i&&(i.className=`tooltip styled-tooltip bs-tooltip-${r(n)} show`)),a&&s()},show:d,hide:l,destroy:()=>{l(),e.removeEventListener("mouseenter",u),e.removeEventListener("mouseleave",p),i&&i.parentNode&&i.parentNode.removeChild(i),i=null}}}function U(e,t){const n=document.createElement(e);return t&&(n.className=t),n}var B,G,K,z,H,q,Q;!function(e){e.LOCAL_TIMEOUT="local_timeout",e.SERVER_WARNING="server_warning"}(B||(B={}));class J{constructor(e,t={}){Object.defineProperty(this,"overlayController",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"currentTrigger",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"isVisible",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"mountElement",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"callbacks",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.mountElement=e,this.callbacks=t}show(e){this.isVisible?k.warn("Inactive overlay already visible, ignoring show request"):(k.info(`Showing inactive overlay (trigger: ${e.type})`),this.currentTrigger=e,this.isVisible=!0,this.overlayController=function(e,t){const n={duration:t.duration??30,isInteractionNeeded:t.isInteractionNeeded??!1,message:t.message??"It looks like you've been inactive for a while. Would you like to continue this conversation?",onContinue:t.onContinue,onEnd:t.onEnd},a=document.createElement("div");a.className="np_companion-inactive-overlay";const i=document.createElement("div");i.className="np_companion-inactive-dialog";const o=document.createElement("p");o.className="np_companion-inactive-message",o.textContent=n.message;const r=document.createElement("div");r.className="np_companion-inactive-timer";const s=document.createElement("div");s.className="np_companion-timer-circle";const c=document.createElementNS("http://www.w3.org/2000/svg","svg");c.setAttribute("viewBox","0 0 36 36");const d=document.createElementNS("http://www.w3.org/2000/svg","path");d.setAttribute("d","M18 2.0845 a 15.9155 15.9155 0 0 1 0 31.831 a 15.9155 15.9155 0 0 1 0 -31.831"),d.setAttribute("fill","none"),d.setAttribute("stroke","rgba(255, 255, 255, 0.2)"),d.setAttribute("stroke-width","2");const l=document.createElementNS("http://www.w3.org/2000/svg","path");l.setAttribute("d","M18 2.0845 a 15.9155 15.9155 0 0 1 0 31.831 a 15.9155 15.9155 0 0 1 0 -31.831"),l.setAttribute("fill","none"),l.setAttribute("stroke","#fff"),l.setAttribute("stroke-width","2");const u=document.createElement("span");u.className="np_companion-timer-number",s.appendChild(c),c.appendChild(d),c.appendChild(l),s.appendChild(u),r.appendChild(s);const p=document.createElement("div");p.className="np_companion-inactive-buttons";const h=document.createElement("button");h.className="np_companion-end-button np_companion__d-none",h.textContent="End Conversation";let m=null;const f=e=>{e&&!m?(m=document.createElement("button"),m.className="np_companion-continue-button",m.textContent="Continue Talking",p.appendChild(m),m.addEventListener("click",n.onContinue)):!e&&m&&(m.removeEventListener("click",n.onContinue),m.parentNode&&m.parentNode.removeChild(m),m=null)};p.appendChild(h),f(n.isInteractionNeeded),i.appendChild(o),i.appendChild(r),i.appendChild(p),a.appendChild(i),e.appendChild(a);let v=Math.max(0,Math.floor(n.duration)),g=null;const C=()=>{u.textContent=String(v),l.setAttribute("stroke-dasharray",(n.duration>0?v/n.duration*100:0)+", 100")},b=()=>{if(v<=0)return E(),void n.onEnd();v-=1,C()},y=()=>{E(),C(),g=window.setInterval(b,1e3)},E=()=>{null!=g&&(window.clearInterval(g),g=null)};return h.addEventListener("click",()=>{E(),n.onEnd()}),y(),{update:e=>{if(void 0!==e.message&&(n.message=e.message,o.textContent=n.message),void 0!==e.isInteractionNeeded&&(n.isInteractionNeeded=!!e.isInteractionNeeded,f(n.isInteractionNeeded)),void 0!==e.duration){const t=Math.max(0,Math.floor(e.duration));n.duration=t,v=t,y()}e.onContinue&&(m&&(m.removeEventListener("click",n.onContinue),m.addEventListener("click",e.onContinue)),n.onContinue=e.onContinue),e.onEnd&&(n.onEnd=e.onEnd)},destroy:()=>{E(),h.removeEventListener("click",n.onEnd),m&&m.removeEventListener("click",n.onContinue),a.parentNode&&a.parentNode.removeChild(a)}}}(this.mountElement,{duration:e.duration,message:e.message,isInteractionNeeded:e.isInteractionNeeded,onContinue:()=>this.handleContinue(),onEnd:()=>this.handleEnd()}),this.callbacks.onShow?.(e))}hide(){this.isVisible&&(k.info("Hiding inactive overlay"),this.isVisible=!1,this.currentTrigger=null,this.overlayController&&(this.overlayController.destroy(),this.overlayController=null),this.callbacks.onHide?.())}isShowing(){return this.isVisible}getCurrentTrigger(){return this.currentTrigger}handleContinue(){k.info("User clicked continue on inactive overlay"),this.hide(),this.callbacks.onContinue?.()}handleEnd(){k.info("Inactive overlay countdown ended"),this.hide(),this.callbacks.onEnd?.()}destroy(){this.hide()}}!function(e){e.TALK_STATE_CHANGED="talk_state_changed",e.MESSAGE_RECEIVED="message_received",e.TRANSCRIPT="transcript",e.AUDIO_TRANSCRIPT_DELTA="response.audio_transcript.delta",e.AUDIO_TRANSCRIPT_DONE="response.audio_transcript.done",e.RESPONSE_DONE="response.done"}(G||(G={})),function(e){e.STARTED="started",e.ENDED="ended",e.CANCELED="canceled"}(K||(K={})),function(e){e.DELTA="delta",e.COMPLETED="completed"}(z||(z={})),function(e){e.USER="user",e.ASSISTANT="assistant"}(H||(H={})),function(e){e.SET_REMOTE_DESCRIPTION="set_remote_description",e.SET_LOCAL_DESCRIPTION="set_local_description",e.ADD_ICE_CANDIDATE="add_ice_candidate",e.ERROR="error"}(q||(q={})),function(e){e.SEND_QUESTION="send_question",e.CANCEL="cancel"}(Q||(Q={}));const Z={iceServers:[{urls:"stun:stun1.ciscape.com:3478"},{urls:"turn:stun1.ciscape.com:3478",username:"tcuser",credential:"dw4k_BR2f-Y4A-@aT7ip@Qzs"},{urls:"stun:129.146.43.226:3478"},{urls:"stun:stun.l.google.com:19302"},{urls:"stun:stun1.l.google.com:19302"},{urls:"turn:129.146.43.226:3478",username:"teamtime_turn",credential:"teamtime"}]};function Y(e,t){if(t)for(const n in t)try{const a=t[n];"string"!=typeof a&&"number"!=typeof a||(e.style[n]=a)}catch{k.warn(`Failed to apply style for key "${n}: ${t[n]}".`)}}function X(e,t,n){const a=[];return a.push("np_companion-align-middle"),e&&(a.push("np_companion-container-fixed"),a.push(`np_companion-${e}`),t&&a.push(`np_companion-view-${t}`)),n&&a.push(n),a.join(" ")}class ee{constructor(){Object.defineProperty(this,"version",{enumerable:!0,configurable:!0,writable:!0,value:"1.0.0-alpha.12"}),Object.defineProperty(this,"mountTarget",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"rootEl",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"embed",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"webrtcController",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"config",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"isInitialized",{enumerable:!0,configurable:!0,writable:!0,value:!1})}static getInstance(){return ee.instance||(ee.instance=new ee),ee.instance}renderApp(){this.mountTarget&&this.config&&(this.rootEl||(this.rootEl=document.createElement("div"),this.rootEl.id="np_companion-sdk-root",this.mountTarget.appendChild(this.rootEl)),this.rootEl.className=X(this.config.position,this.config.avatarStyle?.view,this.config.className),Y(this.rootEl,this.config.style),this.embed?this.embed.update({avatarStyle:this.config.avatarStyle,features:I.getState().app.features,onData:this.config.onData,onAvatarReady:this.config.onAvatarReady,onInactivityStatusChange:this.config.onInactivityStatusChange,onDestroy:()=>this.destroyInstance("ui_end"),onError:this.config.onError}):this.embed=function(e,t={}){const n=O.createDiv("np_companion-live-container np_companion-fade-in");e.appendChild(n);const a=function(e,t={}){const n=O.createDiv("np_companion-avatar"),a=O.createDiv(`np_companion-avatar-container np_companion-loader-${t.features?.showSDKLoader?.type??"spinner"}`);a.id="np_companion-avatar-container",t.avatarStyle?.view&&a.classList.add(`np_companion-view-${t.avatarStyle.view}`);const i=O.createDiv("loader-container"),o=O.createDiv("loader");i.appendChild(o);const r=O.createVideo({className:"np_companion-avatar-video",autoplay:!0,muted:!0,playsInline:!0}),s=O.createAudio({className:"np_companion-avatar-audio",autoplay:!0}),c=O.createCanvas({className:"np_companion-avatar-canvas",styles:{width:"100%",height:"100%",objectFit:"cover",position:"relative",zIndex:"1"}});t.features?.backgroundRemoval?.enabled&&"silhouette"===t.avatarStyle?.view?r.classList.add("np_companion__d-none"):c.classList.add("np_companion__d-none"),a.appendChild(i),a.appendChild(r),a.appendChild(s),a.appendChild(c);const d=O.createDiv(`${D.wrapper} np_companion-action-btn-container-view-${t.avatarStyle?.view}`),l=O.createDiv(`np_companion-disclaimer-text np_companion-disclaimer-view-${t.avatarStyle?.view}`);l.style.display="none";const u=O.createDiv(`np_companion-avatar-control-container np_companion-avatar-control-view-${t.avatarStyle?.view}`);u.appendChild(d),u.appendChild(l),n.appendChild(a),n.appendChild(u),e.appendChild(n);let m=null,f=(t.features?.backgroundRemoval?.enabled&&"silhouette"===t.avatarStyle?.view)??!1,v=null,g=null,C=!1,b=!1,y=!1,E=!0,w=null,_=null,S=null;const T=new J(n,{onContinue:()=>{K(),z()},onEnd:()=>{}});let N=null;const L=()=>{E||(E=!0,u.className=x(),null!=w&&window.clearTimeout(w))},P=()=>{null!=w&&window.clearTimeout(w),w=window.setTimeout(()=>{E=!1,u.className=x()},5e3)};function x(){return A(`np_companion-avatar-control-container np_companion-avatar-control-view-${t.avatarStyle?.view}`,{[D.collapse]:!E})}function V(e){if(!y)return;const n=t.avatarStyle?.borderWidth??("silhouette"!==t.avatarStyle?.view?"4px":void 0);n&&(a.style.borderWidth=n);const i=("silhouette"!==t.avatarStyle?.view?e?"#ec3e41":t.avatarStyle?.borderColor??"#C0C0C0":void 0)??t.avatarStyle?.borderColor;i&&(a.style.borderColor=i);const o=t.avatarStyle?.borderStyle??("silhouette"!==t.avatarStyle?.view?"solid":void 0);o&&(a.style.borderStyle=o)}function F(e){"round"===t.avatarStyle?.view&&(a.style.transform=`translate(-50%, ${e??352-u.offsetHeight-212-12+"px"})`)}function W(){const e=t.features?.disclaimer?.enabled??!1;l.style.display=e&&y?"-webkit-box":"none",_?.update({features:{disclaimer:{enabled:e}}});const n=t.features?.disclaimer?.text??"This is an AI avatar. Check important info.";t.features?.disclaimer?.color&&(l.style.color=t.features?.disclaimer?.color),l.textContent=n,y&&F(e?void 0:"8%")}function j(){y||!t.features?.showSDKLoader?.enabled?n.classList.add("np_companion-bg-transparent"):n.classList.remove("np_companion-bg-transparent")}function G(){t.features?.showSDKLoader?.bgColor&&n.style.setProperty("--np-loader-bg-color",t.features.showSDKLoader.bgColor),t.features?.showSDKLoader?.color&&n.style.setProperty("--np-loader-color",t.features.showSDKLoader.color)}function K(){S&&(k.timer("Resetting inactive timeout due to activity"),clearTimeout(S),S=null,I.dispatch(p(!1)),t.onInactivityStatusChange?.(!1))}function z(){const e=t.features?.inactiveTimeout;e?.enabled?(K(),S=setTimeout(()=>{k.timer(`Inactive timeout of ${e?.duration}ms reached, showing inactive overlay`),I.dispatch(p(!0)),t.onInactivityStatusChange?.(!0),m&&(m.getAudioTracks().forEach(e=>e.enabled=!1),_?.update({isMuted:!0}),V(!0)),T.isShowing()||T.show({type:B.LOCAL_TIMEOUT,duration:Math.min(e.countdown??30,60),message:void 0,isInteractionNeeded:!0})},e.duration)):(K(),T.isShowing()&&T.hide())}function H(){if(!_&&y){const e=!1;_=function(e,t){let n={...t},a=null,i=null,o=[],r=!1;const s=document.createElement("div");s.className=_();const c=U("div",D.container),d=U("div",A(D.questionBar,D.alignBetween)),l=U("div",D.left),u=U("div",D.iconButtonWithState(n.isMuted));u.appendChild(n.isMuted?M.micMuted():M.micUnmuted()),n.toggleMute&&u.addEventListener("click",()=>n.toggleMute?.());const p=U("div",D.middle),h=U("div",D.wave);S();const m=document.createElement("canvas");m.width=160,m.height=40,m.className=D.canvas,h.appendChild(m);const f=U("div",A(D.right,D.alignBetween)),v=U("div",A(D.iconButton(),D.stop)),g=function(e,t={}){let n={initialVolume:50,...t},a=n.initialVolume??50,i=!1,o=!1;const r=document.createElement("div");r.className="np_volume-control";const s=document.createElement("div");s.className="np_volume-slider-container";const c=document.createElement("div");c.className="np_volume-slider-track";const d=document.createElement("div");d.className="np_volume-slider-fill";const l=document.createElement("div");l.className="np_volume-slider-thumb",c.appendChild(d),c.appendChild(l),s.appendChild(c);const u=document.createElement("div");function p(){let e;u.innerHTML="",e=i||0===a?M.volumeMuted():M.volumeHigh(a||100),u.appendChild(e)}function h(){const e=a;d.style.height=`${e}%`,l.style.bottom=`${e}%`}function m(){o=!o,o?s.classList.add("np_volume-slider-visible"):s.classList.remove("np_volume-slider-visible")}function f(e){const t=c.getBoundingClientRect(),o=Math.max(0,Math.min(100,(t.bottom-e)/t.height*100));a=o,h(),i=0===a,i?u.classList.add("np_volume-muted"):u.classList.remove("np_volume-muted"),p(),n.onChange?.(a)}u.className=D.iconButton(),u.setAttribute("aria-label","Volume control"),p(),r.appendChild(s),r.appendChild(u),e.appendChild(r),u.addEventListener("click",e=>{e.stopPropagation(),i=!i,i?(n.initialVolume=a,a=0,h(),u.classList.add("np_volume-muted")):(a=n.initialVolume||50,h(),u.classList.remove("np_volume-muted")),p(),n.onMuteToggle?.(i)}),r.addEventListener("mouseenter",e=>{e.stopPropagation(),o||m()}),r.addEventListener("mouseleave",e=>{setTimeout(()=>{e.stopPropagation(),o&&m()},300)});let v=!1;return c.addEventListener("mousedown",e=>{v=!0,f(e.clientY),e.preventDefault()}),document.addEventListener("mousemove",e=>{v&&f(e.clientY)}),document.addEventListener("mouseup",()=>{v=!1}),l.addEventListener("mousedown",e=>{v=!0,e.preventDefault()}),c.addEventListener("touchstart",e=>{v=!0,f(e.touches[0].clientY),e.preventDefault()}),document.addEventListener("touchmove",e=>{v&&e.touches.length>0&&f(e.touches[0].clientY)}),document.addEventListener("touchend",()=>{v=!1}),document.addEventListener("click",e=>{o&&!r.contains(e.target)&&m()}),h(),{setVolume(e){a=Math.max(0,Math.min(100,e)),h(),p(),n.onChange?.(a)},getVolume:()=>a,toggleMute(){i=!i,i?u.classList.add("np_volume-muted"):u.classList.remove("np_volume-muted"),n.onMuteToggle?.(i)},isMuted:()=>i,update(e){n={...n,...e}},destroy(){r.remove()}}}(v,{initialVolume:50,onChange:e=>{n.onVolumeChange?.(e)},onMuteToggle:e=>{n.onVolumeChange?.(e?0:g.getVolume())}});g.setVolume(70);const C=U("div",D.iconButtonEnd());C.appendChild(M.end()),n.handleEnd&&C.addEventListener("click",()=>n.handleEnd?.()),l.appendChild(u),p.appendChild(h),f.appendChild(v),f.appendChild(C),d.appendChild(l),d.appendChild(f),c.appendChild(d),s.appendChild(c),e.appendChild(s);let b=null,y=null,E=null;function w(){if(!n.userMicrophoneStream)return;const e=new(window.AudioContext||window.webkitAudioContext);a=e.createAnalyser(),e.createMediaStreamSource(n.userMicrophoneStream).connect(a),function(e){if(!a)return;const t=m.getContext("2d");if(!t)return;a.fftSize=256;const n=new Uint8Array(a.frequencyBinCount),s=Math.floor(m.width/3);0===o.length&&(o=new Array(s).fill(0));let c=0;const d=()=>{if(t.clearRect(0,0,m.width,m.height),t.beginPath(),t.moveTo(0,m.height/2),t.lineTo(m.width,m.height/2),t.strokeStyle="#ffffff",t.stroke(),e)r=!1,o.fill(0),S();else{a.getByteFrequencyData(n);const e=6,i=3,s=n.reduce((e,t)=>e+t,0)/n.length/255*m.height*.8;o.shift(),o.push(s);let d=o.filter(t=>t>e).length>=i;d?c=30:c>0&&(c--,d=!0),r=d,S(),t.fillStyle="#ffffff";for(let e=0;e<o.length;e++){const n=3*e,a=o[e];t.fillRect(n,m.height/2-a/2,2,a),t.fillRect(n,m.height/2+a/2,2,-a)}}i=requestAnimationFrame(d)};d()}(!!n.isMuted)}function _(){return A(D.alignMiddle,`np_companion-avatar-${n.avatarStyle?.view}`)}function S(){h.style.filter=!n.isMuted&&r?"brightness(0) saturate(100%) invert(48%) sepia(93%) saturate(1720%) hue-rotate(346deg) brightness(101%) contrast(103%)":"none",h.style.transition="filter 0.3s ease",h.style.height="40px"}function T(){b?.destroy(),b=$(u,{content:n.isMuted?"Unmute":"Mute",placement:"top"}),y?.destroy(),y=null}function I(){for(u.className=D.iconButtonWithState(n.isMuted);u.firstChild;)u.removeChild(u.firstChild);u.appendChild(n.isMuted?M.micMuted():M.micUnmuted())}return b=$(u,{content:n.isMuted?"Unmute":"Mute",placement:"top"}),E=$(C,{content:"End Session",placement:"top"}),w(),{update(e){const t=n;n={...n,...e},s.className=_(),t.isMuted!==n.isMuted&&(I(),T()),t.isAvatarSpeaking!==n.isAvatarSpeaking&&(I(),T()),t.userMicrophoneStream===n.userMicrophoneStream&&t.selectedMicrophone===n.selectedMicrophone||(null!=i&&(cancelAnimationFrame(i),i=null),o=[],a=null,w()),S(),n.features?.disclaimer?.enabled?c.classList.remove("np_companion_disclaimer-disabled"):c.classList.add("np_companion_disclaimer-disabled")},destroy(){b?.destroy(),y?.destroy(),E?.destroy(),null!=i&&cancelAnimationFrame(i),s.parentNode&&s.parentNode.removeChild(s)}}}(d,{avatarStyle:t.avatarStyle,isMuted:e,isAvatarSpeaking:b,userMicrophoneStream:m,features:{waveform:{enabled:!1!==t.features?.waveform?.enabled}},onVolumeChange:e=>{s.volume=e/100},toggleMute:()=>{const t=!(I.getState().avatar.muted??e);I.dispatch(h(t)),m&&m.getAudioTracks().forEach(e=>e.enabled=!t),_?.update({isMuted:t}),V(t),K(),z()},onStopTalking:()=>{try{const e=I.getState().avatar.dataChannel;if(e&&"open"===e.readyState){const t={type:Q.CANCEL};k.avatar("stopping avatar"),e.send(JSON.stringify(t))}else k.critical_warn("Stopping avatar: Data channel not open")}catch(e){k.critical_error("Avatar","Stop: failed to send interrupt",e)}K(),z()},handleEnd:()=>{t.onDestroy?.()}})}}n.addEventListener("mouseenter",L),n.addEventListener("mousemove",L),n.addEventListener("mouseleave",P);const q=()=>{if(C)return;const e=c.getContext("2d",{willReadFrequently:!0});if(!e||!r||r.readyState<2)N=requestAnimationFrame(q);else{if(c.width=r.videoWidth,c.height=r.videoHeight,e.drawImage(r,0,0,c.width,c.height),f){const n=e.getImageData(0,0,c.width,c.height),a=R.process(n);e.putImageData(a,0,0),y||(t.onAvatarReady?.(!0),y=!0,V(),H(),j(),W(),z(),P())}N=requestAnimationFrame(q)}};W(),G(),j();const Z={updateStreams:({videoStream:e,audioStream:n,userMicrophoneStream:a})=>{e&&e instanceof MediaStream?v!==e&&(k.avatar("New video stream received:",{active:e.active,tracks:e.getTracks().length,videoTracks:e.getVideoTracks().length,id:e.id}),v=e,r.srcObject=e,r.play().then(()=>{f||y||(t.onAvatarReady?.(!0),y=!0,V(),H(),j(),W(),z(),F(),P())}).catch(e=>{k.error("Failed to play video stream",e),t.onError?.(e)}),e.addEventListener("inactive",()=>{k.avatar("Video stream became inactive")}),e.getTracks().forEach(e=>{e.addEventListener("ended",()=>{k.avatar("Video track ended:",e.kind)})}),f&&!N&&(N=requestAnimationFrame(q))):(v=null,r.srcObject=null),void 0!==n&&(n&&n instanceof MediaStream?g!==n&&(g=n,s.srcObject=n,s.play().catch(e=>{k.error("Failed to play audio stream",e),t.onError?.(e)})):(g=null,s.srcObject=null)),void 0!==a&&(m=a??null,_?.update({userMicrophoneStream:m}))},updateWaveform:e=>{H(),_?.update(e)},updateFeatures:e=>{t.features={...t.features||{},...e||{}},f=(t.features?.backgroundRemoval?.enabled&&"silhouette"===t.avatarStyle?.view)??!1,f?(r.classList.add("np_companion__d-none"),c.classList.remove("np_companion__d-none")):(r.classList.remove("np_companion__d-none"),c.classList.add("np_companion__d-none")),_?.update({features:{waveform:{enabled:!1!==t.features?.waveform?.enabled}}}),W(),G(),j(),z()},update:e=>{const n=t.avatarStyle?.view;Object.assign(t,e),e.features&&Z.updateFeatures(e.features),e.avatarStyle?.view&&e.avatarStyle.view!==n&&(n&&a.classList.remove(`np_companion-view-${n}`),a.classList.add(`np_companion-view-${e.avatarStyle.view}`),t.features&&Z.updateFeatures(t.features))},setAvatarReady:e=>{e||(y=!1,t.onAvatarReady?.(!1))},handleMessage:e=>{switch("undefined"!=typeof window&&window.parent&&window.parent.postMessage({type:"avatar-data-channel-message",event:e},"*"),e.event){case"avatar_state_changed":break;case"talk_state_changed":b="ended"!==e.data?.state&&"canceled"!==e.data?.state,_?.update({isAvatarSpeaking:b});break;case"message_received":{const{message:t}=e.data||{};if("completed"===t?.action&&"string"==typeof t.content&&t.role){K(),z();const e=T.getCurrentTrigger();e&&!e.isInteractionNeeded&&T.hide()}break}case"avatar_connection_warning":t.showAvatarInactiveOverlay&&(T.show({type:B.SERVER_WARNING,duration:e.data?.disconnect_after??30,message:"Avatar is disconnecting due to inactivity. Say something to keep it active.",isInteractionNeeded:!1}),m&&(m.getAudioTracks().forEach(e=>e.enabled=!0),_?.update({isMuted:!1}),V(!1)))}t.onData?t.onData(e):k.data("onData callback NOT called. Reason:",{onDataExists:!!t.onData,dataType:typeof e,dataIsNull:null===e})},destroy:e=>{C||(C=!0,n.removeEventListener("mousemove",L),n.removeEventListener("mouseenter",L),n.removeEventListener("mouseleave",P),null!=w&&window.clearTimeout(w),null!=N&&(cancelAnimationFrame(N),N=null),S&&(clearTimeout(S),S=null),_?.destroy(),_=null,T?.destroy(),n.parentNode&&n.parentNode.removeChild(n),y=!1,t.onAvatarReady?.(!1),e||t.onDestroy?.())}};return Z}(n,{avatarStyle:t.avatarStyle,showAvatarInactiveOverlay:!0,onData:t.onData,onDestroy:t.onDestroy,onError:t.onError,onInactivityStatusChange:t.onInactivityStatusChange,onAvatarReady:t.onAvatarReady,features:t.features});return{update:e=>{a.update({avatarStyle:e.avatarStyle??t.avatarStyle,onData:e.onData??t.onData,onDestroy:e.onDestroy??t.onDestroy,onError:e.onError??t.onError,onInactivityStatusChange:e.onInactivityStatusChange??t.onInactivityStatusChange,onAvatarReady:e.onAvatarReady??t.onAvatarReady,features:e.features??t.features}),Object.assign(t,e)},updateStreams:e=>{a.updateStreams(e)},handleMessage:e=>{a.handleMessage(e)},destroy:()=>{a.destroy(!0),n.parentNode===e&&e.removeChild(n),t.onDestroy?.()}}}(this.rootEl,{avatarStyle:this.config.avatarStyle,features:I.getState().app.features,onData:this.config.onData,onAvatarReady:this.config.onAvatarReady,onInactivityStatusChange:this.config.onInactivityStatusChange,onDestroy:()=>this.destroyInstance("ui_end"),onError:this.config.onError}),this.initializeWebRTC().catch(e=>{k.critical_error("Failed to establish WebRTC connection:",e),this.config?.onError?.(e)}))}async initializeWebRTC(){const e=I.getState().avatar.connectionToken;if(e&&!this.webrtcController){k.connection("Connecting WebRTC..."),this.webrtcController=function(e={}){const{currentAudioDeviceId:t,onChatMessage:n,onConnectionSuccess:a,onConnectionError:i,onStreams:s,onDataChannel:c,maxReconnectAttempts:d=3,reconnectInterval:l=2e3}=e;let p=null,h=null,v=null,g=null,C=null,b=null,y=null,E="disconnected",w=0,_=null,S=null,T=!0,N=null;function A(e,t){e&&e.readyState===WebSocket.OPEN?e.send(JSON.stringify(t)):k.critical_warn("WebRTC",`WS send skipped; state=${e?.readyState}`)}function D(e){N=e,i?.(e)}function O(e){E=e,k.webrtc(`Connection status changed to: ${e}`)}function R(){!T||!S||w>=d?w>=d&&D(new o("WebSocket connection failed after max retry attempts",{maxAttempts:d,lastAttempt:w})):(w+=1,O("reconnecting"),k.webrtc(`Attempting to reconnect (${w}/${d})...`),_=setTimeout(async()=>{try{if(!S)return;await L(S.connection.signalingEndpoint,S.connection.id,!0),!p&&S&&await M(S.token)}catch(e){k.error("WebRTC","Reconnection attempt failed:",e),w<d&&R()}},l))}async function L(e,t,n=!1){const i=`${e.replace(/\/$/,"")}/ws/connections/${t}/signaling`;h&&h.readyState===WebSocket.OPEN&&h.close();const r=new WebSocket(i);return h=r,await new Promise((e,t)=>{r.onopen=()=>{k.connection(n?"WebSocket reconnected":"WebSocket connected"),O("connected"),w=0,_&&(clearTimeout(_),_=null),e()},r.onclose=e=>{k.connection("WebSocket closed:",e),h=null,O("disconnected"),!e.wasClean&&T&&R(),t(new o("WebSocket connection closed",{code:e.code,reason:e.reason,wasClean:e.wasClean}))},r.onerror=e=>{h=null,O("disconnected");const n=new o("WebSocket connection error",{error:e,timestamp:(new Date).toISOString()});D(n),t(n)}}),a?.(),I.dispatch(m(void 0)),r}async function M(e){if(p&&"disconnected"!==E)k.warn("WebRTC","Connection already in progress, skipping...");else try{O("connecting"),N=null;const a=(e=>{try{const t=atob(e);return JSON.parse(t)}catch(e){return k.critical_error("decodeToBase64: Error decoding token",e),null}})(e);if(!a)throw new o("Failed to decode connection token",{token:e?"provided":"missing"});S={...a,token:e};const i=await L(a.connection.signalingEndpoint,a.connection.id),d=await async function(){k.webrtc("Create PeerConnection");const e=new RTCPeerConnection(Z);return p=e,e.addEventListener("connectionstatechange",()=>{"failed"===e.connectionState?(D(new o("WebRTC connection failed")),R()):"connected"===e.connectionState&&(O("connected"),w=0,_&&(clearTimeout(_),_=null))}),function(e){y=e.addTransceiver("audio",{direction:"sendrecv"});const t=e.addTransceiver("video",{direction:"recvonly"});k.webrtc("Added transceivers",{videoTransceiver:t,audioTransceiver:y});const a=e.createDataChannel("chat",{ordered:!0});b=a,I.dispatch(u(a)),c?.(a),a.onopen=()=>{k.webrtc("Data channel opened")},a.onclose=()=>{k.webrtc("Data channel closed")},a.onerror=e=>{k.critical_error("WebRTC",e),D(new r("Data channel error",{error:e}))},a.onmessage=e=>{try{const t=JSON.parse(e.data);k.data("Data channel message received:",t),n?.(t)}catch{n?.({event:"message_received",data:{message:{content:e.data,action:"completed"}}})}}}(e),e.ontrack=e=>{const t=e.streams[0];k.webrtc(`${e.track.kind} stream received`,{streamId:t?.id,trackId:e.track.id,videoTracks:t?.getVideoTracks().length,audioTracks:t?.getAudioTracks().length}),"video"===e.track.kind?(g=t,C=t):"audio"===e.track.kind&&(C=t,g||(g=t)),s?.({videoStream:g,audioStream:C})},e}();await async function(){try{k.webrtc("Setting up user media");const e=await navigator.mediaDevices.getUserMedia({audio:!t||{deviceId:{exact:t}},video:!1});if(v=e,y&&e.getAudioTracks().length>0){const t=e.getAudioTracks()[0];await y.sender.replaceTrack(t)}s?.({userMicrophoneStream:e})}catch(e){k.critical_warn("WebRTC",e),D(new o("Failed to access user media",{error:e,deviceId:t}))}}(),await async function(e,t){e.addEventListener("icecandidate",e=>{const n=e.candidate;n&&(k.webrtc("send ICE candidate"),A(t,{type:"add_ice_candidate",data:{candidate:n}}))}),e.addEventListener("negotiationneeded",()=>{k.warn("negotiationneeded (waiting for server offer)")}),k.webrtc("createOffer → setLocalDescription → set_remote_description");const n=await e.createOffer();await e.setLocalDescription(n),A(t,{type:"set_remote_description",data:n})}(d,i),i.onmessage=e=>async function(e,t,n){try{const a=JSON.parse(n.data);switch(a.type){case"set_remote_description":k.webrtc("Setting remote description"),await e.setRemoteDescription(a.data),await e.setLocalDescription(),A(t,{type:"set_local_description",data:e.localDescription});break;case"add_ice_candidate":a.data?.candidate&&await e.addIceCandidate(a.data.candidate);break;case"error":k.critical_error("WebRTC",a.data?.error),D(new r(a.data?.error||"Server error",{serverMessage:a.data})),e.close(),t.close();break;default:k.webrtc("Unknown message type:",a.type)}}catch(e){k.critical_error("WebRTC",e),D(new r("Failed to process WebSocket message",{originalError:e,rawMessage:n.data}))}}(d,i,e)}catch(e){const t=e;throw k.critical_error("WebRTC",t),D(t),O("disconnected"),t}}function P(){T=!1,_&&(clearTimeout(_),_=null),w=0;try{if(b)try{b.close()}catch{}if(h)try{h.readyState!==WebSocket.OPEN&&h.readyState!==WebSocket.CONNECTING||h.close(1e3,"Connection closed by client")}catch{}if(p)try{p.getSenders().forEach(e=>{e.track&&e.track.stop()}),p.close()}catch{}if(v)try{v.getTracks().forEach(e=>e.stop())}catch{}}catch(e){k.critical_warn("WebRTC",e)}finally{b=null,h=null,p=null,v=null,y=null,g=null,C=null,S=null,O("disconnected"),I.dispatch(f(void 0))}}return I.dispatch(f(P)),{startWithToken:M,close:P,forceReconnect:async function(){if(S){P(),T=!0,w=0;try{await M(S.token)}catch(e){throw D(e),e}}else D(new o("No connection data available for reconnect"))},getConnectionStatus:function(){return E},getReconnectAttempts:function(){return w},getError:function(){return N},updateAudioDevice:async function(e){if(y&&y.sender.track)try{const t=await navigator.mediaDevices.getUserMedia({audio:{deviceId:{exact:e}},video:!1}),n=t.getAudioTracks()[0];await y.sender.replaceTrack(n),v&&v.getTracks().forEach(e=>e.stop()),v=t,s?.({userMicrophoneStream:t}),k.webrtc(`Audio device updated to: ${e}`)}catch(t){k.critical_warn("WebRTC","Failed to update audio device:",t),D(new o("Failed to update audio device",{error:t,deviceId:e}))}else k.warn("WebRTC","No audio transceiver available for device update")}}}({maxReconnectAttempts:3,reconnectInterval:2e3,onStreams:e=>{this.embed?.updateStreams(e)},onChatMessage:e=>{this.embed?.handleMessage(e)},onConnectionError:e=>{k.critical_error("WebRTC connection error:",e),this.config?.onError?.(e)}});try{k.connection("Initializing WebRTC connection with token:",`${e.substring(0,50)}...`),await this.webrtcController.startWithToken(e),k.connection("WebRTC initialization completed with token")}catch(e){throw k.critical_error("SDK","Failed to Initialize WebRTC:",e),this.webrtcController=null,e}}}destroyWebRTC(){if(this.webrtcController){k.info("SDK","Destroying WebRTC controller");try{this.webrtcController.close()}catch(e){k.critical_error("SDK","Error closing WebRTC controller:",e)}this.webrtcController=null}}destroyInstance(e,t){if(!e)return void k.critical_warn("SDK","destroyInstance ignored (no reason)");W("sdk_destroyed",{reason:e}),t?.();const n=this.config?.onDestroy;if(S(null),I.dispatch(m(void 0)),I.dispatch(f(void 0)),I.dispatch(h(!1)),I.dispatch(y()),I.dispatch(E(void 0)),this.destroyWebRTC(),this.embed){try{this.embed.update({onDestroy:void 0}),this.embed.destroy()}catch(e){k.critical_error("Error during cleanup:",e)}this.embed=null}this.rootEl&&this.rootEl.parentNode&&this.rootEl.parentNode.removeChild(this.rootEl),this.rootEl=null,this.mountTarget=null,this.config=null,this.isInitialized=!1,n?.()}async init(e,t={}){try{if(this.isInitialized)throw new a("SDK is already initialized. Call destroy() first.",{code:s.ALREADY_INITIALIZED});t.analytics?.enabled&&(function(e){F=new V(e)}(t.analytics),W("sdk_init_started",{version:this.version,config:{position:t.position,features:Object.keys(t.features||{})}})),function(e){if(!e||"string"!=typeof e||""===e.trim())throw new i("Invalid connection token: expected non-empty string",{providedToken:typeof e,code:s.INVALID_TOKEN})}(e);const n={avatarStyle:{view:"round"},position:c.BOTTOM_RIGHT,...t};this.config=n,I.dispatch(m(e)),I.dispatch(h(!1)),I.dispatch(w(n.debug)),this.config.features&&Object.entries(this.config.features).forEach(([e,t])=>{const n=P(e,t);I.dispatch(b({feature:e,config:n}))}),S(e=>{try{this.embed&&this.embed.update({features:e})}catch(e){k.critical_error("Unable to update features",e)}this.config?.onFeaturesUpdate?.(e)});const o=function(e){if(!e)return document.body;if("string"==typeof e){const t=document.querySelector(e);return t instanceof HTMLElement?t:(k.warn(`mountContainer should be a valid CSS selector. Provided selector "${e}" is invalid or did not match any elements. Defaulting to document.body.`),document.body)}return e instanceof HTMLElement?e:document.body}(this.config.mountContainer??void 0);return this.mountTarget=o,this.isInitialized=!0,this.renderApp(),this.config.onReady?.(),W("sdk_init_completed",{version:this.version,initTime:Date.now()}),this.createInstanceMethods()}catch(n){const a=d.handle(n,{method:"init",tokenProvided:!!e,config:t});throw t.onError?.(a),a}}createInstanceMethods(){return{showAvatar:()=>{const e=document.getElementById("np_companion-avatar-container");e&&(e.style.display="block",j("show","avatar_widget"))},hideAvatar:()=>{const e=document.getElementById("np_companion-avatar-container");e&&(e.style.display="none",j("hide","avatar_widget"))},avatarIsVisible:()=>{const e=document.getElementById("np_companion-avatar-container");return!!e&&"none"!==e.style.display},destroy:()=>{const{closeConnectionHandler:e}=I.getState().avatar;this.destroyInstance("api",e)},updateStyles:e=>{this.config&&(this.config.style={...this.config.style??{},...e??{}},this.rootEl&&Y(this.rootEl,this.config.style))},setPosition:e=>{if(this.config&&(this.config.position=e,I.dispatch?.(E(e)),this.rootEl)){const t=X(e,this.config.avatarStyle?.view,this.config.className);this.rootEl.className=t}},clearPosition:()=>{this.config&&(I.dispatch?.(E(void 0)),this.config.position=void 0,this.rootEl&&(this.rootEl.className=X(void 0,this.config.avatarStyle?.view,this.config.className)))},enableFeature:e=>{I.dispatch?.(b({feature:e,config:{enabled:!0}})),"disclaimer"===e&&this.rootEl&&this.rootEl.classList.remove("np_companion_disclaimer-disabled")},disableFeature:e=>{I.dispatch?.(b({feature:e,config:{enabled:!1}})),"disclaimer"===e&&this.rootEl&&this.rootEl.classList.add("np_companion_disclaimer-disabled")},updateFeatureConfig:(e,t)=>{const n=P(e,t);I.dispatch?.(b({feature:e,config:n})),"disclaimer"===e&&this.rootEl&&(n?.enabled?this.rootEl.classList.remove("np_companion_disclaimer-disabled"):this.rootEl.classList.add("np_companion_disclaimer-disabled"))},updateAvatarStyle:e=>{if(this.config){if(this.config.avatarStyle={view:"round",...this.config.avatarStyle,...e},e.view&&this.rootEl){const t=X(this.config.position,e.view,this.config.className);this.rootEl.className=t}this.embed&&this.embed.update({avatarStyle:this.config.avatarStyle})}},sendQuestion:e=>{const{dataChannel:t,stopInteraction:n}=I.getState().avatar;t&&"open"===t.readyState&&!n?t.send(JSON.stringify({type:"send_question",data:e})):k.critical_warn("Data channel not available or not open")}}}}Object.defineProperty(ee,"instance",{enumerable:!0,configurable:!0,writable:!0,value:null});const te=ee.getInstance();"undefined"!=typeof window&&(window.napsterCompanionApiSDK=te);export{te as NapsterCompanionApiSdk,c as Position,te as default};
1
+ import{createSlice as e,configureStore as t}from"@reduxjs/toolkit";class n extends Error{constructor(e,t,n){super(e),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"timestamp",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"context",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name="SDKError",this.code=t,this.timestamp=new Date,this.context=n,Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,message:this.message,code:this.code,timestamp:this.timestamp.toISOString(),context:this.context,stack:this.stack}}}class a extends n{constructor(e,t){super(e,"INITIALIZATION_ERROR",t),this.name="InitializationError"}}class i extends n{constructor(e,t){super(e,"TOKEN_ERROR",t),this.name="TokenError"}}class o extends n{constructor(e,t){super(e,"CONNECTION_ERROR",t),this.name="ConnectionError"}}class r extends n{constructor(e,t){super(e,"WEBRTC_ERROR",t),this.name="WebRTCError"}}var s,c;!function(e){e.ALREADY_INITIALIZED="ALREADY_INITIALIZED",e.INVALID_TOKEN="INVALID_TOKEN",e.REACT_VERSION_UNSUPPORTED="REACT_VERSION_UNSUPPORTED",e.CONTAINER_NOT_FOUND="CONTAINER_NOT_FOUND",e.CONNECTION_FAILED="CONNECTION_FAILED",e.TOKEN_GENERATION_FAILED="TOKEN_GENERATION_FAILED",e.MISSING_CREDENTIALS="MISSING_CREDENTIALS",e.WEBRTC_NOT_SUPPORTED="WEBRTC_NOT_SUPPORTED",e.PEER_CONNECTION_FAILED="PEER_CONNECTION_FAILED",e.DATA_CHANNEL_ERROR="DATA_CHANNEL_ERROR",e.API_REQUEST_FAILED="API_REQUEST_FAILED",e.INVALID_RESPONSE="INVALID_RESPONSE",e.RATE_LIMITED="RATE_LIMITED",e.INVALID_CONFIGURATION="INVALID_CONFIGURATION",e.MISSING_REQUIRED_CONFIG="MISSING_REQUIRED_CONFIG",e.FEATURE_NOT_SUPPORTED="FEATURE_NOT_SUPPORTED",e.FEATURE_DISABLED="FEATURE_DISABLED",e.MEDIA_ACCESS_DENIED="MEDIA_ACCESS_DENIED",e.MEDIA_DEVICE_ERROR="MEDIA_DEVICE_ERROR",e.VIDEO_LOAD_ERROR="VIDEO_LOAD_ERROR"}(s||(s={}));class d{static setErrorHandler(e){this.onError=e}static handle(e,t){let a;return function(e){return e instanceof n}(e)?(a=e,t&&(a.context={...a.context,...t})):a=e instanceof Error?new n(e.message,"UNKNOWN_ERROR",{originalError:e.name,...t}):new n("string"==typeof e?e:"Unknown error occurred","UNKNOWN_ERROR",{originalError:e,...t}),this.onError?.(a),a}}!function(e){e.BOTTOM_RIGHT="bottom-right",e.BOTTOM_CENTER="bottom-center",e.BOTTOM_LEFT="bottom-left",e.TOP_RIGHT="top-right",e.TOP_CENTER="top-center",e.TOP_LEFT="top-left",e.CENTER="center"}(c||(c={}));const l=e({name:"avatar",initialState:{avatarReady:!1,dataChannel:null,stopInteraction:!1,muted:!1,transcript:void 0,customVoiceId:void 0,defaultVoiceId:void 0,connectionToken:void 0,companionId:void 0,closeConnectionHandler:void 0},reducers:{setSessionId:(e,t)=>{e.sessionId=t.payload},setAvatarReady:(e,t)=>{e.avatarReady=t.payload},setDataChannel:(e,t)=>{e.dataChannel=t.payload},setAvatarId:(e,t)=>{e.avatarId=t.payload},setVideoId:(e,t)=>{e.videoId=t.payload},setStopInteraction:(e,t)=>{e.stopInteraction=t.payload},setMuted:(e,t)=>{e.muted=t.payload},addTranscript:(e,t)=>{e.transcript=t.payload},setCustomVoiceId:(e,t)=>{e.customVoiceId=t.payload},setDefaultVoiceId:(e,t)=>{e.defaultVoiceId=t.payload},setConnectionToken:(e,t)=>{e.connectionToken=t.payload},setCloseConnectionHandler:(e,t)=>{e.closeConnectionHandler=t.payload}}}),{setDataChannel:u,setStopInteraction:p,setMuted:h,setConnectionToken:m,setCloseConnectionHandler:f}=l.actions,v=l.reducer,g={features:{backgroundRemoval:{enabled:!0},waveform:{enabled:!0,color:"#ffffff"},inactiveTimeout:{enabled:!0,duration:6e4,countdown:30},disclaimer:{enabled:!0,text:"This is an AI avatar. Check important info."},showSDKLoader:{enabled:!0,bgColor:"rgb(222 222 222 / 60%)",color:"#585858ff",type:"spinner"}},position:void 0,showExperience:!1,debugMode:!1},C=e({name:"app",initialState:g,reducers:{setFeatures:(e,t)=>{const{feature:n,config:a}=t.payload,i=e.features[n];e.features[n]={...i,...a,enabled:a?.enabled??!!i?.enabled}},resetFeatures:e=>{e.features=g.features},setPosition:(e,t)=>{e.position=t.payload},setShowExperience:(e,t)=>{e.showExperience=t.payload},setDebugMode:(e,t)=>{e.debugMode=t.payload}}}),{setFeatures:b,resetFeatures:y,setPosition:E,setDebugMode:w}=C.actions;let _=null;const S=e=>{_=e},T=e=>t=>n=>{const a=e.getState().app.features,i=t(n),o=e.getState().app.features;return _&&a!==o&&JSON.stringify(a)!==JSON.stringify(o)&&_(o),i},I=t({reducer:{avatar:v,app:C.reducer},middleware:e=>e({serializableCheck:!1}).concat(T)});var N;!function(e){e.INFO="info",e.WARN="warn",e.ERROR="error",e.DEBUG="debug"}(N||(N={}));const k=new class{constructor(){Object.defineProperty(this,"prefix",{enumerable:!0,configurable:!0,writable:!0,value:"[Napster SDK]"})}isDebugEnabled(){try{return I.getState().app.debugMode||!1}catch{return!1}}log(e,...t){if(!this.isDebugEnabled())return;const n=[this.prefix,...t];switch(e){case N.INFO:console.info(...n);break;case N.WARN:console.warn(...n);break;case N.ERROR:console.error(...n);break;case N.DEBUG:console.debug(...n)}}info(...e){this.log(N.INFO,"ℹ️",...e)}debug(...e){this.log(N.DEBUG,"🐞",...e)}warn(...e){this.log(N.WARN,"⚠️",...e)}error(...e){this.log(N.ERROR,"❌",...e)}critical_warn(...e){console.warn(this.prefix,"⚠️",...e)}critical_error(...e){console.error(this.prefix,"❌",...e)}webrtc(...e){this.log(N.INFO,"📡 WebRTC:",...e)}avatar(...e){this.log(N.INFO,"🎭 Avatar:",...e)}connection(...e){this.log(N.INFO,"🔌 Connection:",...e)}features(...e){this.log(N.INFO,"🔄 Features:",...e)}data(...e){this.log(N.INFO,"📨 Data:",...e)}timer(...e){this.log(N.INFO,"⏱️ Timer:",...e)}cleanup(...e){this.log(N.INFO,"🗑️ Cleanup:",...e)}};function A(...e){const t=[];for(const n of e)if(n)if("string"==typeof n||"number"==typeof n)t.push(String(n));else if(Array.isArray(n)){const e=A(...n);e&&t.push(e)}else if("object"==typeof n)for(const[e,a]of Object.entries(n))a&&t.push(e);return t.join(" ")}const D={icon:"np_companion-action-btn-container-icon",persistFillColor:"np_companion-persist-fill-color",alignMiddle:"np_companion-align-middle",alignBetween:"np_companion-align-between",darkGreyBg:"np_companion-dark-grey-bg",callEnd:"np_companion-action-btn-container-call-end",container:"np_companion-action-btn-container-container",wrapper:"np_companion-action-btn-container-wrapper",canvas:"np_companion-action-btn-container-canvas",controls:"np_companion-action-btn-container-controls",left:"np_companion-action-btn-container-left",middle:"np_companion-action-btn-container-middle",right:"np_companion-action-btn-container-right",wave:"np_companion-action-btn-container-wave",stop:"np_companion-action-btn-container-stop",questionBar:"np_companion-chat-question-bar-container",muted:"muted",hidden:"np_companion-hidden",expanded:"np_companion-action-btn-container-expanded",collapse:"np_companion-action-btn-container-collapse",mobileMode:"np_companion-mobile-mode",displayNone:"np_companion__d-none",iconButton:()=>A(D.icon,D.alignMiddle,D.darkGreyBg),iconButtonEnd:()=>A(D.icon,D.alignMiddle,D.darkGreyBg,D.callEnd),iconButtonWithState:e=>A(D.icon,D.alignMiddle,D.darkGreyBg,{[D.muted]:e})};class O{static createElement(e,t){const n=document.createElement(e);return t?.className&&(n.className=t.className),t?.id&&(n.id=t.id),t?.attributes&&Object.entries(t.attributes).forEach(([e,t])=>{n.setAttribute(e,t)}),t?.styles&&Object.assign(n.style,t.styles),n}static createVideo(e){const t=this.createElement("video",{className:e.className});return t.autoplay=e.autoplay??!1,t.muted=e.muted??!1,t.loop=e.loop??!1,t.playsInline=e.playsInline??!1,e.crossOrigin&&(t.crossOrigin=e.crossOrigin),e.poster&&(t.poster=e.poster),e.src&&(t.src=e.src),t}static createAudio(e){const t=this.createElement("audio",{className:e.className});return t.autoplay=e.autoplay??!1,t}static createCanvas(e){const t=this.createElement("canvas",{className:e.className,styles:e.styles});return void 0!==e.width&&(t.width=e.width),void 0!==e.height&&(t.height=e.height),t}static createButton(e){const t=this.createElement("button",{className:e.className,attributes:e.attributes});return e.textContent&&(t.textContent=e.textContent),e.onClick&&t.addEventListener("click",e.onClick),t}static createDiv(e){return this.createElement("div",{className:e})}}class R{static process(e){const t=e.data;return this.hasGreenScreen(t)?(this.removeGreenScreen(t),e):e}static hasGreenScreen(e){for(let t=0;t<e.length;t+=4)if(this.isGreenPixel(e[t],e[t+1],e[t+2]))return!0;return!1}static isGreenPixel(e,t,n){return e>=0&&e<=120&&t>=150&&t<=255&&n>=0&&n<=120}static removeGreenScreen(e){for(let t=0;t<e.length;t+=4){const n=e[t],a=e[t+1],i=e[t+2];this.isGreenPixel(n,a,i)?e[t+3]=0:this.reduceGreenSpill(e,t,n,a,i)}}static reduceGreenSpill(e,t,n,a,i){const o=a-Math.max(n,i);if(o>0){const r=.5*o;e[t]=Math.min(255,n+.8*r),e[t+2]=Math.min(255,i+.8*r),e[t+1]=Math.max(0,a-r)}}}const L=new class{constructor(){Object.defineProperty(this,"svgNS",{enumerable:!0,configurable:!0,writable:!0,value:"http://www.w3.org/2000/svg"})}createElement(e){const t=document.createElementNS(this.svgNS,e.tag);return e.attributes&&Object.entries(e.attributes).forEach(([e,n])=>{t.setAttribute(e,String(n))}),e.textContent&&(t.textContent=e.textContent),e.children&&e.children.forEach(e=>{const n=this.createElement(e);t.appendChild(n)}),t}createSVG(e,t,n,a,i){const o=document.createElementNS(this.svgNS,"svg");return o.setAttribute("width",String(e)),o.setAttribute("height",String(t)),o.setAttribute("viewBox",n),o.setAttribute("fill","none"),o.setAttribute("xmlns",this.svgNS),i&&o.setAttribute("class",i),a.forEach(e=>{const t=this.createElement(e);o.appendChild(t)}),o}},M={micUnmuted:()=>L.createSVG(17,17,"0 0 17 17",[{tag:"g",attributes:{"clip-path":"url(#clip0_655_3824)"},children:[{tag:"path",attributes:{d:"M8.67241 11.8448C9.49524 11.844 10.2841 11.5167 10.8659 10.9349C11.4478 10.3531 11.775 9.5642 11.7759 8.74138V4.60345C11.7759 3.78036 11.4489 2.99099 10.8669 2.40898C10.2849 1.82697 9.4955 1.5 8.67241 1.5C7.84933 1.5 7.05995 1.82697 6.47794 2.40898C5.89594 2.99099 5.56897 3.78036 5.56897 4.60345V8.74138C5.56982 9.5642 5.89707 10.3531 6.47889 10.9349C7.06071 11.5167 7.84959 11.844 8.67241 11.8448ZM6.60345 4.60345C6.60345 4.05472 6.82143 3.52847 7.20943 3.14047C7.59744 2.75246 8.12369 2.53448 8.67241 2.53448C9.22114 2.53448 9.74739 2.75246 10.1354 3.14047C10.5234 3.52847 10.7414 4.05472 10.7414 4.60345V8.74138C10.7414 9.2901 10.5234 9.81635 10.1354 10.2044C9.74739 10.5924 9.22114 10.8103 8.67241 10.8103C8.12369 10.8103 7.59744 10.5924 7.20943 10.2044C6.82143 9.81635 6.60345 9.2901 6.60345 8.74138V4.60345ZM9.18965 13.8879V15.9828C9.18965 16.1199 9.13516 16.2515 9.03816 16.3485C8.94116 16.4455 8.80959 16.5 8.67241 16.5C8.53523 16.5 8.40367 16.4455 8.30667 16.3485C8.20967 16.2515 8.15517 16.1199 8.15517 15.9828V13.8879C6.87994 13.7582 5.69812 13.1601 4.83826 12.2095C3.9784 11.2589 3.50158 10.0232 3.5 8.74138C3.5 8.6042 3.5545 8.47264 3.6515 8.37563C3.7485 8.27863 3.88006 8.22414 4.01724 8.22414C4.15442 8.22414 4.28598 8.27863 4.38299 8.37563C4.47999 8.47264 4.53448 8.6042 4.53448 8.74138C4.53448 9.83883 4.97044 10.8913 5.74645 11.6673C6.52247 12.4434 7.57497 12.8793 8.67241 12.8793C9.76986 12.8793 10.8224 12.4434 11.5984 11.6673C12.3744 10.8913 12.8103 9.83883 12.8103 8.74138C12.8103 8.6042 12.8648 8.47264 12.9618 8.37563C13.0588 8.27863 13.1904 8.22414 13.3276 8.22414C13.4648 8.22414 13.5963 8.27863 13.6933 8.37563C13.7903 8.47264 13.8448 8.6042 13.8448 8.74138C13.8433 10.0232 13.3664 11.2589 12.5066 12.2095C11.6467 13.1601 10.4649 13.7582 9.18965 13.8879Z",fill:"white"}}]},{tag:"defs",children:[{tag:"clipPath",attributes:{id:"clip0_655_3824"},children:[{tag:"rect",attributes:{width:"16",height:"16",fill:"white",transform:"translate(0.5 0.5)"}}]}]}],"np_companion-mic-unmuted"),micMuted:()=>L.createSVG(22,22,"0 0 17 18",[{tag:"g",attributes:{"clip-path":"url(#clip0_655_4192)"},children:[{tag:"path",attributes:{d:"M14.2432 14.6L3.89604 3.21808C3.80327 3.11843 3.67498 3.05936 3.53896 3.05368C3.40294 3.048 3.27016 3.09616 3.16941 3.18772C3.06866 3.27928 3.00806 3.40686 3.00075 3.5428C2.99343 3.67874 3.04 3.81208 3.13034 3.91392L5.58263 6.61131V8.7396C5.58251 9.26661 5.71656 9.78497 5.97216 10.2458C6.22776 10.7067 6.59649 11.0949 7.04361 11.3739C7.49073 11.6529 8.00151 11.8134 8.52782 11.8404C9.05414 11.8674 9.57867 11.7599 10.052 11.5282L10.7698 12.3171C10.138 12.6868 9.41878 12.8806 8.68679 12.8785C7.58946 12.8773 6.53741 12.4408 5.76148 11.6649C4.98555 10.889 4.54911 9.83693 4.54791 8.7396C4.54791 8.60239 4.4934 8.47079 4.39638 8.37377C4.29935 8.27675 4.16776 8.22224 4.03055 8.22224C3.89334 8.22224 3.76174 8.27675 3.66472 8.37377C3.5677 8.47079 3.51319 8.60239 3.51319 8.7396C3.51476 10.0217 3.9917 11.2577 4.85176 12.2085C5.71182 13.1594 6.8939 13.7575 8.16943 13.8873V15.9826C8.16943 16.1199 8.22394 16.2514 8.32096 16.3485C8.41798 16.4455 8.54958 16.5 8.68679 16.5C8.824 16.5 8.95559 16.4455 9.05262 16.3485C9.14964 16.2514 9.20415 16.1199 9.20415 15.9826V13.8867C10.0143 13.8085 10.794 13.5376 11.4779 13.0964L13.4775 15.2952C13.523 15.3464 13.5781 15.3881 13.6398 15.4178C13.7015 15.4476 13.7684 15.4648 13.8368 15.4685C13.9051 15.4722 13.9735 15.4622 14.038 15.4393C14.1025 15.4163 14.1618 15.3808 14.2125 15.3347C14.2632 15.2887 14.3042 15.2331 14.3332 15.171C14.3622 15.109 14.3786 15.0419 14.3815 14.9735C14.3843 14.9051 14.3736 14.8368 14.3499 14.7725C14.3261 14.7083 14.2899 14.6495 14.2432 14.5993V14.6ZM8.68679 10.809C8.13794 10.809 7.61157 10.591 7.22347 10.2029C6.83538 9.81482 6.61735 9.28845 6.61735 8.7396V7.7495L9.3115 10.7127C9.10943 10.7766 8.89873 10.8091 8.68679 10.809ZM12.4066 10.5562C12.6841 9.99093 12.8275 9.36929 12.8257 8.7396C12.8257 8.60239 12.8802 8.47079 12.9772 8.37377C13.0742 8.27675 13.2058 8.22224 13.343 8.22224C13.4802 8.22224 13.6118 8.27675 13.7089 8.37377C13.8059 8.47079 13.8604 8.60239 13.8604 8.7396C13.8625 9.52693 13.6831 10.3041 13.3359 11.0108C13.2934 11.0979 13.2273 11.1713 13.145 11.2226C13.0628 11.274 12.9679 11.3012 12.8709 11.3012C12.7922 11.3013 12.7145 11.2831 12.6439 11.2481C12.5207 11.1878 12.4265 11.0811 12.382 10.9513C12.3375 10.8215 12.3463 10.6794 12.4066 10.5562ZM5.84131 3.36358C6.12624 2.71004 6.62746 2.1745 7.26073 1.84696C7.894 1.51943 8.62071 1.41987 9.31874 1.56501C10.0168 1.71015 10.6435 2.09116 11.0938 2.64398C11.544 3.19681 11.7902 3.88776 11.7909 4.60072V8.7396C11.7908 8.8476 11.7852 8.95552 11.7741 9.06295C11.7608 9.19066 11.7005 9.30885 11.6049 9.39455C11.5092 9.48025 11.3852 9.52733 11.2568 9.52663C11.2387 9.52757 11.2205 9.52757 11.2025 9.52663C11.066 9.51229 10.9409 9.44435 10.8545 9.33775C10.7682 9.23115 10.7277 9.09462 10.742 8.95818C10.7491 8.88705 10.753 8.81332 10.753 8.74089V4.60072C10.7516 4.12605 10.5871 3.66628 10.2871 3.29848C9.98701 2.93069 9.56963 2.67722 9.10491 2.58058C8.64018 2.48393 8.15636 2.54998 7.73454 2.76766C7.31273 2.98534 6.97857 3.34141 6.78808 3.77618C6.7639 3.84253 6.72639 3.90322 6.67786 3.95452C6.62934 4.00583 6.57082 4.04665 6.50592 4.07449C6.44102 4.10232 6.37111 4.11658 6.30049 4.11637C6.22987 4.11617 6.16005 4.10151 6.09531 4.07329C6.03057 4.04508 5.9723 4.00392 5.92407 3.95233C5.87584 3.90075 5.83869 3.83983 5.81489 3.77335C5.7911 3.70686 5.78117 3.6362 5.78571 3.56573C5.79025 3.49526 5.80917 3.42646 5.84131 3.36358Z",fill:"white"}}]},{tag:"defs",children:[{tag:"clipPath",attributes:{id:"clip0_655_4192"},children:[{tag:"rect",attributes:{width:"16",height:"16",fill:"white",transform:"translate(0.5 0.5)"}}]}]}],"tc-mic-muted"),stop:()=>L.createSVG(20,20,"0 0 32 32",[{tag:"path",attributes:{d:"M5.92 24.096q0 0.832 0.576 1.408t1.44 0.608h16.128q0.832 0 1.44-0.608t0.576-1.408v-16.16q0-0.832-0.576-1.44t-1.44-0.576h-16.128q-0.832 0-1.44 0.576t-0.576 1.44v16.16z",fill:"#ffffff"}}]),volumeHigh(e){const t=[{tag:"path",attributes:{d:"M80 416L128 416L262.1 535.2C268.5 540.9 276.7 544 285.2 544C304.4 544 320 528.4 320 509.2L320 130.8C320 111.6 304.4 96 285.2 96C276.7 96 268.5 99.1 262.1 104.8L128 224L80 224C53.5 224 32 245.5 32 272L32 368C32 394.5 53.5 416 80 416z",fill:"#ffffff"}}];return e>0&&t.push({tag:"path",attributes:{d:"M412.6 245.5C402.3 237.1 387.2 238.7 378.8 249C370.4 259.3 372 274.4 382.3 282.8C393.1 291.6 400 305 400 320C400 335 393.1 348.4 382.3 357.3C372 365.7 370.5 380.8 378.8 391.1C387.1 401.4 402.3 402.9 412.6 394.6C434.1 376.9 448 350.1 448 320C448 289.9 434.1 263.1 412.6 245.5z",fill:"#ffffff"}}),e>=25&&t.push({tag:"path",attributes:{d:"M473.1 171C462.8 162.6 447.7 164.2 439.3 174.5C430.9 184.8 432.5 199.9 442.8 208.3C475.3 234.7 496 274.9 496 320C496 365.1 475.3 405.3 442.8 431.8C432.5 440.2 431 455.3 439.3 465.6C447.6 475.9 462.8 477.4 473.1 469.1C516.3 433.9 544 380.2 544 320.1C544 260 516.3 206.3 473.1 171.1z",fill:"#ffffff"}}),e>=75&&t.push({tag:"path",attributes:{d:"M533.6 96.5C523.3 88.1 508.2 89.7 499.8 100C491.4 110.3 493 125.4 503.3 133.8C557.5 177.8 592 244.8 592 320C592 395.2 557.5 462.2 503.3 506.3C493 514.7 491.5 529.8 499.8 540.1C508.1 550.4 523.3 551.9 533.6 543.6C598.5 490.7 640 410.2 640 320C640 229.8 598.5 149.2 533.6 96.5z",fill:"#ffffff"}}),L.createSVG(16,16,"0 0 640 640",t)},volumeMuted:()=>L.createSVG(16,16,"0 0 640 640",[{tag:"path",attributes:{d:"M80 416L128 416L262.1 535.2C268.5 540.9 276.7 544 285.2 544C304.4 544 320 528.4 320 509.2L320 130.8C320 111.6 304.4 96 285.2 96C276.7 96 268.5 99.1 262.1 104.8L128 224L80 224C53.5 224 32 245.5 32 272L32 368C32 394.5 53.5 416 80 416zM399 239C389.6 248.4 389.6 263.6 399 272.9L446 319.9L399 366.9C389.6 376.3 389.6 391.5 399 400.8C408.4 410.1 423.6 410.2 432.9 400.8L479.9 353.8L526.9 400.8C536.3 410.2 551.5 410.2 560.8 400.8C570.1 391.4 570.2 376.2 560.8 366.9L513.8 319.9L560.8 272.9C570.2 263.5 570.2 248.3 560.8 239C551.4 229.7 536.2 229.6 526.9 239L479.9 286L432.9 239C423.5 229.6 408.3 229.6 399 239z",fill:"#ffffff"}}]),end:()=>L.createSVG(16,16,"0 0 21 16",[{tag:"path",attributes:{d:"M17.7226 12.2992C18.3148 12.5423 18.991 12.308 19.307 11.7578L19.3954 11.6031C20.434 9.78662 20.2705 7.18344 18.2308 5.85533C13.5438 2.80798 7.45789 2.80798 2.77085 5.85533C0.726753 7.18344 0.567646 9.78662 1.60627 11.6031L1.69466 11.7578C2.01066 12.3125 2.68908 12.5445 3.2769 12.3014L6.32204 11.0462C6.83914 10.8341 7.15515 10.3059 7.0999 9.74684L6.90986 7.85081C9.2346 7.06853 11.7759 7.10831 14.0785 7.97456L13.8973 9.74684C13.8399 10.3037 14.1581 10.8297 14.6752 11.0462L17.7226 12.2992Z",fill:"red"}}])},P=(e,t)=>{if("inactiveTimeout"===e){const e=t;return e?.enabled&&void 0!==e.duration&&e.duration>18e4&&(k.critical_warn(`Napster Companion API SDK: inactiveTimeout duration of ${e.duration}ms exceeds the recommended maximum of 180000ms. Setting maximum allowed value.`),delete e.duration),t}return t},x={enabled:!1,batchSize:10,flushInterval:5e3,enablePerformanceTracking:!0,enableErrorTracking:!0,enableUserInteractionTracking:!0};class V{constructor(e={}){Object.defineProperty(this,"config",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"eventQueue",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"performanceQueue",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"errorQueue",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"flushTimer",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"sessionId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"providers",{enumerable:!0,configurable:!0,writable:!0,value:[]}),this.config={...x,...e},this.sessionId=this.config.sessionId||this.generateSessionId(),this.setupProviders(),this.config.enabled&&(this.startFlushTimer(),this.setupErrorTracking(),this.setupPerformanceTracking())}setupProviders(){this.providers=[],this.config.providers&&(this.providers=[...this.config.providers]),this.config.provider&&this.providers.push(this.config.provider),0===this.providers.length&&this.providers.push({type:"custom"})}generateSessionId(){return`session_${Date.now()}_${Math.random().toString(36).substr(2,9)}`}startFlushTimer(){this.flushTimer&&clearInterval(this.flushTimer),this.flushTimer=setInterval(()=>{this.flush()},this.config.flushInterval)}setupErrorTracking(){this.config.enableErrorTracking&&(window.addEventListener("error",e=>{this.trackError(e.error,{source:"window.error",filename:e.filename,lineno:e.lineno,colno:e.colno})}),window.addEventListener("unhandledrejection",e=>{this.trackError(new Error(e.reason),{source:"unhandledrejection",reason:e.reason})}))}setupPerformanceTracking(){this.config.enablePerformanceTracking&&"undefined"!=typeof window&&"performance"in window&&window.addEventListener("load",()=>{setTimeout(()=>{const e=performance.getEntriesByType("navigation")[0];e&&(this.trackPerformance("page_load_time",e.loadEventEnd-e.fetchStart,"ms"),this.trackPerformance("dom_content_loaded",e.domContentLoadedEventEnd-e.fetchStart,"ms"),this.trackPerformance("first_paint",e.responseEnd-e.fetchStart,"ms"))},0)})}trackEvent(e,t){if(!this.config.enabled)return;const n={name:e,properties:t,timestamp:Date.now(),userId:this.config.userId,sessionId:this.sessionId};this.eventQueue.push(n),this.eventQueue.length>=(this.config.batchSize||10)&&this.flush()}trackPerformance(e,t,n,a){if(!this.config.enabled||!this.config.enablePerformanceTracking)return;const i={name:e,value:t,unit:n,timestamp:Date.now(),context:a};this.performanceQueue.push(i)}trackError(e,t){if(!this.config.enabled||!this.config.enableErrorTracking)return;const n={error:e,context:t,timestamp:Date.now(),userId:this.config.userId,sessionId:this.sessionId,stack:e.stack};this.errorQueue.push(n),this.flushErrors()}trackInteraction(e,t,n){this.config.enableUserInteractionTracking&&this.trackEvent("user_interaction",{action:e,target:t,...n})}flush(){this.flushEvents(),this.flushPerformance(),this.flushErrors()}flushEvents(){if(0===this.eventQueue.length)return;const e=[...this.eventQueue];this.eventQueue=[],this.sendData("events",e)}flushPerformance(){if(0===this.performanceQueue.length)return;const e=[...this.performanceQueue];this.performanceQueue=[],this.sendData("performance",e)}flushErrors(){if(0===this.errorQueue.length)return;const e=[...this.errorQueue];this.errorQueue=[],this.sendData("errors",e)}async sendData(e,t){const n=this.providers.map(n=>this.sendToProvider(n,e,t));await Promise.allSettled(n)}async sendToProvider(e,t,n){try{switch(e.type){case"google-analytics-4":await this.sendToGA4(e,n);break;case"mixpanel":await this.sendToMixpanel(e,n);break;case"segment":await this.sendToSegment(e,n);break;case"amplitude":await this.sendToAmplitude(e,n);break;case"posthog":await this.sendToPostHog(e,n);break;case"azure-insights":await this.sendToAzureInsights(e,n);break;default:await this.sendToCustomEndpoint(e,t,n)}}catch(t){k.critical_warn(`Failed to send data to ${e.type}:`,t)}}async sendToCustomEndpoint(e,t,n){const a=e.endpoint,i=e.apiKey;if(!a)return void("development"===process.env.NODE_ENV&&k.info(`Analytics [${t}]:`,n));const o=await fetch(`${a}/${t}`,{method:"POST",headers:{"Content-Type":"application/json",...i&&{Authorization:`Bearer ${i}`}},body:JSON.stringify({data:n,sessionId:this.sessionId,timestamp:Date.now()})});if(!o.ok)throw new Error(`HTTP ${o.status}`)}async sendToGA4(e,t){const n=e.measurementId||e.apiKey;if(!n)throw new Error("GA4 measurement ID required");const a=`https://www.google-analytics.com/mp/collect?measurement_id=${n}&api_secret=${e.apiKey||"default"}`,i=t.map(e=>({name:e.name,params:{...e.properties,session_id:this.sessionId}}));await fetch(a,{method:"POST",body:JSON.stringify({client_id:this.sessionId,user_id:this.config.userId,events:i})})}async sendToMixpanel(e,t){const n=e.projectToken||e.apiKey;if(!n)throw new Error("Mixpanel project token required");const a=e.endpoint||"https://api.mixpanel.com/batch",i=t.map(e=>{const t=e;return{event:t.name,properties:{token:n,distinct_id:this.config.userId||this.sessionId,time:t.timestamp||Date.now(),...t.properties}}});await fetch(a,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(i)})}async sendToSegment(e,t){const n=e.writeKey||e.apiKey;if(!n)throw new Error("Segment write key required");const a=e.endpoint||"https://api.segment.io/v1/batch",i=t.map(e=>({type:"track",userId:this.config.userId||this.sessionId,event:e.name,properties:e.properties,timestamp:new Date(e.timestamp||Date.now()).toISOString()}));await fetch(a,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Basic ${btoa(n+":")}`},body:JSON.stringify({batch:i})})}async sendToAmplitude(e,t){const n=e.apiKey;if(!n)throw new Error("Amplitude API key required");const a=e.endpoint||"https://api2.amplitude.com/2/httpapi",i=t.map(e=>({user_id:this.config.userId||this.sessionId,event_type:e.name,event_properties:e.properties,time:e.timestamp||Date.now()}));await fetch(a,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({api_key:n,events:i})})}async sendToPostHog(e,t){const n=e.apiKey,a=e.endpoint||"https://app.posthog.com";if(!n)throw new Error("PostHog API key required");const i=t.map(e=>({event:e.name,properties:{...e.properties,distinct_id:this.config.userId||this.sessionId},timestamp:new Date(e.timestamp||Date.now()).toISOString()}));await fetch(`${a}/batch/`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({api_key:n,batch:i})})}async sendToAzureInsights(e,t){const n=e.apiKey;if(!n)throw new Error("Azure Application Insights instrumentation key required");const a=e.endpoint||"https://dc.services.visualstudio.com/v2/track",i=t.map(e=>{const t=e;return{name:"Microsoft.ApplicationInsights.Event",time:new Date(t.timestamp||Date.now()).toISOString(),iKey:n,data:{baseType:"EventData",baseData:{name:t.name,properties:t.properties}}}});await fetch(a,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(i)})}updateConfig(e){this.config={...this.config,...e},this.setupProviders(),this.config.enabled&&!this.flushTimer?this.startFlushTimer():!this.config.enabled&&this.flushTimer&&(clearInterval(this.flushTimer),this.flushTimer=void 0)}destroy(){this.flushTimer&&clearInterval(this.flushTimer),this.flush()}}let F=null;const W=(e,t)=>{F?.trackEvent(e,t)},j=(e,t,n)=>{F?.trackInteraction(e,t,n)};function $(e,{content:t,placement:n="top"}){let a=!1,i=null,o=null;const r=e=>"left"===e?"start":"right"===e?"end":e,s=()=>{if(!i)return;const t=e.getBoundingClientRect(),a=i.getBoundingClientRect();let o=0,r=0;switch(n){case"top":o=t.top-a.height-8,r=t.left+(t.width-a.width)/2;break;case"bottom":o=t.bottom+8,r=t.left+(t.width-a.width)/2;break;case"left":o=t.top+(t.height-a.height)/2,r=t.left-a.width-8;break;case"right":o=t.top+(t.height-a.height)/2,r=t.right+8}i.style.top=`${o}px`,i.style.left=`${r}px`},c=()=>s(),d=()=>{if(a)return;const e=(()=>{if(i)return i;const e=document.createElement("div");e.className=`tooltip styled-tooltip bs-tooltip-${r(n)} show`,e.setAttribute("role","tooltip"),Object.assign(e.style,{position:"fixed",top:"0px",left:"0px",zIndex:String(2147483647),opacity:"0",visibility:"hidden",pointerEvents:"none",transition:"opacity 80ms ease"});const a=document.createElement("div");a.className="tooltip-arrow";const o=document.createElement("div");return o.className="tooltip-inner","string"==typeof t?o.textContent=t:o.appendChild(t),e.appendChild(a),e.appendChild(o),document.body.appendChild(e),i=e,e})();a=!0,s(),o=window.setTimeout(s,10),e.style.opacity="1",e.style.visibility="visible",window.addEventListener("scroll",c,!0),window.addEventListener("resize",c)},l=()=>{a&&(a=!1,null!=o&&(window.clearTimeout(o),o=null),i&&(i.style.opacity="0",i.style.visibility="hidden"),window.removeEventListener("scroll",c,!0),window.removeEventListener("resize",c))},u=()=>d(),p=()=>l();return e.addEventListener("mouseenter",u),e.addEventListener("mouseleave",p),e.matches?.(":hover")&&d(),{update:e=>{if(void 0!==e.content&&i){const t=i.querySelector(".tooltip-inner");t&&(t.innerHTML="","string"==typeof e.content?t.textContent=e.content:t.appendChild(e.content))}void 0!==e.placement&&(n=e.placement,i&&(i.className=`tooltip styled-tooltip bs-tooltip-${r(n)} show`)),a&&s()},show:d,hide:l,destroy:()=>{l(),e.removeEventListener("mouseenter",u),e.removeEventListener("mouseleave",p),i&&i.parentNode&&i.parentNode.removeChild(i),i=null}}}function U(e,t){const n=document.createElement(e);return t&&(n.className=t),n}var B,G,K,z,H,q,Q;!function(e){e.LOCAL_TIMEOUT="local_timeout",e.SERVER_WARNING="server_warning"}(B||(B={}));class J{constructor(e,t={}){Object.defineProperty(this,"overlayController",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"currentTrigger",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"isVisible",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"mountElement",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"callbacks",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.mountElement=e,this.callbacks=t}show(e){this.isVisible?k.warn("Inactive overlay already visible, ignoring show request"):(k.info(`Showing inactive overlay (trigger: ${e.type})`),this.currentTrigger=e,this.isVisible=!0,this.overlayController=function(e,t){const n={duration:t.duration??30,isInteractionNeeded:t.isInteractionNeeded??!1,message:t.message??"It looks like you've been inactive for a while. Would you like to continue this conversation?",onContinue:t.onContinue,onEnd:t.onEnd},a=document.createElement("div");a.className="np_companion-inactive-overlay";const i=document.createElement("div");i.className="np_companion-inactive-dialog";const o=document.createElement("p");o.className="np_companion-inactive-message",o.textContent=n.message;const r=document.createElement("div");r.className="np_companion-inactive-timer";const s=document.createElement("div");s.className="np_companion-timer-circle";const c=document.createElementNS("http://www.w3.org/2000/svg","svg");c.setAttribute("viewBox","0 0 36 36");const d=document.createElementNS("http://www.w3.org/2000/svg","path");d.setAttribute("d","M18 2.0845 a 15.9155 15.9155 0 0 1 0 31.831 a 15.9155 15.9155 0 0 1 0 -31.831"),d.setAttribute("fill","none"),d.setAttribute("stroke","rgba(255, 255, 255, 0.2)"),d.setAttribute("stroke-width","2");const l=document.createElementNS("http://www.w3.org/2000/svg","path");l.setAttribute("d","M18 2.0845 a 15.9155 15.9155 0 0 1 0 31.831 a 15.9155 15.9155 0 0 1 0 -31.831"),l.setAttribute("fill","none"),l.setAttribute("stroke","#fff"),l.setAttribute("stroke-width","2");const u=document.createElement("span");u.className="np_companion-timer-number",s.appendChild(c),c.appendChild(d),c.appendChild(l),s.appendChild(u),r.appendChild(s);const p=document.createElement("div");p.className="np_companion-inactive-buttons";const h=document.createElement("button");h.className="np_companion-end-button np_companion__d-none",h.textContent="End Conversation";let m=null;const f=e=>{e&&!m?(m=document.createElement("button"),m.className="np_companion-continue-button",m.textContent="Continue Talking",p.appendChild(m),m.addEventListener("click",n.onContinue)):!e&&m&&(m.removeEventListener("click",n.onContinue),m.parentNode&&m.parentNode.removeChild(m),m=null)};p.appendChild(h),f(n.isInteractionNeeded),i.appendChild(o),i.appendChild(r),i.appendChild(p),a.appendChild(i),e.appendChild(a);let v=Math.max(0,Math.floor(n.duration)),g=null;const C=()=>{u.textContent=String(v),l.setAttribute("stroke-dasharray",(n.duration>0?v/n.duration*100:0)+", 100")},b=()=>{if(v<=0)return E(),void n.onEnd();v-=1,C()},y=()=>{E(),C(),g=window.setInterval(b,1e3)},E=()=>{null!=g&&(window.clearInterval(g),g=null)};return h.addEventListener("click",()=>{E(),n.onEnd()}),y(),{update:e=>{if(void 0!==e.message&&(n.message=e.message,o.textContent=n.message),void 0!==e.isInteractionNeeded&&(n.isInteractionNeeded=!!e.isInteractionNeeded,f(n.isInteractionNeeded)),void 0!==e.duration){const t=Math.max(0,Math.floor(e.duration));n.duration=t,v=t,y()}e.onContinue&&(m&&(m.removeEventListener("click",n.onContinue),m.addEventListener("click",e.onContinue)),n.onContinue=e.onContinue),e.onEnd&&(n.onEnd=e.onEnd)},destroy:()=>{E(),h.removeEventListener("click",n.onEnd),m&&m.removeEventListener("click",n.onContinue),a.parentNode&&a.parentNode.removeChild(a)}}}(this.mountElement,{duration:e.duration,message:e.message,isInteractionNeeded:e.isInteractionNeeded,onContinue:()=>this.handleContinue(),onEnd:()=>this.handleEnd()}),this.callbacks.onShow?.(e))}hide(){this.isVisible&&(k.info("Hiding inactive overlay"),this.isVisible=!1,this.currentTrigger=null,this.overlayController&&(this.overlayController.destroy(),this.overlayController=null),this.callbacks.onHide?.())}isShowing(){return this.isVisible}getCurrentTrigger(){return this.currentTrigger}handleContinue(){k.info("User clicked continue on inactive overlay"),this.hide(),this.callbacks.onContinue?.()}handleEnd(){k.info("Inactive overlay countdown ended"),this.hide(),this.callbacks.onEnd?.()}destroy(){this.hide()}}!function(e){e.TALK_STATE_CHANGED="talk_state_changed",e.MESSAGE_RECEIVED="message_received",e.TRANSCRIPT="transcript",e.AUDIO_TRANSCRIPT_DELTA="response.audio_transcript.delta",e.AUDIO_TRANSCRIPT_DONE="response.audio_transcript.done",e.RESPONSE_DONE="response.done"}(G||(G={})),function(e){e.STARTED="started",e.ENDED="ended",e.CANCELED="canceled"}(K||(K={})),function(e){e.DELTA="delta",e.COMPLETED="completed"}(z||(z={})),function(e){e.USER="user",e.ASSISTANT="assistant"}(H||(H={})),function(e){e.SET_REMOTE_DESCRIPTION="set_remote_description",e.SET_LOCAL_DESCRIPTION="set_local_description",e.ADD_ICE_CANDIDATE="add_ice_candidate",e.ERROR="error"}(q||(q={})),function(e){e.SEND_QUESTION="send_question",e.CANCEL="cancel"}(Q||(Q={}));const Z={iceServers:[{urls:"stun:stun1.ciscape.com:3478"},{urls:"turn:stun1.ciscape.com:3478",username:"tcuser",credential:"dw4k_BR2f-Y4A-@aT7ip@Qzs"},{urls:"stun:129.146.43.226:3478"},{urls:"stun:stun.l.google.com:19302"},{urls:"stun:stun1.l.google.com:19302"},{urls:"turn:129.146.43.226:3478",username:"teamtime_turn",credential:"teamtime"}]};function Y(e,t){if(t)for(const n in t)try{const a=t[n];"string"!=typeof a&&"number"!=typeof a||(e.style[n]=a)}catch{k.warn(`Failed to apply style for key "${n}: ${t[n]}".`)}}function X(e,t,n){const a=[];return a.push("np_companion-align-middle"),e&&(a.push("np_companion-container-fixed"),a.push(`np_companion-${e}`),t&&a.push(`np_companion-view-${t}`)),n&&a.push(n),a.join(" ")}class ee{constructor(){Object.defineProperty(this,"version",{enumerable:!0,configurable:!0,writable:!0,value:"1.0.0-alpha.12"}),Object.defineProperty(this,"mountTarget",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"rootEl",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"embed",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"webrtcController",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"config",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"isInitialized",{enumerable:!0,configurable:!0,writable:!0,value:!1})}static getInstance(){return ee.instance||(ee.instance=new ee),ee.instance}renderApp(){this.mountTarget&&this.config&&(this.rootEl||(this.rootEl=document.createElement("div"),this.rootEl.id="np_companion-sdk-root",this.mountTarget.appendChild(this.rootEl)),this.rootEl.className=X(this.config.position,this.config.avatarStyle?.view,this.config.className),Y(this.rootEl,this.config.style),this.embed?this.embed.update({avatarStyle:this.config.avatarStyle,features:I.getState().app.features,onData:this.config.onData,onAvatarReady:this.config.onAvatarReady,onInactivityStatusChange:this.config.onInactivityStatusChange,onDestroy:()=>this.destroyInstance("ui_end"),onError:this.config.onError}):this.embed=function(e,t={}){const n=O.createDiv("np_companion-live-container np_companion-fade-in");e.appendChild(n);const a=function(e,t={}){const n=O.createDiv("np_companion-avatar"),a=O.createDiv(`np_companion-avatar-container np_companion-loader-${t.features?.showSDKLoader?.type??"spinner"}`);a.id="np_companion-avatar-container",t.avatarStyle?.view&&a.classList.add(`np_companion-view-${t.avatarStyle.view}`);const i=O.createDiv("loader-container"),o=O.createDiv("loader");i.appendChild(o);const r=O.createVideo({className:"np_companion-avatar-video",autoplay:!0,muted:!0,playsInline:!0}),s=O.createAudio({className:"np_companion-avatar-audio",autoplay:!0}),c=O.createCanvas({className:"np_companion-avatar-canvas",styles:{width:"100%",height:"100%",objectFit:"cover",position:"relative",zIndex:"1"}});t.features?.backgroundRemoval?.enabled&&"silhouette"===t.avatarStyle?.view?r.classList.add("np_companion__d-none"):c.classList.add("np_companion__d-none"),a.appendChild(i),a.appendChild(r),a.appendChild(s),a.appendChild(c);const d=O.createDiv(`${D.wrapper} np_companion-action-btn-container-view-${t.avatarStyle?.view}`),l=O.createDiv(`np_companion-disclaimer-text np_companion-disclaimer-view-${t.avatarStyle?.view}`);l.style.display="none";const u=O.createDiv(`np_companion-avatar-control-container np_companion-avatar-control-view-${t.avatarStyle?.view}`);u.appendChild(d),u.appendChild(l),n.appendChild(a),n.appendChild(u),e.appendChild(n);let m=null,f=(t.features?.backgroundRemoval?.enabled&&"silhouette"===t.avatarStyle?.view)??!1,v=null,g=null,C=!1,b=!1,y=!1,E=!0,w=null,_=null,S=null;const T=new J(n,{onContinue:()=>{K();const e=t.features?.inactiveTimeout;e?.enabled&&z()},onEnd:()=>{}});let N=null;const L=()=>{E||(E=!0,u.className=x(),null!=w&&window.clearTimeout(w))},P=()=>{null!=w&&window.clearTimeout(w),w=window.setTimeout(()=>{E=!1,u.className=x()},5e3)};function x(){return A(`np_companion-avatar-control-container np_companion-avatar-control-view-${t.avatarStyle?.view}`,{[D.collapse]:!E})}function V(e){if(!y)return;const n=t.avatarStyle?.borderWidth??("silhouette"!==t.avatarStyle?.view?"4px":void 0);n&&(a.style.borderWidth=n);const i=("silhouette"!==t.avatarStyle?.view?e?"#ec3e41":t.avatarStyle?.borderColor??"#C0C0C0":void 0)??t.avatarStyle?.borderColor;i&&(a.style.borderColor=i);const o=t.avatarStyle?.borderStyle??("silhouette"!==t.avatarStyle?.view?"solid":void 0);o&&(a.style.borderStyle=o)}function F(e){"round"===t.avatarStyle?.view&&(a.style.transform=`translate(-50%, ${e??352-u.offsetHeight-212-12+"px"})`)}function W(){const e=t.features?.disclaimer?.enabled??!1;l.style.display=e&&y?"-webkit-box":"none",_?.update({features:{disclaimer:{enabled:e}}});const n=t.features?.disclaimer?.text??"This is an AI avatar. Check important info.";t.features?.disclaimer?.color&&(l.style.color=t.features?.disclaimer?.color),l.textContent=n,y&&F(e?void 0:"8%")}function j(){y||!t.features?.showSDKLoader?.enabled?n.classList.add("np_companion-bg-transparent"):n.classList.remove("np_companion-bg-transparent")}function G(){t.features?.showSDKLoader?.bgColor&&n.style.setProperty("--np-loader-bg-color",t.features.showSDKLoader.bgColor),t.features?.showSDKLoader?.color&&n.style.setProperty("--np-loader-color",t.features.showSDKLoader.color)}function K(){S&&(k.timer("Resetting inactive timeout due to activity"),clearTimeout(S),S=null,I.dispatch(p(!1)),t.onInactivityStatusChange?.(!1))}function z(){const e=t.features?.inactiveTimeout;e?.enabled?(K(),S=setTimeout(()=>{k.timer(`Inactive timeout of ${e?.duration}ms reached, showing inactive overlay`),I.dispatch(p(!0)),t.onInactivityStatusChange?.(!0),m&&(m.getAudioTracks().forEach(e=>e.enabled=!1),_?.update({isMuted:!0}),V(!0)),T.isShowing()||T.show({type:B.LOCAL_TIMEOUT,duration:Math.min(e.countdown??30,60),message:void 0,isInteractionNeeded:!0})},e.duration)):(K(),T.isShowing()&&T.hide())}function H(){if(!_&&y){const e=!1;_=function(e,t){let n={...t},a=null,i=null,o=[],r=!1;const s=document.createElement("div");s.className=_();const c=U("div",D.container),d=U("div",A(D.questionBar,D.alignBetween)),l=U("div",D.left),u=U("div",D.iconButtonWithState(n.isMuted));u.appendChild(n.isMuted?M.micMuted():M.micUnmuted()),n.toggleMute&&u.addEventListener("click",()=>n.toggleMute?.());const p=U("div",D.middle),h=U("div",D.wave);S();const m=document.createElement("canvas");m.width=160,m.height=40,m.className=D.canvas,h.appendChild(m);const f=U("div",A(D.right,D.alignBetween)),v=U("div",A(D.iconButton(),D.stop)),g=function(e,t={}){let n={initialVolume:50,...t},a=n.initialVolume??50,i=!1,o=!1;const r=document.createElement("div");r.className="np_volume-control";const s=document.createElement("div");s.className="np_volume-slider-container";const c=document.createElement("div");c.className="np_volume-slider-track";const d=document.createElement("div");d.className="np_volume-slider-fill";const l=document.createElement("div");l.className="np_volume-slider-thumb",c.appendChild(d),c.appendChild(l),s.appendChild(c);const u=document.createElement("div");function p(){let e;u.innerHTML="",e=i||0===a?M.volumeMuted():M.volumeHigh(a||100),u.appendChild(e)}function h(){const e=a;d.style.height=`${e}%`,l.style.bottom=`${e}%`}function m(){o=!o,o?s.classList.add("np_volume-slider-visible"):s.classList.remove("np_volume-slider-visible")}function f(e){const t=c.getBoundingClientRect(),o=Math.max(0,Math.min(100,(t.bottom-e)/t.height*100));a=o,h(),i=0===a,i?u.classList.add("np_volume-muted"):u.classList.remove("np_volume-muted"),p(),n.onChange?.(a)}u.className=D.iconButton(),u.setAttribute("aria-label","Volume control"),p(),r.appendChild(s),r.appendChild(u),e.appendChild(r),u.addEventListener("click",e=>{e.stopPropagation(),i=!i,i?(n.initialVolume=a,a=0,h(),u.classList.add("np_volume-muted")):(a=n.initialVolume||50,h(),u.classList.remove("np_volume-muted")),p(),n.onMuteToggle?.(i)}),r.addEventListener("mouseenter",e=>{e.stopPropagation(),o||m()}),r.addEventListener("mouseleave",e=>{setTimeout(()=>{e.stopPropagation(),o&&m()},300)});let v=!1;return c.addEventListener("mousedown",e=>{v=!0,f(e.clientY),e.preventDefault()}),document.addEventListener("mousemove",e=>{v&&f(e.clientY)}),document.addEventListener("mouseup",()=>{v=!1}),l.addEventListener("mousedown",e=>{v=!0,e.preventDefault()}),c.addEventListener("touchstart",e=>{v=!0,f(e.touches[0].clientY),e.preventDefault()}),document.addEventListener("touchmove",e=>{v&&e.touches.length>0&&f(e.touches[0].clientY)}),document.addEventListener("touchend",()=>{v=!1}),document.addEventListener("click",e=>{o&&!r.contains(e.target)&&m()}),h(),{setVolume(e){a=Math.max(0,Math.min(100,e)),h(),p(),n.onChange?.(a)},getVolume:()=>a,toggleMute(){i=!i,i?u.classList.add("np_volume-muted"):u.classList.remove("np_volume-muted"),n.onMuteToggle?.(i)},isMuted:()=>i,update(e){n={...n,...e}},destroy(){r.remove()}}}(v,{initialVolume:50,onChange:e=>{n.onVolumeChange?.(e)},onMuteToggle:e=>{n.onVolumeChange?.(e?0:g.getVolume())}});g.setVolume(70);const C=U("div",D.iconButtonEnd());C.appendChild(M.end()),n.handleEnd&&C.addEventListener("click",()=>n.handleEnd?.()),l.appendChild(u),p.appendChild(h),f.appendChild(v),f.appendChild(C),d.appendChild(l),d.appendChild(f),c.appendChild(d),s.appendChild(c),e.appendChild(s);let b=null,y=null,E=null;function w(){if(!n.userMicrophoneStream)return;const e=new(window.AudioContext||window.webkitAudioContext);a=e.createAnalyser(),e.createMediaStreamSource(n.userMicrophoneStream).connect(a),function(e){if(!a)return;const t=m.getContext("2d");if(!t)return;a.fftSize=256;const n=new Uint8Array(a.frequencyBinCount),s=Math.floor(m.width/3);0===o.length&&(o=new Array(s).fill(0));let c=0;const d=()=>{if(t.clearRect(0,0,m.width,m.height),t.beginPath(),t.moveTo(0,m.height/2),t.lineTo(m.width,m.height/2),t.strokeStyle="#ffffff",t.stroke(),e)r=!1,o.fill(0),S();else{a.getByteFrequencyData(n);const e=6,i=3,s=n.reduce((e,t)=>e+t,0)/n.length/255*m.height*.8;o.shift(),o.push(s);let d=o.filter(t=>t>e).length>=i;d?c=30:c>0&&(c--,d=!0),r=d,S(),t.fillStyle="#ffffff";for(let e=0;e<o.length;e++){const n=3*e,a=o[e];t.fillRect(n,m.height/2-a/2,2,a),t.fillRect(n,m.height/2+a/2,2,-a)}}i=requestAnimationFrame(d)};d()}(!!n.isMuted)}function _(){return A(D.alignMiddle,`np_companion-avatar-${n.avatarStyle?.view}`)}function S(){h.style.filter=!n.isMuted&&r?"brightness(0) saturate(100%) invert(48%) sepia(93%) saturate(1720%) hue-rotate(346deg) brightness(101%) contrast(103%)":"none",h.style.transition="filter 0.3s ease",h.style.height="40px"}function T(){b?.destroy(),b=$(u,{content:n.isMuted?"Unmute":"Mute",placement:"top"}),y?.destroy(),y=null}function I(){for(u.className=D.iconButtonWithState(n.isMuted);u.firstChild;)u.removeChild(u.firstChild);u.appendChild(n.isMuted?M.micMuted():M.micUnmuted())}return b=$(u,{content:n.isMuted?"Unmute":"Mute",placement:"top"}),E=$(C,{content:"End Session",placement:"top"}),w(),{update(e){const t=n;n={...n,...e},s.className=_(),t.isMuted!==n.isMuted&&(I(),T()),t.isAvatarSpeaking!==n.isAvatarSpeaking&&(I(),T()),t.userMicrophoneStream===n.userMicrophoneStream&&t.selectedMicrophone===n.selectedMicrophone||(null!=i&&(cancelAnimationFrame(i),i=null),o=[],a=null,w()),S(),n.features?.disclaimer?.enabled?c.classList.remove("np_companion_disclaimer-disabled"):c.classList.add("np_companion_disclaimer-disabled")},destroy(){b?.destroy(),y?.destroy(),E?.destroy(),null!=i&&cancelAnimationFrame(i),s.parentNode&&s.parentNode.removeChild(s)}}}(d,{avatarStyle:t.avatarStyle,isMuted:e,isAvatarSpeaking:b,userMicrophoneStream:m,features:{waveform:{enabled:!1!==t.features?.waveform?.enabled}},onVolumeChange:e=>{s.volume=e/100},toggleMute:()=>{const t=!(I.getState().avatar.muted??e);I.dispatch(h(t)),m&&m.getAudioTracks().forEach(e=>e.enabled=!t),_?.update({isMuted:t}),V(t),K(),z()},onStopTalking:()=>{try{const e=I.getState().avatar.dataChannel;if(e&&"open"===e.readyState){const t={type:Q.CANCEL};k.avatar("stopping avatar"),e.send(JSON.stringify(t))}else k.critical_warn("Stopping avatar: Data channel not open")}catch(e){k.critical_error("Avatar","Stop: failed to send interrupt",e)}K(),z()},handleEnd:()=>{t.onDestroy?.()}})}}n.addEventListener("mouseenter",L),n.addEventListener("mousemove",L),n.addEventListener("mouseleave",P);const q=()=>{if(C)return;const e=c.getContext("2d",{willReadFrequently:!0});if(!e||!r||r.readyState<2)N=requestAnimationFrame(q);else{if(c.width=r.videoWidth,c.height=r.videoHeight,e.drawImage(r,0,0,c.width,c.height),f){const n=e.getImageData(0,0,c.width,c.height),a=R.process(n);e.putImageData(a,0,0),y||(t.onAvatarReady?.(!0),y=!0,V(),H(),j(),W(),z(),P())}N=requestAnimationFrame(q)}};W(),G(),j();const Z={updateStreams:({videoStream:e,audioStream:n,userMicrophoneStream:a})=>{e&&e instanceof MediaStream?v!==e&&(k.avatar("New video stream received:",{active:e.active,tracks:e.getTracks().length,videoTracks:e.getVideoTracks().length,id:e.id}),v=e,r.srcObject=e,r.play().then(()=>{f||y||(t.onAvatarReady?.(!0),y=!0,V(),H(),j(),W(),z(),F(),P())}).catch(e=>{k.error("Failed to play video stream",e),t.onError?.(e)}),e.addEventListener("inactive",()=>{k.avatar("Video stream became inactive")}),e.getTracks().forEach(e=>{e.addEventListener("ended",()=>{k.avatar("Video track ended:",e.kind)})}),f&&!N&&(N=requestAnimationFrame(q))):(v=null,r.srcObject=null),void 0!==n&&(n&&n instanceof MediaStream?g!==n&&(g=n,s.srcObject=n,s.play().catch(e=>{k.error("Failed to play audio stream",e),t.onError?.(e)})):(g=null,s.srcObject=null)),void 0!==a&&(m=a??null,_?.update({userMicrophoneStream:m}))},updateWaveform:e=>{H(),_?.update(e)},updateFeatures:e=>{t.features={...t.features||{},...e||{}},f=(t.features?.backgroundRemoval?.enabled&&"silhouette"===t.avatarStyle?.view)??!1,f?(r.classList.add("np_companion__d-none"),c.classList.remove("np_companion__d-none")):(r.classList.remove("np_companion__d-none"),c.classList.add("np_companion__d-none")),_?.update({features:{waveform:{enabled:!1!==t.features?.waveform?.enabled}}}),W(),G(),j(),z()},update:e=>{const n=t.avatarStyle?.view;Object.assign(t,e),e.features&&Z.updateFeatures(e.features),e.avatarStyle?.view&&e.avatarStyle.view!==n&&(n&&a.classList.remove(`np_companion-view-${n}`),a.classList.add(`np_companion-view-${e.avatarStyle.view}`),t.features&&Z.updateFeatures(t.features))},setAvatarReady:e=>{e||(y=!1,t.onAvatarReady?.(!1))},handleMessage:e=>{switch("undefined"!=typeof window&&window.parent&&window.parent.postMessage({type:"avatar-data-channel-message",event:e},"*"),e.event){case"avatar_state_changed":break;case"talk_state_changed":b="ended"!==e.data?.state&&"canceled"!==e.data?.state,_?.update({isAvatarSpeaking:b});break;case"message_received":{const{message:t}=e.data||{};if("completed"===t?.action&&"string"==typeof t.content&&t.role){K(),z();const e=T.getCurrentTrigger();e&&!e.isInteractionNeeded&&T.hide()}break}case"avatar_connection_warning":t.showAvatarInactiveOverlay&&(T.show({type:B.SERVER_WARNING,duration:e.data?.disconnect_after??30,message:"Avatar is disconnecting due to inactivity. Say something to keep it active.",isInteractionNeeded:!1}),m&&(m.getAudioTracks().forEach(e=>e.enabled=!0),_?.update({isMuted:!1}),V(!1)))}t.onData?t.onData(e):k.data("onData callback NOT called. Reason:",{onDataExists:!!t.onData,dataType:typeof e,dataIsNull:null===e})},destroy:e=>{C||(C=!0,n.removeEventListener("mousemove",L),n.removeEventListener("mouseenter",L),n.removeEventListener("mouseleave",P),null!=w&&window.clearTimeout(w),null!=N&&(cancelAnimationFrame(N),N=null),S&&(clearTimeout(S),S=null),_?.destroy(),_=null,T?.destroy(),n.parentNode&&n.parentNode.removeChild(n),y=!1,t.onAvatarReady?.(!1),e||t.onDestroy?.())}};return Z}(n,{avatarStyle:t.avatarStyle,showAvatarInactiveOverlay:!0,onData:t.onData,onDestroy:t.onDestroy,onError:t.onError,onInactivityStatusChange:t.onInactivityStatusChange,onAvatarReady:t.onAvatarReady,features:t.features});return{update:e=>{a.update({avatarStyle:e.avatarStyle??t.avatarStyle,onData:e.onData??t.onData,onDestroy:e.onDestroy??t.onDestroy,onError:e.onError??t.onError,onInactivityStatusChange:e.onInactivityStatusChange??t.onInactivityStatusChange,onAvatarReady:e.onAvatarReady??t.onAvatarReady,features:e.features??t.features}),Object.assign(t,e)},updateStreams:e=>{a.updateStreams(e)},handleMessage:e=>{a.handleMessage(e)},destroy:()=>{a.destroy(!0),n.parentNode===e&&e.removeChild(n),t.onDestroy?.()}}}(this.rootEl,{avatarStyle:this.config.avatarStyle,features:I.getState().app.features,onData:this.config.onData,onAvatarReady:this.config.onAvatarReady,onInactivityStatusChange:this.config.onInactivityStatusChange,onDestroy:()=>this.destroyInstance("ui_end"),onError:this.config.onError}),this.initializeWebRTC().catch(e=>{k.critical_error("Failed to establish WebRTC connection:",e),this.config?.onError?.(e)}))}async initializeWebRTC(){const e=I.getState().avatar.connectionToken;if(e&&!this.webrtcController){k.connection("Connecting WebRTC..."),this.webrtcController=function(e={}){const{currentAudioDeviceId:t,onChatMessage:n,onConnectionSuccess:a,onConnectionError:i,onStreams:s,onDataChannel:c,maxReconnectAttempts:d=3,reconnectInterval:l=2e3}=e;let p=null,h=null,v=null,g=null,C=null,b=null,y=null,E="disconnected",w=0,_=null,S=null,T=!0,N=null;function A(e,t){e&&e.readyState===WebSocket.OPEN?e.send(JSON.stringify(t)):k.critical_warn("WebRTC",`WS send skipped; state=${e?.readyState}`)}function D(e){N=e,i?.(e)}function O(e){E=e,k.webrtc(`Connection status changed to: ${e}`)}function R(){!T||!S||w>=d?w>=d&&D(new o("WebSocket connection failed after max retry attempts",{maxAttempts:d,lastAttempt:w})):(w+=1,O("reconnecting"),k.webrtc(`Attempting to reconnect (${w}/${d})...`),_=setTimeout(async()=>{try{if(!S)return;await L(S.connection.signalingEndpoint,S.connection.id,!0),!p&&S&&await M(S.token)}catch(e){k.error("WebRTC","Reconnection attempt failed:",e),w<d&&R()}},l))}async function L(e,t,n=!1){const i=`${e.replace(/\/$/,"")}/ws/connections/${t}/signaling`;h&&h.readyState===WebSocket.OPEN&&h.close();const r=new WebSocket(i);return h=r,await new Promise((e,t)=>{r.onopen=()=>{k.connection(n?"WebSocket reconnected":"WebSocket connected"),O("connected"),w=0,_&&(clearTimeout(_),_=null),e()},r.onclose=e=>{k.connection("WebSocket closed:",e),h=null,O("disconnected"),!e.wasClean&&T&&R(),t(new o("WebSocket connection closed",{code:e.code,reason:e.reason,wasClean:e.wasClean}))},r.onerror=e=>{h=null,O("disconnected");const n=new o("WebSocket connection error",{error:e,timestamp:(new Date).toISOString()});D(n),t(n)}}),a?.(),I.dispatch(m(void 0)),r}async function M(e){if(p&&"disconnected"!==E)k.warn("WebRTC","Connection already in progress, skipping...");else try{O("connecting"),N=null;const a=(e=>{try{const t=atob(e);return JSON.parse(t)}catch(e){return k.critical_error("decodeToBase64: Error decoding token",e),null}})(e);if(!a)throw new o("Failed to decode connection token",{token:e?"provided":"missing"});S={...a,token:e};const i=await L(a.connection.signalingEndpoint,a.connection.id),d=await async function(){k.webrtc("Create PeerConnection");const e=new RTCPeerConnection(Z);return p=e,e.addEventListener("connectionstatechange",()=>{"failed"===e.connectionState?(D(new o("WebRTC connection failed")),R()):"connected"===e.connectionState&&(O("connected"),w=0,_&&(clearTimeout(_),_=null))}),function(e){y=e.addTransceiver("audio",{direction:"sendrecv"});const t=e.addTransceiver("video",{direction:"recvonly"});k.webrtc("Added transceivers",{videoTransceiver:t,audioTransceiver:y});const a=e.createDataChannel("chat",{ordered:!0});b=a,I.dispatch(u(a)),c?.(a),a.onopen=()=>{k.webrtc("Data channel opened")},a.onclose=()=>{k.webrtc("Data channel closed")},a.onerror=e=>{k.critical_error("WebRTC",e),D(new r("Data channel error",{error:e}))},a.onmessage=e=>{try{const t=JSON.parse(e.data);k.data("Data channel message received:",t),n?.(t)}catch{n?.({event:"message_received",data:{message:{content:e.data,action:"completed"}}})}}}(e),e.ontrack=e=>{const t=e.streams[0];k.webrtc(`${e.track.kind} stream received`,{streamId:t?.id,trackId:e.track.id,videoTracks:t?.getVideoTracks().length,audioTracks:t?.getAudioTracks().length}),"video"===e.track.kind?(g=t,C=t):"audio"===e.track.kind&&(C=t,g||(g=t)),s?.({videoStream:g,audioStream:C})},e}();await async function(){try{k.webrtc("Setting up user media");const e=await navigator.mediaDevices.getUserMedia({audio:!t||{deviceId:{exact:t}},video:!1});if(v=e,y&&e.getAudioTracks().length>0){const t=e.getAudioTracks()[0];await y.sender.replaceTrack(t)}s?.({userMicrophoneStream:e})}catch(e){k.critical_warn("WebRTC",e),D(new o("Failed to access user media",{error:e,deviceId:t}))}}(),await async function(e,t){e.addEventListener("icecandidate",e=>{const n=e.candidate;n&&(k.webrtc("send ICE candidate"),A(t,{type:"add_ice_candidate",data:{candidate:n}}))}),e.addEventListener("negotiationneeded",()=>{k.warn("negotiationneeded (waiting for server offer)")}),k.webrtc("createOffer → setLocalDescription → set_remote_description");const n=await e.createOffer();await e.setLocalDescription(n),A(t,{type:"set_remote_description",data:n})}(d,i),i.onmessage=e=>async function(e,t,n){try{const a=JSON.parse(n.data);switch(a.type){case"set_remote_description":k.webrtc("Setting remote description"),await e.setRemoteDescription(a.data),await e.setLocalDescription(),A(t,{type:"set_local_description",data:e.localDescription});break;case"add_ice_candidate":a.data?.candidate&&await e.addIceCandidate(a.data.candidate);break;case"error":k.critical_error("WebRTC",a.data?.error),D(new r(a.data?.error||"Server error",{serverMessage:a.data})),e.close(),t.close();break;default:k.webrtc("Unknown message type:",a.type)}}catch(e){k.critical_error("WebRTC",e),D(new r("Failed to process WebSocket message",{originalError:e,rawMessage:n.data}))}}(d,i,e)}catch(e){const t=e;throw k.critical_error("WebRTC",t),D(t),O("disconnected"),t}}function P(){T=!1,_&&(clearTimeout(_),_=null),w=0;try{if(b)try{b.close()}catch{}if(h)try{h.readyState!==WebSocket.OPEN&&h.readyState!==WebSocket.CONNECTING||h.close(1e3,"Connection closed by client")}catch{}if(p)try{p.getSenders().forEach(e=>{e.track&&e.track.stop()}),p.close()}catch{}if(v)try{v.getTracks().forEach(e=>e.stop())}catch{}}catch(e){k.critical_warn("WebRTC",e)}finally{b=null,h=null,p=null,v=null,y=null,g=null,C=null,S=null,O("disconnected"),I.dispatch(f(void 0))}}return I.dispatch(f(P)),{startWithToken:M,close:P,forceReconnect:async function(){if(S){P(),T=!0,w=0;try{await M(S.token)}catch(e){throw D(e),e}}else D(new o("No connection data available for reconnect"))},getConnectionStatus:function(){return E},getReconnectAttempts:function(){return w},getError:function(){return N},updateAudioDevice:async function(e){if(y&&y.sender.track)try{const t=await navigator.mediaDevices.getUserMedia({audio:{deviceId:{exact:e}},video:!1}),n=t.getAudioTracks()[0];await y.sender.replaceTrack(n),v&&v.getTracks().forEach(e=>e.stop()),v=t,s?.({userMicrophoneStream:t}),k.webrtc(`Audio device updated to: ${e}`)}catch(t){k.critical_warn("WebRTC","Failed to update audio device:",t),D(new o("Failed to update audio device",{error:t,deviceId:e}))}else k.warn("WebRTC","No audio transceiver available for device update")}}}({maxReconnectAttempts:3,reconnectInterval:2e3,onStreams:e=>{this.embed?.updateStreams(e)},onChatMessage:e=>{this.embed?.handleMessage(e)},onConnectionError:e=>{k.critical_error("WebRTC connection error:",e),this.config?.onError?.(e)}});try{k.connection("Initializing WebRTC connection with token:",`${e.substring(0,50)}...`),await this.webrtcController.startWithToken(e),k.connection("WebRTC initialization completed with token")}catch(e){throw k.critical_error("SDK","Failed to Initialize WebRTC:",e),this.webrtcController=null,e}}}destroyWebRTC(){if(this.webrtcController){k.info("SDK","Destroying WebRTC controller");try{this.webrtcController.close()}catch(e){k.critical_error("SDK","Error closing WebRTC controller:",e)}this.webrtcController=null}}destroyInstance(e,t){if(!e)return void k.critical_warn("SDK","destroyInstance ignored (no reason)");W("sdk_destroyed",{reason:e}),t?.();const n=this.config?.onDestroy;if(S(null),I.dispatch(m(void 0)),I.dispatch(f(void 0)),I.dispatch(h(!1)),I.dispatch(y()),I.dispatch(E(void 0)),this.destroyWebRTC(),this.embed){try{this.embed.update({onDestroy:void 0}),this.embed.destroy()}catch(e){k.critical_error("Error during cleanup:",e)}this.embed=null}this.rootEl&&this.rootEl.parentNode&&this.rootEl.parentNode.removeChild(this.rootEl),this.rootEl=null,this.mountTarget=null,this.config=null,this.isInitialized=!1,n?.()}async init(e,t={}){try{if(this.isInitialized)throw new a("SDK is already initialized. Call destroy() first.",{code:s.ALREADY_INITIALIZED});t.analytics?.enabled&&(function(e){F=new V(e)}(t.analytics),W("sdk_init_started",{version:this.version,config:{position:t.position,features:Object.keys(t.features||{})}})),function(e){if(!e||"string"!=typeof e||""===e.trim())throw new i("Invalid connection token: expected non-empty string",{providedToken:typeof e,code:s.INVALID_TOKEN})}(e);const n={avatarStyle:{view:"round"},position:c.BOTTOM_RIGHT,...t};this.config=n,I.dispatch(m(e)),I.dispatch(h(!1)),I.dispatch(w(n.debug)),this.config.features&&Object.entries(this.config.features).forEach(([e,t])=>{const n=P(e,t);I.dispatch(b({feature:e,config:n}))}),S(e=>{try{this.embed&&this.embed.update({features:e})}catch(e){k.critical_error("Unable to update features",e)}this.config?.onFeaturesUpdate?.(e)});const o=function(e){if(!e)return document.body;if("string"==typeof e){const t=document.querySelector(e);return t instanceof HTMLElement?t:(k.warn(`mountContainer should be a valid CSS selector. Provided selector "${e}" is invalid or did not match any elements. Defaulting to document.body.`),document.body)}return e instanceof HTMLElement?e:document.body}(this.config.mountContainer??void 0);return this.mountTarget=o,this.isInitialized=!0,this.renderApp(),this.config.onReady?.(),W("sdk_init_completed",{version:this.version,initTime:Date.now()}),this.createInstanceMethods()}catch(n){const a=d.handle(n,{method:"init",tokenProvided:!!e,config:t});throw t.onError?.(a),a}}createInstanceMethods(){return{showAvatar:()=>{const e=document.getElementById("np_companion-avatar-container");e&&(e.style.display="block",j("show","avatar_widget"))},hideAvatar:()=>{const e=document.getElementById("np_companion-avatar-container");e&&(e.style.display="none",j("hide","avatar_widget"))},avatarIsVisible:()=>{const e=document.getElementById("np_companion-avatar-container");return!!e&&"none"!==e.style.display},destroy:()=>{const{closeConnectionHandler:e}=I.getState().avatar;this.destroyInstance("api",e)},updateStyles:e=>{this.config&&(this.config.style={...this.config.style??{},...e??{}},this.rootEl&&Y(this.rootEl,this.config.style))},setPosition:e=>{if(this.config&&(this.config.position=e,I.dispatch?.(E(e)),this.rootEl)){const t=X(e,this.config.avatarStyle?.view,this.config.className);this.rootEl.className=t}},clearPosition:()=>{this.config&&(I.dispatch?.(E(void 0)),this.config.position=void 0,this.rootEl&&(this.rootEl.className=X(void 0,this.config.avatarStyle?.view,this.config.className)))},enableFeature:e=>{I.dispatch?.(b({feature:e,config:{enabled:!0}})),"disclaimer"===e&&this.rootEl&&this.rootEl.classList.remove("np_companion_disclaimer-disabled")},disableFeature:e=>{I.dispatch?.(b({feature:e,config:{enabled:!1}})),"disclaimer"===e&&this.rootEl&&this.rootEl.classList.add("np_companion_disclaimer-disabled")},updateFeatureConfig:(e,t)=>{const n=P(e,t);I.dispatch?.(b({feature:e,config:n})),"disclaimer"===e&&this.rootEl&&(n?.enabled?this.rootEl.classList.remove("np_companion_disclaimer-disabled"):this.rootEl.classList.add("np_companion_disclaimer-disabled"))},updateAvatarStyle:e=>{if(this.config){if(this.config.avatarStyle={view:"round",...this.config.avatarStyle,...e},e.view&&this.rootEl){const t=X(this.config.position,e.view,this.config.className);this.rootEl.className=t}this.embed&&this.embed.update({avatarStyle:this.config.avatarStyle})}},sendQuestion:e=>{const{dataChannel:t,stopInteraction:n}=I.getState().avatar;t&&"open"===t.readyState&&!n?t.send(JSON.stringify({type:"send_question",data:e})):k.critical_warn("Data channel not available or not open")}}}}Object.defineProperty(ee,"instance",{enumerable:!0,configurable:!0,writable:!0,value:null});const te=ee.getInstance();"undefined"!=typeof window&&(window.napsterCompanionApiSDK=te);export{te as NapsterCompanionApiSdk,c as Position,te as default};
package/lib/index.js CHANGED
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e,t=require("@reduxjs/toolkit");class n extends Error{constructor(e,t,n){super(e),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"timestamp",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"context",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name="SDKError",this.code=t,this.timestamp=new Date,this.context=n,Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,message:this.message,code:this.code,timestamp:this.timestamp.toISOString(),context:this.context,stack:this.stack}}}class a extends n{constructor(e,t){super(e,"INITIALIZATION_ERROR",t),this.name="InitializationError"}}class i extends n{constructor(e,t){super(e,"TOKEN_ERROR",t),this.name="TokenError"}}class o extends n{constructor(e,t){super(e,"CONNECTION_ERROR",t),this.name="ConnectionError"}}class r extends n{constructor(e,t){super(e,"WEBRTC_ERROR",t),this.name="WebRTCError"}}!function(e){e.ALREADY_INITIALIZED="ALREADY_INITIALIZED",e.INVALID_TOKEN="INVALID_TOKEN",e.REACT_VERSION_UNSUPPORTED="REACT_VERSION_UNSUPPORTED",e.CONTAINER_NOT_FOUND="CONTAINER_NOT_FOUND",e.CONNECTION_FAILED="CONNECTION_FAILED",e.TOKEN_GENERATION_FAILED="TOKEN_GENERATION_FAILED",e.MISSING_CREDENTIALS="MISSING_CREDENTIALS",e.WEBRTC_NOT_SUPPORTED="WEBRTC_NOT_SUPPORTED",e.PEER_CONNECTION_FAILED="PEER_CONNECTION_FAILED",e.DATA_CHANNEL_ERROR="DATA_CHANNEL_ERROR",e.API_REQUEST_FAILED="API_REQUEST_FAILED",e.INVALID_RESPONSE="INVALID_RESPONSE",e.RATE_LIMITED="RATE_LIMITED",e.INVALID_CONFIGURATION="INVALID_CONFIGURATION",e.MISSING_REQUIRED_CONFIG="MISSING_REQUIRED_CONFIG",e.FEATURE_NOT_SUPPORTED="FEATURE_NOT_SUPPORTED",e.FEATURE_DISABLED="FEATURE_DISABLED",e.MEDIA_ACCESS_DENIED="MEDIA_ACCESS_DENIED",e.MEDIA_DEVICE_ERROR="MEDIA_DEVICE_ERROR",e.VIDEO_LOAD_ERROR="VIDEO_LOAD_ERROR"}(e||(e={}));class s{static setErrorHandler(e){this.onError=e}static handle(e,t){let a;return function(e){return e instanceof n}(e)?(a=e,t&&(a.context={...a.context,...t})):a=e instanceof Error?new n(e.message,"UNKNOWN_ERROR",{originalError:e.name,...t}):new n("string"==typeof e?e:"Unknown error occurred","UNKNOWN_ERROR",{originalError:e,...t}),this.onError?.(a),a}}exports.Position=void 0,function(e){e.BOTTOM_RIGHT="bottom-right",e.BOTTOM_CENTER="bottom-center",e.BOTTOM_LEFT="bottom-left",e.TOP_RIGHT="top-right",e.TOP_CENTER="top-center",e.TOP_LEFT="top-left",e.CENTER="center"}(exports.Position||(exports.Position={}));const c=t.createSlice({name:"avatar",initialState:{avatarReady:!1,dataChannel:null,stopInteraction:!1,muted:!1,transcript:void 0,customVoiceId:void 0,defaultVoiceId:void 0,connectionToken:void 0,companionId:void 0,closeConnectionHandler:void 0},reducers:{setSessionId:(e,t)=>{e.sessionId=t.payload},setAvatarReady:(e,t)=>{e.avatarReady=t.payload},setDataChannel:(e,t)=>{e.dataChannel=t.payload},setAvatarId:(e,t)=>{e.avatarId=t.payload},setVideoId:(e,t)=>{e.videoId=t.payload},setStopInteraction:(e,t)=>{e.stopInteraction=t.payload},setMuted:(e,t)=>{e.muted=t.payload},addTranscript:(e,t)=>{e.transcript=t.payload},setCustomVoiceId:(e,t)=>{e.customVoiceId=t.payload},setDefaultVoiceId:(e,t)=>{e.defaultVoiceId=t.payload},setConnectionToken:(e,t)=>{e.connectionToken=t.payload},setCloseConnectionHandler:(e,t)=>{e.closeConnectionHandler=t.payload}}}),{setDataChannel:d,setStopInteraction:l,setMuted:u,setConnectionToken:p,setCloseConnectionHandler:h}=c.actions,m=c.reducer,f={features:{backgroundRemoval:{enabled:!0},waveform:{enabled:!0,color:"#ffffff"},inactiveTimeout:{enabled:!0,duration:6e4,countdown:30},disclaimer:{enabled:!0,text:"This is an AI avatar. Check important info."},showSDKLoader:{enabled:!0,bgColor:"rgb(222 222 222 / 60%)",color:"#585858ff",type:"spinner"}},position:void 0,showExperience:!1,debugMode:!1},v=t.createSlice({name:"app",initialState:f,reducers:{setFeatures:(e,t)=>{const{feature:n,config:a}=t.payload,i=e.features[n];e.features[n]={...i,...a,enabled:a?.enabled??!!i?.enabled}},resetFeatures:e=>{e.features=f.features},setPosition:(e,t)=>{e.position=t.payload},setShowExperience:(e,t)=>{e.showExperience=t.payload},setDebugMode:(e,t)=>{e.debugMode=t.payload}}}),{setFeatures:g,resetFeatures:C,setPosition:b,setDebugMode:y}=v.actions;let E=null;const w=e=>{E=e},_=e=>t=>n=>{const a=e.getState().app.features,i=t(n),o=e.getState().app.features;return E&&a!==o&&JSON.stringify(a)!==JSON.stringify(o)&&E(o),i},S=t.configureStore({reducer:{avatar:m,app:v.reducer},middleware:e=>e({serializableCheck:!1}).concat(_)});var T;!function(e){e.INFO="info",e.WARN="warn",e.ERROR="error",e.DEBUG="debug"}(T||(T={}));const I=new class{constructor(){Object.defineProperty(this,"prefix",{enumerable:!0,configurable:!0,writable:!0,value:"[Napster SDK]"})}isDebugEnabled(){try{return S.getState().app.debugMode||!1}catch{return!1}}log(e,...t){if(!this.isDebugEnabled())return;const n=[this.prefix,...t];switch(e){case T.INFO:console.info(...n);break;case T.WARN:console.warn(...n);break;case T.ERROR:console.error(...n);break;case T.DEBUG:console.debug(...n)}}info(...e){this.log(T.INFO,"ℹ️",...e)}debug(...e){this.log(T.DEBUG,"🐞",...e)}warn(...e){this.log(T.WARN,"⚠️",...e)}error(...e){this.log(T.ERROR,"❌",...e)}critical_warn(...e){console.warn(this.prefix,"⚠️",...e)}critical_error(...e){console.error(this.prefix,"❌",...e)}webrtc(...e){this.log(T.INFO,"📡 WebRTC:",...e)}avatar(...e){this.log(T.INFO,"🎭 Avatar:",...e)}connection(...e){this.log(T.INFO,"🔌 Connection:",...e)}features(...e){this.log(T.INFO,"🔄 Features:",...e)}data(...e){this.log(T.INFO,"📨 Data:",...e)}timer(...e){this.log(T.INFO,"⏱️ Timer:",...e)}cleanup(...e){this.log(T.INFO,"🗑️ Cleanup:",...e)}};function N(...e){const t=[];for(const n of e)if(n)if("string"==typeof n||"number"==typeof n)t.push(String(n));else if(Array.isArray(n)){const e=N(...n);e&&t.push(e)}else if("object"==typeof n)for(const[e,a]of Object.entries(n))a&&t.push(e);return t.join(" ")}const k={icon:"np_companion-action-btn-container-icon",persistFillColor:"np_companion-persist-fill-color",alignMiddle:"np_companion-align-middle",alignBetween:"np_companion-align-between",darkGreyBg:"np_companion-dark-grey-bg",callEnd:"np_companion-action-btn-container-call-end",container:"np_companion-action-btn-container-container",wrapper:"np_companion-action-btn-container-wrapper",canvas:"np_companion-action-btn-container-canvas",controls:"np_companion-action-btn-container-controls",left:"np_companion-action-btn-container-left",middle:"np_companion-action-btn-container-middle",right:"np_companion-action-btn-container-right",wave:"np_companion-action-btn-container-wave",stop:"np_companion-action-btn-container-stop",questionBar:"np_companion-chat-question-bar-container",muted:"muted",hidden:"np_companion-hidden",expanded:"np_companion-action-btn-container-expanded",collapse:"np_companion-action-btn-container-collapse",mobileMode:"np_companion-mobile-mode",displayNone:"np_companion__d-none",iconButton:()=>N(k.icon,k.alignMiddle,k.darkGreyBg),iconButtonEnd:()=>N(k.icon,k.alignMiddle,k.darkGreyBg,k.callEnd),iconButtonWithState:e=>N(k.icon,k.alignMiddle,k.darkGreyBg,{[k.muted]:e})};class A{static createElement(e,t){const n=document.createElement(e);return t?.className&&(n.className=t.className),t?.id&&(n.id=t.id),t?.attributes&&Object.entries(t.attributes).forEach(([e,t])=>{n.setAttribute(e,t)}),t?.styles&&Object.assign(n.style,t.styles),n}static createVideo(e){const t=this.createElement("video",{className:e.className});return t.autoplay=e.autoplay??!1,t.muted=e.muted??!1,t.loop=e.loop??!1,t.playsInline=e.playsInline??!1,e.crossOrigin&&(t.crossOrigin=e.crossOrigin),e.poster&&(t.poster=e.poster),e.src&&(t.src=e.src),t}static createAudio(e){const t=this.createElement("audio",{className:e.className});return t.autoplay=e.autoplay??!1,t}static createCanvas(e){const t=this.createElement("canvas",{className:e.className,styles:e.styles});return void 0!==e.width&&(t.width=e.width),void 0!==e.height&&(t.height=e.height),t}static createButton(e){const t=this.createElement("button",{className:e.className,attributes:e.attributes});return e.textContent&&(t.textContent=e.textContent),e.onClick&&t.addEventListener("click",e.onClick),t}static createDiv(e){return this.createElement("div",{className:e})}}class D{static process(e){const t=e.data;return this.hasGreenScreen(t)?(this.removeGreenScreen(t),e):e}static hasGreenScreen(e){for(let t=0;t<e.length;t+=4)if(this.isGreenPixel(e[t],e[t+1],e[t+2]))return!0;return!1}static isGreenPixel(e,t,n){return e>=0&&e<=120&&t>=150&&t<=255&&n>=0&&n<=120}static removeGreenScreen(e){for(let t=0;t<e.length;t+=4){const n=e[t],a=e[t+1],i=e[t+2];this.isGreenPixel(n,a,i)?e[t+3]=0:this.reduceGreenSpill(e,t,n,a,i)}}static reduceGreenSpill(e,t,n,a,i){const o=a-Math.max(n,i);if(o>0){const r=.5*o;e[t]=Math.min(255,n+.8*r),e[t+2]=Math.min(255,i+.8*r),e[t+1]=Math.max(0,a-r)}}}const O=new class{constructor(){Object.defineProperty(this,"svgNS",{enumerable:!0,configurable:!0,writable:!0,value:"http://www.w3.org/2000/svg"})}createElement(e){const t=document.createElementNS(this.svgNS,e.tag);return e.attributes&&Object.entries(e.attributes).forEach(([e,n])=>{t.setAttribute(e,String(n))}),e.textContent&&(t.textContent=e.textContent),e.children&&e.children.forEach(e=>{const n=this.createElement(e);t.appendChild(n)}),t}createSVG(e,t,n,a,i){const o=document.createElementNS(this.svgNS,"svg");return o.setAttribute("width",String(e)),o.setAttribute("height",String(t)),o.setAttribute("viewBox",n),o.setAttribute("fill","none"),o.setAttribute("xmlns",this.svgNS),i&&o.setAttribute("class",i),a.forEach(e=>{const t=this.createElement(e);o.appendChild(t)}),o}},R={micUnmuted:()=>O.createSVG(17,17,"0 0 17 17",[{tag:"g",attributes:{"clip-path":"url(#clip0_655_3824)"},children:[{tag:"path",attributes:{d:"M8.67241 11.8448C9.49524 11.844 10.2841 11.5167 10.8659 10.9349C11.4478 10.3531 11.775 9.5642 11.7759 8.74138V4.60345C11.7759 3.78036 11.4489 2.99099 10.8669 2.40898C10.2849 1.82697 9.4955 1.5 8.67241 1.5C7.84933 1.5 7.05995 1.82697 6.47794 2.40898C5.89594 2.99099 5.56897 3.78036 5.56897 4.60345V8.74138C5.56982 9.5642 5.89707 10.3531 6.47889 10.9349C7.06071 11.5167 7.84959 11.844 8.67241 11.8448ZM6.60345 4.60345C6.60345 4.05472 6.82143 3.52847 7.20943 3.14047C7.59744 2.75246 8.12369 2.53448 8.67241 2.53448C9.22114 2.53448 9.74739 2.75246 10.1354 3.14047C10.5234 3.52847 10.7414 4.05472 10.7414 4.60345V8.74138C10.7414 9.2901 10.5234 9.81635 10.1354 10.2044C9.74739 10.5924 9.22114 10.8103 8.67241 10.8103C8.12369 10.8103 7.59744 10.5924 7.20943 10.2044C6.82143 9.81635 6.60345 9.2901 6.60345 8.74138V4.60345ZM9.18965 13.8879V15.9828C9.18965 16.1199 9.13516 16.2515 9.03816 16.3485C8.94116 16.4455 8.80959 16.5 8.67241 16.5C8.53523 16.5 8.40367 16.4455 8.30667 16.3485C8.20967 16.2515 8.15517 16.1199 8.15517 15.9828V13.8879C6.87994 13.7582 5.69812 13.1601 4.83826 12.2095C3.9784 11.2589 3.50158 10.0232 3.5 8.74138C3.5 8.6042 3.5545 8.47264 3.6515 8.37563C3.7485 8.27863 3.88006 8.22414 4.01724 8.22414C4.15442 8.22414 4.28598 8.27863 4.38299 8.37563C4.47999 8.47264 4.53448 8.6042 4.53448 8.74138C4.53448 9.83883 4.97044 10.8913 5.74645 11.6673C6.52247 12.4434 7.57497 12.8793 8.67241 12.8793C9.76986 12.8793 10.8224 12.4434 11.5984 11.6673C12.3744 10.8913 12.8103 9.83883 12.8103 8.74138C12.8103 8.6042 12.8648 8.47264 12.9618 8.37563C13.0588 8.27863 13.1904 8.22414 13.3276 8.22414C13.4648 8.22414 13.5963 8.27863 13.6933 8.37563C13.7903 8.47264 13.8448 8.6042 13.8448 8.74138C13.8433 10.0232 13.3664 11.2589 12.5066 12.2095C11.6467 13.1601 10.4649 13.7582 9.18965 13.8879Z",fill:"white"}}]},{tag:"defs",children:[{tag:"clipPath",attributes:{id:"clip0_655_3824"},children:[{tag:"rect",attributes:{width:"16",height:"16",fill:"white",transform:"translate(0.5 0.5)"}}]}]}],"np_companion-mic-unmuted"),micMuted:()=>O.createSVG(22,22,"0 0 17 18",[{tag:"g",attributes:{"clip-path":"url(#clip0_655_4192)"},children:[{tag:"path",attributes:{d:"M14.2432 14.6L3.89604 3.21808C3.80327 3.11843 3.67498 3.05936 3.53896 3.05368C3.40294 3.048 3.27016 3.09616 3.16941 3.18772C3.06866 3.27928 3.00806 3.40686 3.00075 3.5428C2.99343 3.67874 3.04 3.81208 3.13034 3.91392L5.58263 6.61131V8.7396C5.58251 9.26661 5.71656 9.78497 5.97216 10.2458C6.22776 10.7067 6.59649 11.0949 7.04361 11.3739C7.49073 11.6529 8.00151 11.8134 8.52782 11.8404C9.05414 11.8674 9.57867 11.7599 10.052 11.5282L10.7698 12.3171C10.138 12.6868 9.41878 12.8806 8.68679 12.8785C7.58946 12.8773 6.53741 12.4408 5.76148 11.6649C4.98555 10.889 4.54911 9.83693 4.54791 8.7396C4.54791 8.60239 4.4934 8.47079 4.39638 8.37377C4.29935 8.27675 4.16776 8.22224 4.03055 8.22224C3.89334 8.22224 3.76174 8.27675 3.66472 8.37377C3.5677 8.47079 3.51319 8.60239 3.51319 8.7396C3.51476 10.0217 3.9917 11.2577 4.85176 12.2085C5.71182 13.1594 6.8939 13.7575 8.16943 13.8873V15.9826C8.16943 16.1199 8.22394 16.2514 8.32096 16.3485C8.41798 16.4455 8.54958 16.5 8.68679 16.5C8.824 16.5 8.95559 16.4455 9.05262 16.3485C9.14964 16.2514 9.20415 16.1199 9.20415 15.9826V13.8867C10.0143 13.8085 10.794 13.5376 11.4779 13.0964L13.4775 15.2952C13.523 15.3464 13.5781 15.3881 13.6398 15.4178C13.7015 15.4476 13.7684 15.4648 13.8368 15.4685C13.9051 15.4722 13.9735 15.4622 14.038 15.4393C14.1025 15.4163 14.1618 15.3808 14.2125 15.3347C14.2632 15.2887 14.3042 15.2331 14.3332 15.171C14.3622 15.109 14.3786 15.0419 14.3815 14.9735C14.3843 14.9051 14.3736 14.8368 14.3499 14.7725C14.3261 14.7083 14.2899 14.6495 14.2432 14.5993V14.6ZM8.68679 10.809C8.13794 10.809 7.61157 10.591 7.22347 10.2029C6.83538 9.81482 6.61735 9.28845 6.61735 8.7396V7.7495L9.3115 10.7127C9.10943 10.7766 8.89873 10.8091 8.68679 10.809ZM12.4066 10.5562C12.6841 9.99093 12.8275 9.36929 12.8257 8.7396C12.8257 8.60239 12.8802 8.47079 12.9772 8.37377C13.0742 8.27675 13.2058 8.22224 13.343 8.22224C13.4802 8.22224 13.6118 8.27675 13.7089 8.37377C13.8059 8.47079 13.8604 8.60239 13.8604 8.7396C13.8625 9.52693 13.6831 10.3041 13.3359 11.0108C13.2934 11.0979 13.2273 11.1713 13.145 11.2226C13.0628 11.274 12.9679 11.3012 12.8709 11.3012C12.7922 11.3013 12.7145 11.2831 12.6439 11.2481C12.5207 11.1878 12.4265 11.0811 12.382 10.9513C12.3375 10.8215 12.3463 10.6794 12.4066 10.5562ZM5.84131 3.36358C6.12624 2.71004 6.62746 2.1745 7.26073 1.84696C7.894 1.51943 8.62071 1.41987 9.31874 1.56501C10.0168 1.71015 10.6435 2.09116 11.0938 2.64398C11.544 3.19681 11.7902 3.88776 11.7909 4.60072V8.7396C11.7908 8.8476 11.7852 8.95552 11.7741 9.06295C11.7608 9.19066 11.7005 9.30885 11.6049 9.39455C11.5092 9.48025 11.3852 9.52733 11.2568 9.52663C11.2387 9.52757 11.2205 9.52757 11.2025 9.52663C11.066 9.51229 10.9409 9.44435 10.8545 9.33775C10.7682 9.23115 10.7277 9.09462 10.742 8.95818C10.7491 8.88705 10.753 8.81332 10.753 8.74089V4.60072C10.7516 4.12605 10.5871 3.66628 10.2871 3.29848C9.98701 2.93069 9.56963 2.67722 9.10491 2.58058C8.64018 2.48393 8.15636 2.54998 7.73454 2.76766C7.31273 2.98534 6.97857 3.34141 6.78808 3.77618C6.7639 3.84253 6.72639 3.90322 6.67786 3.95452C6.62934 4.00583 6.57082 4.04665 6.50592 4.07449C6.44102 4.10232 6.37111 4.11658 6.30049 4.11637C6.22987 4.11617 6.16005 4.10151 6.09531 4.07329C6.03057 4.04508 5.9723 4.00392 5.92407 3.95233C5.87584 3.90075 5.83869 3.83983 5.81489 3.77335C5.7911 3.70686 5.78117 3.6362 5.78571 3.56573C5.79025 3.49526 5.80917 3.42646 5.84131 3.36358Z",fill:"white"}}]},{tag:"defs",children:[{tag:"clipPath",attributes:{id:"clip0_655_4192"},children:[{tag:"rect",attributes:{width:"16",height:"16",fill:"white",transform:"translate(0.5 0.5)"}}]}]}],"tc-mic-muted"),stop:()=>O.createSVG(20,20,"0 0 32 32",[{tag:"path",attributes:{d:"M5.92 24.096q0 0.832 0.576 1.408t1.44 0.608h16.128q0.832 0 1.44-0.608t0.576-1.408v-16.16q0-0.832-0.576-1.44t-1.44-0.576h-16.128q-0.832 0-1.44 0.576t-0.576 1.44v16.16z",fill:"#ffffff"}}]),volumeHigh(e){const t=[{tag:"path",attributes:{d:"M80 416L128 416L262.1 535.2C268.5 540.9 276.7 544 285.2 544C304.4 544 320 528.4 320 509.2L320 130.8C320 111.6 304.4 96 285.2 96C276.7 96 268.5 99.1 262.1 104.8L128 224L80 224C53.5 224 32 245.5 32 272L32 368C32 394.5 53.5 416 80 416z",fill:"#ffffff"}}];return e>0&&t.push({tag:"path",attributes:{d:"M412.6 245.5C402.3 237.1 387.2 238.7 378.8 249C370.4 259.3 372 274.4 382.3 282.8C393.1 291.6 400 305 400 320C400 335 393.1 348.4 382.3 357.3C372 365.7 370.5 380.8 378.8 391.1C387.1 401.4 402.3 402.9 412.6 394.6C434.1 376.9 448 350.1 448 320C448 289.9 434.1 263.1 412.6 245.5z",fill:"#ffffff"}}),e>=25&&t.push({tag:"path",attributes:{d:"M473.1 171C462.8 162.6 447.7 164.2 439.3 174.5C430.9 184.8 432.5 199.9 442.8 208.3C475.3 234.7 496 274.9 496 320C496 365.1 475.3 405.3 442.8 431.8C432.5 440.2 431 455.3 439.3 465.6C447.6 475.9 462.8 477.4 473.1 469.1C516.3 433.9 544 380.2 544 320.1C544 260 516.3 206.3 473.1 171.1z",fill:"#ffffff"}}),e>=75&&t.push({tag:"path",attributes:{d:"M533.6 96.5C523.3 88.1 508.2 89.7 499.8 100C491.4 110.3 493 125.4 503.3 133.8C557.5 177.8 592 244.8 592 320C592 395.2 557.5 462.2 503.3 506.3C493 514.7 491.5 529.8 499.8 540.1C508.1 550.4 523.3 551.9 533.6 543.6C598.5 490.7 640 410.2 640 320C640 229.8 598.5 149.2 533.6 96.5z",fill:"#ffffff"}}),O.createSVG(16,16,"0 0 640 640",t)},volumeMuted:()=>O.createSVG(16,16,"0 0 640 640",[{tag:"path",attributes:{d:"M80 416L128 416L262.1 535.2C268.5 540.9 276.7 544 285.2 544C304.4 544 320 528.4 320 509.2L320 130.8C320 111.6 304.4 96 285.2 96C276.7 96 268.5 99.1 262.1 104.8L128 224L80 224C53.5 224 32 245.5 32 272L32 368C32 394.5 53.5 416 80 416zM399 239C389.6 248.4 389.6 263.6 399 272.9L446 319.9L399 366.9C389.6 376.3 389.6 391.5 399 400.8C408.4 410.1 423.6 410.2 432.9 400.8L479.9 353.8L526.9 400.8C536.3 410.2 551.5 410.2 560.8 400.8C570.1 391.4 570.2 376.2 560.8 366.9L513.8 319.9L560.8 272.9C570.2 263.5 570.2 248.3 560.8 239C551.4 229.7 536.2 229.6 526.9 239L479.9 286L432.9 239C423.5 229.6 408.3 229.6 399 239z",fill:"#ffffff"}}]),end:()=>O.createSVG(16,16,"0 0 21 16",[{tag:"path",attributes:{d:"M17.7226 12.2992C18.3148 12.5423 18.991 12.308 19.307 11.7578L19.3954 11.6031C20.434 9.78662 20.2705 7.18344 18.2308 5.85533C13.5438 2.80798 7.45789 2.80798 2.77085 5.85533C0.726753 7.18344 0.567646 9.78662 1.60627 11.6031L1.69466 11.7578C2.01066 12.3125 2.68908 12.5445 3.2769 12.3014L6.32204 11.0462C6.83914 10.8341 7.15515 10.3059 7.0999 9.74684L6.90986 7.85081C9.2346 7.06853 11.7759 7.10831 14.0785 7.97456L13.8973 9.74684C13.8399 10.3037 14.1581 10.8297 14.6752 11.0462L17.7226 12.2992Z",fill:"red"}}])},L=(e,t)=>{if("inactiveTimeout"===e){const e=t;return e?.enabled&&void 0!==e.duration&&e.duration>18e4&&(I.critical_warn(`Napster Companion API SDK: inactiveTimeout duration of ${e.duration}ms exceeds the recommended maximum of 180000ms. Setting maximum allowed value.`),delete e.duration),t}return t},M={enabled:!1,batchSize:10,flushInterval:5e3,enablePerformanceTracking:!0,enableErrorTracking:!0,enableUserInteractionTracking:!0};class P{constructor(e={}){Object.defineProperty(this,"config",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"eventQueue",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"performanceQueue",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"errorQueue",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"flushTimer",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"sessionId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"providers",{enumerable:!0,configurable:!0,writable:!0,value:[]}),this.config={...M,...e},this.sessionId=this.config.sessionId||this.generateSessionId(),this.setupProviders(),this.config.enabled&&(this.startFlushTimer(),this.setupErrorTracking(),this.setupPerformanceTracking())}setupProviders(){this.providers=[],this.config.providers&&(this.providers=[...this.config.providers]),this.config.provider&&this.providers.push(this.config.provider),0===this.providers.length&&this.providers.push({type:"custom"})}generateSessionId(){return`session_${Date.now()}_${Math.random().toString(36).substr(2,9)}`}startFlushTimer(){this.flushTimer&&clearInterval(this.flushTimer),this.flushTimer=setInterval(()=>{this.flush()},this.config.flushInterval)}setupErrorTracking(){this.config.enableErrorTracking&&(window.addEventListener("error",e=>{this.trackError(e.error,{source:"window.error",filename:e.filename,lineno:e.lineno,colno:e.colno})}),window.addEventListener("unhandledrejection",e=>{this.trackError(new Error(e.reason),{source:"unhandledrejection",reason:e.reason})}))}setupPerformanceTracking(){this.config.enablePerformanceTracking&&"undefined"!=typeof window&&"performance"in window&&window.addEventListener("load",()=>{setTimeout(()=>{const e=performance.getEntriesByType("navigation")[0];e&&(this.trackPerformance("page_load_time",e.loadEventEnd-e.fetchStart,"ms"),this.trackPerformance("dom_content_loaded",e.domContentLoadedEventEnd-e.fetchStart,"ms"),this.trackPerformance("first_paint",e.responseEnd-e.fetchStart,"ms"))},0)})}trackEvent(e,t){if(!this.config.enabled)return;const n={name:e,properties:t,timestamp:Date.now(),userId:this.config.userId,sessionId:this.sessionId};this.eventQueue.push(n),this.eventQueue.length>=(this.config.batchSize||10)&&this.flush()}trackPerformance(e,t,n,a){if(!this.config.enabled||!this.config.enablePerformanceTracking)return;const i={name:e,value:t,unit:n,timestamp:Date.now(),context:a};this.performanceQueue.push(i)}trackError(e,t){if(!this.config.enabled||!this.config.enableErrorTracking)return;const n={error:e,context:t,timestamp:Date.now(),userId:this.config.userId,sessionId:this.sessionId,stack:e.stack};this.errorQueue.push(n),this.flushErrors()}trackInteraction(e,t,n){this.config.enableUserInteractionTracking&&this.trackEvent("user_interaction",{action:e,target:t,...n})}flush(){this.flushEvents(),this.flushPerformance(),this.flushErrors()}flushEvents(){if(0===this.eventQueue.length)return;const e=[...this.eventQueue];this.eventQueue=[],this.sendData("events",e)}flushPerformance(){if(0===this.performanceQueue.length)return;const e=[...this.performanceQueue];this.performanceQueue=[],this.sendData("performance",e)}flushErrors(){if(0===this.errorQueue.length)return;const e=[...this.errorQueue];this.errorQueue=[],this.sendData("errors",e)}async sendData(e,t){const n=this.providers.map(n=>this.sendToProvider(n,e,t));await Promise.allSettled(n)}async sendToProvider(e,t,n){try{switch(e.type){case"google-analytics-4":await this.sendToGA4(e,n);break;case"mixpanel":await this.sendToMixpanel(e,n);break;case"segment":await this.sendToSegment(e,n);break;case"amplitude":await this.sendToAmplitude(e,n);break;case"posthog":await this.sendToPostHog(e,n);break;case"azure-insights":await this.sendToAzureInsights(e,n);break;default:await this.sendToCustomEndpoint(e,t,n)}}catch(t){I.critical_warn(`Failed to send data to ${e.type}:`,t)}}async sendToCustomEndpoint(e,t,n){const a=e.endpoint,i=e.apiKey;if(!a)return void("development"===process.env.NODE_ENV&&I.info(`Analytics [${t}]:`,n));const o=await fetch(`${a}/${t}`,{method:"POST",headers:{"Content-Type":"application/json",...i&&{Authorization:`Bearer ${i}`}},body:JSON.stringify({data:n,sessionId:this.sessionId,timestamp:Date.now()})});if(!o.ok)throw new Error(`HTTP ${o.status}`)}async sendToGA4(e,t){const n=e.measurementId||e.apiKey;if(!n)throw new Error("GA4 measurement ID required");const a=`https://www.google-analytics.com/mp/collect?measurement_id=${n}&api_secret=${e.apiKey||"default"}`,i=t.map(e=>({name:e.name,params:{...e.properties,session_id:this.sessionId}}));await fetch(a,{method:"POST",body:JSON.stringify({client_id:this.sessionId,user_id:this.config.userId,events:i})})}async sendToMixpanel(e,t){const n=e.projectToken||e.apiKey;if(!n)throw new Error("Mixpanel project token required");const a=e.endpoint||"https://api.mixpanel.com/batch",i=t.map(e=>{const t=e;return{event:t.name,properties:{token:n,distinct_id:this.config.userId||this.sessionId,time:t.timestamp||Date.now(),...t.properties}}});await fetch(a,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(i)})}async sendToSegment(e,t){const n=e.writeKey||e.apiKey;if(!n)throw new Error("Segment write key required");const a=e.endpoint||"https://api.segment.io/v1/batch",i=t.map(e=>({type:"track",userId:this.config.userId||this.sessionId,event:e.name,properties:e.properties,timestamp:new Date(e.timestamp||Date.now()).toISOString()}));await fetch(a,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Basic ${btoa(n+":")}`},body:JSON.stringify({batch:i})})}async sendToAmplitude(e,t){const n=e.apiKey;if(!n)throw new Error("Amplitude API key required");const a=e.endpoint||"https://api2.amplitude.com/2/httpapi",i=t.map(e=>({user_id:this.config.userId||this.sessionId,event_type:e.name,event_properties:e.properties,time:e.timestamp||Date.now()}));await fetch(a,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({api_key:n,events:i})})}async sendToPostHog(e,t){const n=e.apiKey,a=e.endpoint||"https://app.posthog.com";if(!n)throw new Error("PostHog API key required");const i=t.map(e=>({event:e.name,properties:{...e.properties,distinct_id:this.config.userId||this.sessionId},timestamp:new Date(e.timestamp||Date.now()).toISOString()}));await fetch(`${a}/batch/`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({api_key:n,batch:i})})}async sendToAzureInsights(e,t){const n=e.apiKey;if(!n)throw new Error("Azure Application Insights instrumentation key required");const a=e.endpoint||"https://dc.services.visualstudio.com/v2/track",i=t.map(e=>{const t=e;return{name:"Microsoft.ApplicationInsights.Event",time:new Date(t.timestamp||Date.now()).toISOString(),iKey:n,data:{baseType:"EventData",baseData:{name:t.name,properties:t.properties}}}});await fetch(a,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(i)})}updateConfig(e){this.config={...this.config,...e},this.setupProviders(),this.config.enabled&&!this.flushTimer?this.startFlushTimer():!this.config.enabled&&this.flushTimer&&(clearInterval(this.flushTimer),this.flushTimer=void 0)}destroy(){this.flushTimer&&clearInterval(this.flushTimer),this.flush()}}let x=null;const V=(e,t)=>{x?.trackEvent(e,t)},F=(e,t,n)=>{x?.trackInteraction(e,t,n)};function W(e,{content:t,placement:n="top"}){let a=!1,i=null,o=null;const r=e=>"left"===e?"start":"right"===e?"end":e,s=()=>{if(!i)return;const t=e.getBoundingClientRect(),a=i.getBoundingClientRect();let o=0,r=0;switch(n){case"top":o=t.top-a.height-8,r=t.left+(t.width-a.width)/2;break;case"bottom":o=t.bottom+8,r=t.left+(t.width-a.width)/2;break;case"left":o=t.top+(t.height-a.height)/2,r=t.left-a.width-8;break;case"right":o=t.top+(t.height-a.height)/2,r=t.right+8}i.style.top=`${o}px`,i.style.left=`${r}px`},c=()=>s(),d=()=>{if(a)return;const e=(()=>{if(i)return i;const e=document.createElement("div");e.className=`tooltip styled-tooltip bs-tooltip-${r(n)} show`,e.setAttribute("role","tooltip"),Object.assign(e.style,{position:"fixed",top:"0px",left:"0px",zIndex:String(2147483647),opacity:"0",visibility:"hidden",pointerEvents:"none",transition:"opacity 80ms ease"});const a=document.createElement("div");a.className="tooltip-arrow";const o=document.createElement("div");return o.className="tooltip-inner","string"==typeof t?o.textContent=t:o.appendChild(t),e.appendChild(a),e.appendChild(o),document.body.appendChild(e),i=e,e})();a=!0,s(),o=window.setTimeout(s,10),e.style.opacity="1",e.style.visibility="visible",window.addEventListener("scroll",c,!0),window.addEventListener("resize",c)},l=()=>{a&&(a=!1,null!=o&&(window.clearTimeout(o),o=null),i&&(i.style.opacity="0",i.style.visibility="hidden"),window.removeEventListener("scroll",c,!0),window.removeEventListener("resize",c))},u=()=>d(),p=()=>l();return e.addEventListener("mouseenter",u),e.addEventListener("mouseleave",p),e.matches?.(":hover")&&d(),{update:e=>{if(void 0!==e.content&&i){const t=i.querySelector(".tooltip-inner");t&&(t.innerHTML="","string"==typeof e.content?t.textContent=e.content:t.appendChild(e.content))}void 0!==e.placement&&(n=e.placement,i&&(i.className=`tooltip styled-tooltip bs-tooltip-${r(n)} show`)),a&&s()},show:d,hide:l,destroy:()=>{l(),e.removeEventListener("mouseenter",u),e.removeEventListener("mouseleave",p),i&&i.parentNode&&i.parentNode.removeChild(i),i=null}}}function j(e,t){const n=document.createElement(e);return t&&(n.className=t),n}var $,U,B,G,K,z,q;!function(e){e.LOCAL_TIMEOUT="local_timeout",e.SERVER_WARNING="server_warning"}($||($={}));class H{constructor(e,t={}){Object.defineProperty(this,"overlayController",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"currentTrigger",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"isVisible",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"mountElement",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"callbacks",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.mountElement=e,this.callbacks=t}show(e){this.isVisible?I.warn("Inactive overlay already visible, ignoring show request"):(I.info(`Showing inactive overlay (trigger: ${e.type})`),this.currentTrigger=e,this.isVisible=!0,this.overlayController=function(e,t){const n={duration:t.duration??30,isInteractionNeeded:t.isInteractionNeeded??!1,message:t.message??"It looks like you've been inactive for a while. Would you like to continue this conversation?",onContinue:t.onContinue,onEnd:t.onEnd},a=document.createElement("div");a.className="np_companion-inactive-overlay";const i=document.createElement("div");i.className="np_companion-inactive-dialog";const o=document.createElement("p");o.className="np_companion-inactive-message",o.textContent=n.message;const r=document.createElement("div");r.className="np_companion-inactive-timer";const s=document.createElement("div");s.className="np_companion-timer-circle";const c=document.createElementNS("http://www.w3.org/2000/svg","svg");c.setAttribute("viewBox","0 0 36 36");const d=document.createElementNS("http://www.w3.org/2000/svg","path");d.setAttribute("d","M18 2.0845 a 15.9155 15.9155 0 0 1 0 31.831 a 15.9155 15.9155 0 0 1 0 -31.831"),d.setAttribute("fill","none"),d.setAttribute("stroke","rgba(255, 255, 255, 0.2)"),d.setAttribute("stroke-width","2");const l=document.createElementNS("http://www.w3.org/2000/svg","path");l.setAttribute("d","M18 2.0845 a 15.9155 15.9155 0 0 1 0 31.831 a 15.9155 15.9155 0 0 1 0 -31.831"),l.setAttribute("fill","none"),l.setAttribute("stroke","#fff"),l.setAttribute("stroke-width","2");const u=document.createElement("span");u.className="np_companion-timer-number",s.appendChild(c),c.appendChild(d),c.appendChild(l),s.appendChild(u),r.appendChild(s);const p=document.createElement("div");p.className="np_companion-inactive-buttons";const h=document.createElement("button");h.className="np_companion-end-button np_companion__d-none",h.textContent="End Conversation";let m=null;const f=e=>{e&&!m?(m=document.createElement("button"),m.className="np_companion-continue-button",m.textContent="Continue Talking",p.appendChild(m),m.addEventListener("click",n.onContinue)):!e&&m&&(m.removeEventListener("click",n.onContinue),m.parentNode&&m.parentNode.removeChild(m),m=null)};p.appendChild(h),f(n.isInteractionNeeded),i.appendChild(o),i.appendChild(r),i.appendChild(p),a.appendChild(i),e.appendChild(a);let v=Math.max(0,Math.floor(n.duration)),g=null;const C=()=>{u.textContent=String(v),l.setAttribute("stroke-dasharray",(n.duration>0?v/n.duration*100:0)+", 100")},b=()=>{if(v<=0)return E(),void n.onEnd();v-=1,C()},y=()=>{E(),C(),g=window.setInterval(b,1e3)},E=()=>{null!=g&&(window.clearInterval(g),g=null)};return h.addEventListener("click",()=>{E(),n.onEnd()}),y(),{update:e=>{if(void 0!==e.message&&(n.message=e.message,o.textContent=n.message),void 0!==e.isInteractionNeeded&&(n.isInteractionNeeded=!!e.isInteractionNeeded,f(n.isInteractionNeeded)),void 0!==e.duration){const t=Math.max(0,Math.floor(e.duration));n.duration=t,v=t,y()}e.onContinue&&(m&&(m.removeEventListener("click",n.onContinue),m.addEventListener("click",e.onContinue)),n.onContinue=e.onContinue),e.onEnd&&(n.onEnd=e.onEnd)},destroy:()=>{E(),h.removeEventListener("click",n.onEnd),m&&m.removeEventListener("click",n.onContinue),a.parentNode&&a.parentNode.removeChild(a)}}}(this.mountElement,{duration:e.duration,message:e.message,isInteractionNeeded:e.isInteractionNeeded,onContinue:()=>this.handleContinue(),onEnd:()=>this.handleEnd()}),this.callbacks.onShow?.(e))}hide(){this.isVisible&&(I.info("Hiding inactive overlay"),this.isVisible=!1,this.currentTrigger=null,this.overlayController&&(this.overlayController.destroy(),this.overlayController=null),this.callbacks.onHide?.())}isShowing(){return this.isVisible}getCurrentTrigger(){return this.currentTrigger}handleContinue(){I.info("User clicked continue on inactive overlay"),this.hide(),this.callbacks.onContinue?.()}handleEnd(){I.info("Inactive overlay countdown ended"),this.hide(),this.callbacks.onEnd?.()}destroy(){this.hide()}}!function(e){e.TALK_STATE_CHANGED="talk_state_changed",e.MESSAGE_RECEIVED="message_received",e.TRANSCRIPT="transcript",e.AUDIO_TRANSCRIPT_DELTA="response.audio_transcript.delta",e.AUDIO_TRANSCRIPT_DONE="response.audio_transcript.done",e.RESPONSE_DONE="response.done"}(U||(U={})),function(e){e.STARTED="started",e.ENDED="ended",e.CANCELED="canceled"}(B||(B={})),function(e){e.DELTA="delta",e.COMPLETED="completed"}(G||(G={})),function(e){e.USER="user",e.ASSISTANT="assistant"}(K||(K={})),function(e){e.SET_REMOTE_DESCRIPTION="set_remote_description",e.SET_LOCAL_DESCRIPTION="set_local_description",e.ADD_ICE_CANDIDATE="add_ice_candidate",e.ERROR="error"}(z||(z={})),function(e){e.SEND_QUESTION="send_question",e.CANCEL="cancel"}(q||(q={}));const Q={iceServers:[{urls:"stun:stun1.ciscape.com:3478"},{urls:"turn:stun1.ciscape.com:3478",username:"tcuser",credential:"dw4k_BR2f-Y4A-@aT7ip@Qzs"},{urls:"stun:129.146.43.226:3478"},{urls:"stun:stun.l.google.com:19302"},{urls:"stun:stun1.l.google.com:19302"},{urls:"turn:129.146.43.226:3478",username:"teamtime_turn",credential:"teamtime"}]};function J(e,t){if(t)for(const n in t)try{const a=t[n];"string"!=typeof a&&"number"!=typeof a||(e.style[n]=a)}catch{I.warn(`Failed to apply style for key "${n}: ${t[n]}".`)}}function Z(e,t,n){const a=[];return a.push("np_companion-align-middle"),e&&(a.push("np_companion-container-fixed"),a.push(`np_companion-${e}`),t&&a.push(`np_companion-view-${t}`)),n&&a.push(n),a.join(" ")}class Y{constructor(){Object.defineProperty(this,"version",{enumerable:!0,configurable:!0,writable:!0,value:"1.0.0-alpha.12"}),Object.defineProperty(this,"mountTarget",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"rootEl",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"embed",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"webrtcController",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"config",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"isInitialized",{enumerable:!0,configurable:!0,writable:!0,value:!1})}static getInstance(){return Y.instance||(Y.instance=new Y),Y.instance}renderApp(){this.mountTarget&&this.config&&(this.rootEl||(this.rootEl=document.createElement("div"),this.rootEl.id="np_companion-sdk-root",this.mountTarget.appendChild(this.rootEl)),this.rootEl.className=Z(this.config.position,this.config.avatarStyle?.view,this.config.className),J(this.rootEl,this.config.style),this.embed?this.embed.update({avatarStyle:this.config.avatarStyle,features:S.getState().app.features,onData:this.config.onData,onAvatarReady:this.config.onAvatarReady,onInactivityStatusChange:this.config.onInactivityStatusChange,onDestroy:()=>this.destroyInstance("ui_end"),onError:this.config.onError}):this.embed=function(e,t={}){const n=A.createDiv("np_companion-live-container np_companion-fade-in");e.appendChild(n);const a=function(e,t={}){const n=A.createDiv("np_companion-avatar"),a=A.createDiv(`np_companion-avatar-container np_companion-loader-${t.features?.showSDKLoader?.type??"spinner"}`);a.id="np_companion-avatar-container",t.avatarStyle?.view&&a.classList.add(`np_companion-view-${t.avatarStyle.view}`);const i=A.createDiv("loader-container"),o=A.createDiv("loader");i.appendChild(o);const r=A.createVideo({className:"np_companion-avatar-video",autoplay:!0,muted:!0,playsInline:!0}),s=A.createAudio({className:"np_companion-avatar-audio",autoplay:!0}),c=A.createCanvas({className:"np_companion-avatar-canvas",styles:{width:"100%",height:"100%",objectFit:"cover",position:"relative",zIndex:"1"}});t.features?.backgroundRemoval?.enabled&&"silhouette"===t.avatarStyle?.view?r.classList.add("np_companion__d-none"):c.classList.add("np_companion__d-none"),a.appendChild(i),a.appendChild(r),a.appendChild(s),a.appendChild(c);const d=A.createDiv(`${k.wrapper} np_companion-action-btn-container-view-${t.avatarStyle?.view}`),p=A.createDiv(`np_companion-disclaimer-text np_companion-disclaimer-view-${t.avatarStyle?.view}`);p.style.display="none";const h=A.createDiv(`np_companion-avatar-control-container np_companion-avatar-control-view-${t.avatarStyle?.view}`);h.appendChild(d),h.appendChild(p),n.appendChild(a),n.appendChild(h),e.appendChild(n);let m=null,f=(t.features?.backgroundRemoval?.enabled&&"silhouette"===t.avatarStyle?.view)??!1,v=null,g=null,C=!1,b=!1,y=!1,E=!0,w=null,_=null,T=null;const O=new H(n,{onContinue:()=>{K(),z()},onEnd:()=>{}});let L=null;const M=()=>{E||(E=!0,h.className=x(),null!=w&&window.clearTimeout(w))},P=()=>{null!=w&&window.clearTimeout(w),w=window.setTimeout(()=>{E=!1,h.className=x()},5e3)};function x(){return N(`np_companion-avatar-control-container np_companion-avatar-control-view-${t.avatarStyle?.view}`,{[k.collapse]:!E})}function V(e){if(!y)return;const n=t.avatarStyle?.borderWidth??("silhouette"!==t.avatarStyle?.view?"4px":void 0);n&&(a.style.borderWidth=n);const i=("silhouette"!==t.avatarStyle?.view?e?"#ec3e41":t.avatarStyle?.borderColor??"#C0C0C0":void 0)??t.avatarStyle?.borderColor;i&&(a.style.borderColor=i);const o=t.avatarStyle?.borderStyle??("silhouette"!==t.avatarStyle?.view?"solid":void 0);o&&(a.style.borderStyle=o)}function F(e){"round"===t.avatarStyle?.view&&(a.style.transform=`translate(-50%, ${e??352-h.offsetHeight-212-12+"px"})`)}function U(){const e=t.features?.disclaimer?.enabled??!1;p.style.display=e&&y?"-webkit-box":"none",_?.update({features:{disclaimer:{enabled:e}}});const n=t.features?.disclaimer?.text??"This is an AI avatar. Check important info.";t.features?.disclaimer?.color&&(p.style.color=t.features?.disclaimer?.color),p.textContent=n,y&&F(e?void 0:"8%")}function B(){y||!t.features?.showSDKLoader?.enabled?n.classList.add("np_companion-bg-transparent"):n.classList.remove("np_companion-bg-transparent")}function G(){t.features?.showSDKLoader?.bgColor&&n.style.setProperty("--np-loader-bg-color",t.features.showSDKLoader.bgColor),t.features?.showSDKLoader?.color&&n.style.setProperty("--np-loader-color",t.features.showSDKLoader.color)}function K(){T&&(I.timer("Resetting inactive timeout due to activity"),clearTimeout(T),T=null,S.dispatch(l(!1)),t.onInactivityStatusChange?.(!1))}function z(){const e=t.features?.inactiveTimeout;e?.enabled?(K(),T=setTimeout(()=>{I.timer(`Inactive timeout of ${e?.duration}ms reached, showing inactive overlay`),S.dispatch(l(!0)),t.onInactivityStatusChange?.(!0),m&&(m.getAudioTracks().forEach(e=>e.enabled=!1),_?.update({isMuted:!0}),V(!0)),O.isShowing()||O.show({type:$.LOCAL_TIMEOUT,duration:Math.min(e.countdown??30,60),message:void 0,isInteractionNeeded:!0})},e.duration)):(K(),O.isShowing()&&O.hide())}function Q(){if(!_&&y){const e=!1;_=function(e,t){let n={...t},a=null,i=null,o=[],r=!1;const s=document.createElement("div");s.className=_();const c=j("div",k.container),d=j("div",N(k.questionBar,k.alignBetween)),l=j("div",k.left),u=j("div",k.iconButtonWithState(n.isMuted));u.appendChild(n.isMuted?R.micMuted():R.micUnmuted()),n.toggleMute&&u.addEventListener("click",()=>n.toggleMute?.());const p=j("div",k.middle),h=j("div",k.wave);S();const m=document.createElement("canvas");m.width=160,m.height=40,m.className=k.canvas,h.appendChild(m);const f=j("div",N(k.right,k.alignBetween)),v=j("div",N(k.iconButton(),k.stop)),g=function(e,t={}){let n={initialVolume:50,...t},a=n.initialVolume??50,i=!1,o=!1;const r=document.createElement("div");r.className="np_volume-control";const s=document.createElement("div");s.className="np_volume-slider-container";const c=document.createElement("div");c.className="np_volume-slider-track";const d=document.createElement("div");d.className="np_volume-slider-fill";const l=document.createElement("div");l.className="np_volume-slider-thumb",c.appendChild(d),c.appendChild(l),s.appendChild(c);const u=document.createElement("div");function p(){let e;u.innerHTML="",e=i||0===a?R.volumeMuted():R.volumeHigh(a||100),u.appendChild(e)}function h(){const e=a;d.style.height=`${e}%`,l.style.bottom=`${e}%`}function m(){o=!o,o?s.classList.add("np_volume-slider-visible"):s.classList.remove("np_volume-slider-visible")}function f(e){const t=c.getBoundingClientRect(),o=Math.max(0,Math.min(100,(t.bottom-e)/t.height*100));a=o,h(),i=0===a,i?u.classList.add("np_volume-muted"):u.classList.remove("np_volume-muted"),p(),n.onChange?.(a)}u.className=k.iconButton(),u.setAttribute("aria-label","Volume control"),p(),r.appendChild(s),r.appendChild(u),e.appendChild(r),u.addEventListener("click",e=>{e.stopPropagation(),i=!i,i?(n.initialVolume=a,a=0,h(),u.classList.add("np_volume-muted")):(a=n.initialVolume||50,h(),u.classList.remove("np_volume-muted")),p(),n.onMuteToggle?.(i)}),r.addEventListener("mouseenter",e=>{e.stopPropagation(),o||m()}),r.addEventListener("mouseleave",e=>{setTimeout(()=>{e.stopPropagation(),o&&m()},300)});let v=!1;return c.addEventListener("mousedown",e=>{v=!0,f(e.clientY),e.preventDefault()}),document.addEventListener("mousemove",e=>{v&&f(e.clientY)}),document.addEventListener("mouseup",()=>{v=!1}),l.addEventListener("mousedown",e=>{v=!0,e.preventDefault()}),c.addEventListener("touchstart",e=>{v=!0,f(e.touches[0].clientY),e.preventDefault()}),document.addEventListener("touchmove",e=>{v&&e.touches.length>0&&f(e.touches[0].clientY)}),document.addEventListener("touchend",()=>{v=!1}),document.addEventListener("click",e=>{o&&!r.contains(e.target)&&m()}),h(),{setVolume(e){a=Math.max(0,Math.min(100,e)),h(),p(),n.onChange?.(a)},getVolume:()=>a,toggleMute(){i=!i,i?u.classList.add("np_volume-muted"):u.classList.remove("np_volume-muted"),n.onMuteToggle?.(i)},isMuted:()=>i,update(e){n={...n,...e}},destroy(){r.remove()}}}(v,{initialVolume:50,onChange:e=>{n.onVolumeChange?.(e)},onMuteToggle:e=>{n.onVolumeChange?.(e?0:g.getVolume())}});g.setVolume(70);const C=j("div",k.iconButtonEnd());C.appendChild(R.end()),n.handleEnd&&C.addEventListener("click",()=>n.handleEnd?.()),l.appendChild(u),p.appendChild(h),f.appendChild(v),f.appendChild(C),d.appendChild(l),d.appendChild(f),c.appendChild(d),s.appendChild(c),e.appendChild(s);let b=null,y=null,E=null;function w(){if(!n.userMicrophoneStream)return;const e=new(window.AudioContext||window.webkitAudioContext);a=e.createAnalyser(),e.createMediaStreamSource(n.userMicrophoneStream).connect(a),function(e){if(!a)return;const t=m.getContext("2d");if(!t)return;a.fftSize=256;const n=new Uint8Array(a.frequencyBinCount),s=Math.floor(m.width/3);0===o.length&&(o=new Array(s).fill(0));let c=0;const d=()=>{if(t.clearRect(0,0,m.width,m.height),t.beginPath(),t.moveTo(0,m.height/2),t.lineTo(m.width,m.height/2),t.strokeStyle="#ffffff",t.stroke(),e)r=!1,o.fill(0),S();else{a.getByteFrequencyData(n);const e=6,i=3,s=n.reduce((e,t)=>e+t,0)/n.length/255*m.height*.8;o.shift(),o.push(s);let d=o.filter(t=>t>e).length>=i;d?c=30:c>0&&(c--,d=!0),r=d,S(),t.fillStyle="#ffffff";for(let e=0;e<o.length;e++){const n=3*e,a=o[e];t.fillRect(n,m.height/2-a/2,2,a),t.fillRect(n,m.height/2+a/2,2,-a)}}i=requestAnimationFrame(d)};d()}(!!n.isMuted)}function _(){return N(k.alignMiddle,`np_companion-avatar-${n.avatarStyle?.view}`)}function S(){h.style.filter=!n.isMuted&&r?"brightness(0) saturate(100%) invert(48%) sepia(93%) saturate(1720%) hue-rotate(346deg) brightness(101%) contrast(103%)":"none",h.style.transition="filter 0.3s ease",h.style.height="40px"}function T(){b?.destroy(),b=W(u,{content:n.isMuted?"Unmute":"Mute",placement:"top"}),y?.destroy(),y=null}function I(){for(u.className=k.iconButtonWithState(n.isMuted);u.firstChild;)u.removeChild(u.firstChild);u.appendChild(n.isMuted?R.micMuted():R.micUnmuted())}return b=W(u,{content:n.isMuted?"Unmute":"Mute",placement:"top"}),E=W(C,{content:"End Session",placement:"top"}),w(),{update(e){const t=n;n={...n,...e},s.className=_(),t.isMuted!==n.isMuted&&(I(),T()),t.isAvatarSpeaking!==n.isAvatarSpeaking&&(I(),T()),t.userMicrophoneStream===n.userMicrophoneStream&&t.selectedMicrophone===n.selectedMicrophone||(null!=i&&(cancelAnimationFrame(i),i=null),o=[],a=null,w()),S(),n.features?.disclaimer?.enabled?c.classList.remove("np_companion_disclaimer-disabled"):c.classList.add("np_companion_disclaimer-disabled")},destroy(){b?.destroy(),y?.destroy(),E?.destroy(),null!=i&&cancelAnimationFrame(i),s.parentNode&&s.parentNode.removeChild(s)}}}(d,{avatarStyle:t.avatarStyle,isMuted:e,isAvatarSpeaking:b,userMicrophoneStream:m,features:{waveform:{enabled:!1!==t.features?.waveform?.enabled}},onVolumeChange:e=>{s.volume=e/100},toggleMute:()=>{const t=!(S.getState().avatar.muted??e);S.dispatch(u(t)),m&&m.getAudioTracks().forEach(e=>e.enabled=!t),_?.update({isMuted:t}),V(t),K(),z()},onStopTalking:()=>{try{const e=S.getState().avatar.dataChannel;if(e&&"open"===e.readyState){const t={type:q.CANCEL};I.avatar("stopping avatar"),e.send(JSON.stringify(t))}else I.critical_warn("Stopping avatar: Data channel not open")}catch(e){I.critical_error("Avatar","Stop: failed to send interrupt",e)}K(),z()},handleEnd:()=>{t.onDestroy?.()}})}}n.addEventListener("mouseenter",M),n.addEventListener("mousemove",M),n.addEventListener("mouseleave",P);const J=()=>{if(C)return;const e=c.getContext("2d",{willReadFrequently:!0});if(!e||!r||r.readyState<2)L=requestAnimationFrame(J);else{if(c.width=r.videoWidth,c.height=r.videoHeight,e.drawImage(r,0,0,c.width,c.height),f){const n=e.getImageData(0,0,c.width,c.height),a=D.process(n);e.putImageData(a,0,0),y||(t.onAvatarReady?.(!0),y=!0,V(),Q(),B(),U(),z(),P())}L=requestAnimationFrame(J)}};U(),G(),B();const Z={updateStreams:({videoStream:e,audioStream:n,userMicrophoneStream:a})=>{e&&e instanceof MediaStream?v!==e&&(I.avatar("New video stream received:",{active:e.active,tracks:e.getTracks().length,videoTracks:e.getVideoTracks().length,id:e.id}),v=e,r.srcObject=e,r.play().then(()=>{f||y||(t.onAvatarReady?.(!0),y=!0,V(),Q(),B(),U(),z(),F(),P())}).catch(e=>{I.error("Failed to play video stream",e),t.onError?.(e)}),e.addEventListener("inactive",()=>{I.avatar("Video stream became inactive")}),e.getTracks().forEach(e=>{e.addEventListener("ended",()=>{I.avatar("Video track ended:",e.kind)})}),f&&!L&&(L=requestAnimationFrame(J))):(v=null,r.srcObject=null),void 0!==n&&(n&&n instanceof MediaStream?g!==n&&(g=n,s.srcObject=n,s.play().catch(e=>{I.error("Failed to play audio stream",e),t.onError?.(e)})):(g=null,s.srcObject=null)),void 0!==a&&(m=a??null,_?.update({userMicrophoneStream:m}))},updateWaveform:e=>{Q(),_?.update(e)},updateFeatures:e=>{t.features={...t.features||{},...e||{}},f=(t.features?.backgroundRemoval?.enabled&&"silhouette"===t.avatarStyle?.view)??!1,f?(r.classList.add("np_companion__d-none"),c.classList.remove("np_companion__d-none")):(r.classList.remove("np_companion__d-none"),c.classList.add("np_companion__d-none")),_?.update({features:{waveform:{enabled:!1!==t.features?.waveform?.enabled}}}),U(),G(),B(),z()},update:e=>{const n=t.avatarStyle?.view;Object.assign(t,e),e.features&&Z.updateFeatures(e.features),e.avatarStyle?.view&&e.avatarStyle.view!==n&&(n&&a.classList.remove(`np_companion-view-${n}`),a.classList.add(`np_companion-view-${e.avatarStyle.view}`),t.features&&Z.updateFeatures(t.features))},setAvatarReady:e=>{e||(y=!1,t.onAvatarReady?.(!1))},handleMessage:e=>{switch("undefined"!=typeof window&&window.parent&&window.parent.postMessage({type:"avatar-data-channel-message",event:e},"*"),e.event){case"avatar_state_changed":break;case"talk_state_changed":b="ended"!==e.data?.state&&"canceled"!==e.data?.state,_?.update({isAvatarSpeaking:b});break;case"message_received":{const{message:t}=e.data||{};if("completed"===t?.action&&"string"==typeof t.content&&t.role){K(),z();const e=O.getCurrentTrigger();e&&!e.isInteractionNeeded&&O.hide()}break}case"avatar_connection_warning":t.showAvatarInactiveOverlay&&(O.show({type:$.SERVER_WARNING,duration:e.data?.disconnect_after??30,message:"Avatar is disconnecting due to inactivity. Say something to keep it active.",isInteractionNeeded:!1}),m&&(m.getAudioTracks().forEach(e=>e.enabled=!0),_?.update({isMuted:!1}),V(!1)))}t.onData?t.onData(e):I.data("onData callback NOT called. Reason:",{onDataExists:!!t.onData,dataType:typeof e,dataIsNull:null===e})},destroy:e=>{C||(C=!0,n.removeEventListener("mousemove",M),n.removeEventListener("mouseenter",M),n.removeEventListener("mouseleave",P),null!=w&&window.clearTimeout(w),null!=L&&(cancelAnimationFrame(L),L=null),T&&(clearTimeout(T),T=null),_?.destroy(),_=null,O?.destroy(),n.parentNode&&n.parentNode.removeChild(n),y=!1,t.onAvatarReady?.(!1),e||t.onDestroy?.())}};return Z}(n,{avatarStyle:t.avatarStyle,showAvatarInactiveOverlay:!0,onData:t.onData,onDestroy:t.onDestroy,onError:t.onError,onInactivityStatusChange:t.onInactivityStatusChange,onAvatarReady:t.onAvatarReady,features:t.features});return{update:e=>{a.update({avatarStyle:e.avatarStyle??t.avatarStyle,onData:e.onData??t.onData,onDestroy:e.onDestroy??t.onDestroy,onError:e.onError??t.onError,onInactivityStatusChange:e.onInactivityStatusChange??t.onInactivityStatusChange,onAvatarReady:e.onAvatarReady??t.onAvatarReady,features:e.features??t.features}),Object.assign(t,e)},updateStreams:e=>{a.updateStreams(e)},handleMessage:e=>{a.handleMessage(e)},destroy:()=>{a.destroy(!0),n.parentNode===e&&e.removeChild(n),t.onDestroy?.()}}}(this.rootEl,{avatarStyle:this.config.avatarStyle,features:S.getState().app.features,onData:this.config.onData,onAvatarReady:this.config.onAvatarReady,onInactivityStatusChange:this.config.onInactivityStatusChange,onDestroy:()=>this.destroyInstance("ui_end"),onError:this.config.onError}),this.initializeWebRTC().catch(e=>{I.critical_error("Failed to establish WebRTC connection:",e),this.config?.onError?.(e)}))}async initializeWebRTC(){const e=S.getState().avatar.connectionToken;if(e&&!this.webrtcController){I.connection("Connecting WebRTC..."),this.webrtcController=function(e={}){const{currentAudioDeviceId:t,onChatMessage:n,onConnectionSuccess:a,onConnectionError:i,onStreams:s,onDataChannel:c,maxReconnectAttempts:l=3,reconnectInterval:u=2e3}=e;let m=null,f=null,v=null,g=null,C=null,b=null,y=null,E="disconnected",w=0,_=null,T=null,N=!0,k=null;function A(e,t){e&&e.readyState===WebSocket.OPEN?e.send(JSON.stringify(t)):I.critical_warn("WebRTC",`WS send skipped; state=${e?.readyState}`)}function D(e){k=e,i?.(e)}function O(e){E=e,I.webrtc(`Connection status changed to: ${e}`)}function R(){!N||!T||w>=l?w>=l&&D(new o("WebSocket connection failed after max retry attempts",{maxAttempts:l,lastAttempt:w})):(w+=1,O("reconnecting"),I.webrtc(`Attempting to reconnect (${w}/${l})...`),_=setTimeout(async()=>{try{if(!T)return;await L(T.connection.signalingEndpoint,T.connection.id,!0),!m&&T&&await M(T.token)}catch(e){I.error("WebRTC","Reconnection attempt failed:",e),w<l&&R()}},u))}async function L(e,t,n=!1){const i=`${e.replace(/\/$/,"")}/ws/connections/${t}/signaling`;f&&f.readyState===WebSocket.OPEN&&f.close();const r=new WebSocket(i);return f=r,await new Promise((e,t)=>{r.onopen=()=>{I.connection(n?"WebSocket reconnected":"WebSocket connected"),O("connected"),w=0,_&&(clearTimeout(_),_=null),e()},r.onclose=e=>{I.connection("WebSocket closed:",e),f=null,O("disconnected"),!e.wasClean&&N&&R(),t(new o("WebSocket connection closed",{code:e.code,reason:e.reason,wasClean:e.wasClean}))},r.onerror=e=>{f=null,O("disconnected");const n=new o("WebSocket connection error",{error:e,timestamp:(new Date).toISOString()});D(n),t(n)}}),a?.(),S.dispatch(p(void 0)),r}async function M(e){if(m&&"disconnected"!==E)I.warn("WebRTC","Connection already in progress, skipping...");else try{O("connecting"),k=null;const a=(e=>{try{const t=atob(e);return JSON.parse(t)}catch(e){return I.critical_error("decodeToBase64: Error decoding token",e),null}})(e);if(!a)throw new o("Failed to decode connection token",{token:e?"provided":"missing"});T={...a,token:e};const i=await L(a.connection.signalingEndpoint,a.connection.id),l=await async function(){I.webrtc("Create PeerConnection");const e=new RTCPeerConnection(Q);return m=e,e.addEventListener("connectionstatechange",()=>{"failed"===e.connectionState?(D(new o("WebRTC connection failed")),R()):"connected"===e.connectionState&&(O("connected"),w=0,_&&(clearTimeout(_),_=null))}),function(e){y=e.addTransceiver("audio",{direction:"sendrecv"});const t=e.addTransceiver("video",{direction:"recvonly"});I.webrtc("Added transceivers",{videoTransceiver:t,audioTransceiver:y});const a=e.createDataChannel("chat",{ordered:!0});b=a,S.dispatch(d(a)),c?.(a),a.onopen=()=>{I.webrtc("Data channel opened")},a.onclose=()=>{I.webrtc("Data channel closed")},a.onerror=e=>{I.critical_error("WebRTC",e),D(new r("Data channel error",{error:e}))},a.onmessage=e=>{try{const t=JSON.parse(e.data);I.data("Data channel message received:",t),n?.(t)}catch{n?.({event:"message_received",data:{message:{content:e.data,action:"completed"}}})}}}(e),e.ontrack=e=>{const t=e.streams[0];I.webrtc(`${e.track.kind} stream received`,{streamId:t?.id,trackId:e.track.id,videoTracks:t?.getVideoTracks().length,audioTracks:t?.getAudioTracks().length}),"video"===e.track.kind?(g=t,C=t):"audio"===e.track.kind&&(C=t,g||(g=t)),s?.({videoStream:g,audioStream:C})},e}();await async function(){try{I.webrtc("Setting up user media");const e=await navigator.mediaDevices.getUserMedia({audio:!t||{deviceId:{exact:t}},video:!1});if(v=e,y&&e.getAudioTracks().length>0){const t=e.getAudioTracks()[0];await y.sender.replaceTrack(t)}s?.({userMicrophoneStream:e})}catch(e){I.critical_warn("WebRTC",e),D(new o("Failed to access user media",{error:e,deviceId:t}))}}(),await async function(e,t){e.addEventListener("icecandidate",e=>{const n=e.candidate;n&&(I.webrtc("send ICE candidate"),A(t,{type:"add_ice_candidate",data:{candidate:n}}))}),e.addEventListener("negotiationneeded",()=>{I.warn("negotiationneeded (waiting for server offer)")}),I.webrtc("createOffer → setLocalDescription → set_remote_description");const n=await e.createOffer();await e.setLocalDescription(n),A(t,{type:"set_remote_description",data:n})}(l,i),i.onmessage=e=>async function(e,t,n){try{const a=JSON.parse(n.data);switch(a.type){case"set_remote_description":I.webrtc("Setting remote description"),await e.setRemoteDescription(a.data),await e.setLocalDescription(),A(t,{type:"set_local_description",data:e.localDescription});break;case"add_ice_candidate":a.data?.candidate&&await e.addIceCandidate(a.data.candidate);break;case"error":I.critical_error("WebRTC",a.data?.error),D(new r(a.data?.error||"Server error",{serverMessage:a.data})),e.close(),t.close();break;default:I.webrtc("Unknown message type:",a.type)}}catch(e){I.critical_error("WebRTC",e),D(new r("Failed to process WebSocket message",{originalError:e,rawMessage:n.data}))}}(l,i,e)}catch(e){const t=e;throw I.critical_error("WebRTC",t),D(t),O("disconnected"),t}}function P(){N=!1,_&&(clearTimeout(_),_=null),w=0;try{if(b)try{b.close()}catch{}if(f)try{f.readyState!==WebSocket.OPEN&&f.readyState!==WebSocket.CONNECTING||f.close(1e3,"Connection closed by client")}catch{}if(m)try{m.getSenders().forEach(e=>{e.track&&e.track.stop()}),m.close()}catch{}if(v)try{v.getTracks().forEach(e=>e.stop())}catch{}}catch(e){I.critical_warn("WebRTC",e)}finally{b=null,f=null,m=null,v=null,y=null,g=null,C=null,T=null,O("disconnected"),S.dispatch(h(void 0))}}return S.dispatch(h(P)),{startWithToken:M,close:P,forceReconnect:async function(){if(T){P(),N=!0,w=0;try{await M(T.token)}catch(e){throw D(e),e}}else D(new o("No connection data available for reconnect"))},getConnectionStatus:function(){return E},getReconnectAttempts:function(){return w},getError:function(){return k},updateAudioDevice:async function(e){if(y&&y.sender.track)try{const t=await navigator.mediaDevices.getUserMedia({audio:{deviceId:{exact:e}},video:!1}),n=t.getAudioTracks()[0];await y.sender.replaceTrack(n),v&&v.getTracks().forEach(e=>e.stop()),v=t,s?.({userMicrophoneStream:t}),I.webrtc(`Audio device updated to: ${e}`)}catch(t){I.critical_warn("WebRTC","Failed to update audio device:",t),D(new o("Failed to update audio device",{error:t,deviceId:e}))}else I.warn("WebRTC","No audio transceiver available for device update")}}}({maxReconnectAttempts:3,reconnectInterval:2e3,onStreams:e=>{this.embed?.updateStreams(e)},onChatMessage:e=>{this.embed?.handleMessage(e)},onConnectionError:e=>{I.critical_error("WebRTC connection error:",e),this.config?.onError?.(e)}});try{I.connection("Initializing WebRTC connection with token:",`${e.substring(0,50)}...`),await this.webrtcController.startWithToken(e),I.connection("WebRTC initialization completed with token")}catch(e){throw I.critical_error("SDK","Failed to Initialize WebRTC:",e),this.webrtcController=null,e}}}destroyWebRTC(){if(this.webrtcController){I.info("SDK","Destroying WebRTC controller");try{this.webrtcController.close()}catch(e){I.critical_error("SDK","Error closing WebRTC controller:",e)}this.webrtcController=null}}destroyInstance(e,t){if(!e)return void I.critical_warn("SDK","destroyInstance ignored (no reason)");V("sdk_destroyed",{reason:e}),t?.();const n=this.config?.onDestroy;if(w(null),S.dispatch(p(void 0)),S.dispatch(h(void 0)),S.dispatch(u(!1)),S.dispatch(C()),S.dispatch(b(void 0)),this.destroyWebRTC(),this.embed){try{this.embed.update({onDestroy:void 0}),this.embed.destroy()}catch(e){I.critical_error("Error during cleanup:",e)}this.embed=null}this.rootEl&&this.rootEl.parentNode&&this.rootEl.parentNode.removeChild(this.rootEl),this.rootEl=null,this.mountTarget=null,this.config=null,this.isInitialized=!1,n?.()}async init(t,n={}){try{if(this.isInitialized)throw new a("SDK is already initialized. Call destroy() first.",{code:e.ALREADY_INITIALIZED});n.analytics?.enabled&&(function(e){x=new P(e)}(n.analytics),V("sdk_init_started",{version:this.version,config:{position:n.position,features:Object.keys(n.features||{})}})),function(t){if(!t||"string"!=typeof t||""===t.trim())throw new i("Invalid connection token: expected non-empty string",{providedToken:typeof t,code:e.INVALID_TOKEN})}(t);const o={avatarStyle:{view:"round"},position:exports.Position.BOTTOM_RIGHT,...n};this.config=o,S.dispatch(p(t)),S.dispatch(u(!1)),S.dispatch(y(o.debug)),this.config.features&&Object.entries(this.config.features).forEach(([e,t])=>{const n=L(e,t);S.dispatch(g({feature:e,config:n}))}),w(e=>{try{this.embed&&this.embed.update({features:e})}catch(e){I.critical_error("Unable to update features",e)}this.config?.onFeaturesUpdate?.(e)});const r=function(e){if(!e)return document.body;if("string"==typeof e){const t=document.querySelector(e);return t instanceof HTMLElement?t:(I.warn(`mountContainer should be a valid CSS selector. Provided selector "${e}" is invalid or did not match any elements. Defaulting to document.body.`),document.body)}return e instanceof HTMLElement?e:document.body}(this.config.mountContainer??void 0);return this.mountTarget=r,this.isInitialized=!0,this.renderApp(),this.config.onReady?.(),V("sdk_init_completed",{version:this.version,initTime:Date.now()}),this.createInstanceMethods()}catch(e){const a=s.handle(e,{method:"init",tokenProvided:!!t,config:n});throw n.onError?.(a),a}}createInstanceMethods(){return{showAvatar:()=>{const e=document.getElementById("np_companion-avatar-container");e&&(e.style.display="block",F("show","avatar_widget"))},hideAvatar:()=>{const e=document.getElementById("np_companion-avatar-container");e&&(e.style.display="none",F("hide","avatar_widget"))},avatarIsVisible:()=>{const e=document.getElementById("np_companion-avatar-container");return!!e&&"none"!==e.style.display},destroy:()=>{const{closeConnectionHandler:e}=S.getState().avatar;this.destroyInstance("api",e)},updateStyles:e=>{this.config&&(this.config.style={...this.config.style??{},...e??{}},this.rootEl&&J(this.rootEl,this.config.style))},setPosition:e=>{if(this.config&&(this.config.position=e,S.dispatch?.(b(e)),this.rootEl)){const t=Z(e,this.config.avatarStyle?.view,this.config.className);this.rootEl.className=t}},clearPosition:()=>{this.config&&(S.dispatch?.(b(void 0)),this.config.position=void 0,this.rootEl&&(this.rootEl.className=Z(void 0,this.config.avatarStyle?.view,this.config.className)))},enableFeature:e=>{S.dispatch?.(g({feature:e,config:{enabled:!0}})),"disclaimer"===e&&this.rootEl&&this.rootEl.classList.remove("np_companion_disclaimer-disabled")},disableFeature:e=>{S.dispatch?.(g({feature:e,config:{enabled:!1}})),"disclaimer"===e&&this.rootEl&&this.rootEl.classList.add("np_companion_disclaimer-disabled")},updateFeatureConfig:(e,t)=>{const n=L(e,t);S.dispatch?.(g({feature:e,config:n})),"disclaimer"===e&&this.rootEl&&(n?.enabled?this.rootEl.classList.remove("np_companion_disclaimer-disabled"):this.rootEl.classList.add("np_companion_disclaimer-disabled"))},updateAvatarStyle:e=>{if(this.config){if(this.config.avatarStyle={view:"round",...this.config.avatarStyle,...e},e.view&&this.rootEl){const t=Z(this.config.position,e.view,this.config.className);this.rootEl.className=t}this.embed&&this.embed.update({avatarStyle:this.config.avatarStyle})}},sendQuestion:e=>{const{dataChannel:t,stopInteraction:n}=S.getState().avatar;t&&"open"===t.readyState&&!n?t.send(JSON.stringify({type:"send_question",data:e})):I.critical_warn("Data channel not available or not open")}}}}Object.defineProperty(Y,"instance",{enumerable:!0,configurable:!0,writable:!0,value:null});const X=Y.getInstance();"undefined"!=typeof window&&(window.napsterCompanionApiSDK=X),exports.NapsterCompanionApiSdk=X,exports.default=X;
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e,t=require("@reduxjs/toolkit");class n extends Error{constructor(e,t,n){super(e),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"timestamp",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"context",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name="SDKError",this.code=t,this.timestamp=new Date,this.context=n,Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,message:this.message,code:this.code,timestamp:this.timestamp.toISOString(),context:this.context,stack:this.stack}}}class a extends n{constructor(e,t){super(e,"INITIALIZATION_ERROR",t),this.name="InitializationError"}}class i extends n{constructor(e,t){super(e,"TOKEN_ERROR",t),this.name="TokenError"}}class o extends n{constructor(e,t){super(e,"CONNECTION_ERROR",t),this.name="ConnectionError"}}class r extends n{constructor(e,t){super(e,"WEBRTC_ERROR",t),this.name="WebRTCError"}}!function(e){e.ALREADY_INITIALIZED="ALREADY_INITIALIZED",e.INVALID_TOKEN="INVALID_TOKEN",e.REACT_VERSION_UNSUPPORTED="REACT_VERSION_UNSUPPORTED",e.CONTAINER_NOT_FOUND="CONTAINER_NOT_FOUND",e.CONNECTION_FAILED="CONNECTION_FAILED",e.TOKEN_GENERATION_FAILED="TOKEN_GENERATION_FAILED",e.MISSING_CREDENTIALS="MISSING_CREDENTIALS",e.WEBRTC_NOT_SUPPORTED="WEBRTC_NOT_SUPPORTED",e.PEER_CONNECTION_FAILED="PEER_CONNECTION_FAILED",e.DATA_CHANNEL_ERROR="DATA_CHANNEL_ERROR",e.API_REQUEST_FAILED="API_REQUEST_FAILED",e.INVALID_RESPONSE="INVALID_RESPONSE",e.RATE_LIMITED="RATE_LIMITED",e.INVALID_CONFIGURATION="INVALID_CONFIGURATION",e.MISSING_REQUIRED_CONFIG="MISSING_REQUIRED_CONFIG",e.FEATURE_NOT_SUPPORTED="FEATURE_NOT_SUPPORTED",e.FEATURE_DISABLED="FEATURE_DISABLED",e.MEDIA_ACCESS_DENIED="MEDIA_ACCESS_DENIED",e.MEDIA_DEVICE_ERROR="MEDIA_DEVICE_ERROR",e.VIDEO_LOAD_ERROR="VIDEO_LOAD_ERROR"}(e||(e={}));class s{static setErrorHandler(e){this.onError=e}static handle(e,t){let a;return function(e){return e instanceof n}(e)?(a=e,t&&(a.context={...a.context,...t})):a=e instanceof Error?new n(e.message,"UNKNOWN_ERROR",{originalError:e.name,...t}):new n("string"==typeof e?e:"Unknown error occurred","UNKNOWN_ERROR",{originalError:e,...t}),this.onError?.(a),a}}exports.Position=void 0,function(e){e.BOTTOM_RIGHT="bottom-right",e.BOTTOM_CENTER="bottom-center",e.BOTTOM_LEFT="bottom-left",e.TOP_RIGHT="top-right",e.TOP_CENTER="top-center",e.TOP_LEFT="top-left",e.CENTER="center"}(exports.Position||(exports.Position={}));const c=t.createSlice({name:"avatar",initialState:{avatarReady:!1,dataChannel:null,stopInteraction:!1,muted:!1,transcript:void 0,customVoiceId:void 0,defaultVoiceId:void 0,connectionToken:void 0,companionId:void 0,closeConnectionHandler:void 0},reducers:{setSessionId:(e,t)=>{e.sessionId=t.payload},setAvatarReady:(e,t)=>{e.avatarReady=t.payload},setDataChannel:(e,t)=>{e.dataChannel=t.payload},setAvatarId:(e,t)=>{e.avatarId=t.payload},setVideoId:(e,t)=>{e.videoId=t.payload},setStopInteraction:(e,t)=>{e.stopInteraction=t.payload},setMuted:(e,t)=>{e.muted=t.payload},addTranscript:(e,t)=>{e.transcript=t.payload},setCustomVoiceId:(e,t)=>{e.customVoiceId=t.payload},setDefaultVoiceId:(e,t)=>{e.defaultVoiceId=t.payload},setConnectionToken:(e,t)=>{e.connectionToken=t.payload},setCloseConnectionHandler:(e,t)=>{e.closeConnectionHandler=t.payload}}}),{setDataChannel:d,setStopInteraction:l,setMuted:u,setConnectionToken:p,setCloseConnectionHandler:h}=c.actions,m=c.reducer,f={features:{backgroundRemoval:{enabled:!0},waveform:{enabled:!0,color:"#ffffff"},inactiveTimeout:{enabled:!0,duration:6e4,countdown:30},disclaimer:{enabled:!0,text:"This is an AI avatar. Check important info."},showSDKLoader:{enabled:!0,bgColor:"rgb(222 222 222 / 60%)",color:"#585858ff",type:"spinner"}},position:void 0,showExperience:!1,debugMode:!1},v=t.createSlice({name:"app",initialState:f,reducers:{setFeatures:(e,t)=>{const{feature:n,config:a}=t.payload,i=e.features[n];e.features[n]={...i,...a,enabled:a?.enabled??!!i?.enabled}},resetFeatures:e=>{e.features=f.features},setPosition:(e,t)=>{e.position=t.payload},setShowExperience:(e,t)=>{e.showExperience=t.payload},setDebugMode:(e,t)=>{e.debugMode=t.payload}}}),{setFeatures:g,resetFeatures:C,setPosition:b,setDebugMode:y}=v.actions;let E=null;const w=e=>{E=e},_=e=>t=>n=>{const a=e.getState().app.features,i=t(n),o=e.getState().app.features;return E&&a!==o&&JSON.stringify(a)!==JSON.stringify(o)&&E(o),i},S=t.configureStore({reducer:{avatar:m,app:v.reducer},middleware:e=>e({serializableCheck:!1}).concat(_)});var T;!function(e){e.INFO="info",e.WARN="warn",e.ERROR="error",e.DEBUG="debug"}(T||(T={}));const I=new class{constructor(){Object.defineProperty(this,"prefix",{enumerable:!0,configurable:!0,writable:!0,value:"[Napster SDK]"})}isDebugEnabled(){try{return S.getState().app.debugMode||!1}catch{return!1}}log(e,...t){if(!this.isDebugEnabled())return;const n=[this.prefix,...t];switch(e){case T.INFO:console.info(...n);break;case T.WARN:console.warn(...n);break;case T.ERROR:console.error(...n);break;case T.DEBUG:console.debug(...n)}}info(...e){this.log(T.INFO,"ℹ️",...e)}debug(...e){this.log(T.DEBUG,"🐞",...e)}warn(...e){this.log(T.WARN,"⚠️",...e)}error(...e){this.log(T.ERROR,"❌",...e)}critical_warn(...e){console.warn(this.prefix,"⚠️",...e)}critical_error(...e){console.error(this.prefix,"❌",...e)}webrtc(...e){this.log(T.INFO,"📡 WebRTC:",...e)}avatar(...e){this.log(T.INFO,"🎭 Avatar:",...e)}connection(...e){this.log(T.INFO,"🔌 Connection:",...e)}features(...e){this.log(T.INFO,"🔄 Features:",...e)}data(...e){this.log(T.INFO,"📨 Data:",...e)}timer(...e){this.log(T.INFO,"⏱️ Timer:",...e)}cleanup(...e){this.log(T.INFO,"🗑️ Cleanup:",...e)}};function N(...e){const t=[];for(const n of e)if(n)if("string"==typeof n||"number"==typeof n)t.push(String(n));else if(Array.isArray(n)){const e=N(...n);e&&t.push(e)}else if("object"==typeof n)for(const[e,a]of Object.entries(n))a&&t.push(e);return t.join(" ")}const k={icon:"np_companion-action-btn-container-icon",persistFillColor:"np_companion-persist-fill-color",alignMiddle:"np_companion-align-middle",alignBetween:"np_companion-align-between",darkGreyBg:"np_companion-dark-grey-bg",callEnd:"np_companion-action-btn-container-call-end",container:"np_companion-action-btn-container-container",wrapper:"np_companion-action-btn-container-wrapper",canvas:"np_companion-action-btn-container-canvas",controls:"np_companion-action-btn-container-controls",left:"np_companion-action-btn-container-left",middle:"np_companion-action-btn-container-middle",right:"np_companion-action-btn-container-right",wave:"np_companion-action-btn-container-wave",stop:"np_companion-action-btn-container-stop",questionBar:"np_companion-chat-question-bar-container",muted:"muted",hidden:"np_companion-hidden",expanded:"np_companion-action-btn-container-expanded",collapse:"np_companion-action-btn-container-collapse",mobileMode:"np_companion-mobile-mode",displayNone:"np_companion__d-none",iconButton:()=>N(k.icon,k.alignMiddle,k.darkGreyBg),iconButtonEnd:()=>N(k.icon,k.alignMiddle,k.darkGreyBg,k.callEnd),iconButtonWithState:e=>N(k.icon,k.alignMiddle,k.darkGreyBg,{[k.muted]:e})};class A{static createElement(e,t){const n=document.createElement(e);return t?.className&&(n.className=t.className),t?.id&&(n.id=t.id),t?.attributes&&Object.entries(t.attributes).forEach(([e,t])=>{n.setAttribute(e,t)}),t?.styles&&Object.assign(n.style,t.styles),n}static createVideo(e){const t=this.createElement("video",{className:e.className});return t.autoplay=e.autoplay??!1,t.muted=e.muted??!1,t.loop=e.loop??!1,t.playsInline=e.playsInline??!1,e.crossOrigin&&(t.crossOrigin=e.crossOrigin),e.poster&&(t.poster=e.poster),e.src&&(t.src=e.src),t}static createAudio(e){const t=this.createElement("audio",{className:e.className});return t.autoplay=e.autoplay??!1,t}static createCanvas(e){const t=this.createElement("canvas",{className:e.className,styles:e.styles});return void 0!==e.width&&(t.width=e.width),void 0!==e.height&&(t.height=e.height),t}static createButton(e){const t=this.createElement("button",{className:e.className,attributes:e.attributes});return e.textContent&&(t.textContent=e.textContent),e.onClick&&t.addEventListener("click",e.onClick),t}static createDiv(e){return this.createElement("div",{className:e})}}class D{static process(e){const t=e.data;return this.hasGreenScreen(t)?(this.removeGreenScreen(t),e):e}static hasGreenScreen(e){for(let t=0;t<e.length;t+=4)if(this.isGreenPixel(e[t],e[t+1],e[t+2]))return!0;return!1}static isGreenPixel(e,t,n){return e>=0&&e<=120&&t>=150&&t<=255&&n>=0&&n<=120}static removeGreenScreen(e){for(let t=0;t<e.length;t+=4){const n=e[t],a=e[t+1],i=e[t+2];this.isGreenPixel(n,a,i)?e[t+3]=0:this.reduceGreenSpill(e,t,n,a,i)}}static reduceGreenSpill(e,t,n,a,i){const o=a-Math.max(n,i);if(o>0){const r=.5*o;e[t]=Math.min(255,n+.8*r),e[t+2]=Math.min(255,i+.8*r),e[t+1]=Math.max(0,a-r)}}}const O=new class{constructor(){Object.defineProperty(this,"svgNS",{enumerable:!0,configurable:!0,writable:!0,value:"http://www.w3.org/2000/svg"})}createElement(e){const t=document.createElementNS(this.svgNS,e.tag);return e.attributes&&Object.entries(e.attributes).forEach(([e,n])=>{t.setAttribute(e,String(n))}),e.textContent&&(t.textContent=e.textContent),e.children&&e.children.forEach(e=>{const n=this.createElement(e);t.appendChild(n)}),t}createSVG(e,t,n,a,i){const o=document.createElementNS(this.svgNS,"svg");return o.setAttribute("width",String(e)),o.setAttribute("height",String(t)),o.setAttribute("viewBox",n),o.setAttribute("fill","none"),o.setAttribute("xmlns",this.svgNS),i&&o.setAttribute("class",i),a.forEach(e=>{const t=this.createElement(e);o.appendChild(t)}),o}},R={micUnmuted:()=>O.createSVG(17,17,"0 0 17 17",[{tag:"g",attributes:{"clip-path":"url(#clip0_655_3824)"},children:[{tag:"path",attributes:{d:"M8.67241 11.8448C9.49524 11.844 10.2841 11.5167 10.8659 10.9349C11.4478 10.3531 11.775 9.5642 11.7759 8.74138V4.60345C11.7759 3.78036 11.4489 2.99099 10.8669 2.40898C10.2849 1.82697 9.4955 1.5 8.67241 1.5C7.84933 1.5 7.05995 1.82697 6.47794 2.40898C5.89594 2.99099 5.56897 3.78036 5.56897 4.60345V8.74138C5.56982 9.5642 5.89707 10.3531 6.47889 10.9349C7.06071 11.5167 7.84959 11.844 8.67241 11.8448ZM6.60345 4.60345C6.60345 4.05472 6.82143 3.52847 7.20943 3.14047C7.59744 2.75246 8.12369 2.53448 8.67241 2.53448C9.22114 2.53448 9.74739 2.75246 10.1354 3.14047C10.5234 3.52847 10.7414 4.05472 10.7414 4.60345V8.74138C10.7414 9.2901 10.5234 9.81635 10.1354 10.2044C9.74739 10.5924 9.22114 10.8103 8.67241 10.8103C8.12369 10.8103 7.59744 10.5924 7.20943 10.2044C6.82143 9.81635 6.60345 9.2901 6.60345 8.74138V4.60345ZM9.18965 13.8879V15.9828C9.18965 16.1199 9.13516 16.2515 9.03816 16.3485C8.94116 16.4455 8.80959 16.5 8.67241 16.5C8.53523 16.5 8.40367 16.4455 8.30667 16.3485C8.20967 16.2515 8.15517 16.1199 8.15517 15.9828V13.8879C6.87994 13.7582 5.69812 13.1601 4.83826 12.2095C3.9784 11.2589 3.50158 10.0232 3.5 8.74138C3.5 8.6042 3.5545 8.47264 3.6515 8.37563C3.7485 8.27863 3.88006 8.22414 4.01724 8.22414C4.15442 8.22414 4.28598 8.27863 4.38299 8.37563C4.47999 8.47264 4.53448 8.6042 4.53448 8.74138C4.53448 9.83883 4.97044 10.8913 5.74645 11.6673C6.52247 12.4434 7.57497 12.8793 8.67241 12.8793C9.76986 12.8793 10.8224 12.4434 11.5984 11.6673C12.3744 10.8913 12.8103 9.83883 12.8103 8.74138C12.8103 8.6042 12.8648 8.47264 12.9618 8.37563C13.0588 8.27863 13.1904 8.22414 13.3276 8.22414C13.4648 8.22414 13.5963 8.27863 13.6933 8.37563C13.7903 8.47264 13.8448 8.6042 13.8448 8.74138C13.8433 10.0232 13.3664 11.2589 12.5066 12.2095C11.6467 13.1601 10.4649 13.7582 9.18965 13.8879Z",fill:"white"}}]},{tag:"defs",children:[{tag:"clipPath",attributes:{id:"clip0_655_3824"},children:[{tag:"rect",attributes:{width:"16",height:"16",fill:"white",transform:"translate(0.5 0.5)"}}]}]}],"np_companion-mic-unmuted"),micMuted:()=>O.createSVG(22,22,"0 0 17 18",[{tag:"g",attributes:{"clip-path":"url(#clip0_655_4192)"},children:[{tag:"path",attributes:{d:"M14.2432 14.6L3.89604 3.21808C3.80327 3.11843 3.67498 3.05936 3.53896 3.05368C3.40294 3.048 3.27016 3.09616 3.16941 3.18772C3.06866 3.27928 3.00806 3.40686 3.00075 3.5428C2.99343 3.67874 3.04 3.81208 3.13034 3.91392L5.58263 6.61131V8.7396C5.58251 9.26661 5.71656 9.78497 5.97216 10.2458C6.22776 10.7067 6.59649 11.0949 7.04361 11.3739C7.49073 11.6529 8.00151 11.8134 8.52782 11.8404C9.05414 11.8674 9.57867 11.7599 10.052 11.5282L10.7698 12.3171C10.138 12.6868 9.41878 12.8806 8.68679 12.8785C7.58946 12.8773 6.53741 12.4408 5.76148 11.6649C4.98555 10.889 4.54911 9.83693 4.54791 8.7396C4.54791 8.60239 4.4934 8.47079 4.39638 8.37377C4.29935 8.27675 4.16776 8.22224 4.03055 8.22224C3.89334 8.22224 3.76174 8.27675 3.66472 8.37377C3.5677 8.47079 3.51319 8.60239 3.51319 8.7396C3.51476 10.0217 3.9917 11.2577 4.85176 12.2085C5.71182 13.1594 6.8939 13.7575 8.16943 13.8873V15.9826C8.16943 16.1199 8.22394 16.2514 8.32096 16.3485C8.41798 16.4455 8.54958 16.5 8.68679 16.5C8.824 16.5 8.95559 16.4455 9.05262 16.3485C9.14964 16.2514 9.20415 16.1199 9.20415 15.9826V13.8867C10.0143 13.8085 10.794 13.5376 11.4779 13.0964L13.4775 15.2952C13.523 15.3464 13.5781 15.3881 13.6398 15.4178C13.7015 15.4476 13.7684 15.4648 13.8368 15.4685C13.9051 15.4722 13.9735 15.4622 14.038 15.4393C14.1025 15.4163 14.1618 15.3808 14.2125 15.3347C14.2632 15.2887 14.3042 15.2331 14.3332 15.171C14.3622 15.109 14.3786 15.0419 14.3815 14.9735C14.3843 14.9051 14.3736 14.8368 14.3499 14.7725C14.3261 14.7083 14.2899 14.6495 14.2432 14.5993V14.6ZM8.68679 10.809C8.13794 10.809 7.61157 10.591 7.22347 10.2029C6.83538 9.81482 6.61735 9.28845 6.61735 8.7396V7.7495L9.3115 10.7127C9.10943 10.7766 8.89873 10.8091 8.68679 10.809ZM12.4066 10.5562C12.6841 9.99093 12.8275 9.36929 12.8257 8.7396C12.8257 8.60239 12.8802 8.47079 12.9772 8.37377C13.0742 8.27675 13.2058 8.22224 13.343 8.22224C13.4802 8.22224 13.6118 8.27675 13.7089 8.37377C13.8059 8.47079 13.8604 8.60239 13.8604 8.7396C13.8625 9.52693 13.6831 10.3041 13.3359 11.0108C13.2934 11.0979 13.2273 11.1713 13.145 11.2226C13.0628 11.274 12.9679 11.3012 12.8709 11.3012C12.7922 11.3013 12.7145 11.2831 12.6439 11.2481C12.5207 11.1878 12.4265 11.0811 12.382 10.9513C12.3375 10.8215 12.3463 10.6794 12.4066 10.5562ZM5.84131 3.36358C6.12624 2.71004 6.62746 2.1745 7.26073 1.84696C7.894 1.51943 8.62071 1.41987 9.31874 1.56501C10.0168 1.71015 10.6435 2.09116 11.0938 2.64398C11.544 3.19681 11.7902 3.88776 11.7909 4.60072V8.7396C11.7908 8.8476 11.7852 8.95552 11.7741 9.06295C11.7608 9.19066 11.7005 9.30885 11.6049 9.39455C11.5092 9.48025 11.3852 9.52733 11.2568 9.52663C11.2387 9.52757 11.2205 9.52757 11.2025 9.52663C11.066 9.51229 10.9409 9.44435 10.8545 9.33775C10.7682 9.23115 10.7277 9.09462 10.742 8.95818C10.7491 8.88705 10.753 8.81332 10.753 8.74089V4.60072C10.7516 4.12605 10.5871 3.66628 10.2871 3.29848C9.98701 2.93069 9.56963 2.67722 9.10491 2.58058C8.64018 2.48393 8.15636 2.54998 7.73454 2.76766C7.31273 2.98534 6.97857 3.34141 6.78808 3.77618C6.7639 3.84253 6.72639 3.90322 6.67786 3.95452C6.62934 4.00583 6.57082 4.04665 6.50592 4.07449C6.44102 4.10232 6.37111 4.11658 6.30049 4.11637C6.22987 4.11617 6.16005 4.10151 6.09531 4.07329C6.03057 4.04508 5.9723 4.00392 5.92407 3.95233C5.87584 3.90075 5.83869 3.83983 5.81489 3.77335C5.7911 3.70686 5.78117 3.6362 5.78571 3.56573C5.79025 3.49526 5.80917 3.42646 5.84131 3.36358Z",fill:"white"}}]},{tag:"defs",children:[{tag:"clipPath",attributes:{id:"clip0_655_4192"},children:[{tag:"rect",attributes:{width:"16",height:"16",fill:"white",transform:"translate(0.5 0.5)"}}]}]}],"tc-mic-muted"),stop:()=>O.createSVG(20,20,"0 0 32 32",[{tag:"path",attributes:{d:"M5.92 24.096q0 0.832 0.576 1.408t1.44 0.608h16.128q0.832 0 1.44-0.608t0.576-1.408v-16.16q0-0.832-0.576-1.44t-1.44-0.576h-16.128q-0.832 0-1.44 0.576t-0.576 1.44v16.16z",fill:"#ffffff"}}]),volumeHigh(e){const t=[{tag:"path",attributes:{d:"M80 416L128 416L262.1 535.2C268.5 540.9 276.7 544 285.2 544C304.4 544 320 528.4 320 509.2L320 130.8C320 111.6 304.4 96 285.2 96C276.7 96 268.5 99.1 262.1 104.8L128 224L80 224C53.5 224 32 245.5 32 272L32 368C32 394.5 53.5 416 80 416z",fill:"#ffffff"}}];return e>0&&t.push({tag:"path",attributes:{d:"M412.6 245.5C402.3 237.1 387.2 238.7 378.8 249C370.4 259.3 372 274.4 382.3 282.8C393.1 291.6 400 305 400 320C400 335 393.1 348.4 382.3 357.3C372 365.7 370.5 380.8 378.8 391.1C387.1 401.4 402.3 402.9 412.6 394.6C434.1 376.9 448 350.1 448 320C448 289.9 434.1 263.1 412.6 245.5z",fill:"#ffffff"}}),e>=25&&t.push({tag:"path",attributes:{d:"M473.1 171C462.8 162.6 447.7 164.2 439.3 174.5C430.9 184.8 432.5 199.9 442.8 208.3C475.3 234.7 496 274.9 496 320C496 365.1 475.3 405.3 442.8 431.8C432.5 440.2 431 455.3 439.3 465.6C447.6 475.9 462.8 477.4 473.1 469.1C516.3 433.9 544 380.2 544 320.1C544 260 516.3 206.3 473.1 171.1z",fill:"#ffffff"}}),e>=75&&t.push({tag:"path",attributes:{d:"M533.6 96.5C523.3 88.1 508.2 89.7 499.8 100C491.4 110.3 493 125.4 503.3 133.8C557.5 177.8 592 244.8 592 320C592 395.2 557.5 462.2 503.3 506.3C493 514.7 491.5 529.8 499.8 540.1C508.1 550.4 523.3 551.9 533.6 543.6C598.5 490.7 640 410.2 640 320C640 229.8 598.5 149.2 533.6 96.5z",fill:"#ffffff"}}),O.createSVG(16,16,"0 0 640 640",t)},volumeMuted:()=>O.createSVG(16,16,"0 0 640 640",[{tag:"path",attributes:{d:"M80 416L128 416L262.1 535.2C268.5 540.9 276.7 544 285.2 544C304.4 544 320 528.4 320 509.2L320 130.8C320 111.6 304.4 96 285.2 96C276.7 96 268.5 99.1 262.1 104.8L128 224L80 224C53.5 224 32 245.5 32 272L32 368C32 394.5 53.5 416 80 416zM399 239C389.6 248.4 389.6 263.6 399 272.9L446 319.9L399 366.9C389.6 376.3 389.6 391.5 399 400.8C408.4 410.1 423.6 410.2 432.9 400.8L479.9 353.8L526.9 400.8C536.3 410.2 551.5 410.2 560.8 400.8C570.1 391.4 570.2 376.2 560.8 366.9L513.8 319.9L560.8 272.9C570.2 263.5 570.2 248.3 560.8 239C551.4 229.7 536.2 229.6 526.9 239L479.9 286L432.9 239C423.5 229.6 408.3 229.6 399 239z",fill:"#ffffff"}}]),end:()=>O.createSVG(16,16,"0 0 21 16",[{tag:"path",attributes:{d:"M17.7226 12.2992C18.3148 12.5423 18.991 12.308 19.307 11.7578L19.3954 11.6031C20.434 9.78662 20.2705 7.18344 18.2308 5.85533C13.5438 2.80798 7.45789 2.80798 2.77085 5.85533C0.726753 7.18344 0.567646 9.78662 1.60627 11.6031L1.69466 11.7578C2.01066 12.3125 2.68908 12.5445 3.2769 12.3014L6.32204 11.0462C6.83914 10.8341 7.15515 10.3059 7.0999 9.74684L6.90986 7.85081C9.2346 7.06853 11.7759 7.10831 14.0785 7.97456L13.8973 9.74684C13.8399 10.3037 14.1581 10.8297 14.6752 11.0462L17.7226 12.2992Z",fill:"red"}}])},L=(e,t)=>{if("inactiveTimeout"===e){const e=t;return e?.enabled&&void 0!==e.duration&&e.duration>18e4&&(I.critical_warn(`Napster Companion API SDK: inactiveTimeout duration of ${e.duration}ms exceeds the recommended maximum of 180000ms. Setting maximum allowed value.`),delete e.duration),t}return t},M={enabled:!1,batchSize:10,flushInterval:5e3,enablePerformanceTracking:!0,enableErrorTracking:!0,enableUserInteractionTracking:!0};class P{constructor(e={}){Object.defineProperty(this,"config",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"eventQueue",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"performanceQueue",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"errorQueue",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"flushTimer",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"sessionId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"providers",{enumerable:!0,configurable:!0,writable:!0,value:[]}),this.config={...M,...e},this.sessionId=this.config.sessionId||this.generateSessionId(),this.setupProviders(),this.config.enabled&&(this.startFlushTimer(),this.setupErrorTracking(),this.setupPerformanceTracking())}setupProviders(){this.providers=[],this.config.providers&&(this.providers=[...this.config.providers]),this.config.provider&&this.providers.push(this.config.provider),0===this.providers.length&&this.providers.push({type:"custom"})}generateSessionId(){return`session_${Date.now()}_${Math.random().toString(36).substr(2,9)}`}startFlushTimer(){this.flushTimer&&clearInterval(this.flushTimer),this.flushTimer=setInterval(()=>{this.flush()},this.config.flushInterval)}setupErrorTracking(){this.config.enableErrorTracking&&(window.addEventListener("error",e=>{this.trackError(e.error,{source:"window.error",filename:e.filename,lineno:e.lineno,colno:e.colno})}),window.addEventListener("unhandledrejection",e=>{this.trackError(new Error(e.reason),{source:"unhandledrejection",reason:e.reason})}))}setupPerformanceTracking(){this.config.enablePerformanceTracking&&"undefined"!=typeof window&&"performance"in window&&window.addEventListener("load",()=>{setTimeout(()=>{const e=performance.getEntriesByType("navigation")[0];e&&(this.trackPerformance("page_load_time",e.loadEventEnd-e.fetchStart,"ms"),this.trackPerformance("dom_content_loaded",e.domContentLoadedEventEnd-e.fetchStart,"ms"),this.trackPerformance("first_paint",e.responseEnd-e.fetchStart,"ms"))},0)})}trackEvent(e,t){if(!this.config.enabled)return;const n={name:e,properties:t,timestamp:Date.now(),userId:this.config.userId,sessionId:this.sessionId};this.eventQueue.push(n),this.eventQueue.length>=(this.config.batchSize||10)&&this.flush()}trackPerformance(e,t,n,a){if(!this.config.enabled||!this.config.enablePerformanceTracking)return;const i={name:e,value:t,unit:n,timestamp:Date.now(),context:a};this.performanceQueue.push(i)}trackError(e,t){if(!this.config.enabled||!this.config.enableErrorTracking)return;const n={error:e,context:t,timestamp:Date.now(),userId:this.config.userId,sessionId:this.sessionId,stack:e.stack};this.errorQueue.push(n),this.flushErrors()}trackInteraction(e,t,n){this.config.enableUserInteractionTracking&&this.trackEvent("user_interaction",{action:e,target:t,...n})}flush(){this.flushEvents(),this.flushPerformance(),this.flushErrors()}flushEvents(){if(0===this.eventQueue.length)return;const e=[...this.eventQueue];this.eventQueue=[],this.sendData("events",e)}flushPerformance(){if(0===this.performanceQueue.length)return;const e=[...this.performanceQueue];this.performanceQueue=[],this.sendData("performance",e)}flushErrors(){if(0===this.errorQueue.length)return;const e=[...this.errorQueue];this.errorQueue=[],this.sendData("errors",e)}async sendData(e,t){const n=this.providers.map(n=>this.sendToProvider(n,e,t));await Promise.allSettled(n)}async sendToProvider(e,t,n){try{switch(e.type){case"google-analytics-4":await this.sendToGA4(e,n);break;case"mixpanel":await this.sendToMixpanel(e,n);break;case"segment":await this.sendToSegment(e,n);break;case"amplitude":await this.sendToAmplitude(e,n);break;case"posthog":await this.sendToPostHog(e,n);break;case"azure-insights":await this.sendToAzureInsights(e,n);break;default:await this.sendToCustomEndpoint(e,t,n)}}catch(t){I.critical_warn(`Failed to send data to ${e.type}:`,t)}}async sendToCustomEndpoint(e,t,n){const a=e.endpoint,i=e.apiKey;if(!a)return void("development"===process.env.NODE_ENV&&I.info(`Analytics [${t}]:`,n));const o=await fetch(`${a}/${t}`,{method:"POST",headers:{"Content-Type":"application/json",...i&&{Authorization:`Bearer ${i}`}},body:JSON.stringify({data:n,sessionId:this.sessionId,timestamp:Date.now()})});if(!o.ok)throw new Error(`HTTP ${o.status}`)}async sendToGA4(e,t){const n=e.measurementId||e.apiKey;if(!n)throw new Error("GA4 measurement ID required");const a=`https://www.google-analytics.com/mp/collect?measurement_id=${n}&api_secret=${e.apiKey||"default"}`,i=t.map(e=>({name:e.name,params:{...e.properties,session_id:this.sessionId}}));await fetch(a,{method:"POST",body:JSON.stringify({client_id:this.sessionId,user_id:this.config.userId,events:i})})}async sendToMixpanel(e,t){const n=e.projectToken||e.apiKey;if(!n)throw new Error("Mixpanel project token required");const a=e.endpoint||"https://api.mixpanel.com/batch",i=t.map(e=>{const t=e;return{event:t.name,properties:{token:n,distinct_id:this.config.userId||this.sessionId,time:t.timestamp||Date.now(),...t.properties}}});await fetch(a,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(i)})}async sendToSegment(e,t){const n=e.writeKey||e.apiKey;if(!n)throw new Error("Segment write key required");const a=e.endpoint||"https://api.segment.io/v1/batch",i=t.map(e=>({type:"track",userId:this.config.userId||this.sessionId,event:e.name,properties:e.properties,timestamp:new Date(e.timestamp||Date.now()).toISOString()}));await fetch(a,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Basic ${btoa(n+":")}`},body:JSON.stringify({batch:i})})}async sendToAmplitude(e,t){const n=e.apiKey;if(!n)throw new Error("Amplitude API key required");const a=e.endpoint||"https://api2.amplitude.com/2/httpapi",i=t.map(e=>({user_id:this.config.userId||this.sessionId,event_type:e.name,event_properties:e.properties,time:e.timestamp||Date.now()}));await fetch(a,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({api_key:n,events:i})})}async sendToPostHog(e,t){const n=e.apiKey,a=e.endpoint||"https://app.posthog.com";if(!n)throw new Error("PostHog API key required");const i=t.map(e=>({event:e.name,properties:{...e.properties,distinct_id:this.config.userId||this.sessionId},timestamp:new Date(e.timestamp||Date.now()).toISOString()}));await fetch(`${a}/batch/`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({api_key:n,batch:i})})}async sendToAzureInsights(e,t){const n=e.apiKey;if(!n)throw new Error("Azure Application Insights instrumentation key required");const a=e.endpoint||"https://dc.services.visualstudio.com/v2/track",i=t.map(e=>{const t=e;return{name:"Microsoft.ApplicationInsights.Event",time:new Date(t.timestamp||Date.now()).toISOString(),iKey:n,data:{baseType:"EventData",baseData:{name:t.name,properties:t.properties}}}});await fetch(a,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(i)})}updateConfig(e){this.config={...this.config,...e},this.setupProviders(),this.config.enabled&&!this.flushTimer?this.startFlushTimer():!this.config.enabled&&this.flushTimer&&(clearInterval(this.flushTimer),this.flushTimer=void 0)}destroy(){this.flushTimer&&clearInterval(this.flushTimer),this.flush()}}let x=null;const V=(e,t)=>{x?.trackEvent(e,t)},F=(e,t,n)=>{x?.trackInteraction(e,t,n)};function W(e,{content:t,placement:n="top"}){let a=!1,i=null,o=null;const r=e=>"left"===e?"start":"right"===e?"end":e,s=()=>{if(!i)return;const t=e.getBoundingClientRect(),a=i.getBoundingClientRect();let o=0,r=0;switch(n){case"top":o=t.top-a.height-8,r=t.left+(t.width-a.width)/2;break;case"bottom":o=t.bottom+8,r=t.left+(t.width-a.width)/2;break;case"left":o=t.top+(t.height-a.height)/2,r=t.left-a.width-8;break;case"right":o=t.top+(t.height-a.height)/2,r=t.right+8}i.style.top=`${o}px`,i.style.left=`${r}px`},c=()=>s(),d=()=>{if(a)return;const e=(()=>{if(i)return i;const e=document.createElement("div");e.className=`tooltip styled-tooltip bs-tooltip-${r(n)} show`,e.setAttribute("role","tooltip"),Object.assign(e.style,{position:"fixed",top:"0px",left:"0px",zIndex:String(2147483647),opacity:"0",visibility:"hidden",pointerEvents:"none",transition:"opacity 80ms ease"});const a=document.createElement("div");a.className="tooltip-arrow";const o=document.createElement("div");return o.className="tooltip-inner","string"==typeof t?o.textContent=t:o.appendChild(t),e.appendChild(a),e.appendChild(o),document.body.appendChild(e),i=e,e})();a=!0,s(),o=window.setTimeout(s,10),e.style.opacity="1",e.style.visibility="visible",window.addEventListener("scroll",c,!0),window.addEventListener("resize",c)},l=()=>{a&&(a=!1,null!=o&&(window.clearTimeout(o),o=null),i&&(i.style.opacity="0",i.style.visibility="hidden"),window.removeEventListener("scroll",c,!0),window.removeEventListener("resize",c))},u=()=>d(),p=()=>l();return e.addEventListener("mouseenter",u),e.addEventListener("mouseleave",p),e.matches?.(":hover")&&d(),{update:e=>{if(void 0!==e.content&&i){const t=i.querySelector(".tooltip-inner");t&&(t.innerHTML="","string"==typeof e.content?t.textContent=e.content:t.appendChild(e.content))}void 0!==e.placement&&(n=e.placement,i&&(i.className=`tooltip styled-tooltip bs-tooltip-${r(n)} show`)),a&&s()},show:d,hide:l,destroy:()=>{l(),e.removeEventListener("mouseenter",u),e.removeEventListener("mouseleave",p),i&&i.parentNode&&i.parentNode.removeChild(i),i=null}}}function j(e,t){const n=document.createElement(e);return t&&(n.className=t),n}var $,U,B,G,K,z,q;!function(e){e.LOCAL_TIMEOUT="local_timeout",e.SERVER_WARNING="server_warning"}($||($={}));class H{constructor(e,t={}){Object.defineProperty(this,"overlayController",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"currentTrigger",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"isVisible",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"mountElement",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"callbacks",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.mountElement=e,this.callbacks=t}show(e){this.isVisible?I.warn("Inactive overlay already visible, ignoring show request"):(I.info(`Showing inactive overlay (trigger: ${e.type})`),this.currentTrigger=e,this.isVisible=!0,this.overlayController=function(e,t){const n={duration:t.duration??30,isInteractionNeeded:t.isInteractionNeeded??!1,message:t.message??"It looks like you've been inactive for a while. Would you like to continue this conversation?",onContinue:t.onContinue,onEnd:t.onEnd},a=document.createElement("div");a.className="np_companion-inactive-overlay";const i=document.createElement("div");i.className="np_companion-inactive-dialog";const o=document.createElement("p");o.className="np_companion-inactive-message",o.textContent=n.message;const r=document.createElement("div");r.className="np_companion-inactive-timer";const s=document.createElement("div");s.className="np_companion-timer-circle";const c=document.createElementNS("http://www.w3.org/2000/svg","svg");c.setAttribute("viewBox","0 0 36 36");const d=document.createElementNS("http://www.w3.org/2000/svg","path");d.setAttribute("d","M18 2.0845 a 15.9155 15.9155 0 0 1 0 31.831 a 15.9155 15.9155 0 0 1 0 -31.831"),d.setAttribute("fill","none"),d.setAttribute("stroke","rgba(255, 255, 255, 0.2)"),d.setAttribute("stroke-width","2");const l=document.createElementNS("http://www.w3.org/2000/svg","path");l.setAttribute("d","M18 2.0845 a 15.9155 15.9155 0 0 1 0 31.831 a 15.9155 15.9155 0 0 1 0 -31.831"),l.setAttribute("fill","none"),l.setAttribute("stroke","#fff"),l.setAttribute("stroke-width","2");const u=document.createElement("span");u.className="np_companion-timer-number",s.appendChild(c),c.appendChild(d),c.appendChild(l),s.appendChild(u),r.appendChild(s);const p=document.createElement("div");p.className="np_companion-inactive-buttons";const h=document.createElement("button");h.className="np_companion-end-button np_companion__d-none",h.textContent="End Conversation";let m=null;const f=e=>{e&&!m?(m=document.createElement("button"),m.className="np_companion-continue-button",m.textContent="Continue Talking",p.appendChild(m),m.addEventListener("click",n.onContinue)):!e&&m&&(m.removeEventListener("click",n.onContinue),m.parentNode&&m.parentNode.removeChild(m),m=null)};p.appendChild(h),f(n.isInteractionNeeded),i.appendChild(o),i.appendChild(r),i.appendChild(p),a.appendChild(i),e.appendChild(a);let v=Math.max(0,Math.floor(n.duration)),g=null;const C=()=>{u.textContent=String(v),l.setAttribute("stroke-dasharray",(n.duration>0?v/n.duration*100:0)+", 100")},b=()=>{if(v<=0)return E(),void n.onEnd();v-=1,C()},y=()=>{E(),C(),g=window.setInterval(b,1e3)},E=()=>{null!=g&&(window.clearInterval(g),g=null)};return h.addEventListener("click",()=>{E(),n.onEnd()}),y(),{update:e=>{if(void 0!==e.message&&(n.message=e.message,o.textContent=n.message),void 0!==e.isInteractionNeeded&&(n.isInteractionNeeded=!!e.isInteractionNeeded,f(n.isInteractionNeeded)),void 0!==e.duration){const t=Math.max(0,Math.floor(e.duration));n.duration=t,v=t,y()}e.onContinue&&(m&&(m.removeEventListener("click",n.onContinue),m.addEventListener("click",e.onContinue)),n.onContinue=e.onContinue),e.onEnd&&(n.onEnd=e.onEnd)},destroy:()=>{E(),h.removeEventListener("click",n.onEnd),m&&m.removeEventListener("click",n.onContinue),a.parentNode&&a.parentNode.removeChild(a)}}}(this.mountElement,{duration:e.duration,message:e.message,isInteractionNeeded:e.isInteractionNeeded,onContinue:()=>this.handleContinue(),onEnd:()=>this.handleEnd()}),this.callbacks.onShow?.(e))}hide(){this.isVisible&&(I.info("Hiding inactive overlay"),this.isVisible=!1,this.currentTrigger=null,this.overlayController&&(this.overlayController.destroy(),this.overlayController=null),this.callbacks.onHide?.())}isShowing(){return this.isVisible}getCurrentTrigger(){return this.currentTrigger}handleContinue(){I.info("User clicked continue on inactive overlay"),this.hide(),this.callbacks.onContinue?.()}handleEnd(){I.info("Inactive overlay countdown ended"),this.hide(),this.callbacks.onEnd?.()}destroy(){this.hide()}}!function(e){e.TALK_STATE_CHANGED="talk_state_changed",e.MESSAGE_RECEIVED="message_received",e.TRANSCRIPT="transcript",e.AUDIO_TRANSCRIPT_DELTA="response.audio_transcript.delta",e.AUDIO_TRANSCRIPT_DONE="response.audio_transcript.done",e.RESPONSE_DONE="response.done"}(U||(U={})),function(e){e.STARTED="started",e.ENDED="ended",e.CANCELED="canceled"}(B||(B={})),function(e){e.DELTA="delta",e.COMPLETED="completed"}(G||(G={})),function(e){e.USER="user",e.ASSISTANT="assistant"}(K||(K={})),function(e){e.SET_REMOTE_DESCRIPTION="set_remote_description",e.SET_LOCAL_DESCRIPTION="set_local_description",e.ADD_ICE_CANDIDATE="add_ice_candidate",e.ERROR="error"}(z||(z={})),function(e){e.SEND_QUESTION="send_question",e.CANCEL="cancel"}(q||(q={}));const Q={iceServers:[{urls:"stun:stun1.ciscape.com:3478"},{urls:"turn:stun1.ciscape.com:3478",username:"tcuser",credential:"dw4k_BR2f-Y4A-@aT7ip@Qzs"},{urls:"stun:129.146.43.226:3478"},{urls:"stun:stun.l.google.com:19302"},{urls:"stun:stun1.l.google.com:19302"},{urls:"turn:129.146.43.226:3478",username:"teamtime_turn",credential:"teamtime"}]};function J(e,t){if(t)for(const n in t)try{const a=t[n];"string"!=typeof a&&"number"!=typeof a||(e.style[n]=a)}catch{I.warn(`Failed to apply style for key "${n}: ${t[n]}".`)}}function Z(e,t,n){const a=[];return a.push("np_companion-align-middle"),e&&(a.push("np_companion-container-fixed"),a.push(`np_companion-${e}`),t&&a.push(`np_companion-view-${t}`)),n&&a.push(n),a.join(" ")}class Y{constructor(){Object.defineProperty(this,"version",{enumerable:!0,configurable:!0,writable:!0,value:"1.0.0-alpha.12"}),Object.defineProperty(this,"mountTarget",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"rootEl",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"embed",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"webrtcController",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"config",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"isInitialized",{enumerable:!0,configurable:!0,writable:!0,value:!1})}static getInstance(){return Y.instance||(Y.instance=new Y),Y.instance}renderApp(){this.mountTarget&&this.config&&(this.rootEl||(this.rootEl=document.createElement("div"),this.rootEl.id="np_companion-sdk-root",this.mountTarget.appendChild(this.rootEl)),this.rootEl.className=Z(this.config.position,this.config.avatarStyle?.view,this.config.className),J(this.rootEl,this.config.style),this.embed?this.embed.update({avatarStyle:this.config.avatarStyle,features:S.getState().app.features,onData:this.config.onData,onAvatarReady:this.config.onAvatarReady,onInactivityStatusChange:this.config.onInactivityStatusChange,onDestroy:()=>this.destroyInstance("ui_end"),onError:this.config.onError}):this.embed=function(e,t={}){const n=A.createDiv("np_companion-live-container np_companion-fade-in");e.appendChild(n);const a=function(e,t={}){const n=A.createDiv("np_companion-avatar"),a=A.createDiv(`np_companion-avatar-container np_companion-loader-${t.features?.showSDKLoader?.type??"spinner"}`);a.id="np_companion-avatar-container",t.avatarStyle?.view&&a.classList.add(`np_companion-view-${t.avatarStyle.view}`);const i=A.createDiv("loader-container"),o=A.createDiv("loader");i.appendChild(o);const r=A.createVideo({className:"np_companion-avatar-video",autoplay:!0,muted:!0,playsInline:!0}),s=A.createAudio({className:"np_companion-avatar-audio",autoplay:!0}),c=A.createCanvas({className:"np_companion-avatar-canvas",styles:{width:"100%",height:"100%",objectFit:"cover",position:"relative",zIndex:"1"}});t.features?.backgroundRemoval?.enabled&&"silhouette"===t.avatarStyle?.view?r.classList.add("np_companion__d-none"):c.classList.add("np_companion__d-none"),a.appendChild(i),a.appendChild(r),a.appendChild(s),a.appendChild(c);const d=A.createDiv(`${k.wrapper} np_companion-action-btn-container-view-${t.avatarStyle?.view}`),p=A.createDiv(`np_companion-disclaimer-text np_companion-disclaimer-view-${t.avatarStyle?.view}`);p.style.display="none";const h=A.createDiv(`np_companion-avatar-control-container np_companion-avatar-control-view-${t.avatarStyle?.view}`);h.appendChild(d),h.appendChild(p),n.appendChild(a),n.appendChild(h),e.appendChild(n);let m=null,f=(t.features?.backgroundRemoval?.enabled&&"silhouette"===t.avatarStyle?.view)??!1,v=null,g=null,C=!1,b=!1,y=!1,E=!0,w=null,_=null,T=null;const O=new H(n,{onContinue:()=>{K();const e=t.features?.inactiveTimeout;e?.enabled&&z()},onEnd:()=>{}});let L=null;const M=()=>{E||(E=!0,h.className=x(),null!=w&&window.clearTimeout(w))},P=()=>{null!=w&&window.clearTimeout(w),w=window.setTimeout(()=>{E=!1,h.className=x()},5e3)};function x(){return N(`np_companion-avatar-control-container np_companion-avatar-control-view-${t.avatarStyle?.view}`,{[k.collapse]:!E})}function V(e){if(!y)return;const n=t.avatarStyle?.borderWidth??("silhouette"!==t.avatarStyle?.view?"4px":void 0);n&&(a.style.borderWidth=n);const i=("silhouette"!==t.avatarStyle?.view?e?"#ec3e41":t.avatarStyle?.borderColor??"#C0C0C0":void 0)??t.avatarStyle?.borderColor;i&&(a.style.borderColor=i);const o=t.avatarStyle?.borderStyle??("silhouette"!==t.avatarStyle?.view?"solid":void 0);o&&(a.style.borderStyle=o)}function F(e){"round"===t.avatarStyle?.view&&(a.style.transform=`translate(-50%, ${e??352-h.offsetHeight-212-12+"px"})`)}function U(){const e=t.features?.disclaimer?.enabled??!1;p.style.display=e&&y?"-webkit-box":"none",_?.update({features:{disclaimer:{enabled:e}}});const n=t.features?.disclaimer?.text??"This is an AI avatar. Check important info.";t.features?.disclaimer?.color&&(p.style.color=t.features?.disclaimer?.color),p.textContent=n,y&&F(e?void 0:"8%")}function B(){y||!t.features?.showSDKLoader?.enabled?n.classList.add("np_companion-bg-transparent"):n.classList.remove("np_companion-bg-transparent")}function G(){t.features?.showSDKLoader?.bgColor&&n.style.setProperty("--np-loader-bg-color",t.features.showSDKLoader.bgColor),t.features?.showSDKLoader?.color&&n.style.setProperty("--np-loader-color",t.features.showSDKLoader.color)}function K(){T&&(I.timer("Resetting inactive timeout due to activity"),clearTimeout(T),T=null,S.dispatch(l(!1)),t.onInactivityStatusChange?.(!1))}function z(){const e=t.features?.inactiveTimeout;e?.enabled?(K(),T=setTimeout(()=>{I.timer(`Inactive timeout of ${e?.duration}ms reached, showing inactive overlay`),S.dispatch(l(!0)),t.onInactivityStatusChange?.(!0),m&&(m.getAudioTracks().forEach(e=>e.enabled=!1),_?.update({isMuted:!0}),V(!0)),O.isShowing()||O.show({type:$.LOCAL_TIMEOUT,duration:Math.min(e.countdown??30,60),message:void 0,isInteractionNeeded:!0})},e.duration)):(K(),O.isShowing()&&O.hide())}function Q(){if(!_&&y){const e=!1;_=function(e,t){let n={...t},a=null,i=null,o=[],r=!1;const s=document.createElement("div");s.className=_();const c=j("div",k.container),d=j("div",N(k.questionBar,k.alignBetween)),l=j("div",k.left),u=j("div",k.iconButtonWithState(n.isMuted));u.appendChild(n.isMuted?R.micMuted():R.micUnmuted()),n.toggleMute&&u.addEventListener("click",()=>n.toggleMute?.());const p=j("div",k.middle),h=j("div",k.wave);S();const m=document.createElement("canvas");m.width=160,m.height=40,m.className=k.canvas,h.appendChild(m);const f=j("div",N(k.right,k.alignBetween)),v=j("div",N(k.iconButton(),k.stop)),g=function(e,t={}){let n={initialVolume:50,...t},a=n.initialVolume??50,i=!1,o=!1;const r=document.createElement("div");r.className="np_volume-control";const s=document.createElement("div");s.className="np_volume-slider-container";const c=document.createElement("div");c.className="np_volume-slider-track";const d=document.createElement("div");d.className="np_volume-slider-fill";const l=document.createElement("div");l.className="np_volume-slider-thumb",c.appendChild(d),c.appendChild(l),s.appendChild(c);const u=document.createElement("div");function p(){let e;u.innerHTML="",e=i||0===a?R.volumeMuted():R.volumeHigh(a||100),u.appendChild(e)}function h(){const e=a;d.style.height=`${e}%`,l.style.bottom=`${e}%`}function m(){o=!o,o?s.classList.add("np_volume-slider-visible"):s.classList.remove("np_volume-slider-visible")}function f(e){const t=c.getBoundingClientRect(),o=Math.max(0,Math.min(100,(t.bottom-e)/t.height*100));a=o,h(),i=0===a,i?u.classList.add("np_volume-muted"):u.classList.remove("np_volume-muted"),p(),n.onChange?.(a)}u.className=k.iconButton(),u.setAttribute("aria-label","Volume control"),p(),r.appendChild(s),r.appendChild(u),e.appendChild(r),u.addEventListener("click",e=>{e.stopPropagation(),i=!i,i?(n.initialVolume=a,a=0,h(),u.classList.add("np_volume-muted")):(a=n.initialVolume||50,h(),u.classList.remove("np_volume-muted")),p(),n.onMuteToggle?.(i)}),r.addEventListener("mouseenter",e=>{e.stopPropagation(),o||m()}),r.addEventListener("mouseleave",e=>{setTimeout(()=>{e.stopPropagation(),o&&m()},300)});let v=!1;return c.addEventListener("mousedown",e=>{v=!0,f(e.clientY),e.preventDefault()}),document.addEventListener("mousemove",e=>{v&&f(e.clientY)}),document.addEventListener("mouseup",()=>{v=!1}),l.addEventListener("mousedown",e=>{v=!0,e.preventDefault()}),c.addEventListener("touchstart",e=>{v=!0,f(e.touches[0].clientY),e.preventDefault()}),document.addEventListener("touchmove",e=>{v&&e.touches.length>0&&f(e.touches[0].clientY)}),document.addEventListener("touchend",()=>{v=!1}),document.addEventListener("click",e=>{o&&!r.contains(e.target)&&m()}),h(),{setVolume(e){a=Math.max(0,Math.min(100,e)),h(),p(),n.onChange?.(a)},getVolume:()=>a,toggleMute(){i=!i,i?u.classList.add("np_volume-muted"):u.classList.remove("np_volume-muted"),n.onMuteToggle?.(i)},isMuted:()=>i,update(e){n={...n,...e}},destroy(){r.remove()}}}(v,{initialVolume:50,onChange:e=>{n.onVolumeChange?.(e)},onMuteToggle:e=>{n.onVolumeChange?.(e?0:g.getVolume())}});g.setVolume(70);const C=j("div",k.iconButtonEnd());C.appendChild(R.end()),n.handleEnd&&C.addEventListener("click",()=>n.handleEnd?.()),l.appendChild(u),p.appendChild(h),f.appendChild(v),f.appendChild(C),d.appendChild(l),d.appendChild(f),c.appendChild(d),s.appendChild(c),e.appendChild(s);let b=null,y=null,E=null;function w(){if(!n.userMicrophoneStream)return;const e=new(window.AudioContext||window.webkitAudioContext);a=e.createAnalyser(),e.createMediaStreamSource(n.userMicrophoneStream).connect(a),function(e){if(!a)return;const t=m.getContext("2d");if(!t)return;a.fftSize=256;const n=new Uint8Array(a.frequencyBinCount),s=Math.floor(m.width/3);0===o.length&&(o=new Array(s).fill(0));let c=0;const d=()=>{if(t.clearRect(0,0,m.width,m.height),t.beginPath(),t.moveTo(0,m.height/2),t.lineTo(m.width,m.height/2),t.strokeStyle="#ffffff",t.stroke(),e)r=!1,o.fill(0),S();else{a.getByteFrequencyData(n);const e=6,i=3,s=n.reduce((e,t)=>e+t,0)/n.length/255*m.height*.8;o.shift(),o.push(s);let d=o.filter(t=>t>e).length>=i;d?c=30:c>0&&(c--,d=!0),r=d,S(),t.fillStyle="#ffffff";for(let e=0;e<o.length;e++){const n=3*e,a=o[e];t.fillRect(n,m.height/2-a/2,2,a),t.fillRect(n,m.height/2+a/2,2,-a)}}i=requestAnimationFrame(d)};d()}(!!n.isMuted)}function _(){return N(k.alignMiddle,`np_companion-avatar-${n.avatarStyle?.view}`)}function S(){h.style.filter=!n.isMuted&&r?"brightness(0) saturate(100%) invert(48%) sepia(93%) saturate(1720%) hue-rotate(346deg) brightness(101%) contrast(103%)":"none",h.style.transition="filter 0.3s ease",h.style.height="40px"}function T(){b?.destroy(),b=W(u,{content:n.isMuted?"Unmute":"Mute",placement:"top"}),y?.destroy(),y=null}function I(){for(u.className=k.iconButtonWithState(n.isMuted);u.firstChild;)u.removeChild(u.firstChild);u.appendChild(n.isMuted?R.micMuted():R.micUnmuted())}return b=W(u,{content:n.isMuted?"Unmute":"Mute",placement:"top"}),E=W(C,{content:"End Session",placement:"top"}),w(),{update(e){const t=n;n={...n,...e},s.className=_(),t.isMuted!==n.isMuted&&(I(),T()),t.isAvatarSpeaking!==n.isAvatarSpeaking&&(I(),T()),t.userMicrophoneStream===n.userMicrophoneStream&&t.selectedMicrophone===n.selectedMicrophone||(null!=i&&(cancelAnimationFrame(i),i=null),o=[],a=null,w()),S(),n.features?.disclaimer?.enabled?c.classList.remove("np_companion_disclaimer-disabled"):c.classList.add("np_companion_disclaimer-disabled")},destroy(){b?.destroy(),y?.destroy(),E?.destroy(),null!=i&&cancelAnimationFrame(i),s.parentNode&&s.parentNode.removeChild(s)}}}(d,{avatarStyle:t.avatarStyle,isMuted:e,isAvatarSpeaking:b,userMicrophoneStream:m,features:{waveform:{enabled:!1!==t.features?.waveform?.enabled}},onVolumeChange:e=>{s.volume=e/100},toggleMute:()=>{const t=!(S.getState().avatar.muted??e);S.dispatch(u(t)),m&&m.getAudioTracks().forEach(e=>e.enabled=!t),_?.update({isMuted:t}),V(t),K(),z()},onStopTalking:()=>{try{const e=S.getState().avatar.dataChannel;if(e&&"open"===e.readyState){const t={type:q.CANCEL};I.avatar("stopping avatar"),e.send(JSON.stringify(t))}else I.critical_warn("Stopping avatar: Data channel not open")}catch(e){I.critical_error("Avatar","Stop: failed to send interrupt",e)}K(),z()},handleEnd:()=>{t.onDestroy?.()}})}}n.addEventListener("mouseenter",M),n.addEventListener("mousemove",M),n.addEventListener("mouseleave",P);const J=()=>{if(C)return;const e=c.getContext("2d",{willReadFrequently:!0});if(!e||!r||r.readyState<2)L=requestAnimationFrame(J);else{if(c.width=r.videoWidth,c.height=r.videoHeight,e.drawImage(r,0,0,c.width,c.height),f){const n=e.getImageData(0,0,c.width,c.height),a=D.process(n);e.putImageData(a,0,0),y||(t.onAvatarReady?.(!0),y=!0,V(),Q(),B(),U(),z(),P())}L=requestAnimationFrame(J)}};U(),G(),B();const Z={updateStreams:({videoStream:e,audioStream:n,userMicrophoneStream:a})=>{e&&e instanceof MediaStream?v!==e&&(I.avatar("New video stream received:",{active:e.active,tracks:e.getTracks().length,videoTracks:e.getVideoTracks().length,id:e.id}),v=e,r.srcObject=e,r.play().then(()=>{f||y||(t.onAvatarReady?.(!0),y=!0,V(),Q(),B(),U(),z(),F(),P())}).catch(e=>{I.error("Failed to play video stream",e),t.onError?.(e)}),e.addEventListener("inactive",()=>{I.avatar("Video stream became inactive")}),e.getTracks().forEach(e=>{e.addEventListener("ended",()=>{I.avatar("Video track ended:",e.kind)})}),f&&!L&&(L=requestAnimationFrame(J))):(v=null,r.srcObject=null),void 0!==n&&(n&&n instanceof MediaStream?g!==n&&(g=n,s.srcObject=n,s.play().catch(e=>{I.error("Failed to play audio stream",e),t.onError?.(e)})):(g=null,s.srcObject=null)),void 0!==a&&(m=a??null,_?.update({userMicrophoneStream:m}))},updateWaveform:e=>{Q(),_?.update(e)},updateFeatures:e=>{t.features={...t.features||{},...e||{}},f=(t.features?.backgroundRemoval?.enabled&&"silhouette"===t.avatarStyle?.view)??!1,f?(r.classList.add("np_companion__d-none"),c.classList.remove("np_companion__d-none")):(r.classList.remove("np_companion__d-none"),c.classList.add("np_companion__d-none")),_?.update({features:{waveform:{enabled:!1!==t.features?.waveform?.enabled}}}),U(),G(),B(),z()},update:e=>{const n=t.avatarStyle?.view;Object.assign(t,e),e.features&&Z.updateFeatures(e.features),e.avatarStyle?.view&&e.avatarStyle.view!==n&&(n&&a.classList.remove(`np_companion-view-${n}`),a.classList.add(`np_companion-view-${e.avatarStyle.view}`),t.features&&Z.updateFeatures(t.features))},setAvatarReady:e=>{e||(y=!1,t.onAvatarReady?.(!1))},handleMessage:e=>{switch("undefined"!=typeof window&&window.parent&&window.parent.postMessage({type:"avatar-data-channel-message",event:e},"*"),e.event){case"avatar_state_changed":break;case"talk_state_changed":b="ended"!==e.data?.state&&"canceled"!==e.data?.state,_?.update({isAvatarSpeaking:b});break;case"message_received":{const{message:t}=e.data||{};if("completed"===t?.action&&"string"==typeof t.content&&t.role){K(),z();const e=O.getCurrentTrigger();e&&!e.isInteractionNeeded&&O.hide()}break}case"avatar_connection_warning":t.showAvatarInactiveOverlay&&(O.show({type:$.SERVER_WARNING,duration:e.data?.disconnect_after??30,message:"Avatar is disconnecting due to inactivity. Say something to keep it active.",isInteractionNeeded:!1}),m&&(m.getAudioTracks().forEach(e=>e.enabled=!0),_?.update({isMuted:!1}),V(!1)))}t.onData?t.onData(e):I.data("onData callback NOT called. Reason:",{onDataExists:!!t.onData,dataType:typeof e,dataIsNull:null===e})},destroy:e=>{C||(C=!0,n.removeEventListener("mousemove",M),n.removeEventListener("mouseenter",M),n.removeEventListener("mouseleave",P),null!=w&&window.clearTimeout(w),null!=L&&(cancelAnimationFrame(L),L=null),T&&(clearTimeout(T),T=null),_?.destroy(),_=null,O?.destroy(),n.parentNode&&n.parentNode.removeChild(n),y=!1,t.onAvatarReady?.(!1),e||t.onDestroy?.())}};return Z}(n,{avatarStyle:t.avatarStyle,showAvatarInactiveOverlay:!0,onData:t.onData,onDestroy:t.onDestroy,onError:t.onError,onInactivityStatusChange:t.onInactivityStatusChange,onAvatarReady:t.onAvatarReady,features:t.features});return{update:e=>{a.update({avatarStyle:e.avatarStyle??t.avatarStyle,onData:e.onData??t.onData,onDestroy:e.onDestroy??t.onDestroy,onError:e.onError??t.onError,onInactivityStatusChange:e.onInactivityStatusChange??t.onInactivityStatusChange,onAvatarReady:e.onAvatarReady??t.onAvatarReady,features:e.features??t.features}),Object.assign(t,e)},updateStreams:e=>{a.updateStreams(e)},handleMessage:e=>{a.handleMessage(e)},destroy:()=>{a.destroy(!0),n.parentNode===e&&e.removeChild(n),t.onDestroy?.()}}}(this.rootEl,{avatarStyle:this.config.avatarStyle,features:S.getState().app.features,onData:this.config.onData,onAvatarReady:this.config.onAvatarReady,onInactivityStatusChange:this.config.onInactivityStatusChange,onDestroy:()=>this.destroyInstance("ui_end"),onError:this.config.onError}),this.initializeWebRTC().catch(e=>{I.critical_error("Failed to establish WebRTC connection:",e),this.config?.onError?.(e)}))}async initializeWebRTC(){const e=S.getState().avatar.connectionToken;if(e&&!this.webrtcController){I.connection("Connecting WebRTC..."),this.webrtcController=function(e={}){const{currentAudioDeviceId:t,onChatMessage:n,onConnectionSuccess:a,onConnectionError:i,onStreams:s,onDataChannel:c,maxReconnectAttempts:l=3,reconnectInterval:u=2e3}=e;let m=null,f=null,v=null,g=null,C=null,b=null,y=null,E="disconnected",w=0,_=null,T=null,N=!0,k=null;function A(e,t){e&&e.readyState===WebSocket.OPEN?e.send(JSON.stringify(t)):I.critical_warn("WebRTC",`WS send skipped; state=${e?.readyState}`)}function D(e){k=e,i?.(e)}function O(e){E=e,I.webrtc(`Connection status changed to: ${e}`)}function R(){!N||!T||w>=l?w>=l&&D(new o("WebSocket connection failed after max retry attempts",{maxAttempts:l,lastAttempt:w})):(w+=1,O("reconnecting"),I.webrtc(`Attempting to reconnect (${w}/${l})...`),_=setTimeout(async()=>{try{if(!T)return;await L(T.connection.signalingEndpoint,T.connection.id,!0),!m&&T&&await M(T.token)}catch(e){I.error("WebRTC","Reconnection attempt failed:",e),w<l&&R()}},u))}async function L(e,t,n=!1){const i=`${e.replace(/\/$/,"")}/ws/connections/${t}/signaling`;f&&f.readyState===WebSocket.OPEN&&f.close();const r=new WebSocket(i);return f=r,await new Promise((e,t)=>{r.onopen=()=>{I.connection(n?"WebSocket reconnected":"WebSocket connected"),O("connected"),w=0,_&&(clearTimeout(_),_=null),e()},r.onclose=e=>{I.connection("WebSocket closed:",e),f=null,O("disconnected"),!e.wasClean&&N&&R(),t(new o("WebSocket connection closed",{code:e.code,reason:e.reason,wasClean:e.wasClean}))},r.onerror=e=>{f=null,O("disconnected");const n=new o("WebSocket connection error",{error:e,timestamp:(new Date).toISOString()});D(n),t(n)}}),a?.(),S.dispatch(p(void 0)),r}async function M(e){if(m&&"disconnected"!==E)I.warn("WebRTC","Connection already in progress, skipping...");else try{O("connecting"),k=null;const a=(e=>{try{const t=atob(e);return JSON.parse(t)}catch(e){return I.critical_error("decodeToBase64: Error decoding token",e),null}})(e);if(!a)throw new o("Failed to decode connection token",{token:e?"provided":"missing"});T={...a,token:e};const i=await L(a.connection.signalingEndpoint,a.connection.id),l=await async function(){I.webrtc("Create PeerConnection");const e=new RTCPeerConnection(Q);return m=e,e.addEventListener("connectionstatechange",()=>{"failed"===e.connectionState?(D(new o("WebRTC connection failed")),R()):"connected"===e.connectionState&&(O("connected"),w=0,_&&(clearTimeout(_),_=null))}),function(e){y=e.addTransceiver("audio",{direction:"sendrecv"});const t=e.addTransceiver("video",{direction:"recvonly"});I.webrtc("Added transceivers",{videoTransceiver:t,audioTransceiver:y});const a=e.createDataChannel("chat",{ordered:!0});b=a,S.dispatch(d(a)),c?.(a),a.onopen=()=>{I.webrtc("Data channel opened")},a.onclose=()=>{I.webrtc("Data channel closed")},a.onerror=e=>{I.critical_error("WebRTC",e),D(new r("Data channel error",{error:e}))},a.onmessage=e=>{try{const t=JSON.parse(e.data);I.data("Data channel message received:",t),n?.(t)}catch{n?.({event:"message_received",data:{message:{content:e.data,action:"completed"}}})}}}(e),e.ontrack=e=>{const t=e.streams[0];I.webrtc(`${e.track.kind} stream received`,{streamId:t?.id,trackId:e.track.id,videoTracks:t?.getVideoTracks().length,audioTracks:t?.getAudioTracks().length}),"video"===e.track.kind?(g=t,C=t):"audio"===e.track.kind&&(C=t,g||(g=t)),s?.({videoStream:g,audioStream:C})},e}();await async function(){try{I.webrtc("Setting up user media");const e=await navigator.mediaDevices.getUserMedia({audio:!t||{deviceId:{exact:t}},video:!1});if(v=e,y&&e.getAudioTracks().length>0){const t=e.getAudioTracks()[0];await y.sender.replaceTrack(t)}s?.({userMicrophoneStream:e})}catch(e){I.critical_warn("WebRTC",e),D(new o("Failed to access user media",{error:e,deviceId:t}))}}(),await async function(e,t){e.addEventListener("icecandidate",e=>{const n=e.candidate;n&&(I.webrtc("send ICE candidate"),A(t,{type:"add_ice_candidate",data:{candidate:n}}))}),e.addEventListener("negotiationneeded",()=>{I.warn("negotiationneeded (waiting for server offer)")}),I.webrtc("createOffer → setLocalDescription → set_remote_description");const n=await e.createOffer();await e.setLocalDescription(n),A(t,{type:"set_remote_description",data:n})}(l,i),i.onmessage=e=>async function(e,t,n){try{const a=JSON.parse(n.data);switch(a.type){case"set_remote_description":I.webrtc("Setting remote description"),await e.setRemoteDescription(a.data),await e.setLocalDescription(),A(t,{type:"set_local_description",data:e.localDescription});break;case"add_ice_candidate":a.data?.candidate&&await e.addIceCandidate(a.data.candidate);break;case"error":I.critical_error("WebRTC",a.data?.error),D(new r(a.data?.error||"Server error",{serverMessage:a.data})),e.close(),t.close();break;default:I.webrtc("Unknown message type:",a.type)}}catch(e){I.critical_error("WebRTC",e),D(new r("Failed to process WebSocket message",{originalError:e,rawMessage:n.data}))}}(l,i,e)}catch(e){const t=e;throw I.critical_error("WebRTC",t),D(t),O("disconnected"),t}}function P(){N=!1,_&&(clearTimeout(_),_=null),w=0;try{if(b)try{b.close()}catch{}if(f)try{f.readyState!==WebSocket.OPEN&&f.readyState!==WebSocket.CONNECTING||f.close(1e3,"Connection closed by client")}catch{}if(m)try{m.getSenders().forEach(e=>{e.track&&e.track.stop()}),m.close()}catch{}if(v)try{v.getTracks().forEach(e=>e.stop())}catch{}}catch(e){I.critical_warn("WebRTC",e)}finally{b=null,f=null,m=null,v=null,y=null,g=null,C=null,T=null,O("disconnected"),S.dispatch(h(void 0))}}return S.dispatch(h(P)),{startWithToken:M,close:P,forceReconnect:async function(){if(T){P(),N=!0,w=0;try{await M(T.token)}catch(e){throw D(e),e}}else D(new o("No connection data available for reconnect"))},getConnectionStatus:function(){return E},getReconnectAttempts:function(){return w},getError:function(){return k},updateAudioDevice:async function(e){if(y&&y.sender.track)try{const t=await navigator.mediaDevices.getUserMedia({audio:{deviceId:{exact:e}},video:!1}),n=t.getAudioTracks()[0];await y.sender.replaceTrack(n),v&&v.getTracks().forEach(e=>e.stop()),v=t,s?.({userMicrophoneStream:t}),I.webrtc(`Audio device updated to: ${e}`)}catch(t){I.critical_warn("WebRTC","Failed to update audio device:",t),D(new o("Failed to update audio device",{error:t,deviceId:e}))}else I.warn("WebRTC","No audio transceiver available for device update")}}}({maxReconnectAttempts:3,reconnectInterval:2e3,onStreams:e=>{this.embed?.updateStreams(e)},onChatMessage:e=>{this.embed?.handleMessage(e)},onConnectionError:e=>{I.critical_error("WebRTC connection error:",e),this.config?.onError?.(e)}});try{I.connection("Initializing WebRTC connection with token:",`${e.substring(0,50)}...`),await this.webrtcController.startWithToken(e),I.connection("WebRTC initialization completed with token")}catch(e){throw I.critical_error("SDK","Failed to Initialize WebRTC:",e),this.webrtcController=null,e}}}destroyWebRTC(){if(this.webrtcController){I.info("SDK","Destroying WebRTC controller");try{this.webrtcController.close()}catch(e){I.critical_error("SDK","Error closing WebRTC controller:",e)}this.webrtcController=null}}destroyInstance(e,t){if(!e)return void I.critical_warn("SDK","destroyInstance ignored (no reason)");V("sdk_destroyed",{reason:e}),t?.();const n=this.config?.onDestroy;if(w(null),S.dispatch(p(void 0)),S.dispatch(h(void 0)),S.dispatch(u(!1)),S.dispatch(C()),S.dispatch(b(void 0)),this.destroyWebRTC(),this.embed){try{this.embed.update({onDestroy:void 0}),this.embed.destroy()}catch(e){I.critical_error("Error during cleanup:",e)}this.embed=null}this.rootEl&&this.rootEl.parentNode&&this.rootEl.parentNode.removeChild(this.rootEl),this.rootEl=null,this.mountTarget=null,this.config=null,this.isInitialized=!1,n?.()}async init(t,n={}){try{if(this.isInitialized)throw new a("SDK is already initialized. Call destroy() first.",{code:e.ALREADY_INITIALIZED});n.analytics?.enabled&&(function(e){x=new P(e)}(n.analytics),V("sdk_init_started",{version:this.version,config:{position:n.position,features:Object.keys(n.features||{})}})),function(t){if(!t||"string"!=typeof t||""===t.trim())throw new i("Invalid connection token: expected non-empty string",{providedToken:typeof t,code:e.INVALID_TOKEN})}(t);const o={avatarStyle:{view:"round"},position:exports.Position.BOTTOM_RIGHT,...n};this.config=o,S.dispatch(p(t)),S.dispatch(u(!1)),S.dispatch(y(o.debug)),this.config.features&&Object.entries(this.config.features).forEach(([e,t])=>{const n=L(e,t);S.dispatch(g({feature:e,config:n}))}),w(e=>{try{this.embed&&this.embed.update({features:e})}catch(e){I.critical_error("Unable to update features",e)}this.config?.onFeaturesUpdate?.(e)});const r=function(e){if(!e)return document.body;if("string"==typeof e){const t=document.querySelector(e);return t instanceof HTMLElement?t:(I.warn(`mountContainer should be a valid CSS selector. Provided selector "${e}" is invalid or did not match any elements. Defaulting to document.body.`),document.body)}return e instanceof HTMLElement?e:document.body}(this.config.mountContainer??void 0);return this.mountTarget=r,this.isInitialized=!0,this.renderApp(),this.config.onReady?.(),V("sdk_init_completed",{version:this.version,initTime:Date.now()}),this.createInstanceMethods()}catch(e){const a=s.handle(e,{method:"init",tokenProvided:!!t,config:n});throw n.onError?.(a),a}}createInstanceMethods(){return{showAvatar:()=>{const e=document.getElementById("np_companion-avatar-container");e&&(e.style.display="block",F("show","avatar_widget"))},hideAvatar:()=>{const e=document.getElementById("np_companion-avatar-container");e&&(e.style.display="none",F("hide","avatar_widget"))},avatarIsVisible:()=>{const e=document.getElementById("np_companion-avatar-container");return!!e&&"none"!==e.style.display},destroy:()=>{const{closeConnectionHandler:e}=S.getState().avatar;this.destroyInstance("api",e)},updateStyles:e=>{this.config&&(this.config.style={...this.config.style??{},...e??{}},this.rootEl&&J(this.rootEl,this.config.style))},setPosition:e=>{if(this.config&&(this.config.position=e,S.dispatch?.(b(e)),this.rootEl)){const t=Z(e,this.config.avatarStyle?.view,this.config.className);this.rootEl.className=t}},clearPosition:()=>{this.config&&(S.dispatch?.(b(void 0)),this.config.position=void 0,this.rootEl&&(this.rootEl.className=Z(void 0,this.config.avatarStyle?.view,this.config.className)))},enableFeature:e=>{S.dispatch?.(g({feature:e,config:{enabled:!0}})),"disclaimer"===e&&this.rootEl&&this.rootEl.classList.remove("np_companion_disclaimer-disabled")},disableFeature:e=>{S.dispatch?.(g({feature:e,config:{enabled:!1}})),"disclaimer"===e&&this.rootEl&&this.rootEl.classList.add("np_companion_disclaimer-disabled")},updateFeatureConfig:(e,t)=>{const n=L(e,t);S.dispatch?.(g({feature:e,config:n})),"disclaimer"===e&&this.rootEl&&(n?.enabled?this.rootEl.classList.remove("np_companion_disclaimer-disabled"):this.rootEl.classList.add("np_companion_disclaimer-disabled"))},updateAvatarStyle:e=>{if(this.config){if(this.config.avatarStyle={view:"round",...this.config.avatarStyle,...e},e.view&&this.rootEl){const t=Z(this.config.position,e.view,this.config.className);this.rootEl.className=t}this.embed&&this.embed.update({avatarStyle:this.config.avatarStyle})}},sendQuestion:e=>{const{dataChannel:t,stopInteraction:n}=S.getState().avatar;t&&"open"===t.readyState&&!n?t.send(JSON.stringify({type:"send_question",data:e})):I.critical_warn("Data channel not available or not open")}}}}Object.defineProperty(Y,"instance",{enumerable:!0,configurable:!0,writable:!0,value:null});const X=Y.getInstance();"undefined"!=typeof window&&(window.napsterCompanionApiSDK=X),exports.NapsterCompanionApiSdk=X,exports.default=X;
@@ -1 +1 @@
1
- !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e="undefined"!=typeof globalThis?globalThis:e||self).napsterCompanionApiSDK=t()}(this,function(){"use strict";class e extends Error{constructor(e,t,n){super(e),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"timestamp",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"context",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name="SDKError",this.code=t,this.timestamp=new Date,this.context=n,Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,message:this.message,code:this.code,timestamp:this.timestamp.toISOString(),context:this.context,stack:this.stack}}}class t extends e{constructor(e,t){super(e,"INITIALIZATION_ERROR",t),this.name="InitializationError"}}class n extends e{constructor(e,t){super(e,"TOKEN_ERROR",t),this.name="TokenError"}}class o extends e{constructor(e,t){super(e,"CONNECTION_ERROR",t),this.name="ConnectionError"}}class i extends e{constructor(e,t){super(e,"WEBRTC_ERROR",t),this.name="WebRTCError"}}var a,r;!function(e){e.ALREADY_INITIALIZED="ALREADY_INITIALIZED",e.INVALID_TOKEN="INVALID_TOKEN",e.REACT_VERSION_UNSUPPORTED="REACT_VERSION_UNSUPPORTED",e.CONTAINER_NOT_FOUND="CONTAINER_NOT_FOUND",e.CONNECTION_FAILED="CONNECTION_FAILED",e.TOKEN_GENERATION_FAILED="TOKEN_GENERATION_FAILED",e.MISSING_CREDENTIALS="MISSING_CREDENTIALS",e.WEBRTC_NOT_SUPPORTED="WEBRTC_NOT_SUPPORTED",e.PEER_CONNECTION_FAILED="PEER_CONNECTION_FAILED",e.DATA_CHANNEL_ERROR="DATA_CHANNEL_ERROR",e.API_REQUEST_FAILED="API_REQUEST_FAILED",e.INVALID_RESPONSE="INVALID_RESPONSE",e.RATE_LIMITED="RATE_LIMITED",e.INVALID_CONFIGURATION="INVALID_CONFIGURATION",e.MISSING_REQUIRED_CONFIG="MISSING_REQUIRED_CONFIG",e.FEATURE_NOT_SUPPORTED="FEATURE_NOT_SUPPORTED",e.FEATURE_DISABLED="FEATURE_DISABLED",e.MEDIA_ACCESS_DENIED="MEDIA_ACCESS_DENIED",e.MEDIA_DEVICE_ERROR="MEDIA_DEVICE_ERROR",e.VIDEO_LOAD_ERROR="VIDEO_LOAD_ERROR"}(a||(a={}));class s{static setErrorHandler(e){this.onError=e}static handle(t,n){let o;return function(t){return t instanceof e}(t)?(o=t,n&&(o.context={...o.context,...n})):o=t instanceof Error?new e(t.message,"UNKNOWN_ERROR",{originalError:t.name,...n}):new e("string"==typeof t?t:"Unknown error occurred","UNKNOWN_ERROR",{originalError:t,...n}),this.onError?.(o),o}}function c(e){return`Minified Redux error #${e}; visit https://redux.js.org/Errors?code=${e} for the full message or use the non-minified dev environment for full errors. `}!function(e){e.BOTTOM_RIGHT="bottom-right",e.BOTTOM_CENTER="bottom-center",e.BOTTOM_LEFT="bottom-left",e.TOP_RIGHT="top-right",e.TOP_CENTER="top-center",e.TOP_LEFT="top-left",e.CENTER="center"}(r||(r={}));var l=(()=>"function"==typeof Symbol&&Symbol.observable||"@@observable")(),d=()=>Math.random().toString(36).substring(7).split("").join("."),p={INIT:`@@redux/INIT${d()}`,REPLACE:`@@redux/REPLACE${d()}`,PROBE_UNKNOWN_ACTION:()=>`@@redux/PROBE_UNKNOWN_ACTION${d()}`};function u(e){if("object"!=typeof e||null===e)return!1;let t=e;for(;null!==Object.getPrototypeOf(t);)t=Object.getPrototypeOf(t);return Object.getPrototypeOf(e)===t||null===Object.getPrototypeOf(e)}function m(e,t,n){if("function"!=typeof e)throw new Error(c(2));if("function"==typeof t&&"function"==typeof n||"function"==typeof n&&"function"==typeof arguments[3])throw new Error(c(0));if("function"==typeof t&&void 0===n&&(n=t,t=void 0),void 0!==n){if("function"!=typeof n)throw new Error(c(1));return n(m)(e,t)}let o=e,i=t,a=new Map,r=a,s=0,d=!1;function h(){r===a&&(r=new Map,a.forEach((e,t)=>{r.set(t,e)}))}function f(){if(d)throw new Error(c(3));return i}function b(e){if("function"!=typeof e)throw new Error(c(4));if(d)throw new Error(c(5));let t=!0;h();const n=s++;return r.set(n,e),function(){if(t){if(d)throw new Error(c(6));t=!1,h(),r.delete(n),a=null}}}function g(e){if(!u(e))throw new Error(c(7));if(void 0===e.type)throw new Error(c(8));if("string"!=typeof e.type)throw new Error(c(17));if(d)throw new Error(c(9));try{d=!0,i=o(i,e)}finally{d=!1}return(a=r).forEach(e=>{e()}),e}return g({type:p.INIT}),{dispatch:g,subscribe:b,getState:f,replaceReducer:function(e){if("function"!=typeof e)throw new Error(c(10));o=e,g({type:p.REPLACE})},[l]:function(){const e=b;return{subscribe(t){if("object"!=typeof t||null===t)throw new Error(c(11));function n(){t.next&&t.next(f())}return n(),{unsubscribe:e(n)}},[l](){return this}}}}}function h(...e){return 0===e.length?e=>e:1===e.length?e[0]:e.reduce((e,t)=>(...n)=>e(t(...n)))}var f=Symbol.for("immer-nothing"),b=Symbol.for("immer-draftable"),g=Symbol.for("immer-state");function v(e,...t){throw new Error(`[Immer] minified error nr: ${e}. Full error at: https://bit.ly/3cXEKWf`)}var _=Object,y=_.getPrototypeOf,w="constructor",C="prototype",E="configurable",S="enumerable",x="writable",k="value",T=e=>!!e&&!!e[g];function I(e){return!!e&&(A(e)||j(e)||!!e[b]||!!e[w]?.[b]||z(e)||F(e))}var N=_[C][w].toString(),O=new WeakMap;function A(e){if(!e||!V(e))return!1;const t=y(e);if(null===t||t===_[C])return!0;const n=_.hasOwnProperty.call(t,w)&&t[w];if(n===Object)return!0;if(!W(n))return!1;let o=O.get(n);return void 0===o&&(o=Function.toString.call(n),O.set(n,o)),o===N}function R(e,t,n=!0){0===D(e)?(n?Reflect.ownKeys(e):_.keys(e)).forEach(n=>{t(n,e[n],e)}):e.forEach((n,o)=>t(o,n,e))}function D(e){const t=e[g];return t?t.type_:j(e)?1:z(e)?2:F(e)?3:0}var L=(e,t,n=D(e))=>2===n?e.has(t):_[C].hasOwnProperty.call(e,t),P=(e,t,n=D(e))=>2===n?e.get(t):e[t],M=(e,t,n,o=D(e))=>{2===o?e.set(t,n):3===o?e.add(n):e[t]=n},j=Array.isArray,z=e=>e instanceof Map,F=e=>e instanceof Set,V=e=>"object"==typeof e,W=e=>"function"==typeof e,B=e=>"boolean"==typeof e,U=e=>e.copy_||e.base_,$=e=>e.modified_?e.copy_:e.base_;function K(e,t){if(z(e))return new Map(e);if(F(e))return new Set(e);if(j(e))return Array[C].slice.call(e);const n=A(e);if(!0===t||"class_only"===t&&!n){const t=_.getOwnPropertyDescriptors(e);delete t[g];let n=Reflect.ownKeys(t);for(let o=0;o<n.length;o++){const i=n[o],a=t[i];!1===a[x]&&(a[x]=!0,a[E]=!0),(a.get||a.set)&&(t[i]={[E]:!0,[x]:!0,[S]:a[S],[k]:e[i]})}return _.create(y(e),t)}{const t=y(e);if(null!==t&&n)return{...e};const o=_.create(t);return _.assign(o,e)}}function G(e,t=!1){return H(e)||T(e)||!I(e)||(D(e)>1&&_.defineProperties(e,{set:q,add:q,clear:q,delete:q}),_.freeze(e),t&&R(e,(e,t)=>{G(t,!0)},!1)),e}var q={[k]:function(){v(2)}};function H(e){return null===e||!V(e)||_.isFrozen(e)}var Q="MapSet",J="Patches",X={};function Y(e){const t=X[e];return t||v(0),t}var Z,ee=e=>!!X[e],te=()=>Z;function ne(e,t){t&&(e.patchPlugin_=Y(J),e.patches_=[],e.inversePatches_=[],e.patchListener_=t)}function oe(e){ie(e),e.drafts_.forEach(re),e.drafts_=null}function ie(e){e===Z&&(Z=e.parent_)}var ae=e=>Z=((e,t)=>({drafts_:[],parent_:e,immer_:t,canAutoFreeze_:!0,unfinalizedDrafts_:0,handledSet_:new Set,processedForPatches_:new Set,mapSetPlugin_:ee(Q)?Y(Q):void 0}))(Z,e);function re(e){const t=e[g];0===t.type_||1===t.type_?t.revoke_():t.revoked_=!0}function se(e,t){t.unfinalizedDrafts_=t.drafts_.length;const n=t.drafts_[0];if(void 0!==e&&e!==n){n[g].modified_&&(oe(t),v(4)),I(e)&&(e=ce(t,e));const{patchPlugin_:o}=t;o&&o.generateReplacementPatches_(n[g].base_,e,t)}else e=ce(t,n);return function(e,t,n=!1){!e.parent_&&e.immer_.autoFreeze_&&e.canAutoFreeze_&&G(t,n)}(t,e,!0),oe(t),t.patches_&&t.patchListener_(t.patches_,t.inversePatches_),e!==f?e:void 0}function ce(e,t){if(H(t))return t;const n=t[g];if(!n)return he(t,e.handledSet_,e);if(!de(n,e))return t;if(!n.modified_)return n.base_;if(!n.finalized_){const{callbacks_:t}=n;if(t)for(;t.length>0;)t.pop()(e);me(n,e)}return n.copy_}function le(e){e.finalized_=!0,e.scope_.unfinalizedDrafts_--}var de=(e,t)=>e.scope_===t,pe=[];function ue(e,t,n,o){const i=U(e),a=e.type_;if(void 0!==o&&P(i,o,a)===t)return void M(i,o,n,a);if(!e.draftLocations_){const t=e.draftLocations_=new Map;R(i,(e,n)=>{if(T(n)){const o=t.get(n)||[];o.push(e),t.set(n,o)}})}const r=e.draftLocations_.get(t)??pe;for(const e of r)M(i,e,n,a)}function me(e,t){if(e.modified_&&!e.finalized_&&(3===e.type_||(e.assigned_?.size??0)>0)){const{patchPlugin_:n}=t;if(n){const o=n.getPath(e);o&&n.generatePatches_(e,o,t)}le(e)}}function he(e,t,n){return!n.immer_.autoFreeze_&&n.unfinalizedDrafts_<1||T(e)||t.has(e)||!I(e)||H(e)||(t.add(e),R(e,(o,i)=>{if(T(i)){const t=i[g];if(de(t,n)){const n=$(t);M(e,o,n,e.type_),le(t)}}else I(i)&&he(i,t,n)})),e}var fe={get(e,t){if(t===g)return e;const n=U(e);if(!L(n,t,e.type_))return function(e,t,n){const o=ve(t,n);return o?k in o?o[k]:o.get?.call(e.draft_):void 0}(e,n,t);const o=n[t];if(e.finalized_||!I(o))return o;if(o===ge(e.base_,t)){ye(e);const n=1===e.type_?+t:t,i=we(0,o,e,n);return e.copy_[n]=i}return o},has:(e,t)=>t in U(e),ownKeys:e=>Reflect.ownKeys(U(e)),set(e,t,n){const o=ve(U(e),t);if(o?.set)return o.set.call(e.draft_,n),!0;if(!e.modified_){const o=ge(U(e),t),i=o?.[g];if(i&&i.base_===n)return e.copy_[t]=n,e.assigned_.set(t,!1),!0;if(function(e,t){return e===t?0!==e||1/e==1/t:e!=e&&t!=t}(n,o)&&(void 0!==n||L(e.base_,t,e.type_)))return!0;ye(e),_e(e)}return e.copy_[t]===n&&(void 0!==n||t in e.copy_)||Number.isNaN(n)&&Number.isNaN(e.copy_[t])||(e.copy_[t]=n,e.assigned_.set(t,!0),function(e,t,n){const{scope_:o}=e;if(T(n)){const i=n[g];de(i,o)&&i.callbacks_.push(function(){ye(e);const o=$(i);ue(e,n,o,t)})}else I(n)&&e.callbacks_.push(function(){const i=U(e);P(i,t,e.type_)===n&&o.drafts_.length>1&&!0===(e.assigned_.get(t)??!1)&&e.copy_&&he(P(e.copy_,t,e.type_),o.handledSet_,o)})}(e,t,n)),!0},deleteProperty:(e,t)=>(ye(e),void 0!==ge(e.base_,t)||t in e.base_?(e.assigned_.set(t,!1),_e(e)):e.assigned_.delete(t),e.copy_&&delete e.copy_[t],!0),getOwnPropertyDescriptor(e,t){const n=U(e),o=Reflect.getOwnPropertyDescriptor(n,t);return o?{[x]:!0,[E]:1!==e.type_||"length"!==t,[S]:o[S],[k]:n[t]}:o},defineProperty(){v(11)},getPrototypeOf:e=>y(e.base_),setPrototypeOf(){v(12)}},be={};function ge(e,t){const n=e[g];return(n?U(n):e)[t]}function ve(e,t){if(!(t in e))return;let n=y(e);for(;n;){const e=Object.getOwnPropertyDescriptor(n,t);if(e)return e;n=y(n)}}function _e(e){e.modified_||(e.modified_=!0,e.parent_&&_e(e.parent_))}function ye(e){e.copy_||(e.assigned_=new Map,e.copy_=K(e.base_,e.scope_.immer_.useStrictShallowCopy_))}function we(e,t,n,o){const[i,a]=z(t)?Y(Q).proxyMap_(t,n):F(t)?Y(Q).proxySet_(t,n):function(e,t){const n=j(e),o={type_:n?1:0,scope_:t?t.scope_:te(),modified_:!1,finalized_:!1,assigned_:void 0,parent_:t,base_:e,draft_:null,copy_:null,revoke_:null,isManual_:!1,callbacks_:void 0};let i=o,a=fe;n&&(i=[o],a=be);const{revoke:r,proxy:s}=Proxy.revocable(i,a);return o.draft_=s,o.revoke_=r,[s,o]}(t,n);return(n?.scope_??te()).drafts_.push(i),a.callbacks_=n?.callbacks_??[],a.key_=o,n&&void 0!==o?function(e,t,n){e.callbacks_.push(function(o){const i=t;if(!i||!de(i,o))return;o.mapSetPlugin_?.fixSetContents(i);const a=$(i);ue(e,i.draft_??i,a,n),me(i,o)})}(n,a,o):a.callbacks_.push(function(e){e.mapSetPlugin_?.fixSetContents(a);const{patchPlugin_:t}=e;a.modified_&&t&&t.generatePatches_(a,[],e)}),i}function Ce(e){if(!I(e)||H(e))return e;const t=e[g];let n,o=!0;if(t){if(!t.modified_)return t.base_;t.finalized_=!0,n=K(e,t.scope_.immer_.useStrictShallowCopy_),o=t.scope_.immer_.shouldUseStrictIteration()}else n=K(e,!0);return R(n,(e,t)=>{M(n,e,Ce(t))},o),t&&(t.finalized_=!1),n}R(fe,(e,t)=>{be[e]=function(){const e=arguments;return e[0]=e[0][0],t.apply(this,e)}}),be.deleteProperty=function(e,t){return be.set.call(this,e,t,void 0)},be.set=function(e,t,n){return fe.set.call(this,e[0],t,n,e[0])};var Ee=(new class{constructor(e){this.autoFreeze_=!0,this.useStrictShallowCopy_=!1,this.useStrictIteration_=!1,this.produce=(e,t,n)=>{if(W(e)&&!W(t)){const n=t;t=e;const o=this;return function(e=n,...i){return o.produce(e,e=>t.call(this,e,...i))}}let o;if(W(t)||v(6),void 0===n||W(n)||v(7),I(e)){const i=ae(this),a=we(0,e,void 0);let r=!0;try{o=t(a),r=!1}finally{r?oe(i):ie(i)}return ne(i,n),se(o,i)}if(!e||!V(e)){if(o=t(e),void 0===o&&(o=e),o===f&&(o=void 0),this.autoFreeze_&&G(o,!0),n){const t=[],i=[];Y(J).generateReplacementPatches_(e,o,{patches_:t,inversePatches_:i}),n(t,i)}return o}v(1)},this.produceWithPatches=(e,t)=>{if(W(e))return(t,...n)=>this.produceWithPatches(t,t=>e(t,...n));let n,o;return[this.produce(e,t,(e,t)=>{n=e,o=t}),n,o]},B(e?.autoFreeze)&&this.setAutoFreeze(e.autoFreeze),B(e?.useStrictShallowCopy)&&this.setUseStrictShallowCopy(e.useStrictShallowCopy),B(e?.useStrictIteration)&&this.setUseStrictIteration(e.useStrictIteration)}createDraft(e){I(e)||v(8),T(e)&&(e=function(e){return T(e)||v(10),Ce(e)}(e));const t=ae(this),n=we(0,e,void 0);return n[g].isManual_=!0,ie(t),n}finishDraft(e,t){const n=e&&e[g];n&&n.isManual_||v(9);const{scope_:o}=n;return ne(o,t),se(void 0,o)}setAutoFreeze(e){this.autoFreeze_=e}setUseStrictShallowCopy(e){this.useStrictShallowCopy_=e}setUseStrictIteration(e){this.useStrictIteration_=e}shouldUseStrictIteration(){return this.useStrictIteration_}applyPatches(e,t){let n;for(n=t.length-1;n>=0;n--){const o=t[n];if(0===o.path.length&&"replace"===o.op){e=o.value;break}}n>-1&&(t=t.slice(n+1));const o=Y(J).applyPatches_;return T(e)?o(e,t):this.produce(e,e=>o(e,t))}}).produce;function Se(e){return({dispatch:t,getState:n})=>o=>i=>"function"==typeof i?i(t,n,e):o(i)}var xe=Se(),ke=Se,Te="undefined"!=typeof window&&window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__?window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__:function(){if(0!==arguments.length)return"object"==typeof arguments[0]?h:h.apply(null,arguments)};function Ie(e,t){function n(...n){if(t){let o=t(...n);if(!o)throw new Error(Ve(0));return{type:e,payload:o.payload,..."meta"in o&&{meta:o.meta},..."error"in o&&{error:o.error}}}return{type:e,payload:n[0]}}return n.toString=()=>`${e}`,n.type=e,n.match=t=>function(e){return u(e)&&"type"in e&&"string"==typeof e.type}(t)&&t.type===e,n}var Ne=class e extends Array{constructor(...t){super(...t),Object.setPrototypeOf(this,e.prototype)}static get[Symbol.species](){return e}concat(...e){return super.concat.apply(this,e)}prepend(...t){return 1===t.length&&Array.isArray(t[0])?new e(...t[0].concat(this)):new e(...t.concat(this))}};function Oe(e){return I(e)?Ee(e,()=>{}):e}function Ae(e,t,n){return e.has(t)?e.get(t):e.set(t,n(t)).get(t)}var Re=e=>t=>{setTimeout(t,e)};function De(e){const t={},n=[];let o;const i={addCase(e,n){const o="string"==typeof e?e:e.type;if(!o)throw new Error(Ve(28));if(o in t)throw new Error(Ve(29));return t[o]=n,i},addAsyncThunk:(e,o)=>(o.pending&&(t[e.pending.type]=o.pending),o.rejected&&(t[e.rejected.type]=o.rejected),o.fulfilled&&(t[e.fulfilled.type]=o.fulfilled),o.settled&&n.push({matcher:e.settled,reducer:o.settled}),i),addMatcher:(e,t)=>(n.push({matcher:e,reducer:t}),i),addDefaultCase:e=>(o=e,i)};return e(i),[t,n,o]}var Le=Symbol.for("rtk-slice-createasyncthunk");function Pe(e,t){return`${e}/${t}`}function Me({creators:e}={}){const t=e?.asyncThunk?.[Le];return function(e){const{name:n,reducerPath:o=n}=e;if(!n)throw new Error(Ve(11));const i=("function"==typeof e.reducers?e.reducers(function(){function e(e,t){return{_reducerDefinitionType:"asyncThunk",payloadCreator:e,...t}}return e.withTypes=()=>e,{reducer:e=>Object.assign({[e.name]:(...t)=>e(...t)}[e.name],{_reducerDefinitionType:"reducer"}),preparedReducer:(e,t)=>({_reducerDefinitionType:"reducerWithPrepare",prepare:e,reducer:t}),asyncThunk:e}}()):e.reducers)||{},a=Object.keys(i),r={sliceCaseReducersByName:{},sliceCaseReducersByType:{},actionCreators:{},sliceMatchers:[]},s={addCase(e,t){const n="string"==typeof e?e:e.type;if(!n)throw new Error(Ve(12));if(n in r.sliceCaseReducersByType)throw new Error(Ve(13));return r.sliceCaseReducersByType[n]=t,s},addMatcher:(e,t)=>(r.sliceMatchers.push({matcher:e,reducer:t}),s),exposeAction:(e,t)=>(r.actionCreators[e]=t,s),exposeCaseReducer:(e,t)=>(r.sliceCaseReducersByName[e]=t,s)};function c(){const[t={},n=[],o]="function"==typeof e.extraReducers?De(e.extraReducers):[e.extraReducers],i={...t,...r.sliceCaseReducersByType};return function(e){let t,[a,s,c]=De(e=>{for(let t in i)e.addCase(t,i[t]);for(let t of r.sliceMatchers)e.addMatcher(t.matcher,t.reducer);for(let t of n)e.addMatcher(t.matcher,t.reducer);o&&e.addDefaultCase(o)});if(function(e){return"function"==typeof e}(e))t=()=>Oe(e());else{const n=Oe(e);t=()=>n}function l(e=t(),n){let o=[a[n.type],...s.filter(({matcher:e})=>e(n)).map(({reducer:e})=>e)];return 0===o.filter(e=>!!e).length&&(o=[c]),o.reduce((e,t)=>{if(t){if(T(e)){const o=t(e,n);return void 0===o?e:o}if(I(e))return Ee(e,e=>t(e,n));{const o=t(e,n);if(void 0===o){if(null===e)return e;throw Error("A case reducer on a non-draftable value must not return undefined")}return o}}return e},e)}return l.getInitialState=t,l}(e.initialState)}a.forEach(o=>{const a=i[o],r={reducerName:o,type:Pe(n,o),createNotation:"function"==typeof e.reducers};!function(e){return"asyncThunk"===e._reducerDefinitionType}(a)?function({type:e,reducerName:t,createNotation:n},o,i){let a,r;if("reducer"in o){if(n&&!function(e){return"reducerWithPrepare"===e._reducerDefinitionType}(o))throw new Error(Ve(17));a=o.reducer,r=o.prepare}else a=o;i.addCase(e,a).exposeCaseReducer(t,a).exposeAction(t,r?Ie(e,r):Ie(e))}(r,a,s):function({type:e,reducerName:t},n,o,i){if(!i)throw new Error(Ve(18));const{payloadCreator:a,fulfilled:r,pending:s,rejected:c,settled:l,options:d}=n,p=i(e,a,d);o.exposeAction(t,p),r&&o.addCase(p.fulfilled,r),s&&o.addCase(p.pending,s),c&&o.addCase(p.rejected,c),l&&o.addMatcher(p.settled,l),o.exposeCaseReducer(t,{fulfilled:r||Fe,pending:s||Fe,rejected:c||Fe,settled:l||Fe})}(r,a,s,t)});const l=e=>e,d=new Map,p=new WeakMap;let u;function m(e,t){return u||(u=c()),u(e,t)}function h(){return u||(u=c()),u.getInitialState()}function f(t,n=!1){function o(e){let i=e[t];return void 0===i&&n&&(i=Ae(p,o,h)),i}function i(t=l){const o=Ae(d,n,()=>new WeakMap);return Ae(o,t,()=>{const o={};for(const[i,a]of Object.entries(e.selectors??{}))o[i]=je(a,t,()=>Ae(p,t,h),n);return o})}return{reducerPath:t,getSelectors:i,get selectors(){return i(o)},selectSlice:o}}const b={name:n,reducer:m,actions:r.actionCreators,caseReducers:r.sliceCaseReducersByName,getInitialState:h,...f(o),injectInto(e,{reducerPath:t,...n}={}){const i=t??o;return e.inject({reducerPath:i,reducer:m},n),{...b,...f(i,!0)}}};return b}}function je(e,t,n,o){function i(i,...a){let r=t(i);return void 0===r&&o&&(r=n()),e(r,...a)}return i.unwrapped=e,i}var ze=Me();function Fe(){}function Ve(e){return`Minified Redux Toolkit error #${e}; visit https://redux-toolkit.js.org/Errors?code=${e} for the full message or use the non-minified dev environment for full errors. `}const We=ze({name:"avatar",initialState:{avatarReady:!1,dataChannel:null,stopInteraction:!1,muted:!1,transcript:void 0,customVoiceId:void 0,defaultVoiceId:void 0,connectionToken:void 0,companionId:void 0,closeConnectionHandler:void 0},reducers:{setSessionId:(e,t)=>{e.sessionId=t.payload},setAvatarReady:(e,t)=>{e.avatarReady=t.payload},setDataChannel:(e,t)=>{e.dataChannel=t.payload},setAvatarId:(e,t)=>{e.avatarId=t.payload},setVideoId:(e,t)=>{e.videoId=t.payload},setStopInteraction:(e,t)=>{e.stopInteraction=t.payload},setMuted:(e,t)=>{e.muted=t.payload},addTranscript:(e,t)=>{e.transcript=t.payload},setCustomVoiceId:(e,t)=>{e.customVoiceId=t.payload},setDefaultVoiceId:(e,t)=>{e.defaultVoiceId=t.payload},setConnectionToken:(e,t)=>{e.connectionToken=t.payload},setCloseConnectionHandler:(e,t)=>{e.closeConnectionHandler=t.payload}}}),{setDataChannel:Be,setStopInteraction:Ue,setMuted:$e,setConnectionToken:Ke,setCloseConnectionHandler:Ge}=We.actions,qe=We.reducer,He={features:{backgroundRemoval:{enabled:!0},waveform:{enabled:!0,color:"#ffffff"},inactiveTimeout:{enabled:!0,duration:6e4,countdown:30},disclaimer:{enabled:!0,text:"This is an AI avatar. Check important info."},showSDKLoader:{enabled:!0,bgColor:"rgb(222 222 222 / 60%)",color:"#585858ff",type:"spinner"}},position:void 0,showExperience:!1,debugMode:!1},Qe=ze({name:"app",initialState:He,reducers:{setFeatures:(e,t)=>{const{feature:n,config:o}=t.payload,i=e.features[n];e.features[n]={...i,...o,enabled:o?.enabled??!!i?.enabled}},resetFeatures:e=>{e.features=He.features},setPosition:(e,t)=>{e.position=t.payload},setShowExperience:(e,t)=>{e.showExperience=t.payload},setDebugMode:(e,t)=>{e.debugMode=t.payload}}}),{setFeatures:Je,resetFeatures:Xe,setPosition:Ye,setDebugMode:Ze}=Qe.actions;let et=null;const tt=e=>{et=e},nt=e=>t=>n=>{const o=e.getState().app.features,i=t(n),a=e.getState().app.features;return et&&o!==a&&JSON.stringify(o)!==JSON.stringify(a)&&et(a),i},ot=function(e){const t=function(e){const{thunk:t=!0,immutableCheck:n=!0,serializableCheck:o=!0,actionCreatorCheck:i=!0}=e??{};let a=new Ne;return t&&(function(e){return"boolean"==typeof e}(t)?a.push(xe):a.push(ke(t.extraArgument))),a},{reducer:n,middleware:o,devTools:i=!0,preloadedState:a,enhancers:r}=e||{};let s,l;if("function"==typeof n)s=n;else{if(!u(n))throw new Error(Ve(1));s=function(e){const t=Object.keys(e),n={};for(let o=0;o<t.length;o++){const i=t[o];"function"==typeof e[i]&&(n[i]=e[i])}const o=Object.keys(n);let i;try{!function(e){Object.keys(e).forEach(t=>{const n=e[t];if(void 0===n(void 0,{type:p.INIT}))throw new Error(c(12));if(void 0===n(void 0,{type:p.PROBE_UNKNOWN_ACTION()}))throw new Error(c(13))})}(n)}catch(e){i=e}return function(e={},t){if(i)throw i;let a=!1;const r={};for(let i=0;i<o.length;i++){const s=o[i],l=e[s],d=(0,n[s])(l,t);if(void 0===d)throw new Error(c(14));r[s]=d,a=a||d!==l}return a=a||o.length!==Object.keys(e).length,a?r:e}}(n)}l="function"==typeof o?o(t):t();let d=h;i&&(d=Te({trace:!1,..."object"==typeof i&&i}));const f=function(...e){return t=>(n,o)=>{const i=t(n,o);let a=()=>{throw new Error(c(15))};const r={getState:i.getState,dispatch:(e,...t)=>a(e,...t)},s=e.map(e=>e(r));return a=h(...s)(i.dispatch),{...i,dispatch:a}}}(...l),b=(e=>function(t){const{autoBatch:n=!0}=t??{};let o=new Ne(e);return n&&o.push(((e={type:"raf"})=>t=>(...n)=>{const o=t(...n);let i=!0,a=!1,r=!1;const s=new Set,c="tick"===e.type?queueMicrotask:"raf"===e.type?"undefined"!=typeof window&&window.requestAnimationFrame?window.requestAnimationFrame:Re(10):"callback"===e.type?e.queueNotification:Re(e.timeout),l=()=>{r=!1,a&&(a=!1,s.forEach(e=>e()))};return Object.assign({},o,{subscribe(e){const t=o.subscribe(()=>i&&e());return s.add(e),()=>{t(),s.delete(e)}},dispatch(e){try{return i=!e?.meta?.RTK_autoBatch,a=!i,a&&(r||(r=!0,c(l))),o.dispatch(e)}finally{i=!0}}})})("object"==typeof n?n:void 0)),o})(f);return m(s,a,d(..."function"==typeof r?r(b):b()))}({reducer:{avatar:qe,app:Qe.reducer},middleware:e=>e({serializableCheck:!1}).concat(nt)});var it;!function(e){e.INFO="info",e.WARN="warn",e.ERROR="error",e.DEBUG="debug"}(it||(it={}));const at=new class{constructor(){Object.defineProperty(this,"prefix",{enumerable:!0,configurable:!0,writable:!0,value:"[Napster SDK]"})}isDebugEnabled(){try{return ot.getState().app.debugMode||!1}catch{return!1}}log(e,...t){if(!this.isDebugEnabled())return;const n=[this.prefix,...t];switch(e){case it.INFO:console.info(...n);break;case it.WARN:console.warn(...n);break;case it.ERROR:console.error(...n);break;case it.DEBUG:console.debug(...n)}}info(...e){this.log(it.INFO,"ℹ️",...e)}debug(...e){this.log(it.DEBUG,"🐞",...e)}warn(...e){this.log(it.WARN,"⚠️",...e)}error(...e){this.log(it.ERROR,"❌",...e)}critical_warn(...e){console.warn(this.prefix,"⚠️",...e)}critical_error(...e){console.error(this.prefix,"❌",...e)}webrtc(...e){this.log(it.INFO,"📡 WebRTC:",...e)}avatar(...e){this.log(it.INFO,"🎭 Avatar:",...e)}connection(...e){this.log(it.INFO,"🔌 Connection:",...e)}features(...e){this.log(it.INFO,"🔄 Features:",...e)}data(...e){this.log(it.INFO,"📨 Data:",...e)}timer(...e){this.log(it.INFO,"⏱️ Timer:",...e)}cleanup(...e){this.log(it.INFO,"🗑️ Cleanup:",...e)}};function rt(...e){const t=[];for(const n of e)if(n)if("string"==typeof n||"number"==typeof n)t.push(String(n));else if(Array.isArray(n)){const e=rt(...n);e&&t.push(e)}else if("object"==typeof n)for(const[e,o]of Object.entries(n))o&&t.push(e);return t.join(" ")}const st={icon:"np_companion-action-btn-container-icon",persistFillColor:"np_companion-persist-fill-color",alignMiddle:"np_companion-align-middle",alignBetween:"np_companion-align-between",darkGreyBg:"np_companion-dark-grey-bg",callEnd:"np_companion-action-btn-container-call-end",container:"np_companion-action-btn-container-container",wrapper:"np_companion-action-btn-container-wrapper",canvas:"np_companion-action-btn-container-canvas",controls:"np_companion-action-btn-container-controls",left:"np_companion-action-btn-container-left",middle:"np_companion-action-btn-container-middle",right:"np_companion-action-btn-container-right",wave:"np_companion-action-btn-container-wave",stop:"np_companion-action-btn-container-stop",questionBar:"np_companion-chat-question-bar-container",muted:"muted",hidden:"np_companion-hidden",expanded:"np_companion-action-btn-container-expanded",collapse:"np_companion-action-btn-container-collapse",mobileMode:"np_companion-mobile-mode",displayNone:"np_companion__d-none",iconButton:()=>rt(st.icon,st.alignMiddle,st.darkGreyBg),iconButtonEnd:()=>rt(st.icon,st.alignMiddle,st.darkGreyBg,st.callEnd),iconButtonWithState:e=>rt(st.icon,st.alignMiddle,st.darkGreyBg,{[st.muted]:e})};class ct{static createElement(e,t){const n=document.createElement(e);return t?.className&&(n.className=t.className),t?.id&&(n.id=t.id),t?.attributes&&Object.entries(t.attributes).forEach(([e,t])=>{n.setAttribute(e,t)}),t?.styles&&Object.assign(n.style,t.styles),n}static createVideo(e){const t=this.createElement("video",{className:e.className});return t.autoplay=e.autoplay??!1,t.muted=e.muted??!1,t.loop=e.loop??!1,t.playsInline=e.playsInline??!1,e.crossOrigin&&(t.crossOrigin=e.crossOrigin),e.poster&&(t.poster=e.poster),e.src&&(t.src=e.src),t}static createAudio(e){const t=this.createElement("audio",{className:e.className});return t.autoplay=e.autoplay??!1,t}static createCanvas(e){const t=this.createElement("canvas",{className:e.className,styles:e.styles});return void 0!==e.width&&(t.width=e.width),void 0!==e.height&&(t.height=e.height),t}static createButton(e){const t=this.createElement("button",{className:e.className,attributes:e.attributes});return e.textContent&&(t.textContent=e.textContent),e.onClick&&t.addEventListener("click",e.onClick),t}static createDiv(e){return this.createElement("div",{className:e})}}class lt{static process(e){const t=e.data;return this.hasGreenScreen(t)?(this.removeGreenScreen(t),e):e}static hasGreenScreen(e){for(let t=0;t<e.length;t+=4)if(this.isGreenPixel(e[t],e[t+1],e[t+2]))return!0;return!1}static isGreenPixel(e,t,n){return e>=0&&e<=120&&t>=150&&t<=255&&n>=0&&n<=120}static removeGreenScreen(e){for(let t=0;t<e.length;t+=4){const n=e[t],o=e[t+1],i=e[t+2];this.isGreenPixel(n,o,i)?e[t+3]=0:this.reduceGreenSpill(e,t,n,o,i)}}static reduceGreenSpill(e,t,n,o,i){const a=o-Math.max(n,i);if(a>0){const r=.5*a;e[t]=Math.min(255,n+.8*r),e[t+2]=Math.min(255,i+.8*r),e[t+1]=Math.max(0,o-r)}}}const dt=new class{constructor(){Object.defineProperty(this,"svgNS",{enumerable:!0,configurable:!0,writable:!0,value:"http://www.w3.org/2000/svg"})}createElement(e){const t=document.createElementNS(this.svgNS,e.tag);return e.attributes&&Object.entries(e.attributes).forEach(([e,n])=>{t.setAttribute(e,String(n))}),e.textContent&&(t.textContent=e.textContent),e.children&&e.children.forEach(e=>{const n=this.createElement(e);t.appendChild(n)}),t}createSVG(e,t,n,o,i){const a=document.createElementNS(this.svgNS,"svg");return a.setAttribute("width",String(e)),a.setAttribute("height",String(t)),a.setAttribute("viewBox",n),a.setAttribute("fill","none"),a.setAttribute("xmlns",this.svgNS),i&&a.setAttribute("class",i),o.forEach(e=>{const t=this.createElement(e);a.appendChild(t)}),a}},pt={micUnmuted:()=>dt.createSVG(17,17,"0 0 17 17",[{tag:"g",attributes:{"clip-path":"url(#clip0_655_3824)"},children:[{tag:"path",attributes:{d:"M8.67241 11.8448C9.49524 11.844 10.2841 11.5167 10.8659 10.9349C11.4478 10.3531 11.775 9.5642 11.7759 8.74138V4.60345C11.7759 3.78036 11.4489 2.99099 10.8669 2.40898C10.2849 1.82697 9.4955 1.5 8.67241 1.5C7.84933 1.5 7.05995 1.82697 6.47794 2.40898C5.89594 2.99099 5.56897 3.78036 5.56897 4.60345V8.74138C5.56982 9.5642 5.89707 10.3531 6.47889 10.9349C7.06071 11.5167 7.84959 11.844 8.67241 11.8448ZM6.60345 4.60345C6.60345 4.05472 6.82143 3.52847 7.20943 3.14047C7.59744 2.75246 8.12369 2.53448 8.67241 2.53448C9.22114 2.53448 9.74739 2.75246 10.1354 3.14047C10.5234 3.52847 10.7414 4.05472 10.7414 4.60345V8.74138C10.7414 9.2901 10.5234 9.81635 10.1354 10.2044C9.74739 10.5924 9.22114 10.8103 8.67241 10.8103C8.12369 10.8103 7.59744 10.5924 7.20943 10.2044C6.82143 9.81635 6.60345 9.2901 6.60345 8.74138V4.60345ZM9.18965 13.8879V15.9828C9.18965 16.1199 9.13516 16.2515 9.03816 16.3485C8.94116 16.4455 8.80959 16.5 8.67241 16.5C8.53523 16.5 8.40367 16.4455 8.30667 16.3485C8.20967 16.2515 8.15517 16.1199 8.15517 15.9828V13.8879C6.87994 13.7582 5.69812 13.1601 4.83826 12.2095C3.9784 11.2589 3.50158 10.0232 3.5 8.74138C3.5 8.6042 3.5545 8.47264 3.6515 8.37563C3.7485 8.27863 3.88006 8.22414 4.01724 8.22414C4.15442 8.22414 4.28598 8.27863 4.38299 8.37563C4.47999 8.47264 4.53448 8.6042 4.53448 8.74138C4.53448 9.83883 4.97044 10.8913 5.74645 11.6673C6.52247 12.4434 7.57497 12.8793 8.67241 12.8793C9.76986 12.8793 10.8224 12.4434 11.5984 11.6673C12.3744 10.8913 12.8103 9.83883 12.8103 8.74138C12.8103 8.6042 12.8648 8.47264 12.9618 8.37563C13.0588 8.27863 13.1904 8.22414 13.3276 8.22414C13.4648 8.22414 13.5963 8.27863 13.6933 8.37563C13.7903 8.47264 13.8448 8.6042 13.8448 8.74138C13.8433 10.0232 13.3664 11.2589 12.5066 12.2095C11.6467 13.1601 10.4649 13.7582 9.18965 13.8879Z",fill:"white"}}]},{tag:"defs",children:[{tag:"clipPath",attributes:{id:"clip0_655_3824"},children:[{tag:"rect",attributes:{width:"16",height:"16",fill:"white",transform:"translate(0.5 0.5)"}}]}]}],"np_companion-mic-unmuted"),micMuted:()=>dt.createSVG(22,22,"0 0 17 18",[{tag:"g",attributes:{"clip-path":"url(#clip0_655_4192)"},children:[{tag:"path",attributes:{d:"M14.2432 14.6L3.89604 3.21808C3.80327 3.11843 3.67498 3.05936 3.53896 3.05368C3.40294 3.048 3.27016 3.09616 3.16941 3.18772C3.06866 3.27928 3.00806 3.40686 3.00075 3.5428C2.99343 3.67874 3.04 3.81208 3.13034 3.91392L5.58263 6.61131V8.7396C5.58251 9.26661 5.71656 9.78497 5.97216 10.2458C6.22776 10.7067 6.59649 11.0949 7.04361 11.3739C7.49073 11.6529 8.00151 11.8134 8.52782 11.8404C9.05414 11.8674 9.57867 11.7599 10.052 11.5282L10.7698 12.3171C10.138 12.6868 9.41878 12.8806 8.68679 12.8785C7.58946 12.8773 6.53741 12.4408 5.76148 11.6649C4.98555 10.889 4.54911 9.83693 4.54791 8.7396C4.54791 8.60239 4.4934 8.47079 4.39638 8.37377C4.29935 8.27675 4.16776 8.22224 4.03055 8.22224C3.89334 8.22224 3.76174 8.27675 3.66472 8.37377C3.5677 8.47079 3.51319 8.60239 3.51319 8.7396C3.51476 10.0217 3.9917 11.2577 4.85176 12.2085C5.71182 13.1594 6.8939 13.7575 8.16943 13.8873V15.9826C8.16943 16.1199 8.22394 16.2514 8.32096 16.3485C8.41798 16.4455 8.54958 16.5 8.68679 16.5C8.824 16.5 8.95559 16.4455 9.05262 16.3485C9.14964 16.2514 9.20415 16.1199 9.20415 15.9826V13.8867C10.0143 13.8085 10.794 13.5376 11.4779 13.0964L13.4775 15.2952C13.523 15.3464 13.5781 15.3881 13.6398 15.4178C13.7015 15.4476 13.7684 15.4648 13.8368 15.4685C13.9051 15.4722 13.9735 15.4622 14.038 15.4393C14.1025 15.4163 14.1618 15.3808 14.2125 15.3347C14.2632 15.2887 14.3042 15.2331 14.3332 15.171C14.3622 15.109 14.3786 15.0419 14.3815 14.9735C14.3843 14.9051 14.3736 14.8368 14.3499 14.7725C14.3261 14.7083 14.2899 14.6495 14.2432 14.5993V14.6ZM8.68679 10.809C8.13794 10.809 7.61157 10.591 7.22347 10.2029C6.83538 9.81482 6.61735 9.28845 6.61735 8.7396V7.7495L9.3115 10.7127C9.10943 10.7766 8.89873 10.8091 8.68679 10.809ZM12.4066 10.5562C12.6841 9.99093 12.8275 9.36929 12.8257 8.7396C12.8257 8.60239 12.8802 8.47079 12.9772 8.37377C13.0742 8.27675 13.2058 8.22224 13.343 8.22224C13.4802 8.22224 13.6118 8.27675 13.7089 8.37377C13.8059 8.47079 13.8604 8.60239 13.8604 8.7396C13.8625 9.52693 13.6831 10.3041 13.3359 11.0108C13.2934 11.0979 13.2273 11.1713 13.145 11.2226C13.0628 11.274 12.9679 11.3012 12.8709 11.3012C12.7922 11.3013 12.7145 11.2831 12.6439 11.2481C12.5207 11.1878 12.4265 11.0811 12.382 10.9513C12.3375 10.8215 12.3463 10.6794 12.4066 10.5562ZM5.84131 3.36358C6.12624 2.71004 6.62746 2.1745 7.26073 1.84696C7.894 1.51943 8.62071 1.41987 9.31874 1.56501C10.0168 1.71015 10.6435 2.09116 11.0938 2.64398C11.544 3.19681 11.7902 3.88776 11.7909 4.60072V8.7396C11.7908 8.8476 11.7852 8.95552 11.7741 9.06295C11.7608 9.19066 11.7005 9.30885 11.6049 9.39455C11.5092 9.48025 11.3852 9.52733 11.2568 9.52663C11.2387 9.52757 11.2205 9.52757 11.2025 9.52663C11.066 9.51229 10.9409 9.44435 10.8545 9.33775C10.7682 9.23115 10.7277 9.09462 10.742 8.95818C10.7491 8.88705 10.753 8.81332 10.753 8.74089V4.60072C10.7516 4.12605 10.5871 3.66628 10.2871 3.29848C9.98701 2.93069 9.56963 2.67722 9.10491 2.58058C8.64018 2.48393 8.15636 2.54998 7.73454 2.76766C7.31273 2.98534 6.97857 3.34141 6.78808 3.77618C6.7639 3.84253 6.72639 3.90322 6.67786 3.95452C6.62934 4.00583 6.57082 4.04665 6.50592 4.07449C6.44102 4.10232 6.37111 4.11658 6.30049 4.11637C6.22987 4.11617 6.16005 4.10151 6.09531 4.07329C6.03057 4.04508 5.9723 4.00392 5.92407 3.95233C5.87584 3.90075 5.83869 3.83983 5.81489 3.77335C5.7911 3.70686 5.78117 3.6362 5.78571 3.56573C5.79025 3.49526 5.80917 3.42646 5.84131 3.36358Z",fill:"white"}}]},{tag:"defs",children:[{tag:"clipPath",attributes:{id:"clip0_655_4192"},children:[{tag:"rect",attributes:{width:"16",height:"16",fill:"white",transform:"translate(0.5 0.5)"}}]}]}],"tc-mic-muted"),stop:()=>dt.createSVG(20,20,"0 0 32 32",[{tag:"path",attributes:{d:"M5.92 24.096q0 0.832 0.576 1.408t1.44 0.608h16.128q0.832 0 1.44-0.608t0.576-1.408v-16.16q0-0.832-0.576-1.44t-1.44-0.576h-16.128q-0.832 0-1.44 0.576t-0.576 1.44v16.16z",fill:"#ffffff"}}]),volumeHigh(e){const t=[{tag:"path",attributes:{d:"M80 416L128 416L262.1 535.2C268.5 540.9 276.7 544 285.2 544C304.4 544 320 528.4 320 509.2L320 130.8C320 111.6 304.4 96 285.2 96C276.7 96 268.5 99.1 262.1 104.8L128 224L80 224C53.5 224 32 245.5 32 272L32 368C32 394.5 53.5 416 80 416z",fill:"#ffffff"}}];return e>0&&t.push({tag:"path",attributes:{d:"M412.6 245.5C402.3 237.1 387.2 238.7 378.8 249C370.4 259.3 372 274.4 382.3 282.8C393.1 291.6 400 305 400 320C400 335 393.1 348.4 382.3 357.3C372 365.7 370.5 380.8 378.8 391.1C387.1 401.4 402.3 402.9 412.6 394.6C434.1 376.9 448 350.1 448 320C448 289.9 434.1 263.1 412.6 245.5z",fill:"#ffffff"}}),e>=25&&t.push({tag:"path",attributes:{d:"M473.1 171C462.8 162.6 447.7 164.2 439.3 174.5C430.9 184.8 432.5 199.9 442.8 208.3C475.3 234.7 496 274.9 496 320C496 365.1 475.3 405.3 442.8 431.8C432.5 440.2 431 455.3 439.3 465.6C447.6 475.9 462.8 477.4 473.1 469.1C516.3 433.9 544 380.2 544 320.1C544 260 516.3 206.3 473.1 171.1z",fill:"#ffffff"}}),e>=75&&t.push({tag:"path",attributes:{d:"M533.6 96.5C523.3 88.1 508.2 89.7 499.8 100C491.4 110.3 493 125.4 503.3 133.8C557.5 177.8 592 244.8 592 320C592 395.2 557.5 462.2 503.3 506.3C493 514.7 491.5 529.8 499.8 540.1C508.1 550.4 523.3 551.9 533.6 543.6C598.5 490.7 640 410.2 640 320C640 229.8 598.5 149.2 533.6 96.5z",fill:"#ffffff"}}),dt.createSVG(16,16,"0 0 640 640",t)},volumeMuted:()=>dt.createSVG(16,16,"0 0 640 640",[{tag:"path",attributes:{d:"M80 416L128 416L262.1 535.2C268.5 540.9 276.7 544 285.2 544C304.4 544 320 528.4 320 509.2L320 130.8C320 111.6 304.4 96 285.2 96C276.7 96 268.5 99.1 262.1 104.8L128 224L80 224C53.5 224 32 245.5 32 272L32 368C32 394.5 53.5 416 80 416zM399 239C389.6 248.4 389.6 263.6 399 272.9L446 319.9L399 366.9C389.6 376.3 389.6 391.5 399 400.8C408.4 410.1 423.6 410.2 432.9 400.8L479.9 353.8L526.9 400.8C536.3 410.2 551.5 410.2 560.8 400.8C570.1 391.4 570.2 376.2 560.8 366.9L513.8 319.9L560.8 272.9C570.2 263.5 570.2 248.3 560.8 239C551.4 229.7 536.2 229.6 526.9 239L479.9 286L432.9 239C423.5 229.6 408.3 229.6 399 239z",fill:"#ffffff"}}]),end:()=>dt.createSVG(16,16,"0 0 21 16",[{tag:"path",attributes:{d:"M17.7226 12.2992C18.3148 12.5423 18.991 12.308 19.307 11.7578L19.3954 11.6031C20.434 9.78662 20.2705 7.18344 18.2308 5.85533C13.5438 2.80798 7.45789 2.80798 2.77085 5.85533C0.726753 7.18344 0.567646 9.78662 1.60627 11.6031L1.69466 11.7578C2.01066 12.3125 2.68908 12.5445 3.2769 12.3014L6.32204 11.0462C6.83914 10.8341 7.15515 10.3059 7.0999 9.74684L6.90986 7.85081C9.2346 7.06853 11.7759 7.10831 14.0785 7.97456L13.8973 9.74684C13.8399 10.3037 14.1581 10.8297 14.6752 11.0462L17.7226 12.2992Z",fill:"red"}}])},ut=(e,t)=>{if("inactiveTimeout"===e){const e=t;return e?.enabled&&void 0!==e.duration&&e.duration>18e4&&(at.critical_warn(`Napster Companion API SDK: inactiveTimeout duration of ${e.duration}ms exceeds the recommended maximum of 180000ms. Setting maximum allowed value.`),delete e.duration),t}return t},mt={enabled:!1,batchSize:10,flushInterval:5e3,enablePerformanceTracking:!0,enableErrorTracking:!0,enableUserInteractionTracking:!0};class ht{constructor(e={}){Object.defineProperty(this,"config",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"eventQueue",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"performanceQueue",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"errorQueue",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"flushTimer",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"sessionId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"providers",{enumerable:!0,configurable:!0,writable:!0,value:[]}),this.config={...mt,...e},this.sessionId=this.config.sessionId||this.generateSessionId(),this.setupProviders(),this.config.enabled&&(this.startFlushTimer(),this.setupErrorTracking(),this.setupPerformanceTracking())}setupProviders(){this.providers=[],this.config.providers&&(this.providers=[...this.config.providers]),this.config.provider&&this.providers.push(this.config.provider),0===this.providers.length&&this.providers.push({type:"custom"})}generateSessionId(){return`session_${Date.now()}_${Math.random().toString(36).substr(2,9)}`}startFlushTimer(){this.flushTimer&&clearInterval(this.flushTimer),this.flushTimer=setInterval(()=>{this.flush()},this.config.flushInterval)}setupErrorTracking(){this.config.enableErrorTracking&&(window.addEventListener("error",e=>{this.trackError(e.error,{source:"window.error",filename:e.filename,lineno:e.lineno,colno:e.colno})}),window.addEventListener("unhandledrejection",e=>{this.trackError(new Error(e.reason),{source:"unhandledrejection",reason:e.reason})}))}setupPerformanceTracking(){this.config.enablePerformanceTracking&&"undefined"!=typeof window&&"performance"in window&&window.addEventListener("load",()=>{setTimeout(()=>{const e=performance.getEntriesByType("navigation")[0];e&&(this.trackPerformance("page_load_time",e.loadEventEnd-e.fetchStart,"ms"),this.trackPerformance("dom_content_loaded",e.domContentLoadedEventEnd-e.fetchStart,"ms"),this.trackPerformance("first_paint",e.responseEnd-e.fetchStart,"ms"))},0)})}trackEvent(e,t){if(!this.config.enabled)return;const n={name:e,properties:t,timestamp:Date.now(),userId:this.config.userId,sessionId:this.sessionId};this.eventQueue.push(n),this.eventQueue.length>=(this.config.batchSize||10)&&this.flush()}trackPerformance(e,t,n,o){if(!this.config.enabled||!this.config.enablePerformanceTracking)return;const i={name:e,value:t,unit:n,timestamp:Date.now(),context:o};this.performanceQueue.push(i)}trackError(e,t){if(!this.config.enabled||!this.config.enableErrorTracking)return;const n={error:e,context:t,timestamp:Date.now(),userId:this.config.userId,sessionId:this.sessionId,stack:e.stack};this.errorQueue.push(n),this.flushErrors()}trackInteraction(e,t,n){this.config.enableUserInteractionTracking&&this.trackEvent("user_interaction",{action:e,target:t,...n})}flush(){this.flushEvents(),this.flushPerformance(),this.flushErrors()}flushEvents(){if(0===this.eventQueue.length)return;const e=[...this.eventQueue];this.eventQueue=[],this.sendData("events",e)}flushPerformance(){if(0===this.performanceQueue.length)return;const e=[...this.performanceQueue];this.performanceQueue=[],this.sendData("performance",e)}flushErrors(){if(0===this.errorQueue.length)return;const e=[...this.errorQueue];this.errorQueue=[],this.sendData("errors",e)}async sendData(e,t){const n=this.providers.map(n=>this.sendToProvider(n,e,t));await Promise.allSettled(n)}async sendToProvider(e,t,n){try{switch(e.type){case"google-analytics-4":await this.sendToGA4(e,n);break;case"mixpanel":await this.sendToMixpanel(e,n);break;case"segment":await this.sendToSegment(e,n);break;case"amplitude":await this.sendToAmplitude(e,n);break;case"posthog":await this.sendToPostHog(e,n);break;case"azure-insights":await this.sendToAzureInsights(e,n);break;default:await this.sendToCustomEndpoint(e,t,n)}}catch(t){at.critical_warn(`Failed to send data to ${e.type}:`,t)}}async sendToCustomEndpoint(e,t,n){const o=e.endpoint,i=e.apiKey;if(!o)return;const a=await fetch(`${o}/${t}`,{method:"POST",headers:{"Content-Type":"application/json",...i&&{Authorization:`Bearer ${i}`}},body:JSON.stringify({data:n,sessionId:this.sessionId,timestamp:Date.now()})});if(!a.ok)throw new Error(`HTTP ${a.status}`)}async sendToGA4(e,t){const n=e.measurementId||e.apiKey;if(!n)throw new Error("GA4 measurement ID required");const o=`https://www.google-analytics.com/mp/collect?measurement_id=${n}&api_secret=${e.apiKey||"default"}`,i=t.map(e=>({name:e.name,params:{...e.properties,session_id:this.sessionId}}));await fetch(o,{method:"POST",body:JSON.stringify({client_id:this.sessionId,user_id:this.config.userId,events:i})})}async sendToMixpanel(e,t){const n=e.projectToken||e.apiKey;if(!n)throw new Error("Mixpanel project token required");const o=e.endpoint||"https://api.mixpanel.com/batch",i=t.map(e=>{const t=e;return{event:t.name,properties:{token:n,distinct_id:this.config.userId||this.sessionId,time:t.timestamp||Date.now(),...t.properties}}});await fetch(o,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(i)})}async sendToSegment(e,t){const n=e.writeKey||e.apiKey;if(!n)throw new Error("Segment write key required");const o=e.endpoint||"https://api.segment.io/v1/batch",i=t.map(e=>({type:"track",userId:this.config.userId||this.sessionId,event:e.name,properties:e.properties,timestamp:new Date(e.timestamp||Date.now()).toISOString()}));await fetch(o,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Basic ${btoa(n+":")}`},body:JSON.stringify({batch:i})})}async sendToAmplitude(e,t){const n=e.apiKey;if(!n)throw new Error("Amplitude API key required");const o=e.endpoint||"https://api2.amplitude.com/2/httpapi",i=t.map(e=>({user_id:this.config.userId||this.sessionId,event_type:e.name,event_properties:e.properties,time:e.timestamp||Date.now()}));await fetch(o,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({api_key:n,events:i})})}async sendToPostHog(e,t){const n=e.apiKey,o=e.endpoint||"https://app.posthog.com";if(!n)throw new Error("PostHog API key required");const i=t.map(e=>({event:e.name,properties:{...e.properties,distinct_id:this.config.userId||this.sessionId},timestamp:new Date(e.timestamp||Date.now()).toISOString()}));await fetch(`${o}/batch/`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({api_key:n,batch:i})})}async sendToAzureInsights(e,t){const n=e.apiKey;if(!n)throw new Error("Azure Application Insights instrumentation key required");const o=e.endpoint||"https://dc.services.visualstudio.com/v2/track",i=t.map(e=>{const t=e;return{name:"Microsoft.ApplicationInsights.Event",time:new Date(t.timestamp||Date.now()).toISOString(),iKey:n,data:{baseType:"EventData",baseData:{name:t.name,properties:t.properties}}}});await fetch(o,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(i)})}updateConfig(e){this.config={...this.config,...e},this.setupProviders(),this.config.enabled&&!this.flushTimer?this.startFlushTimer():!this.config.enabled&&this.flushTimer&&(clearInterval(this.flushTimer),this.flushTimer=void 0)}destroy(){this.flushTimer&&clearInterval(this.flushTimer),this.flush()}}let ft=null;const bt=(e,t)=>{ft?.trackEvent(e,t)},gt=(e,t,n)=>{ft?.trackInteraction(e,t,n)};function vt(e,t){void 0===t&&(t={});var n=t.insertAt;if(e&&"undefined"!=typeof document){var o=document.head||document.getElementsByTagName("head")[0],i=document.createElement("style");i.type="text/css","top"===n&&o.firstChild?o.insertBefore(i,o.firstChild):o.appendChild(i),i.styleSheet?i.styleSheet.cssText=e:i.appendChild(document.createTextNode(e))}}function _t(e,{content:t,placement:n="top"}){let o=!1,i=null,a=null;const r=e=>"left"===e?"start":"right"===e?"end":e,s=()=>{if(!i)return;const t=e.getBoundingClientRect(),o=i.getBoundingClientRect();let a=0,r=0;switch(n){case"top":a=t.top-o.height-8,r=t.left+(t.width-o.width)/2;break;case"bottom":a=t.bottom+8,r=t.left+(t.width-o.width)/2;break;case"left":a=t.top+(t.height-o.height)/2,r=t.left-o.width-8;break;case"right":a=t.top+(t.height-o.height)/2,r=t.right+8}i.style.top=`${a}px`,i.style.left=`${r}px`},c=()=>s(),l=()=>{if(o)return;const e=(()=>{if(i)return i;const e=document.createElement("div");e.className=`tooltip styled-tooltip bs-tooltip-${r(n)} show`,e.setAttribute("role","tooltip"),Object.assign(e.style,{position:"fixed",top:"0px",left:"0px",zIndex:String(2147483647),opacity:"0",visibility:"hidden",pointerEvents:"none",transition:"opacity 80ms ease"});const o=document.createElement("div");o.className="tooltip-arrow";const a=document.createElement("div");return a.className="tooltip-inner","string"==typeof t?a.textContent=t:a.appendChild(t),e.appendChild(o),e.appendChild(a),document.body.appendChild(e),i=e,e})();o=!0,s(),a=window.setTimeout(s,10),e.style.opacity="1",e.style.visibility="visible",window.addEventListener("scroll",c,!0),window.addEventListener("resize",c)},d=()=>{o&&(o=!1,null!=a&&(window.clearTimeout(a),a=null),i&&(i.style.opacity="0",i.style.visibility="hidden"),window.removeEventListener("scroll",c,!0),window.removeEventListener("resize",c))},p=()=>l(),u=()=>d();return e.addEventListener("mouseenter",p),e.addEventListener("mouseleave",u),e.matches?.(":hover")&&l(),{update:e=>{if(void 0!==e.content&&i){const t=i.querySelector(".tooltip-inner");t&&(t.innerHTML="","string"==typeof e.content?t.textContent=e.content:t.appendChild(e.content))}void 0!==e.placement&&(n=e.placement,i&&(i.className=`tooltip styled-tooltip bs-tooltip-${r(n)} show`)),o&&s()},show:l,hide:d,destroy:()=>{d(),e.removeEventListener("mouseenter",p),e.removeEventListener("mouseleave",u),i&&i.parentNode&&i.parentNode.removeChild(i),i=null}}}function yt(e,t){const n=document.createElement(e);return t&&(n.className=t),n}var wt,Ct,Et,St,xt,kt,Tt;vt(".np_companion-live-container,.np_companion-preview-container{height:100%;margin:0;padding:0;position:absolute;transition:opacity .3s ease-in-out;width:100%}.np_companion-preview-container{opacity:1;z-index:2}.np_companion-preview-container.np_companion-fade-out{opacity:0;pointer-events:none;transition:opacity .5s ease-out}.np_companion-live-container{opacity:0;z-index:1}.np_companion-live-container.np_companion-fade-in{opacity:1;z-index:3}"),vt(":root{--base-border-radius:10px;--base-gap:20px}*,:after,:before{-webkit-box-sizing:border-box;box-sizing:border-box}::-webkit-input-placeholder{color:hsla(0,0%,100%,.4)}::-moz-placeholder{color:hsla(0,0%,100%,.4)}:-ms-input-placeholder{color:hsla(0,0%,100%,.4)}:-moz-placeholder{color:hsla(0,0%,100%,.4)}a,input{outline:none}body,html{background-color:transparent;background:transparent;margin:0;padding:0;width:100%}.np_companion-hide{display:none!important}.np_companion-align-middle{align-items:center;display:flex;justify-content:center}.np_companion-align-between{align-items:center;display:flex;justify-content:space-between}.np_companion-align-end{align-items:center;display:flex;justify-content:flex-end}.np_companion-align-start{align-items:flex-start;display:flex;justify-content:flex-start}.np_companion__d-none{display:none!important}#np_companion-sdk-root.np_companion-container-fixed{height:500px;position:fixed;transition:all .3s ease-in-out;width:400px;z-index:9999}#np_companion-sdk-root.np_companion-container-fixed.np_companion-view-rectangle{height:400px;width:340px}#np_companion-sdk-root.np_companion-container-fixed.np_companion-view-silhouette{height:400px}#np_companion-sdk-root.np_companion-container-fixed.np_companion-view-round{height:360px;width:250px}#np_companion-sdk-root.np_companion-container-fixed.np_companion-view-round.np_companion_disclaimer-disabled{height:320px!important}#np_companion-sdk-root.np_companion-container-fixed.np_companion-bottom-right{bottom:0;right:0}#np_companion-sdk-root.np_companion-container-fixed.np_companion-bottom-left{bottom:0;left:0}#np_companion-sdk-root.np_companion-container-fixed.np_companion-bottom-center{bottom:0;left:50%;transform:translateX(-50%)}#np_companion-sdk-root.np_companion-container-fixed.np_companion-top-right{right:0;top:0}#np_companion-sdk-root.np_companion-container-fixed.np_companion-top-left{left:0;top:0}#np_companion-sdk-root.np_companion-container-fixed.np_companion-top-center{left:50%;top:0;transform:translateX(-50%)}#np_companion-sdk-root.np_companion-container-fixed.np_companion-center{left:50%;top:50%;transform:translate(-50%,-50%)}"),vt('.np_companion-avatar{height:100%;position:relative;width:100%}#np_companion-avatar-container{background:transparent;border-radius:var(--base-border-radius);height:100%;overflow:hidden;position:absolute;width:100%}#np_companion-avatar-container:not(.np_companion-view-silhouette){box-shadow:0 0 #0000,0 0 #0000,0 0 #0000,0 0 #0000,0 10px 15px -3px color-mix(in oklab,#00000080 100%,transparent),0 4px 6px -4px color-mix(in oklab,#00000080 100%,transparent)}.np_companion-avatar.np_companion-bg-transparent #np_companion-avatar-container.np_companion-view-silhouette{filter:drop-shadow(0 10px 15px rgba(0,0,0,.5)) drop-shadow(0 4px 6px rgba(0,0,0,.5))}.np_companion-container-fixed #np_companion-avatar-container.np_companion-view-round{border-radius:50%;height:212px;left:50%;transform:translate(-50%,12%);width:212px}.np_companion-container-fixed #np_companion-avatar-container.np_companion-view-rectangle,.np_companion-container-fixed #np_companion-avatar-container.np_companion-view-silhouette{left:50%;transform:translateX(-50%)}.np_companion-avatar-video{height:100%;inset:0;object-fit:cover;pointer-events:none;position:absolute;transition:opacity .3s ease-in-out;width:100%;z-index:10}.np_companion-avatar-video.no-opacity{opacity:0}.np_companion-avatar-canvas{background:transparent;height:100%;object-fit:cover;position:relative;width:100%;z-index:1}.np_companion-container-fixed #np_companion-avatar-container.np_companion-loader-pulse:after{animation:pulse 1.5s ease-in-out infinite;background-color:var(--np-loader-bg-color);border-radius:var(--base-border-radius);content:"";display:block;height:100%;left:0;opacity:.6;overflow:hidden;position:absolute;top:0;width:100%}.np_companion-avatar.np_companion-bg-transparent #np_companion-avatar-container:after{display:none}.np_companion-avatar:has(#np_companion-avatar-container.np_companion-view-round):after{display:none}#np_companion-avatar-container.np_companion-loader-pulse.loader-container.np_companion-view-round:after{animation:pulse 1.5s ease-in-out infinite;background-color:var(--np-loader-bg-color);border-radius:50%;content:"";display:block;height:100%;left:0;opacity:.6;overflow:hidden;position:absolute;top:0;width:100%}.np_companion-avatar.np_companion-bg-transparent #np_companion-avatar-container.np_companion-view-round:after{display:none}@keyframes pulse{0%,to{opacity:.5}50%{opacity:.2}}.np_companion-disclaimer-text{-webkit-box-orient:vertical;-webkit-line-clamp:2;line-clamp:2;color:#fff;font-size:10px;line-height:12px;margin:auto auto 16px;max-width:940px;opacity:.7;overflow:hidden;padding:0 16px;text-align:center;z-index:12}.np_companion-disclaimer-text a{color:#fff}.np_companion-disclaimer-text a:hover{color:#fff;text-decoration:underline}.np_companion-disclaimer-text a:focus,.np_companion-disclaimer-text a:visited{color:#fff}.np_companion-action-btn-container-wrapper{pointer-events:auto;width:100%}.np_companion-avatar-control-container{backdrop-filter:blur(19px);background:none;background-color:rgba(52,51,51,.6);border-radius:16px;bottom:0;box-shadow:0 4px 4px 0 rgba(0,0,0,.25),2px 2px 8px 0 rgba(0,0,0,.12);left:50%;max-width:90%;min-width:210px;opacity:1;position:absolute;transform:translateX(-50%);transition:opacity .4s cubic-bezier(.4,0,.2,1);z-index:99}.np_companion-avatar-control-container.np_companion-action-btn-container-collapse{opacity:0}.np_companion-avatar-control-container:not(.np_companion-avatar-control-view-round){bottom:16px}.np_companion-avatar:not(.np_companion-bg-transparent) .np_companion-loader-spinner:not(.np_companion-view-silhouette){backdrop-filter:blur(19px);background-color:color-mix(in oklab,var(--np-loader-bg-color) 100%,transparent)!important;filter:none!important;height:100%;width:100%}.np_companion-loader-spinner .loader-container{left:50%;position:absolute;top:50%;transform:translate(-50%,-50%)}.np_companion-loader-spinner .loader-container .loader{--_m:conic-gradient(#0000 10%,#000),linear-gradient(#000 0 0) content-box;animation:l3 1s linear infinite;aspect-ratio:1;background:var(--np-loader-color);border-radius:50%;-webkit-mask:var(--_m);mask:var(--_m);-webkit-mask-composite:source-out;mask-composite:subtract;padding:4px;width:24px}@keyframes l3{to{transform:rotate(1turn)}}.np_companion-loader-spinner.np_companion-view-round .loader-container .loader{padding:4px;width:212px}.np_companion-bg-transparent .np_companion-loader-spinner .loader-container{display:none}'),vt(".np_companion-controls-container{align-items:center;background:hsla(0,0%,100%,.3);border:.5px solid #fff;border-radius:12px;bottom:20px;box-shadow:0 1px 1px rgba(0,0,0,.267),0 2px 5px rgba(0,0,0,.267),0 3px 8px rgba(0,0,0,.267);display:flex;gap:8px;left:50%;max-width:360px;pointer-events:auto;position:absolute;transform:translateX(-50%);transform-origin:bottom center;transition:width .3s ease-in-out;-webkit-user-select:none;-moz-user-select:none;user-select:none;width:auto;z-index:99}.np_companion-controls-container.collapsed{gap:0}.np_companion-time-running{color:#fff}.np_companion-controls-time-action-btn-container{align-items:center;background:hsla(0,0%,100%,.1);border-radius:8px;display:flex;filter:grayscale(1);flex-shrink:0;gap:8px;height:32px;padding-left:8px;padding-right:8px;transition:filter .3s ease}.np_companion-controls-mic-control,.np_companion-controls-stop-control{cursor:pointer;display:flex;margin:0 5px;overflow:hidden;transition:opacity .3s ease-in-out,width .3s ease-in-out;width:47px}.np_companion-controls-mic-control.visible,.np_companion-controls-stop-control.visible{opacity:1}.np_companion-controls-mic-control.visible{width:1em}.np_companion-controls-stop-control.visible{width:1.5em}.np_companion-controls-mic-control.hidden,.np_companion-controls-stop-control.hidden{margin:0;opacity:0;padding:0;pointer-events:none;width:0}.np_companion-controls-mic-control:hover svg path{fill:red}.np_companion-controls-stop-control{display:flex;margin:0 5px 0 0}.np_companion-controls-stop-control:hover svg .stop-circle{fill:red}.np_companion-controls-stop-control:hover svg .stop-square{fill:#fff}.np_companion-mic-dropdown{background:#2b2c32;border-radius:4px;border-radius:6px;bottom:35px;box-shadow:0 10px 15px -3px rgba(0,0,0,.2),0 4px 6px -4px rgba(0,0,0,.2),0 0 0 1px #46464d;color:#fff;font-size:14px;list-style-type:none;margin:0;max-height:200px;min-width:300px;overflow-y:auto;overflow:auto;padding:5px;pointer-events:auto;position:absolute;width:auto;z-index:1000}.np_companion-mic-dropdown li{cursor:pointer;padding:8px 12px}.np_companion-mic-dropdown li:hover{background-color:#000}.np_companion-action-btn-container-container{background:transparent;border-radius:80px;gap:8px;padding:16px 16px 12px;transition:all .3s ease-in-out}.np_companion-action-btn-container-container.np_companion_disclaimer-disabled{padding-bottom:16px}.np_companion-action-btn-container-container .np_companion-chat-question-bar-container{border-radius:16px;gap:8px}.np_companion-action-btn-container-container .np_companion-action-btn-container-left{transition:all .3s ease-in-out;width:40px}.np_companion-action-btn-container-container .np_companion-action-btn-container-icon{border-radius:80px;cursor:pointer;height:40px;transition:all .3s ease-in-out;width:40px}.np_companion-dark-grey-bg{background:linear-gradient(0deg,#5e5e5e14 0 100%),#ffffff0f}.np_companion-grey-bg{background:linear-gradient(0deg,rgba(94,94,94,.07),rgba(94,94,94,.07)),hsla(0,0%,100%,.04)}.np_companion-action-btn-container-container .np_companion-action-btn-container-icon svg{height:auto;width:22px}.np_companion-action-btn-container-container .np_companion-action-btn-container-icon.muted svg.np_companion-mic-muted,.np_companion-action-btn-container-container .np_companion-action-btn-container-icon:not(.muted) svg.np_companion-mic-unmuted{display:flex}.np_companion-action-btn-container-container .np_companion-action-btn-container-middle .np_companion-action-btn-container-wave{display:flex;min-width:160px}.np_companion-action-btn-container-container .np_companion-action-btn-container-middle .np_companion-action-btn-container-wave canvas{height:40px;width:100%}.np_companion-action-btn-container-container .np_companion-action-btn-container-right{gap:8px;transition:all .3s ease-in-out}.np_companion-action-btn-container-container .np_companion-action-btn-container-left .np_companion-action-btn-container-icon:hover,.np_companion-action-btn-container-container .np_companion-action-btn-container-right .np_companion-action-btn-container-icon.active,.np_companion-action-btn-container-container .np_companion-action-btn-container-right .np_companion-action-btn-container-icon:hover{background-color:#fff!important}.np_companion-action-btn-container-container .np_companion-action-btn-container-left .np_companion-action-btn-container-icon:not(.np_companion-persist-fill-color):hover svg path{fill:#000}.np_companion-action-btn-container-container .np_companion-action-btn-container-right .np_companion-action-btn-container-icon.np_companion-action-btn-container-call-end svg{height:auto;width:16px}.np_companion-action-btn-container-container .np_companion-action-btn-container-right .np_companion-action-btn-container-icon:not(.np_companion-persist-fill-color).np_companion-action-btn-container-call-end:hover svg path{stroke:#000}.np_companion-action-btn-container-container .np_companion-action-btn-container-right .np_companion-action-btn-container-icon:not(.np_companion-persist-fill-color).active svg path,.np_companion-action-btn-container-container .np_companion-action-btn-container-right .np_companion-action-btn-container-icon:not(.np_companion-persist-fill-color).np_companion-action-btn-container-toggle:hover svg path,.np_companion-action-btn-container-container .np_companion-action-btn-container-right .np_companion-action-btn-container-icon:not(.np_companion-persist-fill-color):hover svg path{fill:#000}.np_companion-mobile-mode{bottom:15px;scale:.7}.np_companion-mobile-mode .np_companion-action-btn-container-container .np_companion-action-btn-container-middle{display:none}.np_companion-mobile-mode .np_companion-action-btn-container-left{opacity:1;width:40px}.np_companion-mobile-mode .np_companion-action-btn-container-right{opacity:1}"),vt('.tooltip{word-wrap:break-word;display:block;font-family:-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Helvetica Neue,Arial,sans-serif;font-size:.875rem;font-style:normal;font-weight:400;letter-spacing:normal;line-break:auto;line-height:1.5;margin:0;opacity:0;position:absolute;text-align:left;text-decoration:none;text-shadow:none;text-transform:none;white-space:normal;word-break:normal;word-spacing:normal;z-index:1080}.tooltip.show{opacity:.9}.tooltip .tooltip-arrow{display:block;height:.4rem;position:absolute;width:.8rem}.tooltip .tooltip-arrow:before{border-color:transparent;border-style:solid;content:"";position:absolute}.bs-tooltip-auto[data-popper-placement^=top],.bs-tooltip-top{padding:0}.bs-tooltip-auto[data-popper-placement^=top] .tooltip-arrow,.bs-tooltip-top .tooltip-arrow{bottom:-.4rem;left:50%;transform:translateX(-50%)}.bs-tooltip-auto[data-popper-placement^=top] .tooltip-arrow:before,.bs-tooltip-top .tooltip-arrow:before{border-top-color:#000;border-width:.4rem .4rem 0;top:0}.bs-tooltip-auto[data-popper-placement^=right],.bs-tooltip-end{padding:0}.bs-tooltip-auto[data-popper-placement^=right] .tooltip-arrow,.bs-tooltip-end .tooltip-arrow{height:.8rem;left:-.4rem;top:50%;transform:translateY(-50%);width:.4rem}.bs-tooltip-auto[data-popper-placement^=right] .tooltip-arrow:before,.bs-tooltip-end .tooltip-arrow:before{border-right-color:#000;border-width:.4rem .4rem .4rem 0;right:0}.bs-tooltip-auto[data-popper-placement^=bottom],.bs-tooltip-bottom{padding:0}.bs-tooltip-auto[data-popper-placement^=bottom] .tooltip-arrow,.bs-tooltip-bottom .tooltip-arrow{left:50%;top:-.4rem;transform:translateX(-50%)}.bs-tooltip-auto[data-popper-placement^=bottom] .tooltip-arrow:before,.bs-tooltip-bottom .tooltip-arrow:before{border-bottom-color:#000;border-width:0 .4rem .4rem;bottom:0}.bs-tooltip-auto[data-popper-placement^=left],.bs-tooltip-start{padding:0}.bs-tooltip-auto[data-popper-placement^=left] .tooltip-arrow,.bs-tooltip-start .tooltip-arrow{height:.8rem;right:-.4rem;top:50%;transform:translateY(-50%);width:.4rem}.bs-tooltip-auto[data-popper-placement^=left] .tooltip-arrow:before,.bs-tooltip-start .tooltip-arrow:before{border-left-color:#000;border-width:.4rem 0 .4rem .4rem;left:0}.tooltip-inner{background-color:#000;border-radius:.25rem;color:#fff;max-width:200px;padding:.25rem .5rem;text-align:center}.styled-tooltip{z-index:99999}.styled-tooltip .tooltip-inner{background-color:#fff;border-radius:.375rem;box-shadow:0 .5rem 1rem rgba(0,0,0,.15);color:#3f4254;display:block;font-size:14px;max-width:300px;padding:10px 14px}.styled-tooltip.bs-tooltip-auto[data-popper-placement^=top] .tooltip-arrow:before,.styled-tooltip.bs-tooltip-top .tooltip-arrow:before{border-top-color:#fff}.styled-tooltip.bs-tooltip-auto[data-popper-placement^=right] .tooltip-arrow:before,.styled-tooltip.bs-tooltip-end .tooltip-arrow:before{border-right-color:#fff}.styled-tooltip.bs-tooltip-auto[data-popper-placement^=bottom] .tooltip-arrow:before,.styled-tooltip.bs-tooltip-bottom .tooltip-arrow:before{border-bottom-color:#fff}.styled-tooltip.bs-tooltip-auto[data-popper-placement^=left] .tooltip-arrow:before,.styled-tooltip.bs-tooltip-start .tooltip-arrow:before{border-left-color:#fff}'),vt(".np_volume-control{align-items:center;display:inline-flex;flex-direction:column;gap:12px;position:relative;z-index:1000}.np_volume-slider-container{background:#6565652e;border-radius:8px;bottom:52px;opacity:0;padding:8px;pointer-events:none;position:absolute;transform:translateY(10px);transition:all .3s ease;visibility:hidden;z-index:1001}.np_volume-control .np_volume-slider-container.np_volume-slider-visible,.np_volume-slider-container:hover{opacity:1;pointer-events:all;transform:translateY(0);visibility:visible}.np_volume-slider-track{backdrop-filter:blur(10px);background:rgba(0,0,0,.4);border:1px solid hsla(0,0%,100%,.3);border-radius:4px;box-shadow:0 2px 8px rgba(0,0,0,.15);cursor:pointer;height:120px;position:relative;width:8px}.np_volume-slider-fill{background:linear-gradient(0deg,hsla(0,0%,100%,.9),hsla(0,0%,100%,.7));border-radius:4px;bottom:0;height:50%;left:0;pointer-events:none;position:absolute;right:0;transition:height .1s ease}.np_volume-slider-thumb{background:#fff;border-radius:50%;bottom:50%;box-shadow:0 2px 6px rgba(0,0,0,.3);cursor:grab;height:16px;left:50%;pointer-events:none;position:absolute;transform:translate(-50%,50%);transition:bottom .1s ease;width:16px}.np_volume-slider-thumb:active{cursor:grabbing;transform:translate(-50%,50%) scale(1.1)}.np_volume-slider-track:hover .np_volume-slider-thumb{transform:translate(-50%,50%) scale(1.15)}@media (max-width:768px){.np_volume-slider-track{height:100px}.np_volume-slider-container{bottom:70px}}"),vt('.np_companion-inactive-overlay{align-items:center;bottom:0;display:flex;justify-content:center;left:0;pointer-events:auto;position:absolute;right:0;top:0;z-index:9999}.np_companion-inactive-dialog{backdrop-filter:blur(19px);background:hsla(0,0%,50%,.3);background-blend-mode:luminosity;border-radius:16px;max-width:500px;overflow:hidden;padding:24px 16px;position:relative;text-align:center;width:100%}.np_companion-inactive-dialog:before{background:linear-gradient(180deg,hsla(0,0%,100%,.4),hsla(0,0%,100%,0),hsla(0,0%,100%,0),hsla(0,0%,100%,.1));border-radius:16px;content:"";inset:0;-webkit-mask:linear-gradient(#fff 0 0) content-box,linear-gradient(#fff 0 0);-webkit-mask-composite:destination-out;mask-composite:exclude;padding:1.473px;pointer-events:none;position:absolute}.np_companion-inactive-message{color:#fff;font-size:16px;line-height:1.5;margin-bottom:24px;margin-top:0}.np_companion-inactive-timer{display:flex;justify-content:center;margin:24px 0}.np_companion-timer-circle{align-items:center;display:flex;height:80px;justify-content:center;position:relative;width:80px}.np_companion-timer-circle svg{overflow:visible;transform:rotate(-90deg)}.np_companion-timer-circle path{transition:stroke-dasharray .3s ease}.np_companion-timer-number{color:#fff;font-size:24px;font-weight:500;position:absolute}.np_companion-inactive-buttons{display:flex;gap:12px;justify-content:center}.np_companion-inactive-buttons button{border:none;border-radius:8px;cursor:pointer;font-size:14px;font-weight:500;padding:12px 24px;transition:all .2s ease}.np_companion-end-button{background:hsla(0,0%,100%,.1);color:#fff}.np_companion-end-button:hover{background:hsla(0,0%,100%,.2)}.np_companion-continue-button{background:#3c19cd;color:#fff}.np_companion-continue-button:hover{background:#2f13a0}'),function(e){e.LOCAL_TIMEOUT="local_timeout",e.SERVER_WARNING="server_warning"}(wt||(wt={}));class It{constructor(e,t={}){Object.defineProperty(this,"overlayController",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"currentTrigger",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"isVisible",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"mountElement",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"callbacks",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.mountElement=e,this.callbacks=t}show(e){this.isVisible?at.warn("Inactive overlay already visible, ignoring show request"):(at.info(`Showing inactive overlay (trigger: ${e.type})`),this.currentTrigger=e,this.isVisible=!0,this.overlayController=function(e,t){const n={duration:t.duration??30,isInteractionNeeded:t.isInteractionNeeded??!1,message:t.message??"It looks like you've been inactive for a while. Would you like to continue this conversation?",onContinue:t.onContinue,onEnd:t.onEnd},o=document.createElement("div");o.className="np_companion-inactive-overlay";const i=document.createElement("div");i.className="np_companion-inactive-dialog";const a=document.createElement("p");a.className="np_companion-inactive-message",a.textContent=n.message;const r=document.createElement("div");r.className="np_companion-inactive-timer";const s=document.createElement("div");s.className="np_companion-timer-circle";const c=document.createElementNS("http://www.w3.org/2000/svg","svg");c.setAttribute("viewBox","0 0 36 36");const l=document.createElementNS("http://www.w3.org/2000/svg","path");l.setAttribute("d","M18 2.0845 a 15.9155 15.9155 0 0 1 0 31.831 a 15.9155 15.9155 0 0 1 0 -31.831"),l.setAttribute("fill","none"),l.setAttribute("stroke","rgba(255, 255, 255, 0.2)"),l.setAttribute("stroke-width","2");const d=document.createElementNS("http://www.w3.org/2000/svg","path");d.setAttribute("d","M18 2.0845 a 15.9155 15.9155 0 0 1 0 31.831 a 15.9155 15.9155 0 0 1 0 -31.831"),d.setAttribute("fill","none"),d.setAttribute("stroke","#fff"),d.setAttribute("stroke-width","2");const p=document.createElement("span");p.className="np_companion-timer-number",s.appendChild(c),c.appendChild(l),c.appendChild(d),s.appendChild(p),r.appendChild(s);const u=document.createElement("div");u.className="np_companion-inactive-buttons";const m=document.createElement("button");m.className="np_companion-end-button np_companion__d-none",m.textContent="End Conversation";let h=null;const f=e=>{e&&!h?(h=document.createElement("button"),h.className="np_companion-continue-button",h.textContent="Continue Talking",u.appendChild(h),h.addEventListener("click",n.onContinue)):!e&&h&&(h.removeEventListener("click",n.onContinue),h.parentNode&&h.parentNode.removeChild(h),h=null)};u.appendChild(m),f(n.isInteractionNeeded),i.appendChild(a),i.appendChild(r),i.appendChild(u),o.appendChild(i),e.appendChild(o);let b=Math.max(0,Math.floor(n.duration)),g=null;const v=()=>{p.textContent=String(b),d.setAttribute("stroke-dasharray",(n.duration>0?b/n.duration*100:0)+", 100")},_=()=>{if(b<=0)return w(),void n.onEnd();b-=1,v()},y=()=>{w(),v(),g=window.setInterval(_,1e3)},w=()=>{null!=g&&(window.clearInterval(g),g=null)};return m.addEventListener("click",()=>{w(),n.onEnd()}),y(),{update:e=>{if(void 0!==e.message&&(n.message=e.message,a.textContent=n.message),void 0!==e.isInteractionNeeded&&(n.isInteractionNeeded=!!e.isInteractionNeeded,f(n.isInteractionNeeded)),void 0!==e.duration){const t=Math.max(0,Math.floor(e.duration));n.duration=t,b=t,y()}e.onContinue&&(h&&(h.removeEventListener("click",n.onContinue),h.addEventListener("click",e.onContinue)),n.onContinue=e.onContinue),e.onEnd&&(n.onEnd=e.onEnd)},destroy:()=>{w(),m.removeEventListener("click",n.onEnd),h&&h.removeEventListener("click",n.onContinue),o.parentNode&&o.parentNode.removeChild(o)}}}(this.mountElement,{duration:e.duration,message:e.message,isInteractionNeeded:e.isInteractionNeeded,onContinue:()=>this.handleContinue(),onEnd:()=>this.handleEnd()}),this.callbacks.onShow?.(e))}hide(){this.isVisible&&(at.info("Hiding inactive overlay"),this.isVisible=!1,this.currentTrigger=null,this.overlayController&&(this.overlayController.destroy(),this.overlayController=null),this.callbacks.onHide?.())}isShowing(){return this.isVisible}getCurrentTrigger(){return this.currentTrigger}handleContinue(){at.info("User clicked continue on inactive overlay"),this.hide(),this.callbacks.onContinue?.()}handleEnd(){at.info("Inactive overlay countdown ended"),this.hide(),this.callbacks.onEnd?.()}destroy(){this.hide()}}!function(e){e.TALK_STATE_CHANGED="talk_state_changed",e.MESSAGE_RECEIVED="message_received",e.TRANSCRIPT="transcript",e.AUDIO_TRANSCRIPT_DELTA="response.audio_transcript.delta",e.AUDIO_TRANSCRIPT_DONE="response.audio_transcript.done",e.RESPONSE_DONE="response.done"}(Ct||(Ct={})),function(e){e.STARTED="started",e.ENDED="ended",e.CANCELED="canceled"}(Et||(Et={})),function(e){e.DELTA="delta",e.COMPLETED="completed"}(St||(St={})),function(e){e.USER="user",e.ASSISTANT="assistant"}(xt||(xt={})),function(e){e.SET_REMOTE_DESCRIPTION="set_remote_description",e.SET_LOCAL_DESCRIPTION="set_local_description",e.ADD_ICE_CANDIDATE="add_ice_candidate",e.ERROR="error"}(kt||(kt={})),function(e){e.SEND_QUESTION="send_question",e.CANCEL="cancel"}(Tt||(Tt={}));const Nt={iceServers:[{urls:"stun:stun1.ciscape.com:3478"},{urls:"turn:stun1.ciscape.com:3478",username:"tcuser",credential:"dw4k_BR2f-Y4A-@aT7ip@Qzs"},{urls:"stun:129.146.43.226:3478"},{urls:"stun:stun.l.google.com:19302"},{urls:"stun:stun1.l.google.com:19302"},{urls:"turn:129.146.43.226:3478",username:"teamtime_turn",credential:"teamtime"}]};function Ot(e,t){if(t)for(const n in t)try{const o=t[n];"string"!=typeof o&&"number"!=typeof o||(e.style[n]=o)}catch{at.warn(`Failed to apply style for key "${n}: ${t[n]}".`)}}function At(e,t,n){const o=[];return o.push("np_companion-align-middle"),e&&(o.push("np_companion-container-fixed"),o.push(`np_companion-${e}`),t&&o.push(`np_companion-view-${t}`)),n&&o.push(n),o.join(" ")}class Rt{constructor(){Object.defineProperty(this,"version",{enumerable:!0,configurable:!0,writable:!0,value:"1.0.0-alpha.12"}),Object.defineProperty(this,"mountTarget",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"rootEl",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"embed",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"webrtcController",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"config",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"isInitialized",{enumerable:!0,configurable:!0,writable:!0,value:!1})}static getInstance(){return Rt.instance||(Rt.instance=new Rt),Rt.instance}renderApp(){this.mountTarget&&this.config&&(this.rootEl||(this.rootEl=document.createElement("div"),this.rootEl.id="np_companion-sdk-root",this.mountTarget.appendChild(this.rootEl)),this.rootEl.className=At(this.config.position,this.config.avatarStyle?.view,this.config.className),Ot(this.rootEl,this.config.style),this.embed?this.embed.update({avatarStyle:this.config.avatarStyle,features:ot.getState().app.features,onData:this.config.onData,onAvatarReady:this.config.onAvatarReady,onInactivityStatusChange:this.config.onInactivityStatusChange,onDestroy:()=>this.destroyInstance("ui_end"),onError:this.config.onError}):this.embed=function(e,t={}){const n=ct.createDiv("np_companion-live-container np_companion-fade-in");e.appendChild(n);const o=function(e,t={}){const n=ct.createDiv("np_companion-avatar"),o=ct.createDiv(`np_companion-avatar-container np_companion-loader-${t.features?.showSDKLoader?.type??"spinner"}`);o.id="np_companion-avatar-container",t.avatarStyle?.view&&o.classList.add(`np_companion-view-${t.avatarStyle.view}`);const i=ct.createDiv("loader-container"),a=ct.createDiv("loader");i.appendChild(a);const r=ct.createVideo({className:"np_companion-avatar-video",autoplay:!0,muted:!0,playsInline:!0}),s=ct.createAudio({className:"np_companion-avatar-audio",autoplay:!0}),c=ct.createCanvas({className:"np_companion-avatar-canvas",styles:{width:"100%",height:"100%",objectFit:"cover",position:"relative",zIndex:"1"}});t.features?.backgroundRemoval?.enabled&&"silhouette"===t.avatarStyle?.view?r.classList.add("np_companion__d-none"):c.classList.add("np_companion__d-none"),o.appendChild(i),o.appendChild(r),o.appendChild(s),o.appendChild(c);const l=ct.createDiv(`${st.wrapper} np_companion-action-btn-container-view-${t.avatarStyle?.view}`),d=ct.createDiv(`np_companion-disclaimer-text np_companion-disclaimer-view-${t.avatarStyle?.view}`);d.style.display="none";const p=ct.createDiv(`np_companion-avatar-control-container np_companion-avatar-control-view-${t.avatarStyle?.view}`);p.appendChild(l),p.appendChild(d),n.appendChild(o),n.appendChild(p),e.appendChild(n);let u=null,m=(t.features?.backgroundRemoval?.enabled&&"silhouette"===t.avatarStyle?.view)??!1,h=null,f=null,b=!1,g=!1,v=!1,_=!0,y=null,w=null,C=null;const E=new It(n,{onContinue:()=>{D(),L()},onEnd:()=>{}});let S=null;const x=()=>{_||(_=!0,p.className=T(),null!=y&&window.clearTimeout(y))},k=()=>{null!=y&&window.clearTimeout(y),y=window.setTimeout(()=>{_=!1,p.className=T()},5e3)};function T(){return rt(`np_companion-avatar-control-container np_companion-avatar-control-view-${t.avatarStyle?.view}`,{[st.collapse]:!_})}function I(e){if(!v)return;const n=t.avatarStyle?.borderWidth??("silhouette"!==t.avatarStyle?.view?"4px":void 0);n&&(o.style.borderWidth=n);const i=("silhouette"!==t.avatarStyle?.view?e?"#ec3e41":t.avatarStyle?.borderColor??"#C0C0C0":void 0)??t.avatarStyle?.borderColor;i&&(o.style.borderColor=i);const a=t.avatarStyle?.borderStyle??("silhouette"!==t.avatarStyle?.view?"solid":void 0);a&&(o.style.borderStyle=a)}function N(e){"round"===t.avatarStyle?.view&&(o.style.transform=`translate(-50%, ${e??352-p.offsetHeight-212-12+"px"})`)}function O(){const e=t.features?.disclaimer?.enabled??!1;d.style.display=e&&v?"-webkit-box":"none",w?.update({features:{disclaimer:{enabled:e}}});const n=t.features?.disclaimer?.text??"This is an AI avatar. Check important info.";t.features?.disclaimer?.color&&(d.style.color=t.features?.disclaimer?.color),d.textContent=n,v&&N(e?void 0:"8%")}function A(){v||!t.features?.showSDKLoader?.enabled?n.classList.add("np_companion-bg-transparent"):n.classList.remove("np_companion-bg-transparent")}function R(){t.features?.showSDKLoader?.bgColor&&n.style.setProperty("--np-loader-bg-color",t.features.showSDKLoader.bgColor),t.features?.showSDKLoader?.color&&n.style.setProperty("--np-loader-color",t.features.showSDKLoader.color)}function D(){C&&(at.timer("Resetting inactive timeout due to activity"),clearTimeout(C),C=null,ot.dispatch(Ue(!1)),t.onInactivityStatusChange?.(!1))}function L(){const e=t.features?.inactiveTimeout;e?.enabled?(D(),C=setTimeout(()=>{at.timer(`Inactive timeout of ${e?.duration}ms reached, showing inactive overlay`),ot.dispatch(Ue(!0)),t.onInactivityStatusChange?.(!0),u&&(u.getAudioTracks().forEach(e=>e.enabled=!1),w?.update({isMuted:!0}),I(!0)),E.isShowing()||E.show({type:wt.LOCAL_TIMEOUT,duration:Math.min(e.countdown??30,60),message:void 0,isInteractionNeeded:!0})},e.duration)):(D(),E.isShowing()&&E.hide())}function P(){if(!w&&v){const e=!1;w=function(e,t){let n={...t},o=null,i=null,a=[],r=!1;const s=document.createElement("div");s.className=E();const c=yt("div",st.container),l=yt("div",rt(st.questionBar,st.alignBetween)),d=yt("div",st.left),p=yt("div",st.iconButtonWithState(n.isMuted));p.appendChild(n.isMuted?pt.micMuted():pt.micUnmuted()),n.toggleMute&&p.addEventListener("click",()=>n.toggleMute?.());const u=yt("div",st.middle),m=yt("div",st.wave);S();const h=document.createElement("canvas");h.width=160,h.height=40,h.className=st.canvas,m.appendChild(h);const f=yt("div",rt(st.right,st.alignBetween)),b=yt("div",rt(st.iconButton(),st.stop)),g=function(e,t={}){let n={initialVolume:50,...t},o=n.initialVolume??50,i=!1,a=!1;const r=document.createElement("div");r.className="np_volume-control";const s=document.createElement("div");s.className="np_volume-slider-container";const c=document.createElement("div");c.className="np_volume-slider-track";const l=document.createElement("div");l.className="np_volume-slider-fill";const d=document.createElement("div");d.className="np_volume-slider-thumb",c.appendChild(l),c.appendChild(d),s.appendChild(c);const p=document.createElement("div");function u(){let e;p.innerHTML="",e=i||0===o?pt.volumeMuted():pt.volumeHigh(o||100),p.appendChild(e)}function m(){const e=o;l.style.height=`${e}%`,d.style.bottom=`${e}%`}function h(){a=!a,a?s.classList.add("np_volume-slider-visible"):s.classList.remove("np_volume-slider-visible")}function f(e){const t=c.getBoundingClientRect(),a=Math.max(0,Math.min(100,(t.bottom-e)/t.height*100));o=a,m(),i=0===o,i?p.classList.add("np_volume-muted"):p.classList.remove("np_volume-muted"),u(),n.onChange?.(o)}p.className=st.iconButton(),p.setAttribute("aria-label","Volume control"),u(),r.appendChild(s),r.appendChild(p),e.appendChild(r),p.addEventListener("click",e=>{e.stopPropagation(),i=!i,i?(n.initialVolume=o,o=0,m(),p.classList.add("np_volume-muted")):(o=n.initialVolume||50,m(),p.classList.remove("np_volume-muted")),u(),n.onMuteToggle?.(i)}),r.addEventListener("mouseenter",e=>{e.stopPropagation(),a||h()}),r.addEventListener("mouseleave",e=>{setTimeout(()=>{e.stopPropagation(),a&&h()},300)});let b=!1;return c.addEventListener("mousedown",e=>{b=!0,f(e.clientY),e.preventDefault()}),document.addEventListener("mousemove",e=>{b&&f(e.clientY)}),document.addEventListener("mouseup",()=>{b=!1}),d.addEventListener("mousedown",e=>{b=!0,e.preventDefault()}),c.addEventListener("touchstart",e=>{b=!0,f(e.touches[0].clientY),e.preventDefault()}),document.addEventListener("touchmove",e=>{b&&e.touches.length>0&&f(e.touches[0].clientY)}),document.addEventListener("touchend",()=>{b=!1}),document.addEventListener("click",e=>{a&&!r.contains(e.target)&&h()}),m(),{setVolume(e){o=Math.max(0,Math.min(100,e)),m(),u(),n.onChange?.(o)},getVolume:()=>o,toggleMute(){i=!i,i?p.classList.add("np_volume-muted"):p.classList.remove("np_volume-muted"),n.onMuteToggle?.(i)},isMuted:()=>i,update(e){n={...n,...e}},destroy(){r.remove()}}}(b,{initialVolume:50,onChange:e=>{n.onVolumeChange?.(e)},onMuteToggle:e=>{n.onVolumeChange?.(e?0:g.getVolume())}});g.setVolume(70);const v=yt("div",st.iconButtonEnd());v.appendChild(pt.end()),n.handleEnd&&v.addEventListener("click",()=>n.handleEnd?.()),d.appendChild(p),u.appendChild(m),f.appendChild(b),f.appendChild(v),l.appendChild(d),l.appendChild(f),c.appendChild(l),s.appendChild(c),e.appendChild(s);let _=null,y=null,w=null;function C(){if(!n.userMicrophoneStream)return;const e=new(window.AudioContext||window.webkitAudioContext);o=e.createAnalyser(),e.createMediaStreamSource(n.userMicrophoneStream).connect(o),function(e){if(!o)return;const t=h.getContext("2d");if(!t)return;o.fftSize=256;const n=new Uint8Array(o.frequencyBinCount),s=Math.floor(h.width/3);0===a.length&&(a=new Array(s).fill(0));let c=0;const l=()=>{if(t.clearRect(0,0,h.width,h.height),t.beginPath(),t.moveTo(0,h.height/2),t.lineTo(h.width,h.height/2),t.strokeStyle="#ffffff",t.stroke(),e)r=!1,a.fill(0),S();else{o.getByteFrequencyData(n);const e=6,i=3,s=n.reduce((e,t)=>e+t,0)/n.length/255*h.height*.8;a.shift(),a.push(s);let l=a.filter(t=>t>e).length>=i;l?c=30:c>0&&(c--,l=!0),r=l,S(),t.fillStyle="#ffffff";for(let e=0;e<a.length;e++){const n=3*e,o=a[e];t.fillRect(n,h.height/2-o/2,2,o),t.fillRect(n,h.height/2+o/2,2,-o)}}i=requestAnimationFrame(l)};l()}(!!n.isMuted)}function E(){return rt(st.alignMiddle,`np_companion-avatar-${n.avatarStyle?.view}`)}function S(){m.style.filter=!n.isMuted&&r?"brightness(0) saturate(100%) invert(48%) sepia(93%) saturate(1720%) hue-rotate(346deg) brightness(101%) contrast(103%)":"none",m.style.transition="filter 0.3s ease",m.style.height="40px"}function x(){_?.destroy(),_=_t(p,{content:n.isMuted?"Unmute":"Mute",placement:"top"}),y?.destroy(),y=null}function k(){for(p.className=st.iconButtonWithState(n.isMuted);p.firstChild;)p.removeChild(p.firstChild);p.appendChild(n.isMuted?pt.micMuted():pt.micUnmuted())}return _=_t(p,{content:n.isMuted?"Unmute":"Mute",placement:"top"}),w=_t(v,{content:"End Session",placement:"top"}),C(),{update(e){const t=n;n={...n,...e},s.className=E(),t.isMuted!==n.isMuted&&(k(),x()),t.isAvatarSpeaking!==n.isAvatarSpeaking&&(k(),x()),t.userMicrophoneStream===n.userMicrophoneStream&&t.selectedMicrophone===n.selectedMicrophone||(null!=i&&(cancelAnimationFrame(i),i=null),a=[],o=null,C()),S(),n.features?.disclaimer?.enabled?c.classList.remove("np_companion_disclaimer-disabled"):c.classList.add("np_companion_disclaimer-disabled")},destroy(){_?.destroy(),y?.destroy(),w?.destroy(),null!=i&&cancelAnimationFrame(i),s.parentNode&&s.parentNode.removeChild(s)}}}(l,{avatarStyle:t.avatarStyle,isMuted:e,isAvatarSpeaking:g,userMicrophoneStream:u,features:{waveform:{enabled:!1!==t.features?.waveform?.enabled}},onVolumeChange:e=>{s.volume=e/100},toggleMute:()=>{const t=!(ot.getState().avatar.muted??e);ot.dispatch($e(t)),u&&u.getAudioTracks().forEach(e=>e.enabled=!t),w?.update({isMuted:t}),I(t),D(),L()},onStopTalking:()=>{try{const e=(e=>e.avatar.dataChannel)(ot.getState());if(e&&"open"===e.readyState){const t={type:Tt.CANCEL};at.avatar("stopping avatar"),e.send(JSON.stringify(t))}else at.critical_warn("Stopping avatar: Data channel not open")}catch(e){at.critical_error("Avatar","Stop: failed to send interrupt",e)}D(),L()},handleEnd:()=>{t.onDestroy?.()}})}}n.addEventListener("mouseenter",x),n.addEventListener("mousemove",x),n.addEventListener("mouseleave",k);const M=()=>{if(b)return;const e=c.getContext("2d",{willReadFrequently:!0});if(!e||!r||r.readyState<2)S=requestAnimationFrame(M);else{if(c.width=r.videoWidth,c.height=r.videoHeight,e.drawImage(r,0,0,c.width,c.height),m){const n=e.getImageData(0,0,c.width,c.height),o=lt.process(n);e.putImageData(o,0,0),v||(t.onAvatarReady?.(!0),v=!0,I(),P(),A(),O(),L(),k())}S=requestAnimationFrame(M)}};O(),R(),A();const j={updateStreams:({videoStream:e,audioStream:n,userMicrophoneStream:o})=>{e&&e instanceof MediaStream?h!==e&&(at.avatar("New video stream received:",{active:e.active,tracks:e.getTracks().length,videoTracks:e.getVideoTracks().length,id:e.id}),h=e,r.srcObject=e,r.play().then(()=>{m||v||(t.onAvatarReady?.(!0),v=!0,I(),P(),A(),O(),L(),N(),k())}).catch(e=>{at.error("Failed to play video stream",e),t.onError?.(e)}),e.addEventListener("inactive",()=>{at.avatar("Video stream became inactive")}),e.getTracks().forEach(e=>{e.addEventListener("ended",()=>{at.avatar("Video track ended:",e.kind)})}),m&&!S&&(S=requestAnimationFrame(M))):(h=null,r.srcObject=null),void 0!==n&&(n&&n instanceof MediaStream?f!==n&&(f=n,s.srcObject=n,s.play().catch(e=>{at.error("Failed to play audio stream",e),t.onError?.(e)})):(f=null,s.srcObject=null)),void 0!==o&&(u=o??null,w?.update({userMicrophoneStream:u}))},updateWaveform:e=>{P(),w?.update(e)},updateFeatures:e=>{t.features={...t.features||{},...e||{}},m=(t.features?.backgroundRemoval?.enabled&&"silhouette"===t.avatarStyle?.view)??!1,m?(r.classList.add("np_companion__d-none"),c.classList.remove("np_companion__d-none")):(r.classList.remove("np_companion__d-none"),c.classList.add("np_companion__d-none")),w?.update({features:{waveform:{enabled:!1!==t.features?.waveform?.enabled}}}),O(),R(),A(),L()},update:e=>{const n=t.avatarStyle?.view;Object.assign(t,e),e.features&&j.updateFeatures(e.features),e.avatarStyle?.view&&e.avatarStyle.view!==n&&(n&&o.classList.remove(`np_companion-view-${n}`),o.classList.add(`np_companion-view-${e.avatarStyle.view}`),t.features&&j.updateFeatures(t.features))},setAvatarReady:e=>{e||(v=!1,t.onAvatarReady?.(!1))},handleMessage:e=>{switch("undefined"!=typeof window&&window.parent&&window.parent.postMessage({type:"avatar-data-channel-message",event:e},"*"),e.event){case"avatar_state_changed":break;case"talk_state_changed":g="ended"!==e.data?.state&&"canceled"!==e.data?.state,w?.update({isAvatarSpeaking:g});break;case"message_received":{const{message:t}=e.data||{};if("completed"===t?.action&&"string"==typeof t.content&&t.role){D(),L();const e=E.getCurrentTrigger();e&&!e.isInteractionNeeded&&E.hide()}break}case"avatar_connection_warning":t.showAvatarInactiveOverlay&&(E.show({type:wt.SERVER_WARNING,duration:e.data?.disconnect_after??30,message:"Avatar is disconnecting due to inactivity. Say something to keep it active.",isInteractionNeeded:!1}),u&&(u.getAudioTracks().forEach(e=>e.enabled=!0),w?.update({isMuted:!1}),I(!1)))}t.onData?t.onData(e):at.data("onData callback NOT called. Reason:",{onDataExists:!!t.onData,dataType:typeof e,dataIsNull:null===e})},destroy:e=>{b||(b=!0,n.removeEventListener("mousemove",x),n.removeEventListener("mouseenter",x),n.removeEventListener("mouseleave",k),null!=y&&window.clearTimeout(y),null!=S&&(cancelAnimationFrame(S),S=null),C&&(clearTimeout(C),C=null),w?.destroy(),w=null,E?.destroy(),n.parentNode&&n.parentNode.removeChild(n),v=!1,t.onAvatarReady?.(!1),e||t.onDestroy?.())}};return j}(n,{avatarStyle:t.avatarStyle,showAvatarInactiveOverlay:!0,onData:t.onData,onDestroy:t.onDestroy,onError:t.onError,onInactivityStatusChange:t.onInactivityStatusChange,onAvatarReady:t.onAvatarReady,features:t.features});return{update:e=>{o.update({avatarStyle:e.avatarStyle??t.avatarStyle,onData:e.onData??t.onData,onDestroy:e.onDestroy??t.onDestroy,onError:e.onError??t.onError,onInactivityStatusChange:e.onInactivityStatusChange??t.onInactivityStatusChange,onAvatarReady:e.onAvatarReady??t.onAvatarReady,features:e.features??t.features}),Object.assign(t,e)},updateStreams:e=>{o.updateStreams(e)},handleMessage:e=>{o.handleMessage(e)},destroy:()=>{o.destroy(!0),n.parentNode===e&&e.removeChild(n),t.onDestroy?.()}}}(this.rootEl,{avatarStyle:this.config.avatarStyle,features:ot.getState().app.features,onData:this.config.onData,onAvatarReady:this.config.onAvatarReady,onInactivityStatusChange:this.config.onInactivityStatusChange,onDestroy:()=>this.destroyInstance("ui_end"),onError:this.config.onError}),this.initializeWebRTC().catch(e=>{at.critical_error("Failed to establish WebRTC connection:",e),this.config?.onError?.(e)}))}async initializeWebRTC(){const e=ot.getState().avatar.connectionToken;if(e&&!this.webrtcController){at.connection("Connecting WebRTC..."),this.webrtcController=function(e={}){const{currentAudioDeviceId:t,onChatMessage:n,onConnectionSuccess:a,onConnectionError:r,onStreams:s,onDataChannel:c,maxReconnectAttempts:l=3,reconnectInterval:d=2e3}=e;let p=null,u=null,m=null,h=null,f=null,b=null,g=null,v="disconnected",_=0,y=null,w=null,C=!0,E=null;function S(e,t){e&&e.readyState===WebSocket.OPEN?e.send(JSON.stringify(t)):at.critical_warn("WebRTC",`WS send skipped; state=${e?.readyState}`)}function x(e){E=e,r?.(e)}function k(e){v=e,at.webrtc(`Connection status changed to: ${e}`)}function T(){!C||!w||_>=l?_>=l&&x(new o("WebSocket connection failed after max retry attempts",{maxAttempts:l,lastAttempt:_})):(_+=1,k("reconnecting"),at.webrtc(`Attempting to reconnect (${_}/${l})...`),y=setTimeout(async()=>{try{if(!w)return;await I(w.connection.signalingEndpoint,w.connection.id,!0),!p&&w&&await N(w.token)}catch(e){at.error("WebRTC","Reconnection attempt failed:",e),_<l&&T()}},d))}async function I(e,t,n=!1){const i=`${e.replace(/\/$/,"")}/ws/connections/${t}/signaling`;u&&u.readyState===WebSocket.OPEN&&u.close();const r=new WebSocket(i);return u=r,await new Promise((e,t)=>{r.onopen=()=>{at.connection(n?"WebSocket reconnected":"WebSocket connected"),k("connected"),_=0,y&&(clearTimeout(y),y=null),e()},r.onclose=e=>{at.connection("WebSocket closed:",e),u=null,k("disconnected"),!e.wasClean&&C&&T(),t(new o("WebSocket connection closed",{code:e.code,reason:e.reason,wasClean:e.wasClean}))},r.onerror=e=>{u=null,k("disconnected");const n=new o("WebSocket connection error",{error:e,timestamp:(new Date).toISOString()});x(n),t(n)}}),a?.(),ot.dispatch(Ke(void 0)),r}async function N(e){if(p&&"disconnected"!==v)at.warn("WebRTC","Connection already in progress, skipping...");else try{k("connecting"),E=null;const a=(e=>{try{const t=atob(e);return JSON.parse(t)}catch(e){return at.critical_error("decodeToBase64: Error decoding token",e),null}})(e);if(!a)throw new o("Failed to decode connection token",{token:e?"provided":"missing"});w={...a,token:e};const r=await I(a.connection.signalingEndpoint,a.connection.id),l=await async function(){at.webrtc("Create PeerConnection");const e=new RTCPeerConnection(Nt);return p=e,e.addEventListener("connectionstatechange",()=>{"failed"===e.connectionState?(x(new o("WebRTC connection failed")),T()):"connected"===e.connectionState&&(k("connected"),_=0,y&&(clearTimeout(y),y=null))}),function(e){g=e.addTransceiver("audio",{direction:"sendrecv"});const t=e.addTransceiver("video",{direction:"recvonly"});at.webrtc("Added transceivers",{videoTransceiver:t,audioTransceiver:g});const o=e.createDataChannel("chat",{ordered:!0});b=o,ot.dispatch(Be(o)),c?.(o),o.onopen=()=>{at.webrtc("Data channel opened")},o.onclose=()=>{at.webrtc("Data channel closed")},o.onerror=e=>{at.critical_error("WebRTC",e),x(new i("Data channel error",{error:e}))},o.onmessage=e=>{try{const t=JSON.parse(e.data);at.data("Data channel message received:",t),n?.(t)}catch{n?.({event:"message_received",data:{message:{content:e.data,action:"completed"}}})}}}(e),e.ontrack=e=>{const t=e.streams[0];at.webrtc(`${e.track.kind} stream received`,{streamId:t?.id,trackId:e.track.id,videoTracks:t?.getVideoTracks().length,audioTracks:t?.getAudioTracks().length}),"video"===e.track.kind?(h=t,f=t):"audio"===e.track.kind&&(f=t,h||(h=t)),s?.({videoStream:h,audioStream:f})},e}();await async function(){try{at.webrtc("Setting up user media");const e=await navigator.mediaDevices.getUserMedia({audio:!t||{deviceId:{exact:t}},video:!1});if(m=e,g&&e.getAudioTracks().length>0){const t=e.getAudioTracks()[0];await g.sender.replaceTrack(t)}s?.({userMicrophoneStream:e})}catch(e){at.critical_warn("WebRTC",e),x(new o("Failed to access user media",{error:e,deviceId:t}))}}(),await async function(e,t){e.addEventListener("icecandidate",e=>{const n=e.candidate;n&&(at.webrtc("send ICE candidate"),S(t,{type:"add_ice_candidate",data:{candidate:n}}))}),e.addEventListener("negotiationneeded",()=>{at.warn("negotiationneeded (waiting for server offer)")}),at.webrtc("createOffer → setLocalDescription → set_remote_description");const n=await e.createOffer();await e.setLocalDescription(n),S(t,{type:"set_remote_description",data:n})}(l,r),r.onmessage=e=>async function(e,t,n){try{const o=JSON.parse(n.data);switch(o.type){case"set_remote_description":at.webrtc("Setting remote description"),await e.setRemoteDescription(o.data),await e.setLocalDescription(),S(t,{type:"set_local_description",data:e.localDescription});break;case"add_ice_candidate":o.data?.candidate&&await e.addIceCandidate(o.data.candidate);break;case"error":at.critical_error("WebRTC",o.data?.error),x(new i(o.data?.error||"Server error",{serverMessage:o.data})),e.close(),t.close();break;default:at.webrtc("Unknown message type:",o.type)}}catch(e){at.critical_error("WebRTC",e),x(new i("Failed to process WebSocket message",{originalError:e,rawMessage:n.data}))}}(l,r,e)}catch(e){const t=e;throw at.critical_error("WebRTC",t),x(t),k("disconnected"),t}}function O(){C=!1,y&&(clearTimeout(y),y=null),_=0;try{if(b)try{b.close()}catch{}if(u)try{u.readyState!==WebSocket.OPEN&&u.readyState!==WebSocket.CONNECTING||u.close(1e3,"Connection closed by client")}catch{}if(p)try{p.getSenders().forEach(e=>{e.track&&e.track.stop()}),p.close()}catch{}if(m)try{m.getTracks().forEach(e=>e.stop())}catch{}}catch(e){at.critical_warn("WebRTC",e)}finally{b=null,u=null,p=null,m=null,g=null,h=null,f=null,w=null,k("disconnected"),ot.dispatch(Ge(void 0))}}return ot.dispatch(Ge(O)),{startWithToken:N,close:O,forceReconnect:async function(){if(w){O(),C=!0,_=0;try{await N(w.token)}catch(e){throw x(e),e}}else x(new o("No connection data available for reconnect"))},getConnectionStatus:function(){return v},getReconnectAttempts:function(){return _},getError:function(){return E},updateAudioDevice:async function(e){if(g&&g.sender.track)try{const t=await navigator.mediaDevices.getUserMedia({audio:{deviceId:{exact:e}},video:!1}),n=t.getAudioTracks()[0];await g.sender.replaceTrack(n),m&&m.getTracks().forEach(e=>e.stop()),m=t,s?.({userMicrophoneStream:t}),at.webrtc(`Audio device updated to: ${e}`)}catch(t){at.critical_warn("WebRTC","Failed to update audio device:",t),x(new o("Failed to update audio device",{error:t,deviceId:e}))}else at.warn("WebRTC","No audio transceiver available for device update")}}}({maxReconnectAttempts:3,reconnectInterval:2e3,onStreams:e=>{this.embed?.updateStreams(e)},onChatMessage:e=>{this.embed?.handleMessage(e)},onConnectionError:e=>{at.critical_error("WebRTC connection error:",e),this.config?.onError?.(e)}});try{at.connection("Initializing WebRTC connection with token:",`${e.substring(0,50)}...`),await this.webrtcController.startWithToken(e),at.connection("WebRTC initialization completed with token")}catch(e){throw at.critical_error("SDK","Failed to Initialize WebRTC:",e),this.webrtcController=null,e}}}destroyWebRTC(){if(this.webrtcController){at.info("SDK","Destroying WebRTC controller");try{this.webrtcController.close()}catch(e){at.critical_error("SDK","Error closing WebRTC controller:",e)}this.webrtcController=null}}destroyInstance(e,t){if(!e)return void at.critical_warn("SDK","destroyInstance ignored (no reason)");bt("sdk_destroyed",{reason:e}),t?.();const n=this.config?.onDestroy;if(tt(null),ot.dispatch(Ke(void 0)),ot.dispatch(Ge(void 0)),ot.dispatch($e(!1)),ot.dispatch(Xe()),ot.dispatch(Ye(void 0)),this.destroyWebRTC(),this.embed){try{this.embed.update({onDestroy:void 0}),this.embed.destroy()}catch(e){at.critical_error("Error during cleanup:",e)}this.embed=null}this.rootEl&&this.rootEl.parentNode&&this.rootEl.parentNode.removeChild(this.rootEl),this.rootEl=null,this.mountTarget=null,this.config=null,this.isInitialized=!1,n?.()}async init(e,o={}){try{if(this.isInitialized)throw new t("SDK is already initialized. Call destroy() first.",{code:a.ALREADY_INITIALIZED});o.analytics?.enabled&&(function(e){ft=new ht(e)}(o.analytics),bt("sdk_init_started",{version:this.version,config:{position:o.position,features:Object.keys(o.features||{})}})),function(e){if(!e||"string"!=typeof e||""===e.trim())throw new n("Invalid connection token: expected non-empty string",{providedToken:typeof e,code:a.INVALID_TOKEN})}(e);const i={avatarStyle:{view:"round"},position:r.BOTTOM_RIGHT,...o};this.config=i,ot.dispatch(Ke(e)),ot.dispatch($e(!1)),ot.dispatch(Ze(i.debug)),this.config.features&&Object.entries(this.config.features).forEach(([e,t])=>{const n=ut(e,t);ot.dispatch(Je({feature:e,config:n}))}),tt(e=>{try{this.embed&&this.embed.update({features:e})}catch(e){at.critical_error("Unable to update features",e)}this.config?.onFeaturesUpdate?.(e)});const s=function(e){if(!e)return document.body;if("string"==typeof e){const t=document.querySelector(e);return t instanceof HTMLElement?t:(at.warn(`mountContainer should be a valid CSS selector. Provided selector "${e}" is invalid or did not match any elements. Defaulting to document.body.`),document.body)}return e instanceof HTMLElement?e:document.body}(this.config.mountContainer??void 0);return this.mountTarget=s,this.isInitialized=!0,this.renderApp(),this.config.onReady?.(),bt("sdk_init_completed",{version:this.version,initTime:Date.now()}),this.createInstanceMethods()}catch(t){const n=s.handle(t,{method:"init",tokenProvided:!!e,config:o});throw o.onError?.(n),n}}createInstanceMethods(){return{showAvatar:()=>{const e=document.getElementById("np_companion-avatar-container");e&&(e.style.display="block",gt("show","avatar_widget"))},hideAvatar:()=>{const e=document.getElementById("np_companion-avatar-container");e&&(e.style.display="none",gt("hide","avatar_widget"))},avatarIsVisible:()=>{const e=document.getElementById("np_companion-avatar-container");return!!e&&"none"!==e.style.display},destroy:()=>{const{closeConnectionHandler:e}=ot.getState().avatar;this.destroyInstance("api",e)},updateStyles:e=>{this.config&&(this.config.style={...this.config.style??{},...e??{}},this.rootEl&&Ot(this.rootEl,this.config.style))},setPosition:e=>{if(this.config&&(this.config.position=e,ot.dispatch?.(Ye(e)),this.rootEl)){const t=At(e,this.config.avatarStyle?.view,this.config.className);this.rootEl.className=t}},clearPosition:()=>{this.config&&(ot.dispatch?.(Ye(void 0)),this.config.position=void 0,this.rootEl&&(this.rootEl.className=At(void 0,this.config.avatarStyle?.view,this.config.className)))},enableFeature:e=>{ot.dispatch?.(Je({feature:e,config:{enabled:!0}})),"disclaimer"===e&&this.rootEl&&this.rootEl.classList.remove("np_companion_disclaimer-disabled")},disableFeature:e=>{ot.dispatch?.(Je({feature:e,config:{enabled:!1}})),"disclaimer"===e&&this.rootEl&&this.rootEl.classList.add("np_companion_disclaimer-disabled")},updateFeatureConfig:(e,t)=>{const n=ut(e,t);ot.dispatch?.(Je({feature:e,config:n})),"disclaimer"===e&&this.rootEl&&(n?.enabled?this.rootEl.classList.remove("np_companion_disclaimer-disabled"):this.rootEl.classList.add("np_companion_disclaimer-disabled"))},updateAvatarStyle:e=>{if(this.config){if(this.config.avatarStyle={view:"round",...this.config.avatarStyle,...e},e.view&&this.rootEl){const t=At(this.config.position,e.view,this.config.className);this.rootEl.className=t}this.embed&&this.embed.update({avatarStyle:this.config.avatarStyle})}},sendQuestion:e=>{const{dataChannel:t,stopInteraction:n}=ot.getState().avatar;t&&"open"===t.readyState&&!n?t.send(JSON.stringify({type:"send_question",data:e})):at.critical_warn("Data channel not available or not open")}}}}Object.defineProperty(Rt,"instance",{enumerable:!0,configurable:!0,writable:!0,value:null});const Dt=Rt.getInstance();return"undefined"!=typeof window&&(window.napsterCompanionApiSDK=Dt),Dt});
1
+ !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e="undefined"!=typeof globalThis?globalThis:e||self).napsterCompanionApiSDK=t()}(this,function(){"use strict";class e extends Error{constructor(e,t,n){super(e),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"timestamp",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"context",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name="SDKError",this.code=t,this.timestamp=new Date,this.context=n,Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,message:this.message,code:this.code,timestamp:this.timestamp.toISOString(),context:this.context,stack:this.stack}}}class t extends e{constructor(e,t){super(e,"INITIALIZATION_ERROR",t),this.name="InitializationError"}}class n extends e{constructor(e,t){super(e,"TOKEN_ERROR",t),this.name="TokenError"}}class o extends e{constructor(e,t){super(e,"CONNECTION_ERROR",t),this.name="ConnectionError"}}class i extends e{constructor(e,t){super(e,"WEBRTC_ERROR",t),this.name="WebRTCError"}}var a,r;!function(e){e.ALREADY_INITIALIZED="ALREADY_INITIALIZED",e.INVALID_TOKEN="INVALID_TOKEN",e.REACT_VERSION_UNSUPPORTED="REACT_VERSION_UNSUPPORTED",e.CONTAINER_NOT_FOUND="CONTAINER_NOT_FOUND",e.CONNECTION_FAILED="CONNECTION_FAILED",e.TOKEN_GENERATION_FAILED="TOKEN_GENERATION_FAILED",e.MISSING_CREDENTIALS="MISSING_CREDENTIALS",e.WEBRTC_NOT_SUPPORTED="WEBRTC_NOT_SUPPORTED",e.PEER_CONNECTION_FAILED="PEER_CONNECTION_FAILED",e.DATA_CHANNEL_ERROR="DATA_CHANNEL_ERROR",e.API_REQUEST_FAILED="API_REQUEST_FAILED",e.INVALID_RESPONSE="INVALID_RESPONSE",e.RATE_LIMITED="RATE_LIMITED",e.INVALID_CONFIGURATION="INVALID_CONFIGURATION",e.MISSING_REQUIRED_CONFIG="MISSING_REQUIRED_CONFIG",e.FEATURE_NOT_SUPPORTED="FEATURE_NOT_SUPPORTED",e.FEATURE_DISABLED="FEATURE_DISABLED",e.MEDIA_ACCESS_DENIED="MEDIA_ACCESS_DENIED",e.MEDIA_DEVICE_ERROR="MEDIA_DEVICE_ERROR",e.VIDEO_LOAD_ERROR="VIDEO_LOAD_ERROR"}(a||(a={}));class s{static setErrorHandler(e){this.onError=e}static handle(t,n){let o;return function(t){return t instanceof e}(t)?(o=t,n&&(o.context={...o.context,...n})):o=t instanceof Error?new e(t.message,"UNKNOWN_ERROR",{originalError:t.name,...n}):new e("string"==typeof t?t:"Unknown error occurred","UNKNOWN_ERROR",{originalError:t,...n}),this.onError?.(o),o}}function c(e){return`Minified Redux error #${e}; visit https://redux.js.org/Errors?code=${e} for the full message or use the non-minified dev environment for full errors. `}!function(e){e.BOTTOM_RIGHT="bottom-right",e.BOTTOM_CENTER="bottom-center",e.BOTTOM_LEFT="bottom-left",e.TOP_RIGHT="top-right",e.TOP_CENTER="top-center",e.TOP_LEFT="top-left",e.CENTER="center"}(r||(r={}));var l=(()=>"function"==typeof Symbol&&Symbol.observable||"@@observable")(),d=()=>Math.random().toString(36).substring(7).split("").join("."),p={INIT:`@@redux/INIT${d()}`,REPLACE:`@@redux/REPLACE${d()}`,PROBE_UNKNOWN_ACTION:()=>`@@redux/PROBE_UNKNOWN_ACTION${d()}`};function u(e){if("object"!=typeof e||null===e)return!1;let t=e;for(;null!==Object.getPrototypeOf(t);)t=Object.getPrototypeOf(t);return Object.getPrototypeOf(e)===t||null===Object.getPrototypeOf(e)}function m(e,t,n){if("function"!=typeof e)throw new Error(c(2));if("function"==typeof t&&"function"==typeof n||"function"==typeof n&&"function"==typeof arguments[3])throw new Error(c(0));if("function"==typeof t&&void 0===n&&(n=t,t=void 0),void 0!==n){if("function"!=typeof n)throw new Error(c(1));return n(m)(e,t)}let o=e,i=t,a=new Map,r=a,s=0,d=!1;function h(){r===a&&(r=new Map,a.forEach((e,t)=>{r.set(t,e)}))}function f(){if(d)throw new Error(c(3));return i}function b(e){if("function"!=typeof e)throw new Error(c(4));if(d)throw new Error(c(5));let t=!0;h();const n=s++;return r.set(n,e),function(){if(t){if(d)throw new Error(c(6));t=!1,h(),r.delete(n),a=null}}}function g(e){if(!u(e))throw new Error(c(7));if(void 0===e.type)throw new Error(c(8));if("string"!=typeof e.type)throw new Error(c(17));if(d)throw new Error(c(9));try{d=!0,i=o(i,e)}finally{d=!1}return(a=r).forEach(e=>{e()}),e}return g({type:p.INIT}),{dispatch:g,subscribe:b,getState:f,replaceReducer:function(e){if("function"!=typeof e)throw new Error(c(10));o=e,g({type:p.REPLACE})},[l]:function(){const e=b;return{subscribe(t){if("object"!=typeof t||null===t)throw new Error(c(11));function n(){t.next&&t.next(f())}return n(),{unsubscribe:e(n)}},[l](){return this}}}}}function h(...e){return 0===e.length?e=>e:1===e.length?e[0]:e.reduce((e,t)=>(...n)=>e(t(...n)))}var f=Symbol.for("immer-nothing"),b=Symbol.for("immer-draftable"),g=Symbol.for("immer-state");function v(e,...t){throw new Error(`[Immer] minified error nr: ${e}. Full error at: https://bit.ly/3cXEKWf`)}var _=Object,y=_.getPrototypeOf,w="constructor",C="prototype",E="configurable",S="enumerable",x="writable",k="value",T=e=>!!e&&!!e[g];function I(e){return!!e&&(A(e)||j(e)||!!e[b]||!!e[w]?.[b]||z(e)||F(e))}var N=_[C][w].toString(),O=new WeakMap;function A(e){if(!e||!V(e))return!1;const t=y(e);if(null===t||t===_[C])return!0;const n=_.hasOwnProperty.call(t,w)&&t[w];if(n===Object)return!0;if(!W(n))return!1;let o=O.get(n);return void 0===o&&(o=Function.toString.call(n),O.set(n,o)),o===N}function R(e,t,n=!0){0===D(e)?(n?Reflect.ownKeys(e):_.keys(e)).forEach(n=>{t(n,e[n],e)}):e.forEach((n,o)=>t(o,n,e))}function D(e){const t=e[g];return t?t.type_:j(e)?1:z(e)?2:F(e)?3:0}var L=(e,t,n=D(e))=>2===n?e.has(t):_[C].hasOwnProperty.call(e,t),P=(e,t,n=D(e))=>2===n?e.get(t):e[t],M=(e,t,n,o=D(e))=>{2===o?e.set(t,n):3===o?e.add(n):e[t]=n},j=Array.isArray,z=e=>e instanceof Map,F=e=>e instanceof Set,V=e=>"object"==typeof e,W=e=>"function"==typeof e,B=e=>"boolean"==typeof e,U=e=>e.copy_||e.base_,$=e=>e.modified_?e.copy_:e.base_;function K(e,t){if(z(e))return new Map(e);if(F(e))return new Set(e);if(j(e))return Array[C].slice.call(e);const n=A(e);if(!0===t||"class_only"===t&&!n){const t=_.getOwnPropertyDescriptors(e);delete t[g];let n=Reflect.ownKeys(t);for(let o=0;o<n.length;o++){const i=n[o],a=t[i];!1===a[x]&&(a[x]=!0,a[E]=!0),(a.get||a.set)&&(t[i]={[E]:!0,[x]:!0,[S]:a[S],[k]:e[i]})}return _.create(y(e),t)}{const t=y(e);if(null!==t&&n)return{...e};const o=_.create(t);return _.assign(o,e)}}function G(e,t=!1){return H(e)||T(e)||!I(e)||(D(e)>1&&_.defineProperties(e,{set:q,add:q,clear:q,delete:q}),_.freeze(e),t&&R(e,(e,t)=>{G(t,!0)},!1)),e}var q={[k]:function(){v(2)}};function H(e){return null===e||!V(e)||_.isFrozen(e)}var Q="MapSet",J="Patches",X={};function Y(e){const t=X[e];return t||v(0),t}var Z,ee=e=>!!X[e],te=()=>Z;function ne(e,t){t&&(e.patchPlugin_=Y(J),e.patches_=[],e.inversePatches_=[],e.patchListener_=t)}function oe(e){ie(e),e.drafts_.forEach(re),e.drafts_=null}function ie(e){e===Z&&(Z=e.parent_)}var ae=e=>Z=((e,t)=>({drafts_:[],parent_:e,immer_:t,canAutoFreeze_:!0,unfinalizedDrafts_:0,handledSet_:new Set,processedForPatches_:new Set,mapSetPlugin_:ee(Q)?Y(Q):void 0}))(Z,e);function re(e){const t=e[g];0===t.type_||1===t.type_?t.revoke_():t.revoked_=!0}function se(e,t){t.unfinalizedDrafts_=t.drafts_.length;const n=t.drafts_[0];if(void 0!==e&&e!==n){n[g].modified_&&(oe(t),v(4)),I(e)&&(e=ce(t,e));const{patchPlugin_:o}=t;o&&o.generateReplacementPatches_(n[g].base_,e,t)}else e=ce(t,n);return function(e,t,n=!1){!e.parent_&&e.immer_.autoFreeze_&&e.canAutoFreeze_&&G(t,n)}(t,e,!0),oe(t),t.patches_&&t.patchListener_(t.patches_,t.inversePatches_),e!==f?e:void 0}function ce(e,t){if(H(t))return t;const n=t[g];if(!n)return he(t,e.handledSet_,e);if(!de(n,e))return t;if(!n.modified_)return n.base_;if(!n.finalized_){const{callbacks_:t}=n;if(t)for(;t.length>0;)t.pop()(e);me(n,e)}return n.copy_}function le(e){e.finalized_=!0,e.scope_.unfinalizedDrafts_--}var de=(e,t)=>e.scope_===t,pe=[];function ue(e,t,n,o){const i=U(e),a=e.type_;if(void 0!==o&&P(i,o,a)===t)return void M(i,o,n,a);if(!e.draftLocations_){const t=e.draftLocations_=new Map;R(i,(e,n)=>{if(T(n)){const o=t.get(n)||[];o.push(e),t.set(n,o)}})}const r=e.draftLocations_.get(t)??pe;for(const e of r)M(i,e,n,a)}function me(e,t){if(e.modified_&&!e.finalized_&&(3===e.type_||(e.assigned_?.size??0)>0)){const{patchPlugin_:n}=t;if(n){const o=n.getPath(e);o&&n.generatePatches_(e,o,t)}le(e)}}function he(e,t,n){return!n.immer_.autoFreeze_&&n.unfinalizedDrafts_<1||T(e)||t.has(e)||!I(e)||H(e)||(t.add(e),R(e,(o,i)=>{if(T(i)){const t=i[g];if(de(t,n)){const n=$(t);M(e,o,n,e.type_),le(t)}}else I(i)&&he(i,t,n)})),e}var fe={get(e,t){if(t===g)return e;const n=U(e);if(!L(n,t,e.type_))return function(e,t,n){const o=ve(t,n);return o?k in o?o[k]:o.get?.call(e.draft_):void 0}(e,n,t);const o=n[t];if(e.finalized_||!I(o))return o;if(o===ge(e.base_,t)){ye(e);const n=1===e.type_?+t:t,i=we(0,o,e,n);return e.copy_[n]=i}return o},has:(e,t)=>t in U(e),ownKeys:e=>Reflect.ownKeys(U(e)),set(e,t,n){const o=ve(U(e),t);if(o?.set)return o.set.call(e.draft_,n),!0;if(!e.modified_){const o=ge(U(e),t),i=o?.[g];if(i&&i.base_===n)return e.copy_[t]=n,e.assigned_.set(t,!1),!0;if(function(e,t){return e===t?0!==e||1/e==1/t:e!=e&&t!=t}(n,o)&&(void 0!==n||L(e.base_,t,e.type_)))return!0;ye(e),_e(e)}return e.copy_[t]===n&&(void 0!==n||t in e.copy_)||Number.isNaN(n)&&Number.isNaN(e.copy_[t])||(e.copy_[t]=n,e.assigned_.set(t,!0),function(e,t,n){const{scope_:o}=e;if(T(n)){const i=n[g];de(i,o)&&i.callbacks_.push(function(){ye(e);const o=$(i);ue(e,n,o,t)})}else I(n)&&e.callbacks_.push(function(){const i=U(e);P(i,t,e.type_)===n&&o.drafts_.length>1&&!0===(e.assigned_.get(t)??!1)&&e.copy_&&he(P(e.copy_,t,e.type_),o.handledSet_,o)})}(e,t,n)),!0},deleteProperty:(e,t)=>(ye(e),void 0!==ge(e.base_,t)||t in e.base_?(e.assigned_.set(t,!1),_e(e)):e.assigned_.delete(t),e.copy_&&delete e.copy_[t],!0),getOwnPropertyDescriptor(e,t){const n=U(e),o=Reflect.getOwnPropertyDescriptor(n,t);return o?{[x]:!0,[E]:1!==e.type_||"length"!==t,[S]:o[S],[k]:n[t]}:o},defineProperty(){v(11)},getPrototypeOf:e=>y(e.base_),setPrototypeOf(){v(12)}},be={};function ge(e,t){const n=e[g];return(n?U(n):e)[t]}function ve(e,t){if(!(t in e))return;let n=y(e);for(;n;){const e=Object.getOwnPropertyDescriptor(n,t);if(e)return e;n=y(n)}}function _e(e){e.modified_||(e.modified_=!0,e.parent_&&_e(e.parent_))}function ye(e){e.copy_||(e.assigned_=new Map,e.copy_=K(e.base_,e.scope_.immer_.useStrictShallowCopy_))}function we(e,t,n,o){const[i,a]=z(t)?Y(Q).proxyMap_(t,n):F(t)?Y(Q).proxySet_(t,n):function(e,t){const n=j(e),o={type_:n?1:0,scope_:t?t.scope_:te(),modified_:!1,finalized_:!1,assigned_:void 0,parent_:t,base_:e,draft_:null,copy_:null,revoke_:null,isManual_:!1,callbacks_:void 0};let i=o,a=fe;n&&(i=[o],a=be);const{revoke:r,proxy:s}=Proxy.revocable(i,a);return o.draft_=s,o.revoke_=r,[s,o]}(t,n);return(n?.scope_??te()).drafts_.push(i),a.callbacks_=n?.callbacks_??[],a.key_=o,n&&void 0!==o?function(e,t,n){e.callbacks_.push(function(o){const i=t;if(!i||!de(i,o))return;o.mapSetPlugin_?.fixSetContents(i);const a=$(i);ue(e,i.draft_??i,a,n),me(i,o)})}(n,a,o):a.callbacks_.push(function(e){e.mapSetPlugin_?.fixSetContents(a);const{patchPlugin_:t}=e;a.modified_&&t&&t.generatePatches_(a,[],e)}),i}function Ce(e){if(!I(e)||H(e))return e;const t=e[g];let n,o=!0;if(t){if(!t.modified_)return t.base_;t.finalized_=!0,n=K(e,t.scope_.immer_.useStrictShallowCopy_),o=t.scope_.immer_.shouldUseStrictIteration()}else n=K(e,!0);return R(n,(e,t)=>{M(n,e,Ce(t))},o),t&&(t.finalized_=!1),n}R(fe,(e,t)=>{be[e]=function(){const e=arguments;return e[0]=e[0][0],t.apply(this,e)}}),be.deleteProperty=function(e,t){return be.set.call(this,e,t,void 0)},be.set=function(e,t,n){return fe.set.call(this,e[0],t,n,e[0])};var Ee=(new class{constructor(e){this.autoFreeze_=!0,this.useStrictShallowCopy_=!1,this.useStrictIteration_=!1,this.produce=(e,t,n)=>{if(W(e)&&!W(t)){const n=t;t=e;const o=this;return function(e=n,...i){return o.produce(e,e=>t.call(this,e,...i))}}let o;if(W(t)||v(6),void 0===n||W(n)||v(7),I(e)){const i=ae(this),a=we(0,e,void 0);let r=!0;try{o=t(a),r=!1}finally{r?oe(i):ie(i)}return ne(i,n),se(o,i)}if(!e||!V(e)){if(o=t(e),void 0===o&&(o=e),o===f&&(o=void 0),this.autoFreeze_&&G(o,!0),n){const t=[],i=[];Y(J).generateReplacementPatches_(e,o,{patches_:t,inversePatches_:i}),n(t,i)}return o}v(1)},this.produceWithPatches=(e,t)=>{if(W(e))return(t,...n)=>this.produceWithPatches(t,t=>e(t,...n));let n,o;return[this.produce(e,t,(e,t)=>{n=e,o=t}),n,o]},B(e?.autoFreeze)&&this.setAutoFreeze(e.autoFreeze),B(e?.useStrictShallowCopy)&&this.setUseStrictShallowCopy(e.useStrictShallowCopy),B(e?.useStrictIteration)&&this.setUseStrictIteration(e.useStrictIteration)}createDraft(e){I(e)||v(8),T(e)&&(e=function(e){return T(e)||v(10),Ce(e)}(e));const t=ae(this),n=we(0,e,void 0);return n[g].isManual_=!0,ie(t),n}finishDraft(e,t){const n=e&&e[g];n&&n.isManual_||v(9);const{scope_:o}=n;return ne(o,t),se(void 0,o)}setAutoFreeze(e){this.autoFreeze_=e}setUseStrictShallowCopy(e){this.useStrictShallowCopy_=e}setUseStrictIteration(e){this.useStrictIteration_=e}shouldUseStrictIteration(){return this.useStrictIteration_}applyPatches(e,t){let n;for(n=t.length-1;n>=0;n--){const o=t[n];if(0===o.path.length&&"replace"===o.op){e=o.value;break}}n>-1&&(t=t.slice(n+1));const o=Y(J).applyPatches_;return T(e)?o(e,t):this.produce(e,e=>o(e,t))}}).produce;function Se(e){return({dispatch:t,getState:n})=>o=>i=>"function"==typeof i?i(t,n,e):o(i)}var xe=Se(),ke=Se,Te="undefined"!=typeof window&&window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__?window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__:function(){if(0!==arguments.length)return"object"==typeof arguments[0]?h:h.apply(null,arguments)};function Ie(e,t){function n(...n){if(t){let o=t(...n);if(!o)throw new Error(Ve(0));return{type:e,payload:o.payload,..."meta"in o&&{meta:o.meta},..."error"in o&&{error:o.error}}}return{type:e,payload:n[0]}}return n.toString=()=>`${e}`,n.type=e,n.match=t=>function(e){return u(e)&&"type"in e&&"string"==typeof e.type}(t)&&t.type===e,n}var Ne=class e extends Array{constructor(...t){super(...t),Object.setPrototypeOf(this,e.prototype)}static get[Symbol.species](){return e}concat(...e){return super.concat.apply(this,e)}prepend(...t){return 1===t.length&&Array.isArray(t[0])?new e(...t[0].concat(this)):new e(...t.concat(this))}};function Oe(e){return I(e)?Ee(e,()=>{}):e}function Ae(e,t,n){return e.has(t)?e.get(t):e.set(t,n(t)).get(t)}var Re=e=>t=>{setTimeout(t,e)};function De(e){const t={},n=[];let o;const i={addCase(e,n){const o="string"==typeof e?e:e.type;if(!o)throw new Error(Ve(28));if(o in t)throw new Error(Ve(29));return t[o]=n,i},addAsyncThunk:(e,o)=>(o.pending&&(t[e.pending.type]=o.pending),o.rejected&&(t[e.rejected.type]=o.rejected),o.fulfilled&&(t[e.fulfilled.type]=o.fulfilled),o.settled&&n.push({matcher:e.settled,reducer:o.settled}),i),addMatcher:(e,t)=>(n.push({matcher:e,reducer:t}),i),addDefaultCase:e=>(o=e,i)};return e(i),[t,n,o]}var Le=Symbol.for("rtk-slice-createasyncthunk");function Pe(e,t){return`${e}/${t}`}function Me({creators:e}={}){const t=e?.asyncThunk?.[Le];return function(e){const{name:n,reducerPath:o=n}=e;if(!n)throw new Error(Ve(11));const i=("function"==typeof e.reducers?e.reducers(function(){function e(e,t){return{_reducerDefinitionType:"asyncThunk",payloadCreator:e,...t}}return e.withTypes=()=>e,{reducer:e=>Object.assign({[e.name]:(...t)=>e(...t)}[e.name],{_reducerDefinitionType:"reducer"}),preparedReducer:(e,t)=>({_reducerDefinitionType:"reducerWithPrepare",prepare:e,reducer:t}),asyncThunk:e}}()):e.reducers)||{},a=Object.keys(i),r={sliceCaseReducersByName:{},sliceCaseReducersByType:{},actionCreators:{},sliceMatchers:[]},s={addCase(e,t){const n="string"==typeof e?e:e.type;if(!n)throw new Error(Ve(12));if(n in r.sliceCaseReducersByType)throw new Error(Ve(13));return r.sliceCaseReducersByType[n]=t,s},addMatcher:(e,t)=>(r.sliceMatchers.push({matcher:e,reducer:t}),s),exposeAction:(e,t)=>(r.actionCreators[e]=t,s),exposeCaseReducer:(e,t)=>(r.sliceCaseReducersByName[e]=t,s)};function c(){const[t={},n=[],o]="function"==typeof e.extraReducers?De(e.extraReducers):[e.extraReducers],i={...t,...r.sliceCaseReducersByType};return function(e){let t,[a,s,c]=De(e=>{for(let t in i)e.addCase(t,i[t]);for(let t of r.sliceMatchers)e.addMatcher(t.matcher,t.reducer);for(let t of n)e.addMatcher(t.matcher,t.reducer);o&&e.addDefaultCase(o)});if(function(e){return"function"==typeof e}(e))t=()=>Oe(e());else{const n=Oe(e);t=()=>n}function l(e=t(),n){let o=[a[n.type],...s.filter(({matcher:e})=>e(n)).map(({reducer:e})=>e)];return 0===o.filter(e=>!!e).length&&(o=[c]),o.reduce((e,t)=>{if(t){if(T(e)){const o=t(e,n);return void 0===o?e:o}if(I(e))return Ee(e,e=>t(e,n));{const o=t(e,n);if(void 0===o){if(null===e)return e;throw Error("A case reducer on a non-draftable value must not return undefined")}return o}}return e},e)}return l.getInitialState=t,l}(e.initialState)}a.forEach(o=>{const a=i[o],r={reducerName:o,type:Pe(n,o),createNotation:"function"==typeof e.reducers};!function(e){return"asyncThunk"===e._reducerDefinitionType}(a)?function({type:e,reducerName:t,createNotation:n},o,i){let a,r;if("reducer"in o){if(n&&!function(e){return"reducerWithPrepare"===e._reducerDefinitionType}(o))throw new Error(Ve(17));a=o.reducer,r=o.prepare}else a=o;i.addCase(e,a).exposeCaseReducer(t,a).exposeAction(t,r?Ie(e,r):Ie(e))}(r,a,s):function({type:e,reducerName:t},n,o,i){if(!i)throw new Error(Ve(18));const{payloadCreator:a,fulfilled:r,pending:s,rejected:c,settled:l,options:d}=n,p=i(e,a,d);o.exposeAction(t,p),r&&o.addCase(p.fulfilled,r),s&&o.addCase(p.pending,s),c&&o.addCase(p.rejected,c),l&&o.addMatcher(p.settled,l),o.exposeCaseReducer(t,{fulfilled:r||Fe,pending:s||Fe,rejected:c||Fe,settled:l||Fe})}(r,a,s,t)});const l=e=>e,d=new Map,p=new WeakMap;let u;function m(e,t){return u||(u=c()),u(e,t)}function h(){return u||(u=c()),u.getInitialState()}function f(t,n=!1){function o(e){let i=e[t];return void 0===i&&n&&(i=Ae(p,o,h)),i}function i(t=l){const o=Ae(d,n,()=>new WeakMap);return Ae(o,t,()=>{const o={};for(const[i,a]of Object.entries(e.selectors??{}))o[i]=je(a,t,()=>Ae(p,t,h),n);return o})}return{reducerPath:t,getSelectors:i,get selectors(){return i(o)},selectSlice:o}}const b={name:n,reducer:m,actions:r.actionCreators,caseReducers:r.sliceCaseReducersByName,getInitialState:h,...f(o),injectInto(e,{reducerPath:t,...n}={}){const i=t??o;return e.inject({reducerPath:i,reducer:m},n),{...b,...f(i,!0)}}};return b}}function je(e,t,n,o){function i(i,...a){let r=t(i);return void 0===r&&o&&(r=n()),e(r,...a)}return i.unwrapped=e,i}var ze=Me();function Fe(){}function Ve(e){return`Minified Redux Toolkit error #${e}; visit https://redux-toolkit.js.org/Errors?code=${e} for the full message or use the non-minified dev environment for full errors. `}const We=ze({name:"avatar",initialState:{avatarReady:!1,dataChannel:null,stopInteraction:!1,muted:!1,transcript:void 0,customVoiceId:void 0,defaultVoiceId:void 0,connectionToken:void 0,companionId:void 0,closeConnectionHandler:void 0},reducers:{setSessionId:(e,t)=>{e.sessionId=t.payload},setAvatarReady:(e,t)=>{e.avatarReady=t.payload},setDataChannel:(e,t)=>{e.dataChannel=t.payload},setAvatarId:(e,t)=>{e.avatarId=t.payload},setVideoId:(e,t)=>{e.videoId=t.payload},setStopInteraction:(e,t)=>{e.stopInteraction=t.payload},setMuted:(e,t)=>{e.muted=t.payload},addTranscript:(e,t)=>{e.transcript=t.payload},setCustomVoiceId:(e,t)=>{e.customVoiceId=t.payload},setDefaultVoiceId:(e,t)=>{e.defaultVoiceId=t.payload},setConnectionToken:(e,t)=>{e.connectionToken=t.payload},setCloseConnectionHandler:(e,t)=>{e.closeConnectionHandler=t.payload}}}),{setDataChannel:Be,setStopInteraction:Ue,setMuted:$e,setConnectionToken:Ke,setCloseConnectionHandler:Ge}=We.actions,qe=We.reducer,He={features:{backgroundRemoval:{enabled:!0},waveform:{enabled:!0,color:"#ffffff"},inactiveTimeout:{enabled:!0,duration:6e4,countdown:30},disclaimer:{enabled:!0,text:"This is an AI avatar. Check important info."},showSDKLoader:{enabled:!0,bgColor:"rgb(222 222 222 / 60%)",color:"#585858ff",type:"spinner"}},position:void 0,showExperience:!1,debugMode:!1},Qe=ze({name:"app",initialState:He,reducers:{setFeatures:(e,t)=>{const{feature:n,config:o}=t.payload,i=e.features[n];e.features[n]={...i,...o,enabled:o?.enabled??!!i?.enabled}},resetFeatures:e=>{e.features=He.features},setPosition:(e,t)=>{e.position=t.payload},setShowExperience:(e,t)=>{e.showExperience=t.payload},setDebugMode:(e,t)=>{e.debugMode=t.payload}}}),{setFeatures:Je,resetFeatures:Xe,setPosition:Ye,setDebugMode:Ze}=Qe.actions;let et=null;const tt=e=>{et=e},nt=e=>t=>n=>{const o=e.getState().app.features,i=t(n),a=e.getState().app.features;return et&&o!==a&&JSON.stringify(o)!==JSON.stringify(a)&&et(a),i},ot=function(e){const t=function(e){const{thunk:t=!0,immutableCheck:n=!0,serializableCheck:o=!0,actionCreatorCheck:i=!0}=e??{};let a=new Ne;return t&&(function(e){return"boolean"==typeof e}(t)?a.push(xe):a.push(ke(t.extraArgument))),a},{reducer:n,middleware:o,devTools:i=!0,preloadedState:a,enhancers:r}=e||{};let s,l;if("function"==typeof n)s=n;else{if(!u(n))throw new Error(Ve(1));s=function(e){const t=Object.keys(e),n={};for(let o=0;o<t.length;o++){const i=t[o];"function"==typeof e[i]&&(n[i]=e[i])}const o=Object.keys(n);let i;try{!function(e){Object.keys(e).forEach(t=>{const n=e[t];if(void 0===n(void 0,{type:p.INIT}))throw new Error(c(12));if(void 0===n(void 0,{type:p.PROBE_UNKNOWN_ACTION()}))throw new Error(c(13))})}(n)}catch(e){i=e}return function(e={},t){if(i)throw i;let a=!1;const r={};for(let i=0;i<o.length;i++){const s=o[i],l=e[s],d=(0,n[s])(l,t);if(void 0===d)throw new Error(c(14));r[s]=d,a=a||d!==l}return a=a||o.length!==Object.keys(e).length,a?r:e}}(n)}l="function"==typeof o?o(t):t();let d=h;i&&(d=Te({trace:!1,..."object"==typeof i&&i}));const f=function(...e){return t=>(n,o)=>{const i=t(n,o);let a=()=>{throw new Error(c(15))};const r={getState:i.getState,dispatch:(e,...t)=>a(e,...t)},s=e.map(e=>e(r));return a=h(...s)(i.dispatch),{...i,dispatch:a}}}(...l),b=(e=>function(t){const{autoBatch:n=!0}=t??{};let o=new Ne(e);return n&&o.push(((e={type:"raf"})=>t=>(...n)=>{const o=t(...n);let i=!0,a=!1,r=!1;const s=new Set,c="tick"===e.type?queueMicrotask:"raf"===e.type?"undefined"!=typeof window&&window.requestAnimationFrame?window.requestAnimationFrame:Re(10):"callback"===e.type?e.queueNotification:Re(e.timeout),l=()=>{r=!1,a&&(a=!1,s.forEach(e=>e()))};return Object.assign({},o,{subscribe(e){const t=o.subscribe(()=>i&&e());return s.add(e),()=>{t(),s.delete(e)}},dispatch(e){try{return i=!e?.meta?.RTK_autoBatch,a=!i,a&&(r||(r=!0,c(l))),o.dispatch(e)}finally{i=!0}}})})("object"==typeof n?n:void 0)),o})(f);return m(s,a,d(..."function"==typeof r?r(b):b()))}({reducer:{avatar:qe,app:Qe.reducer},middleware:e=>e({serializableCheck:!1}).concat(nt)});var it;!function(e){e.INFO="info",e.WARN="warn",e.ERROR="error",e.DEBUG="debug"}(it||(it={}));const at=new class{constructor(){Object.defineProperty(this,"prefix",{enumerable:!0,configurable:!0,writable:!0,value:"[Napster SDK]"})}isDebugEnabled(){try{return ot.getState().app.debugMode||!1}catch{return!1}}log(e,...t){if(!this.isDebugEnabled())return;const n=[this.prefix,...t];switch(e){case it.INFO:console.info(...n);break;case it.WARN:console.warn(...n);break;case it.ERROR:console.error(...n);break;case it.DEBUG:console.debug(...n)}}info(...e){this.log(it.INFO,"ℹ️",...e)}debug(...e){this.log(it.DEBUG,"🐞",...e)}warn(...e){this.log(it.WARN,"⚠️",...e)}error(...e){this.log(it.ERROR,"❌",...e)}critical_warn(...e){console.warn(this.prefix,"⚠️",...e)}critical_error(...e){console.error(this.prefix,"❌",...e)}webrtc(...e){this.log(it.INFO,"📡 WebRTC:",...e)}avatar(...e){this.log(it.INFO,"🎭 Avatar:",...e)}connection(...e){this.log(it.INFO,"🔌 Connection:",...e)}features(...e){this.log(it.INFO,"🔄 Features:",...e)}data(...e){this.log(it.INFO,"📨 Data:",...e)}timer(...e){this.log(it.INFO,"⏱️ Timer:",...e)}cleanup(...e){this.log(it.INFO,"🗑️ Cleanup:",...e)}};function rt(...e){const t=[];for(const n of e)if(n)if("string"==typeof n||"number"==typeof n)t.push(String(n));else if(Array.isArray(n)){const e=rt(...n);e&&t.push(e)}else if("object"==typeof n)for(const[e,o]of Object.entries(n))o&&t.push(e);return t.join(" ")}const st={icon:"np_companion-action-btn-container-icon",persistFillColor:"np_companion-persist-fill-color",alignMiddle:"np_companion-align-middle",alignBetween:"np_companion-align-between",darkGreyBg:"np_companion-dark-grey-bg",callEnd:"np_companion-action-btn-container-call-end",container:"np_companion-action-btn-container-container",wrapper:"np_companion-action-btn-container-wrapper",canvas:"np_companion-action-btn-container-canvas",controls:"np_companion-action-btn-container-controls",left:"np_companion-action-btn-container-left",middle:"np_companion-action-btn-container-middle",right:"np_companion-action-btn-container-right",wave:"np_companion-action-btn-container-wave",stop:"np_companion-action-btn-container-stop",questionBar:"np_companion-chat-question-bar-container",muted:"muted",hidden:"np_companion-hidden",expanded:"np_companion-action-btn-container-expanded",collapse:"np_companion-action-btn-container-collapse",mobileMode:"np_companion-mobile-mode",displayNone:"np_companion__d-none",iconButton:()=>rt(st.icon,st.alignMiddle,st.darkGreyBg),iconButtonEnd:()=>rt(st.icon,st.alignMiddle,st.darkGreyBg,st.callEnd),iconButtonWithState:e=>rt(st.icon,st.alignMiddle,st.darkGreyBg,{[st.muted]:e})};class ct{static createElement(e,t){const n=document.createElement(e);return t?.className&&(n.className=t.className),t?.id&&(n.id=t.id),t?.attributes&&Object.entries(t.attributes).forEach(([e,t])=>{n.setAttribute(e,t)}),t?.styles&&Object.assign(n.style,t.styles),n}static createVideo(e){const t=this.createElement("video",{className:e.className});return t.autoplay=e.autoplay??!1,t.muted=e.muted??!1,t.loop=e.loop??!1,t.playsInline=e.playsInline??!1,e.crossOrigin&&(t.crossOrigin=e.crossOrigin),e.poster&&(t.poster=e.poster),e.src&&(t.src=e.src),t}static createAudio(e){const t=this.createElement("audio",{className:e.className});return t.autoplay=e.autoplay??!1,t}static createCanvas(e){const t=this.createElement("canvas",{className:e.className,styles:e.styles});return void 0!==e.width&&(t.width=e.width),void 0!==e.height&&(t.height=e.height),t}static createButton(e){const t=this.createElement("button",{className:e.className,attributes:e.attributes});return e.textContent&&(t.textContent=e.textContent),e.onClick&&t.addEventListener("click",e.onClick),t}static createDiv(e){return this.createElement("div",{className:e})}}class lt{static process(e){const t=e.data;return this.hasGreenScreen(t)?(this.removeGreenScreen(t),e):e}static hasGreenScreen(e){for(let t=0;t<e.length;t+=4)if(this.isGreenPixel(e[t],e[t+1],e[t+2]))return!0;return!1}static isGreenPixel(e,t,n){return e>=0&&e<=120&&t>=150&&t<=255&&n>=0&&n<=120}static removeGreenScreen(e){for(let t=0;t<e.length;t+=4){const n=e[t],o=e[t+1],i=e[t+2];this.isGreenPixel(n,o,i)?e[t+3]=0:this.reduceGreenSpill(e,t,n,o,i)}}static reduceGreenSpill(e,t,n,o,i){const a=o-Math.max(n,i);if(a>0){const r=.5*a;e[t]=Math.min(255,n+.8*r),e[t+2]=Math.min(255,i+.8*r),e[t+1]=Math.max(0,o-r)}}}const dt=new class{constructor(){Object.defineProperty(this,"svgNS",{enumerable:!0,configurable:!0,writable:!0,value:"http://www.w3.org/2000/svg"})}createElement(e){const t=document.createElementNS(this.svgNS,e.tag);return e.attributes&&Object.entries(e.attributes).forEach(([e,n])=>{t.setAttribute(e,String(n))}),e.textContent&&(t.textContent=e.textContent),e.children&&e.children.forEach(e=>{const n=this.createElement(e);t.appendChild(n)}),t}createSVG(e,t,n,o,i){const a=document.createElementNS(this.svgNS,"svg");return a.setAttribute("width",String(e)),a.setAttribute("height",String(t)),a.setAttribute("viewBox",n),a.setAttribute("fill","none"),a.setAttribute("xmlns",this.svgNS),i&&a.setAttribute("class",i),o.forEach(e=>{const t=this.createElement(e);a.appendChild(t)}),a}},pt={micUnmuted:()=>dt.createSVG(17,17,"0 0 17 17",[{tag:"g",attributes:{"clip-path":"url(#clip0_655_3824)"},children:[{tag:"path",attributes:{d:"M8.67241 11.8448C9.49524 11.844 10.2841 11.5167 10.8659 10.9349C11.4478 10.3531 11.775 9.5642 11.7759 8.74138V4.60345C11.7759 3.78036 11.4489 2.99099 10.8669 2.40898C10.2849 1.82697 9.4955 1.5 8.67241 1.5C7.84933 1.5 7.05995 1.82697 6.47794 2.40898C5.89594 2.99099 5.56897 3.78036 5.56897 4.60345V8.74138C5.56982 9.5642 5.89707 10.3531 6.47889 10.9349C7.06071 11.5167 7.84959 11.844 8.67241 11.8448ZM6.60345 4.60345C6.60345 4.05472 6.82143 3.52847 7.20943 3.14047C7.59744 2.75246 8.12369 2.53448 8.67241 2.53448C9.22114 2.53448 9.74739 2.75246 10.1354 3.14047C10.5234 3.52847 10.7414 4.05472 10.7414 4.60345V8.74138C10.7414 9.2901 10.5234 9.81635 10.1354 10.2044C9.74739 10.5924 9.22114 10.8103 8.67241 10.8103C8.12369 10.8103 7.59744 10.5924 7.20943 10.2044C6.82143 9.81635 6.60345 9.2901 6.60345 8.74138V4.60345ZM9.18965 13.8879V15.9828C9.18965 16.1199 9.13516 16.2515 9.03816 16.3485C8.94116 16.4455 8.80959 16.5 8.67241 16.5C8.53523 16.5 8.40367 16.4455 8.30667 16.3485C8.20967 16.2515 8.15517 16.1199 8.15517 15.9828V13.8879C6.87994 13.7582 5.69812 13.1601 4.83826 12.2095C3.9784 11.2589 3.50158 10.0232 3.5 8.74138C3.5 8.6042 3.5545 8.47264 3.6515 8.37563C3.7485 8.27863 3.88006 8.22414 4.01724 8.22414C4.15442 8.22414 4.28598 8.27863 4.38299 8.37563C4.47999 8.47264 4.53448 8.6042 4.53448 8.74138C4.53448 9.83883 4.97044 10.8913 5.74645 11.6673C6.52247 12.4434 7.57497 12.8793 8.67241 12.8793C9.76986 12.8793 10.8224 12.4434 11.5984 11.6673C12.3744 10.8913 12.8103 9.83883 12.8103 8.74138C12.8103 8.6042 12.8648 8.47264 12.9618 8.37563C13.0588 8.27863 13.1904 8.22414 13.3276 8.22414C13.4648 8.22414 13.5963 8.27863 13.6933 8.37563C13.7903 8.47264 13.8448 8.6042 13.8448 8.74138C13.8433 10.0232 13.3664 11.2589 12.5066 12.2095C11.6467 13.1601 10.4649 13.7582 9.18965 13.8879Z",fill:"white"}}]},{tag:"defs",children:[{tag:"clipPath",attributes:{id:"clip0_655_3824"},children:[{tag:"rect",attributes:{width:"16",height:"16",fill:"white",transform:"translate(0.5 0.5)"}}]}]}],"np_companion-mic-unmuted"),micMuted:()=>dt.createSVG(22,22,"0 0 17 18",[{tag:"g",attributes:{"clip-path":"url(#clip0_655_4192)"},children:[{tag:"path",attributes:{d:"M14.2432 14.6L3.89604 3.21808C3.80327 3.11843 3.67498 3.05936 3.53896 3.05368C3.40294 3.048 3.27016 3.09616 3.16941 3.18772C3.06866 3.27928 3.00806 3.40686 3.00075 3.5428C2.99343 3.67874 3.04 3.81208 3.13034 3.91392L5.58263 6.61131V8.7396C5.58251 9.26661 5.71656 9.78497 5.97216 10.2458C6.22776 10.7067 6.59649 11.0949 7.04361 11.3739C7.49073 11.6529 8.00151 11.8134 8.52782 11.8404C9.05414 11.8674 9.57867 11.7599 10.052 11.5282L10.7698 12.3171C10.138 12.6868 9.41878 12.8806 8.68679 12.8785C7.58946 12.8773 6.53741 12.4408 5.76148 11.6649C4.98555 10.889 4.54911 9.83693 4.54791 8.7396C4.54791 8.60239 4.4934 8.47079 4.39638 8.37377C4.29935 8.27675 4.16776 8.22224 4.03055 8.22224C3.89334 8.22224 3.76174 8.27675 3.66472 8.37377C3.5677 8.47079 3.51319 8.60239 3.51319 8.7396C3.51476 10.0217 3.9917 11.2577 4.85176 12.2085C5.71182 13.1594 6.8939 13.7575 8.16943 13.8873V15.9826C8.16943 16.1199 8.22394 16.2514 8.32096 16.3485C8.41798 16.4455 8.54958 16.5 8.68679 16.5C8.824 16.5 8.95559 16.4455 9.05262 16.3485C9.14964 16.2514 9.20415 16.1199 9.20415 15.9826V13.8867C10.0143 13.8085 10.794 13.5376 11.4779 13.0964L13.4775 15.2952C13.523 15.3464 13.5781 15.3881 13.6398 15.4178C13.7015 15.4476 13.7684 15.4648 13.8368 15.4685C13.9051 15.4722 13.9735 15.4622 14.038 15.4393C14.1025 15.4163 14.1618 15.3808 14.2125 15.3347C14.2632 15.2887 14.3042 15.2331 14.3332 15.171C14.3622 15.109 14.3786 15.0419 14.3815 14.9735C14.3843 14.9051 14.3736 14.8368 14.3499 14.7725C14.3261 14.7083 14.2899 14.6495 14.2432 14.5993V14.6ZM8.68679 10.809C8.13794 10.809 7.61157 10.591 7.22347 10.2029C6.83538 9.81482 6.61735 9.28845 6.61735 8.7396V7.7495L9.3115 10.7127C9.10943 10.7766 8.89873 10.8091 8.68679 10.809ZM12.4066 10.5562C12.6841 9.99093 12.8275 9.36929 12.8257 8.7396C12.8257 8.60239 12.8802 8.47079 12.9772 8.37377C13.0742 8.27675 13.2058 8.22224 13.343 8.22224C13.4802 8.22224 13.6118 8.27675 13.7089 8.37377C13.8059 8.47079 13.8604 8.60239 13.8604 8.7396C13.8625 9.52693 13.6831 10.3041 13.3359 11.0108C13.2934 11.0979 13.2273 11.1713 13.145 11.2226C13.0628 11.274 12.9679 11.3012 12.8709 11.3012C12.7922 11.3013 12.7145 11.2831 12.6439 11.2481C12.5207 11.1878 12.4265 11.0811 12.382 10.9513C12.3375 10.8215 12.3463 10.6794 12.4066 10.5562ZM5.84131 3.36358C6.12624 2.71004 6.62746 2.1745 7.26073 1.84696C7.894 1.51943 8.62071 1.41987 9.31874 1.56501C10.0168 1.71015 10.6435 2.09116 11.0938 2.64398C11.544 3.19681 11.7902 3.88776 11.7909 4.60072V8.7396C11.7908 8.8476 11.7852 8.95552 11.7741 9.06295C11.7608 9.19066 11.7005 9.30885 11.6049 9.39455C11.5092 9.48025 11.3852 9.52733 11.2568 9.52663C11.2387 9.52757 11.2205 9.52757 11.2025 9.52663C11.066 9.51229 10.9409 9.44435 10.8545 9.33775C10.7682 9.23115 10.7277 9.09462 10.742 8.95818C10.7491 8.88705 10.753 8.81332 10.753 8.74089V4.60072C10.7516 4.12605 10.5871 3.66628 10.2871 3.29848C9.98701 2.93069 9.56963 2.67722 9.10491 2.58058C8.64018 2.48393 8.15636 2.54998 7.73454 2.76766C7.31273 2.98534 6.97857 3.34141 6.78808 3.77618C6.7639 3.84253 6.72639 3.90322 6.67786 3.95452C6.62934 4.00583 6.57082 4.04665 6.50592 4.07449C6.44102 4.10232 6.37111 4.11658 6.30049 4.11637C6.22987 4.11617 6.16005 4.10151 6.09531 4.07329C6.03057 4.04508 5.9723 4.00392 5.92407 3.95233C5.87584 3.90075 5.83869 3.83983 5.81489 3.77335C5.7911 3.70686 5.78117 3.6362 5.78571 3.56573C5.79025 3.49526 5.80917 3.42646 5.84131 3.36358Z",fill:"white"}}]},{tag:"defs",children:[{tag:"clipPath",attributes:{id:"clip0_655_4192"},children:[{tag:"rect",attributes:{width:"16",height:"16",fill:"white",transform:"translate(0.5 0.5)"}}]}]}],"tc-mic-muted"),stop:()=>dt.createSVG(20,20,"0 0 32 32",[{tag:"path",attributes:{d:"M5.92 24.096q0 0.832 0.576 1.408t1.44 0.608h16.128q0.832 0 1.44-0.608t0.576-1.408v-16.16q0-0.832-0.576-1.44t-1.44-0.576h-16.128q-0.832 0-1.44 0.576t-0.576 1.44v16.16z",fill:"#ffffff"}}]),volumeHigh(e){const t=[{tag:"path",attributes:{d:"M80 416L128 416L262.1 535.2C268.5 540.9 276.7 544 285.2 544C304.4 544 320 528.4 320 509.2L320 130.8C320 111.6 304.4 96 285.2 96C276.7 96 268.5 99.1 262.1 104.8L128 224L80 224C53.5 224 32 245.5 32 272L32 368C32 394.5 53.5 416 80 416z",fill:"#ffffff"}}];return e>0&&t.push({tag:"path",attributes:{d:"M412.6 245.5C402.3 237.1 387.2 238.7 378.8 249C370.4 259.3 372 274.4 382.3 282.8C393.1 291.6 400 305 400 320C400 335 393.1 348.4 382.3 357.3C372 365.7 370.5 380.8 378.8 391.1C387.1 401.4 402.3 402.9 412.6 394.6C434.1 376.9 448 350.1 448 320C448 289.9 434.1 263.1 412.6 245.5z",fill:"#ffffff"}}),e>=25&&t.push({tag:"path",attributes:{d:"M473.1 171C462.8 162.6 447.7 164.2 439.3 174.5C430.9 184.8 432.5 199.9 442.8 208.3C475.3 234.7 496 274.9 496 320C496 365.1 475.3 405.3 442.8 431.8C432.5 440.2 431 455.3 439.3 465.6C447.6 475.9 462.8 477.4 473.1 469.1C516.3 433.9 544 380.2 544 320.1C544 260 516.3 206.3 473.1 171.1z",fill:"#ffffff"}}),e>=75&&t.push({tag:"path",attributes:{d:"M533.6 96.5C523.3 88.1 508.2 89.7 499.8 100C491.4 110.3 493 125.4 503.3 133.8C557.5 177.8 592 244.8 592 320C592 395.2 557.5 462.2 503.3 506.3C493 514.7 491.5 529.8 499.8 540.1C508.1 550.4 523.3 551.9 533.6 543.6C598.5 490.7 640 410.2 640 320C640 229.8 598.5 149.2 533.6 96.5z",fill:"#ffffff"}}),dt.createSVG(16,16,"0 0 640 640",t)},volumeMuted:()=>dt.createSVG(16,16,"0 0 640 640",[{tag:"path",attributes:{d:"M80 416L128 416L262.1 535.2C268.5 540.9 276.7 544 285.2 544C304.4 544 320 528.4 320 509.2L320 130.8C320 111.6 304.4 96 285.2 96C276.7 96 268.5 99.1 262.1 104.8L128 224L80 224C53.5 224 32 245.5 32 272L32 368C32 394.5 53.5 416 80 416zM399 239C389.6 248.4 389.6 263.6 399 272.9L446 319.9L399 366.9C389.6 376.3 389.6 391.5 399 400.8C408.4 410.1 423.6 410.2 432.9 400.8L479.9 353.8L526.9 400.8C536.3 410.2 551.5 410.2 560.8 400.8C570.1 391.4 570.2 376.2 560.8 366.9L513.8 319.9L560.8 272.9C570.2 263.5 570.2 248.3 560.8 239C551.4 229.7 536.2 229.6 526.9 239L479.9 286L432.9 239C423.5 229.6 408.3 229.6 399 239z",fill:"#ffffff"}}]),end:()=>dt.createSVG(16,16,"0 0 21 16",[{tag:"path",attributes:{d:"M17.7226 12.2992C18.3148 12.5423 18.991 12.308 19.307 11.7578L19.3954 11.6031C20.434 9.78662 20.2705 7.18344 18.2308 5.85533C13.5438 2.80798 7.45789 2.80798 2.77085 5.85533C0.726753 7.18344 0.567646 9.78662 1.60627 11.6031L1.69466 11.7578C2.01066 12.3125 2.68908 12.5445 3.2769 12.3014L6.32204 11.0462C6.83914 10.8341 7.15515 10.3059 7.0999 9.74684L6.90986 7.85081C9.2346 7.06853 11.7759 7.10831 14.0785 7.97456L13.8973 9.74684C13.8399 10.3037 14.1581 10.8297 14.6752 11.0462L17.7226 12.2992Z",fill:"red"}}])},ut=(e,t)=>{if("inactiveTimeout"===e){const e=t;return e?.enabled&&void 0!==e.duration&&e.duration>18e4&&(at.critical_warn(`Napster Companion API SDK: inactiveTimeout duration of ${e.duration}ms exceeds the recommended maximum of 180000ms. Setting maximum allowed value.`),delete e.duration),t}return t},mt={enabled:!1,batchSize:10,flushInterval:5e3,enablePerformanceTracking:!0,enableErrorTracking:!0,enableUserInteractionTracking:!0};class ht{constructor(e={}){Object.defineProperty(this,"config",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"eventQueue",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"performanceQueue",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"errorQueue",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"flushTimer",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"sessionId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"providers",{enumerable:!0,configurable:!0,writable:!0,value:[]}),this.config={...mt,...e},this.sessionId=this.config.sessionId||this.generateSessionId(),this.setupProviders(),this.config.enabled&&(this.startFlushTimer(),this.setupErrorTracking(),this.setupPerformanceTracking())}setupProviders(){this.providers=[],this.config.providers&&(this.providers=[...this.config.providers]),this.config.provider&&this.providers.push(this.config.provider),0===this.providers.length&&this.providers.push({type:"custom"})}generateSessionId(){return`session_${Date.now()}_${Math.random().toString(36).substr(2,9)}`}startFlushTimer(){this.flushTimer&&clearInterval(this.flushTimer),this.flushTimer=setInterval(()=>{this.flush()},this.config.flushInterval)}setupErrorTracking(){this.config.enableErrorTracking&&(window.addEventListener("error",e=>{this.trackError(e.error,{source:"window.error",filename:e.filename,lineno:e.lineno,colno:e.colno})}),window.addEventListener("unhandledrejection",e=>{this.trackError(new Error(e.reason),{source:"unhandledrejection",reason:e.reason})}))}setupPerformanceTracking(){this.config.enablePerformanceTracking&&"undefined"!=typeof window&&"performance"in window&&window.addEventListener("load",()=>{setTimeout(()=>{const e=performance.getEntriesByType("navigation")[0];e&&(this.trackPerformance("page_load_time",e.loadEventEnd-e.fetchStart,"ms"),this.trackPerformance("dom_content_loaded",e.domContentLoadedEventEnd-e.fetchStart,"ms"),this.trackPerformance("first_paint",e.responseEnd-e.fetchStart,"ms"))},0)})}trackEvent(e,t){if(!this.config.enabled)return;const n={name:e,properties:t,timestamp:Date.now(),userId:this.config.userId,sessionId:this.sessionId};this.eventQueue.push(n),this.eventQueue.length>=(this.config.batchSize||10)&&this.flush()}trackPerformance(e,t,n,o){if(!this.config.enabled||!this.config.enablePerformanceTracking)return;const i={name:e,value:t,unit:n,timestamp:Date.now(),context:o};this.performanceQueue.push(i)}trackError(e,t){if(!this.config.enabled||!this.config.enableErrorTracking)return;const n={error:e,context:t,timestamp:Date.now(),userId:this.config.userId,sessionId:this.sessionId,stack:e.stack};this.errorQueue.push(n),this.flushErrors()}trackInteraction(e,t,n){this.config.enableUserInteractionTracking&&this.trackEvent("user_interaction",{action:e,target:t,...n})}flush(){this.flushEvents(),this.flushPerformance(),this.flushErrors()}flushEvents(){if(0===this.eventQueue.length)return;const e=[...this.eventQueue];this.eventQueue=[],this.sendData("events",e)}flushPerformance(){if(0===this.performanceQueue.length)return;const e=[...this.performanceQueue];this.performanceQueue=[],this.sendData("performance",e)}flushErrors(){if(0===this.errorQueue.length)return;const e=[...this.errorQueue];this.errorQueue=[],this.sendData("errors",e)}async sendData(e,t){const n=this.providers.map(n=>this.sendToProvider(n,e,t));await Promise.allSettled(n)}async sendToProvider(e,t,n){try{switch(e.type){case"google-analytics-4":await this.sendToGA4(e,n);break;case"mixpanel":await this.sendToMixpanel(e,n);break;case"segment":await this.sendToSegment(e,n);break;case"amplitude":await this.sendToAmplitude(e,n);break;case"posthog":await this.sendToPostHog(e,n);break;case"azure-insights":await this.sendToAzureInsights(e,n);break;default:await this.sendToCustomEndpoint(e,t,n)}}catch(t){at.critical_warn(`Failed to send data to ${e.type}:`,t)}}async sendToCustomEndpoint(e,t,n){const o=e.endpoint,i=e.apiKey;if(!o)return;const a=await fetch(`${o}/${t}`,{method:"POST",headers:{"Content-Type":"application/json",...i&&{Authorization:`Bearer ${i}`}},body:JSON.stringify({data:n,sessionId:this.sessionId,timestamp:Date.now()})});if(!a.ok)throw new Error(`HTTP ${a.status}`)}async sendToGA4(e,t){const n=e.measurementId||e.apiKey;if(!n)throw new Error("GA4 measurement ID required");const o=`https://www.google-analytics.com/mp/collect?measurement_id=${n}&api_secret=${e.apiKey||"default"}`,i=t.map(e=>({name:e.name,params:{...e.properties,session_id:this.sessionId}}));await fetch(o,{method:"POST",body:JSON.stringify({client_id:this.sessionId,user_id:this.config.userId,events:i})})}async sendToMixpanel(e,t){const n=e.projectToken||e.apiKey;if(!n)throw new Error("Mixpanel project token required");const o=e.endpoint||"https://api.mixpanel.com/batch",i=t.map(e=>{const t=e;return{event:t.name,properties:{token:n,distinct_id:this.config.userId||this.sessionId,time:t.timestamp||Date.now(),...t.properties}}});await fetch(o,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(i)})}async sendToSegment(e,t){const n=e.writeKey||e.apiKey;if(!n)throw new Error("Segment write key required");const o=e.endpoint||"https://api.segment.io/v1/batch",i=t.map(e=>({type:"track",userId:this.config.userId||this.sessionId,event:e.name,properties:e.properties,timestamp:new Date(e.timestamp||Date.now()).toISOString()}));await fetch(o,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Basic ${btoa(n+":")}`},body:JSON.stringify({batch:i})})}async sendToAmplitude(e,t){const n=e.apiKey;if(!n)throw new Error("Amplitude API key required");const o=e.endpoint||"https://api2.amplitude.com/2/httpapi",i=t.map(e=>({user_id:this.config.userId||this.sessionId,event_type:e.name,event_properties:e.properties,time:e.timestamp||Date.now()}));await fetch(o,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({api_key:n,events:i})})}async sendToPostHog(e,t){const n=e.apiKey,o=e.endpoint||"https://app.posthog.com";if(!n)throw new Error("PostHog API key required");const i=t.map(e=>({event:e.name,properties:{...e.properties,distinct_id:this.config.userId||this.sessionId},timestamp:new Date(e.timestamp||Date.now()).toISOString()}));await fetch(`${o}/batch/`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({api_key:n,batch:i})})}async sendToAzureInsights(e,t){const n=e.apiKey;if(!n)throw new Error("Azure Application Insights instrumentation key required");const o=e.endpoint||"https://dc.services.visualstudio.com/v2/track",i=t.map(e=>{const t=e;return{name:"Microsoft.ApplicationInsights.Event",time:new Date(t.timestamp||Date.now()).toISOString(),iKey:n,data:{baseType:"EventData",baseData:{name:t.name,properties:t.properties}}}});await fetch(o,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(i)})}updateConfig(e){this.config={...this.config,...e},this.setupProviders(),this.config.enabled&&!this.flushTimer?this.startFlushTimer():!this.config.enabled&&this.flushTimer&&(clearInterval(this.flushTimer),this.flushTimer=void 0)}destroy(){this.flushTimer&&clearInterval(this.flushTimer),this.flush()}}let ft=null;const bt=(e,t)=>{ft?.trackEvent(e,t)},gt=(e,t,n)=>{ft?.trackInteraction(e,t,n)};function vt(e,t){void 0===t&&(t={});var n=t.insertAt;if(e&&"undefined"!=typeof document){var o=document.head||document.getElementsByTagName("head")[0],i=document.createElement("style");i.type="text/css","top"===n&&o.firstChild?o.insertBefore(i,o.firstChild):o.appendChild(i),i.styleSheet?i.styleSheet.cssText=e:i.appendChild(document.createTextNode(e))}}function _t(e,{content:t,placement:n="top"}){let o=!1,i=null,a=null;const r=e=>"left"===e?"start":"right"===e?"end":e,s=()=>{if(!i)return;const t=e.getBoundingClientRect(),o=i.getBoundingClientRect();let a=0,r=0;switch(n){case"top":a=t.top-o.height-8,r=t.left+(t.width-o.width)/2;break;case"bottom":a=t.bottom+8,r=t.left+(t.width-o.width)/2;break;case"left":a=t.top+(t.height-o.height)/2,r=t.left-o.width-8;break;case"right":a=t.top+(t.height-o.height)/2,r=t.right+8}i.style.top=`${a}px`,i.style.left=`${r}px`},c=()=>s(),l=()=>{if(o)return;const e=(()=>{if(i)return i;const e=document.createElement("div");e.className=`tooltip styled-tooltip bs-tooltip-${r(n)} show`,e.setAttribute("role","tooltip"),Object.assign(e.style,{position:"fixed",top:"0px",left:"0px",zIndex:String(2147483647),opacity:"0",visibility:"hidden",pointerEvents:"none",transition:"opacity 80ms ease"});const o=document.createElement("div");o.className="tooltip-arrow";const a=document.createElement("div");return a.className="tooltip-inner","string"==typeof t?a.textContent=t:a.appendChild(t),e.appendChild(o),e.appendChild(a),document.body.appendChild(e),i=e,e})();o=!0,s(),a=window.setTimeout(s,10),e.style.opacity="1",e.style.visibility="visible",window.addEventListener("scroll",c,!0),window.addEventListener("resize",c)},d=()=>{o&&(o=!1,null!=a&&(window.clearTimeout(a),a=null),i&&(i.style.opacity="0",i.style.visibility="hidden"),window.removeEventListener("scroll",c,!0),window.removeEventListener("resize",c))},p=()=>l(),u=()=>d();return e.addEventListener("mouseenter",p),e.addEventListener("mouseleave",u),e.matches?.(":hover")&&l(),{update:e=>{if(void 0!==e.content&&i){const t=i.querySelector(".tooltip-inner");t&&(t.innerHTML="","string"==typeof e.content?t.textContent=e.content:t.appendChild(e.content))}void 0!==e.placement&&(n=e.placement,i&&(i.className=`tooltip styled-tooltip bs-tooltip-${r(n)} show`)),o&&s()},show:l,hide:d,destroy:()=>{d(),e.removeEventListener("mouseenter",p),e.removeEventListener("mouseleave",u),i&&i.parentNode&&i.parentNode.removeChild(i),i=null}}}function yt(e,t){const n=document.createElement(e);return t&&(n.className=t),n}var wt,Ct,Et,St,xt,kt,Tt;vt(".np_companion-live-container,.np_companion-preview-container{height:100%;margin:0;padding:0;position:absolute;transition:opacity .3s ease-in-out;width:100%}.np_companion-preview-container{opacity:1;z-index:2}.np_companion-preview-container.np_companion-fade-out{opacity:0;pointer-events:none;transition:opacity .5s ease-out}.np_companion-live-container{opacity:0;z-index:1}.np_companion-live-container.np_companion-fade-in{opacity:1;z-index:3}"),vt(":root{--base-border-radius:10px;--base-gap:20px}*,:after,:before{-webkit-box-sizing:border-box;box-sizing:border-box}::-webkit-input-placeholder{color:hsla(0,0%,100%,.4)}::-moz-placeholder{color:hsla(0,0%,100%,.4)}:-ms-input-placeholder{color:hsla(0,0%,100%,.4)}:-moz-placeholder{color:hsla(0,0%,100%,.4)}a,input{outline:none}body,html{background-color:transparent;background:transparent;margin:0;padding:0;width:100%}.np_companion-hide{display:none!important}.np_companion-align-middle{align-items:center;display:flex;justify-content:center}.np_companion-align-between{align-items:center;display:flex;justify-content:space-between}.np_companion-align-end{align-items:center;display:flex;justify-content:flex-end}.np_companion-align-start{align-items:flex-start;display:flex;justify-content:flex-start}.np_companion__d-none{display:none!important}#np_companion-sdk-root.np_companion-container-fixed{height:500px;position:fixed;transition:all .3s ease-in-out;width:400px;z-index:9999}#np_companion-sdk-root.np_companion-container-fixed.np_companion-view-rectangle{height:400px;width:340px}#np_companion-sdk-root.np_companion-container-fixed.np_companion-view-silhouette{height:400px}#np_companion-sdk-root.np_companion-container-fixed.np_companion-view-round{height:360px;width:250px}#np_companion-sdk-root.np_companion-container-fixed.np_companion-view-round.np_companion_disclaimer-disabled{height:320px!important}#np_companion-sdk-root.np_companion-container-fixed.np_companion-bottom-right{bottom:0;right:0}#np_companion-sdk-root.np_companion-container-fixed.np_companion-bottom-left{bottom:0;left:0}#np_companion-sdk-root.np_companion-container-fixed.np_companion-bottom-center{bottom:0;left:50%;transform:translateX(-50%)}#np_companion-sdk-root.np_companion-container-fixed.np_companion-top-right{right:0;top:0}#np_companion-sdk-root.np_companion-container-fixed.np_companion-top-left{left:0;top:0}#np_companion-sdk-root.np_companion-container-fixed.np_companion-top-center{left:50%;top:0;transform:translateX(-50%)}#np_companion-sdk-root.np_companion-container-fixed.np_companion-center{left:50%;top:50%;transform:translate(-50%,-50%)}"),vt('.np_companion-avatar{height:100%;position:relative;width:100%}#np_companion-avatar-container{background:transparent;border-radius:var(--base-border-radius);height:100%;overflow:hidden;position:absolute;width:100%}#np_companion-avatar-container:not(.np_companion-view-silhouette){box-shadow:0 0 #0000,0 0 #0000,0 0 #0000,0 0 #0000,0 10px 15px -3px color-mix(in oklab,#00000080 100%,transparent),0 4px 6px -4px color-mix(in oklab,#00000080 100%,transparent)}.np_companion-avatar.np_companion-bg-transparent #np_companion-avatar-container.np_companion-view-silhouette{filter:drop-shadow(0 10px 15px rgba(0,0,0,.5)) drop-shadow(0 4px 6px rgba(0,0,0,.5))}.np_companion-container-fixed #np_companion-avatar-container.np_companion-view-round{border-radius:50%;height:212px;left:50%;transform:translate(-50%,12%);width:212px}.np_companion-container-fixed #np_companion-avatar-container.np_companion-view-rectangle,.np_companion-container-fixed #np_companion-avatar-container.np_companion-view-silhouette{left:50%;transform:translateX(-50%)}.np_companion-avatar-video{height:100%;inset:0;object-fit:cover;pointer-events:none;position:absolute;transition:opacity .3s ease-in-out;width:100%;z-index:10}.np_companion-avatar-video.no-opacity{opacity:0}.np_companion-avatar-canvas{background:transparent;height:100%;object-fit:cover;position:relative;width:100%;z-index:1}.np_companion-container-fixed #np_companion-avatar-container.np_companion-loader-pulse:after{animation:pulse 1.5s ease-in-out infinite;background-color:var(--np-loader-bg-color);border-radius:var(--base-border-radius);content:"";display:block;height:100%;left:0;opacity:.6;overflow:hidden;position:absolute;top:0;width:100%}.np_companion-avatar.np_companion-bg-transparent #np_companion-avatar-container:after{display:none}.np_companion-avatar:has(#np_companion-avatar-container.np_companion-view-round):after{display:none}#np_companion-avatar-container.np_companion-loader-pulse.loader-container.np_companion-view-round:after{animation:pulse 1.5s ease-in-out infinite;background-color:var(--np-loader-bg-color);border-radius:50%;content:"";display:block;height:100%;left:0;opacity:.6;overflow:hidden;position:absolute;top:0;width:100%}.np_companion-avatar.np_companion-bg-transparent #np_companion-avatar-container.np_companion-view-round:after{display:none}@keyframes pulse{0%,to{opacity:.5}50%{opacity:.2}}.np_companion-disclaimer-text{-webkit-box-orient:vertical;-webkit-line-clamp:2;line-clamp:2;color:#fff;font-size:10px;line-height:12px;margin:auto auto 16px;max-width:940px;opacity:.7;overflow:hidden;padding:0 16px;text-align:center;z-index:12}.np_companion-disclaimer-text a{color:#fff}.np_companion-disclaimer-text a:hover{color:#fff;text-decoration:underline}.np_companion-disclaimer-text a:focus,.np_companion-disclaimer-text a:visited{color:#fff}.np_companion-action-btn-container-wrapper{pointer-events:auto;width:100%}.np_companion-avatar-control-container{backdrop-filter:blur(19px);background:none;background-color:rgba(52,51,51,.6);border-radius:16px;bottom:0;box-shadow:0 4px 4px 0 rgba(0,0,0,.25),2px 2px 8px 0 rgba(0,0,0,.12);left:50%;max-width:90%;min-width:210px;opacity:1;position:absolute;transform:translateX(-50%);transition:opacity .4s cubic-bezier(.4,0,.2,1);z-index:99}.np_companion-avatar-control-container.np_companion-action-btn-container-collapse{opacity:0}.np_companion-avatar-control-container:not(.np_companion-avatar-control-view-round){bottom:16px}.np_companion-avatar:not(.np_companion-bg-transparent) .np_companion-loader-spinner:not(.np_companion-view-silhouette){backdrop-filter:blur(19px);background-color:color-mix(in oklab,var(--np-loader-bg-color) 100%,transparent)!important;filter:none!important;height:100%;width:100%}.np_companion-loader-spinner .loader-container{left:50%;position:absolute;top:50%;transform:translate(-50%,-50%)}.np_companion-loader-spinner .loader-container .loader{--_m:conic-gradient(#0000 10%,#000),linear-gradient(#000 0 0) content-box;animation:l3 1s linear infinite;aspect-ratio:1;background:var(--np-loader-color);border-radius:50%;-webkit-mask:var(--_m);mask:var(--_m);-webkit-mask-composite:source-out;mask-composite:subtract;padding:4px;width:24px}@keyframes l3{to{transform:rotate(1turn)}}.np_companion-loader-spinner.np_companion-view-round .loader-container .loader{padding:4px;width:212px}.np_companion-bg-transparent .np_companion-loader-spinner .loader-container{display:none}'),vt(".np_companion-controls-container{align-items:center;background:hsla(0,0%,100%,.3);border:.5px solid #fff;border-radius:12px;bottom:20px;box-shadow:0 1px 1px rgba(0,0,0,.267),0 2px 5px rgba(0,0,0,.267),0 3px 8px rgba(0,0,0,.267);display:flex;gap:8px;left:50%;max-width:360px;pointer-events:auto;position:absolute;transform:translateX(-50%);transform-origin:bottom center;transition:width .3s ease-in-out;-webkit-user-select:none;-moz-user-select:none;user-select:none;width:auto;z-index:99}.np_companion-controls-container.collapsed{gap:0}.np_companion-time-running{color:#fff}.np_companion-controls-time-action-btn-container{align-items:center;background:hsla(0,0%,100%,.1);border-radius:8px;display:flex;filter:grayscale(1);flex-shrink:0;gap:8px;height:32px;padding-left:8px;padding-right:8px;transition:filter .3s ease}.np_companion-controls-mic-control,.np_companion-controls-stop-control{cursor:pointer;display:flex;margin:0 5px;overflow:hidden;transition:opacity .3s ease-in-out,width .3s ease-in-out;width:47px}.np_companion-controls-mic-control.visible,.np_companion-controls-stop-control.visible{opacity:1}.np_companion-controls-mic-control.visible{width:1em}.np_companion-controls-stop-control.visible{width:1.5em}.np_companion-controls-mic-control.hidden,.np_companion-controls-stop-control.hidden{margin:0;opacity:0;padding:0;pointer-events:none;width:0}.np_companion-controls-mic-control:hover svg path{fill:red}.np_companion-controls-stop-control{display:flex;margin:0 5px 0 0}.np_companion-controls-stop-control:hover svg .stop-circle{fill:red}.np_companion-controls-stop-control:hover svg .stop-square{fill:#fff}.np_companion-mic-dropdown{background:#2b2c32;border-radius:4px;border-radius:6px;bottom:35px;box-shadow:0 10px 15px -3px rgba(0,0,0,.2),0 4px 6px -4px rgba(0,0,0,.2),0 0 0 1px #46464d;color:#fff;font-size:14px;list-style-type:none;margin:0;max-height:200px;min-width:300px;overflow-y:auto;overflow:auto;padding:5px;pointer-events:auto;position:absolute;width:auto;z-index:1000}.np_companion-mic-dropdown li{cursor:pointer;padding:8px 12px}.np_companion-mic-dropdown li:hover{background-color:#000}.np_companion-action-btn-container-container{background:transparent;border-radius:80px;gap:8px;padding:16px 16px 12px;transition:all .3s ease-in-out}.np_companion-action-btn-container-container.np_companion_disclaimer-disabled{padding-bottom:16px}.np_companion-action-btn-container-container .np_companion-chat-question-bar-container{border-radius:16px;gap:8px}.np_companion-action-btn-container-container .np_companion-action-btn-container-left{transition:all .3s ease-in-out;width:40px}.np_companion-action-btn-container-container .np_companion-action-btn-container-icon{border-radius:80px;cursor:pointer;height:40px;transition:all .3s ease-in-out;width:40px}.np_companion-dark-grey-bg{background:linear-gradient(0deg,#5e5e5e14 0 100%),#ffffff0f}.np_companion-grey-bg{background:linear-gradient(0deg,rgba(94,94,94,.07),rgba(94,94,94,.07)),hsla(0,0%,100%,.04)}.np_companion-action-btn-container-container .np_companion-action-btn-container-icon svg{height:auto;width:22px}.np_companion-action-btn-container-container .np_companion-action-btn-container-icon.muted svg.np_companion-mic-muted,.np_companion-action-btn-container-container .np_companion-action-btn-container-icon:not(.muted) svg.np_companion-mic-unmuted{display:flex}.np_companion-action-btn-container-container .np_companion-action-btn-container-middle .np_companion-action-btn-container-wave{display:flex;min-width:160px}.np_companion-action-btn-container-container .np_companion-action-btn-container-middle .np_companion-action-btn-container-wave canvas{height:40px;width:100%}.np_companion-action-btn-container-container .np_companion-action-btn-container-right{gap:8px;transition:all .3s ease-in-out}.np_companion-action-btn-container-container .np_companion-action-btn-container-left .np_companion-action-btn-container-icon:hover,.np_companion-action-btn-container-container .np_companion-action-btn-container-right .np_companion-action-btn-container-icon.active,.np_companion-action-btn-container-container .np_companion-action-btn-container-right .np_companion-action-btn-container-icon:hover{background-color:#fff!important}.np_companion-action-btn-container-container .np_companion-action-btn-container-left .np_companion-action-btn-container-icon:not(.np_companion-persist-fill-color):hover svg path{fill:#000}.np_companion-action-btn-container-container .np_companion-action-btn-container-right .np_companion-action-btn-container-icon.np_companion-action-btn-container-call-end svg{height:auto;width:16px}.np_companion-action-btn-container-container .np_companion-action-btn-container-right .np_companion-action-btn-container-icon:not(.np_companion-persist-fill-color).np_companion-action-btn-container-call-end:hover svg path{stroke:#000}.np_companion-action-btn-container-container .np_companion-action-btn-container-right .np_companion-action-btn-container-icon:not(.np_companion-persist-fill-color).active svg path,.np_companion-action-btn-container-container .np_companion-action-btn-container-right .np_companion-action-btn-container-icon:not(.np_companion-persist-fill-color).np_companion-action-btn-container-toggle:hover svg path,.np_companion-action-btn-container-container .np_companion-action-btn-container-right .np_companion-action-btn-container-icon:not(.np_companion-persist-fill-color):hover svg path{fill:#000}.np_companion-mobile-mode{bottom:15px;scale:.7}.np_companion-mobile-mode .np_companion-action-btn-container-container .np_companion-action-btn-container-middle{display:none}.np_companion-mobile-mode .np_companion-action-btn-container-left{opacity:1;width:40px}.np_companion-mobile-mode .np_companion-action-btn-container-right{opacity:1}"),vt('.tooltip{word-wrap:break-word;display:block;font-family:-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Helvetica Neue,Arial,sans-serif;font-size:.875rem;font-style:normal;font-weight:400;letter-spacing:normal;line-break:auto;line-height:1.5;margin:0;opacity:0;position:absolute;text-align:left;text-decoration:none;text-shadow:none;text-transform:none;white-space:normal;word-break:normal;word-spacing:normal;z-index:1080}.tooltip.show{opacity:.9}.tooltip .tooltip-arrow{display:block;height:.4rem;position:absolute;width:.8rem}.tooltip .tooltip-arrow:before{border-color:transparent;border-style:solid;content:"";position:absolute}.bs-tooltip-auto[data-popper-placement^=top],.bs-tooltip-top{padding:0}.bs-tooltip-auto[data-popper-placement^=top] .tooltip-arrow,.bs-tooltip-top .tooltip-arrow{bottom:-.4rem;left:50%;transform:translateX(-50%)}.bs-tooltip-auto[data-popper-placement^=top] .tooltip-arrow:before,.bs-tooltip-top .tooltip-arrow:before{border-top-color:#000;border-width:.4rem .4rem 0;top:0}.bs-tooltip-auto[data-popper-placement^=right],.bs-tooltip-end{padding:0}.bs-tooltip-auto[data-popper-placement^=right] .tooltip-arrow,.bs-tooltip-end .tooltip-arrow{height:.8rem;left:-.4rem;top:50%;transform:translateY(-50%);width:.4rem}.bs-tooltip-auto[data-popper-placement^=right] .tooltip-arrow:before,.bs-tooltip-end .tooltip-arrow:before{border-right-color:#000;border-width:.4rem .4rem .4rem 0;right:0}.bs-tooltip-auto[data-popper-placement^=bottom],.bs-tooltip-bottom{padding:0}.bs-tooltip-auto[data-popper-placement^=bottom] .tooltip-arrow,.bs-tooltip-bottom .tooltip-arrow{left:50%;top:-.4rem;transform:translateX(-50%)}.bs-tooltip-auto[data-popper-placement^=bottom] .tooltip-arrow:before,.bs-tooltip-bottom .tooltip-arrow:before{border-bottom-color:#000;border-width:0 .4rem .4rem;bottom:0}.bs-tooltip-auto[data-popper-placement^=left],.bs-tooltip-start{padding:0}.bs-tooltip-auto[data-popper-placement^=left] .tooltip-arrow,.bs-tooltip-start .tooltip-arrow{height:.8rem;right:-.4rem;top:50%;transform:translateY(-50%);width:.4rem}.bs-tooltip-auto[data-popper-placement^=left] .tooltip-arrow:before,.bs-tooltip-start .tooltip-arrow:before{border-left-color:#000;border-width:.4rem 0 .4rem .4rem;left:0}.tooltip-inner{background-color:#000;border-radius:.25rem;color:#fff;max-width:200px;padding:.25rem .5rem;text-align:center}.styled-tooltip{z-index:99999}.styled-tooltip .tooltip-inner{background-color:#fff;border-radius:.375rem;box-shadow:0 .5rem 1rem rgba(0,0,0,.15);color:#3f4254;display:block;font-size:14px;max-width:300px;padding:10px 14px}.styled-tooltip.bs-tooltip-auto[data-popper-placement^=top] .tooltip-arrow:before,.styled-tooltip.bs-tooltip-top .tooltip-arrow:before{border-top-color:#fff}.styled-tooltip.bs-tooltip-auto[data-popper-placement^=right] .tooltip-arrow:before,.styled-tooltip.bs-tooltip-end .tooltip-arrow:before{border-right-color:#fff}.styled-tooltip.bs-tooltip-auto[data-popper-placement^=bottom] .tooltip-arrow:before,.styled-tooltip.bs-tooltip-bottom .tooltip-arrow:before{border-bottom-color:#fff}.styled-tooltip.bs-tooltip-auto[data-popper-placement^=left] .tooltip-arrow:before,.styled-tooltip.bs-tooltip-start .tooltip-arrow:before{border-left-color:#fff}'),vt(".np_volume-control{align-items:center;display:inline-flex;flex-direction:column;gap:12px;position:relative;z-index:1000}.np_volume-slider-container{background:#6565652e;border-radius:8px;bottom:52px;opacity:0;padding:8px;pointer-events:none;position:absolute;transform:translateY(10px);transition:all .3s ease;visibility:hidden;z-index:1001}.np_volume-control .np_volume-slider-container.np_volume-slider-visible,.np_volume-slider-container:hover{opacity:1;pointer-events:all;transform:translateY(0);visibility:visible}.np_volume-slider-track{backdrop-filter:blur(10px);background:rgba(0,0,0,.4);border:1px solid hsla(0,0%,100%,.3);border-radius:4px;box-shadow:0 2px 8px rgba(0,0,0,.15);cursor:pointer;height:120px;position:relative;width:8px}.np_volume-slider-fill{background:linear-gradient(0deg,hsla(0,0%,100%,.9),hsla(0,0%,100%,.7));border-radius:4px;bottom:0;height:50%;left:0;pointer-events:none;position:absolute;right:0;transition:height .1s ease}.np_volume-slider-thumb{background:#fff;border-radius:50%;bottom:50%;box-shadow:0 2px 6px rgba(0,0,0,.3);cursor:grab;height:16px;left:50%;pointer-events:none;position:absolute;transform:translate(-50%,50%);transition:bottom .1s ease;width:16px}.np_volume-slider-thumb:active{cursor:grabbing;transform:translate(-50%,50%) scale(1.1)}.np_volume-slider-track:hover .np_volume-slider-thumb{transform:translate(-50%,50%) scale(1.15)}@media (max-width:768px){.np_volume-slider-track{height:100px}.np_volume-slider-container{bottom:70px}}"),vt('.np_companion-inactive-overlay{align-items:center;bottom:0;display:flex;justify-content:center;left:0;pointer-events:auto;position:absolute;right:0;top:0;z-index:9999}.np_companion-inactive-dialog{backdrop-filter:blur(19px);background:hsla(0,0%,50%,.3);background-blend-mode:luminosity;border-radius:16px;max-width:500px;overflow:hidden;padding:24px 16px;position:relative;text-align:center;width:100%}.np_companion-inactive-dialog:before{background:linear-gradient(180deg,hsla(0,0%,100%,.4),hsla(0,0%,100%,0),hsla(0,0%,100%,0),hsla(0,0%,100%,.1));border-radius:16px;content:"";inset:0;-webkit-mask:linear-gradient(#fff 0 0) content-box,linear-gradient(#fff 0 0);-webkit-mask-composite:destination-out;mask-composite:exclude;padding:1.473px;pointer-events:none;position:absolute}.np_companion-inactive-message{color:#fff;font-size:16px;line-height:1.5;margin-bottom:24px;margin-top:0}.np_companion-inactive-timer{display:flex;justify-content:center;margin:24px 0}.np_companion-timer-circle{align-items:center;display:flex;height:80px;justify-content:center;position:relative;width:80px}.np_companion-timer-circle svg{overflow:visible;transform:rotate(-90deg)}.np_companion-timer-circle path{transition:stroke-dasharray .3s ease}.np_companion-timer-number{color:#fff;font-size:24px;font-weight:500;position:absolute}.np_companion-inactive-buttons{display:flex;gap:12px;justify-content:center}.np_companion-inactive-buttons button{border:none;border-radius:8px;cursor:pointer;font-size:14px;font-weight:500;padding:12px 24px;transition:all .2s ease}.np_companion-end-button{background:hsla(0,0%,100%,.1);color:#fff}.np_companion-end-button:hover{background:hsla(0,0%,100%,.2)}.np_companion-continue-button{background:#3c19cd;color:#fff}.np_companion-continue-button:hover{background:#2f13a0}'),function(e){e.LOCAL_TIMEOUT="local_timeout",e.SERVER_WARNING="server_warning"}(wt||(wt={}));class It{constructor(e,t={}){Object.defineProperty(this,"overlayController",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"currentTrigger",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"isVisible",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"mountElement",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"callbacks",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.mountElement=e,this.callbacks=t}show(e){this.isVisible?at.warn("Inactive overlay already visible, ignoring show request"):(at.info(`Showing inactive overlay (trigger: ${e.type})`),this.currentTrigger=e,this.isVisible=!0,this.overlayController=function(e,t){const n={duration:t.duration??30,isInteractionNeeded:t.isInteractionNeeded??!1,message:t.message??"It looks like you've been inactive for a while. Would you like to continue this conversation?",onContinue:t.onContinue,onEnd:t.onEnd},o=document.createElement("div");o.className="np_companion-inactive-overlay";const i=document.createElement("div");i.className="np_companion-inactive-dialog";const a=document.createElement("p");a.className="np_companion-inactive-message",a.textContent=n.message;const r=document.createElement("div");r.className="np_companion-inactive-timer";const s=document.createElement("div");s.className="np_companion-timer-circle";const c=document.createElementNS("http://www.w3.org/2000/svg","svg");c.setAttribute("viewBox","0 0 36 36");const l=document.createElementNS("http://www.w3.org/2000/svg","path");l.setAttribute("d","M18 2.0845 a 15.9155 15.9155 0 0 1 0 31.831 a 15.9155 15.9155 0 0 1 0 -31.831"),l.setAttribute("fill","none"),l.setAttribute("stroke","rgba(255, 255, 255, 0.2)"),l.setAttribute("stroke-width","2");const d=document.createElementNS("http://www.w3.org/2000/svg","path");d.setAttribute("d","M18 2.0845 a 15.9155 15.9155 0 0 1 0 31.831 a 15.9155 15.9155 0 0 1 0 -31.831"),d.setAttribute("fill","none"),d.setAttribute("stroke","#fff"),d.setAttribute("stroke-width","2");const p=document.createElement("span");p.className="np_companion-timer-number",s.appendChild(c),c.appendChild(l),c.appendChild(d),s.appendChild(p),r.appendChild(s);const u=document.createElement("div");u.className="np_companion-inactive-buttons";const m=document.createElement("button");m.className="np_companion-end-button np_companion__d-none",m.textContent="End Conversation";let h=null;const f=e=>{e&&!h?(h=document.createElement("button"),h.className="np_companion-continue-button",h.textContent="Continue Talking",u.appendChild(h),h.addEventListener("click",n.onContinue)):!e&&h&&(h.removeEventListener("click",n.onContinue),h.parentNode&&h.parentNode.removeChild(h),h=null)};u.appendChild(m),f(n.isInteractionNeeded),i.appendChild(a),i.appendChild(r),i.appendChild(u),o.appendChild(i),e.appendChild(o);let b=Math.max(0,Math.floor(n.duration)),g=null;const v=()=>{p.textContent=String(b),d.setAttribute("stroke-dasharray",(n.duration>0?b/n.duration*100:0)+", 100")},_=()=>{if(b<=0)return w(),void n.onEnd();b-=1,v()},y=()=>{w(),v(),g=window.setInterval(_,1e3)},w=()=>{null!=g&&(window.clearInterval(g),g=null)};return m.addEventListener("click",()=>{w(),n.onEnd()}),y(),{update:e=>{if(void 0!==e.message&&(n.message=e.message,a.textContent=n.message),void 0!==e.isInteractionNeeded&&(n.isInteractionNeeded=!!e.isInteractionNeeded,f(n.isInteractionNeeded)),void 0!==e.duration){const t=Math.max(0,Math.floor(e.duration));n.duration=t,b=t,y()}e.onContinue&&(h&&(h.removeEventListener("click",n.onContinue),h.addEventListener("click",e.onContinue)),n.onContinue=e.onContinue),e.onEnd&&(n.onEnd=e.onEnd)},destroy:()=>{w(),m.removeEventListener("click",n.onEnd),h&&h.removeEventListener("click",n.onContinue),o.parentNode&&o.parentNode.removeChild(o)}}}(this.mountElement,{duration:e.duration,message:e.message,isInteractionNeeded:e.isInteractionNeeded,onContinue:()=>this.handleContinue(),onEnd:()=>this.handleEnd()}),this.callbacks.onShow?.(e))}hide(){this.isVisible&&(at.info("Hiding inactive overlay"),this.isVisible=!1,this.currentTrigger=null,this.overlayController&&(this.overlayController.destroy(),this.overlayController=null),this.callbacks.onHide?.())}isShowing(){return this.isVisible}getCurrentTrigger(){return this.currentTrigger}handleContinue(){at.info("User clicked continue on inactive overlay"),this.hide(),this.callbacks.onContinue?.()}handleEnd(){at.info("Inactive overlay countdown ended"),this.hide(),this.callbacks.onEnd?.()}destroy(){this.hide()}}!function(e){e.TALK_STATE_CHANGED="talk_state_changed",e.MESSAGE_RECEIVED="message_received",e.TRANSCRIPT="transcript",e.AUDIO_TRANSCRIPT_DELTA="response.audio_transcript.delta",e.AUDIO_TRANSCRIPT_DONE="response.audio_transcript.done",e.RESPONSE_DONE="response.done"}(Ct||(Ct={})),function(e){e.STARTED="started",e.ENDED="ended",e.CANCELED="canceled"}(Et||(Et={})),function(e){e.DELTA="delta",e.COMPLETED="completed"}(St||(St={})),function(e){e.USER="user",e.ASSISTANT="assistant"}(xt||(xt={})),function(e){e.SET_REMOTE_DESCRIPTION="set_remote_description",e.SET_LOCAL_DESCRIPTION="set_local_description",e.ADD_ICE_CANDIDATE="add_ice_candidate",e.ERROR="error"}(kt||(kt={})),function(e){e.SEND_QUESTION="send_question",e.CANCEL="cancel"}(Tt||(Tt={}));const Nt={iceServers:[{urls:"stun:stun1.ciscape.com:3478"},{urls:"turn:stun1.ciscape.com:3478",username:"tcuser",credential:"dw4k_BR2f-Y4A-@aT7ip@Qzs"},{urls:"stun:129.146.43.226:3478"},{urls:"stun:stun.l.google.com:19302"},{urls:"stun:stun1.l.google.com:19302"},{urls:"turn:129.146.43.226:3478",username:"teamtime_turn",credential:"teamtime"}]};function Ot(e,t){if(t)for(const n in t)try{const o=t[n];"string"!=typeof o&&"number"!=typeof o||(e.style[n]=o)}catch{at.warn(`Failed to apply style for key "${n}: ${t[n]}".`)}}function At(e,t,n){const o=[];return o.push("np_companion-align-middle"),e&&(o.push("np_companion-container-fixed"),o.push(`np_companion-${e}`),t&&o.push(`np_companion-view-${t}`)),n&&o.push(n),o.join(" ")}class Rt{constructor(){Object.defineProperty(this,"version",{enumerable:!0,configurable:!0,writable:!0,value:"1.0.0-alpha.12"}),Object.defineProperty(this,"mountTarget",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"rootEl",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"embed",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"webrtcController",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"config",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"isInitialized",{enumerable:!0,configurable:!0,writable:!0,value:!1})}static getInstance(){return Rt.instance||(Rt.instance=new Rt),Rt.instance}renderApp(){this.mountTarget&&this.config&&(this.rootEl||(this.rootEl=document.createElement("div"),this.rootEl.id="np_companion-sdk-root",this.mountTarget.appendChild(this.rootEl)),this.rootEl.className=At(this.config.position,this.config.avatarStyle?.view,this.config.className),Ot(this.rootEl,this.config.style),this.embed?this.embed.update({avatarStyle:this.config.avatarStyle,features:ot.getState().app.features,onData:this.config.onData,onAvatarReady:this.config.onAvatarReady,onInactivityStatusChange:this.config.onInactivityStatusChange,onDestroy:()=>this.destroyInstance("ui_end"),onError:this.config.onError}):this.embed=function(e,t={}){const n=ct.createDiv("np_companion-live-container np_companion-fade-in");e.appendChild(n);const o=function(e,t={}){const n=ct.createDiv("np_companion-avatar"),o=ct.createDiv(`np_companion-avatar-container np_companion-loader-${t.features?.showSDKLoader?.type??"spinner"}`);o.id="np_companion-avatar-container",t.avatarStyle?.view&&o.classList.add(`np_companion-view-${t.avatarStyle.view}`);const i=ct.createDiv("loader-container"),a=ct.createDiv("loader");i.appendChild(a);const r=ct.createVideo({className:"np_companion-avatar-video",autoplay:!0,muted:!0,playsInline:!0}),s=ct.createAudio({className:"np_companion-avatar-audio",autoplay:!0}),c=ct.createCanvas({className:"np_companion-avatar-canvas",styles:{width:"100%",height:"100%",objectFit:"cover",position:"relative",zIndex:"1"}});t.features?.backgroundRemoval?.enabled&&"silhouette"===t.avatarStyle?.view?r.classList.add("np_companion__d-none"):c.classList.add("np_companion__d-none"),o.appendChild(i),o.appendChild(r),o.appendChild(s),o.appendChild(c);const l=ct.createDiv(`${st.wrapper} np_companion-action-btn-container-view-${t.avatarStyle?.view}`),d=ct.createDiv(`np_companion-disclaimer-text np_companion-disclaimer-view-${t.avatarStyle?.view}`);d.style.display="none";const p=ct.createDiv(`np_companion-avatar-control-container np_companion-avatar-control-view-${t.avatarStyle?.view}`);p.appendChild(l),p.appendChild(d),n.appendChild(o),n.appendChild(p),e.appendChild(n);let u=null,m=(t.features?.backgroundRemoval?.enabled&&"silhouette"===t.avatarStyle?.view)??!1,h=null,f=null,b=!1,g=!1,v=!1,_=!0,y=null,w=null,C=null;const E=new It(n,{onContinue:()=>{D();const e=t.features?.inactiveTimeout;e?.enabled&&L()},onEnd:()=>{}});let S=null;const x=()=>{_||(_=!0,p.className=T(),null!=y&&window.clearTimeout(y))},k=()=>{null!=y&&window.clearTimeout(y),y=window.setTimeout(()=>{_=!1,p.className=T()},5e3)};function T(){return rt(`np_companion-avatar-control-container np_companion-avatar-control-view-${t.avatarStyle?.view}`,{[st.collapse]:!_})}function I(e){if(!v)return;const n=t.avatarStyle?.borderWidth??("silhouette"!==t.avatarStyle?.view?"4px":void 0);n&&(o.style.borderWidth=n);const i=("silhouette"!==t.avatarStyle?.view?e?"#ec3e41":t.avatarStyle?.borderColor??"#C0C0C0":void 0)??t.avatarStyle?.borderColor;i&&(o.style.borderColor=i);const a=t.avatarStyle?.borderStyle??("silhouette"!==t.avatarStyle?.view?"solid":void 0);a&&(o.style.borderStyle=a)}function N(e){"round"===t.avatarStyle?.view&&(o.style.transform=`translate(-50%, ${e??352-p.offsetHeight-212-12+"px"})`)}function O(){const e=t.features?.disclaimer?.enabled??!1;d.style.display=e&&v?"-webkit-box":"none",w?.update({features:{disclaimer:{enabled:e}}});const n=t.features?.disclaimer?.text??"This is an AI avatar. Check important info.";t.features?.disclaimer?.color&&(d.style.color=t.features?.disclaimer?.color),d.textContent=n,v&&N(e?void 0:"8%")}function A(){v||!t.features?.showSDKLoader?.enabled?n.classList.add("np_companion-bg-transparent"):n.classList.remove("np_companion-bg-transparent")}function R(){t.features?.showSDKLoader?.bgColor&&n.style.setProperty("--np-loader-bg-color",t.features.showSDKLoader.bgColor),t.features?.showSDKLoader?.color&&n.style.setProperty("--np-loader-color",t.features.showSDKLoader.color)}function D(){C&&(at.timer("Resetting inactive timeout due to activity"),clearTimeout(C),C=null,ot.dispatch(Ue(!1)),t.onInactivityStatusChange?.(!1))}function L(){const e=t.features?.inactiveTimeout;e?.enabled?(D(),C=setTimeout(()=>{at.timer(`Inactive timeout of ${e?.duration}ms reached, showing inactive overlay`),ot.dispatch(Ue(!0)),t.onInactivityStatusChange?.(!0),u&&(u.getAudioTracks().forEach(e=>e.enabled=!1),w?.update({isMuted:!0}),I(!0)),E.isShowing()||E.show({type:wt.LOCAL_TIMEOUT,duration:Math.min(e.countdown??30,60),message:void 0,isInteractionNeeded:!0})},e.duration)):(D(),E.isShowing()&&E.hide())}function P(){if(!w&&v){const e=!1;w=function(e,t){let n={...t},o=null,i=null,a=[],r=!1;const s=document.createElement("div");s.className=E();const c=yt("div",st.container),l=yt("div",rt(st.questionBar,st.alignBetween)),d=yt("div",st.left),p=yt("div",st.iconButtonWithState(n.isMuted));p.appendChild(n.isMuted?pt.micMuted():pt.micUnmuted()),n.toggleMute&&p.addEventListener("click",()=>n.toggleMute?.());const u=yt("div",st.middle),m=yt("div",st.wave);S();const h=document.createElement("canvas");h.width=160,h.height=40,h.className=st.canvas,m.appendChild(h);const f=yt("div",rt(st.right,st.alignBetween)),b=yt("div",rt(st.iconButton(),st.stop)),g=function(e,t={}){let n={initialVolume:50,...t},o=n.initialVolume??50,i=!1,a=!1;const r=document.createElement("div");r.className="np_volume-control";const s=document.createElement("div");s.className="np_volume-slider-container";const c=document.createElement("div");c.className="np_volume-slider-track";const l=document.createElement("div");l.className="np_volume-slider-fill";const d=document.createElement("div");d.className="np_volume-slider-thumb",c.appendChild(l),c.appendChild(d),s.appendChild(c);const p=document.createElement("div");function u(){let e;p.innerHTML="",e=i||0===o?pt.volumeMuted():pt.volumeHigh(o||100),p.appendChild(e)}function m(){const e=o;l.style.height=`${e}%`,d.style.bottom=`${e}%`}function h(){a=!a,a?s.classList.add("np_volume-slider-visible"):s.classList.remove("np_volume-slider-visible")}function f(e){const t=c.getBoundingClientRect(),a=Math.max(0,Math.min(100,(t.bottom-e)/t.height*100));o=a,m(),i=0===o,i?p.classList.add("np_volume-muted"):p.classList.remove("np_volume-muted"),u(),n.onChange?.(o)}p.className=st.iconButton(),p.setAttribute("aria-label","Volume control"),u(),r.appendChild(s),r.appendChild(p),e.appendChild(r),p.addEventListener("click",e=>{e.stopPropagation(),i=!i,i?(n.initialVolume=o,o=0,m(),p.classList.add("np_volume-muted")):(o=n.initialVolume||50,m(),p.classList.remove("np_volume-muted")),u(),n.onMuteToggle?.(i)}),r.addEventListener("mouseenter",e=>{e.stopPropagation(),a||h()}),r.addEventListener("mouseleave",e=>{setTimeout(()=>{e.stopPropagation(),a&&h()},300)});let b=!1;return c.addEventListener("mousedown",e=>{b=!0,f(e.clientY),e.preventDefault()}),document.addEventListener("mousemove",e=>{b&&f(e.clientY)}),document.addEventListener("mouseup",()=>{b=!1}),d.addEventListener("mousedown",e=>{b=!0,e.preventDefault()}),c.addEventListener("touchstart",e=>{b=!0,f(e.touches[0].clientY),e.preventDefault()}),document.addEventListener("touchmove",e=>{b&&e.touches.length>0&&f(e.touches[0].clientY)}),document.addEventListener("touchend",()=>{b=!1}),document.addEventListener("click",e=>{a&&!r.contains(e.target)&&h()}),m(),{setVolume(e){o=Math.max(0,Math.min(100,e)),m(),u(),n.onChange?.(o)},getVolume:()=>o,toggleMute(){i=!i,i?p.classList.add("np_volume-muted"):p.classList.remove("np_volume-muted"),n.onMuteToggle?.(i)},isMuted:()=>i,update(e){n={...n,...e}},destroy(){r.remove()}}}(b,{initialVolume:50,onChange:e=>{n.onVolumeChange?.(e)},onMuteToggle:e=>{n.onVolumeChange?.(e?0:g.getVolume())}});g.setVolume(70);const v=yt("div",st.iconButtonEnd());v.appendChild(pt.end()),n.handleEnd&&v.addEventListener("click",()=>n.handleEnd?.()),d.appendChild(p),u.appendChild(m),f.appendChild(b),f.appendChild(v),l.appendChild(d),l.appendChild(f),c.appendChild(l),s.appendChild(c),e.appendChild(s);let _=null,y=null,w=null;function C(){if(!n.userMicrophoneStream)return;const e=new(window.AudioContext||window.webkitAudioContext);o=e.createAnalyser(),e.createMediaStreamSource(n.userMicrophoneStream).connect(o),function(e){if(!o)return;const t=h.getContext("2d");if(!t)return;o.fftSize=256;const n=new Uint8Array(o.frequencyBinCount),s=Math.floor(h.width/3);0===a.length&&(a=new Array(s).fill(0));let c=0;const l=()=>{if(t.clearRect(0,0,h.width,h.height),t.beginPath(),t.moveTo(0,h.height/2),t.lineTo(h.width,h.height/2),t.strokeStyle="#ffffff",t.stroke(),e)r=!1,a.fill(0),S();else{o.getByteFrequencyData(n);const e=6,i=3,s=n.reduce((e,t)=>e+t,0)/n.length/255*h.height*.8;a.shift(),a.push(s);let l=a.filter(t=>t>e).length>=i;l?c=30:c>0&&(c--,l=!0),r=l,S(),t.fillStyle="#ffffff";for(let e=0;e<a.length;e++){const n=3*e,o=a[e];t.fillRect(n,h.height/2-o/2,2,o),t.fillRect(n,h.height/2+o/2,2,-o)}}i=requestAnimationFrame(l)};l()}(!!n.isMuted)}function E(){return rt(st.alignMiddle,`np_companion-avatar-${n.avatarStyle?.view}`)}function S(){m.style.filter=!n.isMuted&&r?"brightness(0) saturate(100%) invert(48%) sepia(93%) saturate(1720%) hue-rotate(346deg) brightness(101%) contrast(103%)":"none",m.style.transition="filter 0.3s ease",m.style.height="40px"}function x(){_?.destroy(),_=_t(p,{content:n.isMuted?"Unmute":"Mute",placement:"top"}),y?.destroy(),y=null}function k(){for(p.className=st.iconButtonWithState(n.isMuted);p.firstChild;)p.removeChild(p.firstChild);p.appendChild(n.isMuted?pt.micMuted():pt.micUnmuted())}return _=_t(p,{content:n.isMuted?"Unmute":"Mute",placement:"top"}),w=_t(v,{content:"End Session",placement:"top"}),C(),{update(e){const t=n;n={...n,...e},s.className=E(),t.isMuted!==n.isMuted&&(k(),x()),t.isAvatarSpeaking!==n.isAvatarSpeaking&&(k(),x()),t.userMicrophoneStream===n.userMicrophoneStream&&t.selectedMicrophone===n.selectedMicrophone||(null!=i&&(cancelAnimationFrame(i),i=null),a=[],o=null,C()),S(),n.features?.disclaimer?.enabled?c.classList.remove("np_companion_disclaimer-disabled"):c.classList.add("np_companion_disclaimer-disabled")},destroy(){_?.destroy(),y?.destroy(),w?.destroy(),null!=i&&cancelAnimationFrame(i),s.parentNode&&s.parentNode.removeChild(s)}}}(l,{avatarStyle:t.avatarStyle,isMuted:e,isAvatarSpeaking:g,userMicrophoneStream:u,features:{waveform:{enabled:!1!==t.features?.waveform?.enabled}},onVolumeChange:e=>{s.volume=e/100},toggleMute:()=>{const t=!(ot.getState().avatar.muted??e);ot.dispatch($e(t)),u&&u.getAudioTracks().forEach(e=>e.enabled=!t),w?.update({isMuted:t}),I(t),D(),L()},onStopTalking:()=>{try{const e=(e=>e.avatar.dataChannel)(ot.getState());if(e&&"open"===e.readyState){const t={type:Tt.CANCEL};at.avatar("stopping avatar"),e.send(JSON.stringify(t))}else at.critical_warn("Stopping avatar: Data channel not open")}catch(e){at.critical_error("Avatar","Stop: failed to send interrupt",e)}D(),L()},handleEnd:()=>{t.onDestroy?.()}})}}n.addEventListener("mouseenter",x),n.addEventListener("mousemove",x),n.addEventListener("mouseleave",k);const M=()=>{if(b)return;const e=c.getContext("2d",{willReadFrequently:!0});if(!e||!r||r.readyState<2)S=requestAnimationFrame(M);else{if(c.width=r.videoWidth,c.height=r.videoHeight,e.drawImage(r,0,0,c.width,c.height),m){const n=e.getImageData(0,0,c.width,c.height),o=lt.process(n);e.putImageData(o,0,0),v||(t.onAvatarReady?.(!0),v=!0,I(),P(),A(),O(),L(),k())}S=requestAnimationFrame(M)}};O(),R(),A();const j={updateStreams:({videoStream:e,audioStream:n,userMicrophoneStream:o})=>{e&&e instanceof MediaStream?h!==e&&(at.avatar("New video stream received:",{active:e.active,tracks:e.getTracks().length,videoTracks:e.getVideoTracks().length,id:e.id}),h=e,r.srcObject=e,r.play().then(()=>{m||v||(t.onAvatarReady?.(!0),v=!0,I(),P(),A(),O(),L(),N(),k())}).catch(e=>{at.error("Failed to play video stream",e),t.onError?.(e)}),e.addEventListener("inactive",()=>{at.avatar("Video stream became inactive")}),e.getTracks().forEach(e=>{e.addEventListener("ended",()=>{at.avatar("Video track ended:",e.kind)})}),m&&!S&&(S=requestAnimationFrame(M))):(h=null,r.srcObject=null),void 0!==n&&(n&&n instanceof MediaStream?f!==n&&(f=n,s.srcObject=n,s.play().catch(e=>{at.error("Failed to play audio stream",e),t.onError?.(e)})):(f=null,s.srcObject=null)),void 0!==o&&(u=o??null,w?.update({userMicrophoneStream:u}))},updateWaveform:e=>{P(),w?.update(e)},updateFeatures:e=>{t.features={...t.features||{},...e||{}},m=(t.features?.backgroundRemoval?.enabled&&"silhouette"===t.avatarStyle?.view)??!1,m?(r.classList.add("np_companion__d-none"),c.classList.remove("np_companion__d-none")):(r.classList.remove("np_companion__d-none"),c.classList.add("np_companion__d-none")),w?.update({features:{waveform:{enabled:!1!==t.features?.waveform?.enabled}}}),O(),R(),A(),L()},update:e=>{const n=t.avatarStyle?.view;Object.assign(t,e),e.features&&j.updateFeatures(e.features),e.avatarStyle?.view&&e.avatarStyle.view!==n&&(n&&o.classList.remove(`np_companion-view-${n}`),o.classList.add(`np_companion-view-${e.avatarStyle.view}`),t.features&&j.updateFeatures(t.features))},setAvatarReady:e=>{e||(v=!1,t.onAvatarReady?.(!1))},handleMessage:e=>{switch("undefined"!=typeof window&&window.parent&&window.parent.postMessage({type:"avatar-data-channel-message",event:e},"*"),e.event){case"avatar_state_changed":break;case"talk_state_changed":g="ended"!==e.data?.state&&"canceled"!==e.data?.state,w?.update({isAvatarSpeaking:g});break;case"message_received":{const{message:t}=e.data||{};if("completed"===t?.action&&"string"==typeof t.content&&t.role){D(),L();const e=E.getCurrentTrigger();e&&!e.isInteractionNeeded&&E.hide()}break}case"avatar_connection_warning":t.showAvatarInactiveOverlay&&(E.show({type:wt.SERVER_WARNING,duration:e.data?.disconnect_after??30,message:"Avatar is disconnecting due to inactivity. Say something to keep it active.",isInteractionNeeded:!1}),u&&(u.getAudioTracks().forEach(e=>e.enabled=!0),w?.update({isMuted:!1}),I(!1)))}t.onData?t.onData(e):at.data("onData callback NOT called. Reason:",{onDataExists:!!t.onData,dataType:typeof e,dataIsNull:null===e})},destroy:e=>{b||(b=!0,n.removeEventListener("mousemove",x),n.removeEventListener("mouseenter",x),n.removeEventListener("mouseleave",k),null!=y&&window.clearTimeout(y),null!=S&&(cancelAnimationFrame(S),S=null),C&&(clearTimeout(C),C=null),w?.destroy(),w=null,E?.destroy(),n.parentNode&&n.parentNode.removeChild(n),v=!1,t.onAvatarReady?.(!1),e||t.onDestroy?.())}};return j}(n,{avatarStyle:t.avatarStyle,showAvatarInactiveOverlay:!0,onData:t.onData,onDestroy:t.onDestroy,onError:t.onError,onInactivityStatusChange:t.onInactivityStatusChange,onAvatarReady:t.onAvatarReady,features:t.features});return{update:e=>{o.update({avatarStyle:e.avatarStyle??t.avatarStyle,onData:e.onData??t.onData,onDestroy:e.onDestroy??t.onDestroy,onError:e.onError??t.onError,onInactivityStatusChange:e.onInactivityStatusChange??t.onInactivityStatusChange,onAvatarReady:e.onAvatarReady??t.onAvatarReady,features:e.features??t.features}),Object.assign(t,e)},updateStreams:e=>{o.updateStreams(e)},handleMessage:e=>{o.handleMessage(e)},destroy:()=>{o.destroy(!0),n.parentNode===e&&e.removeChild(n),t.onDestroy?.()}}}(this.rootEl,{avatarStyle:this.config.avatarStyle,features:ot.getState().app.features,onData:this.config.onData,onAvatarReady:this.config.onAvatarReady,onInactivityStatusChange:this.config.onInactivityStatusChange,onDestroy:()=>this.destroyInstance("ui_end"),onError:this.config.onError}),this.initializeWebRTC().catch(e=>{at.critical_error("Failed to establish WebRTC connection:",e),this.config?.onError?.(e)}))}async initializeWebRTC(){const e=ot.getState().avatar.connectionToken;if(e&&!this.webrtcController){at.connection("Connecting WebRTC..."),this.webrtcController=function(e={}){const{currentAudioDeviceId:t,onChatMessage:n,onConnectionSuccess:a,onConnectionError:r,onStreams:s,onDataChannel:c,maxReconnectAttempts:l=3,reconnectInterval:d=2e3}=e;let p=null,u=null,m=null,h=null,f=null,b=null,g=null,v="disconnected",_=0,y=null,w=null,C=!0,E=null;function S(e,t){e&&e.readyState===WebSocket.OPEN?e.send(JSON.stringify(t)):at.critical_warn("WebRTC",`WS send skipped; state=${e?.readyState}`)}function x(e){E=e,r?.(e)}function k(e){v=e,at.webrtc(`Connection status changed to: ${e}`)}function T(){!C||!w||_>=l?_>=l&&x(new o("WebSocket connection failed after max retry attempts",{maxAttempts:l,lastAttempt:_})):(_+=1,k("reconnecting"),at.webrtc(`Attempting to reconnect (${_}/${l})...`),y=setTimeout(async()=>{try{if(!w)return;await I(w.connection.signalingEndpoint,w.connection.id,!0),!p&&w&&await N(w.token)}catch(e){at.error("WebRTC","Reconnection attempt failed:",e),_<l&&T()}},d))}async function I(e,t,n=!1){const i=`${e.replace(/\/$/,"")}/ws/connections/${t}/signaling`;u&&u.readyState===WebSocket.OPEN&&u.close();const r=new WebSocket(i);return u=r,await new Promise((e,t)=>{r.onopen=()=>{at.connection(n?"WebSocket reconnected":"WebSocket connected"),k("connected"),_=0,y&&(clearTimeout(y),y=null),e()},r.onclose=e=>{at.connection("WebSocket closed:",e),u=null,k("disconnected"),!e.wasClean&&C&&T(),t(new o("WebSocket connection closed",{code:e.code,reason:e.reason,wasClean:e.wasClean}))},r.onerror=e=>{u=null,k("disconnected");const n=new o("WebSocket connection error",{error:e,timestamp:(new Date).toISOString()});x(n),t(n)}}),a?.(),ot.dispatch(Ke(void 0)),r}async function N(e){if(p&&"disconnected"!==v)at.warn("WebRTC","Connection already in progress, skipping...");else try{k("connecting"),E=null;const a=(e=>{try{const t=atob(e);return JSON.parse(t)}catch(e){return at.critical_error("decodeToBase64: Error decoding token",e),null}})(e);if(!a)throw new o("Failed to decode connection token",{token:e?"provided":"missing"});w={...a,token:e};const r=await I(a.connection.signalingEndpoint,a.connection.id),l=await async function(){at.webrtc("Create PeerConnection");const e=new RTCPeerConnection(Nt);return p=e,e.addEventListener("connectionstatechange",()=>{"failed"===e.connectionState?(x(new o("WebRTC connection failed")),T()):"connected"===e.connectionState&&(k("connected"),_=0,y&&(clearTimeout(y),y=null))}),function(e){g=e.addTransceiver("audio",{direction:"sendrecv"});const t=e.addTransceiver("video",{direction:"recvonly"});at.webrtc("Added transceivers",{videoTransceiver:t,audioTransceiver:g});const o=e.createDataChannel("chat",{ordered:!0});b=o,ot.dispatch(Be(o)),c?.(o),o.onopen=()=>{at.webrtc("Data channel opened")},o.onclose=()=>{at.webrtc("Data channel closed")},o.onerror=e=>{at.critical_error("WebRTC",e),x(new i("Data channel error",{error:e}))},o.onmessage=e=>{try{const t=JSON.parse(e.data);at.data("Data channel message received:",t),n?.(t)}catch{n?.({event:"message_received",data:{message:{content:e.data,action:"completed"}}})}}}(e),e.ontrack=e=>{const t=e.streams[0];at.webrtc(`${e.track.kind} stream received`,{streamId:t?.id,trackId:e.track.id,videoTracks:t?.getVideoTracks().length,audioTracks:t?.getAudioTracks().length}),"video"===e.track.kind?(h=t,f=t):"audio"===e.track.kind&&(f=t,h||(h=t)),s?.({videoStream:h,audioStream:f})},e}();await async function(){try{at.webrtc("Setting up user media");const e=await navigator.mediaDevices.getUserMedia({audio:!t||{deviceId:{exact:t}},video:!1});if(m=e,g&&e.getAudioTracks().length>0){const t=e.getAudioTracks()[0];await g.sender.replaceTrack(t)}s?.({userMicrophoneStream:e})}catch(e){at.critical_warn("WebRTC",e),x(new o("Failed to access user media",{error:e,deviceId:t}))}}(),await async function(e,t){e.addEventListener("icecandidate",e=>{const n=e.candidate;n&&(at.webrtc("send ICE candidate"),S(t,{type:"add_ice_candidate",data:{candidate:n}}))}),e.addEventListener("negotiationneeded",()=>{at.warn("negotiationneeded (waiting for server offer)")}),at.webrtc("createOffer → setLocalDescription → set_remote_description");const n=await e.createOffer();await e.setLocalDescription(n),S(t,{type:"set_remote_description",data:n})}(l,r),r.onmessage=e=>async function(e,t,n){try{const o=JSON.parse(n.data);switch(o.type){case"set_remote_description":at.webrtc("Setting remote description"),await e.setRemoteDescription(o.data),await e.setLocalDescription(),S(t,{type:"set_local_description",data:e.localDescription});break;case"add_ice_candidate":o.data?.candidate&&await e.addIceCandidate(o.data.candidate);break;case"error":at.critical_error("WebRTC",o.data?.error),x(new i(o.data?.error||"Server error",{serverMessage:o.data})),e.close(),t.close();break;default:at.webrtc("Unknown message type:",o.type)}}catch(e){at.critical_error("WebRTC",e),x(new i("Failed to process WebSocket message",{originalError:e,rawMessage:n.data}))}}(l,r,e)}catch(e){const t=e;throw at.critical_error("WebRTC",t),x(t),k("disconnected"),t}}function O(){C=!1,y&&(clearTimeout(y),y=null),_=0;try{if(b)try{b.close()}catch{}if(u)try{u.readyState!==WebSocket.OPEN&&u.readyState!==WebSocket.CONNECTING||u.close(1e3,"Connection closed by client")}catch{}if(p)try{p.getSenders().forEach(e=>{e.track&&e.track.stop()}),p.close()}catch{}if(m)try{m.getTracks().forEach(e=>e.stop())}catch{}}catch(e){at.critical_warn("WebRTC",e)}finally{b=null,u=null,p=null,m=null,g=null,h=null,f=null,w=null,k("disconnected"),ot.dispatch(Ge(void 0))}}return ot.dispatch(Ge(O)),{startWithToken:N,close:O,forceReconnect:async function(){if(w){O(),C=!0,_=0;try{await N(w.token)}catch(e){throw x(e),e}}else x(new o("No connection data available for reconnect"))},getConnectionStatus:function(){return v},getReconnectAttempts:function(){return _},getError:function(){return E},updateAudioDevice:async function(e){if(g&&g.sender.track)try{const t=await navigator.mediaDevices.getUserMedia({audio:{deviceId:{exact:e}},video:!1}),n=t.getAudioTracks()[0];await g.sender.replaceTrack(n),m&&m.getTracks().forEach(e=>e.stop()),m=t,s?.({userMicrophoneStream:t}),at.webrtc(`Audio device updated to: ${e}`)}catch(t){at.critical_warn("WebRTC","Failed to update audio device:",t),x(new o("Failed to update audio device",{error:t,deviceId:e}))}else at.warn("WebRTC","No audio transceiver available for device update")}}}({maxReconnectAttempts:3,reconnectInterval:2e3,onStreams:e=>{this.embed?.updateStreams(e)},onChatMessage:e=>{this.embed?.handleMessage(e)},onConnectionError:e=>{at.critical_error("WebRTC connection error:",e),this.config?.onError?.(e)}});try{at.connection("Initializing WebRTC connection with token:",`${e.substring(0,50)}...`),await this.webrtcController.startWithToken(e),at.connection("WebRTC initialization completed with token")}catch(e){throw at.critical_error("SDK","Failed to Initialize WebRTC:",e),this.webrtcController=null,e}}}destroyWebRTC(){if(this.webrtcController){at.info("SDK","Destroying WebRTC controller");try{this.webrtcController.close()}catch(e){at.critical_error("SDK","Error closing WebRTC controller:",e)}this.webrtcController=null}}destroyInstance(e,t){if(!e)return void at.critical_warn("SDK","destroyInstance ignored (no reason)");bt("sdk_destroyed",{reason:e}),t?.();const n=this.config?.onDestroy;if(tt(null),ot.dispatch(Ke(void 0)),ot.dispatch(Ge(void 0)),ot.dispatch($e(!1)),ot.dispatch(Xe()),ot.dispatch(Ye(void 0)),this.destroyWebRTC(),this.embed){try{this.embed.update({onDestroy:void 0}),this.embed.destroy()}catch(e){at.critical_error("Error during cleanup:",e)}this.embed=null}this.rootEl&&this.rootEl.parentNode&&this.rootEl.parentNode.removeChild(this.rootEl),this.rootEl=null,this.mountTarget=null,this.config=null,this.isInitialized=!1,n?.()}async init(e,o={}){try{if(this.isInitialized)throw new t("SDK is already initialized. Call destroy() first.",{code:a.ALREADY_INITIALIZED});o.analytics?.enabled&&(function(e){ft=new ht(e)}(o.analytics),bt("sdk_init_started",{version:this.version,config:{position:o.position,features:Object.keys(o.features||{})}})),function(e){if(!e||"string"!=typeof e||""===e.trim())throw new n("Invalid connection token: expected non-empty string",{providedToken:typeof e,code:a.INVALID_TOKEN})}(e);const i={avatarStyle:{view:"round"},position:r.BOTTOM_RIGHT,...o};this.config=i,ot.dispatch(Ke(e)),ot.dispatch($e(!1)),ot.dispatch(Ze(i.debug)),this.config.features&&Object.entries(this.config.features).forEach(([e,t])=>{const n=ut(e,t);ot.dispatch(Je({feature:e,config:n}))}),tt(e=>{try{this.embed&&this.embed.update({features:e})}catch(e){at.critical_error("Unable to update features",e)}this.config?.onFeaturesUpdate?.(e)});const s=function(e){if(!e)return document.body;if("string"==typeof e){const t=document.querySelector(e);return t instanceof HTMLElement?t:(at.warn(`mountContainer should be a valid CSS selector. Provided selector "${e}" is invalid or did not match any elements. Defaulting to document.body.`),document.body)}return e instanceof HTMLElement?e:document.body}(this.config.mountContainer??void 0);return this.mountTarget=s,this.isInitialized=!0,this.renderApp(),this.config.onReady?.(),bt("sdk_init_completed",{version:this.version,initTime:Date.now()}),this.createInstanceMethods()}catch(t){const n=s.handle(t,{method:"init",tokenProvided:!!e,config:o});throw o.onError?.(n),n}}createInstanceMethods(){return{showAvatar:()=>{const e=document.getElementById("np_companion-avatar-container");e&&(e.style.display="block",gt("show","avatar_widget"))},hideAvatar:()=>{const e=document.getElementById("np_companion-avatar-container");e&&(e.style.display="none",gt("hide","avatar_widget"))},avatarIsVisible:()=>{const e=document.getElementById("np_companion-avatar-container");return!!e&&"none"!==e.style.display},destroy:()=>{const{closeConnectionHandler:e}=ot.getState().avatar;this.destroyInstance("api",e)},updateStyles:e=>{this.config&&(this.config.style={...this.config.style??{},...e??{}},this.rootEl&&Ot(this.rootEl,this.config.style))},setPosition:e=>{if(this.config&&(this.config.position=e,ot.dispatch?.(Ye(e)),this.rootEl)){const t=At(e,this.config.avatarStyle?.view,this.config.className);this.rootEl.className=t}},clearPosition:()=>{this.config&&(ot.dispatch?.(Ye(void 0)),this.config.position=void 0,this.rootEl&&(this.rootEl.className=At(void 0,this.config.avatarStyle?.view,this.config.className)))},enableFeature:e=>{ot.dispatch?.(Je({feature:e,config:{enabled:!0}})),"disclaimer"===e&&this.rootEl&&this.rootEl.classList.remove("np_companion_disclaimer-disabled")},disableFeature:e=>{ot.dispatch?.(Je({feature:e,config:{enabled:!1}})),"disclaimer"===e&&this.rootEl&&this.rootEl.classList.add("np_companion_disclaimer-disabled")},updateFeatureConfig:(e,t)=>{const n=ut(e,t);ot.dispatch?.(Je({feature:e,config:n})),"disclaimer"===e&&this.rootEl&&(n?.enabled?this.rootEl.classList.remove("np_companion_disclaimer-disabled"):this.rootEl.classList.add("np_companion_disclaimer-disabled"))},updateAvatarStyle:e=>{if(this.config){if(this.config.avatarStyle={view:"round",...this.config.avatarStyle,...e},e.view&&this.rootEl){const t=At(this.config.position,e.view,this.config.className);this.rootEl.className=t}this.embed&&this.embed.update({avatarStyle:this.config.avatarStyle})}},sendQuestion:e=>{const{dataChannel:t,stopInteraction:n}=ot.getState().avatar;t&&"open"===t.readyState&&!n?t.send(JSON.stringify({type:"send_question",data:e})):at.critical_warn("Data channel not available or not open")}}}}Object.defineProperty(Rt,"instance",{enumerable:!0,configurable:!0,writable:!0,value:null});const Dt=Rt.getInstance();return"undefined"!=typeof window&&(window.napsterCompanionApiSDK=Dt),Dt});
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@touchcastllc/napster-companion-api",
3
- "version": "1.0.0-alpha.21",
3
+ "version": "1.0.0-alpha.22",
4
4
  "keywords": [
5
5
  "napster",
6
6
  "companion-api",