@touchcastllc/napster-companion-api 1.0.0-alpha.36 → 1.0.0-alpha.37

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 r extends n{constructor(e,t){super(e,"CONNECTION_ERROR",t),this.name="ConnectionError"}}class o extends n{constructor(e,t){super(e,"WEBRTC_ERROR",t),this.name="WebRTCError"}}class s extends n{constructor(e,t){super(e,"FEATURE_ERROR",t),this.name="FeatureError"}}class c extends n{constructor(e,t,n){super(e,t,n),this.name="FaceTrackingError"}}var l,d;!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.CAMERA_PERMISSION_DENIED="CAMERA_PERMISSION_DENIED",e.CAMERA_NOT_FOUND="CAMERA_NOT_FOUND",e.MODEL_LOAD_FAILED="MODEL_LOAD_FAILED",e.DETECTION_FAILED="DETECTION_FAILED"}(l||(l={}));class u{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"}(d||(d={}));const h=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:p,setStopInteraction:m,setMuted:f,setConnectionToken:g,setCloseConnectionHandler:v}=h.actions,S=h.reducer,C={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},b=e({name:"app",initialState:C,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=C.features},setPosition:(e,t)=>{e.position=t.payload},setShowExperience:(e,t)=>{e.showExperience=t.payload},setDebugMode:(e,t)=>{e.debugMode=t.payload}}}),{setFeatures:y,resetFeatures:E,setPosition:w,setDebugMode:_}=b.actions;let T=null;const I=e=>{T=e},k=e=>t=>n=>{const a=e.getState().app.features,i=t(n),r=e.getState().app.features;return T&&a!==r&&JSON.stringify(a)!==JSON.stringify(r)&&T(r),i},N=t({reducer:{avatar:S,app:b.reducer},middleware:e=>e({serializableCheck:!1}).concat(k)}),A=e=>e.avatar.dataChannel;var D;!function(e){e.INFO="info",e.WARN="warn",e.ERROR="error",e.DEBUG="debug"}(D||(D={}));const O=new class{constructor(){Object.defineProperty(this,"prefix",{enumerable:!0,configurable:!0,writable:!0,value:"[Napster SDK]"})}isDebugEnabled(){try{return N.getState().app.debugMode||!1}catch{return!1}}log(e,...t){if(!this.isDebugEnabled())return;const n=[this.prefix,...t];switch(e){case D.INFO:console.info(...n);break;case D.WARN:console.warn(...n);break;case D.ERROR:console.error(...n);break;case D.DEBUG:console.debug(...n)}}info(...e){this.log(D.INFO,"ℹ️",...e)}debug(...e){this.log(D.DEBUG,"🐞",...e)}warn(...e){this.log(D.WARN,"⚠️",...e)}error(...e){this.log(D.ERROR,"❌",...e)}critical_warn(...e){console.warn(this.prefix,"⚠️",...e)}critical_error(...e){console.error(this.prefix,"❌",...e)}webrtc(...e){this.log(D.INFO,"📡 WebRTC:",...e)}avatar(...e){this.log(D.INFO,"🎭 Avatar:",...e)}connection(...e){this.log(D.INFO,"🔌 Connection:",...e)}features(...e){this.log(D.INFO,"🔄 Features:",...e)}data(...e){this.log(D.INFO,"📨 Data:",...e)}timer(...e){this.log(D.INFO,"⏱️ Timer:",...e)}cleanup(...e){this.log(D.INFO,"🗑️ Cleanup:",...e)}};function R(...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=R(...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 L={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",talking:"np_companion-talking",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:()=>R(L.icon,L.alignMiddle,L.darkGreyBg),iconButtonEnd:()=>R(L.icon,L.alignMiddle,L.darkGreyBg,L.callEnd),iconButtonWithState:e=>R(L.icon,L.alignMiddle,L.darkGreyBg,{[L.muted]:e})};class M{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 P{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 r=a-Math.max(n,i);if(r>0){const o=.5*r;e[t]=Math.min(255,n+.8*o),e[t+2]=Math.min(255,i+.8*o),e[t+1]=Math.max(0,a-o)}}}const F=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 r=document.createElementNS(this.svgNS,"svg");return r.setAttribute("width",String(e)),r.setAttribute("height",String(t)),r.setAttribute("viewBox",n),r.setAttribute("fill","none"),r.setAttribute("xmlns",this.svgNS),i&&r.setAttribute("class",i),a.forEach(e=>{const t=this.createElement(e);r.appendChild(t)}),r}},x={micUnmuted:()=>F.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:()=>F.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)"}}]}]}],"np_companion-mic-muted"),stop:()=>F.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"}}),F.createSVG(16,16,"0 0 640 640",t)},volumeMuted:()=>F.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"}}]),screenShare:()=>F.createSVG(17,17,"0 0 24 24",[{tag:"path",attributes:{d:"M4 3C2.89543 3 2 3.89543 2 5V15C2 16.1046 2.89543 17 4 17H9V19H7V21H17V19H15V17H20C21.1046 17 22 16.1046 22 15V5C22 3.89543 21.1046 3 20 3H4ZM4 5H20V15H4V5Z",fill:"currentColor",stroke:"currentColor","stroke-width":"0.5"}}]),screenShareActive:()=>F.createSVG(17,17,"0 0 24 24",[{tag:"path",attributes:{d:"M4 3C2.89543 3 2 3.89543 2 5V15C2 16.1046 2.89543 17 4 17H9V19H7V21H17V19H15V17H20C21.1046 17 22 16.1046 22 15V5C22 3.89543 21.1046 3 20 3H4ZM4 5H20V15H4V5Z",fill:"#4ade80",stroke:"#4ade80","stroke-width":"0.5"}}]),end:()=>F.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"}}])},V=e=>{const t=N.getState(),n=A(t),a=(e=>e.avatar.stopInteraction)(t);return n&&"open"===n.readyState&&!a?(O.avatar("Sending command:",e),n.send(JSON.stringify(e)),!0):(O.critical_warn(n?"open"!==n.readyState?`Data channel state: ${n.readyState}`:"Interaction stopped":"Data channel not available"),!1)};class j{constructor(e=1e3){Object.defineProperty(this,"video",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"canvas",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"ctx",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"worker",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"interval",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.interval=e,this.video=document.createElement("video"),this.video.setAttribute("autoplay","true"),this.video.setAttribute("playsinline","true"),this.video.muted=!0,this.canvas=document.createElement("canvas"),this.canvas.width=1280,this.canvas.height=720;const t=this.canvas.getContext("2d");if(!t)throw new Error("Failed to get canvas 2d context for MediaCapture");this.ctx=t,this.initWorker()}initWorker(){try{const e=new Blob(["\n let intervalId = null;\n self.onmessage = function(e) {\n if (e.data.command === 'start') {\n if (intervalId) clearInterval(intervalId);\n intervalId = setInterval(() => self.postMessage('tick'), e.data.interval);\n } else if (e.data.command === 'stop') {\n if (intervalId) { clearInterval(intervalId); intervalId = null; }\n }\n };\n"],{type:"application/javascript"}),t=URL.createObjectURL(e);this.worker=new Worker(t),URL.revokeObjectURL(t),this.worker.onmessage=()=>{this.drawFrame()}}catch(e){O.critical_warn("MediaCapture","Failed to create worker:",e)}}drawFrame(){if(this.video.readyState<2)return;const e=this.video.videoWidth||1280,t=this.video.videoHeight||720;this.canvas.width=e,this.canvas.height=t,this.ctx.drawImage(this.video,0,0,e,t)}getCanvas(){return this.canvas}setStream(e){e?(this.video.srcObject=e,this.video.play().catch(e=>{O.critical_warn("MediaCapture","Failed to play video:",e)}),this.worker?.postMessage({command:"start",interval:this.interval})):(this.worker?.postMessage({command:"stop"}),this.video.pause(),this.video.srcObject=null)}terminate(){this.worker?.postMessage({command:"stop"}),this.worker?.terminate(),this.worker=null,this.video.pause(),this.video.srcObject=null}}const W=(e,t)=>{if("inactiveTimeout"===e){const e=t;return e?.enabled&&void 0!==e.duration&&e.duration>18e4&&(O.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},U={enabled:!1,batchSize:10,flushInterval:5e3,enablePerformanceTracking:!0,enableErrorTracking:!0,enableUserInteractionTracking:!0};class G{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={...U,...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){O.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&&O.info(`Analytics [${t}]:`,n));const r=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(!r.ok)throw new Error(`HTTP ${r.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 H=null;const $=(e,t)=>{H?.trackEvent(e,t)},B=(e,t,n)=>{H?.trackInteraction(e,t,n)};function K(e,{content:t,placement:n="top"}){let a=!1,i=null,r=null;const o=e=>"left"===e?"start":"right"===e?"end":e,s=()=>{if(!i)return;const t=e.getBoundingClientRect(),a=i.getBoundingClientRect();let r=0,o=0;switch(n){case"top":r=t.top-a.height-8,o=t.left+(t.width-a.width)/2;break;case"bottom":r=t.bottom+8,o=t.left+(t.width-a.width)/2;break;case"left":r=t.top+(t.height-a.height)/2,o=t.left-a.width-8;break;case"right":r=t.top+(t.height-a.height)/2,o=t.right+8}i.style.top=`${r}px`,i.style.left=`${o}px`},c=()=>s(),l=()=>{if(a)return;const e=(()=>{if(i)return i;const e=document.createElement("div");e.className=`tooltip styled-tooltip bs-tooltip-${o(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 r=document.createElement("div");return r.className="tooltip-inner","string"==typeof t?r.textContent=t:r.appendChild(t),e.appendChild(a),e.appendChild(r),document.body.appendChild(e),i=e,e})();a=!0,s(),r=window.setTimeout(s,10),e.style.opacity="1",e.style.visibility="visible",window.addEventListener("scroll",c,!0),window.addEventListener("resize",c)},d=()=>{a&&(a=!1,null!=r&&(window.clearTimeout(r),r=null),i&&(i.style.opacity="0",i.style.visibility="hidden"),window.removeEventListener("scroll",c,!0),window.removeEventListener("resize",c))},u=()=>l(),h=()=>d();return e.addEventListener("mouseenter",u),e.addEventListener("mouseleave",h),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-${o(n)} show`)),a&&s()},show:l,hide:d,destroy:()=>{d(),e.removeEventListener("mouseenter",u),e.removeEventListener("mouseleave",h),i&&i.parentNode&&i.parentNode.removeChild(i),i=null}}}function z(e,t){const n=document.createElement(e);return t&&(n.className=t),n}var q,Q,Z,J,Y,X,ee;!function(e){e.LOCAL_TIMEOUT="local_timeout",e.SERVER_WARNING="server_warning"}(q||(q={}));class te{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?O.warn("Inactive overlay already visible, ignoring show request"):(O.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 r=document.createElement("p");r.className="np_companion-inactive-message",r.textContent=n.message;const o=document.createElement("div");o.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 u=document.createElement("span");u.className="np_companion-timer-number",s.appendChild(c),c.appendChild(l),c.appendChild(d),s.appendChild(u),o.appendChild(s);const h=document.createElement("div");h.className="np_companion-inactive-buttons";const p=document.createElement("button");p.className="np_companion-end-button np_companion__d-none",p.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",h.appendChild(m),m.addEventListener("click",n.onContinue)):!e&&m&&(m.removeEventListener("click",n.onContinue),m.parentNode&&m.parentNode.removeChild(m),m=null)};h.appendChild(p),f(n.isInteractionNeeded),i.appendChild(r),i.appendChild(o),i.appendChild(h),a.appendChild(i),e.appendChild(a);let g=Math.max(0,Math.floor(n.duration)),v=null;const S=()=>{u.textContent=String(g),d.setAttribute("stroke-dasharray",(n.duration>0?g/n.duration*100:0)+", 100")},C=()=>{if(g<=0)return y(),void n.onEnd();g-=1,S()},b=()=>{y(),S(),v=window.setInterval(C,1e3)},y=()=>{null!=v&&(window.clearInterval(v),v=null)};return p.addEventListener("click",()=>{y(),n.onEnd()}),b(),{update:e=>{if(void 0!==e.message&&(n.message=e.message,r.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,g=t,b()}e.onContinue&&(m&&(m.removeEventListener("click",n.onContinue),m.addEventListener("click",e.onContinue)),n.onContinue=e.onContinue),e.onEnd&&(n.onEnd=e.onEnd)},destroy:()=>{y(),p.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&&(O.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(){O.info("User clicked continue on inactive overlay"),this.hide(),this.callbacks.onContinue?.()}handleEnd(){O.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"}(Q||(Q={})),function(e){e.STARTED="started",e.ENDED="ended",e.CANCELED="canceled"}(Z||(Z={})),function(e){e.DELTA="delta",e.COMPLETED="completed"}(J||(J={})),function(e){e.USER="user",e.ASSISTANT="assistant"}(Y||(Y={})),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"}(X||(X={})),function(e){e.SEND_MESSAGE="send_message",e.CANCEL="cancel",e.SET_SETTINGS="set_settings",e.START_VIDEO="start_video",e.STOP_VIDEO="stop_video"}(ee||(ee={}));const ne={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 ae(){return"undefined"!=typeof navigator&&!!navigator.mediaDevices&&"function"==typeof navigator.mediaDevices.getDisplayMedia}function ie(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{O.warn(`Failed to apply style for key "${n}: ${t[n]}".`)}}function re(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 oe{static getInstance(){return oe.instance||(oe.instance=new oe),oe.instance}constructor(){Object.defineProperty(this,"version",{enumerable:!0,configurable:!0,writable:!0,value:"1.0.0-alpha.23"}),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,"screenShareController",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"faceTrackingController",{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}),Object.defineProperty(this,"unloadHandler",{enumerable:!0,configurable:!0,writable:!0,value:null}),"undefined"!=typeof window&&(this.unloadHandler=()=>{this.screenShareController?.destroy()},window.addEventListener("beforeunload",this.unloadHandler))}renderApp(){if(!this.mountTarget||!this.config)return;this.rootEl||(this.rootEl=document.createElement("div"),this.rootEl.id="np_companion-sdk-root",this.mountTarget.appendChild(this.rootEl)),this.rootEl.className=re(this.config.position,this.config.avatarStyle?.view,this.config.className),ie(this.rootEl,this.config.style),this.screenShareController||(this.screenShareController=function(){const e=new j(1e3);let t=null,n=!1,a=!1;async function i(){if(!n&&!a)if(ae()){a=!0;try{const a=await navigator.mediaDevices.getDisplayMedia({video:{frameRate:{max:1},width:{max:1280},height:{max:720}},audio:!1,selfBrowserSurface:"include"});t=a;const i=a.getVideoTracks()[0];i&&i.addEventListener("ended",()=>{r()}),e.setStream(a),n=!0,await function(e=5e3){const t=A(N.getState());return t&&"open"===t.readyState?Promise.resolve():new Promise((t,n)=>{const a=setTimeout(()=>{i(),n(new Error("Timed out waiting for data channel to open"))},e),i=N.subscribe(()=>{const e=A(N.getState());e&&"open"===e.readyState&&(clearTimeout(a),i(),t())})})}(),V({type:ee.START_VIDEO,data:null}),O.webrtc("Screen sharing started")}catch(a){throw t&&(t.getTracks().forEach(e=>e.stop()),t=null),e.setStream(null),n=!1,"NotAllowedError"===a.name?O.warn("ScreenShare","Permission denied by user"):"NotFoundError"===a.name?O.warn("ScreenShare","No screen sharing source selected"):O.critical_warn("ScreenShare","Failed to start screen share:",a),a}finally{a=!1}}else O.critical_warn("ScreenShare","getDisplayMedia is not supported in this browser")}function r(){n&&(t&&(t.getTracks().forEach(e=>e.stop()),t=null),e.setStream(null),n=!1,V({type:ee.STOP_VIDEO,data:null}),O.webrtc("Screen sharing stopped"))}return{start:i,stop:r,toggle:async function(){n||a?n&&r():await i()},isSharing:function(){return n},isSupported:function(){return ae()},getCapture:function(){return e},destroy:function(){r(),e.terminate()}}}());const e=ae(),t=N.getState().app.features.screenShare?.enabled??!1,n={isScreenSharing:this.screenShareController.isSharing(),isScreenShareSupported:e&&t,onScreenShareToggle:()=>this.handleScreenShareToggle()};this.embed?this.embed.update({avatarStyle:this.config.avatarStyle,features:N.getState().app.features,onData:this.config.onData,onAvatarReady:this.config.onAvatarReady,onInactivityStatusChange:this.config.onInactivityStatusChange,onDestroy:()=>this.destroyInstance("ui_end"),onError:this.config.onError,...n}):this.embed=function(e,t={}){const n=M.createDiv("np_companion-live-container np_companion-fade-in");e.appendChild(n);const a=function(e,t={}){const n=M.createDiv("np_companion-avatar"),a=M.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=M.createDiv("loader-container"),r=M.createDiv("loader");i.appendChild(r);const o=M.createVideo({className:"np_companion-avatar-video",autoplay:!0,muted:!0,playsInline:!0}),s=M.createAudio({className:"np_companion-avatar-audio",autoplay:!0}),c=M.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?o.classList.add("np_companion__d-none"):c.classList.add("np_companion__d-none"),a.appendChild(i),a.appendChild(o),a.appendChild(s),a.appendChild(c);const l=M.createDiv(`${L.wrapper} np_companion-action-btn-container-view-${t.avatarStyle?.view}`),d=M.createDiv(`np_companion-disclaimer-text np_companion-disclaimer-view-${t.avatarStyle?.view}`);d.style.display="none";const u=M.createDiv(`np_companion-avatar-control-container np_companion-avatar-control-view-${t.avatarStyle?.view}`);u.appendChild(l),u.appendChild(d),n.appendChild(a),n.appendChild(u),e.appendChild(n);let h=null,p=(t.features?.backgroundRemoval?.enabled&&"silhouette"===t.avatarStyle?.view)??!1,g=null,v=null,S=!1,C=!1,b=!1,y=!0,E=null,w=null,_=null;const T=new te(n,{onContinue:()=>{H();const e=t.features?.inactiveTimeout;e?.enabled&&$()},onEnd:()=>{}});let I=null;const k=()=>{y||(y=!0,u.className=D(),null!=E&&window.clearTimeout(E))},A=()=>{null!=E&&window.clearTimeout(E),E=window.setTimeout(()=>{y=!1,u.className=D()},5e3)};function D(){return R(`np_companion-avatar-control-container np_companion-avatar-control-view-${t.avatarStyle?.view}`,{[L.collapse]:!y})}function F(e){if(!b)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 r=t.avatarStyle?.borderStyle??("silhouette"!==t.avatarStyle?.view?"solid":void 0);r&&(a.style.borderStyle=r)}function j(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;d.style.display=e&&b?"-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,b&&j(e?void 0:"8%")}function U(){b||!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 H(){_&&(O.timer("Resetting inactive timeout due to activity"),clearTimeout(_),_=null,N.dispatch(m(!1)),t.onInactivityStatusChange?.(!1))}function $(){const e=t.features?.inactiveTimeout;e?.enabled?(H(),_=setTimeout(()=>{O.timer(`Inactive timeout of ${e?.duration}ms reached, showing inactive overlay`),N.dispatch(m(!0)),t.onInactivityStatusChange?.(!0),h&&(h.getAudioTracks().forEach(e=>e.enabled=!1),w?.update({isMuted:!0}),F(!0)),T.isShowing()||T.show({type:q.LOCAL_TIMEOUT,duration:Math.min(e.countdown??30,60),message:void 0,isInteractionNeeded:!0})},e.duration)):(H(),T.isShowing()&&T.hide())}function B(){if(!w&&b){const e=!1;w=function(e,t){let n={...t},a=null,i=null,r=[],o=!1;const s=document.createElement("div");s.className=I();const c=z("div",L.container),l=z("div",R(L.questionBar,L.alignBetween)),d=z("div",L.left),u=z("div",L.iconButtonWithState(n.isMuted));u.appendChild(n.isMuted?x.micMuted():x.micUnmuted()),n.toggleMute&&u.addEventListener("click",()=>n.toggleMute?.());const h=z("div",L.middle),p=z("div",L.wave);k();const m=document.createElement("canvas");m.width=160,m.height=40,m.className=L.canvas,p.appendChild(m);const f=z("div",R(L.right,L.alignBetween)),g=z("div",R(L.iconButton(),L.stop)),v=function(e,t={}){let n={initialVolume:50,...t},a=n.initialVolume??50,i=!1,r=!1;const o=document.createElement("div");o.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 u=document.createElement("div");function h(){let e;u.innerHTML="",e=i||0===a?x.volumeMuted():x.volumeHigh(a||100),u.appendChild(e)}function p(){const e=a;l.style.height=`${e}%`,d.style.bottom=`${e}%`}function m(){r=!r,r?s.classList.add("np_volume-slider-visible"):s.classList.remove("np_volume-slider-visible")}function f(e){const t=c.getBoundingClientRect(),r=Math.max(0,Math.min(100,(t.bottom-e)/t.height*100));a=r,p(),i=0===a,i?u.classList.add("np_volume-muted"):u.classList.remove("np_volume-muted"),h(),n.onChange?.(a)}u.className=L.iconButton(),u.setAttribute("aria-label","Volume control"),h(),o.appendChild(s),o.appendChild(u),e.appendChild(o),u.addEventListener("click",e=>{e.stopPropagation(),i=!i,i?(n.initialVolume=a,a=0,p(),u.classList.add("np_volume-muted")):(a=n.initialVolume||50,p(),u.classList.remove("np_volume-muted")),h(),n.onMuteToggle?.(i)}),o.addEventListener("mouseenter",e=>{e.stopPropagation(),r||m()}),o.addEventListener("mouseleave",e=>{setTimeout(()=>{e.stopPropagation(),r&&m()},300)});let g=!1;return c.addEventListener("mousedown",e=>{g=!0,f(e.clientY),e.preventDefault()}),document.addEventListener("mousemove",e=>{g&&f(e.clientY)}),document.addEventListener("mouseup",()=>{g=!1}),d.addEventListener("mousedown",e=>{g=!0,e.preventDefault()}),c.addEventListener("touchstart",e=>{g=!0,f(e.touches[0].clientY),e.preventDefault()}),document.addEventListener("touchmove",e=>{g&&e.touches.length>0&&f(e.touches[0].clientY)}),document.addEventListener("touchend",()=>{g=!1}),document.addEventListener("click",e=>{r&&!o.contains(e.target)&&m()}),p(),{setVolume(e){a=Math.max(0,Math.min(100,e)),p(),h(),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(){o.remove()}}}(g,{initialVolume:50,onChange:e=>{n.onVolumeChange?.(e)},onMuteToggle:e=>{n.onVolumeChange?.(e?0:v.getVolume())}});v.setVolume(70);const S=z("div",L.iconButton());S.appendChild(n.isScreenSharing?x.screenShareActive():x.screenShare()),S.addEventListener("click",()=>n.onScreenShareToggle?.());const C=n.isScreenShareSupported;C||(S.style.display="none");const b=z("div",L.iconButtonEnd());b.appendChild(x.end()),n.handleEnd&&b.addEventListener("click",()=>n.handleEnd?.()),d.appendChild(u),h.appendChild(p),f.appendChild(g),f.appendChild(S),f.appendChild(b),l.appendChild(d),l.appendChild(f),c.appendChild(l),s.appendChild(c),e.appendChild(s);let y=null,E=null,w=null,_=null;function T(){if(!n.userMicrophoneStream)return;const e=new(window.AudioContext||window.webkitAudioContext);a=e.createAnalyser(),e.createMediaStreamSource(n.userMicrophoneStream).connect(a),function(){if(!a)return;const e=m.getContext("2d");if(!e)return;a.fftSize=256;const t=a.frequencyBinCount,s=new Uint8Array(t),c=Math.floor(m.width/3);0===r.length&&(r=new Array(c).fill(0));let l=0;const d=()=>{if(e.clearRect(0,0,m.width,m.height),e.beginPath(),e.moveTo(0,m.height/2),e.lineTo(m.width,m.height/2),e.strokeStyle="#ffffff",e.stroke(),n.isMuted)o=!1,r.fill(0),k();else{a.getByteFrequencyData(s);const n=4,i=Math.floor(.05*t),c=Math.floor(.4*t);let d=0;for(let e=i;e<c;e++)s[e]>d&&(d=s[e]);const u=d/255*m.height*.8;r.shift(),r.push(u);let h=r.slice(-5).some(e=>e>n);h?l=30:l>0&&(l--,h=!0),o=h,k(),e.fillStyle="#ffffff";for(let t=0;t<r.length;t++){const n=3*t,a=r[t];e.fillRect(n,m.height/2-a/2,2,a),e.fillRect(n,m.height/2+a/2,2,-a)}}i=requestAnimationFrame(d)};d()}()}function I(){return R(L.alignMiddle,`np_companion-avatar-${n.avatarStyle?.view}`)}function k(){p.style.filter=!n.isMuted&&o?"brightness(0) saturate(100%) invert(48%) sepia(93%) saturate(1720%) hue-rotate(346deg) brightness(101%) contrast(103%)":"none",p.style.transition="filter 0.3s ease",p.style.height="40px",!n.isMuted&&o?u.classList.add(L.talking):u.classList.remove(L.talking)}function N(){y?.destroy(),y=K(u,{content:n.isMuted?"Unmute":"Mute",placement:"top"}),E?.destroy(),E=null,_?.destroy(),_=null,n.isScreenShareSupported&&(_=K(S,{content:n.isScreenSharing?"Stop Sharing":"Share Screen",placement:"top"}))}function A(){for(u.className=L.iconButtonWithState(n.isMuted);u.firstChild;)u.removeChild(u.firstChild);for(u.appendChild(n.isMuted?x.micMuted():x.micUnmuted());S.firstChild;)S.removeChild(S.firstChild);S.appendChild(n.isScreenSharing?x.screenShareActive():x.screenShare()),S.style.display=n.isScreenShareSupported?"":"none"}return y=K(u,{content:n.isMuted?"Unmute":"Mute",placement:"top"}),w=K(b,{content:"End Session",placement:"top"}),C&&(_=K(S,{content:n.isScreenSharing?"Stop Sharing":"Share Screen",placement:"top"})),T(),{update(e){const t=n;n={...n,...e},s.className=I(),t.isMuted!==n.isMuted&&(A(),N()),t.isAvatarSpeaking!==n.isAvatarSpeaking&&(A(),N()),t.isScreenSharing===n.isScreenSharing&&t.isScreenShareSupported===n.isScreenShareSupported||(A(),N()),t.userMicrophoneStream===n.userMicrophoneStream&&t.selectedMicrophone===n.selectedMicrophone||(null!=i&&(cancelAnimationFrame(i),i=null),r=[],a=null,T()),k(),n.features?.disclaimer?.enabled?c.classList.remove("np_companion_disclaimer-disabled"):c.classList.add("np_companion_disclaimer-disabled")},destroy(){y?.destroy(),E?.destroy(),w?.destroy(),_?.destroy(),null!=i&&cancelAnimationFrame(i),s.parentNode&&s.parentNode.removeChild(s)}}}(l,{avatarStyle:t.avatarStyle,isMuted:e,isAvatarSpeaking:C,userMicrophoneStream:h,isScreenSharing:t.isScreenSharing,isScreenShareSupported:t.isScreenShareSupported,onScreenShareToggle:()=>t.onScreenShareToggle?.(),features:{waveform:{enabled:!1!==t.features?.waveform?.enabled},screenShare:t.features?.screenShare},onVolumeChange:e=>{s.volume=e/100},toggleMute:()=>{const t=!(N.getState().avatar.muted??e);N.dispatch(f(t)),h&&h.getAudioTracks().forEach(e=>e.enabled=!t),w?.update({isMuted:t}),F(t),H(),$()},onStopTalking:()=>{try{O.avatar("stopping avatar"),V({type:ee.CANCEL})}catch(e){O.critical_error("Avatar","Stop: failed to send interrupt",e)}H(),$()},handleEnd:()=>{t.onDestroy?.()}})}}n.addEventListener("mouseenter",k),n.addEventListener("mousemove",k),n.addEventListener("mouseleave",A);const Q=()=>{if(S)return;const e=c.getContext("2d",{willReadFrequently:!0});if(!e||!o||o.readyState<2)I=requestAnimationFrame(Q);else{if(c.width=o.videoWidth,c.height=o.videoHeight,e.drawImage(o,0,0,c.width,c.height),p){const n=e.getImageData(0,0,c.width,c.height),a=P.process(n);e.putImageData(a,0,0),b||(t.onAvatarReady?.(!0),b=!0,F(),B(),U(),W(),$(),A())}I=requestAnimationFrame(Q)}};W(),G(),U();const Z={updateStreams:({videoStream:e,audioStream:n,userMicrophoneStream:a})=>{e&&e instanceof MediaStream?g!==e&&(O.avatar("New video stream received:",{active:e.active,tracks:e.getTracks().length,videoTracks:e.getVideoTracks().length,id:e.id}),g=e,o.srcObject=e,S||o.play().then(()=>{S||p||b||(t.onAvatarReady?.(!0),b=!0,F(),B(),U(),W(),$(),j(),A())}).catch(e=>{S||"AbortError"===e?.name||(O.error("Failed to play video stream",e),t.onError?.(e))}),e.addEventListener("inactive",()=>{O.avatar("Video stream became inactive")}),e.getTracks().forEach(e=>{e.addEventListener("ended",()=>{O.avatar("Video track ended:",e.kind)})}),p&&!I&&(I=requestAnimationFrame(Q))):(g=null,o.srcObject=null),void 0!==n&&(n&&n instanceof MediaStream?v!==n&&(v=n,s.srcObject=n,S||s.play().catch(e=>{S||"AbortError"===e?.name||(O.error("Failed to play audio stream",e),t.onError?.(e))})):(v=null,s.srcObject=null)),void 0!==a&&(h=a??null,w?.update({userMicrophoneStream:h}))},updateWaveform:e=>{B(),w?.update(e)},updateFeatures:e=>{t.features={...t.features||{},...e||{}},p=(t.features?.backgroundRemoval?.enabled&&"silhouette"===t.avatarStyle?.view)??!1,p?(o.classList.add("np_companion__d-none"),c.classList.remove("np_companion__d-none")):(o.classList.remove("np_companion__d-none"),c.classList.add("np_companion__d-none")),w?.update({features:{waveform:{enabled:!1!==t.features?.waveform?.enabled}}}),W(),G(),U(),$()},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||(b=!1,t.onAvatarReady?.(!1))},updateScreenShareState:e=>{t.isScreenSharing=e,w?.update({isScreenSharing:e})},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":C="ended"!==e.data?.state&&"canceled"!==e.data?.state,w?.update({isAvatarSpeaking:C});break;case"message_received":{const{message:t}=e.data||{};if("completed"===t?.action&&"string"==typeof t.content&&t.role){H(),$();const e=T.getCurrentTrigger();e&&!e.isInteractionNeeded&&T.hide()}break}case"avatar_connection_warning":t.showAvatarInactiveOverlay&&(T.show({type:q.SERVER_WARNING,duration:e.data?.disconnect_after??30,message:"Avatar is disconnecting due to inactivity. Say something to keep it active.",isInteractionNeeded:!1}),h&&(h.getAudioTracks().forEach(e=>e.enabled=!0),w?.update({isMuted:!1}),F(!1)))}t.onData?t.onData(e):O.data("onData callback NOT called. Reason:",{onDataExists:!!t.onData,dataType:typeof e,dataIsNull:null===e})},destroy:e=>{if(!S){S=!0,n.removeEventListener("mousemove",k),n.removeEventListener("mouseenter",k),n.removeEventListener("mouseleave",A),null!=E&&window.clearTimeout(E),null!=I&&(cancelAnimationFrame(I),I=null),_&&(clearTimeout(_),_=null);try{o.pause(),o.srcObject=null}catch{}try{s.pause(),s.srcObject=null}catch{}try{g?.getTracks().forEach(e=>e.stop())}catch{}try{v?.getTracks().forEach(e=>e.stop())}catch{}g=null,v=null,w?.destroy(),w=null,T?.destroy(),n.parentNode&&n.parentNode.removeChild(n),b=!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,onScreenShareToggle:t.onScreenShareToggle,isScreenSharing:t.isScreenSharing,isScreenShareSupported:t.isScreenShareSupported});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,onScreenShareToggle:e.onScreenShareToggle??t.onScreenShareToggle,isScreenSharing:e.isScreenSharing??t.isScreenSharing,isScreenShareSupported:e.isScreenShareSupported??t.isScreenShareSupported}),Object.assign(t,e)},updateStreams:e=>{a.updateStreams(e)},handleMessage:e=>{a.handleMessage(e)},updateScreenShareState:e=>{a.updateScreenShareState(e)},destroy:()=>{a.destroy(!0),n.parentNode===e&&e.removeChild(n),t.onDestroy?.()}}}(this.rootEl,{avatarStyle:this.config.avatarStyle,features:N.getState().app.features,onData:this.config.onData,onAvatarReady:this.config.onAvatarReady,onInactivityStatusChange:this.config.onInactivityStatusChange,onDestroy:()=>this.destroyInstance("ui_end"),onError:this.config.onError,...n}),this.initializeWebRTC().catch(e=>{O.critical_error("Failed to establish WebRTC connection:",e),this.config?.onError?.(e)})}async handleScreenShareToggle(){if(this.screenShareController)try{await this.screenShareController.toggle(),this.embed?.updateScreenShareState(this.screenShareController.isSharing())}catch(e){O.critical_warn("SDK","Screen share toggle failed:",e),this.config?.onError?.(e),this.embed?.updateScreenShareState(this.screenShareController.isSharing())}}async initializeWebRTC(){const e=N.getState().avatar.connectionToken;if(e&&!this.webrtcController){O.connection("Connecting WebRTC..."),this.webrtcController=function(e={}){const{currentAudioDeviceId:t,functions:n,screenShareCapture:a,onChatMessage:i,onConnectionSuccess:s,onConnectionError:c,onStreams:l,onDataChannel:d,maxReconnectAttempts:u=3,reconnectInterval:h=2e3}=e;let m=null,f=null,S=null,C=null,b=null,y=null,E=null,w="disconnected",_=0,T=null,I=null,k=!0,A=null;function D(e,t){return e&&e.readyState===WebSocket.OPEN?(e.send(JSON.stringify(t)),!0):(O.critical_warn("WebRTC",`WS send skipped; state=${e?.readyState}`),!1)}function R(e){A=e,c?.(e)}function L(e){w=e,O.webrtc(`Connection status changed to: ${e}`)}function M(){if(!k||!I||_>=u){if(_>=u){const e=_;O.critical_error("WebRTC",`All ${u} reconnect attempts exhausted. Closing WebSocket and WebRTC connections.`),x();const t=new r("Connection failed after max retry attempts. Closing all connections.",{maxAttempts:u,lastAttempt:e});A=t,c?.(t)}}else _+=1,L("reconnecting"),O.webrtc(`Attempting to reconnect (${_}/${u})...`),T=setTimeout(async()=>{try{if(!I)return;await P(I.connection.signalingEndpoint,I.connection.id,!0),!m&&I&&await F(I.token)}catch(e){O.error("WebRTC","Reconnection attempt failed:",e),M()}},h)}async function P(e,t,n=!1){const a=`${e.replace(/\/$/,"")}/ws/connections/${t}/signaling`;f&&f.readyState===WebSocket.OPEN&&f.close();const i=new WebSocket(a);return f=i,await new Promise((e,t)=>{i.onopen=()=>{O.connection(n?"WebSocket reconnected":"WebSocket connected"),L("connected"),_=0,T&&(clearTimeout(T),T=null),e()},i.onclose=e=>{O.connection("WebSocket closed:",e),f=null,L("disconnected"),!e.wasClean&&k&&M(),t(new r("WebSocket connection closed",{code:e.code,reason:e.reason,wasClean:e.wasClean}))},i.onerror=e=>{f=null,L("disconnected");const n=new r("WebSocket connection error",{error:e,timestamp:(new Date).toISOString()});R(n),t(n)}}),N.dispatch(g(void 0)),i}async function F(e){if(m&&"disconnected"!==w)O.warn("WebRTC","Connection already in progress, skipping...");else try{L("connecting"),A=null;const c=(e=>{try{const t=atob(e);return JSON.parse(t)}catch(e){return O.critical_error("decodeToBase64: Error decoding token",e),null}})(e);if(!c)throw new r("Failed to decode connection token",{token:e?"provided":"missing"});I={...c,token:e};const u=await P(c.connection.signalingEndpoint,c.connection.id),h=await async function(){O.webrtc("Create PeerConnection");const e=new RTCPeerConnection(ne);return m=e,e.addEventListener("connectionstatechange",()=>{"failed"===e.connectionState?(R(new r("WebRTC connection failed")),M()):"connected"===e.connectionState&&(L("connected"),_=0,T&&(clearTimeout(T),T=null))}),function(e){E=e.addTransceiver("audio",{direction:"sendrecv"});const t=e.addTransceiver("video",{direction:"recvonly"});if(a){const t=a.getCanvas().captureStream(1);t.getTracks().forEach(n=>{e.addTrack(n,t)})}O.webrtc("Added transceivers",{videoTransceiver:t,audioTransceiver:E});const r=e.createDataChannel("chat",{ordered:!0});y=r,r.onopen=()=>{O.webrtc("Data channel opened"),N.dispatch(p(r)),d?.(r),s?.(),n&&n.length>0&&(V({type:ee.SET_SETTINGS,data:{functions:n}}),O.webrtc("Functions sent via data channel",n))},r.onclose=()=>{O.webrtc("Data channel closed"),N.dispatch(p(null))},r.onerror=e=>{O.critical_error("WebRTC",e),R(new o("Data channel error",{error:e}))},r.onmessage=e=>{try{const t=JSON.parse(e.data);O.data("Data channel message received:",t),i?.(t)}catch{i?.({event:"message_received",data:{message:{content:e.data,action:"completed"}}})}}}(e),e.ontrack=e=>{const t=e.streams[0];O.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?(C=t,b=t):"audio"===e.track.kind&&(b=t,C||(C=t)),l?.({videoStream:C,audioStream:b})},e}();await async function(){try{O.webrtc("Setting up user media");const e=await navigator.mediaDevices.getUserMedia({audio:t?{deviceId:{exact:t},noiseSuppression:!0,echoCancellation:!0,autoGainControl:!0}:{noiseSuppression:!0,echoCancellation:!0,autoGainControl:!0},video:!1});if(S=e,E&&e.getAudioTracks().length>0){const t=e.getAudioTracks()[0];await E.sender.replaceTrack(t)}l?.({userMicrophoneStream:e})}catch(e){O.critical_warn("WebRTC",e),R(new r("Failed to access user media",{error:e,deviceId:t}))}}(),await async function(e,t){e.addEventListener("icecandidate",e=>{const n=e.candidate;n&&(O.webrtc("send ICE candidate"),D(t,{type:"add_ice_candidate",data:{candidate:n}}))}),e.addEventListener("negotiationneeded",async()=>{O.webrtc("negotiationneeded — creating new offer");try{const n=await e.createOffer();await e.setLocalDescription(n),D(t,{type:"set_remote_description",data:n})}catch(e){O.critical_error("WebRTC","Failed to renegotiate:",e)}}),O.webrtc("createOffer → setLocalDescription → set_remote_description");const n=await e.createOffer();await e.setLocalDescription(n),D(t,{type:"set_remote_description",data:n})}(h,u),u.onmessage=e=>async function(e,t,n){try{const a=JSON.parse(n.data);switch(a.type){case"set_remote_description":O.webrtc("Setting remote description"),await e.setRemoteDescription(a.data),await e.setLocalDescription(),D(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":O.critical_error("WebRTC",a.data?.error),R(new o(a.data?.error||"Server error",{serverMessage:a.data})),e.close(),t.close();break;default:O.webrtc("Unknown message type:",a.type)}}catch(e){O.critical_error("WebRTC",e),R(new o("Failed to process WebSocket message",{originalError:e,rawMessage:n.data}))}}(h,u,e)}catch(e){const t=e;throw O.critical_error("WebRTC",t),R(t),L("disconnected"),t}}function x(){k=!1,T&&(clearTimeout(T),T=null),_=0;try{if(y)try{y.close()}catch{}if(f)try{f.readyState!==WebSocket.OPEN&&f.readyState!==WebSocket.CONNECTING||f.close(1e3,"Connection closed by client")}catch{}try{C?.getTracks().forEach(e=>e.stop())}catch{}try{b?.getTracks().forEach(e=>e.stop())}catch{}if(m)try{m.getSenders().forEach(e=>{e.track&&e.track.stop()}),m.close()}catch{}if(S)try{S.getTracks().forEach(e=>e.stop())}catch{}}catch(e){O.critical_warn("WebRTC",e)}finally{y=null,f=null,m=null,S=null,E=null,C=null,b=null,I=null,L("disconnected"),N.dispatch(v(void 0))}}return N.dispatch(v(x)),{startWithToken:F,close:x,forceReconnect:async function(){if(I){x(),k=!0,_=0;try{await F(I.token)}catch(e){throw R(e),e}}else R(new r("No connection data available for reconnect"))},getConnectionStatus:function(){return w},getReconnectAttempts:function(){return _},getError:function(){return A},updateAudioDevice:async function(e){if(E&&E.sender.track)try{const t=await navigator.mediaDevices.getUserMedia({audio:{deviceId:{exact:e},noiseSuppression:!0,echoCancellation:!0,autoGainControl:!0},video:!1}),n=t.getAudioTracks()[0];await E.sender.replaceTrack(n),S&&S.getTracks().forEach(e=>e.stop()),S=t,l?.({userMicrophoneStream:t}),O.webrtc(`Audio device updated to: ${e}`)}catch(t){O.critical_warn("WebRTC","Failed to update audio device:",t),R(new r("Failed to update audio device",{error:t,deviceId:e}))}else O.warn("WebRTC","No audio transceiver available for device update")}}}({maxReconnectAttempts:3,reconnectInterval:2e3,functions:this.config?.functions,screenShareCapture:this.screenShareController?.getCapture()??null,onStreams:e=>{this.embed?.updateStreams(e)},onChatMessage:e=>{this.embed?.handleMessage(e)},onConnectionError:e=>{O.critical_error("WebRTC connection error:",e),this.config?.onError?.(e),this.webrtcController&&"disconnected"===this.webrtcController.getConnectionStatus()&&(O.critical_error("SDK","Connection unrecoverable after all retries. Destroying SDK instance."),this.destroyInstance("internal"))}});try{O.connection("Initializing WebRTC connection with token:",`${e.substring(0,50)}...`),await this.webrtcController.startWithToken(e),O.connection("WebRTC initialization completed with token")}catch(e){throw O.critical_error("SDK","Failed to Initialize WebRTC:",e),this.webrtcController=null,e}}}destroyWebRTC(){if(this.screenShareController?.isSharing()&&(this.screenShareController.stop(),this.embed?.updateScreenShareState(!1)),this.webrtcController){O.info("SDK","Destroying WebRTC controller");try{this.webrtcController.close()}catch(e){O.critical_error("SDK","Error closing WebRTC controller:",e)}this.webrtcController=null}}destroyInstance(e,t){if(!e)return void O.critical_warn("SDK","destroyInstance ignored (no reason)");$("sdk_destroyed",{reason:e}),t?.();const n=this.config?.onDestroy;if(I(null),N.dispatch(g(void 0)),N.dispatch(v(void 0)),N.dispatch(f(!1)),N.dispatch(E()),N.dispatch(w(void 0)),this.embed){try{this.embed.update({onDestroy:void 0}),this.embed.destroy()}catch(e){O.critical_error("Error during cleanup:",e)}this.embed=null}this.screenShareController&&(this.screenShareController.destroy(),this.screenShareController=null),this.faceTrackingController&&(this.faceTrackingController.destroy(),this.faceTrackingController=null),this.unloadHandler&&"undefined"!=typeof window&&(window.removeEventListener("beforeunload",this.unloadHandler),this.unloadHandler=null),this.destroyWebRTC(),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:l.ALREADY_INITIALIZED});t.analytics?.enabled&&(function(e){H=new G(e)}(t.analytics),$("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:l.INVALID_TOKEN})}(e);const n={avatarStyle:{view:"round"},position:d.BOTTOM_RIGHT,...t};this.config=n,N.dispatch(g(e)),N.dispatch(f(!1)),N.dispatch(_(n.debug)),this.config.features&&Object.entries(this.config.features).forEach(([e,t])=>{const n=W(e,t);N.dispatch(y({feature:e,config:n}))}),I(e=>{try{this.embed&&this.embed.update({features:e})}catch(e){O.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:(O.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?.(),$("sdk_init_completed",{version:this.version,initTime:Date.now()}),this.createInstanceMethods()}catch(n){const a=u.handle(n,{method:"init",tokenProvided:!!e,config:t});throw t.onError?.(a),a}}createInstanceMethods(){const e=this;return{showAvatar:()=>{const e=document.getElementById("np_companion-avatar-container");e&&(e.style.display="block",B("show","avatar_widget"))},hideAvatar:()=>{const e=document.getElementById("np_companion-avatar-container");e&&(e.style.display="none",B("hide","avatar_widget"))},avatarIsVisible:()=>{const e=document.getElementById("np_companion-avatar-container");return!!e&&"none"!==e.style.display},destroy:()=>{const{closeConnectionHandler:e}=N.getState().avatar;this.destroyInstance("api",e)},updateStyles:e=>{this.config&&(this.config.style={...this.config.style??{},...e??{}},this.rootEl&&ie(this.rootEl,this.config.style))},setPosition:e=>{if(this.config&&(this.config.position=e,N.dispatch?.(w(e)),this.rootEl)){const t=re(e,this.config.avatarStyle?.view,this.config.className);this.rootEl.className=t}},clearPosition:()=>{this.config&&(N.dispatch?.(w(void 0)),this.config.position=void 0,this.rootEl&&(this.rootEl.className=re(void 0,this.config.avatarStyle?.view,this.config.className)))},enableFeature:e=>{N.dispatch?.(y({feature:e,config:{enabled:!0}})),"disclaimer"===e&&this.rootEl&&this.rootEl.classList.remove("np_companion_disclaimer-disabled")},disableFeature:e=>{N.dispatch?.(y({feature:e,config:{enabled:!1}})),"disclaimer"===e&&this.rootEl&&this.rootEl.classList.add("np_companion_disclaimer-disabled")},updateFeatureConfig:(e,t)=>{const n=W(e,t);N.dispatch?.(y({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=re(this.config.position,e.view,this.config.className);this.rootEl.className=t}this.embed&&this.embed.update({avatarStyle:this.config.avatarStyle})}},sendCommand:e=>{V(e)},startScreenShare:async()=>{if(!this.screenShareController?.isSharing())try{await(this.screenShareController?.start()),this.embed?.updateScreenShareState(this.screenShareController?.isSharing()??!1)}catch(e){throw O.critical_warn("SDK","Failed to start screen share:",e),this.config?.onError?.(e),e}},stopScreenShare:()=>{this.screenShareController?.isSharing()&&(this.screenShareController.stop(),this.embed?.updateScreenShareState(!1))},toggleScreenShare:async()=>{await this.handleScreenShareToggle()},get isScreenSharing(){return e.screenShareController?.isSharing()??!1},get isScreenShareSupported(){return ae()&&(N.getState().app.features.screenShare?.enabled??!1)},startFaceTracking:async()=>{const e=N.getState().app.features.faceTracking;if(!e?.enabled)throw new s("Face tracking is not enabled. Set features.faceTracking.enabled = true.",{code:l.FEATURE_DISABLED});this.faceTrackingController||(this.faceTrackingController=function(e={},t={}){const n=Math.min(Math.max(e.fps??15,1),30),a=e.talkingThreshold??.015,i=e.videoWidth??640,r=e.videoHeight??480,o=1e3/n;let s=null,d=null,u=null,h=null,p=null,m=null,f=!1,g=!1,v=0;const S=function(e=5){let t=[];return{push:n=>(t.push(n),t.length>e&&t.shift(),t.reduce((e,t)=>e+t,0)/t.length),reset(){t=[]}}}(e.smoothingFrames??5);function C(e,n){const a=new c(e,n);O.error("FaceTracking:",e),t.onError?.(a)}function b(){u||(u=document.createElement("canvas")),h||(h=u.getContext("2d"))}function y(e){f&&(e-v>=o&&(v=e,async function(){if(d&&p&&!(d.readyState<4))try{b(),u.width=d.videoWidth,u.height=d.videoHeight,h.drawImage(d,0,0);const e=await p.estimateFaces(u);if(e&&e.length>0){const n=e[0].keypoints,o=d.videoWidth||i,s=d.videoHeight||r,c=n.map(e=>({x:e.x/o,y:e.y/s,z:e.z??0})),l=function(e,t,n){if(!e||0===e.length)return null;const a=e[13],i=e[14],r=e[61],o=e[291];if(!(a&&i&&r&&o))return null;const s=Math.abs(a.y-i.y),c=Math.abs(o.x-r.x),l=s/Math.max(c,1),d=t||640,u=n||480;return{mouthLandmarks:{topLip:{x:a.x/d,y:a.y/u},bottomLip:{x:i.x/d,y:i.y/u},leftCorner:{x:r.x/d,y:r.y/u},rightCorner:{x:o.x/d,y:o.y/u}},openingRatio:l}}(n,o,s);let u=!1;l&&(u=S.push(l.openingRatio)>a),t.onData?.({landmarks:c,mouthLandmarks:l?.mouthLandmarks??null,isTalking:u})}else t.onData?.(null)}catch(e){O.error("FaceTracking: detection error",e)}}()),m=requestAnimationFrame(y))}function E(){f=!1,null!==m&&(cancelAnimationFrame(m),m=null),s&&(s.getTracks().forEach(e=>e.stop()),s=null),d&&(d.srcObject=null,d=null),S.reset(),O.info("FaceTracking:","Stopped (model kept for restart)")}return{start:async function(){g?C("Cannot start: face tracking service has been destroyed.",l.DETECTION_FAILED):f||(O.info("FaceTracking:","Starting face tracking..."),await async function(){try{s=await navigator.mediaDevices.getUserMedia({video:{width:i,height:r,facingMode:"user"},audio:!1})}catch(e){throw e instanceof Error?"NotAllowedError"===e.name?C("Camera permission denied. Please allow camera access for face tracking.",l.CAMERA_PERMISSION_DENIED):"NotFoundError"===e.name?C("No camera found. Please ensure a camera is connected.",l.CAMERA_NOT_FOUND):C(`Camera error: ${e.message}`,l.CAMERA_PERMISSION_DENIED):C("Failed to access camera for face tracking.",l.CAMERA_PERMISSION_DENIED),e}d=document.createElement("video"),d.setAttribute("autoplay",""),d.setAttribute("playsinline",""),d.setAttribute("muted",""),d.muted=!0,d.srcObject=s,await new Promise((e,t)=>{if(!d)return t();d.onloadedmetadata=()=>{d.play().then(e).catch(t)}})}(),p||await async function(){try{const[e,t]=await Promise.all([import("@tensorflow/tfjs"),import("@tensorflow-models/face-landmarks-detection")]);await e.ready();const n=t.SupportedModels.MediaPipeFaceMesh;p=await t.createDetector(n,{runtime:"tfjs",maxFaces:1,refineLandmarks:!0}),O.info("FaceTracking:","MediaPipe Face Mesh model loaded")}catch(e){throw C("Failed to load face detection model.",l.MODEL_LOAD_FAILED),e}}(),b(),S.reset(),f=!0,v=0,m=requestAnimationFrame(y),O.info("FaceTracking:",`Detection running at ${n} FPS`))},stop:E,isActive:function(){return f},destroy:function(){if(E(),p){try{p.dispose()}catch{}p=null}u=null,h=null,g=!0,O.info("FaceTracking:","Destroyed")}}}({fps:e.fps,talkingThreshold:e.talkingThreshold},{onData:e=>{this.config?.onFaceTrackingData?.(e)},onError:e=>{this.config?.onFaceTrackingError?.(e),this.config?.onError?.(e)}})),await this.faceTrackingController.start()},stopFaceTracking:()=>{this.faceTrackingController?.stop()}}}}Object.defineProperty(oe,"instance",{enumerable:!0,configurable:!0,writable:!0,value:null});const se=oe.getInstance();"undefined"!=typeof window&&(window.napsterCompanionApiSDK=se);export{ee as DataChannelMessageType,se as NapsterCompanionApiSdk,d as Position,se 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 r extends n{constructor(e,t){super(e,"CONNECTION_ERROR",t),this.name="ConnectionError"}}class o extends n{constructor(e,t){super(e,"WEBRTC_ERROR",t),this.name="WebRTCError"}}class s extends n{constructor(e,t){super(e,"FEATURE_ERROR",t),this.name="FeatureError"}}class c extends n{constructor(e,t,n){super(e,t,n),this.name="FaceTrackingError"}}var l,d;!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.CAMERA_PERMISSION_DENIED="CAMERA_PERMISSION_DENIED",e.CAMERA_NOT_FOUND="CAMERA_NOT_FOUND",e.MODEL_LOAD_FAILED="MODEL_LOAD_FAILED",e.DETECTION_FAILED="DETECTION_FAILED"}(l||(l={}));class u{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"}(d||(d={}));const h=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:p,setStopInteraction:m,setMuted:f,setConnectionToken:g,setCloseConnectionHandler:v}=h.actions,S=h.reducer,C={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},b=e({name:"app",initialState:C,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=C.features},setPosition:(e,t)=>{e.position=t.payload},setShowExperience:(e,t)=>{e.showExperience=t.payload},setDebugMode:(e,t)=>{e.debugMode=t.payload}}}),{setFeatures:y,resetFeatures:E,setPosition:w,setDebugMode:_}=b.actions;let T=null;const I=e=>{T=e},k=e=>t=>n=>{const a=e.getState().app.features,i=t(n),r=e.getState().app.features;return T&&a!==r&&JSON.stringify(a)!==JSON.stringify(r)&&T(r),i},N=t({reducer:{avatar:S,app:b.reducer},middleware:e=>e({serializableCheck:!1}).concat(k)}),D=e=>e.avatar.dataChannel;var A;!function(e){e.INFO="info",e.WARN="warn",e.ERROR="error",e.DEBUG="debug"}(A||(A={}));const O=new class{constructor(){Object.defineProperty(this,"prefix",{enumerable:!0,configurable:!0,writable:!0,value:"[Napster SDK]"})}isDebugEnabled(){try{return N.getState().app.debugMode||!1}catch{return!1}}log(e,...t){if(!this.isDebugEnabled())return;const n=[this.prefix,...t];switch(e){case A.INFO:console.info(...n);break;case A.WARN:console.warn(...n);break;case A.ERROR:console.error(...n);break;case A.DEBUG:console.debug(...n)}}info(...e){this.log(A.INFO,"ℹ️",...e)}debug(...e){this.log(A.DEBUG,"🐞",...e)}warn(...e){this.log(A.WARN,"⚠️",...e)}error(...e){this.log(A.ERROR,"❌",...e)}critical_warn(...e){console.warn(this.prefix,"⚠️",...e)}critical_error(...e){console.error(this.prefix,"❌",...e)}webrtc(...e){this.log(A.INFO,"📡 WebRTC:",...e)}avatar(...e){this.log(A.INFO,"🎭 Avatar:",...e)}connection(...e){this.log(A.INFO,"🔌 Connection:",...e)}features(...e){this.log(A.INFO,"🔄 Features:",...e)}data(...e){this.log(A.INFO,"📨 Data:",...e)}timer(...e){this.log(A.INFO,"⏱️ Timer:",...e)}cleanup(...e){this.log(A.INFO,"🗑️ Cleanup:",...e)}};function R(...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=R(...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 L={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",talking:"np_companion-talking",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:()=>R(L.icon,L.alignMiddle,L.darkGreyBg),iconButtonEnd:()=>R(L.icon,L.alignMiddle,L.darkGreyBg,L.callEnd),iconButtonWithState:e=>R(L.icon,L.alignMiddle,L.darkGreyBg,{[L.muted]:e})};class M{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 P{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 r=a-Math.max(n,i);if(r>0){const o=.5*r;e[t]=Math.min(255,n+.8*o),e[t+2]=Math.min(255,i+.8*o),e[t+1]=Math.max(0,a-o)}}}const F=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 r=document.createElementNS(this.svgNS,"svg");return r.setAttribute("width",String(e)),r.setAttribute("height",String(t)),r.setAttribute("viewBox",n),r.setAttribute("fill","none"),r.setAttribute("xmlns",this.svgNS),i&&r.setAttribute("class",i),a.forEach(e=>{const t=this.createElement(e);r.appendChild(t)}),r}},x={micUnmuted:()=>F.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:()=>F.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)"}}]}]}],"np_companion-mic-muted"),stop:()=>F.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"}}),F.createSVG(16,16,"0 0 640 640",t)},volumeMuted:()=>F.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"}}]),screenShare:()=>F.createSVG(17,17,"0 0 24 24",[{tag:"path",attributes:{d:"M4 3C2.89543 3 2 3.89543 2 5V15C2 16.1046 2.89543 17 4 17H9V19H7V21H17V19H15V17H20C21.1046 17 22 16.1046 22 15V5C22 3.89543 21.1046 3 20 3H4ZM4 5H20V15H4V5Z",fill:"currentColor",stroke:"currentColor","stroke-width":"0.5"}}]),screenShareActive:()=>F.createSVG(17,17,"0 0 24 24",[{tag:"path",attributes:{d:"M4 3C2.89543 3 2 3.89543 2 5V15C2 16.1046 2.89543 17 4 17H9V19H7V21H17V19H15V17H20C21.1046 17 22 16.1046 22 15V5C22 3.89543 21.1046 3 20 3H4ZM4 5H20V15H4V5Z",fill:"#4ade80",stroke:"#4ade80","stroke-width":"0.5"}}]),end:()=>F.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"}}])},V=e=>{const t=N.getState(),n=D(t),a=(e=>e.avatar.stopInteraction)(t);return n&&"open"===n.readyState&&!a?(O.avatar("Sending command:",e),n.send(JSON.stringify(e)),!0):(O.critical_warn(n?"open"!==n.readyState?`Data channel state: ${n.readyState}`:"Interaction stopped":"Data channel not available"),!1)};class j{constructor(e=1e3){Object.defineProperty(this,"video",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"canvas",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"ctx",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"worker",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"interval",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.interval=e,this.video=document.createElement("video"),this.video.setAttribute("autoplay","true"),this.video.setAttribute("playsinline","true"),this.video.muted=!0,this.canvas=document.createElement("canvas"),this.canvas.width=1280,this.canvas.height=720;const t=this.canvas.getContext("2d");if(!t)throw new Error("Failed to get canvas 2d context for MediaCapture");this.ctx=t,this.initWorker()}initWorker(){try{const e=new Blob(["\n let intervalId = null;\n self.onmessage = function(e) {\n if (e.data.command === 'start') {\n if (intervalId) clearInterval(intervalId);\n intervalId = setInterval(() => self.postMessage('tick'), e.data.interval);\n } else if (e.data.command === 'stop') {\n if (intervalId) { clearInterval(intervalId); intervalId = null; }\n }\n };\n"],{type:"application/javascript"}),t=URL.createObjectURL(e);this.worker=new Worker(t),URL.revokeObjectURL(t),this.worker.onmessage=()=>{this.drawFrame()}}catch(e){O.critical_warn("MediaCapture","Failed to create worker:",e)}}drawFrame(){if(this.video.readyState<2)return;const e=this.video.videoWidth||1280,t=this.video.videoHeight||720;this.canvas.width=e,this.canvas.height=t,this.ctx.drawImage(this.video,0,0,e,t)}getCanvas(){return this.canvas}setStream(e){e?(this.video.srcObject=e,this.video.play().catch(e=>{O.critical_warn("MediaCapture","Failed to play video:",e)}),this.worker?.postMessage({command:"start",interval:this.interval})):(this.worker?.postMessage({command:"stop"}),this.video.pause(),this.video.srcObject=null)}terminate(){this.worker?.postMessage({command:"stop"}),this.worker?.terminate(),this.worker=null,this.video.pause(),this.video.srcObject=null}}const W=(e,t)=>{if("inactiveTimeout"===e){const e=t;return e?.enabled&&void 0!==e.duration&&e.duration>18e4&&(O.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},U={enabled:!1,batchSize:10,flushInterval:5e3,enablePerformanceTracking:!0,enableErrorTracking:!0,enableUserInteractionTracking:!0};class G{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={...U,...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){O.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&&O.info(`Analytics [${t}]:`,n));const r=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(!r.ok)throw new Error(`HTTP ${r.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 H=null;const $=(e,t)=>{H?.trackEvent(e,t)},B=(e,t,n)=>{H?.trackInteraction(e,t,n)};function K(e,{content:t,placement:n="top"}){let a=!1,i=null,r=null;const o=e=>"left"===e?"start":"right"===e?"end":e,s=()=>{if(!i)return;const t=e.getBoundingClientRect(),a=i.getBoundingClientRect();let r=0,o=0;switch(n){case"top":r=t.top-a.height-8,o=t.left+(t.width-a.width)/2;break;case"bottom":r=t.bottom+8,o=t.left+(t.width-a.width)/2;break;case"left":r=t.top+(t.height-a.height)/2,o=t.left-a.width-8;break;case"right":r=t.top+(t.height-a.height)/2,o=t.right+8}i.style.top=`${r}px`,i.style.left=`${o}px`},c=()=>s(),l=()=>{if(a)return;const e=(()=>{if(i)return i;const e=document.createElement("div");e.className=`tooltip styled-tooltip bs-tooltip-${o(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 r=document.createElement("div");return r.className="tooltip-inner","string"==typeof t?r.textContent=t:r.appendChild(t),e.appendChild(a),e.appendChild(r),document.body.appendChild(e),i=e,e})();a=!0,s(),r=window.setTimeout(s,10),e.style.opacity="1",e.style.visibility="visible",window.addEventListener("scroll",c,!0),window.addEventListener("resize",c)},d=()=>{a&&(a=!1,null!=r&&(window.clearTimeout(r),r=null),i&&(i.style.opacity="0",i.style.visibility="hidden"),window.removeEventListener("scroll",c,!0),window.removeEventListener("resize",c))},u=()=>l(),h=()=>d();return e.addEventListener("mouseenter",u),e.addEventListener("mouseleave",h),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-${o(n)} show`)),a&&s()},show:l,hide:d,destroy:()=>{d(),e.removeEventListener("mouseenter",u),e.removeEventListener("mouseleave",h),i&&i.parentNode&&i.parentNode.removeChild(i),i=null}}}function z(e,t){const n=document.createElement(e);return t&&(n.className=t),n}var q,Q,Z,J,Y,X,ee;!function(e){e.LOCAL_TIMEOUT="local_timeout",e.SERVER_WARNING="server_warning"}(q||(q={}));class te{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?O.warn("Inactive overlay already visible, ignoring show request"):(O.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 r=document.createElement("p");r.className="np_companion-inactive-message",r.textContent=n.message;const o=document.createElement("div");o.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 u=document.createElement("span");u.className="np_companion-timer-number",s.appendChild(c),c.appendChild(l),c.appendChild(d),s.appendChild(u),o.appendChild(s);const h=document.createElement("div");h.className="np_companion-inactive-buttons";const p=document.createElement("button");p.className="np_companion-end-button np_companion__d-none",p.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",h.appendChild(m),m.addEventListener("click",n.onContinue)):!e&&m&&(m.removeEventListener("click",n.onContinue),m.parentNode&&m.parentNode.removeChild(m),m=null)};h.appendChild(p),f(n.isInteractionNeeded),i.appendChild(r),i.appendChild(o),i.appendChild(h),a.appendChild(i),e.appendChild(a);let g=Math.max(0,Math.floor(n.duration)),v=null;const S=()=>{u.textContent=String(g),d.setAttribute("stroke-dasharray",(n.duration>0?g/n.duration*100:0)+", 100")},C=()=>{if(g<=0)return y(),void n.onEnd();g-=1,S()},b=()=>{y(),S(),v=window.setInterval(C,1e3)},y=()=>{null!=v&&(window.clearInterval(v),v=null)};return p.addEventListener("click",()=>{y(),n.onEnd()}),b(),{update:e=>{if(void 0!==e.message&&(n.message=e.message,r.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,g=t,b()}e.onContinue&&(m&&(m.removeEventListener("click",n.onContinue),m.addEventListener("click",e.onContinue)),n.onContinue=e.onContinue),e.onEnd&&(n.onEnd=e.onEnd)},destroy:()=>{y(),p.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&&(O.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(){O.info("User clicked continue on inactive overlay"),this.hide(),this.callbacks.onContinue?.()}handleEnd(){O.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"}(Q||(Q={})),function(e){e.STARTED="started",e.ENDED="ended",e.CANCELED="canceled"}(Z||(Z={})),function(e){e.DELTA="delta",e.COMPLETED="completed"}(J||(J={})),function(e){e.USER="user",e.ASSISTANT="assistant"}(Y||(Y={})),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"}(X||(X={})),function(e){e.SEND_MESSAGE="send_message",e.CANCEL="cancel",e.SET_SETTINGS="set_settings",e.START_VIDEO="start_video",e.STOP_VIDEO="stop_video"}(ee||(ee={}));const ne={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 ae(){return"undefined"!=typeof navigator&&!!navigator.mediaDevices&&"function"==typeof navigator.mediaDevices.getDisplayMedia}function ie(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{O.warn(`Failed to apply style for key "${n}: ${t[n]}".`)}}function re(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 oe{static getInstance(){return oe.instance||(oe.instance=new oe),oe.instance}constructor(){Object.defineProperty(this,"version",{enumerable:!0,configurable:!0,writable:!0,value:"1.0.0-alpha.23"}),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,"screenShareController",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"faceTrackingController",{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}),Object.defineProperty(this,"unloadHandler",{enumerable:!0,configurable:!0,writable:!0,value:null}),"undefined"!=typeof window&&(this.unloadHandler=()=>{this.screenShareController?.destroy()},window.addEventListener("beforeunload",this.unloadHandler))}renderApp(){if(!this.mountTarget||!this.config)return;this.rootEl||(this.rootEl=document.createElement("div"),this.rootEl.id="np_companion-sdk-root",this.mountTarget.appendChild(this.rootEl)),this.rootEl.className=re(this.config.position,this.config.avatarStyle?.view,this.config.className),ie(this.rootEl,this.config.style),this.screenShareController||(this.screenShareController=function(){const e=new j(1e3);let t=null,n=!1,a=!1;async function i(){if(!n&&!a)if(ae()){a=!0;try{const a=await navigator.mediaDevices.getDisplayMedia({video:{frameRate:{max:1},width:{max:1280},height:{max:720}},audio:!1,selfBrowserSurface:"include"});t=a;const i=a.getVideoTracks()[0];i&&i.addEventListener("ended",()=>{r()}),e.setStream(a),n=!0,await function(e=5e3){const t=D(N.getState());return t&&"open"===t.readyState?Promise.resolve():new Promise((t,n)=>{const a=setTimeout(()=>{i(),n(new Error("Timed out waiting for data channel to open"))},e),i=N.subscribe(()=>{const e=D(N.getState());e&&"open"===e.readyState&&(clearTimeout(a),i(),t())})})}(),V({type:ee.START_VIDEO,data:null}),O.webrtc("Screen sharing started")}catch(a){throw t&&(t.getTracks().forEach(e=>e.stop()),t=null),e.setStream(null),n=!1,"NotAllowedError"===a.name?O.warn("ScreenShare","Permission denied by user"):"NotFoundError"===a.name?O.warn("ScreenShare","No screen sharing source selected"):O.critical_warn("ScreenShare","Failed to start screen share:",a),a}finally{a=!1}}else O.critical_warn("ScreenShare","getDisplayMedia is not supported in this browser")}function r(){n&&(t&&(t.getTracks().forEach(e=>e.stop()),t=null),e.setStream(null),n=!1,V({type:ee.STOP_VIDEO,data:null}),O.webrtc("Screen sharing stopped"))}return{start:i,stop:r,toggle:async function(){n||a?n&&r():await i()},isSharing:function(){return n},isSupported:function(){return ae()},getCapture:function(){return e},destroy:function(){r(),e.terminate()}}}());const e=ae(),t=N.getState().app.features.screenShare?.enabled??!1,n={isScreenSharing:this.screenShareController.isSharing(),isScreenShareSupported:e&&t,onScreenShareToggle:()=>this.handleScreenShareToggle()};this.embed?this.embed.update({avatarStyle:this.config.avatarStyle,features:N.getState().app.features,onData:this.config.onData,onAvatarReady:this.config.onAvatarReady,onInactivityStatusChange:this.config.onInactivityStatusChange,onDestroy:()=>this.destroyInstance("ui_end"),onError:this.config.onError,...n}):this.embed=function(e,t={}){const n=M.createDiv("np_companion-live-container np_companion-fade-in");e.appendChild(n);const a=function(e,t={}){const n=M.createDiv("np_companion-avatar"),a=M.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=M.createDiv("loader-container"),r=M.createDiv("loader");i.appendChild(r);const o=M.createVideo({className:"np_companion-avatar-video",autoplay:!0,muted:!0,playsInline:!0}),s=M.createAudio({className:"np_companion-avatar-audio",autoplay:!0}),c=M.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?o.classList.add("np_companion__d-none"):c.classList.add("np_companion__d-none"),a.appendChild(i),a.appendChild(o),a.appendChild(s),a.appendChild(c);const l=M.createDiv(`${L.wrapper} np_companion-action-btn-container-view-${t.avatarStyle?.view}`),d=M.createDiv(`np_companion-disclaimer-text np_companion-disclaimer-view-${t.avatarStyle?.view}`);d.style.display="none";const u=M.createDiv(`np_companion-avatar-control-container np_companion-avatar-control-view-${t.avatarStyle?.view}`);u.appendChild(l),u.appendChild(d),n.appendChild(a),n.appendChild(u),e.appendChild(n);let h=null,p=(t.features?.backgroundRemoval?.enabled&&"silhouette"===t.avatarStyle?.view)??!1,g=null,v=null,S=!1,C=!1,b=!1,y=!0,E=null,w=null,_=null;const T=new te(n,{onContinue:()=>{H();const e=t.features?.inactiveTimeout;e?.enabled&&$()},onEnd:()=>{t.onDestroy?.()}});let I=null;const k=()=>{y||(y=!0,u.className=A(),null!=E&&window.clearTimeout(E))},D=()=>{null!=E&&window.clearTimeout(E),E=window.setTimeout(()=>{y=!1,u.className=A()},5e3)};function A(){return R(`np_companion-avatar-control-container np_companion-avatar-control-view-${t.avatarStyle?.view}`,{[L.collapse]:!y})}function F(e){if(!b)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 r=t.avatarStyle?.borderStyle??("silhouette"!==t.avatarStyle?.view?"solid":void 0);r&&(a.style.borderStyle=r)}function j(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;d.style.display=e&&b?"-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,b&&j(e?void 0:"8%")}function U(){b||!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 H(){_&&(O.timer("Resetting inactive timeout due to activity"),clearTimeout(_),_=null,N.dispatch(m(!1)),t.onInactivityStatusChange?.(!1))}function $(){const e=t.features?.inactiveTimeout;e?.enabled?(H(),_=setTimeout(()=>{O.timer(`Inactive timeout of ${e?.duration}ms reached, showing inactive overlay`),N.dispatch(m(!0)),t.onInactivityStatusChange?.(!0),h&&(h.getAudioTracks().forEach(e=>e.enabled=!1),w?.update({isMuted:!0}),F(!0)),T.isShowing()||T.show({type:q.LOCAL_TIMEOUT,duration:Math.min(e.countdown??30,60),message:void 0,isInteractionNeeded:!0})},e.duration)):(H(),T.isShowing()&&T.hide())}function B(){if(!w&&b){const e=!1;w=function(e,t){let n={...t},a=null,i=null,r=[],o=!1;const s=document.createElement("div");s.className=I();const c=z("div",L.container),l=z("div",R(L.questionBar,L.alignBetween)),d=z("div",L.left),u=z("div",L.iconButtonWithState(n.isMuted));u.appendChild(n.isMuted?x.micMuted():x.micUnmuted()),n.toggleMute&&u.addEventListener("click",()=>n.toggleMute?.());const h=z("div",L.middle),p=z("div",L.wave);k();const m=document.createElement("canvas");m.width=160,m.height=40,m.className=L.canvas,p.appendChild(m);const f=z("div",R(L.right,L.alignBetween)),g=z("div",R(L.iconButton(),L.stop)),v=function(e,t={}){let n={initialVolume:50,...t},a=n.initialVolume??50,i=!1,r=!1;const o=document.createElement("div");o.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 u=document.createElement("div");function h(){let e;u.innerHTML="",e=i||0===a?x.volumeMuted():x.volumeHigh(a||100),u.appendChild(e)}function p(){const e=a;l.style.height=`${e}%`,d.style.bottom=`${e}%`}function m(){r=!r,r?s.classList.add("np_volume-slider-visible"):s.classList.remove("np_volume-slider-visible")}function f(e){const t=c.getBoundingClientRect(),r=Math.max(0,Math.min(100,(t.bottom-e)/t.height*100));a=r,p(),i=0===a,i?u.classList.add("np_volume-muted"):u.classList.remove("np_volume-muted"),h(),n.onChange?.(a)}u.className=L.iconButton(),u.setAttribute("aria-label","Volume control"),h(),o.appendChild(s),o.appendChild(u),e.appendChild(o),u.addEventListener("click",e=>{e.stopPropagation(),i=!i,i?(n.initialVolume=a,a=0,p(),u.classList.add("np_volume-muted")):(a=n.initialVolume||50,p(),u.classList.remove("np_volume-muted")),h(),n.onMuteToggle?.(i)}),o.addEventListener("mouseenter",e=>{e.stopPropagation(),r||m()}),o.addEventListener("mouseleave",e=>{setTimeout(()=>{e.stopPropagation(),r&&m()},300)});let g=!1;return c.addEventListener("mousedown",e=>{g=!0,f(e.clientY),e.preventDefault()}),document.addEventListener("mousemove",e=>{g&&f(e.clientY)}),document.addEventListener("mouseup",()=>{g=!1}),d.addEventListener("mousedown",e=>{g=!0,e.preventDefault()}),c.addEventListener("touchstart",e=>{g=!0,f(e.touches[0].clientY),e.preventDefault()}),document.addEventListener("touchmove",e=>{g&&e.touches.length>0&&f(e.touches[0].clientY)}),document.addEventListener("touchend",()=>{g=!1}),document.addEventListener("click",e=>{r&&!o.contains(e.target)&&m()}),p(),{setVolume(e){a=Math.max(0,Math.min(100,e)),p(),h(),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(){o.remove()}}}(g,{initialVolume:50,onChange:e=>{n.onVolumeChange?.(e)},onMuteToggle:e=>{n.onVolumeChange?.(e?0:v.getVolume())}});v.setVolume(70);const S=z("div",L.iconButton());S.appendChild(n.isScreenSharing?x.screenShareActive():x.screenShare()),S.addEventListener("click",()=>n.onScreenShareToggle?.());const C=n.isScreenShareSupported;C||(S.style.display="none");const b=z("div",L.iconButtonEnd());b.appendChild(x.end()),n.handleEnd&&b.addEventListener("click",()=>n.handleEnd?.()),d.appendChild(u),h.appendChild(p),f.appendChild(g),f.appendChild(S),f.appendChild(b),l.appendChild(d),l.appendChild(f),c.appendChild(l),s.appendChild(c),e.appendChild(s);let y=null,E=null,w=null,_=null;function T(){if(!n.userMicrophoneStream)return;const e=new(window.AudioContext||window.webkitAudioContext);a=e.createAnalyser(),e.createMediaStreamSource(n.userMicrophoneStream).connect(a),function(){if(!a)return;const e=m.getContext("2d");if(!e)return;a.fftSize=256;const t=a.frequencyBinCount,s=new Uint8Array(t),c=Math.floor(m.width/3);0===r.length&&(r=new Array(c).fill(0));let l=0;const d=()=>{if(e.clearRect(0,0,m.width,m.height),e.beginPath(),e.moveTo(0,m.height/2),e.lineTo(m.width,m.height/2),e.strokeStyle="#ffffff",e.stroke(),n.isMuted)o=!1,r.fill(0),k();else{a.getByteFrequencyData(s);const n=4,i=Math.floor(.05*t),c=Math.floor(.4*t);let d=0;for(let e=i;e<c;e++)s[e]>d&&(d=s[e]);const u=d/255*m.height*.8;r.shift(),r.push(u);let h=r.slice(-5).some(e=>e>n);h?l=30:l>0&&(l--,h=!0),o=h,k(),e.fillStyle="#ffffff";for(let t=0;t<r.length;t++){const n=3*t,a=r[t];e.fillRect(n,m.height/2-a/2,2,a),e.fillRect(n,m.height/2+a/2,2,-a)}}i=requestAnimationFrame(d)};d()}()}function I(){return R(L.alignMiddle,`np_companion-avatar-${n.avatarStyle?.view}`)}function k(){p.style.filter=!n.isMuted&&o?"brightness(0) saturate(100%) invert(48%) sepia(93%) saturate(1720%) hue-rotate(346deg) brightness(101%) contrast(103%)":"none",p.style.transition="filter 0.3s ease",p.style.height="40px",!n.isMuted&&o?u.classList.add(L.talking):u.classList.remove(L.talking)}function N(){y?.destroy(),y=K(u,{content:n.isMuted?"Unmute":"Mute",placement:"top"}),E?.destroy(),E=null,_?.destroy(),_=null,n.isScreenShareSupported&&(_=K(S,{content:n.isScreenSharing?"Stop Sharing":"Share Screen",placement:"top"}))}function D(){for(u.className=L.iconButtonWithState(n.isMuted);u.firstChild;)u.removeChild(u.firstChild);for(u.appendChild(n.isMuted?x.micMuted():x.micUnmuted());S.firstChild;)S.removeChild(S.firstChild);S.appendChild(n.isScreenSharing?x.screenShareActive():x.screenShare()),S.style.display=n.isScreenShareSupported?"":"none"}return y=K(u,{content:n.isMuted?"Unmute":"Mute",placement:"top"}),w=K(b,{content:"End Session",placement:"top"}),C&&(_=K(S,{content:n.isScreenSharing?"Stop Sharing":"Share Screen",placement:"top"})),T(),{update(e){const t=n;n={...n,...e},s.className=I(),t.isMuted!==n.isMuted&&(D(),N()),t.isAvatarSpeaking!==n.isAvatarSpeaking&&(D(),N()),t.isScreenSharing===n.isScreenSharing&&t.isScreenShareSupported===n.isScreenShareSupported||(D(),N()),t.userMicrophoneStream===n.userMicrophoneStream&&t.selectedMicrophone===n.selectedMicrophone||(null!=i&&(cancelAnimationFrame(i),i=null),r=[],a=null,T()),k(),n.features?.disclaimer?.enabled?c.classList.remove("np_companion_disclaimer-disabled"):c.classList.add("np_companion_disclaimer-disabled")},destroy(){y?.destroy(),E?.destroy(),w?.destroy(),_?.destroy(),null!=i&&cancelAnimationFrame(i),s.parentNode&&s.parentNode.removeChild(s)}}}(l,{avatarStyle:t.avatarStyle,isMuted:e,isAvatarSpeaking:C,userMicrophoneStream:h,isScreenSharing:t.isScreenSharing,isScreenShareSupported:t.isScreenShareSupported,onScreenShareToggle:()=>t.onScreenShareToggle?.(),features:{waveform:{enabled:!1!==t.features?.waveform?.enabled},screenShare:t.features?.screenShare},onVolumeChange:e=>{s.volume=e/100},toggleMute:()=>{const t=!(N.getState().avatar.muted??e);N.dispatch(f(t)),h&&h.getAudioTracks().forEach(e=>e.enabled=!t),w?.update({isMuted:t}),F(t),H(),$()},onStopTalking:()=>{try{O.avatar("stopping avatar"),V({type:ee.CANCEL})}catch(e){O.critical_error("Avatar","Stop: failed to send interrupt",e)}H(),$()},handleEnd:()=>{t.onDestroy?.()}})}}n.addEventListener("mouseenter",k),n.addEventListener("mousemove",k),n.addEventListener("mouseleave",D);const Q=()=>{if(S)return;const e=c.getContext("2d",{willReadFrequently:!0});if(!e||!o||o.readyState<2)I=requestAnimationFrame(Q);else{if(c.width=o.videoWidth,c.height=o.videoHeight,e.drawImage(o,0,0,c.width,c.height),p){const n=e.getImageData(0,0,c.width,c.height),a=P.process(n);e.putImageData(a,0,0),b||(t.onAvatarReady?.(!0),b=!0,F(),B(),U(),W(),$(),D())}I=requestAnimationFrame(Q)}};W(),G(),U();const Z={updateStreams:({videoStream:e,audioStream:n,userMicrophoneStream:a})=>{e&&e instanceof MediaStream?g!==e&&(O.avatar("New video stream received:",{active:e.active,tracks:e.getTracks().length,videoTracks:e.getVideoTracks().length,id:e.id}),g=e,o.srcObject=e,S||o.play().then(()=>{S||p||b||(t.onAvatarReady?.(!0),b=!0,F(),B(),U(),W(),$(),j(),D())}).catch(e=>{S||"AbortError"===e?.name||(O.error("Failed to play video stream",e),t.onError?.(e))}),e.addEventListener("inactive",()=>{O.avatar("Video stream became inactive")}),e.getTracks().forEach(e=>{e.addEventListener("ended",()=>{O.avatar("Video track ended:",e.kind)})}),p&&!I&&(I=requestAnimationFrame(Q))):(g=null,o.srcObject=null),void 0!==n&&(n&&n instanceof MediaStream?v!==n&&(v=n,s.srcObject=n,S||s.play().catch(e=>{S||"AbortError"===e?.name||(O.error("Failed to play audio stream",e),t.onError?.(e))})):(v=null,s.srcObject=null)),void 0!==a&&(h=a??null,w?.update({userMicrophoneStream:h}))},updateWaveform:e=>{B(),w?.update(e)},updateFeatures:e=>{t.features={...t.features||{},...e||{}},p=(t.features?.backgroundRemoval?.enabled&&"silhouette"===t.avatarStyle?.view)??!1,p?(o.classList.add("np_companion__d-none"),c.classList.remove("np_companion__d-none")):(o.classList.remove("np_companion__d-none"),c.classList.add("np_companion__d-none")),w?.update({features:{waveform:{enabled:!1!==t.features?.waveform?.enabled}}}),W(),G(),U(),$()},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||(b=!1,t.onAvatarReady?.(!1))},updateScreenShareState:e=>{t.isScreenSharing=e,w?.update({isScreenSharing:e})},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":C="ended"!==e.data?.state&&"canceled"!==e.data?.state,w?.update({isAvatarSpeaking:C});break;case"message_received":{const{message:t}=e.data||{};if("completed"===t?.action&&"string"==typeof t.content&&t.role){H(),$();const e=T.getCurrentTrigger();e&&!e.isInteractionNeeded&&T.hide()}break}case"avatar_connection_warning":t.showAvatarInactiveOverlay&&(T.show({type:q.SERVER_WARNING,duration:e.data?.disconnect_after??30,message:"Avatar is disconnecting due to inactivity. Say something to keep it active.",isInteractionNeeded:!1}),h&&(h.getAudioTracks().forEach(e=>e.enabled=!0),w?.update({isMuted:!1}),F(!1)))}t.onData?t.onData(e):O.data("onData callback NOT called. Reason:",{onDataExists:!!t.onData,dataType:typeof e,dataIsNull:null===e})},destroy:e=>{if(!S){S=!0,n.removeEventListener("mousemove",k),n.removeEventListener("mouseenter",k),n.removeEventListener("mouseleave",D),null!=E&&window.clearTimeout(E),null!=I&&(cancelAnimationFrame(I),I=null),_&&(clearTimeout(_),_=null);try{o.pause(),o.srcObject=null}catch{}try{s.pause(),s.srcObject=null}catch{}try{g?.getTracks().forEach(e=>e.stop())}catch{}try{v?.getTracks().forEach(e=>e.stop())}catch{}g=null,v=null,w?.destroy(),w=null,T?.destroy(),n.parentNode&&n.parentNode.removeChild(n),b=!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,onScreenShareToggle:t.onScreenShareToggle,isScreenSharing:t.isScreenSharing,isScreenShareSupported:t.isScreenShareSupported});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,onScreenShareToggle:e.onScreenShareToggle??t.onScreenShareToggle,isScreenSharing:e.isScreenSharing??t.isScreenSharing,isScreenShareSupported:e.isScreenShareSupported??t.isScreenShareSupported}),Object.assign(t,e)},updateStreams:e=>{a.updateStreams(e)},handleMessage:e=>{a.handleMessage(e)},updateScreenShareState:e=>{a.updateScreenShareState(e)},destroy:()=>{a.destroy(!0),n.parentNode===e&&e.removeChild(n),t.onDestroy?.()}}}(this.rootEl,{avatarStyle:this.config.avatarStyle,features:N.getState().app.features,onData:this.config.onData,onAvatarReady:this.config.onAvatarReady,onInactivityStatusChange:this.config.onInactivityStatusChange,onDestroy:()=>this.destroyInstance("ui_end"),onError:this.config.onError,...n}),this.initializeWebRTC().catch(e=>{O.critical_error("Failed to establish WebRTC connection:",e),this.config?.onError?.(e)})}async handleScreenShareToggle(){if(this.screenShareController)try{await this.screenShareController.toggle(),this.embed?.updateScreenShareState(this.screenShareController.isSharing())}catch(e){O.critical_warn("SDK","Screen share toggle failed:",e),this.config?.onError?.(e),this.embed?.updateScreenShareState(this.screenShareController.isSharing())}}async initializeWebRTC(){const e=N.getState().avatar.connectionToken;if(e&&!this.webrtcController){O.connection("Connecting WebRTC..."),this.webrtcController=function(e={}){const{currentAudioDeviceId:t,functions:n,screenShareCapture:a,onChatMessage:i,onConnectionSuccess:s,onConnectionError:c,onStreams:l,onDataChannel:d,maxReconnectAttempts:u=3,reconnectInterval:h=2e3}=e;let m=null,f=null,S=null,C=null,b=null,y=null,E=null,w="disconnected",_=0,T=null,I=null,k=!0,D=null;function A(e,t){return e&&e.readyState===WebSocket.OPEN?(e.send(JSON.stringify(t)),!0):(O.critical_warn("WebRTC",`WS send skipped; state=${e?.readyState}`),!1)}function R(e){D=e,c?.(e)}function L(e){w=e,O.webrtc(`Connection status changed to: ${e}`)}function M(){if(!k||!I||_>=u){if(_>=u){const e=_;O.critical_error("WebRTC",`All ${u} reconnect attempts exhausted. Closing WebSocket and WebRTC connections.`),x();const t=new r("Connection failed after max retry attempts. Closing all connections.",{maxAttempts:u,lastAttempt:e});D=t,c?.(t)}}else _+=1,L("reconnecting"),O.webrtc(`Attempting to reconnect (${_}/${u})...`),T=setTimeout(async()=>{try{if(!I)return;await P(I.connection.signalingEndpoint,I.connection.id,!0),!m&&I&&await F(I.token)}catch(e){O.error("WebRTC","Reconnection attempt failed:",e),M()}},h)}async function P(e,t,n=!1){const a=`${e.replace(/\/$/,"")}/ws/connections/${t}/signaling`;f&&f.readyState===WebSocket.OPEN&&f.close();const i=new WebSocket(a);return f=i,await new Promise((e,t)=>{i.onopen=()=>{O.connection(n?"WebSocket reconnected":"WebSocket connected"),L("connected"),_=0,T&&(clearTimeout(T),T=null),e()},i.onclose=e=>{O.connection("WebSocket closed:",e),f=null,L("disconnected"),!e.wasClean&&k&&M(),t(new r("WebSocket connection closed",{code:e.code,reason:e.reason,wasClean:e.wasClean}))},i.onerror=e=>{f=null,L("disconnected");const n=new r("WebSocket connection error",{error:e,timestamp:(new Date).toISOString()});R(n),t(n)}}),N.dispatch(g(void 0)),i}async function F(e){if(m&&"disconnected"!==w)O.warn("WebRTC","Connection already in progress, skipping...");else try{L("connecting"),D=null;const c=(e=>{try{const t=atob(e);return JSON.parse(t)}catch(e){return O.critical_error("decodeToBase64: Error decoding token",e),null}})(e);if(!c)throw new r("Failed to decode connection token",{token:e?"provided":"missing"});I={...c,token:e};const u=await P(c.connection.signalingEndpoint,c.connection.id),h=await async function(){O.webrtc("Create PeerConnection");const e=new RTCPeerConnection(ne);return m=e,e.addEventListener("connectionstatechange",()=>{"failed"===e.connectionState?(R(new r("WebRTC connection failed")),M()):"connected"===e.connectionState&&(L("connected"),_=0,T&&(clearTimeout(T),T=null))}),function(e){E=e.addTransceiver("audio",{direction:"sendrecv"});const t=e.addTransceiver("video",{direction:"recvonly"});if(a){const t=a.getCanvas().captureStream(1);t.getTracks().forEach(n=>{e.addTrack(n,t)})}O.webrtc("Added transceivers",{videoTransceiver:t,audioTransceiver:E});const r=e.createDataChannel("chat",{ordered:!0});y=r,r.onopen=()=>{O.webrtc("Data channel opened"),N.dispatch(p(r)),d?.(r),s?.(),n&&n.length>0&&(V({type:ee.SET_SETTINGS,data:{functions:n}}),O.webrtc("Functions sent via data channel",n))},r.onclose=()=>{O.webrtc("Data channel closed"),N.dispatch(p(null))},r.onerror=e=>{O.critical_error("WebRTC",e),R(new o("Data channel error",{error:e}))},r.onmessage=e=>{try{const t=JSON.parse(e.data);O.data("Data channel message received:",t),i?.(t)}catch{i?.({event:"message_received",data:{message:{content:e.data,action:"completed"}}})}}}(e),e.ontrack=e=>{const t=e.streams[0];O.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?(C=t,b=t):"audio"===e.track.kind&&(b=t,C||(C=t)),l?.({videoStream:C,audioStream:b})},e}();await async function(){try{O.webrtc("Setting up user media");const e=await navigator.mediaDevices.getUserMedia({audio:t?{deviceId:{exact:t},noiseSuppression:!0,echoCancellation:!0,autoGainControl:!0}:{noiseSuppression:!0,echoCancellation:!0,autoGainControl:!0},video:!1});if(S=e,E&&e.getAudioTracks().length>0){const t=e.getAudioTracks()[0];await E.sender.replaceTrack(t)}l?.({userMicrophoneStream:e})}catch(e){O.critical_warn("WebRTC",e),R(new r("Failed to access user media",{error:e,deviceId:t}))}}(),await async function(e,t){e.addEventListener("icecandidate",e=>{const n=e.candidate;n&&(O.webrtc("send ICE candidate"),A(t,{type:"add_ice_candidate",data:{candidate:n}}))}),e.addEventListener("negotiationneeded",async()=>{O.webrtc("negotiationneeded — creating new offer");try{const n=await e.createOffer();await e.setLocalDescription(n),A(t,{type:"set_remote_description",data:n})}catch(e){O.critical_error("WebRTC","Failed to renegotiate:",e)}}),O.webrtc("createOffer → setLocalDescription → set_remote_description");const n=await e.createOffer();await e.setLocalDescription(n),A(t,{type:"set_remote_description",data:n})}(h,u),u.onmessage=e=>async function(e,t,n){try{const a=JSON.parse(n.data);switch(a.type){case"set_remote_description":O.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":O.critical_error("WebRTC",a.data?.error),R(new o(a.data?.error||"Server error",{serverMessage:a.data})),e.close(),t.close();break;default:O.webrtc("Unknown message type:",a.type)}}catch(e){O.critical_error("WebRTC",e),R(new o("Failed to process WebSocket message",{originalError:e,rawMessage:n.data}))}}(h,u,e)}catch(e){const t=e;throw O.critical_error("WebRTC",t),R(t),L("disconnected"),t}}function x(){k=!1,T&&(clearTimeout(T),T=null),_=0;try{if(y)try{y.close()}catch{}if(f)try{f.readyState!==WebSocket.OPEN&&f.readyState!==WebSocket.CONNECTING||f.close(1e3,"Connection closed by client")}catch{}try{C?.getTracks().forEach(e=>e.stop())}catch{}try{b?.getTracks().forEach(e=>e.stop())}catch{}if(m)try{m.getSenders().forEach(e=>{e.track&&e.track.stop()}),m.close()}catch{}if(S)try{S.getTracks().forEach(e=>e.stop())}catch{}}catch(e){O.critical_warn("WebRTC",e)}finally{y=null,f=null,m=null,S=null,E=null,C=null,b=null,I=null,L("disconnected"),N.dispatch(v(void 0))}}return N.dispatch(v(x)),{startWithToken:F,close:x,forceReconnect:async function(){if(I){x(),k=!0,_=0;try{await F(I.token)}catch(e){throw R(e),e}}else R(new r("No connection data available for reconnect"))},getConnectionStatus:function(){return w},getReconnectAttempts:function(){return _},getError:function(){return D},updateAudioDevice:async function(e){if(E&&E.sender.track)try{const t=await navigator.mediaDevices.getUserMedia({audio:{deviceId:{exact:e},noiseSuppression:!0,echoCancellation:!0,autoGainControl:!0},video:!1}),n=t.getAudioTracks()[0];await E.sender.replaceTrack(n),S&&S.getTracks().forEach(e=>e.stop()),S=t,l?.({userMicrophoneStream:t}),O.webrtc(`Audio device updated to: ${e}`)}catch(t){O.critical_warn("WebRTC","Failed to update audio device:",t),R(new r("Failed to update audio device",{error:t,deviceId:e}))}else O.warn("WebRTC","No audio transceiver available for device update")}}}({maxReconnectAttempts:3,reconnectInterval:2e3,functions:this.config?.functions,screenShareCapture:this.screenShareController?.getCapture()??null,onStreams:e=>{this.embed?.updateStreams(e)},onChatMessage:e=>{this.embed?.handleMessage(e)},onConnectionError:e=>{O.critical_error("WebRTC connection error:",e),this.config?.onError?.(e),this.webrtcController&&"disconnected"===this.webrtcController.getConnectionStatus()&&(O.critical_error("SDK","Connection unrecoverable after all retries. Destroying SDK instance."),this.destroyInstance("internal"))}});try{O.connection("Initializing WebRTC connection with token:",`${e.substring(0,50)}...`),await this.webrtcController.startWithToken(e),O.connection("WebRTC initialization completed with token")}catch(e){throw O.critical_error("SDK","Failed to Initialize WebRTC:",e),this.webrtcController=null,e}}}destroyWebRTC(){if(this.screenShareController?.isSharing()&&(this.screenShareController.stop(),this.embed?.updateScreenShareState(!1)),this.webrtcController){O.info("SDK","Destroying WebRTC controller");try{this.webrtcController.close()}catch(e){O.critical_error("SDK","Error closing WebRTC controller:",e)}this.webrtcController=null}}destroyInstance(e,t){if(!e)return void O.critical_warn("SDK","destroyInstance ignored (no reason)");$("sdk_destroyed",{reason:e}),t?.();const n=this.config?.onDestroy;if(I(null),N.dispatch(g(void 0)),N.dispatch(v(void 0)),N.dispatch(f(!1)),N.dispatch(E()),N.dispatch(w(void 0)),this.embed){try{this.embed.update({onDestroy:void 0}),this.embed.destroy()}catch(e){O.critical_error("Error during cleanup:",e)}this.embed=null}this.screenShareController&&(this.screenShareController.destroy(),this.screenShareController=null),this.faceTrackingController&&(this.faceTrackingController.destroy(),this.faceTrackingController=null),this.unloadHandler&&"undefined"!=typeof window&&(window.removeEventListener("beforeunload",this.unloadHandler),this.unloadHandler=null),this.destroyWebRTC(),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:l.ALREADY_INITIALIZED});t.analytics?.enabled&&(function(e){H=new G(e)}(t.analytics),$("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:l.INVALID_TOKEN})}(e);const n={avatarStyle:{view:"round"},position:d.BOTTOM_RIGHT,...t};this.config=n,N.dispatch(g(e)),N.dispatch(f(!1)),N.dispatch(_(n.debug)),this.config.features&&Object.entries(this.config.features).forEach(([e,t])=>{const n=W(e,t);N.dispatch(y({feature:e,config:n}))}),I(e=>{try{this.embed&&this.embed.update({features:e})}catch(e){O.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:(O.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?.(),$("sdk_init_completed",{version:this.version,initTime:Date.now()}),this.createInstanceMethods()}catch(n){const a=u.handle(n,{method:"init",tokenProvided:!!e,config:t});throw t.onError?.(a),a}}createInstanceMethods(){const e=this;return{showAvatar:()=>{const e=document.getElementById("np_companion-avatar-container");e&&(e.style.display="block",B("show","avatar_widget"))},hideAvatar:()=>{const e=document.getElementById("np_companion-avatar-container");e&&(e.style.display="none",B("hide","avatar_widget"))},avatarIsVisible:()=>{const e=document.getElementById("np_companion-avatar-container");return!!e&&"none"!==e.style.display},destroy:()=>{const{closeConnectionHandler:e}=N.getState().avatar;this.destroyInstance("api",e)},updateStyles:e=>{this.config&&(this.config.style={...this.config.style??{},...e??{}},this.rootEl&&ie(this.rootEl,this.config.style))},setPosition:e=>{if(this.config&&(this.config.position=e,N.dispatch?.(w(e)),this.rootEl)){const t=re(e,this.config.avatarStyle?.view,this.config.className);this.rootEl.className=t}},clearPosition:()=>{this.config&&(N.dispatch?.(w(void 0)),this.config.position=void 0,this.rootEl&&(this.rootEl.className=re(void 0,this.config.avatarStyle?.view,this.config.className)))},enableFeature:e=>{N.dispatch?.(y({feature:e,config:{enabled:!0}})),"disclaimer"===e&&this.rootEl&&this.rootEl.classList.remove("np_companion_disclaimer-disabled")},disableFeature:e=>{N.dispatch?.(y({feature:e,config:{enabled:!1}})),"disclaimer"===e&&this.rootEl&&this.rootEl.classList.add("np_companion_disclaimer-disabled")},updateFeatureConfig:(e,t)=>{const n=W(e,t);N.dispatch?.(y({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=re(this.config.position,e.view,this.config.className);this.rootEl.className=t}this.embed&&this.embed.update({avatarStyle:this.config.avatarStyle})}},sendCommand:e=>{V(e)},startScreenShare:async()=>{if(!this.screenShareController?.isSharing())try{await(this.screenShareController?.start()),this.embed?.updateScreenShareState(this.screenShareController?.isSharing()??!1)}catch(e){throw O.critical_warn("SDK","Failed to start screen share:",e),this.config?.onError?.(e),e}},stopScreenShare:()=>{this.screenShareController?.isSharing()&&(this.screenShareController.stop(),this.embed?.updateScreenShareState(!1))},toggleScreenShare:async()=>{await this.handleScreenShareToggle()},get isScreenSharing(){return e.screenShareController?.isSharing()??!1},get isScreenShareSupported(){return ae()&&(N.getState().app.features.screenShare?.enabled??!1)},startFaceTracking:async()=>{const e=N.getState().app.features.faceTracking;if(!e?.enabled)throw new s("Face tracking is not enabled. Set features.faceTracking.enabled = true.",{code:l.FEATURE_DISABLED});this.faceTrackingController||(this.faceTrackingController=function(e={},t={}){const n=Math.min(Math.max(e.fps??15,1),30),a=e.talkingThreshold??.015,i=e.videoWidth??640,r=e.videoHeight??480,o=1e3/n;let s=null,d=null,u=null,h=null,p=null,m=null,f=!1,g=!1,v=0;const S=function(e=5){let t=[];return{push:n=>(t.push(n),t.length>e&&t.shift(),t.reduce((e,t)=>e+t,0)/t.length),reset(){t=[]}}}(e.smoothingFrames??5);function C(e,n){const a=new c(e,n);O.error("FaceTracking:",e),t.onError?.(a)}function b(){u||(u=document.createElement("canvas")),h||(h=u.getContext("2d"))}function y(e){f&&(e-v>=o&&(v=e,async function(){if(d&&p&&!(d.readyState<4))try{b(),u.width=d.videoWidth,u.height=d.videoHeight,h.drawImage(d,0,0);const e=await p.estimateFaces(u);if(e&&e.length>0){const n=e[0].keypoints,o=d.videoWidth||i,s=d.videoHeight||r,c=n.map(e=>({x:e.x/o,y:e.y/s,z:e.z??0})),l=function(e,t,n){if(!e||0===e.length)return null;const a=e[13],i=e[14],r=e[61],o=e[291];if(!(a&&i&&r&&o))return null;const s=Math.abs(a.y-i.y),c=Math.abs(o.x-r.x),l=s/Math.max(c,1),d=t||640,u=n||480;return{mouthLandmarks:{topLip:{x:a.x/d,y:a.y/u},bottomLip:{x:i.x/d,y:i.y/u},leftCorner:{x:r.x/d,y:r.y/u},rightCorner:{x:o.x/d,y:o.y/u}},openingRatio:l}}(n,o,s);let u=!1;l&&(u=S.push(l.openingRatio)>a),t.onData?.({landmarks:c,mouthLandmarks:l?.mouthLandmarks??null,isTalking:u})}else t.onData?.(null)}catch(e){O.error("FaceTracking: detection error",e)}}()),m=requestAnimationFrame(y))}function E(){f=!1,null!==m&&(cancelAnimationFrame(m),m=null),s&&(s.getTracks().forEach(e=>e.stop()),s=null),d&&(d.srcObject=null,d=null),S.reset(),O.info("FaceTracking:","Stopped (model kept for restart)")}return{start:async function(){g?C("Cannot start: face tracking service has been destroyed.",l.DETECTION_FAILED):f||(O.info("FaceTracking:","Starting face tracking..."),await async function(){try{s=await navigator.mediaDevices.getUserMedia({video:{width:i,height:r,facingMode:"user"},audio:!1})}catch(e){throw e instanceof Error?"NotAllowedError"===e.name?C("Camera permission denied. Please allow camera access for face tracking.",l.CAMERA_PERMISSION_DENIED):"NotFoundError"===e.name?C("No camera found. Please ensure a camera is connected.",l.CAMERA_NOT_FOUND):C(`Camera error: ${e.message}`,l.CAMERA_PERMISSION_DENIED):C("Failed to access camera for face tracking.",l.CAMERA_PERMISSION_DENIED),e}d=document.createElement("video"),d.setAttribute("autoplay",""),d.setAttribute("playsinline",""),d.setAttribute("muted",""),d.muted=!0,d.srcObject=s,await new Promise((e,t)=>{if(!d)return t();d.onloadedmetadata=()=>{d.play().then(e).catch(t)}})}(),p||await async function(){try{const[e,t]=await Promise.all([import("@tensorflow/tfjs"),import("@tensorflow-models/face-landmarks-detection")]);await e.ready();const n=t.SupportedModels.MediaPipeFaceMesh;p=await t.createDetector(n,{runtime:"tfjs",maxFaces:1,refineLandmarks:!0}),O.info("FaceTracking:","MediaPipe Face Mesh model loaded")}catch(e){throw C("Failed to load face detection model.",l.MODEL_LOAD_FAILED),e}}(),b(),S.reset(),f=!0,v=0,m=requestAnimationFrame(y),O.info("FaceTracking:",`Detection running at ${n} FPS`))},stop:E,isActive:function(){return f},destroy:function(){if(E(),p){try{p.dispose()}catch{}p=null}u=null,h=null,g=!0,O.info("FaceTracking:","Destroyed")}}}({fps:e.fps,talkingThreshold:e.talkingThreshold},{onData:e=>{this.config?.onFaceTrackingData?.(e)},onError:e=>{this.config?.onFaceTrackingError?.(e),this.config?.onError?.(e)}})),await this.faceTrackingController.start()},stopFaceTracking:()=>{this.faceTrackingController?.stop()}}}}Object.defineProperty(oe,"instance",{enumerable:!0,configurable:!0,writable:!0,value:null});const se=oe.getInstance();"undefined"!=typeof window&&(window.napsterCompanionApiSDK=se);export{ee as DataChannelMessageType,se as NapsterCompanionApiSdk,d as Position,se as default};