obi-sdk 0.19.54-beta.0 → 0.19.54-beta.1

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.
@@ -42,7 +42,7 @@ a=extmap-allow-mixed`)!==-1){const a=r.sdp.split(`
42
42
  `},sg}var MS;function fD(){if(MS)return or;MS=1;var t=dD(),e=hD(),n=og();return or.grammar=n,or.write=e,or.parse=t.parse,or.parseParams=t.parseParams,or.parseFmtpConfig=t.parseFmtpConfig,or.parsePayloads=t.parsePayloads,or.parseRemoteCandidates=t.parseRemoteCandidates,or.parseImageAttributes=t.parseImageAttributes,or.parseSimulcastStreamList=t.parseSimulcastStreamList,or}var Ha=fD();function lg(t,e,n){var i,r,a;e===void 0&&(e=50),n===void 0&&(n={});var o=(i=n.isImmediate)!=null&&i,s=(r=n.callback)!=null&&r,l=n.maxWait,c=Date.now(),u=[];function d(){if(l!==void 0){var p=Date.now()-c;if(p+e>=l)return l-p}return e}var h=function(){var p=[].slice.call(arguments),b=this;return new Promise(function(m,S){var g=o&&a===void 0;if(a!==void 0&&clearTimeout(a),a=setTimeout(function(){if(a=void 0,c=Date.now(),!o){var x=t.apply(b,p);s&&s(x),u.forEach(function(v){return(0,v.resolve)(x)}),u=[]}},d()),g){var y=t.apply(b,p);return s&&s(y),m(y)}u.push({resolve:m,reject:S})})};return h.cancel=function(p){a!==void 0&&clearTimeout(a),u.forEach(function(b){return(0,b.reject)(p)}),u=[]},h}const pD=.7,mD=20,Us={NegotiationStarted:"negotiationStarted",NegotiationComplete:"negotiationComplete",RTPVideoPayloadTypes:"rtpVideoPayloadTypes"};class DS extends Rr.EventEmitter{get pc(){return this._pc||(this._pc=this.createPC()),this._pc}constructor(e){let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};var i;super(),this.log=Re,this.ddExtID=0,this.latestOfferId=0,this.pendingCandidates=[],this.restartingIce=!1,this.renegotiate=!1,this.trackBitrates=[],this.remoteStereoMids=[],this.remoteNackMids=[],this.negotiate=lg(r=>E(this,void 0,void 0,function*(){this.emit(Us.NegotiationStarted);try{yield this.createAndSendOffer()}catch(a){if(r)r(a);else throw a}}),mD),this.close=()=>{this._pc&&(this._pc.close(),this._pc.onconnectionstatechange=null,this._pc.oniceconnectionstatechange=null,this._pc.onicegatheringstatechange=null,this._pc.ondatachannel=null,this._pc.onnegotiationneeded=null,this._pc.onsignalingstatechange=null,this._pc.onicecandidate=null,this._pc.ondatachannel=null,this._pc.ontrack=null,this._pc.onconnectionstatechange=null,this._pc.oniceconnectionstatechange=null,this._pc=null)},this.log=Kr((i=n.loggerName)!==null&&i!==void 0?i:rr.PCTransport),this.loggerOptions=n,this.config=e,this._pc=this.createPC(),this.offerLock=new In}createPC(){const e=new RTCPeerConnection(this.config);return e.onicecandidate=n=>{var i;n.candidate&&((i=this.onIceCandidate)===null||i===void 0||i.call(this,n.candidate))},e.onicecandidateerror=n=>{var i;(i=this.onIceCandidateError)===null||i===void 0||i.call(this,n)},e.oniceconnectionstatechange=()=>{var n;(n=this.onIceConnectionStateChange)===null||n===void 0||n.call(this,e.iceConnectionState)},e.onsignalingstatechange=()=>{var n;(n=this.onSignalingStatechange)===null||n===void 0||n.call(this,e.signalingState)},e.onconnectionstatechange=()=>{var n;(n=this.onConnectionStateChange)===null||n===void 0||n.call(this,e.connectionState)},e.ondatachannel=n=>{var i;(i=this.onDataChannel)===null||i===void 0||i.call(this,n)},e.ontrack=n=>{var i;(i=this.onTrack)===null||i===void 0||i.call(this,n)},e}get logContext(){var e,n;return Object.assign({},(n=(e=this.loggerOptions).loggerContextCb)===null||n===void 0?void 0:n.call(e))}get isICEConnected(){return this._pc!==null&&(this.pc.iceConnectionState==="connected"||this.pc.iceConnectionState==="completed")}addIceCandidate(e){return E(this,void 0,void 0,function*(){if(this.pc.remoteDescription&&!this.restartingIce)return this.pc.addIceCandidate(e);this.pendingCandidates.push(e)})}setRemoteDescription(e,n){return E(this,void 0,void 0,function*(){var i;if(e.type==="answer"&&this.latestOfferId>0&&n>0&&n!==this.latestOfferId)return this.log.warn("ignoring answer for old offer",Object.assign(Object.assign({},this.logContext),{offerId:n,latestOfferId:this.latestOfferId})),!1;let r;if(e.type==="offer"){let{stereoMids:a,nackMids:o}=gD(e);this.remoteStereoMids=a,this.remoteNackMids=o}else if(e.type==="answer"){const a=Ha.parse((i=e.sdp)!==null&&i!==void 0?i:"");a.media.forEach(o=>{const s=cg(o.mid);o.type==="audio"&&this.trackBitrates.some(l=>{if(!l.transceiver||s!=l.transceiver.mid)return!1;let c=0;if(o.rtp.some(d=>d.codec.toUpperCase()===l.codec.toUpperCase()?(c=d.payload,!0):!1),c===0)return!0;let u=!1;for(const d of o.fmtp)if(d.payload===c){d.config=d.config.split(";").filter(h=>!h.includes("maxaveragebitrate")).join(";"),l.maxbr>0&&(d.config+=";maxaveragebitrate=".concat(l.maxbr*1e3)),u=!0;break}return u||l.maxbr>0&&o.fmtp.push({payload:c,config:"maxaveragebitrate=".concat(l.maxbr*1e3)}),!0})}),r=Ha.write(a)}return yield this.setMungedSDP(e,r,!0),this.pendingCandidates.forEach(a=>{this.pc.addIceCandidate(a)}),this.pendingCandidates=[],this.restartingIce=!1,this.renegotiate?(this.renegotiate=!1,yield this.createAndSendOffer()):e.type==="answer"&&(this.emit(Us.NegotiationComplete),e.sdp&&Ha.parse(e.sdp).media.forEach(o=>{o.type==="video"&&this.emit(Us.RTPVideoPayloadTypes,o.rtp)})),!0})}createAndSendOffer(e){return E(this,void 0,void 0,function*(){var n;const i=yield this.offerLock.lock();try{if(this.onOffer===void 0)return;if(e!=null&&e.iceRestart&&(this.log.debug("restarting ICE",this.logContext),this.restartingIce=!0),this._pc&&this._pc.signalingState==="have-local-offer"){const s=this._pc.remoteDescription;if(e!=null&&e.iceRestart&&s)yield this._pc.setRemoteDescription(s);else{this.renegotiate=!0;return}}else if(!this._pc||this._pc.signalingState==="closed"){this.log.warn("could not createOffer with closed peer connection",this.logContext);return}this.log.debug("starting to negotiate",this.logContext);const r=this.latestOfferId+1;this.latestOfferId=r;const a=yield this.pc.createOffer(e);this.log.debug("original offer",Object.assign({sdp:a.sdp},this.logContext));const o=Ha.parse((n=a.sdp)!==null&&n!==void 0?n:"");if(o.media.forEach(s=>{LS(s),s.type==="audio"?PS(s,["all"],[]):s.type==="video"&&this.trackBitrates.some(l=>{if(!s.msid||!l.cid||!s.msid.includes(l.cid))return!1;let c=0;if(s.rtp.some(d=>d.codec.toUpperCase()===l.codec.toUpperCase()?(c=d.payload,!0):!1),c===0||(ar(l.codec)&&!Vo()&&this.ensureVideoDDExtensionForSVC(s,o),!ar(l.codec)))return!0;const u=Math.round(l.maxbr*pD);for(const d of s.fmtp)if(d.payload===c){d.config.includes("x-google-start-bitrate")||(d.config+=";x-google-start-bitrate=".concat(u));break}return!0})}),this.latestOfferId>r){this.log.warn("latestOfferId mismatch",Object.assign(Object.assign({},this.logContext),{latestOfferId:this.latestOfferId,offerId:r}));return}yield this.setMungedSDP(a,Ha.write(o)),this.onOffer(a,this.latestOfferId)}finally{i()}})}createAndSetAnswer(){return E(this,void 0,void 0,function*(){var e;const n=yield this.pc.createAnswer(),i=Ha.parse((e=n.sdp)!==null&&e!==void 0?e:"");return i.media.forEach(r=>{LS(r),r.type==="audio"&&PS(r,this.remoteStereoMids,this.remoteNackMids)}),yield this.setMungedSDP(n,Ha.write(i)),n})}createDataChannel(e,n){return this.pc.createDataChannel(e,n)}addTransceiver(e,n){return this.pc.addTransceiver(e,n)}addTransceiverOfKind(e,n){return this.pc.addTransceiver(e,n)}addTrack(e){if(!this._pc)throw new Qt("PC closed, cannot add track");return this._pc.addTrack(e)}setTrackCodecBitrate(e){this.trackBitrates.push(e)}setConfiguration(e){var n;if(!this._pc)throw new Qt("PC closed, cannot configure");return(n=this._pc)===null||n===void 0?void 0:n.setConfiguration(e)}canRemoveTrack(){var e;return!!(!((e=this._pc)===null||e===void 0)&&e.removeTrack)}removeTrack(e){var n;return(n=this._pc)===null||n===void 0?void 0:n.removeTrack(e)}getConnectionState(){var e,n;return(n=(e=this._pc)===null||e===void 0?void 0:e.connectionState)!==null&&n!==void 0?n:"closed"}getICEConnectionState(){var e,n;return(n=(e=this._pc)===null||e===void 0?void 0:e.iceConnectionState)!==null&&n!==void 0?n:"closed"}getSignallingState(){var e,n;return(n=(e=this._pc)===null||e===void 0?void 0:e.signalingState)!==null&&n!==void 0?n:"closed"}getTransceivers(){var e,n;return(n=(e=this._pc)===null||e===void 0?void 0:e.getTransceivers())!==null&&n!==void 0?n:[]}getSenders(){var e,n;return(n=(e=this._pc)===null||e===void 0?void 0:e.getSenders())!==null&&n!==void 0?n:[]}getLocalDescription(){var e;return(e=this._pc)===null||e===void 0?void 0:e.localDescription}getRemoteDescription(){var e;return(e=this.pc)===null||e===void 0?void 0:e.remoteDescription}getStats(){return this.pc.getStats()}getConnectedAddress(){return E(this,void 0,void 0,function*(){var e;if(!this._pc)return;let n="";const i=new Map,r=new Map;if((yield this._pc.getStats()).forEach(s=>{switch(s.type){case"transport":n=s.selectedCandidatePairId;break;case"candidate-pair":n===""&&s.selected&&(n=s.id),i.set(s.id,s);break;case"remote-candidate":r.set(s.id,"".concat(s.address,":").concat(s.port));break}}),n==="")return;const o=(e=i.get(n))===null||e===void 0?void 0:e.remoteCandidateId;if(o!==void 0)return r.get(o)})}setMungedSDP(e,n,i){return E(this,void 0,void 0,function*(){if(n){const r=e.sdp;e.sdp=n;try{this.log.debug("setting munged ".concat(i?"remote":"local"," description"),this.logContext),i?yield this.pc.setRemoteDescription(e):yield this.pc.setLocalDescription(e);return}catch(a){this.log.warn("not able to set ".concat(e.type,", falling back to unmodified sdp"),Object.assign(Object.assign({},this.logContext),{error:a,sdp:n})),e.sdp=r}}try{i?yield this.pc.setRemoteDescription(e):yield this.pc.setLocalDescription(e)}catch(r){let a="unknown error";r instanceof Error?a=r.message:typeof r=="string"&&(a=r);const o={error:a,sdp:e.sdp};throw!i&&this.pc.remoteDescription&&(o.remoteSdp=this.pc.remoteDescription),this.log.error("unable to set ".concat(e.type),Object.assign(Object.assign({},this.logContext),{fields:o})),new Um(a)}})}ensureVideoDDExtensionForSVC(e,n){var i,r;if(!((i=e.ext)===null||i===void 0?void 0:i.some(o=>o.uri===dS))){if(this.ddExtID===0){let o=0;n.media.forEach(s=>{var l;s.type==="video"&&((l=s.ext)===null||l===void 0||l.forEach(c=>{c.value>o&&(o=c.value)}))}),this.ddExtID=o+1}(r=e.ext)===null||r===void 0||r.push({value:this.ddExtID,uri:dS})}}}function PS(t,e,n){const i=cg(t.mid);let r=0;t.rtp.some(a=>a.codec==="opus"?(r=a.payload,!0):!1),r>0&&(t.rtcpFb||(t.rtcpFb=[]),n.includes(i)&&!t.rtcpFb.some(a=>a.payload===r&&a.type==="nack")&&t.rtcpFb.push({payload:r,type:"nack"}),(e.includes(i)||e.length===1&&e[0]==="all")&&t.fmtp.some(a=>a.payload===r?(a.config.includes("stereo=1")||(a.config+=";stereo=1"),!0):!1))}function gD(t){var e;const n=[],i=[],r=Ha.parse((e=t.sdp)!==null&&e!==void 0?e:"");let a=0;return r.media.forEach(o=>{var s;const l=cg(o.mid);o.type==="audio"&&(o.rtp.some(c=>c.codec==="opus"?(a=c.payload,!0):!1),!((s=o.rtcpFb)===null||s===void 0)&&s.some(c=>c.payload===a&&c.type==="nack")&&i.push(l),o.fmtp.some(c=>c.payload===a?(c.config.includes("sprop-stereo=1")&&n.push(l),!0):!1))}),{stereoMids:n,nackMids:i}}function LS(t){if(t.connection){const e=t.connection.ip.indexOf(":")>=0;(t.connection.version===4&&e||t.connection.version===6&&!e)&&(t.connection.ip="0.0.0.0",t.connection.version=4)}}function cg(t){return typeof t=="number"?t.toFixed(0):t}const ug="vp8",vD={audioPreset:zm.music,dtx:!0,red:!0,forceStereo:!1,simulcast:!0,screenShareEncoding:qm.h1080fps15.encoding,stopMicTrackOnMute:!1,videoCodec:ug,backupCodec:!0,preConnectBuffer:!1},IS={deviceId:{ideal:"default"},autoGainControl:!0,echoCancellation:!0,noiseSuppression:!0,voiceIsolation:!0},jS={deviceId:{ideal:"default"},resolution:dc.h720.resolution},bD={adaptiveStream:!1,dynacast:!1,stopLocalTrackOnUnpublish:!0,reconnectPolicy:new $M,disconnectOnPageLeave:!0,webAudioMix:!1,singlePeerConnection:!1},dg={autoSubscribe:!0,maxRetries:1,peerConnectionTimeout:15e3,websocketTimeout:15e3};var Mt;(function(t){t[t.NEW=0]="NEW",t[t.CONNECTING=1]="CONNECTING",t[t.CONNECTED=2]="CONNECTED",t[t.FAILED=3]="FAILED",t[t.CLOSING=4]="CLOSING",t[t.CLOSED=5]="CLOSED"})(Mt||(Mt={}));class yD{get needsPublisher(){return this.isPublisherConnectionRequired}get needsSubscriber(){return this.isSubscriberConnectionRequired}get currentState(){return this.state}constructor(e,n,i){var r;this.peerConnectionTimeout=dg.peerConnectionTimeout,this.log=Re,this.updateState=()=>{var a,o;const s=this.state,l=this.requiredTransports.map(c=>c.getConnectionState());l.every(c=>c==="connected")?this.state=Mt.CONNECTED:l.some(c=>c==="failed")?this.state=Mt.FAILED:l.some(c=>c==="connecting")?this.state=Mt.CONNECTING:l.every(c=>c==="closed")?this.state=Mt.CLOSED:l.some(c=>c==="closed")?this.state=Mt.CLOSING:l.every(c=>c==="new")&&(this.state=Mt.NEW),s!==this.state&&(this.log.debug("pc state change: from ".concat(Mt[s]," to ").concat(Mt[this.state]),this.logContext),(a=this.onStateChange)===null||a===void 0||a.call(this,this.state,this.publisher.getConnectionState(),(o=this.subscriber)===null||o===void 0?void 0:o.getConnectionState()))},this.log=Kr((r=i.loggerName)!==null&&r!==void 0?r:rr.PCManager),this.loggerOptions=i,this.isPublisherConnectionRequired=n!=="subscriber-primary",this.isSubscriberConnectionRequired=n==="subscriber-primary",this.publisher=new DS(e,i),n!=="publisher-only"&&(this.subscriber=new DS(e,i),this.subscriber.onConnectionStateChange=this.updateState,this.subscriber.onIceConnectionStateChange=this.updateState,this.subscriber.onSignalingStatechange=this.updateState,this.subscriber.onIceCandidate=a=>{var o;(o=this.onIceCandidate)===null||o===void 0||o.call(this,a,ir.SUBSCRIBER)},this.subscriber.onDataChannel=a=>{var o;(o=this.onDataChannel)===null||o===void 0||o.call(this,a)},this.subscriber.onTrack=a=>{var o;(o=this.onTrack)===null||o===void 0||o.call(this,a)}),this.publisher.onConnectionStateChange=this.updateState,this.publisher.onIceConnectionStateChange=this.updateState,this.publisher.onSignalingStatechange=this.updateState,this.publisher.onIceCandidate=a=>{var o;(o=this.onIceCandidate)===null||o===void 0||o.call(this,a,ir.PUBLISHER)},this.publisher.onTrack=a=>{var o;(o=this.onTrack)===null||o===void 0||o.call(this,a)},this.publisher.onOffer=(a,o)=>{var s;(s=this.onPublisherOffer)===null||s===void 0||s.call(this,a,o)},this.state=Mt.NEW,this.connectionLock=new In,this.remoteOfferLock=new In}get logContext(){var e,n;return Object.assign({},(n=(e=this.loggerOptions).loggerContextCb)===null||n===void 0?void 0:n.call(e))}requirePublisher(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;this.isPublisherConnectionRequired=e,this.updateState()}createAndSendPublisherOffer(e){return this.publisher.createAndSendOffer(e)}setPublisherAnswer(e,n){return this.publisher.setRemoteDescription(e,n)}removeTrack(e){return this.publisher.removeTrack(e)}close(){return E(this,void 0,void 0,function*(){var e;if(this.publisher&&this.publisher.getSignallingState()!=="closed"){const n=this.publisher;for(const i of n.getSenders())try{n.canRemoveTrack()&&n.removeTrack(i)}catch(r){this.log.warn("could not removeTrack",Object.assign(Object.assign({},this.logContext),{error:r}))}}yield Promise.all([this.publisher.close(),(e=this.subscriber)===null||e===void 0?void 0:e.close()]),this.updateState()})}triggerIceRestart(){return E(this,void 0,void 0,function*(){this.subscriber&&(this.subscriber.restartingIce=!0),this.needsPublisher&&(yield this.createAndSendPublisherOffer({iceRestart:!0}))})}addIceCandidate(e,n){return E(this,void 0,void 0,function*(){var i;n===ir.PUBLISHER?yield this.publisher.addIceCandidate(e):yield(i=this.subscriber)===null||i===void 0?void 0:i.addIceCandidate(e)})}createSubscriberAnswerFromOffer(e,n){return E(this,void 0,void 0,function*(){var i,r,a;this.log.debug("received server offer",Object.assign(Object.assign({},this.logContext),{RTCSdpType:e.type,sdp:e.sdp,signalingState:(i=this.subscriber)===null||i===void 0?void 0:i.getSignallingState().toString()}));const o=yield this.remoteOfferLock.lock();try{return(yield(r=this.subscriber)===null||r===void 0?void 0:r.setRemoteDescription(e,n))?yield(a=this.subscriber)===null||a===void 0?void 0:a.createAndSetAnswer():void 0}finally{o()}})}updateConfiguration(e,n){var i;this.publisher.setConfiguration(e),(i=this.subscriber)===null||i===void 0||i.setConfiguration(e),n&&this.triggerIceRestart()}ensurePCTransportConnection(e,n){return E(this,void 0,void 0,function*(){var i;const r=yield this.connectionLock.lock();try{this.isPublisherConnectionRequired&&this.publisher.getConnectionState()!=="connected"&&this.publisher.getConnectionState()!=="connecting"&&(this.log.debug("negotiation required, start negotiating",this.logContext),this.publisher.negotiate()),yield Promise.all((i=this.requiredTransports)===null||i===void 0?void 0:i.map(a=>this.ensureTransportConnected(a,e,n)))}finally{r()}})}negotiate(e){return E(this,void 0,void 0,function*(){return new Promise((n,i)=>E(this,void 0,void 0,function*(){const r=setTimeout(()=>{i("negotiation timed out")},this.peerConnectionTimeout),a=()=>{clearTimeout(r),i("negotiation aborted")};e.signal.addEventListener("abort",a),this.publisher.once(Us.NegotiationStarted,()=>{e.signal.aborted||this.publisher.once(Us.NegotiationComplete,()=>{clearTimeout(r),n()})}),yield this.publisher.negotiate(o=>{clearTimeout(r),i(o)})}))})}addPublisherTransceiver(e,n){return this.publisher.addTransceiver(e,n)}addPublisherTransceiverOfKind(e,n){return this.publisher.addTransceiverOfKind(e,n)}getMidForReceiver(e){const i=(this.subscriber?this.subscriber.getTransceivers():this.publisher.getTransceivers()).find(r=>r.receiver===e);return i==null?void 0:i.mid}addPublisherTrack(e){return this.publisher.addTrack(e)}createPublisherDataChannel(e,n){return this.publisher.createDataChannel(e,n)}getConnectedAddress(e){return e===ir.PUBLISHER?this.publisher.getConnectedAddress():e===ir.SUBSCRIBER?this.publisher.getConnectedAddress():this.requiredTransports[0].getConnectedAddress()}get requiredTransports(){const e=[];return this.isPublisherConnectionRequired&&e.push(this.publisher),this.isSubscriberConnectionRequired&&this.subscriber&&e.push(this.subscriber),e}ensureTransportConnected(e,n){return E(this,arguments,void 0,function(i,r){var a=this;let o=arguments.length>2&&arguments[2]!==void 0?arguments[2]:this.peerConnectionTimeout;return function*(){if(i.getConnectionState()!=="connected")return new Promise((l,c)=>E(a,void 0,void 0,function*(){const u=()=>{this.log.warn("abort transport connection",this.logContext),yn.clearTimeout(d),c(xe.cancelled("room connection has been cancelled"))};r!=null&&r.signal.aborted&&u(),r==null||r.signal.addEventListener("abort",u);const d=yn.setTimeout(()=>{r==null||r.signal.removeEventListener("abort",u),c(xe.internal("could not establish pc connection"))},o);for(;this.state!==Mt.CONNECTED;)if(yield _n(50),r!=null&&r.signal.aborted){c(xe.cancelled("room connection has been cancelled"));return}yn.clearTimeout(d),r==null||r.signal.removeEventListener("abort",u),l()}))}()})}}const BS=5e3,_D=3e4;class Ke{static fetchRegionSettings(e,n,i){return E(this,void 0,void 0,function*(){const r=yield Ke.fetchLock.lock();try{const a=yield fetch("".concat(xD(e),"/regions"),{headers:{authorization:"Bearer ".concat(n)},signal:i});if(a.ok){const o=G8(a.headers),s=o?o*1e3:BS;return{regionSettings:yield a.json(),updatedAtInMs:Date.now(),maxAgeInMs:s}}else throw a.status===401?xe.notAllowed("Could not fetch region settings: ".concat(a.statusText),a.status):xe.internal("Could not fetch region settings: ".concat(a.statusText))}catch(a){throw a instanceof xe?a:i!=null&&i.aborted?xe.cancelled("Region fetching was aborted"):xe.serverUnreachable("Could not fetch region settings, ".concat(a instanceof Error?"".concat(a.name,": ").concat(a.message):a))}finally{r()}})}static scheduleRefetch(e,n,i){return E(this,void 0,void 0,function*(){const r=Ke.settingsTimeouts.get(e.hostname);clearTimeout(r),Ke.settingsTimeouts.set(e.hostname,setTimeout(()=>E(this,void 0,void 0,function*(){try{const a=yield Ke.fetchRegionSettings(e,n);Ke.updateCachedRegionSettings(e,n,a)}catch(a){if(a instanceof xe&&a.reason===xt.NotAllowed){Re.debug("token is not valid, cancelling auto region refresh");return}Re.debug("auto refetching of region settings failed",{error:a}),Ke.scheduleRefetch(e,n,i)}}),i))})}static updateCachedRegionSettings(e,n,i){Ke.cache.set(e.hostname,i),Ke.scheduleRefetch(e,n,i.maxAgeInMs)}static stopRefetch(e){const n=Ke.settingsTimeouts.get(e);n&&(clearTimeout(n),Ke.settingsTimeouts.delete(e))}static scheduleCleanup(e){let n=Ke.connectionTrackers.get(e);n&&(n.cleanupTimeout&&clearTimeout(n.cleanupTimeout),n.cleanupTimeout=setTimeout(()=>{const i=Ke.connectionTrackers.get(e);i&&i.connectionCount===0&&(Re.debug("stopping region refetch after disconnect delay",{hostname:e}),Ke.stopRefetch(e)),i&&(i.cleanupTimeout=void 0)},_D))}static cancelCleanup(e){const n=Ke.connectionTrackers.get(e);n!=null&&n.cleanupTimeout&&(clearTimeout(n.cleanupTimeout),n.cleanupTimeout=void 0)}notifyConnected(){const e=this.serverUrl.hostname;let n=Ke.connectionTrackers.get(e);n||(n={connectionCount:0},Ke.connectionTrackers.set(e,n)),n.connectionCount++,Ke.cancelCleanup(e)}notifyDisconnected(){const e=this.serverUrl.hostname,n=Ke.connectionTrackers.get(e);n&&(n.connectionCount=Math.max(0,n.connectionCount-1),n.connectionCount===0&&Ke.scheduleCleanup(e))}constructor(e,n){this.attemptedRegions=[],this.serverUrl=new URL(e),this.token=n}updateToken(e){this.token=e}isCloud(){return Ls(this.serverUrl)}getServerUrl(){return this.serverUrl}fetchRegionSettings(e){return E(this,void 0,void 0,function*(){return Ke.fetchRegionSettings(this.serverUrl,this.token,e)})}getNextBestRegionUrl(e){return E(this,void 0,void 0,function*(){if(!this.isCloud())throw Error("region availability is only supported for LiveKit Cloud domains");let n=Ke.cache.get(this.serverUrl.hostname);(!n||Date.now()-n.updatedAtInMs>n.maxAgeInMs)&&(n=yield this.fetchRegionSettings(e),Ke.updateCachedRegionSettings(this.serverUrl,this.token,n));const i=n.regionSettings.regions.filter(r=>!this.attemptedRegions.find(a=>a.url===r.url));if(i.length>0){const r=i[0];return this.attemptedRegions.push(r),Re.debug("next region: ".concat(r.region)),r.url}else return null})}resetAttempts(){this.attemptedRegions=[]}setServerReportedRegions(e){Ke.updateCachedRegionSettings(this.serverUrl,this.token,e)}}Ke.cache=new Map,Ke.settingsTimeouts=new Map,Ke.connectionTrackers=new Map,Ke.fetchLock=new In;function xD(t){return"".concat(t.protocol.replace("ws","http"),"//").concat(t.host,"/settings")}class Dt extends Error{constructor(e,n,i){super(n),this.code=e,this.message=zS(n,Dt.MAX_MESSAGE_BYTES),this.data=i?zS(i,Dt.MAX_DATA_BYTES):void 0}static fromProto(e){return new Dt(e.code,e.message,e.data)}toProto(){return new Y_({code:this.code,message:this.message,data:this.data})}static builtIn(e,n){return new Dt(Dt.ErrorCode[e],Dt.ErrorMessage[e],n)}}Dt.MAX_MESSAGE_BYTES=256,Dt.MAX_DATA_BYTES=15360,Dt.ErrorCode={APPLICATION_ERROR:1500,CONNECTION_TIMEOUT:1501,RESPONSE_TIMEOUT:1502,RECIPIENT_DISCONNECTED:1503,RESPONSE_PAYLOAD_TOO_LARGE:1504,SEND_FAILED:1505,UNSUPPORTED_METHOD:1400,RECIPIENT_NOT_FOUND:1401,REQUEST_PAYLOAD_TOO_LARGE:1402,UNSUPPORTED_SERVER:1403,UNSUPPORTED_VERSION:1404},Dt.ErrorMessage={APPLICATION_ERROR:"Application error in method handler",CONNECTION_TIMEOUT:"Connection timeout",RESPONSE_TIMEOUT:"Response timeout",RECIPIENT_DISCONNECTED:"Recipient disconnected",RESPONSE_PAYLOAD_TOO_LARGE:"Response payload too large",SEND_FAILED:"Failed to send",UNSUPPORTED_METHOD:"Method not supported at destination",RECIPIENT_NOT_FOUND:"Recipient not found",REQUEST_PAYLOAD_TOO_LARGE:"Request payload too large",UNSUPPORTED_SERVER:"RPC not supported by server",UNSUPPORTED_VERSION:"Unsupported RPC version"};const US=15360;function hg(t){return new TextEncoder().encode(t).length}function zS(t,e){if(hg(t)<=e)return t;let n=0,i=t.length;const r=new TextEncoder;for(;n<i;){const a=Math.floor((n+i+1)/2);r.encode(t.slice(0,a)).length<=e?n=a:i=a-1}return t.slice(0,n)}const fg=2e3;function dh(t,e){if(!e)return 0;let n,i;return"bytesReceived"in t?(n=t.bytesReceived,i=e.bytesReceived):"bytesSent"in t&&(n=t.bytesSent,i=e.bytesSent),n===void 0||i===void 0||t.timestamp===void 0||e.timestamp===void 0?0:(n-i)*8*1e3/(t.timestamp-e.timestamp)}const pg=typeof MediaRecorder<"u";class SD{constructor(){throw new Error("MediaRecorder is not available in this environment")}}const kD=pg?MediaRecorder:SD;class TD extends kD{constructor(e,n){if(!pg)throw new Error("MediaRecorder is not available in this environment");super(new MediaStream([e.mediaStreamTrack]),n);let i,r;const a=()=>r===void 0,o=()=>{this.removeEventListener("dataavailable",i),this.removeEventListener("stop",o),this.removeEventListener("error",s),r==null||r.close(),r=void 0},s=l=>{r==null||r.error(l),this.removeEventListener("dataavailable",i),this.removeEventListener("stop",o),this.removeEventListener("error",s),r=void 0};this.byteStream=new ReadableStream({start:l=>{r=l,i=c=>E(this,void 0,void 0,function*(){let u;if(c.data.arrayBuffer){const d=yield c.data.arrayBuffer();u=new Uint8Array(d)}else if(c.data.byteArray)u=c.data.byteArray;else throw new Error("no data available!");a()||l.enqueue(u)}),this.addEventListener("dataavailable",i)},cancel:()=>{o()}}),this.addEventListener("stop",o),this.addEventListener("error",s)}}function wD(){return pg}const CD=1e3,ED=1e4;class FS extends V{get sender(){return this._sender}set sender(e){this._sender=e}get constraints(){return this._constraints}get hasPreConnectBuffer(){return!!this.localTrackRecorder}constructor(e,n,i){let r=arguments.length>3&&arguments[3]!==void 0?arguments[3]:!1,a=arguments.length>4?arguments[4]:void 0;super(e,n,a),this.manuallyStopped=!1,this._isUpstreamPaused=!1,this.handleTrackMuteEvent=()=>this.debouncedTrackMuteHandler().catch(()=>this.log.debug("track mute bounce got cancelled by an unmute event",this.logContext)),this.debouncedTrackMuteHandler=lg(()=>E(this,void 0,void 0,function*(){yield this.pauseUpstream()}),5e3),this.handleTrackUnmuteEvent=()=>E(this,void 0,void 0,function*(){this.debouncedTrackMuteHandler.cancel("unmute"),yield this.resumeUpstream()}),this.handleEnded=()=>{this.isInBackground&&(this.reacquireTrack=!0),this._mediaStreamTrack.removeEventListener("mute",this.handleTrackMuteEvent),this._mediaStreamTrack.removeEventListener("unmute",this.handleTrackUnmuteEvent),this.emit(ne.Ended,this)},this.reacquireTrack=!1,this.providedByUser=r,this.muteLock=new In,this.pauseUpstreamLock=new In,this.trackChangeLock=new In,this.trackChangeLock.lock().then(o=>E(this,void 0,void 0,function*(){try{yield this.setMediaStreamTrack(e,!0)}finally{o()}})),this._constraints=e.getConstraints(),i&&(this._constraints=i)}get id(){return this._mediaStreamTrack.id}get dimensions(){if(this.kind!==V.Kind.Video)return;const{width:e,height:n}=this._mediaStreamTrack.getSettings();if(e&&n)return{width:e,height:n}}get isUpstreamPaused(){return this._isUpstreamPaused}get isUserProvided(){return this.providedByUser}get mediaStreamTrack(){var e,n;return(n=(e=this.processor)===null||e===void 0?void 0:e.processedTrack)!==null&&n!==void 0?n:this._mediaStreamTrack}get isLocal(){return!0}getSourceTrackSettings(){return this._mediaStreamTrack.getSettings()}setMediaStreamTrack(e,n){return E(this,void 0,void 0,function*(){var i;if(e===this._mediaStreamTrack&&!n)return;this._mediaStreamTrack&&(this.attachedElements.forEach(a=>{Ps(this._mediaStreamTrack,a)}),this.debouncedTrackMuteHandler.cancel("new-track"),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this._mediaStreamTrack.removeEventListener("mute",this.handleTrackMuteEvent),this._mediaStreamTrack.removeEventListener("unmute",this.handleTrackUnmuteEvent)),this.mediaStream=new MediaStream([e]),e&&(e.addEventListener("ended",this.handleEnded),e.addEventListener("mute",this.handleTrackMuteEvent),e.addEventListener("unmute",this.handleTrackUnmuteEvent),this._constraints=e.getConstraints());let r;if(this.processor&&e){if(this.log.debug("restarting processor",this.logContext),this.kind==="unknown")throw TypeError("cannot set processor on track of unknown kind");this.processorElement&&(Ds(e,this.processorElement),this.processorElement.muted=!0),yield this.processor.restart({track:e,kind:this.kind,element:this.processorElement}),r=this.processor.processedTrack}this.sender&&((i=this.sender.transport)===null||i===void 0?void 0:i.state)!=="closed"&&(yield this.sender.replaceTrack(r??e)),!this.providedByUser&&this._mediaStreamTrack!==e&&this._mediaStreamTrack.stop(),this._mediaStreamTrack=e,e&&(this._mediaStreamTrack.enabled=!this.isMuted,yield this.resumeUpstream(),this.attachedElements.forEach(a=>{Ds(r??e,a)}))})}waitForDimensions(){return E(this,arguments,void 0,function(){var e=this;let n=arguments.length>0&&arguments[0]!==void 0?arguments[0]:CD;return function*(){var i;if(e.kind===V.Kind.Audio)throw new Error("cannot get dimensions for audio tracks");((i=ii())===null||i===void 0?void 0:i.os)==="iOS"&&(yield _n(10));const r=Date.now();for(;Date.now()-r<n;){const a=e.dimensions;if(a)return a;yield _n(50)}throw new Jr("unable to get track dimensions after timeout")}()})}setDeviceId(e){return E(this,void 0,void 0,function*(){return this._constraints.deviceId===e&&this._mediaStreamTrack.getSettings().deviceId===Ba(e)||(this._constraints.deviceId=e,this.isMuted)?!0:(yield this.restartTrack(),Ba(e)===this._mediaStreamTrack.getSettings().deviceId)})}getDeviceId(){return E(this,arguments,void 0,function(){var e=this;let n=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return function*(){if(e.source===V.Source.ScreenShare)return;const{deviceId:i,groupId:r}=e._mediaStreamTrack.getSettings(),a=e.kind===V.Kind.Audio?"audioinput":"videoinput";return n?on.getInstance().normalizeDeviceId(a,i,r):i}()})}mute(){return E(this,void 0,void 0,function*(){return this.setTrackMuted(!0),this})}unmute(){return E(this,void 0,void 0,function*(){return this.setTrackMuted(!1),this})}replaceTrack(e,n){return E(this,void 0,void 0,function*(){const i=yield this.trackChangeLock.lock();try{if(!this.sender)throw new Jr("unable to replace an unpublished track");let r,a;return typeof n=="boolean"?r=n:n!==void 0&&(r=n.userProvidedTrack,a=n.stopProcessor),this.providedByUser=r??!0,this.log.debug("replace MediaStreamTrack",this.logContext),yield this.setMediaStreamTrack(e),a&&this.processor&&(yield this.internalStopProcessor()),this}finally{i()}})}restart(e){return E(this,void 0,void 0,function*(){this.manuallyStopped=!1;const n=yield this.trackChangeLock.lock();try{e||(e=this._constraints);const{deviceId:i,facingMode:r}=e,a=QM(e,["deviceId","facingMode"]);this.log.debug("restarting track with constraints",Object.assign(Object.assign({},this.logContext),{constraints:e}));const o={audio:!1,video:!1};this.kind===V.Kind.Video?o.video=i||r?{deviceId:i,facingMode:r}:!0:o.audio=i?Object.assign({deviceId:i},a):!0,this.attachedElements.forEach(c=>{Ps(this.mediaStreamTrack,c)}),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this._mediaStreamTrack.stop();const l=(yield navigator.mediaDevices.getUserMedia(o)).getTracks()[0];return this.kind===V.Kind.Video&&(yield l.applyConstraints(a)),l.addEventListener("ended",this.handleEnded),this.log.debug("re-acquired MediaStreamTrack",this.logContext),yield this.setMediaStreamTrack(l),this._constraints=e,this.emit(ne.Restarted,this),this.manuallyStopped&&(this.log.warn("track was stopped during a restart, stopping restarted track",this.logContext),this.stop()),this}finally{n()}})}setTrackMuted(e){this.log.debug("setting ".concat(this.kind," track ").concat(e?"muted":"unmuted"),this.logContext),!(this.isMuted===e&&this._mediaStreamTrack.enabled!==e)&&(this.isMuted=e,this._mediaStreamTrack.enabled=!e,this.emit(e?ne.Muted:ne.Unmuted,this))}get needsReAcquisition(){return this._mediaStreamTrack.readyState!=="live"||this._mediaStreamTrack.muted||!this._mediaStreamTrack.enabled||this.reacquireTrack}handleAppVisibilityChanged(){const e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return E(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),fS()&&(this.log.debug("visibility changed, is in Background: ".concat(this.isInBackground),this.logContext),!this.isInBackground&&this.needsReAcquisition&&!this.isUserProvided&&!this.isMuted&&(this.log.debug("track needs to be reacquired, restarting ".concat(this.source),this.logContext),yield this.restart(),this.reacquireTrack=!1))})}stop(){var e;this.manuallyStopped=!0,super.stop(),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this._mediaStreamTrack.removeEventListener("mute",this.handleTrackMuteEvent),this._mediaStreamTrack.removeEventListener("unmute",this.handleTrackUnmuteEvent),(e=this.processor)===null||e===void 0||e.destroy(),this.processor=void 0}pauseUpstream(){return E(this,void 0,void 0,function*(){var e;const n=yield this.pauseUpstreamLock.lock();try{if(this._isUpstreamPaused===!0)return;if(!this.sender){this.log.warn("unable to pause upstream for an unpublished track",this.logContext);return}this._isUpstreamPaused=!0,this.emit(ne.UpstreamPaused,this);const i=ii();if((i==null?void 0:i.name)==="Safari"&&Or(i.version,"12.0")<0)throw new Bm("pauseUpstream is not supported on Safari < 12.");((e=this.sender.transport)===null||e===void 0?void 0:e.state)!=="closed"&&(yield this.sender.replaceTrack(null))}finally{n()}})}resumeUpstream(){return E(this,void 0,void 0,function*(){var e;const n=yield this.pauseUpstreamLock.lock();try{if(this._isUpstreamPaused===!1)return;if(!this.sender){this.log.warn("unable to resume upstream for an unpublished track",this.logContext);return}this._isUpstreamPaused=!1,this.emit(ne.UpstreamResumed,this),((e=this.sender.transport)===null||e===void 0?void 0:e.state)!=="closed"&&(yield this.sender.replaceTrack(this.mediaStreamTrack))}finally{n()}})}getRTCStatsReport(){return E(this,void 0,void 0,function*(){var e;return!((e=this.sender)===null||e===void 0)&&e.getStats?yield this.sender.getStats():void 0})}setProcessor(e){return E(this,arguments,void 0,function(n){var i=this;let r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return function*(){var a;const o=yield i.trackChangeLock.lock();try{i.log.debug("setting up processor",i.logContext);const s=document.createElement(i.kind),l={kind:i.kind,track:i._mediaStreamTrack,element:s,audioContext:i.audioContext};if(yield n.init(l),i.log.debug("processor initialized",i.logContext),i.processor&&(yield i.internalStopProcessor()),i.kind==="unknown")throw TypeError("cannot set processor on track of unknown kind");if(Ds(i._mediaStreamTrack,s),s.muted=!0,s.play().catch(c=>{c instanceof DOMException&&c.name==="AbortError"?(i.log.warn("failed to play processor element, retrying",Object.assign(Object.assign({},i.logContext),{error:c})),setTimeout(()=>{s.play().catch(u=>{i.log.error("failed to play processor element",Object.assign(Object.assign({},i.logContext),{err:u}))})},100)):i.log.error("failed to play processor element",Object.assign(Object.assign({},i.logContext),{error:c}))}),i.processor=n,i.processorElement=s,i.processor.processedTrack){for(const c of i.attachedElements)c!==i.processorElement&&r&&(Ps(i._mediaStreamTrack,c),Ds(i.processor.processedTrack,c));yield(a=i.sender)===null||a===void 0?void 0:a.replaceTrack(i.processor.processedTrack)}i.emit(ne.TrackProcessorUpdate,i.processor)}finally{o()}}()})}getProcessor(){return this.processor}stopProcessor(){return E(this,arguments,void 0,function(){var e=this;let n=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return function*(){const i=yield e.trackChangeLock.lock();try{yield e.internalStopProcessor(n)}finally{i()}}()})}internalStopProcessor(){return E(this,arguments,void 0,function(){var e=this;let n=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return function*(){var i,r;e.processor&&(e.log.debug("stopping processor",e.logContext),(i=e.processor.processedTrack)===null||i===void 0||i.stop(),yield e.processor.destroy(),e.processor=void 0,n||((r=e.processorElement)===null||r===void 0||r.remove(),e.processorElement=void 0),yield e._mediaStreamTrack.applyConstraints(e._constraints),yield e.setMediaStreamTrack(e._mediaStreamTrack,!0),e.emit(ne.TrackProcessorUpdate))}()})}startPreConnectBuffer(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:100;if(!wD()){this.log.warn("MediaRecorder is not available, cannot start preconnect buffer",this.logContext);return}if(this.localTrackRecorder){this.log.warn("preconnect buffer already started");return}else{let n="audio/webm;codecs=opus";MediaRecorder.isTypeSupported(n)||(n="video/mp4"),this.localTrackRecorder=new TD(this,{mimeType:n})}this.localTrackRecorder.start(e),this.autoStopPreConnectBuffer=setTimeout(()=>{this.log.warn("preconnect buffer timed out, stopping recording automatically",this.logContext),this.stopPreConnectBuffer()},ED)}stopPreConnectBuffer(){clearTimeout(this.autoStopPreConnectBuffer),this.localTrackRecorder&&(this.localTrackRecorder.stop(),this.localTrackRecorder=void 0)}getPreConnectBuffer(){var e;return(e=this.localTrackRecorder)===null||e===void 0?void 0:e.byteStream}getPreConnectBufferMimeType(){var e;return(e=this.localTrackRecorder)===null||e===void 0?void 0:e.mimeType}}class hh extends FS{get enhancedNoiseCancellation(){return this.isKrispNoiseFilterEnabled}constructor(e,n){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0,r=arguments.length>3?arguments[3]:void 0,a=arguments.length>4?arguments[4]:void 0;super(e,V.Kind.Audio,n,i,a),this.stopOnMute=!1,this.isKrispNoiseFilterEnabled=!1,this.monitorSender=()=>E(this,void 0,void 0,function*(){if(!this.sender){this._currentBitrate=0;return}let o;try{o=yield this.getSenderStats()}catch(s){this.log.error("could not get audio sender stats",Object.assign(Object.assign({},this.logContext),{error:s}));return}o&&this.prevStats&&(this._currentBitrate=dh(o,this.prevStats)),this.prevStats=o}),this.handleKrispNoiseFilterEnable=()=>{this.isKrispNoiseFilterEnabled=!0,this.log.debug("Krisp noise filter enabled",this.logContext),this.emit(ne.AudioTrackFeatureUpdate,this,an.TF_ENHANCED_NOISE_CANCELLATION,!0)},this.handleKrispNoiseFilterDisable=()=>{this.isKrispNoiseFilterEnabled=!1,this.log.debug("Krisp noise filter disabled",this.logContext),this.emit(ne.AudioTrackFeatureUpdate,this,an.TF_ENHANCED_NOISE_CANCELLATION,!1)},this.audioContext=r,this.checkForSilence()}mute(){const e=Object.create(null,{mute:{get:()=>super.mute}});return E(this,void 0,void 0,function*(){const n=yield this.muteLock.lock();try{return this.isMuted?(this.log.debug("Track already muted",this.logContext),this):(this.source===V.Source.Microphone&&this.stopOnMute&&!this.isUserProvided&&(this.log.debug("stopping mic track",this.logContext),this._mediaStreamTrack.stop()),yield e.mute.call(this),this)}finally{n()}})}unmute(){const e=Object.create(null,{unmute:{get:()=>super.unmute}});return E(this,void 0,void 0,function*(){const n=yield this.muteLock.lock();try{if(!this.isMuted)return this.log.debug("Track already unmuted",this.logContext),this;const i=this._constraints.deviceId&&this._mediaStreamTrack.getSettings().deviceId!==Ba(this._constraints.deviceId);return this.source===V.Source.Microphone&&(this.stopOnMute||this._mediaStreamTrack.readyState==="ended"||i)&&!this.isUserProvided&&(this.log.debug("reacquiring mic track",this.logContext),yield this.restartTrack()),yield e.unmute.call(this),this}finally{n()}})}restartTrack(e){return E(this,void 0,void 0,function*(){let n;if(e){const i=Vm({audio:e});typeof i.audio!="boolean"&&(n=i.audio)}yield this.restart(n)})}restart(e){const n=Object.create(null,{restart:{get:()=>super.restart}});return E(this,void 0,void 0,function*(){const i=yield n.restart.call(this,e);return this.checkForSilence(),i})}startMonitor(){ri()&&(this.monitorInterval||(this.monitorInterval=setInterval(()=>{this.monitorSender()},fg)))}setProcessor(e){return E(this,void 0,void 0,function*(){var n;const i=yield this.trackChangeLock.lock();try{if(!Nr()&&!this.audioContext)throw Error("Audio context needs to be set on LocalAudioTrack in order to enable processors");this.processor&&(yield this.internalStopProcessor());const r={kind:this.kind,track:this._mediaStreamTrack,audioContext:this.audioContext};this.log.debug("setting up audio processor ".concat(e.name),this.logContext),yield e.init(r),this.processor=e,this.processor.processedTrack&&(yield(n=this.sender)===null||n===void 0?void 0:n.replaceTrack(this.processor.processedTrack),this.processor.processedTrack.addEventListener("enable-lk-krisp-noise-filter",this.handleKrispNoiseFilterEnable),this.processor.processedTrack.addEventListener("disable-lk-krisp-noise-filter",this.handleKrispNoiseFilterDisable)),this.emit(ne.TrackProcessorUpdate,this.processor)}finally{i()}})}setAudioContext(e){this.audioContext=e}getSenderStats(){return E(this,void 0,void 0,function*(){var e;if(!(!((e=this.sender)===null||e===void 0)&&e.getStats))return;const n=yield this.sender.getStats();let i;return n.forEach(r=>{r.type==="outbound-rtp"&&(i={type:"audio",streamId:r.id,packetsSent:r.packetsSent,packetsLost:r.packetsLost,bytesSent:r.bytesSent,timestamp:r.timestamp,roundTripTime:r.roundTripTime,jitter:r.jitter})}),i})}checkForSilence(){return E(this,void 0,void 0,function*(){const e=yield sS(this);return e&&(this.isMuted||this.log.debug("silence detected on local audio track",this.logContext),this.emit(ne.AudioSilenceDetected)),e})}}function RD(t,e,n){switch(t.kind){case"audio":return new hh(t,e,!1,void 0,n);case"video":return new fh(t,e,!1,n);default:throw new Jr("unsupported track type: ".concat(t.kind))}}const AD=Object.values(dc),ND=Object.values(Fm),OD=Object.values(qm),MD=[dc.h180,dc.h360],DD=[Fm.h180,Fm.h360],PD=t=>[{scaleResolutionDownBy:2,fps:t.encoding.maxFramerate}].map(n=>{var i,r;return new ct(Math.floor(t.width/n.scaleResolutionDownBy),Math.floor(t.height/n.scaleResolutionDownBy),Math.max(15e4,Math.floor(t.encoding.maxBitrate/(Math.pow(n.scaleResolutionDownBy,2)*(((i=t.encoding.maxFramerate)!==null&&i!==void 0?i:30)/((r=n.fps)!==null&&r!==void 0?r:30))))),n.fps,t.encoding.priority)}),mg=["q","h","f"];function gg(t,e,n,i){var r,a;let o=i==null?void 0:i.videoEncoding;t&&(o=i==null?void 0:i.screenShareEncoding);const s=i==null?void 0:i.simulcast,l=i==null?void 0:i.scalabilityMode,c=i==null?void 0:i.videoCodec;if(!o&&!s&&!l||!e||!n)return[{}];o||(o=ID(t,e,n,c),Re.debug("using video encoding",o));const u=o.maxFramerate,d=new ct(e,n,o.maxBitrate,o.maxFramerate,o.priority);if(l&&ar(c)){const b=new VS(l),m=[];if(b.spatial>3)throw new Error("unsupported scalabilityMode: ".concat(l));const S=ii();if(pc()||Nr()||(S==null?void 0:S.name)==="Chrome"&&Or(S==null?void 0:S.version,"113")<0){const g=b.suffix=="h"?2:3,y=D8(S);for(let x=0;x<b.spatial;x+=1)m.push({rid:mg[2-x],maxBitrate:o.maxBitrate/Math.pow(g,x),maxFramerate:d.encoding.maxFramerate,scaleResolutionDownBy:y?Math.pow(2,x):void 0});m[0].scalabilityMode=l}else m.push({maxBitrate:o.maxBitrate,maxFramerate:d.encoding.maxFramerate,scalabilityMode:l});return d.encoding.priority&&(m[0].priority=d.encoding.priority,m[0].networkPriority=d.encoding.priority),Re.debug("using svc encoding",{encodings:m}),m}if(!s)return[o];let h=[];t?h=(r=HS(i==null?void 0:i.screenShareSimulcastLayers))!==null&&r!==void 0?r:qS(t,d):h=(a=HS(i==null?void 0:i.videoSimulcastLayers))!==null&&a!==void 0?a:qS(t,d);let p;if(h.length>0){const b=h[0];h.length>1&&([,p]=h);const m=Math.max(e,n);if(m>=960&&p)return vg(e,n,[b,p,d],u);if(m>=480)return vg(e,n,[b,d],u)}return vg(e,n,[d])}function LD(t,e,n){var i,r,a,o;if(!n.backupCodec||n.backupCodec===!0||n.backupCodec.codec===n.videoCodec)return;e!==n.backupCodec.codec&&Re.warn("requested a different codec than specified as backup",{serverRequested:e,backup:n.backupCodec.codec}),n.videoCodec=e,n.videoEncoding=n.backupCodec.encoding;const s=t.mediaStreamTrack.getSettings(),l=(i=s.width)!==null&&i!==void 0?i:(r=t.dimensions)===null||r===void 0?void 0:r.width,c=(a=s.height)!==null&&a!==void 0?a:(o=t.dimensions)===null||o===void 0?void 0:o.height;return t.source===V.Source.ScreenShare&&n.simulcast&&(n.simulcast=!1),gg(t.source===V.Source.ScreenShare,l,c,n)}function ID(t,e,n,i){const r=jD(t,e,n);let{encoding:a}=r[0];const o=Math.max(e,n);for(let s=0;s<r.length;s+=1){const l=r[s];if(a=l.encoding,l.width>=o)break}if(i)switch(i){case"av1":case"h265":a=Object.assign({},a),a.maxBitrate=a.maxBitrate*.7;break;case"vp9":a=Object.assign({},a),a.maxBitrate=a.maxBitrate*.85;break}return a}function jD(t,e,n){if(t)return OD;const i=e>n?e/n:n/e;return Math.abs(i-16/9)<Math.abs(i-4/3)?AD:ND}function qS(t,e){if(t)return PD(e);const{width:n,height:i}=e,r=n>i?n/i:i/n;return Math.abs(r-16/9)<Math.abs(r-4/3)?MD:DD}function vg(t,e,n,i){const r=[];if(n.forEach((a,o)=>{if(o>=mg.length)return;const s=Math.min(t,e),c={rid:mg[o],scaleResolutionDownBy:Math.max(1,s/Math.min(a.width,a.height)),maxBitrate:a.encoding.maxBitrate},u=i&&a.encoding.maxFramerate?Math.min(i,a.encoding.maxFramerate):a.encoding.maxFramerate;u&&(c.maxFramerate=u);const d=Ho()||o===0;a.encoding.priority&&d&&(c.priority=a.encoding.priority,c.networkPriority=a.encoding.priority),r.push(c)}),Nr()&&mS()==="ios"){let a;r.forEach(s=>{a?s.maxFramerate&&s.maxFramerate>a&&(a=s.maxFramerate):a=s.maxFramerate});let o=!0;r.forEach(s=>{var l;s.maxFramerate!=a&&(o&&(o=!1,Re.info("Simulcast on iOS React-Native requires all encodings to share the same framerate.")),Re.info('Setting framerate of encoding "'.concat((l=s.rid)!==null&&l!==void 0?l:"",'" to ').concat(a)),s.maxFramerate=a)})}return r}function HS(t){if(t)return t.sort((e,n)=>{const{encoding:i}=e,{encoding:r}=n;return i.maxBitrate>r.maxBitrate?1:i.maxBitrate<r.maxBitrate?-1:i.maxBitrate===r.maxBitrate&&i.maxFramerate&&r.maxFramerate?i.maxFramerate>r.maxFramerate?1:-1:0})}class VS{constructor(e){const n=e.match(/^L(\d)T(\d)(h|_KEY|_KEY_SHIFT){0,1}$/);if(!n)throw new Error("invalid scalability mode");if(this.spatial=parseInt(n[1]),this.temporal=parseInt(n[2]),n.length>3)switch(n[3]){case"h":case"_KEY":case"_KEY_SHIFT":this.suffix=n[3]}}toString(){var e;return"L".concat(this.spatial,"T").concat(this.temporal).concat((e=this.suffix)!==null&&e!==void 0?e:"")}}function BD(t){return t.source===V.Source.ScreenShare||t.constraints.height&&Ba(t.constraints.height)>=1080?"maintain-resolution":"balanced"}const UD=5e3;class fh extends FS{get sender(){return this._sender}set sender(e){this._sender=e,this.degradationPreference&&this.setDegradationPreference(this.degradationPreference)}constructor(e,n){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0,r=arguments.length>3?arguments[3]:void 0;super(e,V.Kind.Video,n,i,r),this.simulcastCodecs=new Map,this.degradationPreference="balanced",this.isCpuConstrained=!1,this.optimizeForPerformance=!1,this.monitorSender=()=>E(this,void 0,void 0,function*(){if(!this.sender){this._currentBitrate=0;return}let a;try{a=yield this.getSenderStats()}catch(l){this.log.error("could not get video sender stats",Object.assign(Object.assign({},this.logContext),{error:l}));return}const o=new Map(a.map(l=>[l.rid,l])),s=a.some(l=>l.qualityLimitationReason==="cpu");if(s!==this.isCpuConstrained&&(this.isCpuConstrained=s,this.isCpuConstrained&&this.emit(ne.CpuConstrained)),this.prevStats){let l=0;o.forEach((c,u)=>{var d;const h=(d=this.prevStats)===null||d===void 0?void 0:d.get(u);l+=dh(c,h)}),this._currentBitrate=l}this.prevStats=o}),this.senderLock=new In}get isSimulcast(){return!!(this.sender&&this.sender.getParameters().encodings.length>1)}startMonitor(e){var n;if(this.signalClient=e,!ri())return;const i=(n=this.sender)===null||n===void 0?void 0:n.getParameters();i&&(this.encodings=i.encodings),!this.monitorInterval&&(this.monitorInterval=setInterval(()=>{this.monitorSender()},fg))}stop(){this._mediaStreamTrack.getConstraints(),this.simulcastCodecs.forEach(e=>{e.mediaStreamTrack.stop()}),super.stop()}pauseUpstream(){const e=Object.create(null,{pauseUpstream:{get:()=>super.pauseUpstream}});return E(this,void 0,void 0,function*(){var n,i,r,a,o;yield e.pauseUpstream.call(this);try{for(var s=!0,l=Xr(this.simulcastCodecs.values()),c;c=yield l.next(),n=c.done,!n;s=!0)a=c.value,s=!1,yield(o=a.sender)===null||o===void 0?void 0:o.replaceTrack(null)}catch(u){i={error:u}}finally{try{!s&&!n&&(r=l.return)&&(yield r.call(l))}finally{if(i)throw i.error}}})}resumeUpstream(){const e=Object.create(null,{resumeUpstream:{get:()=>super.resumeUpstream}});return E(this,void 0,void 0,function*(){var n,i,r,a,o;yield e.resumeUpstream.call(this);try{for(var s=!0,l=Xr(this.simulcastCodecs.values()),c;c=yield l.next(),n=c.done,!n;s=!0){a=c.value,s=!1;const u=a;yield(o=u.sender)===null||o===void 0?void 0:o.replaceTrack(u.mediaStreamTrack)}}catch(u){i={error:u}}finally{try{!s&&!n&&(r=l.return)&&(yield r.call(l))}finally{if(i)throw i.error}}})}mute(){const e=Object.create(null,{mute:{get:()=>super.mute}});return E(this,void 0,void 0,function*(){const n=yield this.muteLock.lock();try{return this.isMuted?(this.log.debug("Track already muted",this.logContext),this):(this.source===V.Source.Camera&&!this.isUserProvided&&(this.log.debug("stopping camera track",this.logContext),this._mediaStreamTrack.stop()),yield e.mute.call(this),this)}finally{n()}})}unmute(){const e=Object.create(null,{unmute:{get:()=>super.unmute}});return E(this,void 0,void 0,function*(){const n=yield this.muteLock.lock();try{return this.isMuted?(this.source===V.Source.Camera&&!this.isUserProvided&&(this.log.debug("reacquiring camera track",this.logContext),yield this.restartTrack()),yield e.unmute.call(this),this):(this.log.debug("Track already unmuted",this.logContext),this)}finally{n()}})}setTrackMuted(e){super.setTrackMuted(e);for(const n of this.simulcastCodecs.values())n.mediaStreamTrack.enabled=!e}getSenderStats(){return E(this,void 0,void 0,function*(){var e;if(!(!((e=this.sender)===null||e===void 0)&&e.getStats))return[];const n=[],i=yield this.sender.getStats();return i.forEach(r=>{var a;if(r.type==="outbound-rtp"){const o={type:"video",streamId:r.id,frameHeight:r.frameHeight,frameWidth:r.frameWidth,framesPerSecond:r.framesPerSecond,framesSent:r.framesSent,firCount:r.firCount,pliCount:r.pliCount,nackCount:r.nackCount,packetsSent:r.packetsSent,bytesSent:r.bytesSent,qualityLimitationReason:r.qualityLimitationReason,qualityLimitationDurations:r.qualityLimitationDurations,qualityLimitationResolutionChanges:r.qualityLimitationResolutionChanges,rid:(a=r.rid)!==null&&a!==void 0?a:r.id,retransmittedPacketsSent:r.retransmittedPacketsSent,targetBitrate:r.targetBitrate,timestamp:r.timestamp},s=i.get(r.remoteId);s&&(o.jitter=s.jitter,o.packetsLost=s.packetsLost,o.roundTripTime=s.roundTripTime),n.push(o)}}),n.sort((r,a)=>{var o,s;return((o=a.frameWidth)!==null&&o!==void 0?o:0)-((s=r.frameWidth)!==null&&s!==void 0?s:0)}),n})}setPublishingQuality(e){const n=[];for(let i=vi.LOW;i<=vi.HIGH;i+=1)n.push(new Tm({quality:i,enabled:i<=e}));this.log.debug("setting publishing quality. max quality ".concat(e),this.logContext),this.setPublishingLayers(ar(this.codec),n)}restartTrack(e){return E(this,void 0,void 0,function*(){var n,i,r,a,o;let s;if(e){const d=Vm({video:e});typeof d.video!="boolean"&&(s=d.video)}yield this.restart(s),this.isCpuConstrained=!1;try{for(var l=!0,c=Xr(this.simulcastCodecs.values()),u;u=yield c.next(),n=u.done,!n;l=!0){a=u.value,l=!1;const d=a;d.sender&&((o=d.sender.transport)===null||o===void 0?void 0:o.state)!=="closed"&&(d.mediaStreamTrack=this.mediaStreamTrack.clone(),yield d.sender.replaceTrack(d.mediaStreamTrack))}}catch(d){i={error:d}}finally{try{!l&&!n&&(r=c.return)&&(yield r.call(c))}finally{if(i)throw i.error}}})}setProcessor(e){const n=Object.create(null,{setProcessor:{get:()=>super.setProcessor}});return E(this,arguments,void 0,function(i){var r=this;let a=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return function*(){var o,s,l,c,u,d;if(yield n.setProcessor.call(r,i,a),!((u=r.processor)===null||u===void 0)&&u.processedTrack)try{for(var h=!0,p=Xr(r.simulcastCodecs.values()),b;b=yield p.next(),o=b.done,!o;h=!0)c=b.value,h=!1,yield(d=c.sender)===null||d===void 0?void 0:d.replaceTrack(r.processor.processedTrack)}catch(m){s={error:m}}finally{try{!h&&!o&&(l=p.return)&&(yield l.call(p))}finally{if(s)throw s.error}}}()})}setDegradationPreference(e){return E(this,void 0,void 0,function*(){if(this.degradationPreference=e,this.sender)try{this.log.debug("setting degradationPreference to ".concat(e),this.logContext);const n=this.sender.getParameters();n.degradationPreference=e,this.sender.setParameters(n)}catch(n){this.log.warn("failed to set degradationPreference",Object.assign({error:n},this.logContext))}})}addSimulcastTrack(e,n){if(this.simulcastCodecs.has(e)){this.log.error("".concat(e," already added, skipping adding simulcast codec"),this.logContext);return}const i={codec:e,mediaStreamTrack:this.mediaStreamTrack.clone(),sender:void 0,encodings:n};return this.simulcastCodecs.set(e,i),i}setSimulcastTrackSender(e,n){const i=this.simulcastCodecs.get(e);i&&(i.sender=n,setTimeout(()=>{this.subscribedCodecs&&this.setPublishingCodecs(this.subscribedCodecs)},UD))}setPublishingCodecs(e){return E(this,void 0,void 0,function*(){var n,i,r,a,o,s,l;if(this.log.debug("setting publishing codecs",Object.assign(Object.assign({},this.logContext),{codecs:e,currentCodec:this.codec})),!this.codec&&e.length>0)return yield this.setPublishingLayers(ar(e[0].codec),e[0].qualities),[];this.subscribedCodecs=e;const c=[];try{for(n=!0,i=Xr(e);r=yield i.next(),a=r.done,!a;n=!0){l=r.value,n=!1;const u=l;if(!this.codec||this.codec===u.codec)yield this.setPublishingLayers(ar(u.codec),u.qualities);else{const d=this.simulcastCodecs.get(u.codec);if(this.log.debug("try setPublishingCodec for ".concat(u.codec),Object.assign(Object.assign({},this.logContext),{simulcastCodecInfo:d})),!d||!d.sender){for(const h of u.qualities)if(h.enabled){c.push(u.codec);break}}else d.encodings&&(this.log.debug("try setPublishingLayersForSender ".concat(u.codec),this.logContext),yield GS(d.sender,d.encodings,u.qualities,this.senderLock,ar(u.codec),this.log,this.logContext))}}}catch(u){o={error:u}}finally{try{!n&&!a&&(s=i.return)&&(yield s.call(i))}finally{if(o)throw o.error}}return c})}setPublishingLayers(e,n){return E(this,void 0,void 0,function*(){if(this.optimizeForPerformance){this.log.info("skipping setPublishingLayers due to optimized publishing performance",Object.assign(Object.assign({},this.logContext),{qualities:n}));return}this.log.debug("setting publishing layers",Object.assign(Object.assign({},this.logContext),{qualities:n})),!(!this.sender||!this.encodings)&&(yield GS(this.sender,this.encodings,n,this.senderLock,e,this.log,this.logContext))})}prioritizePerformance(){return E(this,void 0,void 0,function*(){if(!this.sender)throw new Error("sender not found");const e=yield this.senderLock.lock();try{this.optimizeForPerformance=!0;const n=this.sender.getParameters();n.encodings=n.encodings.map((i,r)=>{var a;return Object.assign(Object.assign({},i),{active:r===0,scaleResolutionDownBy:Math.max(1,Math.ceil(((a=this.mediaStreamTrack.getSettings().height)!==null&&a!==void 0?a:360)/360)),scalabilityMode:r===0&&ar(this.codec)?"L1T3":void 0,maxFramerate:r===0?15:0,maxBitrate:r===0?i.maxBitrate:0})}),this.log.debug("setting performance optimised encodings",Object.assign(Object.assign({},this.logContext),{encodings:n.encodings})),this.encodings=n.encodings,yield this.sender.setParameters(n)}catch(n){this.log.error("failed to set performance optimised encodings",Object.assign(Object.assign({},this.logContext),{error:n})),this.optimizeForPerformance=!1}finally{e()}})}handleAppVisibilityChanged(){const e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return E(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),fS()&&this.isInBackground&&this.source===V.Source.Camera&&(this._mediaStreamTrack.enabled=!1)})}}function GS(t,e,n,i,r,a,o){return E(this,void 0,void 0,function*(){const s=yield i.lock();a.debug("setPublishingLayersForSender",Object.assign(Object.assign({},o),{sender:t,qualities:n,senderEncodings:e}));try{const l=t.getParameters(),{encodings:c}=l;if(!c)return;if(c.length!==e.length){a.warn("cannot set publishing layers, encodings mismatch",Object.assign(Object.assign({},o),{encodings:c,senderEncodings:e}));return}let u=!1;!1&&c[0].scalabilityMode||(r&&n.some(p=>p.enabled)&&n.forEach(p=>p.enabled=!0),c.forEach((h,p)=>{var b;let m=(b=h.rid)!==null&&b!==void 0?b:"";m===""&&(m="q");const S=WS(m),g=n.find(y=>y.quality===S);g&&h.active!==g.enabled&&(u=!0,h.active=g.enabled,a.debug("setting layer ".concat(g.quality," to ").concat(h.active?"enabled":"disabled"),o),Ho()&&(g.enabled?(h.scaleResolutionDownBy=e[p].scaleResolutionDownBy,h.maxBitrate=e[p].maxBitrate,h.maxFrameRate=e[p].maxFrameRate):(h.scaleResolutionDownBy=4,h.maxBitrate=10,h.maxFrameRate=2)))})),u&&(l.encodings=c,a.debug("setting encodings",Object.assign(Object.assign({},o),{encodings:l.encodings})),yield t.setParameters(l))}finally{s()}})}function WS(t){switch(t){case"f":return vi.HIGH;case"h":return vi.MEDIUM;case"q":return vi.LOW;default:return vi.HIGH}}function YS(t,e,n,i){if(!n)return[new Ia({quality:vi.HIGH,width:t,height:e,bitrate:0,ssrc:0})];if(i){const r=n[0].scalabilityMode,a=new VS(r),o=[],s=a.suffix=="h"?1.5:2,l=a.suffix=="h"?2:3;for(let c=0;c<a.spatial;c+=1)o.push(new Ia({quality:Math.min(vi.HIGH,a.spatial-1)-c,width:Math.ceil(t/Math.pow(s,c)),height:Math.ceil(e/Math.pow(s,c)),bitrate:n[0].maxBitrate?Math.ceil(n[0].maxBitrate/Math.pow(l,c)):0,ssrc:0}));return o}return n.map(r=>{var a,o,s;const l=(a=r.scaleResolutionDownBy)!==null&&a!==void 0?a:1;let c=WS((o=r.rid)!==null&&o!==void 0?o:"");return new Ia({quality:c,width:Math.ceil(t/l),height:Math.ceil(e/l),bitrate:(s=r.maxBitrate)!==null&&s!==void 0?s:0,ssrc:0})})}const KS="_lossy",XS="_reliable",zD=2*1e3,bg="leave-reconnect",FD=3e4,qD=8*1024,HD=256*1024;var Ii;(function(t){t[t.New=0]="New",t[t.Connected=1]="Connected",t[t.Disconnected=2]="Disconnected",t[t.Reconnecting=3]="Reconnecting",t[t.Closed=4]="Closed"})(Ii||(Ii={}));class VD extends Rr.EventEmitter{get isClosed(){return this._isClosed}get pendingReconnect(){return!!this.reconnectTimeout}constructor(e){var n;super(),this.options=e,this.rtcConfig={},this.peerConnectionTimeout=dg.peerConnectionTimeout,this.fullReconnectOnNext=!1,this.latestRemoteOfferId=0,this.subscriberPrimary=!1,this.pcState=Ii.New,this._isClosed=!0,this.pendingTrackResolvers={},this.reconnectAttempts=0,this.reconnectStart=0,this.attemptingReconnect=!1,this.joinAttempts=0,this.maxJoinAttempts=1,this.shouldFailNext=!1,this.log=Re,this.reliableDataSequence=1,this.reliableMessageBuffer=new RS,this.reliableReceivedState=new uD(FD),this.lossyDataStatCurrentBytes=0,this.lossyDataStatByterate=0,this.lossyDataDropCount=0,this.midToTrackId={},this.isWaitingForNetworkReconnect=!1,this.handleDataChannel=i=>E(this,[i],void 0,function(r){var a=this;let{channel:o}=r;return function*(){if(o){if(o.label===XS)a.reliableDCSub=o;else if(o.label===KS)a.lossyDCSub=o;else return;a.log.debug("on data channel ".concat(o.id,", ").concat(o.label),a.logContext),o.onmessage=a.handleDataMessage}}()}),this.handleDataMessage=i=>E(this,void 0,void 0,function*(){var r,a,o,s,l;const c=yield this.dataProcessLock.lock();try{let u;if(i.data instanceof ArrayBuffer)u=i.data;else if(i.data instanceof Blob)u=yield i.data.arrayBuffer();else{this.log.error("unsupported data type",Object.assign(Object.assign({},this.logContext),{data:i.data}));return}const d=jn.fromBinary(new Uint8Array(u));if(d.sequence>0&&d.participantSid!==""){const h=this.reliableReceivedState.get(d.participantSid);if(h&&d.sequence<=h)return;this.reliableReceivedState.set(d.participantSid,d.sequence)}if(((r=d.value)===null||r===void 0?void 0:r.case)==="speaker")this.emit(re.ActiveSpeakersUpdate,d.value.value.speakers);else if(((a=d.value)===null||a===void 0?void 0:a.case)==="encryptedPacket"){if(!this.e2eeManager){this.log.error("Received encrypted packet but E2EE not set up",this.logContext);return}const h=yield(o=this.e2eeManager)===null||o===void 0?void 0:o.handleEncryptedData(d.value.value.encryptedValue,d.value.value.iv,d.participantIdentity,d.value.value.keyIndex),p=V_.fromBinary(h.payload),b=new jn({value:p.value,participantIdentity:d.participantIdentity,participantSid:d.participantSid});((s=b.value)===null||s===void 0?void 0:s.case)==="user"&&JS(b,b.value.value),this.emit(re.DataPacketReceived,b,d.value.value.encryptionType)}else((l=d.value)===null||l===void 0?void 0:l.case)==="user"&&JS(d,d.value.value),this.emit(re.DataPacketReceived,d,$t.NONE)}finally{c()}}),this.handleDataError=i=>{const a=i.currentTarget.maxRetransmits===0?"lossy":"reliable";if(i instanceof ErrorEvent&&i.error){const{error:o}=i.error;this.log.error("DataChannel error on ".concat(a,": ").concat(i.message),Object.assign(Object.assign({},this.logContext),{error:o}))}else this.log.error("Unknown DataChannel error on ".concat(a),Object.assign(Object.assign({},this.logContext),{event:i}))},this.handleBufferedAmountLow=i=>{const a=i.currentTarget.maxRetransmits===0?Me.LOSSY:Me.RELIABLE;this.updateAndEmitDCBufferStatus(a)},this.handleDisconnect=(i,r)=>{if(this._isClosed)return;this.log.warn("".concat(i," disconnected"),this.logContext),this.reconnectAttempts===0&&(this.reconnectStart=Date.now());const a=l=>{this.log.warn("could not recover connection after ".concat(this.reconnectAttempts," attempts, ").concat(l,"ms. giving up"),this.logContext),this.emit(re.Disconnected),this.close()},o=Date.now()-this.reconnectStart;let s=this.getNextRetryDelay({elapsedMs:o,retryCount:this.reconnectAttempts});if(s===null){a(o);return}i===bg&&(s=0),this.log.debug("reconnecting in ".concat(s,"ms"),this.logContext),this.clearReconnectTimeout(),this.token&&this.regionUrlProvider&&this.regionUrlProvider.updateToken(this.token),this.reconnectTimeout=yn.setTimeout(()=>this.attemptReconnect(r).finally(()=>this.reconnectTimeout=void 0),s)},this.waitForRestarted=()=>new Promise((i,r)=>{this.pcState===Ii.Connected&&i();const a=()=>{this.off(re.Disconnected,o),i()},o=()=>{this.off(re.Restarted,a),r()};this.once(re.Restarted,a),this.once(re.Disconnected,o)}),this.updateAndEmitDCBufferStatus=i=>{if(i===Me.RELIABLE){const a=this.dataChannelForKind(i);a&&this.reliableMessageBuffer.alignBufferedAmount(a.bufferedAmount)}const r=this.isBufferStatusLow(i);typeof r<"u"&&r!==this.dcBufferStatus.get(i)&&(this.dcBufferStatus.set(i,r),this.emit(re.DCBufferStatusChanged,r,i))},this.isBufferStatusLow=i=>{const r=this.dataChannelForKind(i);if(r)return r.bufferedAmount<=r.bufferedAmountLowThreshold},this.handleBrowserOnLine=()=>E(this,void 0,void 0,function*(){!this.url||!(yield fetch(gc(this.url),{method:"HEAD"}).then(r=>r.ok).catch(()=>!1))||(this.log.info("detected network reconnected"),(this.client.currentState===pt.RECONNECTING||this.isWaitingForNetworkReconnect&&this.client.currentState===pt.CONNECTED)&&(this.clearReconnectTimeout(),this.attemptReconnect(zo.RR_SIGNAL_DISCONNECTED),this.isWaitingForNetworkReconnect=!1))}),this.handleBrowserOffline=()=>E(this,void 0,void 0,function*(){if(this.url)try{yield Promise.race([fetch(gc(this.url),{method:"HEAD"}),_n(4e3).then(()=>Promise.reject())])}catch{window.navigator.onLine===!1&&(this.log.info("detected network interruption"),this.isWaitingForNetworkReconnect=!0)}}),this.log=Kr((n=e.loggerName)!==null&&n!==void 0?n:rr.Engine),this.loggerOptions={loggerName:e.loggerName,loggerContextCb:()=>this.logContext},this.client=new ig(void 0,this.loggerOptions),this.client.signalLatency=this.options.expSignalLatency,this.reconnectPolicy=this.options.reconnectPolicy,this.closingLock=new In,this.dataProcessLock=new In,this.dcBufferStatus=new Map([[Me.LOSSY,!0],[Me.RELIABLE,!0]]),this.client.onParticipantUpdate=i=>this.emit(re.ParticipantUpdate,i),this.client.onConnectionQuality=i=>this.emit(re.ConnectionQualityUpdate,i),this.client.onRoomUpdate=i=>this.emit(re.RoomUpdate,i),this.client.onSubscriptionError=i=>this.emit(re.SubscriptionError,i),this.client.onSubscriptionPermissionUpdate=i=>this.emit(re.SubscriptionPermissionUpdate,i),this.client.onSpeakersChanged=i=>this.emit(re.SpeakersChanged,i),this.client.onStreamStateUpdate=i=>this.emit(re.StreamStateChanged,i),this.client.onRequestResponse=i=>this.emit(re.SignalRequestResponse,i)}get logContext(){var e,n,i,r,a,o;return{room:(n=(e=this.latestJoinResponse)===null||e===void 0?void 0:e.room)===null||n===void 0?void 0:n.name,roomID:(r=(i=this.latestJoinResponse)===null||i===void 0?void 0:i.room)===null||r===void 0?void 0:r.sid,participant:(o=(a=this.latestJoinResponse)===null||a===void 0?void 0:a.participant)===null||o===void 0?void 0:o.identity,pID:this.participantSid}}join(e,n,i,r){return E(this,void 0,void 0,function*(){this.url=e,this.token=n,this.signalOpts=i,this.maxJoinAttempts=i.maxRetries;try{this.joinAttempts+=1,this.setupSignalClientCallbacks();const a=yield this.client.join(e,n,i,r);return this._isClosed=!1,this.latestJoinResponse=a,this.subscriberPrimary=a.subscriberPrimary,this.pcManager||(yield this.configure(a)),(!this.subscriberPrimary||a.fastPublish)&&this.negotiate().catch(o=>{Re.error(o,this.logContext)}),this.registerOnLineListener(),this.clientConfiguration=a.clientConfiguration,this.emit(re.SignalConnected,a),a}catch(a){if(a instanceof xe&&a.reason===xt.ServerUnreachable&&(this.log.warn("Couldn't connect to server, attempt ".concat(this.joinAttempts," of ").concat(this.maxJoinAttempts),this.logContext),this.joinAttempts<this.maxJoinAttempts))return this.join(e,n,i,r);throw a}})}close(){return E(this,void 0,void 0,function*(){const e=yield this.closingLock.lock();if(this.isClosed){e();return}try{this._isClosed=!0,this.joinAttempts=0,this.emit(re.Closing),this.removeAllListeners(),this.deregisterOnLineListener(),this.clearPendingReconnect(),this.cleanupLossyDataStats(),yield this.cleanupPeerConnections(),yield this.cleanupClient()}finally{e()}})}cleanupPeerConnections(){return E(this,void 0,void 0,function*(){var e;yield(e=this.pcManager)===null||e===void 0?void 0:e.close(),this.pcManager=void 0;const n=i=>{i&&(i.close(),i.onbufferedamountlow=null,i.onclose=null,i.onclosing=null,i.onerror=null,i.onmessage=null,i.onopen=null)};n(this.lossyDC),n(this.lossyDCSub),n(this.reliableDC),n(this.reliableDCSub),this.lossyDC=void 0,this.lossyDCSub=void 0,this.reliableDC=void 0,this.reliableDCSub=void 0,this.reliableMessageBuffer=new RS,this.reliableDataSequence=1,this.reliableReceivedState.clear()})}cleanupLossyDataStats(){this.lossyDataStatByterate=0,this.lossyDataStatCurrentBytes=0,this.lossyDataStatInterval&&(clearInterval(this.lossyDataStatInterval),this.lossyDataStatInterval=void 0),this.lossyDataDropCount=0}cleanupClient(){return E(this,void 0,void 0,function*(){yield this.client.close(),this.client.resetCallbacks()})}addTrack(e){if(this.pendingTrackResolvers[e.cid])throw new Jr("a track with the same ID has already been published");return new Promise((n,i)=>{const r=setTimeout(()=>{delete this.pendingTrackResolvers[e.cid],i(xe.timeout("publication of local track timed out, no response from server"))},1e4);this.pendingTrackResolvers[e.cid]={resolve:a=>{clearTimeout(r),n(a)},reject:()=>{clearTimeout(r),i(new Error("Cancelled publication by calling unpublish"))}},this.client.sendAddTrack(e)})}removeTrack(e){if(e.track&&this.pendingTrackResolvers[e.track.id]){const{reject:n}=this.pendingTrackResolvers[e.track.id];n&&n(),delete this.pendingTrackResolvers[e.track.id]}try{return this.pcManager.removeTrack(e),!0}catch(n){this.log.warn("failed to remove track",Object.assign(Object.assign({},this.logContext),{error:n}))}return!1}updateMuteStatus(e,n){this.client.sendMuteTrack(e,n)}get dataSubscriberReadyState(){var e;return(e=this.reliableDCSub)===null||e===void 0?void 0:e.readyState}getConnectedServerAddress(){return E(this,void 0,void 0,function*(){var e;return(e=this.pcManager)===null||e===void 0?void 0:e.getConnectedAddress()})}setRegionUrlProvider(e){this.regionUrlProvider=e}configure(e){return E(this,void 0,void 0,function*(){var n,i;if(this.pcManager&&this.pcManager.currentState!==Mt.NEW)return;this.participantSid=(n=e.participant)===null||n===void 0?void 0:n.sid;const r=this.makeRTCConfiguration(e);this.pcManager=new yD(r,this.options.singlePeerConnection?"publisher-only":e.subscriberPrimary?"subscriber-primary":"publisher-primary",this.loggerOptions),this.emit(re.TransportsCreated,this.pcManager.publisher,this.pcManager.subscriber),this.pcManager.onIceCandidate=(a,o)=>{this.client.sendIceCandidate(a,o)},this.pcManager.onPublisherOffer=(a,o)=>{this.client.sendOffer(a,o)},this.pcManager.onDataChannel=this.handleDataChannel,this.pcManager.onStateChange=(a,o,s)=>E(this,void 0,void 0,function*(){if(this.log.debug("primary PC state changed ".concat(a),this.logContext),["closed","disconnected","failed"].includes(o)&&(this.publisherConnectionPromise=void 0),a===Mt.CONNECTED){const u=this.pcState===Ii.New;this.pcState=Ii.Connected,u&&this.emit(re.Connected,e)}else a===Mt.FAILED&&(this.pcState===Ii.Connected||this.pcState===Ii.Reconnecting)&&(this.pcState=Ii.Disconnected,this.handleDisconnect("peerconnection failed",s==="failed"?zo.RR_SUBSCRIBER_FAILED:zo.RR_PUBLISHER_FAILED));const l=this.client.isDisconnected||this.client.currentState===pt.RECONNECTING,c=[Mt.FAILED,Mt.CLOSING,Mt.CLOSED].includes(a);l&&c&&!this._isClosed&&this.emit(re.Offline)}),this.pcManager.onTrack=a=>{a.streams.length!==0&&this.emit(re.MediaTrackAdded,a.track,a.streams[0],a.receiver)},GD((i=e.serverInfo)===null||i===void 0?void 0:i.protocol)||this.createDataChannels()})}setupSignalClientCallbacks(){this.client.onAnswer=(e,n,i)=>E(this,void 0,void 0,function*(){this.pcManager&&(this.log.debug("received server answer",Object.assign(Object.assign({},this.logContext),{RTCSdpType:e.type,sdp:e.sdp,midToTrackId:i})),this.midToTrackId=i,yield this.pcManager.setPublisherAnswer(e,n))}),this.client.onTrickle=(e,n)=>{this.pcManager&&(this.log.debug("got ICE candidate from peer",Object.assign(Object.assign({},this.logContext),{candidate:e,target:n})),this.pcManager.addIceCandidate(e,n))},this.client.onOffer=(e,n,i)=>E(this,void 0,void 0,function*(){if(this.latestRemoteOfferId=n,!this.pcManager)return;this.midToTrackId=i;const r=yield this.pcManager.createSubscriberAnswerFromOffer(e,n);r&&this.client.sendAnswer(r,n)}),this.client.onLocalTrackPublished=e=>{var n;if(this.log.debug("received trackPublishedResponse",Object.assign(Object.assign({},this.logContext),{cid:e.cid,track:(n=e.track)===null||n===void 0?void 0:n.sid})),!this.pendingTrackResolvers[e.cid]){this.log.error("missing track resolver for ".concat(e.cid),Object.assign(Object.assign({},this.logContext),{cid:e.cid}));return}const{resolve:i}=this.pendingTrackResolvers[e.cid];delete this.pendingTrackResolvers[e.cid],i(e.track)},this.client.onLocalTrackUnpublished=e=>{this.emit(re.LocalTrackUnpublished,e)},this.client.onLocalTrackSubscribed=e=>{this.emit(re.LocalTrackSubscribed,e)},this.client.onTokenRefresh=e=>{var n;this.token=e,(n=this.regionUrlProvider)===null||n===void 0||n.updateToken(e)},this.client.onRemoteMuteChanged=(e,n)=>{this.emit(re.RemoteMute,e,n)},this.client.onSubscribedQualityUpdate=e=>{this.emit(re.SubscribedQualityUpdate,e)},this.client.onRoomMoved=e=>{var n;this.participantSid=(n=e.participant)===null||n===void 0?void 0:n.sid,this.latestJoinResponse&&(this.latestJoinResponse.room=e.room),this.emit(re.RoomMoved,e)},this.client.onMediaSectionsRequirement=e=>{var n,i;const r={direction:"recvonly"};for(let a=0;a<e.numAudios;a++)(n=this.pcManager)===null||n===void 0||n.addPublisherTransceiverOfKind("audio",r);for(let a=0;a<e.numVideos;a++)(i=this.pcManager)===null||i===void 0||i.addPublisherTransceiverOfKind("video",r);this.negotiate()},this.client.onClose=()=>{this.handleDisconnect("signal",zo.RR_SIGNAL_DISCONNECTED)},this.client.onLeave=e=>{switch(this.log.debug("client leave request",Object.assign(Object.assign({},this.logContext),{reason:e==null?void 0:e.reason})),e.regions&&this.regionUrlProvider&&(this.log.debug("updating regions",this.logContext),this.regionUrlProvider.setServerReportedRegions({updatedAtInMs:Date.now(),maxAgeInMs:BS,regionSettings:e.regions})),e.action){case Ns.DISCONNECT:this.emit(re.Disconnected,e==null?void 0:e.reason),this.close();break;case Ns.RECONNECT:this.fullReconnectOnNext=!0,this.handleDisconnect(bg);break;case Ns.RESUME:this.handleDisconnect(bg)}}}makeRTCConfiguration(e){var n;const i=Object.assign({},this.rtcConfig);if(!((n=this.signalOpts)===null||n===void 0)&&n.e2eeEnabled&&(this.log.debug("E2EE - setting up transports with insertable streams",this.logContext),i.encodedInsertableStreams=!0),e.iceServers&&!i.iceServers){const r=[];e.iceServers.forEach(a=>{const o={urls:a.urls};a.username&&(o.username=a.username),a.credential&&(o.credential=a.credential),r.push(o)}),i.iceServers=r}return e.clientConfiguration&&e.clientConfiguration.forceRelay===oc.ENABLED&&(i.iceTransportPolicy="relay"),i.sdpSemantics="unified-plan",i.continualGatheringPolicy="gather_continually",i}createDataChannels(){this.pcManager&&(this.lossyDC&&(this.lossyDC.onmessage=null,this.lossyDC.onerror=null),this.reliableDC&&(this.reliableDC.onmessage=null,this.reliableDC.onerror=null),this.lossyDC=this.pcManager.createPublisherDataChannel(KS,{ordered:!1,maxRetransmits:0}),this.reliableDC=this.pcManager.createPublisherDataChannel(XS,{ordered:!0}),this.lossyDC.onmessage=this.handleDataMessage,this.reliableDC.onmessage=this.handleDataMessage,this.lossyDC.onerror=this.handleDataError,this.reliableDC.onerror=this.handleDataError,this.lossyDC.bufferedAmountLowThreshold=65535,this.reliableDC.bufferedAmountLowThreshold=65535,this.lossyDC.onbufferedamountlow=this.handleBufferedAmountLow,this.reliableDC.onbufferedamountlow=this.handleBufferedAmountLow,this.cleanupLossyDataStats(),this.lossyDataStatInterval=setInterval(()=>{this.lossyDataStatByterate=this.lossyDataStatCurrentBytes,this.lossyDataStatCurrentBytes=0;const e=this.dataChannelForKind(Me.LOSSY);if(e){const n=this.lossyDataStatByterate/10;e.bufferedAmountLowThreshold=Math.min(Math.max(n,qD),HD)}},1e3))}createSender(e,n,i){return E(this,void 0,void 0,function*(){if(Wm())return yield this.createTransceiverRTCRtpSender(e,n,i);if(Ym())return this.log.warn("using add-track fallback",this.logContext),yield this.createRTCRtpSender(e.mediaStreamTrack);throw new Qt("Required webRTC APIs not supported on this device")})}createSimulcastSender(e,n,i,r){return E(this,void 0,void 0,function*(){if(Wm())return this.createSimulcastTransceiverSender(e,n,i,r);if(Ym())return this.log.debug("using add-track fallback",this.logContext),this.createRTCRtpSender(e.mediaStreamTrack);throw new Qt("Cannot stream on this device")})}createTransceiverRTCRtpSender(e,n,i){return E(this,void 0,void 0,function*(){if(!this.pcManager)throw new Qt("publisher is closed");const r=[];e.mediaStream&&r.push(e.mediaStream),Ua(e)&&(e.codec=n.videoCodec);const a={direction:"sendonly",streams:r};return i&&(a.sendEncodings=i),(yield this.pcManager.addPublisherTransceiver(e.mediaStreamTrack,a)).sender})}createSimulcastTransceiverSender(e,n,i,r){return E(this,void 0,void 0,function*(){if(!this.pcManager)throw new Qt("publisher is closed");const a={direction:"sendonly"};r&&(a.sendEncodings=r);const o=yield this.pcManager.addPublisherTransceiver(n.mediaStreamTrack,a);if(i.videoCodec)return e.setSimulcastTrackSender(i.videoCodec,o.sender),o.sender})}createRTCRtpSender(e){return E(this,void 0,void 0,function*(){if(!this.pcManager)throw new Qt("publisher is closed");return this.pcManager.addPublisherTrack(e)})}attemptReconnect(e){return E(this,void 0,void 0,function*(){var n,i,r;if(!this._isClosed){if(this.attemptingReconnect){Re.warn("already attempting reconnect, returning early",this.logContext);return}(((n=this.clientConfiguration)===null||n===void 0?void 0:n.resumeConnection)===oc.DISABLED||((r=(i=this.pcManager)===null||i===void 0?void 0:i.currentState)!==null&&r!==void 0?r:Mt.NEW)===Mt.NEW)&&(this.fullReconnectOnNext=!0);try{this.attemptingReconnect=!0,this.fullReconnectOnNext?yield this.restartConnection():yield this.resumeConnection(e),this.clearPendingReconnect(),this.fullReconnectOnNext=!1}catch(a){this.reconnectAttempts+=1;let o=!0;a instanceof Qt?(this.log.debug("received unrecoverable error",Object.assign(Object.assign({},this.logContext),{error:a})),o=!1):a instanceof Ms||(this.fullReconnectOnNext=!0),o?this.handleDisconnect("reconnect",zo.RR_UNKNOWN):(this.log.info("could not recover connection after ".concat(this.reconnectAttempts," attempts, ").concat(Date.now()-this.reconnectStart,"ms. giving up"),this.logContext),this.emit(re.Disconnected),yield this.close())}finally{this.attemptingReconnect=!1}}})}getNextRetryDelay(e){try{return this.reconnectPolicy.nextRetryDelayInMs(e)}catch(n){this.log.warn("encountered error in reconnect policy",Object.assign(Object.assign({},this.logContext),{error:n}))}return null}restartConnection(e){return E(this,void 0,void 0,function*(){var n,i,r;try{if(!this.url||!this.token)throw new Qt("could not reconnect, url or token not saved");this.log.info("reconnecting, attempt: ".concat(this.reconnectAttempts),this.logContext),this.emit(re.Restarting),this.client.isDisconnected||(yield this.client.sendLeave()),yield this.cleanupPeerConnections(),yield this.cleanupClient();let a;try{if(!this.signalOpts)throw this.log.warn("attempted connection restart, without signal options present",this.logContext),new Ms;a=yield this.join(e??this.url,this.token,this.signalOpts)}catch(o){throw o instanceof xe&&o.reason===xt.NotAllowed?new Qt("could not reconnect, token might be expired"):new Ms}if(this.shouldFailNext)throw this.shouldFailNext=!1,new Error("simulated failure");if(this.client.setReconnected(),this.emit(re.SignalRestarted,a),yield this.waitForPCReconnected(),this.client.currentState!==pt.CONNECTED)throw new Ms("Signal connection got severed during reconnect");(n=this.regionUrlProvider)===null||n===void 0||n.resetAttempts(),this.emit(re.Restarted)}catch(a){const o=yield(i=this.regionUrlProvider)===null||i===void 0?void 0:i.getNextBestRegionUrl();if(o){yield this.restartConnection(o);return}else throw(r=this.regionUrlProvider)===null||r===void 0||r.resetAttempts(),a}})}resumeConnection(e){return E(this,void 0,void 0,function*(){var n;if(!this.url||!this.token)throw new Qt("could not reconnect, url or token not saved");if(!this.pcManager)throw new Qt("publisher and subscriber connections unset");this.log.info("resuming signal connection, attempt ".concat(this.reconnectAttempts),this.logContext),this.emit(re.Resuming);let i;try{this.setupSignalClientCallbacks(),i=yield this.client.reconnect(this.url,this.token,this.participantSid,e)}catch(r){let a="";throw r instanceof Error&&(a=r.message,this.log.error(r.message,Object.assign(Object.assign({},this.logContext),{error:r}))),r instanceof xe&&r.reason===xt.NotAllowed?new Qt("could not reconnect, token might be expired"):r instanceof xe&&r.reason===xt.LeaveRequest?r:new Ms(a)}if(this.emit(re.SignalResumed),i){const r=this.makeRTCConfiguration(i);this.pcManager.updateConfiguration(r),this.latestJoinResponse&&(this.latestJoinResponse.serverInfo=i.serverInfo)}else this.log.warn("Did not receive reconnect response",this.logContext);if(this.shouldFailNext)throw this.shouldFailNext=!1,new Error("simulated failure");if(yield this.pcManager.triggerIceRestart(),yield this.waitForPCReconnected(),this.client.currentState!==pt.CONNECTED)throw new Ms("Signal connection got severed during reconnect");this.client.setReconnected(),((n=this.reliableDC)===null||n===void 0?void 0:n.readyState)==="open"&&this.reliableDC.id===null&&this.createDataChannels(),i!=null&&i.lastMessageSeq&&this.resendReliableMessagesForResume(i.lastMessageSeq),this.emit(re.Resumed)})}waitForPCInitialConnection(e,n){return E(this,void 0,void 0,function*(){if(!this.pcManager)throw new Qt("PC manager is closed");yield this.pcManager.ensurePCTransportConnection(n,e)})}waitForPCReconnected(){return E(this,void 0,void 0,function*(){this.pcState=Ii.Reconnecting,this.log.debug("waiting for peer connection to reconnect",this.logContext);try{if(yield _n(zD),!this.pcManager)throw new Qt("PC manager is closed");yield this.pcManager.ensurePCTransportConnection(void 0,this.peerConnectionTimeout),this.pcState=Ii.Connected}catch(e){throw this.pcState=Ii.Disconnected,xe.internal("could not establish PC connection, ".concat(e.message))}})}publishRpcResponse(e,n,i,r){return E(this,void 0,void 0,function*(){const a=new jn({destinationIdentities:[e],kind:Me.RELIABLE,value:{case:"rpcResponse",value:new vm({requestId:n,value:r?{case:"error",value:r.toProto()}:{case:"payload",value:i??""}})}});yield this.sendDataPacket(a,Me.RELIABLE)})}publishRpcAck(e,n){return E(this,void 0,void 0,function*(){const i=new jn({destinationIdentities:[e],kind:Me.RELIABLE,value:{case:"rpcAck",value:new gm({requestId:n})}});yield this.sendDataPacket(i,Me.RELIABLE)})}sendDataPacket(e,n){return E(this,void 0,void 0,function*(){if(yield this.ensurePublisherConnected(n),this.e2eeManager&&this.e2eeManager.isDataChannelEncryptionEnabled){const a=Z8(e);if(a){const o=yield this.e2eeManager.encryptData(a.toBinary());e.value={case:"encryptedPacket",value:new H_({encryptedValue:o.payload,iv:o.iv,keyIndex:o.keyIndex})}}}n===Me.RELIABLE&&(e.sequence=this.reliableDataSequence,this.reliableDataSequence+=1);const i=e.toBinary(),r=this.dataChannelForKind(n);if(r){if(n===Me.RELIABLE)yield this.waitForBufferStatusLow(n),this.reliableMessageBuffer.push({data:i,sequence:e.sequence});else{if(!this.isBufferStatusLow(n)){this.lossyDataDropCount+=1,this.lossyDataDropCount%100===0&&this.log.warn("dropping lossy data channel messages, total dropped: ".concat(this.lossyDataDropCount),this.logContext);return}this.lossyDataStatCurrentBytes+=i.byteLength}if(this.attemptingReconnect)return;r.send(i)}this.updateAndEmitDCBufferStatus(n)})}resendReliableMessagesForResume(e){return E(this,void 0,void 0,function*(){yield this.ensurePublisherConnected(Me.RELIABLE);const n=this.dataChannelForKind(Me.RELIABLE);n&&(this.reliableMessageBuffer.popToSequence(e),this.reliableMessageBuffer.getAll().forEach(i=>{n.send(i.data)})),this.updateAndEmitDCBufferStatus(Me.RELIABLE)})}waitForBufferStatusLow(e){return new Promise((n,i)=>E(this,void 0,void 0,function*(){if(this.isBufferStatusLow(e))n();else{const r=()=>i("Engine closed");for(this.once(re.Closing,r);!this.dcBufferStatus.get(e);)yield _n(10);this.off(re.Closing,r),n()}}))}ensureDataTransportConnected(e){return E(this,arguments,void 0,function(n){var i=this;let r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:this.subscriberPrimary;return function*(){var a;if(!i.pcManager)throw new Qt("PC manager is closed");const o=r?i.pcManager.subscriber:i.pcManager.publisher,s=r?"Subscriber":"Publisher";if(!o)throw xe.internal("".concat(s," connection not set"));let l=!1;!r&&!i.dataChannelForKind(n,r)&&(i.createDataChannels(),l=!0),!l&&!r&&!i.pcManager.publisher.isICEConnected&&i.pcManager.publisher.getICEConnectionState()!=="checking"&&(l=!0),l&&i.negotiate().catch(d=>{Re.error(d,i.logContext)});const c=i.dataChannelForKind(n,r);if((c==null?void 0:c.readyState)==="open")return;const u=new Date().getTime()+i.peerConnectionTimeout;for(;new Date().getTime()<u;){if(o.isICEConnected&&((a=i.dataChannelForKind(n,r))===null||a===void 0?void 0:a.readyState)==="open")return;yield _n(50)}throw xe.internal("could not establish ".concat(s," connection, state: ").concat(o.getICEConnectionState()))}()})}ensurePublisherConnected(e){return E(this,void 0,void 0,function*(){this.publisherConnectionPromise||(this.publisherConnectionPromise=this.ensureDataTransportConnected(e,!1)),yield this.publisherConnectionPromise})}verifyTransport(){return!(!this.pcManager||this.pcManager.currentState!==Mt.CONNECTED||!this.client.ws||this.client.ws.readyState===WebSocket.CLOSED)}negotiate(){return E(this,void 0,void 0,function*(){return new Promise((e,n)=>E(this,void 0,void 0,function*(){if(!this.pcManager){n(new Um("PC manager is closed"));return}this.pcManager.requirePublisher(),this.pcManager.publisher.getTransceivers().length==0&&!this.lossyDC&&!this.reliableDC&&this.createDataChannels();const i=new AbortController,r=()=>{i.abort(),this.log.debug("engine disconnected while negotiation was ongoing",this.logContext),e()};this.isClosed&&n("cannot negotiate on closed engine"),this.on(re.Closing,r),this.pcManager.publisher.once(Us.RTPVideoPayloadTypes,a=>{const o=new Map;a.forEach(s=>{const l=s.codec.toLowerCase();B8(l)&&o.set(s.payload,l)}),this.emit(re.RTPVideoMapUpdate,o)});try{yield this.pcManager.negotiate(i),e()}catch(a){a instanceof Um&&(this.fullReconnectOnNext=!0),this.handleDisconnect("negotiation",zo.RR_UNKNOWN),n(a)}finally{this.off(re.Closing,r)}}))})}dataChannelForKind(e,n){if(n){if(e===Me.LOSSY)return this.lossyDCSub;if(e===Me.RELIABLE)return this.reliableDCSub}else{if(e===Me.LOSSY)return this.lossyDC;if(e===Me.RELIABLE)return this.reliableDC}}sendSyncState(e,n){var i,r,a,o;if(!this.pcManager){this.log.warn("sync state cannot be sent without peer connection setup",this.logContext);return}const s=this.pcManager.publisher.getLocalDescription(),l=this.pcManager.publisher.getRemoteDescription(),c=(i=this.pcManager.subscriber)===null||i===void 0?void 0:i.getRemoteDescription(),u=(r=this.pcManager.subscriber)===null||r===void 0?void 0:r.getLocalDescription(),d=(o=(a=this.signalOpts)===null||a===void 0?void 0:a.autoSubscribe)!==null&&o!==void 0?o:!0,h=new Array,p=new Array;e.forEach(b=>{b.isDesired!==d&&h.push(b.trackSid),b.isEnabled||p.push(b.trackSid)}),this.client.sendSyncState(new wm({answer:this.options.singlePeerConnection?l?Bs({sdp:l.sdp,type:l.type}):void 0:u?Bs({sdp:u.sdp,type:u.type}):void 0,offer:this.options.singlePeerConnection?s?Bs({sdp:s.sdp,type:s.type}):void 0:c?Bs({sdp:c.sdp,type:c.type}):void 0,subscription:new Qd({trackSids:h,subscribe:!d,participantTracks:[]}),publishTracks:x8(n),dataChannels:this.dataChannelsInfo(),trackSidsDisabled:p,datachannelReceiveStates:this.reliableReceivedState.map((b,m)=>new dx({publisherSid:m,lastSeq:b}))}))}failNext(){this.shouldFailNext=!0}dataChannelsInfo(){const e=[],n=(i,r)=>{(i==null?void 0:i.id)!==void 0&&i.id!==null&&e.push(new hx({label:i.label,id:i.id,target:r}))};return n(this.dataChannelForKind(Me.LOSSY),ir.PUBLISHER),n(this.dataChannelForKind(Me.RELIABLE),ir.PUBLISHER),n(this.dataChannelForKind(Me.LOSSY,!0),ir.SUBSCRIBER),n(this.dataChannelForKind(Me.RELIABLE,!0),ir.SUBSCRIBER),e}clearReconnectTimeout(){this.reconnectTimeout&&yn.clearTimeout(this.reconnectTimeout)}clearPendingReconnect(){this.clearReconnectTimeout(),this.reconnectAttempts=0}registerOnLineListener(){ri()&&(window.addEventListener("online",this.handleBrowserOnLine),window.addEventListener("offline",this.handleBrowserOffline))}deregisterOnLineListener(){ri()&&(window.removeEventListener("online",this.handleBrowserOnLine),window.removeEventListener("offline",this.handleBrowserOffline))}getTrackIdForReceiver(e){var n;const i=(n=this.pcManager)===null||n===void 0?void 0:n.getMidForReceiver(e);if(i){const r=Object.entries(this.midToTrackId).find(a=>{let[o]=a;return o===i});if(r)return r[1]}}}function GD(t){return t!==void 0&&t>13}function JS(t,e){const n=t.participantIdentity?t.participantIdentity:e.participantIdentity;t.participantIdentity=n,e.participantIdentity=n;const i=t.destinationIdentities.length!==0?t.destinationIdentities:e.destinationIdentities;t.destinationIdentities=i,e.destinationIdentities=i}class $S{get info(){return this._info}validateBytesReceived(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!1;if(!(typeof this.totalByteSize!="number"||this.totalByteSize===0)){if(e&&this.bytesReceived<this.totalByteSize)throw new Pi("Not enough chunk(s) received - expected ".concat(this.totalByteSize," bytes of data total, only received ").concat(this.bytesReceived," bytes"),Bn.Incomplete);if(this.bytesReceived>this.totalByteSize)throw new Pi("Extra chunk(s) received - expected ".concat(this.totalByteSize," bytes of data total, received ").concat(this.bytesReceived," bytes"),Bn.LengthExceeded)}}constructor(e,n,i,r){this.reader=n,this.totalByteSize=i,this._info=e,this.bytesReceived=0,this.outOfBandFailureRejectingFuture=r}}class WD extends $S{handleChunkReceived(e){var n;this.bytesReceived+=e.content.byteLength,this.validateBytesReceived();const i=this.totalByteSize?this.bytesReceived/this.totalByteSize:void 0;(n=this.onProgress)===null||n===void 0||n.call(this,i)}[Symbol.asyncIterator](){const e=this.reader.getReader();let n=new Li,i=null,r=null;if(this.signal){const o=this.signal;r=()=>{var s;(s=n.reject)===null||s===void 0||s.call(n,o.reason)},o.addEventListener("abort",r),i=o}const a=()=>{e.releaseLock(),i&&r&&i.removeEventListener("abort",r),this.signal=void 0};return{next:()=>E(this,void 0,void 0,function*(){var o,s;try{const{done:l,value:c}=yield Promise.race([e.read(),n.promise,(s=(o=this.outOfBandFailureRejectingFuture)===null||o===void 0?void 0:o.promise)!==null&&s!==void 0?s:new Promise(()=>{})]);return l?(this.validateBytesReceived(!0),{done:!0,value:void 0}):(this.handleChunkReceived(c),{done:!1,value:c.content})}catch(l){throw a(),l}}),return(){return E(this,void 0,void 0,function*(){return a(),{done:!0,value:void 0}})}}}withAbortSignal(e){return this.signal=e,this}readAll(){return E(this,arguments,void 0,function(){var e=this;let n=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};return function*(){var i,r,a,o;let s=new Set;const l=n.signal?e.withAbortSignal(n.signal):e;try{for(var c=!0,u=Xr(l),d;d=yield u.next(),i=d.done,!i;c=!0){o=d.value,c=!1;const h=o;s.add(h)}}catch(h){r={error:h}}finally{try{!c&&!i&&(a=u.return)&&(yield a.call(u))}finally{if(r)throw r.error}}return Array.from(s)}()})}}class YD extends $S{constructor(e,n,i,r){super(e,n,i,r),this.receivedChunks=new Map}handleChunkReceived(e){var n;const i=uh(e.chunkIndex),r=this.receivedChunks.get(i);if(r&&r.version>e.version)return;this.receivedChunks.set(i,e),this.bytesReceived+=e.content.byteLength,this.validateBytesReceived();const a=this.totalByteSize?this.bytesReceived/this.totalByteSize:void 0;(n=this.onProgress)===null||n===void 0||n.call(this,a)}[Symbol.asyncIterator](){const e=this.reader.getReader(),n=new TextDecoder("utf-8",{fatal:!0});let i=new Li,r=null,a=null;if(this.signal){const s=this.signal;a=()=>{var l;(l=i.reject)===null||l===void 0||l.call(i,s.reason)},s.addEventListener("abort",a),r=s}const o=()=>{e.releaseLock(),r&&a&&r.removeEventListener("abort",a),this.signal=void 0};return{next:()=>E(this,void 0,void 0,function*(){var s,l;try{const{done:c,value:u}=yield Promise.race([e.read(),i.promise,(l=(s=this.outOfBandFailureRejectingFuture)===null||s===void 0?void 0:s.promise)!==null&&l!==void 0?l:new Promise(()=>{})]);if(c)return this.validateBytesReceived(!0),{done:!0,value:void 0};{this.handleChunkReceived(u);let d;try{d=n.decode(u.content)}catch(h){throw new Pi("Cannot decode datastream chunk ".concat(u.chunkIndex," as text: ").concat(h),Bn.DecodeFailed)}return{done:!1,value:d}}}catch(c){throw o(),c}}),return(){return E(this,void 0,void 0,function*(){return o(),{done:!0,value:void 0}})}}}withAbortSignal(e){return this.signal=e,this}readAll(){return E(this,arguments,void 0,function(){var e=this;let n=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};return function*(){var i,r,a,o;let s="";const l=n.signal?e.withAbortSignal(n.signal):e;try{for(var c=!0,u=Xr(l),d;d=yield u.next(),i=d.done,!i;c=!0)o=d.value,c=!1,s+=o}catch(h){r={error:h}}finally{try{!c&&!i&&(a=u.return)&&(yield a.call(u))}finally{if(r)throw r.error}}return s}()})}}class KD{constructor(){this.log=Re,this.byteStreamControllers=new Map,this.textStreamControllers=new Map,this.byteStreamHandlers=new Map,this.textStreamHandlers=new Map}registerTextStreamHandler(e,n){if(this.textStreamHandlers.has(e))throw new Pi('A text stream handler for topic "'.concat(e,'" has already been set.'),Bn.HandlerAlreadyRegistered);this.textStreamHandlers.set(e,n)}unregisterTextStreamHandler(e){this.textStreamHandlers.delete(e)}registerByteStreamHandler(e,n){if(this.byteStreamHandlers.has(e))throw new Pi('A byte stream handler for topic "'.concat(e,'" has already been set.'),Bn.HandlerAlreadyRegistered);this.byteStreamHandlers.set(e,n)}unregisterByteStreamHandler(e){this.byteStreamHandlers.delete(e)}clearControllers(){this.byteStreamControllers.clear(),this.textStreamControllers.clear()}validateParticipantHasNoActiveDataStreams(e){var n,i,r,a;const o=Array.from(this.textStreamControllers.entries()).filter(l=>l[1].sendingParticipantIdentity===e),s=Array.from(this.byteStreamControllers.entries()).filter(l=>l[1].sendingParticipantIdentity===e);if(o.length>0||s.length>0){const l=new Pi("Participant ".concat(e," unexpectedly disconnected in the middle of sending data"),Bn.AbnormalEnd);for(const[c,u]of s)(i=(n=u.outOfBandFailureRejectingFuture).reject)===null||i===void 0||i.call(n,l),this.byteStreamControllers.delete(c);for(const[c,u]of o)(a=(r=u.outOfBandFailureRejectingFuture).reject)===null||a===void 0||a.call(r,l),this.textStreamControllers.delete(c)}}handleDataStreamPacket(e,n){return E(this,void 0,void 0,function*(){switch(e.value.case){case"streamHeader":return this.handleStreamHeader(e.value.value,e.participantIdentity,n);case"streamChunk":return this.handleStreamChunk(e.value.value,n);case"streamTrailer":return this.handleStreamTrailer(e.value.value,n);default:throw new Error('DataPacket of value "'.concat(e.value.case,'" is not data stream related!'))}})}handleStreamHeader(e,n,i){return E(this,void 0,void 0,function*(){var r;if(e.contentHeader.case==="byteHeader"){const a=this.byteStreamHandlers.get(e.topic);if(!a){this.log.debug("ignoring incoming byte stream due to no handler for topic",e.topic);return}let o;const s=new Li;s.promise.catch(u=>{this.log.error(u)});const l={id:e.streamId,name:(r=e.contentHeader.value.name)!==null&&r!==void 0?r:"unknown",mimeType:e.mimeType,size:e.totalLength?Number(e.totalLength):void 0,topic:e.topic,timestamp:uh(e.timestamp),attributes:e.attributes,encryptionType:i},c=new ReadableStream({start:u=>{if(o=u,this.textStreamControllers.has(e.streamId))throw new Pi("A data stream read is already in progress for a stream with id ".concat(e.streamId,"."),Bn.AlreadyOpened);this.byteStreamControllers.set(e.streamId,{info:l,controller:o,startTime:Date.now(),sendingParticipantIdentity:n,outOfBandFailureRejectingFuture:s})}});a(new WD(l,c,uh(e.totalLength),s),{identity:n})}else if(e.contentHeader.case==="textHeader"){const a=this.textStreamHandlers.get(e.topic);if(!a){this.log.debug("ignoring incoming text stream due to no handler for topic",e.topic);return}let o;const s=new Li;s.promise.catch(u=>{this.log.error(u)});const l={id:e.streamId,mimeType:e.mimeType,size:e.totalLength?Number(e.totalLength):void 0,topic:e.topic,timestamp:Number(e.timestamp),attributes:e.attributes,encryptionType:i},c=new ReadableStream({start:u=>{if(o=u,this.textStreamControllers.has(e.streamId))throw new Pi("A data stream read is already in progress for a stream with id ".concat(e.streamId,"."),Bn.AlreadyOpened);this.textStreamControllers.set(e.streamId,{info:l,controller:o,startTime:Date.now(),sendingParticipantIdentity:n,outOfBandFailureRejectingFuture:s})}});a(new YD(l,c,uh(e.totalLength),s),{identity:n})}})}handleStreamChunk(e,n){const i=this.byteStreamControllers.get(e.streamId);i&&(i.info.encryptionType!==n?(i.controller.error(new Pi("Encryption type mismatch for stream ".concat(e.streamId,". Expected ").concat(n,", got ").concat(i.info.encryptionType),Bn.EncryptionTypeMismatch)),this.byteStreamControllers.delete(e.streamId)):e.content.length>0&&i.controller.enqueue(e));const r=this.textStreamControllers.get(e.streamId);r&&(r.info.encryptionType!==n?(r.controller.error(new Pi("Encryption type mismatch for stream ".concat(e.streamId,". Expected ").concat(n,", got ").concat(r.info.encryptionType),Bn.EncryptionTypeMismatch)),this.textStreamControllers.delete(e.streamId)):e.content.length>0&&r.controller.enqueue(e))}handleStreamTrailer(e,n){const i=this.textStreamControllers.get(e.streamId);i&&(i.info.encryptionType!==n?i.controller.error(new Pi("Encryption type mismatch for stream ".concat(e.streamId,". Expected ").concat(n,", got ").concat(i.info.encryptionType),Bn.EncryptionTypeMismatch)):(i.info.attributes=Object.assign(Object.assign({},i.info.attributes),e.attributes),i.controller.close(),this.textStreamControllers.delete(e.streamId)));const r=this.byteStreamControllers.get(e.streamId);r&&(r.info.encryptionType!==n?r.controller.error(new Pi("Encryption type mismatch for stream ".concat(e.streamId,". Expected ").concat(n,", got ").concat(r.info.encryptionType),Bn.EncryptionTypeMismatch)):(r.info.attributes=Object.assign(Object.assign({},r.info.attributes),e.attributes),r.controller.close()),this.byteStreamControllers.delete(e.streamId))}}class QS{constructor(e,n,i){this.writableStream=e,this.defaultWriter=e.getWriter(),this.onClose=i,this.info=n}write(e){return this.defaultWriter.write(e)}close(){return E(this,void 0,void 0,function*(){var e;yield this.defaultWriter.close(),this.defaultWriter.releaseLock(),(e=this.onClose)===null||e===void 0||e.call(this)})}}class XD extends QS{}class JD extends QS{}const ZS=15e3;class $D{constructor(e,n){this.engine=e,this.log=n}setupEngine(e){this.engine=e}sendText(e,n){return E(this,void 0,void 0,function*(){var i;const r=crypto.randomUUID(),o=new TextEncoder().encode(e).byteLength,s=(i=n==null?void 0:n.attachments)===null||i===void 0?void 0:i.map(()=>crypto.randomUUID()),l=new Array(s?s.length+1:1).fill(0),c=(d,h)=>{var p;l[h]=d;const b=l.reduce((m,S)=>m+S,0);(p=n==null?void 0:n.onProgress)===null||p===void 0||p.call(n,b)},u=yield this.streamText({streamId:r,totalSize:o,destinationIdentities:n==null?void 0:n.destinationIdentities,topic:n==null?void 0:n.topic,attachedStreamIds:s,attributes:n==null?void 0:n.attributes});return yield u.write(e),c(1,0),yield u.close(),n!=null&&n.attachments&&s&&(yield Promise.all(n.attachments.map((d,h)=>E(this,void 0,void 0,function*(){return this._sendFile(s[h],d,{topic:n.topic,mimeType:d.type,onProgress:p=>{c(p,h+1)}})})))),u.info})}streamText(e){return E(this,void 0,void 0,function*(){var n,i,r;const a=(n=e==null?void 0:e.streamId)!==null&&n!==void 0?n:crypto.randomUUID(),o={id:a,mimeType:"text/plain",timestamp:Date.now(),topic:(i=e==null?void 0:e.topic)!==null&&i!==void 0?i:"",size:e==null?void 0:e.totalSize,attributes:e==null?void 0:e.attributes,encryptionType:!((r=this.engine.e2eeManager)===null||r===void 0)&&r.isDataChannelEncryptionEnabled?$t.GCM:$t.NONE},s=new Yd({streamId:a,mimeType:o.mimeType,topic:o.topic,timestamp:Go(o.timestamp),totalLength:Go(e==null?void 0:e.totalSize),attributes:o.attributes,contentHeader:{case:"textHeader",value:new nx({version:e==null?void 0:e.version,attachedStreamIds:e==null?void 0:e.attachedStreamIds,replyToStreamId:e==null?void 0:e.replyToStreamId,operationType:(e==null?void 0:e.type)==="update"?bm.UPDATE:bm.CREATE})}}),l=e==null?void 0:e.destinationIdentities,c=new jn({destinationIdentities:l,value:{case:"streamHeader",value:s}});yield this.engine.sendDataPacket(c,Me.RELIABLE);let u=0;const d=this.engine,h=new WritableStream({write(m){return E(this,void 0,void 0,function*(){for(const S of V8(m,ZS)){const g=new Kd({content:S,streamId:a,chunkIndex:Go(u)}),y=new jn({destinationIdentities:l,value:{case:"streamChunk",value:g}});yield d.sendDataPacket(y,Me.RELIABLE),u+=1}})},close(){return E(this,void 0,void 0,function*(){const m=new Xd({streamId:a}),S=new jn({destinationIdentities:l,value:{case:"streamTrailer",value:m}});yield d.sendDataPacket(S,Me.RELIABLE)})},abort(m){console.log("Sink error:",m)}});let p=()=>E(this,void 0,void 0,function*(){yield b.close()});d.once(re.Closing,p);const b=new XD(h,o,()=>this.engine.off(re.Closing,p));return b})}sendFile(e,n){return E(this,void 0,void 0,function*(){const i=crypto.randomUUID();return yield this._sendFile(i,e,n),{id:i}})}_sendFile(e,n,i){return E(this,void 0,void 0,function*(){var r;const a=yield this.streamBytes({streamId:e,totalSize:n.size,name:n.name,mimeType:(r=i==null?void 0:i.mimeType)!==null&&r!==void 0?r:n.type,topic:i==null?void 0:i.topic,destinationIdentities:i==null?void 0:i.destinationIdentities}),o=n.stream().getReader();for(;;){const{done:s,value:l}=yield o.read();if(s)break;yield a.write(l)}return yield a.close(),a.info})}streamBytes(e){return E(this,void 0,void 0,function*(){var n,i,r,a,o,s;const l=(n=e==null?void 0:e.streamId)!==null&&n!==void 0?n:crypto.randomUUID(),c=e==null?void 0:e.destinationIdentities,u={id:l,mimeType:(i=e==null?void 0:e.mimeType)!==null&&i!==void 0?i:"application/octet-stream",topic:(r=e==null?void 0:e.topic)!==null&&r!==void 0?r:"",timestamp:Date.now(),attributes:e==null?void 0:e.attributes,size:e==null?void 0:e.totalSize,name:(a=e==null?void 0:e.name)!==null&&a!==void 0?a:"unknown",encryptionType:!((o=this.engine.e2eeManager)===null||o===void 0)&&o.isDataChannelEncryptionEnabled?$t.GCM:$t.NONE},d=new Yd({totalLength:Go((s=u.size)!==null&&s!==void 0?s:0),mimeType:u.mimeType,streamId:l,topic:u.topic,timestamp:Go(Date.now()),attributes:u.attributes,contentHeader:{case:"byteHeader",value:new ix({name:u.name})}}),h=new jn({destinationIdentities:c,value:{case:"streamHeader",value:d}});yield this.engine.sendDataPacket(h,Me.RELIABLE);let p=0;const b=new In,m=this.engine,S=this.log,g=new WritableStream({write(x){return E(this,void 0,void 0,function*(){const v=yield b.lock();let k=0;try{for(;k<x.byteLength;){const T=x.slice(k,k+ZS),C=new jn({destinationIdentities:c,value:{case:"streamChunk",value:new Kd({content:T,streamId:l,chunkIndex:Go(p)})}});yield m.sendDataPacket(C,Me.RELIABLE),p+=1,k+=T.byteLength}}finally{v()}})},close(){return E(this,void 0,void 0,function*(){const x=new Xd({streamId:l}),v=new jn({destinationIdentities:c,value:{case:"streamTrailer",value:x}});yield m.sendDataPacket(v,Me.RELIABLE)})},abort(x){S.error("Sink error:",x)}});return new JD(g,u)})}}class ek extends V{constructor(e,n,i,r,a){super(e,i,a),this.sid=n,this.receiver=r}get isLocal(){return!1}setMuted(e){this.isMuted!==e&&(this.isMuted=e,this._mediaStreamTrack.enabled=!e,this.emit(e?ne.Muted:ne.Unmuted,this))}setMediaStream(e){this.mediaStream=e;const n=i=>{i.track===this._mediaStreamTrack&&(e.removeEventListener("removetrack",n),this.receiver&&"playoutDelayHint"in this.receiver&&(this.receiver.playoutDelayHint=void 0),this.receiver=void 0,this._currentBitrate=0,this.emit(ne.Ended,this))};e.addEventListener("removetrack",n)}start(){this.startMonitor(),super.enable()}stop(){this.stopMonitor(),super.disable()}getRTCStatsReport(){return E(this,void 0,void 0,function*(){var e;return!((e=this.receiver)===null||e===void 0)&&e.getStats?yield this.receiver.getStats():void 0})}setPlayoutDelay(e){this.receiver?"playoutDelayHint"in this.receiver?this.receiver.playoutDelayHint=e:this.log.warn("Playout delay not supported in this browser"):this.log.warn("Cannot set playout delay, track already ended")}getPlayoutDelay(){if(this.receiver){if("playoutDelayHint"in this.receiver)return this.receiver.playoutDelayHint;this.log.warn("Playout delay not supported in this browser")}else this.log.warn("Cannot get playout delay, track already ended");return 0}startMonitor(){this.monitorInterval||(this.monitorInterval=setInterval(()=>this.monitorReceiver(),fg)),S8()&&this.registerTimeSyncUpdate()}registerTimeSyncUpdate(){const e=()=>{var n;this.timeSyncHandle=requestAnimationFrame(()=>e());const i=(n=this.receiver)===null||n===void 0?void 0:n.getSynchronizationSources()[0];if(i){const{timestamp:r,rtpTimestamp:a}=i;a&&this.rtpTimestamp!==a&&(this.emit(ne.TimeSyncUpdate,{timestamp:r,rtpTimestamp:a}),this.rtpTimestamp=a)}};e()}}class QD extends ek{constructor(e,n,i,r,a,o){super(e,n,V.Kind.Audio,i,o),this.monitorReceiver=()=>E(this,void 0,void 0,function*(){if(!this.receiver){this._currentBitrate=0;return}const s=yield this.getReceiverStats();s&&this.prevStats&&this.receiver&&(this._currentBitrate=dh(s,this.prevStats)),this.prevStats=s}),this.audioContext=r,this.webAudioPluginNodes=[],a&&(this.sinkId=a.deviceId)}setVolume(e){var n;for(const i of this.attachedElements)this.audioContext?(n=this.gainNode)===null||n===void 0||n.gain.setTargetAtTime(e,0,.1):i.volume=e;Nr()&&this._mediaStreamTrack._setVolume(e),this.elementVolume=e}getVolume(){if(this.elementVolume)return this.elementVolume;if(Nr())return 1;let e=0;return this.attachedElements.forEach(n=>{n.volume>e&&(e=n.volume)}),e}setSinkId(e){return E(this,void 0,void 0,function*(){this.sinkId=e,yield Promise.all(this.attachedElements.map(n=>{if(Km(n))return n.setSinkId(e)}))})}attach(e){const n=this.attachedElements.length===0;return e?super.attach(e):e=super.attach(),this.sinkId&&Km(e)&&e.setSinkId(this.sinkId).catch(i=>{this.log.error("Failed to set sink id on remote audio track",i,this.logContext)}),this.audioContext&&n&&(this.log.debug("using audio context mapping",this.logContext),this.connectWebAudio(this.audioContext,e),e.volume=0,e.muted=!0),this.elementVolume&&this.setVolume(this.elementVolume),e}detach(e){let n;return e?(n=super.detach(e),this.audioContext&&(this.attachedElements.length>0?this.connectWebAudio(this.audioContext,this.attachedElements[0]):this.disconnectWebAudio())):(n=super.detach(),this.disconnectWebAudio()),n}setAudioContext(e){this.audioContext=e,e&&this.attachedElements.length>0?this.connectWebAudio(e,this.attachedElements[0]):e||this.disconnectWebAudio()}setWebAudioPlugins(e){this.webAudioPluginNodes=e,this.attachedElements.length>0&&this.audioContext&&this.connectWebAudio(this.audioContext,this.attachedElements[0])}connectWebAudio(e,n){this.disconnectWebAudio(),this.sourceNode=e.createMediaStreamSource(n.srcObject);let i=this.sourceNode;this.webAudioPluginNodes.forEach(r=>{i.connect(r),i=r}),this.gainNode=e.createGain(),i.connect(this.gainNode),this.gainNode.connect(e.destination),this.elementVolume&&this.gainNode.gain.setTargetAtTime(this.elementVolume,0,.1),e.state!=="running"&&e.resume().then(()=>{e.state!=="running"&&this.emit(ne.AudioPlaybackFailed,new Error("Audio Context couldn't be started automatically"))}).catch(r=>{this.emit(ne.AudioPlaybackFailed,r)})}disconnectWebAudio(){var e,n;(e=this.gainNode)===null||e===void 0||e.disconnect(),(n=this.sourceNode)===null||n===void 0||n.disconnect(),this.gainNode=void 0,this.sourceNode=void 0}getReceiverStats(){return E(this,void 0,void 0,function*(){if(!this.receiver||!this.receiver.getStats)return;const e=yield this.receiver.getStats();let n;return e.forEach(i=>{i.type==="inbound-rtp"&&(n={type:"audio",streamId:i.id,timestamp:i.timestamp,jitter:i.jitter,bytesReceived:i.bytesReceived,concealedSamples:i.concealedSamples,concealmentEvents:i.concealmentEvents,silentConcealedSamples:i.silentConcealedSamples,silentConcealmentEvents:i.silentConcealmentEvents,totalAudioEnergy:i.totalAudioEnergy,totalSamplesDuration:i.totalSamplesDuration})}),n})}}const yg=100;class ZD extends ek{constructor(e,n,i,r,a){super(e,n,V.Kind.Video,i,a),this.elementInfos=[],this.monitorReceiver=()=>E(this,void 0,void 0,function*(){if(!this.receiver){this._currentBitrate=0;return}const o=yield this.getReceiverStats();o&&this.prevStats&&this.receiver&&(this._currentBitrate=dh(o,this.prevStats)),this.prevStats=o}),this.debouncedHandleResize=lg(()=>{this.updateDimensions()},yg),this.adaptiveStreamSettings=r}get isAdaptiveStream(){return this.adaptiveStreamSettings!==void 0}setStreamState(e){super.setStreamState(e),this.log.debug("setStreamState",e),this.isAdaptiveStream&&e===V.StreamState.Active&&this.updateVisibility()}get mediaStreamTrack(){return this._mediaStreamTrack}setMuted(e){super.setMuted(e),this.attachedElements.forEach(n=>{e?Ps(this._mediaStreamTrack,n):Ds(this._mediaStreamTrack,n)})}attach(e){if(e?super.attach(e):e=super.attach(),this.adaptiveStreamSettings&&this.elementInfos.find(n=>n.element===e)===void 0){const n=new eP(e);this.observeElementInfo(n)}return e}observeElementInfo(e){this.adaptiveStreamSettings&&this.elementInfos.find(n=>n===e)===void 0?(e.handleResize=()=>{this.debouncedHandleResize()},e.handleVisibilityChanged=()=>{this.updateVisibility()},this.elementInfos.push(e),e.observe(),this.debouncedHandleResize(),this.updateVisibility()):this.log.warn("visibility resize observer not triggered",this.logContext)}stopObservingElementInfo(e){if(!this.isAdaptiveStream){this.log.warn("stopObservingElementInfo ignored",this.logContext);return}const n=this.elementInfos.filter(i=>i===e);for(const i of n)i.stopObserving();this.elementInfos=this.elementInfos.filter(i=>i!==e),this.updateVisibility(),this.debouncedHandleResize()}detach(e){let n=[];if(e)return this.stopObservingElement(e),super.detach(e);n=super.detach();for(const i of n)this.stopObservingElement(i);return n}getDecoderImplementation(){var e;return(e=this.prevStats)===null||e===void 0?void 0:e.decoderImplementation}getReceiverStats(){return E(this,void 0,void 0,function*(){if(!this.receiver||!this.receiver.getStats)return;const e=yield this.receiver.getStats();let n,i="",r=new Map;return e.forEach(a=>{a.type==="inbound-rtp"?(i=a.codecId,n={type:"video",streamId:a.id,framesDecoded:a.framesDecoded,framesDropped:a.framesDropped,framesReceived:a.framesReceived,packetsReceived:a.packetsReceived,packetsLost:a.packetsLost,frameWidth:a.frameWidth,frameHeight:a.frameHeight,pliCount:a.pliCount,firCount:a.firCount,nackCount:a.nackCount,jitter:a.jitter,timestamp:a.timestamp,bytesReceived:a.bytesReceived,decoderImplementation:a.decoderImplementation}):a.type==="codec"&&r.set(a.id,a)}),n&&i!==""&&r.get(i)&&(n.mimeType=r.get(i).mimeType),n})}stopObservingElement(e){const n=this.elementInfos.filter(i=>i.element===e);for(const i of n)this.stopObservingElementInfo(i)}handleAppVisibilityChanged(){const e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return E(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),this.isAdaptiveStream&&this.updateVisibility()})}updateVisibility(e){var n,i;const r=this.elementInfos.reduce((l,c)=>Math.max(l,c.visibilityChangedAt||0),0),a=!((i=(n=this.adaptiveStreamSettings)===null||n===void 0?void 0:n.pauseVideoInBackground)!==null&&i!==void 0)||i?this.isInBackground:!1,o=this.elementInfos.some(l=>l.pictureInPicture),s=this.elementInfos.some(l=>l.visible)&&!a||o;if(!(this.lastVisible===s&&!e)){if(!s&&Date.now()-r<yg){yn.setTimeout(()=>{this.updateVisibility()},yg);return}this.lastVisible=s,this.emit(ne.VisibilityChanged,s,this)}}updateDimensions(){var e,n;let i=0,r=0;const a=this.getPixelDensity();for(const o of this.elementInfos){const s=o.width()*a,l=o.height()*a;s+l>i+r&&(i=s,r=l)}((e=this.lastDimensions)===null||e===void 0?void 0:e.width)===i&&((n=this.lastDimensions)===null||n===void 0?void 0:n.height)===r||(this.lastDimensions={width:i,height:r},this.emit(ne.VideoDimensionsChanged,this.lastDimensions,this))}getPixelDensity(){var e;const n=(e=this.adaptiveStreamSettings)===null||e===void 0?void 0:e.pixelDensity;return n==="screen"?gS():n||(gS()>2?2:1)}}class eP{get visible(){return this.isPiP||this.isIntersecting}get pictureInPicture(){return this.isPiP}constructor(e,n){this.onVisibilityChanged=i=>{var r;const{target:a,isIntersecting:o}=i;a===this.element&&(this.isIntersecting=o,this.isPiP=yc(this.element),this.visibilityChangedAt=Date.now(),(r=this.handleVisibilityChanged)===null||r===void 0||r.call(this))},this.onEnterPiP=()=>{var i,r,a;(r=(i=window.documentPictureInPicture)===null||i===void 0?void 0:i.window)===null||r===void 0||r.addEventListener("pagehide",this.onLeavePiP),this.isPiP=yc(this.element),(a=this.handleVisibilityChanged)===null||a===void 0||a.call(this)},this.onLeavePiP=()=>{var i;this.isPiP=yc(this.element),(i=this.handleVisibilityChanged)===null||i===void 0||i.call(this)},this.element=e,this.isIntersecting=n??_g(e),this.isPiP=ri()&&yc(e),this.visibilityChangedAt=0}width(){return this.element.clientWidth}height(){return this.element.clientHeight}observe(){var e,n,i;this.isIntersecting=_g(this.element),this.isPiP=yc(this.element),this.element.handleResize=()=>{var r;(r=this.handleResize)===null||r===void 0||r.call(this)},this.element.handleVisibilityChanged=this.onVisibilityChanged,bS().observe(this.element),vS().observe(this.element),this.element.addEventListener("enterpictureinpicture",this.onEnterPiP),this.element.addEventListener("leavepictureinpicture",this.onLeavePiP),(e=window.documentPictureInPicture)===null||e===void 0||e.addEventListener("enter",this.onEnterPiP),(i=(n=window.documentPictureInPicture)===null||n===void 0?void 0:n.window)===null||i===void 0||i.addEventListener("pagehide",this.onLeavePiP)}stopObserving(){var e,n,i,r,a;(e=bS())===null||e===void 0||e.unobserve(this.element),(n=vS())===null||n===void 0||n.unobserve(this.element),this.element.removeEventListener("enterpictureinpicture",this.onEnterPiP),this.element.removeEventListener("leavepictureinpicture",this.onLeavePiP),(i=window.documentPictureInPicture)===null||i===void 0||i.removeEventListener("enter",this.onEnterPiP),(a=(r=window.documentPictureInPicture)===null||r===void 0?void 0:r.window)===null||a===void 0||a.removeEventListener("pagehide",this.onLeavePiP)}}function yc(t){var e,n;return document.pictureInPictureElement===t?!0:!((e=window.documentPictureInPicture)===null||e===void 0)&&e.window?_g(t,(n=window.documentPictureInPicture)===null||n===void 0?void 0:n.window):!1}function _g(t,e){const n=e||window;let i=t.offsetTop,r=t.offsetLeft;const a=t.offsetWidth,o=t.offsetHeight,{hidden:s}=t,{display:l}=getComputedStyle(t);for(;t.offsetParent;)t=t.offsetParent,i+=t.offsetTop,r+=t.offsetLeft;return i<n.pageYOffset+n.innerHeight&&r<n.pageXOffset+n.innerWidth&&i+o>n.pageYOffset&&r+a>n.pageXOffset&&!s&&l!=="none"}class Qr extends Rr.EventEmitter{constructor(e,n,i,r){var a;super(),this.metadataMuted=!1,this.encryption=$t.NONE,this.log=Re,this.handleMuted=()=>{this.emit(ne.Muted)},this.handleUnmuted=()=>{this.emit(ne.Unmuted)},this.log=Kr((a=r==null?void 0:r.loggerName)!==null&&a!==void 0?a:rr.Publication),this.loggerContextCb=this.loggerContextCb,this.setMaxListeners(100),this.kind=e,this.trackSid=n,this.trackName=i,this.source=V.Source.Unknown}setTrack(e){this.track&&(this.track.off(ne.Muted,this.handleMuted),this.track.off(ne.Unmuted,this.handleUnmuted)),this.track=e,e&&(e.on(ne.Muted,this.handleMuted),e.on(ne.Unmuted,this.handleUnmuted))}get logContext(){var e;return Object.assign(Object.assign({},(e=this.loggerContextCb)===null||e===void 0?void 0:e.call(this)),Be(this))}get isMuted(){return this.metadataMuted}get isEnabled(){return!0}get isSubscribed(){return this.track!==void 0}get isEncrypted(){return this.encryption!==$t.NONE}get audioTrack(){if(Mr(this.track))return this.track}get videoTrack(){if(Ua(this.track))return this.track}updateInfo(e){this.trackSid=e.sid,this.trackName=e.name,this.source=V.sourceFromProto(e.source),this.mimeType=e.mimeType,this.kind===V.Kind.Video&&e.width>0&&(this.dimensions={width:e.width,height:e.height},this.simulcasted=e.simulcast),this.encryption=e.encryption,this.trackInfo=e,this.log.debug("update publication info",Object.assign(Object.assign({},this.logContext),{info:e}))}}(function(t){(function(e){e.Desired="desired",e.Subscribed="subscribed",e.Unsubscribed="unsubscribed"})(t.SubscriptionStatus||(t.SubscriptionStatus={})),function(e){e.Allowed="allowed",e.NotAllowed="not_allowed"}(t.PermissionStatus||(t.PermissionStatus={}))})(Qr||(Qr={}));class xg extends Qr{get isUpstreamPaused(){var e;return(e=this.track)===null||e===void 0?void 0:e.isUpstreamPaused}constructor(e,n,i,r){super(e,n.sid,n.name,r),this.track=void 0,this.handleTrackEnded=()=>{this.emit(ne.Ended)},this.handleCpuConstrained=()=>{this.track&&Ua(this.track)&&this.emit(ne.CpuConstrained,this.track)},this.updateInfo(n),this.setTrack(i)}setTrack(e){this.track&&(this.track.off(ne.Ended,this.handleTrackEnded),this.track.off(ne.CpuConstrained,this.handleCpuConstrained)),super.setTrack(e),e&&(e.on(ne.Ended,this.handleTrackEnded),e.on(ne.CpuConstrained,this.handleCpuConstrained))}get isMuted(){return this.track?this.track.isMuted:super.isMuted}get audioTrack(){return super.audioTrack}get videoTrack(){return super.videoTrack}get isLocal(){return!0}mute(){return E(this,void 0,void 0,function*(){var e;return(e=this.track)===null||e===void 0?void 0:e.mute()})}unmute(){return E(this,void 0,void 0,function*(){var e;return(e=this.track)===null||e===void 0?void 0:e.unmute()})}pauseUpstream(){return E(this,void 0,void 0,function*(){var e;yield(e=this.track)===null||e===void 0?void 0:e.pauseUpstream()})}resumeUpstream(){return E(this,void 0,void 0,function*(){var e;yield(e=this.track)===null||e===void 0?void 0:e.resumeUpstream()})}getTrackFeatures(){var e;if(Mr(this.track)){const n=this.track.getSourceTrackSettings(),i=new Set;return n.autoGainControl&&i.add(an.TF_AUTO_GAIN_CONTROL),n.echoCancellation&&i.add(an.TF_ECHO_CANCELLATION),n.noiseSuppression&&i.add(an.TF_NOISE_SUPPRESSION),n.channelCount&&n.channelCount>1&&i.add(an.TF_STEREO),!((e=this.options)===null||e===void 0)&&e.dtx||i.add(an.TF_NO_DTX),this.track.enhancedNoiseCancellation&&i.add(an.TF_ENHANCED_NOISE_CANCELLATION),Array.from(i.values())}else return[]}}function ph(t,e){return E(this,void 0,void 0,function*(){t??(t={});let n=!1;const{audioProcessor:i,videoProcessor:r,optionsWithoutProcessor:a}=cS(t);let o=a.audio,s=a.video;if(i&&typeof a.audio=="object"&&(a.audio.processor=i),r&&typeof a.video=="object"&&(a.video.processor=r),t.audio&&typeof a.audio=="object"&&typeof a.audio.deviceId=="string"){const d=a.audio.deviceId;a.audio.deviceId={exact:d},n=!0,o=Object.assign(Object.assign({},a.audio),{deviceId:{ideal:d}})}if(a.video&&typeof a.video=="object"&&typeof a.video.deviceId=="string"){const d=a.video.deviceId;a.video.deviceId={exact:d},n=!0,s=Object.assign(Object.assign({},a.video),{deviceId:{ideal:d}})}a.audio===!0?a.audio={deviceId:"default"}:typeof a.audio=="object"&&a.audio!==null&&(a.audio=Object.assign(Object.assign({},a.audio),{deviceId:a.audio.deviceId||"default"})),a.video===!0?a.video={deviceId:"default"}:typeof a.video=="object"&&!a.video.deviceId&&(a.video.deviceId="default");const l=oS(a,IS,jS),c=Vm(l),u=navigator.mediaDevices.getUserMedia(c);a.audio&&(on.userMediaPromiseMap.set("audioinput",u),u.catch(()=>on.userMediaPromiseMap.delete("audioinput"))),a.video&&(on.userMediaPromiseMap.set("videoinput",u),u.catch(()=>on.userMediaPromiseMap.delete("videoinput")));try{const d=yield u;return yield Promise.all(d.getTracks().map(h=>E(this,void 0,void 0,function*(){const p=h.kind==="audio";let b=p?l.audio:l.video;(typeof b=="boolean"||!b)&&(b={});let m;const S=p?c.audio:c.video;typeof S!="boolean"&&(m=S);const g=h.getSettings().deviceId;m!=null&&m.deviceId&&Ba(m.deviceId)!==g?m.deviceId=g:m||(m={deviceId:g});const y=RD(h,m,e);return y.kind===V.Kind.Video?y.source=V.Source.Camera:y.kind===V.Kind.Audio&&(y.source=V.Source.Microphone),y.mediaStream=d,Mr(y)&&i?yield y.setProcessor(i):Ua(y)&&r&&(yield y.setProcessor(r)),y})))}catch(d){if(!n)throw d;return ph(Object.assign(Object.assign({},t),{audio:o,video:s}),e)}})}function tP(t){return E(this,void 0,void 0,function*(){return(yield ph({audio:!1,video:t??!0}))[0]})}function nP(t){return E(this,void 0,void 0,function*(){return(yield ph({audio:t??!0,video:!1}))[0]})}var Va;(function(t){t.Excellent="excellent",t.Good="good",t.Poor="poor",t.Lost="lost",t.Unknown="unknown"})(Va||(Va={}));function iP(t){switch(t){case ac.EXCELLENT:return Va.Excellent;case ac.GOOD:return Va.Good;case ac.POOR:return Va.Poor;case ac.LOST:return Va.Lost;default:return Va.Unknown}}class tk extends Rr.EventEmitter{get logContext(){var e,n;return Object.assign({},(n=(e=this.loggerOptions)===null||e===void 0?void 0:e.loggerContextCb)===null||n===void 0?void 0:n.call(e))}get isEncrypted(){return this.trackPublications.size>0&&Array.from(this.trackPublications.values()).every(e=>e.isEncrypted)}get isAgent(){var e;return((e=this.permissions)===null||e===void 0?void 0:e.agent)||this.kind===sc.AGENT}get isActive(){var e;return((e=this.participantInfo)===null||e===void 0?void 0:e.state)===Rs.ACTIVE}get kind(){return this._kind}get attributes(){return Object.freeze(Object.assign({},this._attributes))}constructor(e,n,i,r,a,o){let s=arguments.length>6&&arguments[6]!==void 0?arguments[6]:sc.STANDARD;var l;super(),this.audioLevel=0,this.isSpeaking=!1,this._connectionQuality=Va.Unknown,this.log=Re,this.log=Kr((l=o==null?void 0:o.loggerName)!==null&&l!==void 0?l:rr.Participant),this.loggerOptions=o,this.setMaxListeners(100),this.sid=e,this.identity=n,this.name=i,this.metadata=r,this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.trackPublications=new Map,this._kind=s,this._attributes=a??{}}getTrackPublications(){return Array.from(this.trackPublications.values())}getTrackPublication(e){for(const[,n]of this.trackPublications)if(n.source===e)return n}getTrackPublicationByName(e){for(const[,n]of this.trackPublications)if(n.trackName===e)return n}waitUntilActive(){return this.isActive?Promise.resolve():this.activeFuture?this.activeFuture.promise:(this.activeFuture=new Li,this.once(se.Active,()=>{var e,n;(n=(e=this.activeFuture)===null||e===void 0?void 0:e.resolve)===null||n===void 0||n.call(e),this.activeFuture=void 0}),this.activeFuture.promise)}get connectionQuality(){return this._connectionQuality}get isCameraEnabled(){var e;const n=this.getTrackPublication(V.Source.Camera);return!(!((e=n==null?void 0:n.isMuted)!==null&&e!==void 0)||e)}get isMicrophoneEnabled(){var e;const n=this.getTrackPublication(V.Source.Microphone);return!(!((e=n==null?void 0:n.isMuted)!==null&&e!==void 0)||e)}get isScreenShareEnabled(){return!!this.getTrackPublication(V.Source.ScreenShare)}get isLocal(){return!1}get joinedAt(){return this.participantInfo?new Date(Number.parseInt(this.participantInfo.joinedAt.toString())*1e3):new Date}updateInfo(e){var n;return this.participantInfo&&this.participantInfo.sid===e.sid&&this.participantInfo.version>e.version?!1:(this.identity=e.identity,this.sid=e.sid,this._setName(e.name),this._setMetadata(e.metadata),this._setAttributes(e.attributes),e.state===Rs.ACTIVE&&((n=this.participantInfo)===null||n===void 0?void 0:n.state)!==Rs.ACTIVE&&this.emit(se.Active),e.permission&&this.setPermissions(e.permission),this.participantInfo=e,!0)}_setMetadata(e){const n=this.metadata!==e,i=this.metadata;this.metadata=e,n&&this.emit(se.ParticipantMetadataChanged,i)}_setName(e){const n=this.name!==e;this.name=e,n&&this.emit(se.ParticipantNameChanged,e)}_setAttributes(e){const n=k8(this.attributes,e);this._attributes=e,Object.keys(n).length>0&&this.emit(se.AttributesChanged,n)}setPermissions(e){var n,i,r,a,o,s;const l=this.permissions,c=e.canPublish!==((n=this.permissions)===null||n===void 0?void 0:n.canPublish)||e.canSubscribe!==((i=this.permissions)===null||i===void 0?void 0:i.canSubscribe)||e.canPublishData!==((r=this.permissions)===null||r===void 0?void 0:r.canPublishData)||e.hidden!==((a=this.permissions)===null||a===void 0?void 0:a.hidden)||e.recorder!==((o=this.permissions)===null||o===void 0?void 0:o.recorder)||e.canPublishSources.length!==this.permissions.canPublishSources.length||e.canPublishSources.some((u,d)=>{var h;return u!==((h=this.permissions)===null||h===void 0?void 0:h.canPublishSources[d])})||e.canSubscribeMetrics!==((s=this.permissions)===null||s===void 0?void 0:s.canSubscribeMetrics);return this.permissions=e,c&&this.emit(se.ParticipantPermissionsChanged,l),c}setIsSpeaking(e){e!==this.isSpeaking&&(this.isSpeaking=e,e&&(this.lastSpokeAt=new Date),this.emit(se.IsSpeakingChanged,e))}setConnectionQuality(e){const n=this._connectionQuality;this._connectionQuality=iP(e),n!==this._connectionQuality&&this.emit(se.ConnectionQualityChanged,this._connectionQuality)}setDisconnected(){var e,n;this.activeFuture&&((n=(e=this.activeFuture).reject)===null||n===void 0||n.call(e,new Error("Participant disconnected")),this.activeFuture=void 0)}setAudioContext(e){this.audioContext=e,this.audioTrackPublications.forEach(n=>Mr(n.track)&&n.track.setAudioContext(e))}addTrackPublication(e){e.on(ne.Muted,()=>{this.emit(se.TrackMuted,e)}),e.on(ne.Unmuted,()=>{this.emit(se.TrackUnmuted,e)});const n=e;switch(n.track&&(n.track.sid=e.trackSid),this.trackPublications.set(e.trackSid,e),e.kind){case V.Kind.Audio:this.audioTrackPublications.set(e.trackSid,e);break;case V.Kind.Video:this.videoTrackPublications.set(e.trackSid,e);break}}}function rP(t){var e,n,i;if(!t.participantSid&&!t.participantIdentity)throw new Error("Invalid track permission, must provide at least one of participantIdentity and participantSid");return new cx({participantIdentity:(e=t.participantIdentity)!==null&&e!==void 0?e:"",participantSid:(n=t.participantSid)!==null&&n!==void 0?n:"",allTracks:(i=t.allowAll)!==null&&i!==void 0?i:!1,trackSids:t.allowedTrackSids||[]})}class aP extends tk{constructor(e,n,i,r,a,o){super(e,n,void 0,void 0,void 0,{loggerName:r.loggerName,loggerContextCb:()=>this.engine.logContext}),this.pendingPublishing=new Set,this.pendingPublishPromises=new Map,this.participantTrackPermissions=[],this.allParticipantsAllowedToSubscribe=!0,this.encryptionType=$t.NONE,this.enabledPublishVideoCodecs=[],this.pendingAcks=new Map,this.pendingResponses=new Map,this.handleReconnecting=()=>{this.reconnectFuture||(this.reconnectFuture=new Li)},this.handleReconnected=()=>{var s,l;(l=(s=this.reconnectFuture)===null||s===void 0?void 0:s.resolve)===null||l===void 0||l.call(s),this.reconnectFuture=void 0,this.updateTrackSubscriptionPermissions()},this.handleClosing=()=>{var s,l,c,u,d,h;this.reconnectFuture&&(this.reconnectFuture.promise.catch(p=>this.log.warn(p.message,this.logContext)),(l=(s=this.reconnectFuture)===null||s===void 0?void 0:s.reject)===null||l===void 0||l.call(s,new Error("Got disconnected during reconnection attempt")),this.reconnectFuture=void 0),this.signalConnectedFuture&&((u=(c=this.signalConnectedFuture).reject)===null||u===void 0||u.call(c,new Error("Got disconnected without signal connected")),this.signalConnectedFuture=void 0),(h=(d=this.activeAgentFuture)===null||d===void 0?void 0:d.reject)===null||h===void 0||h.call(d,new Error("Got disconnected without active agent present")),this.activeAgentFuture=void 0,this.firstActiveAgent=void 0},this.handleSignalConnected=s=>{var l,c;s.participant&&this.updateInfo(s.participant),this.signalConnectedFuture||(this.signalConnectedFuture=new Li),(c=(l=this.signalConnectedFuture).resolve)===null||c===void 0||c.call(l)},this.handleSignalRequestResponse=s=>{const{requestId:l,reason:c,message:u}=s,d=this.pendingSignalRequests.get(l);d&&(c!==Cm.OK&&d.reject(new rS(u,c)),this.pendingSignalRequests.delete(l))},this.handleDataPacket=s=>{switch(s.value.case){case"rpcResponse":let l=s.value.value,c=null,u=null;l.value.case==="payload"?c=l.value.value:l.value.case==="error"&&(u=Dt.fromProto(l.value.value)),this.handleIncomingRpcResponse(l.requestId,c,u);break;case"rpcAck":let d=s.value.value;this.handleIncomingRpcAck(d.requestId);break}},this.updateTrackSubscriptionPermissions=()=>{this.log.debug("updating track subscription permissions",Object.assign(Object.assign({},this.logContext),{allParticipantsAllowed:this.allParticipantsAllowedToSubscribe,participantTrackPermissions:this.participantTrackPermissions})),this.engine.client.sendUpdateSubscriptionPermissions(this.allParticipantsAllowedToSubscribe,this.participantTrackPermissions.map(s=>rP(s)))},this.onTrackUnmuted=s=>{this.onTrackMuted(s,s.isUpstreamPaused)},this.onTrackMuted=(s,l)=>{if(l===void 0&&(l=!0),!s.sid){this.log.error("could not update mute status for unpublished track",Object.assign(Object.assign({},this.logContext),Be(s)));return}this.engine.updateMuteStatus(s.sid,l)},this.onTrackUpstreamPaused=s=>{this.log.debug("upstream paused",Object.assign(Object.assign({},this.logContext),Be(s))),this.onTrackMuted(s,!0)},this.onTrackUpstreamResumed=s=>{this.log.debug("upstream resumed",Object.assign(Object.assign({},this.logContext),Be(s))),this.onTrackMuted(s,s.isMuted)},this.onTrackFeatureUpdate=s=>{const l=this.audioTrackPublications.get(s.sid);if(!l){this.log.warn("Could not update local audio track settings, missing publication for track ".concat(s.sid),this.logContext);return}this.engine.client.sendUpdateLocalAudioTrack(l.trackSid,l.getTrackFeatures())},this.onTrackCpuConstrained=(s,l)=>{this.log.debug("track cpu constrained",Object.assign(Object.assign({},this.logContext),Be(l))),this.emit(se.LocalTrackCpuConstrained,s,l)},this.handleSubscribedQualityUpdate=s=>E(this,void 0,void 0,function*(){var l,c,u,d,h;if(!(!((h=this.roomOptions)===null||h===void 0)&&h.dynacast))return;const p=this.videoTrackPublications.get(s.trackSid);if(!p){this.log.warn("received subscribed quality update for unknown track",Object.assign(Object.assign({},this.logContext),{trackSid:s.trackSid}));return}if(!p.videoTrack)return;const b=yield p.videoTrack.setPublishingCodecs(s.subscribedCodecs);try{for(var m=!0,S=Xr(b),g;g=yield S.next(),l=g.done,!l;m=!0){d=g.value,m=!1;const y=d;b8(y)&&(this.log.debug("publish ".concat(y," for ").concat(p.videoTrack.sid),Object.assign(Object.assign({},this.logContext),Be(p))),yield this.publishAdditionalCodecForTrack(p.videoTrack,y,p.options))}}catch(y){c={error:y}}finally{try{!m&&!l&&(u=S.return)&&(yield u.call(S))}finally{if(c)throw c.error}}}),this.handleLocalTrackUnpublished=s=>{const l=this.trackPublications.get(s.trackSid);if(!l){this.log.warn("received unpublished event for unknown track",Object.assign(Object.assign({},this.logContext),{trackSid:s.trackSid}));return}this.unpublishTrack(l.track)},this.handleTrackEnded=s=>E(this,void 0,void 0,function*(){if(s.source===V.Source.ScreenShare||s.source===V.Source.ScreenShareAudio)this.log.debug("unpublishing local track due to TrackEnded",Object.assign(Object.assign({},this.logContext),Be(s))),this.unpublishTrack(s);else if(s.isUserProvided)yield s.mute();else if($r(s)||za(s))try{if(ri())try{const l=yield navigator==null?void 0:navigator.permissions.query({name:s.source===V.Source.Camera?"camera":"microphone"});if(l&&l.state==="denied")throw this.log.warn("user has revoked access to ".concat(s.source),Object.assign(Object.assign({},this.logContext),Be(s))),l.onchange=()=>{l.state!=="denied"&&(s.isMuted||s.restartTrack(),l.onchange=null)},new Error("GetUserMedia Permission denied")}catch{}s.isMuted||(this.log.debug("track ended, attempting to use a different device",Object.assign(Object.assign({},this.logContext),Be(s))),$r(s)?yield s.restartTrack({deviceId:"default"}):yield s.restartTrack())}catch{this.log.warn("could not restart track, muting instead",Object.assign(Object.assign({},this.logContext),Be(s))),yield s.mute()}}),this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.trackPublications=new Map,this.engine=i,this.roomOptions=r,this.setupEngine(i),this.activeDeviceMap=new Map([["audioinput","default"],["videoinput","default"],["audiooutput","default"]]),this.pendingSignalRequests=new Map,this.rpcHandlers=a,this.roomOutgoingDataStreamManager=o}get lastCameraError(){return this.cameraError}get lastMicrophoneError(){return this.microphoneError}get isE2EEEnabled(){return this.encryptionType!==$t.NONE}getTrackPublication(e){const n=super.getTrackPublication(e);if(n)return n}getTrackPublicationByName(e){const n=super.getTrackPublicationByName(e);if(n)return n}setupEngine(e){var n;this.engine=e,this.engine.on(re.RemoteMute,(i,r)=>{const a=this.trackPublications.get(i);!a||!a.track||(r?a.mute():a.unmute())}),!((n=this.signalConnectedFuture)===null||n===void 0)&&n.isResolved&&(this.signalConnectedFuture=void 0),this.engine.on(re.Connected,this.handleReconnected).on(re.SignalConnected,this.handleSignalConnected).on(re.SignalRestarted,this.handleReconnected).on(re.SignalResumed,this.handleReconnected).on(re.Restarting,this.handleReconnecting).on(re.Resuming,this.handleReconnecting).on(re.LocalTrackUnpublished,this.handleLocalTrackUnpublished).on(re.SubscribedQualityUpdate,this.handleSubscribedQualityUpdate).on(re.Closing,this.handleClosing).on(re.SignalRequestResponse,this.handleSignalRequestResponse).on(re.DataPacketReceived,this.handleDataPacket)}setMetadata(e){return E(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({metadata:e})})}setName(e){return E(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({name:e})})}setAttributes(e){return E(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({attributes:e})})}requestMetadataUpdate(e){return E(this,arguments,void 0,function(n){var i=this;let{metadata:r,name:a,attributes:o}=n;return function*(){return new Promise((s,l)=>E(i,void 0,void 0,function*(){var c,u;try{let d=!1;const h=yield this.engine.client.sendUpdateLocalMetadata((c=r??this.metadata)!==null&&c!==void 0?c:"",(u=a??this.name)!==null&&u!==void 0?u:"",o),p=performance.now();for(this.pendingSignalRequests.set(h,{resolve:s,reject:b=>{l(b),d=!0},values:{name:a,metadata:r,attributes:o}});performance.now()-p<5e3&&!d;){if((!a||this.name===a)&&(!r||this.metadata===r)&&(!o||Object.entries(o).every(b=>{let[m,S]=b;return this.attributes[m]===S||S===""&&!this.attributes[m]}))){this.pendingSignalRequests.delete(h),s();return}yield _n(50)}l(new rS("Request to update local metadata timed out","TimeoutError"))}catch(d){d instanceof Error&&l(d)}}))}()})}setCameraEnabled(e,n,i){return this.setTrackEnabled(V.Source.Camera,e,n,i)}setMicrophoneEnabled(e,n,i){return this.setTrackEnabled(V.Source.Microphone,e,n,i)}setScreenShareEnabled(e,n,i){return this.setTrackEnabled(V.Source.ScreenShare,e,n,i)}setE2EEEnabled(e){return E(this,void 0,void 0,function*(){this.encryptionType=e?$t.GCM:$t.NONE,yield this.republishAllTracks(void 0,!1)})}setTrackEnabled(e,n,i,r){return E(this,void 0,void 0,function*(){var a,o;this.log.debug("setTrackEnabled",Object.assign(Object.assign({},this.logContext),{source:e,enabled:n})),this.republishPromise&&(yield this.republishPromise);let s=this.getTrackPublication(e);if(n)if(s)yield s.unmute();else{let l;if(this.pendingPublishing.has(e)){const c=yield this.waitForPendingPublicationOfSource(e);return c||this.log.info("waiting for pending publication promise timed out",Object.assign(Object.assign({},this.logContext),{source:e})),yield c==null?void 0:c.unmute(),c}this.pendingPublishing.add(e);try{switch(e){case V.Source.Camera:l=yield this.createTracks({video:(a=i)!==null&&a!==void 0?a:!0});break;case V.Source.Microphone:l=yield this.createTracks({audio:(o=i)!==null&&o!==void 0?o:!0});break;case V.Source.ScreenShare:l=yield this.createScreenTracks(Object.assign({},i));break;default:throw new Jr(e)}}catch(c){throw l==null||l.forEach(u=>{u.stop()}),c instanceof Error&&this.emit(se.MediaDevicesError,c,Gm(e)),this.pendingPublishing.delete(e),c}for(const c of l){const u=Object.assign(Object.assign({},this.roomOptions.publishDefaults),i);e===V.Source.Microphone&&Mr(c)&&u.preConnectBuffer&&(this.log.info("starting preconnect buffer for microphone",Object.assign({},this.logContext)),c.startPreConnectBuffer())}try{const c=[];for(const d of l)this.log.info("publishing track",Object.assign(Object.assign({},this.logContext),Be(d))),c.push(this.publishTrack(d,r));[s]=yield Promise.all(c)}catch(c){throw l==null||l.forEach(u=>{u.stop()}),c}finally{this.pendingPublishing.delete(e)}}else if(!(s!=null&&s.track)&&this.pendingPublishing.has(e)&&(s=yield this.waitForPendingPublicationOfSource(e),s||this.log.info("waiting for pending publication promise timed out",Object.assign(Object.assign({},this.logContext),{source:e}))),s&&s.track)if(e===V.Source.ScreenShare){s=yield this.unpublishTrack(s.track);const l=this.getTrackPublication(V.Source.ScreenShareAudio);l&&l.track&&this.unpublishTrack(l.track)}else yield s.mute();return s})}enableCameraAndMicrophone(){return E(this,void 0,void 0,function*(){if(!(this.pendingPublishing.has(V.Source.Camera)||this.pendingPublishing.has(V.Source.Microphone))){this.pendingPublishing.add(V.Source.Camera),this.pendingPublishing.add(V.Source.Microphone);try{const e=yield this.createTracks({audio:!0,video:!0});yield Promise.all(e.map(n=>this.publishTrack(n)))}finally{this.pendingPublishing.delete(V.Source.Camera),this.pendingPublishing.delete(V.Source.Microphone)}}})}createTracks(e){return E(this,void 0,void 0,function*(){var n,i;e??(e={});const r=oS(e,(n=this.roomOptions)===null||n===void 0?void 0:n.audioCaptureDefaults,(i=this.roomOptions)===null||i===void 0?void 0:i.videoCaptureDefaults);try{return(yield ph(r,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext})).map(s=>(Mr(s)&&(this.microphoneError=void 0,s.setAudioContext(this.audioContext),s.source=V.Source.Microphone,this.emit(se.AudioStreamAcquired)),Ua(s)&&(this.cameraError=void 0,s.source=V.Source.Camera),s))}catch(a){throw a instanceof Error&&(e.audio&&(this.microphoneError=a),e.video&&(this.cameraError=a)),a}})}createScreenTracks(e){return E(this,void 0,void 0,function*(){if(e===void 0&&(e={}),navigator.mediaDevices.getDisplayMedia===void 0)throw new Bm("getDisplayMedia not supported");e.resolution===void 0&&!M8()&&(e.resolution=qm.h1080fps30.resolution);const n=_8(e),i=yield navigator.mediaDevices.getDisplayMedia(n),r=i.getVideoTracks();if(r.length===0)throw new Jr("no video track found");const a=new fh(r[0],void 0,!1,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});a.source=V.Source.ScreenShare,e.contentHint&&(a.mediaStreamTrack.contentHint=e.contentHint);const o=[a];if(i.getAudioTracks().length>0){this.emit(se.AudioStreamAcquired);const s=new hh(i.getAudioTracks()[0],void 0,!1,this.audioContext,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});s.source=V.Source.ScreenShareAudio,o.push(s)}return o})}publishTrack(e,n){return E(this,void 0,void 0,function*(){return this.publishOrRepublishTrack(e,n)})}publishOrRepublishTrack(e,n){return E(this,arguments,void 0,function(i,r){var a=this;let o=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1;return function*(){var s,l,c,u;$r(i)&&i.setAudioContext(a.audioContext),yield(s=a.reconnectFuture)===null||s===void 0?void 0:s.promise,a.republishPromise&&!o&&(yield a.republishPromise),Is(i)&&a.pendingPublishPromises.has(i)&&(yield a.pendingPublishPromises.get(i));let d;if(i instanceof MediaStreamTrack)d=i.getConstraints();else{d=i.constraints;let g;switch(i.source){case V.Source.Microphone:g="audioinput";break;case V.Source.Camera:g="videoinput"}g&&a.activeDeviceMap.has(g)&&(d=Object.assign(Object.assign({},d),{deviceId:a.activeDeviceMap.get(g)}))}if(i instanceof MediaStreamTrack)switch(i.kind){case"audio":i=new hh(i,d,!0,a.audioContext,{loggerName:a.roomOptions.loggerName,loggerContextCb:()=>a.logContext});break;case"video":i=new fh(i,d,!0,{loggerName:a.roomOptions.loggerName,loggerContextCb:()=>a.logContext});break;default:throw new Jr("unsupported MediaStreamTrack kind ".concat(i.kind))}else i.updateLoggerOptions({loggerName:a.roomOptions.loggerName,loggerContextCb:()=>a.logContext});let h;if(a.trackPublications.forEach(g=>{g.track&&g.track===i&&(h=g)}),h)return a.log.warn("track has already been published, skipping",Object.assign(Object.assign({},a.logContext),Be(h))),h;const p=Object.assign(Object.assign({},a.roomOptions.publishDefaults),r),b="channelCount"in i.mediaStreamTrack.getSettings()&&i.mediaStreamTrack.getSettings().channelCount===2||i.mediaStreamTrack.getConstraints().channelCount===2,m=(l=p.forceStereo)!==null&&l!==void 0?l:b;m&&(p.dtx===void 0&&a.log.info("Opus DTX will be disabled for stereo tracks by default. Enable them explicitly to make it work.",Object.assign(Object.assign({},a.logContext),Be(i))),p.red===void 0&&a.log.info("Opus RED will be disabled for stereo tracks by default. Enable them explicitly to make it work."),(c=p.dtx)!==null&&c!==void 0||(p.dtx=!1),(u=p.red)!==null&&u!==void 0||(p.red=!1)),!P8()&&a.roomOptions.e2ee&&(a.log.info("End-to-end encryption is set up, simulcast publishing will be disabled on Safari versions and iOS browsers running iOS < v17.2",Object.assign({},a.logContext)),p.simulcast=!1),p.source&&(i.source=p.source);const S=new Promise((g,y)=>E(a,void 0,void 0,function*(){try{if(this.engine.client.currentState!==pt.CONNECTED){this.log.debug("deferring track publication until signal is connected",Object.assign(Object.assign({},this.logContext),{track:Be(i)}));let x=!1;const v=setTimeout(()=>{x=!0,i.stop(),y(new iS("publishing rejected as engine not connected within timeout",408))},15e3);if(yield this.waitUntilEngineConnected(),clearTimeout(v),x)return;const k=yield this.publish(i,p,m);g(k)}else try{const x=yield this.publish(i,p,m);g(x)}catch(x){y(x)}}catch(x){y(x)}}));a.pendingPublishPromises.set(i,S);try{return yield S}catch(g){throw g}finally{a.pendingPublishPromises.delete(i)}}()})}waitUntilEngineConnected(){return this.signalConnectedFuture||(this.signalConnectedFuture=new Li),this.signalConnectedFuture.promise}hasPermissionsToPublish(e){if(!this.permissions)return this.log.warn("no permissions present for publishing track",Object.assign(Object.assign({},this.logContext),Be(e))),!1;const{canPublish:n,canPublishSources:i}=this.permissions;return n&&(i.length===0||i.map(r=>T8(r)).includes(e.source))?!0:(this.log.warn("insufficient permissions to publish",Object.assign(Object.assign({},this.logContext),Be(e))),!1)}publish(e,n,i){return E(this,void 0,void 0,function*(){var r,a,o,s,l,c,u,d,h,p;if(!this.hasPermissionsToPublish(e))throw new iS("failed to publish track, insufficient permissions",403);Array.from(this.trackPublications.values()).find(A=>Is(e)&&A.source===e.source)&&e.source!==V.Source.Unknown&&this.log.info("publishing a second track with the same source: ".concat(e.source),Object.assign(Object.assign({},this.logContext),Be(e))),n.stopMicTrackOnMute&&Mr(e)&&(e.stopOnMute=!0),e.source===V.Source.ScreenShare&&Ho()&&(n.simulcast=!1),n.videoCodec==="av1"&&!A8()&&(n.videoCodec=void 0),n.videoCodec==="vp9"&&!N8()&&(n.videoCodec=void 0),n.videoCodec===void 0&&(n.videoCodec=ug),this.enabledPublishVideoCodecs.length>0&&(this.enabledPublishVideoCodecs.some(A=>n.videoCodec===hc(A.mime))||(n.videoCodec=hc(this.enabledPublishVideoCodecs[0].mime)));const m=n.videoCodec;e.on(ne.Muted,this.onTrackMuted),e.on(ne.Unmuted,this.onTrackUnmuted),e.on(ne.Ended,this.handleTrackEnded),e.on(ne.UpstreamPaused,this.onTrackUpstreamPaused),e.on(ne.UpstreamResumed,this.onTrackUpstreamResumed),e.on(ne.AudioTrackFeatureUpdate,this.onTrackFeatureUpdate);const S=[],g=!(!((r=n.dtx)!==null&&r!==void 0)||r),y=e.getSourceTrackSettings();y.autoGainControl&&S.push(an.TF_AUTO_GAIN_CONTROL),y.echoCancellation&&S.push(an.TF_ECHO_CANCELLATION),y.noiseSuppression&&S.push(an.TF_NOISE_SUPPRESSION),y.channelCount&&y.channelCount>1&&S.push(an.TF_STEREO),g&&S.push(an.TF_NO_DTX),$r(e)&&e.hasPreConnectBuffer&&S.push(an.TF_PRECONNECT_BUFFER);const x=new lc({cid:e.mediaStreamTrack.id,name:n.name,type:V.kindToProto(e.kind),muted:e.isMuted,source:V.sourceToProto(e.source),disableDtx:g,encryption:this.encryptionType,stereo:i,disableRed:this.isE2EEEnabled||!(!((a=n.red)!==null&&a!==void 0)||a),stream:n==null?void 0:n.stream,backupCodecPolicy:n==null?void 0:n.backupCodecPolicy,audioFeatures:S});let v;if(e.kind===V.Kind.Video){let A={width:0,height:0};try{A=yield e.waitForDimensions()}catch{const O=(s=(o=this.roomOptions.videoCaptureDefaults)===null||o===void 0?void 0:o.resolution)!==null&&s!==void 0?s:dc.h720.resolution;A={width:O.width,height:O.height},this.log.error("could not determine track dimensions, using defaults",Object.assign(Object.assign(Object.assign({},this.logContext),Be(e)),{dims:A}))}x.width=A.width,x.height=A.height,za(e)&&(ar(m)&&(e.source===V.Source.ScreenShare&&(n.scalabilityMode="L1T3","contentHint"in e.mediaStreamTrack&&(e.mediaStreamTrack.contentHint="motion",this.log.info("forcing contentHint to motion for screenshare with SVC codecs",Object.assign(Object.assign({},this.logContext),Be(e))))),n.scalabilityMode=(l=n.scalabilityMode)!==null&&l!==void 0?l:"L3T3_KEY"),x.simulcastCodecs=[new _m({codec:m,cid:e.mediaStreamTrack.id})],n.backupCodec===!0&&(n.backupCodec={codec:ug}),n.backupCodec&&m!==n.backupCodec.codec&&x.encryption===$t.NONE&&(this.roomOptions.dynacast||(this.roomOptions.dynacast=!0),x.simulcastCodecs.push(new _m({codec:n.backupCodec.codec,cid:""})))),v=gg(e.source===V.Source.ScreenShare,x.width,x.height,n),x.layers=YS(x.width,x.height,v,ar(n.videoCodec))}else e.kind===V.Kind.Audio&&(v=[{maxBitrate:(c=n.audioPreset)===null||c===void 0?void 0:c.maxBitrate,priority:(d=(u=n.audioPreset)===null||u===void 0?void 0:u.priority)!==null&&d!==void 0?d:"high",networkPriority:(p=(h=n.audioPreset)===null||h===void 0?void 0:h.priority)!==null&&p!==void 0?p:"high"}]);if(!this.engine||this.engine.isClosed)throw new Qt("cannot publish track when not connected");const k=()=>E(this,void 0,void 0,function*(){var A,N,O;if(!this.engine.pcManager)throw new Qt("pcManager is not ready");if(e.sender=yield this.engine.createSender(e,n,v),this.emit(se.LocalSenderCreated,e.sender,e),za(e)&&((A=n.degradationPreference)!==null&&A!==void 0||(n.degradationPreference=BD(e)),e.setDegradationPreference(n.degradationPreference)),v)if(Ho()&&e.kind===V.Kind.Audio){let z;for(const Y of this.engine.pcManager.publisher.getTransceivers())if(Y.sender===e.sender){z=Y;break}z&&this.engine.pcManager.publisher.setTrackCodecBitrate({transceiver:z,codec:"opus",maxbr:!((N=v[0])===null||N===void 0)&&N.maxBitrate?v[0].maxBitrate/1e3:0})}else e.codec&&ar(e.codec)&&(!((O=v[0])===null||O===void 0)&&O.maxBitrate)&&this.engine.pcManager.publisher.setTrackCodecBitrate({cid:x.cid,codec:e.codec,maxbr:v[0].maxBitrate/1e3});yield this.engine.negotiate()});let T;const C=new Promise((A,N)=>E(this,void 0,void 0,function*(){var O;try{T=yield this.engine.addTrack(x),A(T)}catch(z){e.sender&&(!((O=this.engine.pcManager)===null||O===void 0)&&O.publisher)&&(this.engine.pcManager.publisher.removeTrack(e.sender),yield this.engine.negotiate().catch(Y=>{this.log.error("failed to negotiate after removing track due to failed add track request",Object.assign(Object.assign(Object.assign({},this.logContext),Be(e)),{error:Y}))})),N(z)}}));if(this.enabledPublishVideoCodecs.length>0)T=(yield Promise.all([C,k()]))[0];else{T=yield C;let A;if(T.codecs.forEach(N=>{A===void 0&&(A=N.mimeType)}),A&&e.kind===V.Kind.Video){const N=hc(A);N!==m&&(this.log.debug("falling back to server selected codec",Object.assign(Object.assign(Object.assign({},this.logContext),Be(e)),{codec:N})),n.videoCodec=N,v=gg(e.source===V.Source.ScreenShare,x.width,x.height,n))}yield k()}const R=new xg(e.kind,T,e,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});if(R.on(ne.CpuConstrained,A=>this.onTrackCpuConstrained(A,R)),R.options=n,e.sid=T.sid,this.log.debug("publishing ".concat(e.kind," with encodings"),Object.assign(Object.assign({},this.logContext),{encodings:v,trackInfo:T})),za(e)?e.startMonitor(this.engine.client):$r(e)&&e.startMonitor(),this.addTrackPublication(R),this.emit(se.LocalTrackPublished,R),$r(e)&&T.audioFeatures.includes(an.TF_PRECONNECT_BUFFER)){const A=e.getPreConnectBuffer(),N=e.getPreConnectBufferMimeType();this.on(se.LocalTrackSubscribed,O=>{if(O.trackSid===T.sid){if(!e.hasPreConnectBuffer){this.log.warn("subscribe event came to late, buffer already closed",this.logContext);return}this.log.debug("finished recording preconnect buffer",Object.assign(Object.assign({},this.logContext),Be(e))),e.stopPreConnectBuffer()}}),A&&new Promise((z,Y)=>E(this,void 0,void 0,function*(){var L,X,P,G,J,te;try{this.log.debug("waiting for agent",Object.assign(Object.assign({},this.logContext),Be(e)));const $=setTimeout(()=>{Y(new Error("agent not active within 10 seconds"))},1e4),ue=yield this.waitUntilActiveAgentPresent();clearTimeout($),this.log.debug("sending preconnect buffer",Object.assign(Object.assign({},this.logContext),Be(e)));const B=yield this.streamBytes({name:"preconnect-buffer",mimeType:N,topic:"lk.agent.pre-connect-audio-buffer",destinationIdentities:[ue.identity],attributes:{trackId:R.trackSid,sampleRate:String((J=y.sampleRate)!==null&&J!==void 0?J:"48000"),channels:String((te=y.channelCount)!==null&&te!==void 0?te:"1")}});try{for(var Z=!0,q=Xr(A),ee;ee=yield q.next(),L=ee.done,!L;Z=!0){G=ee.value,Z=!1;const ve=G;yield B.write(ve)}}catch(ve){X={error:ve}}finally{try{!Z&&!L&&(P=q.return)&&(yield P.call(q))}finally{if(X)throw X.error}}yield B.close(),z()}catch($){Y($)}})).then(()=>{this.log.debug("preconnect buffer sent successfully",Object.assign(Object.assign({},this.logContext),Be(e)))}).catch(z=>{this.log.error("error sending preconnect buffer",Object.assign(Object.assign(Object.assign({},this.logContext),Be(e)),{error:z}))})}return R})}get isLocal(){return!0}publishAdditionalCodecForTrack(e,n,i){return E(this,void 0,void 0,function*(){var r;if(this.encryptionType!==$t.NONE)return;let a;if(this.trackPublications.forEach(p=>{p.track&&p.track===e&&(a=p)}),!a)throw new Jr("track is not published");if(!za(e))throw new Jr("track is not a video track");const o=Object.assign(Object.assign({},(r=this.roomOptions)===null||r===void 0?void 0:r.publishDefaults),i),s=LD(e,n,o);if(!s){this.log.info("backup codec has been disabled, ignoring request to add additional codec for track",Object.assign(Object.assign({},this.logContext),Be(e)));return}const l=e.addSimulcastTrack(n,s);if(!l)return;const c=new lc({cid:l.mediaStreamTrack.id,type:V.kindToProto(e.kind),muted:e.isMuted,source:V.sourceToProto(e.source),sid:e.sid,simulcastCodecs:[{codec:o.videoCodec,cid:l.mediaStreamTrack.id}]});if(c.layers=YS(c.width,c.height,s),!this.engine||this.engine.isClosed)throw new Qt("cannot publish track when not connected");const u=()=>E(this,void 0,void 0,function*(){yield this.engine.createSimulcastSender(e,l,o,s),yield this.engine.negotiate()}),h=(yield Promise.all([this.engine.addTrack(c),u()]))[0];this.log.debug("published ".concat(n," for track ").concat(e.sid),Object.assign(Object.assign({},this.logContext),{encodings:s,trackInfo:h}))})}unpublishTrack(e,n){return E(this,void 0,void 0,function*(){var i,r;if(Is(e)){const c=this.pendingPublishPromises.get(e);c&&(this.log.info("awaiting publish promise before attempting to unpublish",Object.assign(Object.assign({},this.logContext),Be(e))),yield c)}const a=this.getPublicationForTrack(e),o=a?Be(a):void 0;if(this.log.debug("unpublishing track",Object.assign(Object.assign({},this.logContext),o)),!a||!a.track){this.log.warn("track was not unpublished because no publication was found",Object.assign(Object.assign({},this.logContext),o));return}e=a.track,e.off(ne.Muted,this.onTrackMuted),e.off(ne.Unmuted,this.onTrackUnmuted),e.off(ne.Ended,this.handleTrackEnded),e.off(ne.UpstreamPaused,this.onTrackUpstreamPaused),e.off(ne.UpstreamResumed,this.onTrackUpstreamResumed),e.off(ne.AudioTrackFeatureUpdate,this.onTrackFeatureUpdate),n===void 0&&(n=(r=(i=this.roomOptions)===null||i===void 0?void 0:i.stopLocalTrackOnUnpublish)!==null&&r!==void 0?r:!0),n?e.stop():e.stopMonitor();let s=!1;const l=e.sender;if(e.sender=void 0,this.engine.pcManager&&this.engine.pcManager.currentState<Mt.FAILED&&l)try{for(const c of this.engine.pcManager.publisher.getTransceivers())c.sender===l&&(c.direction="inactive",s=!0);if(this.engine.removeTrack(l)&&(s=!0),za(e)){for(const[,c]of e.simulcastCodecs)c.sender&&(this.engine.removeTrack(c.sender)&&(s=!0),c.sender=void 0);e.simulcastCodecs.clear()}}catch(c){this.log.warn("failed to unpublish track",Object.assign(Object.assign(Object.assign({},this.logContext),o),{error:c}))}switch(this.trackPublications.delete(a.trackSid),a.kind){case V.Kind.Audio:this.audioTrackPublications.delete(a.trackSid);break;case V.Kind.Video:this.videoTrackPublications.delete(a.trackSid);break}return this.emit(se.LocalTrackUnpublished,a),a.setTrack(void 0),s&&(yield this.engine.negotiate()),a})}unpublishTracks(e){return E(this,void 0,void 0,function*(){return(yield Promise.all(e.map(i=>this.unpublishTrack(i)))).filter(i=>!!i)})}republishAllTracks(e){return E(this,arguments,void 0,function(n){var i=this;let r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return function*(){i.republishPromise&&(yield i.republishPromise),i.republishPromise=new Promise((a,o)=>E(i,void 0,void 0,function*(){try{const s=[];this.trackPublications.forEach(l=>{l.track&&(n&&(l.options=Object.assign(Object.assign({},l.options),n)),s.push(l))}),yield Promise.all(s.map(l=>E(this,void 0,void 0,function*(){const c=l.track;yield this.unpublishTrack(c,!1),r&&!c.isMuted&&c.source!==V.Source.ScreenShare&&c.source!==V.Source.ScreenShareAudio&&($r(c)||za(c))&&!c.isUserProvided&&(this.log.debug("restarting existing track",Object.assign(Object.assign({},this.logContext),{track:l.trackSid})),yield c.restartTrack()),yield this.publishOrRepublishTrack(c,l.options,!0)}))),a()}catch(s){o(s)}finally{this.republishPromise=void 0}})),yield i.republishPromise}()})}publishData(e){return E(this,arguments,void 0,function(n){var i=this;let r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};return function*(){const a=r.reliable?Me.RELIABLE:Me.LOSSY,o=r.destinationIdentities,s=r.topic;let l=new pm({participantIdentity:i.identity,payload:n,destinationIdentities:o,topic:s});const c=new jn({kind:a,value:{case:"user",value:l}});yield i.engine.sendDataPacket(c,a)}()})}publishDtmf(e,n){return E(this,void 0,void 0,function*(){const i=new jn({kind:Me.RELIABLE,value:{case:"sipDtmf",value:new W_({code:e,digit:n})}});yield this.engine.sendDataPacket(i,Me.RELIABLE)})}sendChatMessage(e,n){return E(this,void 0,void 0,function*(){const i={id:crypto.randomUUID(),message:e,timestamp:Date.now(),attachedFiles:n==null?void 0:n.attachments},r=new jn({value:{case:"chatMessage",value:new Wd(Object.assign(Object.assign({},i),{timestamp:Et.parse(i.timestamp)}))}});return yield this.engine.sendDataPacket(r,Me.RELIABLE),this.emit(se.ChatMessage,i),i})}editChatMessage(e,n){return E(this,void 0,void 0,function*(){const i=Object.assign(Object.assign({},n),{message:e,editTimestamp:Date.now()}),r=new jn({value:{case:"chatMessage",value:new Wd(Object.assign(Object.assign({},i),{timestamp:Et.parse(i.timestamp),editTimestamp:Et.parse(i.editTimestamp)}))}});return yield this.engine.sendDataPacket(r,Me.RELIABLE),this.emit(se.ChatMessage,i),i})}sendText(e,n){return E(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.sendText(e,n)})}streamText(e){return E(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.streamText(e)})}sendFile(e,n){return E(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.sendFile(e,n)})}streamBytes(e){return E(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.streamBytes(e)})}performRpc(e){return E(this,arguments,void 0,function(n){var i=this;let{destinationIdentity:r,method:a,payload:o,responseTimeout:s=15e3}=n;return function*(){return new Promise((u,d)=>E(i,void 0,void 0,function*(){var h,p,b,m;if(hg(o)>US){d(Dt.builtIn("REQUEST_PAYLOAD_TOO_LARGE"));return}if(!((p=(h=this.engine.latestJoinResponse)===null||h===void 0?void 0:h.serverInfo)===null||p===void 0)&&p.version&&Or((m=(b=this.engine.latestJoinResponse)===null||b===void 0?void 0:b.serverInfo)===null||m===void 0?void 0:m.version,"1.8.0")<0){d(Dt.builtIn("UNSUPPORTED_SERVER"));return}const S=Math.max(s,8e3),g=crypto.randomUUID();yield this.publishRpcRequest(r,g,a,o,S);const y=setTimeout(()=>{this.pendingAcks.delete(g),d(Dt.builtIn("CONNECTION_TIMEOUT")),this.pendingResponses.delete(g),clearTimeout(x)},7e3);this.pendingAcks.set(g,{resolve:()=>{clearTimeout(y)},participantIdentity:r});const x=setTimeout(()=>{this.pendingResponses.delete(g),d(Dt.builtIn("RESPONSE_TIMEOUT"))},s);this.pendingResponses.set(g,{resolve:(v,k)=>{clearTimeout(x),this.pendingAcks.has(g)&&(this.log.warn("RPC response received before ack",g),this.pendingAcks.delete(g),clearTimeout(y)),k?d(k):u(v??"")},participantIdentity:r})}))}()})}registerRpcMethod(e,n){this.rpcHandlers.has(e)&&this.log.warn("you're overriding the RPC handler for method ".concat(e,", in the future this will throw an error")),this.rpcHandlers.set(e,n)}unregisterRpcMethod(e){this.rpcHandlers.delete(e)}setTrackSubscriptionPermissions(e){let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:[];this.participantTrackPermissions=n,this.allParticipantsAllowedToSubscribe=e,this.engine.client.isDisconnected||this.updateTrackSubscriptionPermissions()}handleIncomingRpcAck(e){const n=this.pendingAcks.get(e);n?(n.resolve(),this.pendingAcks.delete(e)):console.error("Ack received for unexpected RPC request",e)}handleIncomingRpcResponse(e,n,i){const r=this.pendingResponses.get(e);r?(r.resolve(n,i),this.pendingResponses.delete(e)):console.error("Response received for unexpected RPC request",e)}publishRpcRequest(e,n,i,r,a){return E(this,void 0,void 0,function*(){const o=new jn({destinationIdentities:[e],kind:Me.RELIABLE,value:{case:"rpcRequest",value:new mm({id:n,method:i,payload:r,responseTimeoutMs:a,version:1})}});yield this.engine.sendDataPacket(o,Me.RELIABLE)})}handleParticipantDisconnected(e){for(const[n,{participantIdentity:i}]of this.pendingAcks)i===e&&this.pendingAcks.delete(n);for(const[n,{participantIdentity:i,resolve:r}]of this.pendingResponses)i===e&&(r(null,Dt.builtIn("RECIPIENT_DISCONNECTED")),this.pendingResponses.delete(n))}setEnabledPublishCodecs(e){this.enabledPublishVideoCodecs=e.filter(n=>n.mime.split("/")[0].toLowerCase()==="video")}updateInfo(e){return super.updateInfo(e)?(e.tracks.forEach(n=>{var i,r;const a=this.trackPublications.get(n.sid);if(a){const o=a.isMuted||((r=(i=a.track)===null||i===void 0?void 0:i.isUpstreamPaused)!==null&&r!==void 0?r:!1);o!==n.muted&&(this.log.debug("updating server mute state after reconcile",Object.assign(Object.assign(Object.assign({},this.logContext),Be(a)),{mutedOnServer:o})),this.engine.client.sendMuteTrack(n.sid,o))}}),!0):!1}setActiveAgent(e){var n,i,r,a;this.firstActiveAgent=e,e&&!this.firstActiveAgent&&(this.firstActiveAgent=e),e?(i=(n=this.activeAgentFuture)===null||n===void 0?void 0:n.resolve)===null||i===void 0||i.call(n,e):(a=(r=this.activeAgentFuture)===null||r===void 0?void 0:r.reject)===null||a===void 0||a.call(r,new Error("Agent disconnected")),this.activeAgentFuture=void 0}waitUntilActiveAgentPresent(){return this.firstActiveAgent?Promise.resolve(this.firstActiveAgent):(this.activeAgentFuture||(this.activeAgentFuture=new Li),this.activeAgentFuture.promise)}getPublicationForTrack(e){let n;return this.trackPublications.forEach(i=>{const r=i.track;r&&(e instanceof MediaStreamTrack?($r(r)||za(r))&&r.mediaStreamTrack===e&&(n=i):e===r&&(n=i))}),n}waitForPendingPublicationOfSource(e){return E(this,void 0,void 0,function*(){const i=Date.now();for(;Date.now()<i+1e4;){const r=Array.from(this.pendingPublishPromises.entries()).find(a=>{let[o]=a;return o.source===e});if(r)return r[1];yield _n(20)}})}}class oP extends Qr{constructor(e,n,i,r){super(e,n.sid,n.name,r),this.track=void 0,this.allowed=!0,this.requestedDisabled=void 0,this.visible=!0,this.handleEnded=a=>{this.setTrack(void 0),this.emit(ne.Ended,a)},this.handleVisibilityChange=a=>{this.log.debug("adaptivestream video visibility ".concat(this.trackSid,", visible=").concat(a),this.logContext),this.visible=a,this.emitTrackUpdate()},this.handleVideoDimensionsChange=a=>{this.log.debug("adaptivestream video dimensions ".concat(a.width,"x").concat(a.height),this.logContext),this.videoDimensionsAdaptiveStream=a,this.emitTrackUpdate()},this.subscribed=i,this.updateInfo(n)}setSubscribed(e){const n=this.subscriptionStatus,i=this.permissionStatus;this.subscribed=e,e&&(this.allowed=!0);const r=new Qd({trackSids:[this.trackSid],subscribe:this.subscribed,participantTracks:[new K_({participantSid:"",trackSids:[this.trackSid]})]});this.emit(ne.UpdateSubscription,r),this.emitSubscriptionUpdateIfChanged(n),this.emitPermissionUpdateIfChanged(i)}get subscriptionStatus(){return this.subscribed===!1?Qr.SubscriptionStatus.Unsubscribed:super.isSubscribed?Qr.SubscriptionStatus.Subscribed:Qr.SubscriptionStatus.Desired}get permissionStatus(){return this.allowed?Qr.PermissionStatus.Allowed:Qr.PermissionStatus.NotAllowed}get isSubscribed(){return this.subscribed===!1?!1:super.isSubscribed}get isDesired(){return this.subscribed!==!1}get isEnabled(){return this.requestedDisabled!==void 0?!this.requestedDisabled:this.isAdaptiveStream?this.visible:!0}get isLocal(){return!1}setEnabled(e){!this.isManualOperationAllowed()||this.requestedDisabled===!e||(this.requestedDisabled=!e,this.emitTrackUpdate())}setVideoQuality(e){!this.isManualOperationAllowed()||this.requestedMaxQuality===e||(this.requestedMaxQuality=e,this.requestedVideoDimensions=void 0,this.emitTrackUpdate())}setVideoDimensions(e){var n,i;this.isManualOperationAllowed()&&(((n=this.requestedVideoDimensions)===null||n===void 0?void 0:n.width)===e.width&&((i=this.requestedVideoDimensions)===null||i===void 0?void 0:i.height)===e.height||(eg(this.track)&&(this.requestedVideoDimensions=e),this.requestedMaxQuality=void 0,this.emitTrackUpdate()))}setVideoFPS(e){this.isManualOperationAllowed()&&eg(this.track)&&this.fps!==e&&(this.fps=e,this.emitTrackUpdate())}get videoQuality(){var e;return(e=this.requestedMaxQuality)!==null&&e!==void 0?e:vi.HIGH}setTrack(e){const n=this.subscriptionStatus,i=this.permissionStatus,r=this.track;r!==e&&(r&&(r.off(ne.VideoDimensionsChanged,this.handleVideoDimensionsChange),r.off(ne.VisibilityChanged,this.handleVisibilityChange),r.off(ne.Ended,this.handleEnded),r.detach(),r.stopMonitor(),this.emit(ne.Unsubscribed,r)),super.setTrack(e),e&&(e.sid=this.trackSid,e.on(ne.VideoDimensionsChanged,this.handleVideoDimensionsChange),e.on(ne.VisibilityChanged,this.handleVisibilityChange),e.on(ne.Ended,this.handleEnded),this.emit(ne.Subscribed,e)),this.emitPermissionUpdateIfChanged(i),this.emitSubscriptionUpdateIfChanged(n))}setAllowed(e){const n=this.subscriptionStatus,i=this.permissionStatus;this.allowed=e,this.emitPermissionUpdateIfChanged(i),this.emitSubscriptionUpdateIfChanged(n)}setSubscriptionError(e){this.emit(ne.SubscriptionFailed,e)}updateInfo(e){super.updateInfo(e);const n=this.metadataMuted;this.metadataMuted=e.muted,this.track?this.track.setMuted(e.muted):n!==e.muted&&this.emit(e.muted?ne.Muted:ne.Unmuted)}emitSubscriptionUpdateIfChanged(e){const n=this.subscriptionStatus;e!==n&&this.emit(ne.SubscriptionStatusChanged,n,e)}emitPermissionUpdateIfChanged(e){this.permissionStatus!==e&&this.emit(ne.SubscriptionPermissionChanged,this.permissionStatus,e)}isManualOperationAllowed(){return this.isDesired?!0:(this.log.warn("cannot update track settings when not subscribed",this.logContext),!1)}get isAdaptiveStream(){return eg(this.track)&&this.track.isAdaptiveStream}emitTrackUpdate(){const e=new ax({trackSids:[this.trackSid],disabled:!this.isEnabled,fps:this.fps});if(this.kind===V.Kind.Video){let n=this.requestedVideoDimensions;if(this.videoDimensionsAdaptiveStream!==void 0)if(n)uS(this.videoDimensionsAdaptiveStream,n)&&(this.log.debug("using adaptive stream dimensions instead of requested",Object.assign(Object.assign({},this.logContext),this.videoDimensionsAdaptiveStream)),n=this.videoDimensionsAdaptiveStream);else if(this.requestedMaxQuality!==void 0&&this.trackInfo){const i=w8(this.trackInfo,this.requestedMaxQuality);i&&uS(this.videoDimensionsAdaptiveStream,i)&&(this.log.debug("using adaptive stream dimensions instead of max quality layer",Object.assign(Object.assign({},this.logContext),this.videoDimensionsAdaptiveStream)),n=this.videoDimensionsAdaptiveStream)}else this.log.debug("using adaptive stream dimensions",Object.assign(Object.assign({},this.logContext),this.videoDimensionsAdaptiveStream)),n=this.videoDimensionsAdaptiveStream;n?(e.width=Math.ceil(n.width),e.height=Math.ceil(n.height)):this.requestedMaxQuality!==void 0?(this.log.debug("using requested max quality",Object.assign(Object.assign({},this.logContext),{quality:this.requestedMaxQuality})),e.quality=this.requestedMaxQuality):(this.log.debug("using default quality",Object.assign(Object.assign({},this.logContext),{quality:vi.HIGH})),e.quality=vi.HIGH)}this.emit(ne.UpdateSettings,e)}}class mh extends tk{static fromParticipantInfo(e,n,i){return new mh(e,n.sid,n.identity,n.name,n.metadata,n.attributes,i,n.kind)}get logContext(){return Object.assign(Object.assign({},super.logContext),{rpID:this.sid,remoteParticipant:this.identity})}constructor(e,n,i,r,a,o,s){let l=arguments.length>7&&arguments[7]!==void 0?arguments[7]:sc.STANDARD;super(n,i||"",r,a,o,s,l),this.signalClient=e,this.trackPublications=new Map,this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.volumeMap=new Map}addTrackPublication(e){super.addTrackPublication(e),e.on(ne.UpdateSettings,n=>{this.log.debug("send update settings",Object.assign(Object.assign(Object.assign({},this.logContext),Be(e)),{settings:n})),this.signalClient.sendUpdateTrackSettings(n)}),e.on(ne.UpdateSubscription,n=>{n.participantTracks.forEach(i=>{i.participantSid=this.sid}),this.signalClient.sendUpdateSubscription(n)}),e.on(ne.SubscriptionPermissionChanged,n=>{this.emit(se.TrackSubscriptionPermissionChanged,e,n)}),e.on(ne.SubscriptionStatusChanged,n=>{this.emit(se.TrackSubscriptionStatusChanged,e,n)}),e.on(ne.Subscribed,n=>{this.emit(se.TrackSubscribed,n,e)}),e.on(ne.Unsubscribed,n=>{this.emit(se.TrackUnsubscribed,n,e)}),e.on(ne.SubscriptionFailed,n=>{this.emit(se.TrackSubscriptionFailed,e.trackSid,n)})}getTrackPublication(e){const n=super.getTrackPublication(e);if(n)return n}getTrackPublicationByName(e){const n=super.getTrackPublicationByName(e);if(n)return n}setVolume(e){let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:V.Source.Microphone;this.volumeMap.set(n,e);const i=this.getTrackPublication(n);i&&i.track&&i.track.setVolume(e)}getVolume(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:V.Source.Microphone;const n=this.getTrackPublication(e);return n&&n.track?n.track.getVolume():this.volumeMap.get(e)}addSubscribedMediaTrack(e,n,i,r,a,o){let s=this.getTrackPublicationBySid(n);if(s||n.startsWith("TR")||this.trackPublications.forEach(u=>{!s&&e.kind===u.kind.toString()&&(s=u)}),!s){if(o===0){this.log.error("could not find published track",Object.assign(Object.assign({},this.logContext),{trackSid:n})),this.emit(se.TrackSubscriptionFailed,n);return}o===void 0&&(o=20),setTimeout(()=>{this.addSubscribedMediaTrack(e,n,i,r,a,o-1)},150);return}if(e.readyState==="ended"){this.log.error("unable to subscribe because MediaStreamTrack is ended. Do not call MediaStreamTrack.stop()",Object.assign(Object.assign({},this.logContext),Be(s))),this.emit(se.TrackSubscriptionFailed,n);return}const l=e.kind==="video";let c;return l?c=new ZD(e,n,r,a):c=new QD(e,n,r,this.audioContext,this.audioOutput),c.source=s.source,c.isMuted=s.isMuted,c.setMediaStream(i),c.start(),s.setTrack(c),this.volumeMap.has(s.source)&&Zm(c)&&Mr(c)&&c.setVolume(this.volumeMap.get(s.source)),s}get hasMetadata(){return!!this.participantInfo}getTrackPublicationBySid(e){return this.trackPublications.get(e)}updateInfo(e){if(!super.updateInfo(e))return!1;const n=new Map,i=new Map;return e.tracks.forEach(r=>{var a,o;let s=this.getTrackPublicationBySid(r.sid);if(s)s.updateInfo(r);else{const l=V.kindFromProto(r.type);if(!l)return;s=new oP(l,r,(a=this.signalClient.connectOptions)===null||a===void 0?void 0:a.autoSubscribe,{loggerContextCb:()=>this.logContext,loggerName:(o=this.loggerOptions)===null||o===void 0?void 0:o.loggerName}),s.updateInfo(r),i.set(r.sid,s);const c=Array.from(this.trackPublications.values()).find(u=>u.source===(s==null?void 0:s.source));c&&s.source!==V.Source.Unknown&&this.log.debug("received a second track publication for ".concat(this.identity," with the same source: ").concat(s.source),Object.assign(Object.assign({},this.logContext),{oldTrack:Be(c),newTrack:Be(s)})),this.addTrackPublication(s)}n.set(r.sid,s)}),this.trackPublications.forEach(r=>{n.has(r.trackSid)||(this.log.trace("detected removed track on remote participant, unpublishing",Object.assign(Object.assign({},this.logContext),Be(r))),this.unpublishTrack(r.trackSid,!0))}),i.forEach(r=>{this.emit(se.TrackPublished,r)}),!0}unpublishTrack(e,n){const i=this.trackPublications.get(e);if(!i)return;const{track:r}=i;switch(r&&(r.stop(),i.setTrack(void 0)),this.trackPublications.delete(e),i.kind){case V.Kind.Audio:this.audioTrackPublications.delete(e);break;case V.Kind.Video:this.videoTrackPublications.delete(e);break}n&&this.emit(se.TrackUnpublished,i)}setAudioOutput(e){return E(this,void 0,void 0,function*(){this.audioOutput=e;const n=[];this.audioTrackPublications.forEach(i=>{var r;Mr(i.track)&&Zm(i.track)&&n.push(i.track.setSinkId((r=e.deviceId)!==null&&r!==void 0?r:"default"))}),yield Promise.all(n)})}emit(e){for(var n=arguments.length,i=new Array(n>1?n-1:0),r=1;r<n;r++)i[r-1]=arguments[r];return this.log.trace("participant event",Object.assign(Object.assign({},this.logContext),{event:e,args:i})),super.emit(e,...i)}}var Xe;(function(t){t.Disconnected="disconnected",t.Connecting="connecting",t.Connected="connected",t.Reconnecting="reconnecting",t.SignalReconnecting="signalReconnecting"})(Xe||(Xe={}));const sP=4*1e3;class zs extends Rr.EventEmitter{get hasE2EESetup(){return this.e2eeManager!==void 0}constructor(e){var n,i,r,a;if(super(),n=this,this.state=Xe.Disconnected,this.activeSpeakers=[],this.isE2EEEnabled=!1,this.audioEnabled=!0,this.isVideoPlaybackBlocked=!1,this.log=Re,this.bufferedEvents=[],this.isResuming=!1,this.rpcHandlers=new Map,this.connect=(o,s,l)=>E(this,void 0,void 0,function*(){var c;if(!O8())throw Nr()?Error("WebRTC isn't detected, have you called registerGlobals?"):Error("LiveKit doesn't seem to be supported on this browser. Try to update your browser and make sure no browser extensions are disabling webRTC.");const u=yield this.disconnectLock.lock();if(this.state===Xe.Connected)return this.log.info("already connected to room ".concat(this.name),this.logContext),u(),Promise.resolve();if(this.connectFuture)return u(),this.connectFuture.promise;this.setAndEmitConnectionState(Xe.Connecting),((c=this.regionUrlProvider)===null||c===void 0?void 0:c.getServerUrl().toString())!==xS(o)&&(this.regionUrl=void 0,this.regionUrlProvider=void 0),Ls(new URL(o))&&(this.regionUrlProvider===void 0?this.regionUrlProvider=new Ke(o,s):this.regionUrlProvider.updateToken(s),this.regionUrlProvider.fetchRegionSettings().then(p=>{var b;(b=this.regionUrlProvider)===null||b===void 0||b.setServerReportedRegions(p)}).catch(p=>{this.log.warn("could not fetch region settings",Object.assign(Object.assign({},this.logContext),{error:p}))}));const d=(p,b,m)=>E(this,void 0,void 0,function*(){var S,g;this.abortController&&this.abortController.abort();const y=new AbortController;this.abortController=y,u==null||u();try{if(yield js.getInstance().getBackOffPromise(o),y.signal.aborted)throw xe.cancelled("Connection attempt aborted");yield this.attemptConnection(m??o,s,l,y),this.abortController=void 0,p()}catch(x){if(this.regionUrlProvider&&x instanceof xe&&x.reason!==xt.Cancelled&&x.reason!==xt.NotAllowed){let v=null;try{this.log.debug("Fetching next region"),v=yield this.regionUrlProvider.getNextBestRegionUrl((S=this.abortController)===null||S===void 0?void 0:S.signal)}catch(k){if(k instanceof xe&&(k.status===401||k.reason===xt.Cancelled)){this.handleDisconnect(this.options.stopLocalTrackOnUnpublish),b(k);return}}[xt.InternalError,xt.ServerUnreachable,xt.Timeout].includes(x.reason)&&(this.log.debug("Adding failed connection attempt to back off"),js.getInstance().addFailedConnectionAttempt(o)),v&&!(!((g=this.abortController)===null||g===void 0)&&g.signal.aborted)?(this.log.info("Initial connection failed with ConnectionError: ".concat(x.message,". Retrying with another region: ").concat(v),this.logContext),this.recreateEngine(),yield d(p,b,v)):(this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,_S(x)),b(x))}else{let v=nr.UNKNOWN_REASON;x instanceof xe&&(v=_S(x)),this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,v),b(x)}}}),h=this.regionUrl;return this.regionUrl=void 0,this.connectFuture=new Li((p,b)=>{d(p,b,h)},()=>{this.clearConnectionFutures()}),this.connectFuture.promise}),this.connectSignal=(o,s,l,c,u,d)=>E(this,void 0,void 0,function*(){var h,p,b;const m=yield l.join(o,s,{autoSubscribe:c.autoSubscribe,adaptiveStream:typeof u.adaptiveStream=="object"?!0:u.adaptiveStream,maxRetries:c.maxRetries,e2eeEnabled:!!this.e2eeManager,websocketTimeout:c.websocketTimeout,singlePeerConnection:u.singlePeerConnection},d.signal);let S=m.serverInfo;if(S||(S={version:m.serverVersion,region:m.serverRegion}),this.serverInfo=S,this.log.debug("connected to Livekit Server ".concat(Object.entries(S).map(g=>{let[y,x]=g;return"".concat(y,": ").concat(x)}).join(", ")),{room:(h=m.room)===null||h===void 0?void 0:h.name,roomSid:(p=m.room)===null||p===void 0?void 0:p.sid,identity:(b=m.participant)===null||b===void 0?void 0:b.identity}),!S.version)throw new f8("unknown server version");return S.version==="0.15.1"&&this.options.dynacast&&(this.log.debug("disabling dynacast due to server version",this.logContext),u.dynacast=!1),m}),this.applyJoinResponse=o=>{const s=o.participant;if(this.localParticipant.sid=s.sid,this.localParticipant.identity=s.identity,this.localParticipant.setEnabledPublishCodecs(o.enabledPublishCodecs),this.e2eeManager)try{this.e2eeManager.setSifTrailer(o.sifTrailer)}catch(l){this.log.error(l instanceof Error?l.message:"Could not set SifTrailer",Object.assign(Object.assign({},this.logContext),{error:l}))}this.handleParticipantUpdates([s,...o.otherParticipants]),o.room&&this.handleRoomUpdate(o.room)},this.attemptConnection=(o,s,l,c)=>E(this,void 0,void 0,function*(){var u,d;this.state===Xe.Reconnecting||this.isResuming||!((u=this.engine)===null||u===void 0)&&u.pendingReconnect?(this.log.info("Reconnection attempt replaced by new connection attempt",this.logContext),this.recreateEngine()):this.maybeCreateEngine(),!((d=this.regionUrlProvider)===null||d===void 0)&&d.isCloud()&&this.engine.setRegionUrlProvider(this.regionUrlProvider),this.acquireAudioContext(),this.connOptions=Object.assign(Object.assign({},dg),l),this.connOptions.rtcConfig&&(this.engine.rtcConfig=this.connOptions.rtcConfig),this.connOptions.peerConnectionTimeout&&(this.engine.peerConnectionTimeout=this.connOptions.peerConnectionTimeout);try{const h=yield this.connectSignal(o,s,this.engine,this.connOptions,this.options,c);this.applyJoinResponse(h),this.setupLocalParticipantEvents(),this.emit(Q.SignalConnected)}catch(h){yield this.engine.close(),this.recreateEngine();const p=c.signal.aborted?xe.cancelled("Signal connection aborted"):xe.serverUnreachable("could not establish signal connection");throw h instanceof Error&&(p.message="".concat(p.message,": ").concat(h.message)),h instanceof xe&&(p.reason=h.reason,p.status=h.status),this.log.debug("error trying to establish signal connection",Object.assign(Object.assign({},this.logContext),{error:h})),p}if(c.signal.aborted)throw yield this.engine.close(),this.recreateEngine(),xe.cancelled("Connection attempt aborted");try{yield this.engine.waitForPCInitialConnection(this.connOptions.peerConnectionTimeout,c)}catch(h){throw yield this.engine.close(),this.recreateEngine(),h}ri()&&this.options.disconnectOnPageLeave&&(window.addEventListener("pagehide",this.onPageLeave),window.addEventListener("beforeunload",this.onPageLeave)),ri()&&window.addEventListener("freeze",this.onPageLeave),this.setAndEmitConnectionState(Xe.Connected),this.emit(Q.Connected),js.getInstance().resetFailedConnectionAttempts(o),this.registerConnectionReconcile(),this.regionUrlProvider&&this.regionUrlProvider.notifyConnected()}),this.disconnect=function(){for(var o=arguments.length,s=new Array(o),l=0;l<o;l++)s[l]=arguments[l];return E(n,[...s],void 0,function(){var c=this;let u=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return function*(){var d,h,p;const b=yield c.disconnectLock.lock();try{if(c.state===Xe.Disconnected){c.log.debug("already disconnected",c.logContext);return}if(c.log.info("disconnect from room",Object.assign({},c.logContext)),c.state===Xe.Connecting||c.state===Xe.Reconnecting||c.isResuming){const m="Abort connection attempt due to user initiated disconnect";c.log.warn(m,c.logContext),(d=c.abortController)===null||d===void 0||d.abort(m),(p=(h=c.connectFuture)===null||h===void 0?void 0:h.reject)===null||p===void 0||p.call(h,xe.cancelled("Client initiated disconnect")),c.connectFuture=void 0}c.engine&&(c.engine.client.isDisconnected||(yield c.engine.client.sendLeave()),yield c.engine.close()),c.handleDisconnect(u,nr.CLIENT_INITIATED),c.engine=void 0}finally{b()}}()})},this.onPageLeave=()=>E(this,void 0,void 0,function*(){this.log.info("Page leave detected, disconnecting",this.logContext),yield this.disconnect()}),this.startAudio=()=>E(this,void 0,void 0,function*(){const o=[],s=ii();if(s&&s.os==="iOS"){const l="livekit-dummy-audio-el";let c=document.getElementById(l);if(!c){c=document.createElement("audio"),c.id=l,c.autoplay=!0,c.hidden=!0;const u=Qm();u.enabled=!0;const d=new MediaStream([u]);c.srcObject=d,document.addEventListener("visibilitychange",()=>{c&&(c.srcObject=document.hidden?null:d,document.hidden||(this.log.debug("page visible again, triggering startAudio to resume playback and update playback status",this.logContext),this.startAudio()))}),document.body.append(c),this.once(Q.Disconnected,()=>{c==null||c.remove(),c=null})}o.push(c)}this.remoteParticipants.forEach(l=>{l.audioTrackPublications.forEach(c=>{c.track&&c.track.attachedElements.forEach(u=>{o.push(u)})})});try{yield Promise.all([this.acquireAudioContext(),...o.map(l=>(l.muted=!1,l.play()))]),this.handleAudioPlaybackStarted()}catch(l){throw this.handleAudioPlaybackFailed(l),l}}),this.startVideo=()=>E(this,void 0,void 0,function*(){const o=[];for(const s of this.remoteParticipants.values())s.videoTrackPublications.forEach(l=>{var c;(c=l.track)===null||c===void 0||c.attachedElements.forEach(u=>{o.includes(u)||o.push(u)})});yield Promise.all(o.map(s=>s.play())).then(()=>{this.handleVideoPlaybackStarted()}).catch(s=>{s.name==="NotAllowedError"?this.handleVideoPlaybackFailed():this.log.warn("Resuming video playback failed, make sure you call `startVideo` directly in a user gesture handler",this.logContext)})}),this.handleRestarting=()=>{this.clearConnectionReconcile(),this.isResuming=!1;for(const o of this.remoteParticipants.values())this.handleParticipantDisconnected(o.identity,o);this.setAndEmitConnectionState(Xe.Reconnecting)&&this.emit(Q.Reconnecting)},this.handleSignalRestarted=o=>E(this,void 0,void 0,function*(){this.log.debug("signal reconnected to server, region ".concat(o.serverRegion),Object.assign(Object.assign({},this.logContext),{region:o.serverRegion})),this.bufferedEvents=[],this.applyJoinResponse(o);try{yield this.localParticipant.republishAllTracks(void 0,!0)}catch(s){this.log.error("error trying to re-publish tracks after reconnection",Object.assign(Object.assign({},this.logContext),{error:s}))}try{yield this.engine.waitForRestarted(),this.log.debug("fully reconnected to server",Object.assign(Object.assign({},this.logContext),{region:o.serverRegion}))}catch{return}this.setAndEmitConnectionState(Xe.Connected),this.emit(Q.Reconnected),this.registerConnectionReconcile(),this.emitBufferedEvents()}),this.handleParticipantUpdates=o=>{o.forEach(s=>{var l;if(s.identity===this.localParticipant.identity){this.localParticipant.updateInfo(s);return}s.identity===""&&(s.identity=(l=this.sidToIdentity.get(s.sid))!==null&&l!==void 0?l:"");let c=this.remoteParticipants.get(s.identity);s.state===Rs.DISCONNECTED?this.handleParticipantDisconnected(s.identity,c):c=this.getOrCreateParticipant(s.identity,s)})},this.handleActiveSpeakersUpdate=o=>{const s=[],l={};o.forEach(c=>{if(l[c.sid]=!0,c.sid===this.localParticipant.sid)this.localParticipant.audioLevel=c.level,this.localParticipant.setIsSpeaking(!0),s.push(this.localParticipant);else{const u=this.getRemoteParticipantBySid(c.sid);u&&(u.audioLevel=c.level,u.setIsSpeaking(!0),s.push(u))}}),l[this.localParticipant.sid]||(this.localParticipant.audioLevel=0,this.localParticipant.setIsSpeaking(!1)),this.remoteParticipants.forEach(c=>{l[c.sid]||(c.audioLevel=0,c.setIsSpeaking(!1))}),this.activeSpeakers=s,this.emitWhenConnected(Q.ActiveSpeakersChanged,s)},this.handleSpeakersChanged=o=>{const s=new Map;this.activeSpeakers.forEach(c=>{const u=this.remoteParticipants.get(c.identity);u&&u.sid!==c.sid||s.set(c.sid,c)}),o.forEach(c=>{let u=this.getRemoteParticipantBySid(c.sid);c.sid===this.localParticipant.sid&&(u=this.localParticipant),u&&(u.audioLevel=c.level,u.setIsSpeaking(c.active),c.active?s.set(c.sid,u):s.delete(c.sid))});const l=Array.from(s.values());l.sort((c,u)=>u.audioLevel-c.audioLevel),this.activeSpeakers=l,this.emitWhenConnected(Q.ActiveSpeakersChanged,l)},this.handleStreamStateUpdate=o=>{o.streamStates.forEach(s=>{const l=this.getRemoteParticipantBySid(s.participantSid);if(!l)return;const c=l.getTrackPublicationBySid(s.trackSid);if(!c||!c.track)return;const u=V.streamStateFromProto(s.state);c.track.setStreamState(u),u!==c.track.streamState&&(l.emit(se.TrackStreamStateChanged,c,c.track.streamState),this.emitWhenConnected(Q.TrackStreamStateChanged,c,c.track.streamState,l))})},this.handleSubscriptionPermissionUpdate=o=>{const s=this.getRemoteParticipantBySid(o.participantSid);if(!s)return;const l=s.getTrackPublicationBySid(o.trackSid);l&&l.setAllowed(o.allowed)},this.handleSubscriptionError=o=>{const s=Array.from(this.remoteParticipants.values()).find(c=>c.trackPublications.has(o.trackSid));if(!s)return;const l=s.getTrackPublicationBySid(o.trackSid);l&&l.setSubscriptionError(o.err)},this.handleDataPacket=(o,s)=>{const l=this.remoteParticipants.get(o.participantIdentity);if(o.value.case==="user")this.handleUserPacket(l,o.value.value,o.kind,s);else if(o.value.case==="transcription")this.handleTranscription(l,o.value.value);else if(o.value.case==="sipDtmf")this.handleSipDtmf(l,o.value.value);else if(o.value.case==="chatMessage")this.handleChatMessage(l,o.value.value);else if(o.value.case==="metrics")this.handleMetrics(o.value.value,l);else if(o.value.case==="streamHeader"||o.value.case==="streamChunk"||o.value.case==="streamTrailer")this.handleDataStream(o,s);else if(o.value.case==="rpcRequest"){const c=o.value.value;this.handleIncomingRpcRequest(o.participantIdentity,c.id,c.method,c.payload,c.responseTimeoutMs,c.version)}},this.handleUserPacket=(o,s,l,c)=>{this.emit(Q.DataReceived,s.payload,o,l,s.topic,c),o==null||o.emit(se.DataReceived,s.payload,l,c)},this.handleSipDtmf=(o,s)=>{this.emit(Q.SipDTMFReceived,s,o),o==null||o.emit(se.SipDTMFReceived,s)},this.handleTranscription=(o,s)=>{const l=s.transcribedParticipantIdentity===this.localParticipant.identity?this.localParticipant:this.getParticipantByIdentity(s.transcribedParticipantIdentity),c=l==null?void 0:l.trackPublications.get(s.trackId),u=z8(s,this.transcriptionReceivedTimes);c==null||c.emit(ne.TranscriptionReceived,u),l==null||l.emit(se.TranscriptionReceived,u,c),this.emit(Q.TranscriptionReceived,u,l,c)},this.handleChatMessage=(o,s)=>{const l=F8(s);this.emit(Q.ChatMessage,l,o)},this.handleMetrics=(o,s)=>{this.emit(Q.MetricsReceived,o,s)},this.handleDataStream=(o,s)=>{this.incomingDataStreamManager.handleDataStreamPacket(o,s)},this.bufferedSegments=new Map,this.handleAudioPlaybackStarted=()=>{this.canPlaybackAudio||(this.audioEnabled=!0,this.emit(Q.AudioPlaybackStatusChanged,!0))},this.handleAudioPlaybackFailed=o=>{this.log.warn("could not playback audio",Object.assign(Object.assign({},this.logContext),{error:o})),this.canPlaybackAudio&&(this.audioEnabled=!1,this.emit(Q.AudioPlaybackStatusChanged,!1))},this.handleVideoPlaybackStarted=()=>{this.isVideoPlaybackBlocked&&(this.isVideoPlaybackBlocked=!1,this.emit(Q.VideoPlaybackStatusChanged,!0))},this.handleVideoPlaybackFailed=()=>{this.isVideoPlaybackBlocked||(this.isVideoPlaybackBlocked=!0,this.emit(Q.VideoPlaybackStatusChanged,!1))},this.handleDeviceChange=()=>E(this,void 0,void 0,function*(){var o;((o=ii())===null||o===void 0?void 0:o.os)!=="iOS"&&(yield this.selectDefaultDevices()),this.emit(Q.MediaDevicesChanged)}),this.handleRoomUpdate=o=>{const s=this.roomInfo;this.roomInfo=o,s&&s.metadata!==o.metadata&&this.emitWhenConnected(Q.RoomMetadataChanged,o.metadata),(s==null?void 0:s.activeRecording)!==o.activeRecording&&this.emitWhenConnected(Q.RecordingStatusChanged,o.activeRecording)},this.handleConnectionQualityUpdate=o=>{o.updates.forEach(s=>{if(s.participantSid===this.localParticipant.sid){this.localParticipant.setConnectionQuality(s.quality);return}const l=this.getRemoteParticipantBySid(s.participantSid);l&&l.setConnectionQuality(s.quality)})},this.onLocalParticipantMetadataChanged=o=>{this.emit(Q.ParticipantMetadataChanged,o,this.localParticipant)},this.onLocalParticipantNameChanged=o=>{this.emit(Q.ParticipantNameChanged,o,this.localParticipant)},this.onLocalAttributesChanged=o=>{this.emit(Q.ParticipantAttributesChanged,o,this.localParticipant)},this.onLocalTrackMuted=o=>{this.emit(Q.TrackMuted,o,this.localParticipant)},this.onLocalTrackUnmuted=o=>{this.emit(Q.TrackUnmuted,o,this.localParticipant)},this.onTrackProcessorUpdate=o=>{var s;(s=o==null?void 0:o.onPublish)===null||s===void 0||s.call(o,this)},this.onLocalTrackPublished=o=>E(this,void 0,void 0,function*(){var s,l,c,u,d,h;(s=o.track)===null||s===void 0||s.on(ne.TrackProcessorUpdate,this.onTrackProcessorUpdate),(l=o.track)===null||l===void 0||l.on(ne.Restarted,this.onLocalTrackRestarted),(d=(u=(c=o.track)===null||c===void 0?void 0:c.getProcessor())===null||u===void 0?void 0:u.onPublish)===null||d===void 0||d.call(u,this),this.emit(Q.LocalTrackPublished,o,this.localParticipant),$r(o.track)&&(yield o.track.checkForSilence())&&this.emit(Q.LocalAudioSilenceDetected,o);const p=yield(h=o.track)===null||h===void 0?void 0:h.getDeviceId(!1),b=Gm(o.source);b&&p&&p!==this.localParticipant.activeDeviceMap.get(b)&&(this.localParticipant.activeDeviceMap.set(b,p),this.emit(Q.ActiveDeviceChanged,b,p))}),this.onLocalTrackUnpublished=o=>{var s,l;(s=o.track)===null||s===void 0||s.off(ne.TrackProcessorUpdate,this.onTrackProcessorUpdate),(l=o.track)===null||l===void 0||l.off(ne.Restarted,this.onLocalTrackRestarted),this.emit(Q.LocalTrackUnpublished,o,this.localParticipant)},this.onLocalTrackRestarted=o=>E(this,void 0,void 0,function*(){const s=yield o.getDeviceId(!1),l=Gm(o.source);l&&s&&s!==this.localParticipant.activeDeviceMap.get(l)&&(this.log.debug("local track restarted, setting ".concat(l," ").concat(s," active"),this.logContext),this.localParticipant.activeDeviceMap.set(l,s),this.emit(Q.ActiveDeviceChanged,l,s))}),this.onLocalConnectionQualityChanged=o=>{this.emit(Q.ConnectionQualityChanged,o,this.localParticipant)},this.onMediaDevicesError=(o,s)=>{this.emit(Q.MediaDevicesError,o,s)},this.onLocalParticipantPermissionsChanged=o=>{this.emit(Q.ParticipantPermissionsChanged,o,this.localParticipant)},this.onLocalChatMessageSent=o=>{this.emit(Q.ChatMessage,o,this.localParticipant)},this.setMaxListeners(100),this.remoteParticipants=new Map,this.sidToIdentity=new Map,this.options=Object.assign(Object.assign({},bD),e),this.log=Kr((i=this.options.loggerName)!==null&&i!==void 0?i:rr.Room),this.transcriptionReceivedTimes=new Map,this.options.audioCaptureDefaults=Object.assign(Object.assign({},IS),e==null?void 0:e.audioCaptureDefaults),this.options.videoCaptureDefaults=Object.assign(Object.assign({},jS),e==null?void 0:e.videoCaptureDefaults),this.options.publishDefaults=Object.assign(Object.assign({},vD),e==null?void 0:e.publishDefaults),this.maybeCreateEngine(),this.incomingDataStreamManager=new KD,this.outgoingDataStreamManager=new $D(this.engine,this.log),this.disconnectLock=new In,this.localParticipant=new aP("","",this.engine,this.options,this.rpcHandlers,this.outgoingDataStreamManager),(this.options.e2ee||this.options.encryption)&&this.setupE2EE(),this.engine.e2eeManager=this.e2eeManager,this.options.videoCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set("videoinput",Ba(this.options.videoCaptureDefaults.deviceId)),this.options.audioCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set("audioinput",Ba(this.options.audioCaptureDefaults.deviceId)),!((r=this.options.audioOutput)===null||r===void 0)&&r.deviceId&&this.switchActiveDevice("audiooutput",Ba(this.options.audioOutput.deviceId)).catch(o=>this.log.warn("Could not set audio output: ".concat(o.message),this.logContext)),ri()){const o=new AbortController;(a=navigator.mediaDevices)===null||a===void 0||a.addEventListener("devicechange",this.handleDeviceChange,{signal:o.signal}),zs.cleanupRegistry&&zs.cleanupRegistry.register(this,()=>{o.abort()})}}registerTextStreamHandler(e,n){return this.incomingDataStreamManager.registerTextStreamHandler(e,n)}unregisterTextStreamHandler(e){return this.incomingDataStreamManager.unregisterTextStreamHandler(e)}registerByteStreamHandler(e,n){return this.incomingDataStreamManager.registerByteStreamHandler(e,n)}unregisterByteStreamHandler(e){return this.incomingDataStreamManager.unregisterByteStreamHandler(e)}registerRpcMethod(e,n){if(this.rpcHandlers.has(e))throw Error("RPC handler already registered for method ".concat(e,", unregisterRpcMethod before trying to register again"));this.rpcHandlers.set(e,n)}unregisterRpcMethod(e){this.rpcHandlers.delete(e)}setE2EEEnabled(e){return E(this,void 0,void 0,function*(){if(this.e2eeManager)yield Promise.all([this.localParticipant.setE2EEEnabled(e)]),this.localParticipant.identity!==""&&this.e2eeManager.setParticipantCryptorEnabled(e,this.localParticipant.identity);else throw Error("e2ee not configured, please set e2ee settings within the room options")})}setupE2EE(){var e;const n=!!this.options.encryption,i=this.options.encryption||this.options.e2ee;i&&("e2eeManager"in i?(this.e2eeManager=i.e2eeManager,this.e2eeManager.isDataChannelEncryptionEnabled=n):this.e2eeManager=new eD(i,n),this.e2eeManager.on(qa.ParticipantEncryptionStatusChanged,(r,a)=>{H8(a)&&(this.isE2EEEnabled=r),this.emit(Q.ParticipantEncryptionStatusChanged,r,a)}),this.e2eeManager.on(qa.EncryptionError,(r,a)=>{const o=a?this.getParticipantByIdentity(a):void 0;this.emit(Q.EncryptionError,r,o)}),(e=this.e2eeManager)===null||e===void 0||e.setup(this))}get logContext(){var e;return{room:this.name,roomID:(e=this.roomInfo)===null||e===void 0?void 0:e.sid,participant:this.localParticipant.identity,pID:this.localParticipant.sid}}get isRecording(){var e,n;return(n=(e=this.roomInfo)===null||e===void 0?void 0:e.activeRecording)!==null&&n!==void 0?n:!1}getSid(){return E(this,void 0,void 0,function*(){return this.state===Xe.Disconnected?"":this.roomInfo&&this.roomInfo.sid!==""?this.roomInfo.sid:new Promise((e,n)=>{const i=r=>{r.sid!==""&&(this.engine.off(re.RoomUpdate,i),e(r.sid))};this.engine.on(re.RoomUpdate,i),this.once(Q.Disconnected,()=>{this.engine.off(re.RoomUpdate,i),n("Room disconnected before room server id was available")})})})}get name(){var e,n;return(n=(e=this.roomInfo)===null||e===void 0?void 0:e.name)!==null&&n!==void 0?n:""}get metadata(){var e;return(e=this.roomInfo)===null||e===void 0?void 0:e.metadata}get numParticipants(){var e,n;return(n=(e=this.roomInfo)===null||e===void 0?void 0:e.numParticipants)!==null&&n!==void 0?n:0}get numPublishers(){var e,n;return(n=(e=this.roomInfo)===null||e===void 0?void 0:e.numPublishers)!==null&&n!==void 0?n:0}maybeCreateEngine(){this.engine&&!this.engine.isClosed||(this.engine=new VD(this.options),this.engine.e2eeManager=this.e2eeManager,this.engine.on(re.ParticipantUpdate,this.handleParticipantUpdates).on(re.RoomUpdate,this.handleRoomUpdate).on(re.SpeakersChanged,this.handleSpeakersChanged).on(re.StreamStateChanged,this.handleStreamStateUpdate).on(re.ConnectionQualityUpdate,this.handleConnectionQualityUpdate).on(re.SubscriptionError,this.handleSubscriptionError).on(re.SubscriptionPermissionUpdate,this.handleSubscriptionPermissionUpdate).on(re.MediaTrackAdded,(e,n,i)=>{this.onTrackAdded(e,n,i)}).on(re.Disconnected,e=>{this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,e)}).on(re.ActiveSpeakersUpdate,this.handleActiveSpeakersUpdate).on(re.DataPacketReceived,this.handleDataPacket).on(re.Resuming,()=>{this.clearConnectionReconcile(),this.isResuming=!0,this.log.info("Resuming signal connection",this.logContext),this.setAndEmitConnectionState(Xe.SignalReconnecting)&&this.emit(Q.SignalReconnecting)}).on(re.Resumed,()=>{this.registerConnectionReconcile(),this.isResuming=!1,this.log.info("Resumed signal connection",this.logContext),this.updateSubscriptions(),this.emitBufferedEvents(),this.setAndEmitConnectionState(Xe.Connected)&&this.emit(Q.Reconnected)}).on(re.SignalResumed,()=>{this.bufferedEvents=[],(this.state===Xe.Reconnecting||this.isResuming)&&this.sendSyncState()}).on(re.Restarting,this.handleRestarting).on(re.SignalRestarted,this.handleSignalRestarted).on(re.Offline,()=>{this.setAndEmitConnectionState(Xe.Reconnecting)&&this.emit(Q.Reconnecting)}).on(re.DCBufferStatusChanged,(e,n)=>{this.emit(Q.DCBufferStatusChanged,e,n)}).on(re.LocalTrackSubscribed,e=>{const n=this.localParticipant.getTrackPublications().find(i=>{let{trackSid:r}=i;return r===e});if(!n){this.log.warn("could not find local track subscription for subscribed event",this.logContext);return}this.localParticipant.emit(se.LocalTrackSubscribed,n),this.emitWhenConnected(Q.LocalTrackSubscribed,n,this.localParticipant)}).on(re.RoomMoved,e=>{this.log.debug("room moved",e),e.room&&this.handleRoomUpdate(e.room),this.remoteParticipants.forEach((n,i)=>{this.handleParticipantDisconnected(i,n)}),this.emit(Q.Moved,e.room.name),e.participant?this.handleParticipantUpdates([e.participant,...e.otherParticipants]):this.handleParticipantUpdates(e.otherParticipants)}),this.localParticipant&&this.localParticipant.setupEngine(this.engine),this.e2eeManager&&this.e2eeManager.setupEngine(this.engine),this.outgoingDataStreamManager&&this.outgoingDataStreamManager.setupEngine(this.engine))}static getLocalDevices(e){let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return on.getInstance().getDevices(e,n)}prepareConnection(e,n){return E(this,void 0,void 0,function*(){if(this.state===Xe.Disconnected){this.log.debug("prepareConnection to ".concat(e),this.logContext);try{if(Ls(new URL(e))&&n){this.regionUrlProvider=new Ke(e,n);const i=yield this.regionUrlProvider.getNextBestRegionUrl();i&&this.state===Xe.Disconnected&&(this.regionUrl=i,yield fetch(gc(i),{method:"HEAD"}),this.log.debug("prepared connection to ".concat(i),this.logContext))}else yield fetch(gc(e),{method:"HEAD"})}catch(i){this.log.warn("could not prepare connection",Object.assign(Object.assign({},this.logContext),{error:i}))}}})}getParticipantByIdentity(e){return this.localParticipant.identity===e?this.localParticipant:this.remoteParticipants.get(e)}clearConnectionFutures(){this.connectFuture=void 0}simulateScenario(e,n){return E(this,void 0,void 0,function*(){let i=()=>E(this,void 0,void 0,function*(){}),r;switch(e){case"signal-reconnect":yield this.engine.client.handleOnClose("simulate disconnect");break;case"speaker":r=new Er({scenario:{case:"speakerUpdate",value:3}});break;case"node-failure":r=new Er({scenario:{case:"nodeFailure",value:!0}});break;case"server-leave":r=new Er({scenario:{case:"serverLeave",value:!0}});break;case"migration":r=new Er({scenario:{case:"migration",value:!0}});break;case"resume-reconnect":this.engine.failNext(),yield this.engine.client.handleOnClose("simulate resume-disconnect");break;case"disconnect-signal-on-resume":i=()=>E(this,void 0,void 0,function*(){yield this.engine.client.handleOnClose("simulate resume-disconnect")}),r=new Er({scenario:{case:"disconnectSignalOnResume",value:!0}});break;case"disconnect-signal-on-resume-no-messages":i=()=>E(this,void 0,void 0,function*(){yield this.engine.client.handleOnClose("simulate resume-disconnect")}),r=new Er({scenario:{case:"disconnectSignalOnResumeNoMessages",value:!0}});break;case"full-reconnect":this.engine.fullReconnectOnNext=!0,yield this.engine.client.handleOnClose("simulate full-reconnect");break;case"force-tcp":case"force-tls":r=new Er({scenario:{case:"switchCandidateProtocol",value:e==="force-tls"?2:1}}),i=()=>E(this,void 0,void 0,function*(){const a=this.engine.client.onLeave;a&&a(new Zd({reason:nr.CLIENT_INITIATED,action:Ns.RECONNECT}))});break;case"subscriber-bandwidth":if(n===void 0||typeof n!="number")throw new Error("subscriber-bandwidth requires a number as argument");r=new Er({scenario:{case:"subscriberBandwidth",value:Go(n)}});break;case"leave-full-reconnect":r=new Er({scenario:{case:"leaveRequestFullReconnect",value:!0}})}r&&(yield this.engine.client.sendSimulateScenario(r),yield i())})}get canPlaybackAudio(){return this.audioEnabled}get canPlaybackVideo(){return!this.isVideoPlaybackBlocked}getActiveDevice(e){return this.localParticipant.activeDeviceMap.get(e)}switchActiveDevice(e,n){return E(this,arguments,void 0,function(i,r){var a=this;let o=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0;return function*(){var s,l,c,u,d,h,p;let b=!0,m=!1;const S=o?{exact:r}:r;if(i==="audioinput"){m=a.localParticipant.audioTrackPublications.size===0;const g=(s=a.getActiveDevice(i))!==null&&s!==void 0?s:a.options.audioCaptureDefaults.deviceId;a.options.audioCaptureDefaults.deviceId=S;const y=Array.from(a.localParticipant.audioTrackPublications.values()).filter(v=>v.source===V.Source.Microphone);try{b=(yield Promise.all(y.map(v=>{var k;return(k=v.audioTrack)===null||k===void 0?void 0:k.setDeviceId(S)}))).every(v=>v===!0)}catch(v){throw a.options.audioCaptureDefaults.deviceId=g,v}const x=y.some(v=>{var k,T;return(T=(k=v.track)===null||k===void 0?void 0:k.isMuted)!==null&&T!==void 0?T:!1});b&&x&&(m=!0)}else if(i==="videoinput"){m=a.localParticipant.videoTrackPublications.size===0;const g=(l=a.getActiveDevice(i))!==null&&l!==void 0?l:a.options.videoCaptureDefaults.deviceId;a.options.videoCaptureDefaults.deviceId=S;const y=Array.from(a.localParticipant.videoTrackPublications.values()).filter(v=>v.source===V.Source.Camera);try{b=(yield Promise.all(y.map(v=>{var k;return(k=v.videoTrack)===null||k===void 0?void 0:k.setDeviceId(S)}))).every(v=>v===!0)}catch(v){throw a.options.videoCaptureDefaults.deviceId=g,v}const x=y.some(v=>{var k,T;return(T=(k=v.track)===null||k===void 0?void 0:k.isMuted)!==null&&T!==void 0?T:!1});b&&x&&(m=!0)}else if(i==="audiooutput"){if(m=!0,!Km()&&!a.options.webAudioMix||a.options.webAudioMix&&a.audioContext&&!("setSinkId"in a.audioContext))throw new Error("cannot switch audio output, the current browser does not support it");a.options.webAudioMix&&(r=(c=yield on.getInstance().normalizeDeviceId("audiooutput",r))!==null&&c!==void 0?c:""),(u=(p=a.options).audioOutput)!==null&&u!==void 0||(p.audioOutput={});const g=(d=a.getActiveDevice(i))!==null&&d!==void 0?d:a.options.audioOutput.deviceId;a.options.audioOutput.deviceId=r;try{a.options.webAudioMix&&((h=a.audioContext)===null||h===void 0||h.setSinkId(r)),yield Promise.all(Array.from(a.remoteParticipants.values()).map(y=>y.setAudioOutput({deviceId:r})))}catch(y){throw a.options.audioOutput.deviceId=g,y}}return m&&(a.localParticipant.activeDeviceMap.set(i,r),a.emit(Q.ActiveDeviceChanged,i,r)),b}()})}setupLocalParticipantEvents(){this.localParticipant.on(se.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).on(se.ParticipantNameChanged,this.onLocalParticipantNameChanged).on(se.AttributesChanged,this.onLocalAttributesChanged).on(se.TrackMuted,this.onLocalTrackMuted).on(se.TrackUnmuted,this.onLocalTrackUnmuted).on(se.LocalTrackPublished,this.onLocalTrackPublished).on(se.LocalTrackUnpublished,this.onLocalTrackUnpublished).on(se.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).on(se.MediaDevicesError,this.onMediaDevicesError).on(se.AudioStreamAcquired,this.startAudio).on(se.ChatMessage,this.onLocalChatMessageSent).on(se.ParticipantPermissionsChanged,this.onLocalParticipantPermissionsChanged)}recreateEngine(){var e;(e=this.engine)===null||e===void 0||e.close(),this.engine=void 0,this.isResuming=!1,this.remoteParticipants.clear(),this.sidToIdentity.clear(),this.bufferedEvents=[],this.maybeCreateEngine()}onTrackAdded(e,n,i){if(this.state===Xe.Connecting||this.state===Xe.Reconnecting){const d=()=>{this.log.debug("deferring on track for later",{mediaTrackId:e.id,mediaStreamId:n.id,tracksInStream:n.getTracks().map(p=>p.id)}),this.onTrackAdded(e,n,i),h()},h=()=>{this.off(Q.Reconnected,d),this.off(Q.Connected,d),this.off(Q.Disconnected,h)};this.once(Q.Reconnected,d),this.once(Q.Connected,d),this.once(Q.Disconnected,h);return}if(this.state===Xe.Disconnected){this.log.warn("skipping incoming track after Room disconnected",this.logContext);return}if(e.readyState==="ended"){this.log.info("skipping incoming track as it already ended",this.logContext);return}const r=R8(n.id),a=r[0];let o=r[1],s=e.id;if(o&&o.startsWith("TR")&&(s=o),a===this.localParticipant.sid){this.log.warn("tried to create RemoteParticipant for local participant",this.logContext);return}const l=Array.from(this.remoteParticipants.values()).find(d=>d.sid===a);if(!l){this.log.error("Tried to add a track for a participant, that's not present. Sid: ".concat(a),this.logContext);return}if(!s.startsWith("TR")){const d=this.engine.getTrackIdForReceiver(i);if(!d){this.log.error("Tried to add a track whose 'sid' could not be found for a participant, that's not present. Sid: ".concat(a),this.logContext);return}s=d}s.startsWith("TR")||this.log.warn("Tried to add a track whose 'sid' could not be determined for a participant, that's not present. Sid: ".concat(a,", streamId: ").concat(o,", trackId: ").concat(s),Object.assign(Object.assign({},this.logContext),{rpID:a,streamId:o,trackId:s}));let c;this.options.adaptiveStream&&(typeof this.options.adaptiveStream=="object"?c=this.options.adaptiveStream:c={});const u=l.addSubscribedMediaTrack(e,s,n,i,c);u!=null&&u.isEncrypted&&!this.e2eeManager&&this.emit(Q.EncryptionError,new Error("Encrypted ".concat(u.source," track received from participant ").concat(l.sid,", but room does not have encryption enabled!")))}handleDisconnect(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0,n=arguments.length>1?arguments[1]:void 0;var i;if(this.clearConnectionReconcile(),this.isResuming=!1,this.bufferedEvents=[],this.transcriptionReceivedTimes.clear(),this.incomingDataStreamManager.clearControllers(),this.state!==Xe.Disconnected){this.regionUrl=void 0,this.regionUrlProvider&&this.regionUrlProvider.notifyDisconnected();try{this.remoteParticipants.forEach(r=>{r.trackPublications.forEach(a=>{r.unpublishTrack(a.trackSid)})}),this.localParticipant.trackPublications.forEach(r=>{var a,o,s;r.track&&this.localParticipant.unpublishTrack(r.track,e),e?((a=r.track)===null||a===void 0||a.detach(),(o=r.track)===null||o===void 0||o.stop()):(s=r.track)===null||s===void 0||s.stopMonitor()}),this.localParticipant.off(se.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).off(se.ParticipantNameChanged,this.onLocalParticipantNameChanged).off(se.AttributesChanged,this.onLocalAttributesChanged).off(se.TrackMuted,this.onLocalTrackMuted).off(se.TrackUnmuted,this.onLocalTrackUnmuted).off(se.LocalTrackPublished,this.onLocalTrackPublished).off(se.LocalTrackUnpublished,this.onLocalTrackUnpublished).off(se.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).off(se.MediaDevicesError,this.onMediaDevicesError).off(se.AudioStreamAcquired,this.startAudio).off(se.ChatMessage,this.onLocalChatMessageSent).off(se.ParticipantPermissionsChanged,this.onLocalParticipantPermissionsChanged),this.localParticipant.trackPublications.clear(),this.localParticipant.videoTrackPublications.clear(),this.localParticipant.audioTrackPublications.clear(),this.remoteParticipants.clear(),this.sidToIdentity.clear(),this.activeSpeakers=[],this.audioContext&&typeof this.options.webAudioMix=="boolean"&&(this.audioContext.close(),this.audioContext=void 0),ri()&&(window.removeEventListener("beforeunload",this.onPageLeave),window.removeEventListener("pagehide",this.onPageLeave),window.removeEventListener("freeze",this.onPageLeave),(i=navigator.mediaDevices)===null||i===void 0||i.removeEventListener("devicechange",this.handleDeviceChange))}finally{this.setAndEmitConnectionState(Xe.Disconnected),this.emit(Q.Disconnected,n)}}}handleParticipantDisconnected(e,n){var i;this.remoteParticipants.delete(e),n&&(this.incomingDataStreamManager.validateParticipantHasNoActiveDataStreams(e),n.trackPublications.forEach(r=>{n.unpublishTrack(r.trackSid,!0)}),this.emit(Q.ParticipantDisconnected,n),n.setDisconnected(),(i=this.localParticipant)===null||i===void 0||i.handleParticipantDisconnected(n.identity))}handleIncomingRpcRequest(e,n,i,r,a,o){return E(this,void 0,void 0,function*(){if(yield this.engine.publishRpcAck(e,n),o!==1){yield this.engine.publishRpcResponse(e,n,null,Dt.builtIn("UNSUPPORTED_VERSION"));return}const s=this.rpcHandlers.get(i);if(!s){yield this.engine.publishRpcResponse(e,n,null,Dt.builtIn("UNSUPPORTED_METHOD"));return}let l=null,c=null;try{const u=yield s({requestId:n,callerIdentity:e,payload:r,responseTimeout:a});hg(u)>US?(l=Dt.builtIn("RESPONSE_PAYLOAD_TOO_LARGE"),this.log.warn("RPC Response payload too large for ".concat(i))):c=u}catch(u){u instanceof Dt?l=u:(this.log.warn("Uncaught error returned by RPC handler for ".concat(i,". Returning APPLICATION_ERROR instead."),u),l=Dt.builtIn("APPLICATION_ERROR"))}yield this.engine.publishRpcResponse(e,n,c,l)})}selectDefaultDevices(){return E(this,void 0,void 0,function*(){var e,n,i;const r=on.getInstance().previousDevices,a=yield on.getInstance().getDevices(void 0,!1),o=ii();if((o==null?void 0:o.name)==="Chrome"&&o.os!=="iOS")for(let l of a){const c=r.find(u=>u.deviceId===l.deviceId);c&&c.label!==""&&c.kind===l.kind&&c.label!==l.label&&this.getActiveDevice(l.kind)==="default"&&this.emit(Q.ActiveDeviceChanged,l.kind,l.deviceId)}const s=["audiooutput","audioinput","videoinput"];for(let l of s){const c=y8(l),u=this.localParticipant.getTrackPublication(c);if(u&&(!((e=u.track)===null||e===void 0)&&e.isUserProvided))continue;const d=a.filter(p=>p.kind===l),h=this.getActiveDevice(l);if(h===((n=r.filter(p=>p.kind===l)[0])===null||n===void 0?void 0:n.deviceId)&&d.length>0&&((i=d[0])===null||i===void 0?void 0:i.deviceId)!==h){yield this.switchActiveDevice(l,d[0].deviceId);continue}l==="audioinput"&&!pc()||l==="videoinput"||d.length>0&&!d.find(p=>p.deviceId===this.getActiveDevice(l))&&(l!=="audiooutput"||!pc())&&(yield this.switchActiveDevice(l,d[0].deviceId))}})}acquireAudioContext(){return E(this,void 0,void 0,function*(){var e,n;if(typeof this.options.webAudioMix!="boolean"&&this.options.webAudioMix.audioContext?this.audioContext=this.options.webAudioMix.audioContext:(!this.audioContext||this.audioContext.state==="closed")&&(this.audioContext=(e=lS())!==null&&e!==void 0?e:void 0),this.options.webAudioMix&&this.remoteParticipants.forEach(r=>r.setAudioContext(this.audioContext)),this.localParticipant.setAudioContext(this.audioContext),this.audioContext&&this.audioContext.state==="suspended")try{yield Promise.race([this.audioContext.resume(),_n(200)])}catch(r){this.log.warn("Could not resume audio context",Object.assign(Object.assign({},this.logContext),{error:r}))}const i=((n=this.audioContext)===null||n===void 0?void 0:n.state)==="running";i!==this.canPlaybackAudio&&(this.audioEnabled=i,this.emit(Q.AudioPlaybackStatusChanged,i))})}createParticipant(e,n){var i;let r;return n?r=mh.fromParticipantInfo(this.engine.client,n,{loggerContextCb:()=>this.logContext,loggerName:this.options.loggerName}):r=new mh(this.engine.client,"",e,void 0,void 0,void 0,{loggerContextCb:()=>this.logContext,loggerName:this.options.loggerName}),this.options.webAudioMix&&r.setAudioContext(this.audioContext),!((i=this.options.audioOutput)===null||i===void 0)&&i.deviceId&&r.setAudioOutput(this.options.audioOutput).catch(a=>this.log.warn("Could not set audio output: ".concat(a.message),this.logContext)),r}getOrCreateParticipant(e,n){if(this.remoteParticipants.has(e)){const r=this.remoteParticipants.get(e);return n&&r.updateInfo(n)&&this.sidToIdentity.set(n.sid,n.identity),r}const i=this.createParticipant(e,n);return this.remoteParticipants.set(e,i),this.sidToIdentity.set(n.sid,n.identity),this.emitWhenConnected(Q.ParticipantConnected,i),i.on(se.TrackPublished,r=>{this.emitWhenConnected(Q.TrackPublished,r,i)}).on(se.TrackSubscribed,(r,a)=>{r.kind===V.Kind.Audio?(r.on(ne.AudioPlaybackStarted,this.handleAudioPlaybackStarted),r.on(ne.AudioPlaybackFailed,this.handleAudioPlaybackFailed)):r.kind===V.Kind.Video&&(r.on(ne.VideoPlaybackFailed,this.handleVideoPlaybackFailed),r.on(ne.VideoPlaybackStarted,this.handleVideoPlaybackStarted)),this.emit(Q.TrackSubscribed,r,a,i)}).on(se.TrackUnpublished,r=>{this.emit(Q.TrackUnpublished,r,i)}).on(se.TrackUnsubscribed,(r,a)=>{this.emit(Q.TrackUnsubscribed,r,a,i)}).on(se.TrackMuted,r=>{this.emitWhenConnected(Q.TrackMuted,r,i)}).on(se.TrackUnmuted,r=>{this.emitWhenConnected(Q.TrackUnmuted,r,i)}).on(se.ParticipantMetadataChanged,r=>{this.emitWhenConnected(Q.ParticipantMetadataChanged,r,i)}).on(se.ParticipantNameChanged,r=>{this.emitWhenConnected(Q.ParticipantNameChanged,r,i)}).on(se.AttributesChanged,r=>{this.emitWhenConnected(Q.ParticipantAttributesChanged,r,i)}).on(se.ConnectionQualityChanged,r=>{this.emitWhenConnected(Q.ConnectionQualityChanged,r,i)}).on(se.ParticipantPermissionsChanged,r=>{this.emitWhenConnected(Q.ParticipantPermissionsChanged,r,i)}).on(se.TrackSubscriptionStatusChanged,(r,a)=>{this.emitWhenConnected(Q.TrackSubscriptionStatusChanged,r,a,i)}).on(se.TrackSubscriptionFailed,(r,a)=>{this.emit(Q.TrackSubscriptionFailed,r,i,a)}).on(se.TrackSubscriptionPermissionChanged,(r,a)=>{this.emitWhenConnected(Q.TrackSubscriptionPermissionChanged,r,a,i)}).on(se.Active,()=>{this.emitWhenConnected(Q.ParticipantActive,i),i.kind===sc.AGENT&&this.localParticipant.setActiveAgent(i)}),n&&i.updateInfo(n),i}sendSyncState(){const e=Array.from(this.remoteParticipants.values()).reduce((i,r)=>(i.push(...r.getTrackPublications()),i),[]),n=this.localParticipant.getTrackPublications();this.engine.sendSyncState(e,n)}updateSubscriptions(){for(const e of this.remoteParticipants.values())for(const n of e.videoTrackPublications.values())n.isSubscribed&&q8(n)&&n.emitTrackUpdate()}getRemoteParticipantBySid(e){const n=this.sidToIdentity.get(e);if(n)return this.remoteParticipants.get(n)}registerConnectionReconcile(){this.clearConnectionReconcile();let e=0;this.connectionReconcileInterval=yn.setInterval(()=>{!this.engine||this.engine.isClosed||!this.engine.verifyTransport()?(e++,this.log.warn("detected connection state mismatch",Object.assign(Object.assign({},this.logContext),{numFailures:e,engine:this.engine?{closed:this.engine.isClosed,transportsConnected:this.engine.verifyTransport()}:void 0})),e>=3&&(this.recreateEngine(),this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,nr.STATE_MISMATCH))):e=0},sP)}clearConnectionReconcile(){this.connectionReconcileInterval&&yn.clearInterval(this.connectionReconcileInterval)}setAndEmitConnectionState(e){return e===this.state?!1:(this.state=e,this.emit(Q.ConnectionStateChanged,this.state),!0)}emitBufferedEvents(){this.bufferedEvents.forEach(e=>{let[n,i]=e;this.emit(n,...i)}),this.bufferedEvents=[]}emitWhenConnected(e){for(var n=arguments.length,i=new Array(n>1?n-1:0),r=1;r<n;r++)i[r-1]=arguments[r];if(this.state===Xe.Reconnecting||this.isResuming||!this.engine||this.engine.pendingReconnect)this.bufferedEvents.push([e,i]);else if(this.state===Xe.Connected)return this.emit(e,...i);return!1}simulateParticipants(e){return E(this,void 0,void 0,function*(){var n,i;const r=Object.assign({audio:!0,video:!0,useRealTracks:!1},e.publish),a=Object.assign({count:9,audio:!1,video:!0,aspectRatios:[1.66,1.7,1.3]},e.participants);if(this.handleDisconnect(),this.roomInfo=new Vd({sid:"RM_SIMULATED",name:"simulated-room",emptyTimeout:0,maxParticipants:0,creationTime:Et.parse(new Date().getTime()),metadata:"",numParticipants:1,numPublishers:1,turnPassword:"",enabledCodecs:[],activeRecording:!1}),this.localParticipant.updateInfo(new Fo({identity:"simulated-local",name:"local-name"})),this.setupLocalParticipantEvents(),this.emit(Q.SignalConnected),this.emit(Q.Connected),this.setAndEmitConnectionState(Xe.Connected),r.video){const o=new xg(V.Kind.Video,new As({source:Vt.CAMERA,sid:Math.floor(Math.random()*1e4).toString(),type:tr.AUDIO,name:"video-dummy"}),new fh(r.useRealTracks?(yield window.navigator.mediaDevices.getUserMedia({video:!0})).getVideoTracks()[0]:yS(160*((n=a.aspectRatios[0])!==null&&n!==void 0?n:1),160,!0,!0),void 0,!1,{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext}),{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext});this.localParticipant.addTrackPublication(o),this.localParticipant.emit(se.LocalTrackPublished,o)}if(r.audio){const o=new xg(V.Kind.Audio,new As({source:Vt.MICROPHONE,sid:Math.floor(Math.random()*1e4).toString(),type:tr.AUDIO}),new hh(r.useRealTracks?(yield navigator.mediaDevices.getUserMedia({audio:!0})).getAudioTracks()[0]:Qm(),void 0,!1,this.audioContext,{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext}),{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext});this.localParticipant.addTrackPublication(o),this.localParticipant.emit(se.LocalTrackPublished,o)}for(let o=0;o<a.count-1;o+=1){let s=new Fo({sid:Math.floor(Math.random()*1e4).toString(),identity:"simulated-".concat(o),state:Rs.ACTIVE,tracks:[],joinedAt:Et.parse(Date.now())});const l=this.getOrCreateParticipant(s.identity,s);if(a.video){const c=yS(160*((i=a.aspectRatios[o%a.aspectRatios.length])!==null&&i!==void 0?i:1),160,!1,!0),u=new As({source:Vt.CAMERA,sid:Math.floor(Math.random()*1e4).toString(),type:tr.AUDIO});l.addSubscribedMediaTrack(c,u.sid,new MediaStream([c]),new RTCRtpReceiver),s.tracks=[...s.tracks,u]}if(a.audio){const c=Qm(),u=new As({source:Vt.MICROPHONE,sid:Math.floor(Math.random()*1e4).toString(),type:tr.AUDIO});l.addSubscribedMediaTrack(c,u.sid,new MediaStream([c]),new RTCRtpReceiver),s.tracks=[...s.tracks,u]}l.updateInfo(s)}})}emit(e){for(var n=arguments.length,i=new Array(n>1?n-1:0),r=1;r<n;r++)i[r-1]=arguments[r];if(e!==Q.ActiveSpeakersChanged&&e!==Q.TranscriptionReceived){const a=nk(i).filter(o=>o!==void 0);(e===Q.TrackSubscribed||e===Q.TrackUnsubscribed)&&this.log.trace("subscribe trace: ".concat(e),Object.assign(Object.assign({},this.logContext),{event:e,args:a})),this.log.debug("room event ".concat(e),Object.assign(Object.assign({},this.logContext),{event:e,args:a}))}return super.emit(e,...i)}}zs.cleanupRegistry=typeof FinalizationRegistry<"u"&&new FinalizationRegistry(t=>{t()});function nk(t){return t.map(e=>{if(e)return Array.isArray(e)?nk(e):typeof e=="object"?"logContext"in e?e.logContext:void 0:e})}var sr;(function(t){t[t.IDLE=0]="IDLE",t[t.RUNNING=1]="RUNNING",t[t.SKIPPED=2]="SKIPPED",t[t.SUCCESS=3]="SUCCESS",t[t.FAILED=4]="FAILED"})(sr||(sr={}));class Ga extends Rr.EventEmitter{constructor(e,n){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};super(),this.status=sr.IDLE,this.logs=[],this.options={},this.url=e,this.token=n,this.name=this.constructor.name,this.room=new zs(i.roomOptions),this.connectOptions=i.connectOptions,this.options=i}run(e){return E(this,void 0,void 0,function*(){if(this.status!==sr.IDLE)throw Error("check is running already");this.setStatus(sr.RUNNING);try{yield this.perform()}catch(n){n instanceof Error&&(this.options.errorsAsWarnings?this.appendWarning(n.message):this.appendError(n.message))}return yield this.disconnect(),yield new Promise(n=>setTimeout(n,500)),this.status!==sr.SKIPPED&&this.setStatus(this.isSuccess()?sr.SUCCESS:sr.FAILED),e&&e(),this.getInfo()})}isSuccess(){return!this.logs.some(e=>e.level==="error")}connect(e){return E(this,void 0,void 0,function*(){return this.room.state===Xe.Connected?this.room:(e||(e=this.url),yield this.room.connect(e,this.token,this.connectOptions),this.room)})}disconnect(){return E(this,void 0,void 0,function*(){this.room&&this.room.state!==Xe.Disconnected&&(yield this.room.disconnect(),yield new Promise(e=>setTimeout(e,500)))})}skip(){this.setStatus(sr.SKIPPED)}switchProtocol(e){return E(this,void 0,void 0,function*(){let n=!1,i=!1;if(this.room.on(Q.Reconnecting,()=>{n=!0}),this.room.once(Q.Reconnected,()=>{i=!0}),this.room.simulateScenario("force-".concat(e)),yield new Promise(a=>setTimeout(a,1e3)),!n)return;const r=Date.now()+1e4;for(;Date.now()<r;){if(i)return;yield _n(100)}throw new Error("Could not reconnect using ".concat(e," protocol after 10 seconds"))})}appendMessage(e){this.logs.push({level:"info",message:e}),this.emit("update",this.getInfo())}appendWarning(e){this.logs.push({level:"warning",message:e}),this.emit("update",this.getInfo())}appendError(e){this.logs.push({level:"error",message:e}),this.emit("update",this.getInfo())}setStatus(e){this.status=e,this.emit("update",this.getInfo())}get engine(){var e;return(e=this.room)===null||e===void 0?void 0:e.engine}getInfo(){return{logs:this.logs,name:this.name,status:this.status,description:this.description}}}class lP extends Ga{get description(){return"Cloud regions"}perform(){return E(this,void 0,void 0,function*(){const e=new Ke(this.url,this.token);if(!e.isCloud()){this.skip();return}const n=[],i=new Set;for(let a=0;a<3;a++){const o=yield e.getNextBestRegionUrl();if(!o)break;if(i.has(o))continue;i.add(o);const s=yield this.checkCloudRegion(o);this.appendMessage("".concat(s.region," RTT: ").concat(s.rtt,"ms, duration: ").concat(s.duration,"ms")),n.push(s)}n.sort((a,o)=>(a.duration-o.duration)*.5+(a.rtt-o.rtt)*.5);const r=n[0];this.bestStats=r,this.appendMessage("best Cloud region: ".concat(r.region))})}getInfo(){const e=super.getInfo();return e.data=this.bestStats,e}checkCloudRegion(e){return E(this,void 0,void 0,function*(){var n,i;yield this.connect(e),this.options.protocol==="tcp"&&(yield this.switchProtocol("tcp"));const r=(n=this.room.serverInfo)===null||n===void 0?void 0:n.region;if(!r)throw new Error("Region not found");const a=yield this.room.localParticipant.streamText({topic:"test"}),o=1e3,l=1e6/o,c="A".repeat(o),u=Date.now();for(let b=0;b<l;b++)yield a.write(c);yield a.close();const d=Date.now(),h=yield(i=this.room.engine.pcManager)===null||i===void 0?void 0:i.publisher.getStats(),p={region:r,rtt:1e4,duration:d-u};return h==null||h.forEach(b=>{b.type==="candidate-pair"&&b.nominated&&(p.rtt=b.currentRoundTripTime*1e3)}),yield this.disconnect(),p})}}const Sg=1e4;class cP extends Ga{get description(){return"Connection via UDP vs TCP"}perform(){return E(this,void 0,void 0,function*(){const e=yield this.checkConnectionProtocol("udp"),n=yield this.checkConnectionProtocol("tcp");this.bestStats=e,e.qualityLimitationDurations.bandwidth-n.qualityLimitationDurations.bandwidth>.5||(e.packetsLost-n.packetsLost)/e.packetsSent>.01?(this.appendMessage("best connection quality via tcp"),this.bestStats=n):this.appendMessage("best connection quality via udp");const i=this.bestStats;this.appendMessage("upstream bitrate: ".concat((i.bitrateTotal/i.count/1e3/1e3).toFixed(2)," mbps")),this.appendMessage("RTT: ".concat((i.rttTotal/i.count*1e3).toFixed(2)," ms")),this.appendMessage("jitter: ".concat((i.jitterTotal/i.count*1e3).toFixed(2)," ms")),i.packetsLost>0&&this.appendWarning("packets lost: ".concat((i.packetsLost/i.packetsSent*100).toFixed(2),"%")),i.qualityLimitationDurations.bandwidth>1&&this.appendWarning("bandwidth limited ".concat((i.qualityLimitationDurations.bandwidth/(Sg/1e3)*100).toFixed(2),"%")),i.qualityLimitationDurations.cpu>0&&this.appendWarning("cpu limited ".concat((i.qualityLimitationDurations.cpu/(Sg/1e3)*100).toFixed(2),"%"))})}getInfo(){const e=super.getInfo();return e.data=this.bestStats,e}checkConnectionProtocol(e){return E(this,void 0,void 0,function*(){yield this.connect(),e==="tcp"?yield this.switchProtocol("tcp"):yield this.switchProtocol("udp");const n=document.createElement("canvas");n.width=1280,n.height=720;const i=n.getContext("2d");if(!i)throw new Error("Could not get canvas context");let r=0;const a=()=>{r=(r+1)%360,i.fillStyle="hsl(".concat(r,", 100%, 50%)"),i.fillRect(0,0,n.width,n.height),requestAnimationFrame(a)};a();const s=n.captureStream(30).getVideoTracks()[0],c=(yield this.room.localParticipant.publishTrack(s,{simulcast:!1,degradationPreference:"maintain-resolution",videoEncoding:{maxBitrate:2e6}})).track,u={protocol:e,packetsLost:0,packetsSent:0,qualityLimitationDurations:{},rttTotal:0,jitterTotal:0,bitrateTotal:0,count:0},d=setInterval(()=>E(this,void 0,void 0,function*(){const h=yield c.getRTCStatsReport();h==null||h.forEach(p=>{p.type==="outbound-rtp"?(u.packetsSent=p.packetsSent,u.qualityLimitationDurations=p.qualityLimitationDurations,u.bitrateTotal+=p.targetBitrate,u.count++):p.type==="remote-inbound-rtp"&&(u.packetsLost=p.packetsLost,u.rttTotal+=p.roundTripTime,u.jitterTotal+=p.jitter)})}),1e3);return yield new Promise(h=>setTimeout(h,Sg)),clearInterval(d),s.stop(),n.remove(),yield this.disconnect(),u})}}class uP extends Ga{get description(){return"Can publish audio"}perform(){return E(this,void 0,void 0,function*(){var e;const n=yield this.connect(),i=yield nP();if(yield sS(i,1e3))throw new Error("unable to detect audio from microphone");this.appendMessage("detected audio from microphone"),n.localParticipant.publishTrack(i),yield new Promise(s=>setTimeout(s,3e3));const a=yield(e=i.sender)===null||e===void 0?void 0:e.getStats();if(!a)throw new Error("Could not get RTCStats");let o=0;if(a.forEach(s=>{s.type==="outbound-rtp"&&(s.kind==="audio"||!s.kind&&s.mediaType==="audio")&&(o=s.packetsSent)}),o===0)throw new Error("Could not determine packets are sent");this.appendMessage("published ".concat(o," audio packets"))})}}class dP extends Ga{get description(){return"Can publish video"}perform(){return E(this,void 0,void 0,function*(){var e;const n=yield this.connect(),i=yield tP();yield this.checkForVideo(i.mediaStreamTrack),n.localParticipant.publishTrack(i),yield new Promise(o=>setTimeout(o,5e3));const r=yield(e=i.sender)===null||e===void 0?void 0:e.getStats();if(!r)throw new Error("Could not get RTCStats");let a=0;if(r.forEach(o=>{o.type==="outbound-rtp"&&(o.kind==="video"||!o.kind&&o.mediaType==="video")&&(a+=o.packetsSent)}),a===0)throw new Error("Could not determine packets are sent");this.appendMessage("published ".concat(a," video packets"))})}checkForVideo(e){return E(this,void 0,void 0,function*(){const n=new MediaStream;n.addTrack(e.clone());const i=document.createElement("video");i.srcObject=n,i.muted=!0,i.autoplay=!0,i.playsInline=!0,i.setAttribute("playsinline","true"),document.body.appendChild(i),yield new Promise(r=>{i.onplay=()=>{setTimeout(()=>{var a,o,s,l;const c=document.createElement("canvas"),u=e.getSettings(),d=(o=(a=u.width)!==null&&a!==void 0?a:i.videoWidth)!==null&&o!==void 0?o:1280,h=(l=(s=u.height)!==null&&s!==void 0?s:i.videoHeight)!==null&&l!==void 0?l:720;c.width=d,c.height=h;const p=c.getContext("2d");p.drawImage(i,0,0);const m=p.getImageData(0,0,c.width,c.height).data;let S=!0;for(let g=0;g<m.length;g+=4)if(m[g]!==0||m[g+1]!==0||m[g+2]!==0){S=!1;break}S?this.appendError("camera appears to be producing only black frames"):this.appendMessage("received video frames"),r()},1e3)},i.play()}),n.getTracks().forEach(r=>r.stop()),i.remove()})}}class hP extends Ga{get description(){return"Resuming connection after interruption"}perform(){return E(this,void 0,void 0,function*(){var e;const n=yield this.connect();let i=!1,r=!1,a;const o=new Promise(c=>{setTimeout(c,5e3),a=c}),s=()=>{i=!0};n.on(Q.SignalReconnecting,s).on(Q.Reconnecting,s).on(Q.Reconnected,()=>{r=!0,a(!0)}),(e=n.engine.client.ws)===null||e===void 0||e.close();const l=n.engine.client.onClose;if(l&&l(""),yield o,i){if(!r||n.state!==Xe.Connected)throw this.appendWarning("reconnection is only possible in Redis-based configurations"),new Error("Not able to reconnect")}else throw new Error("Did not attempt to reconnect")})}}class fP extends Ga{get description(){return"Can connect via TURN"}perform(){return E(this,void 0,void 0,function*(){var e,n,i;Ls(new URL(this.url))&&(this.appendMessage("Using region specific url"),this.url=(e=yield new Ke(this.url,this.token).getNextBestRegionUrl())!==null&&e!==void 0?e:this.url);const r=new ig,a=yield r.join(this.url,this.token,{autoSubscribe:!0,maxRetries:0,e2eeEnabled:!1,websocketTimeout:15e3,singlePeerConnection:!1});let o=!1,s=!1,l=!1;for(let c of a.iceServers)for(let u of c.urls)u.startsWith("turn:")?(s=!0,l=!0):u.startsWith("turns:")&&(s=!0,l=!0,o=!0),u.startsWith("stun:")&&(l=!0);l?s&&!o&&this.appendWarning("TURN is configured server side, but TURN/TLS is unavailable."):this.appendWarning("No STUN servers configured on server side."),yield r.close(),!((i=(n=this.connectOptions)===null||n===void 0?void 0:n.rtcConfig)===null||i===void 0)&&i.iceServers||s?yield this.room.connect(this.url,this.token,{rtcConfig:{iceTransportPolicy:"relay"}}):(this.appendWarning("No TURN servers configured."),this.skip(),yield new Promise(c=>setTimeout(c,0)))})}}class pP extends Ga{get description(){return"Establishing WebRTC connection"}perform(){return E(this,void 0,void 0,function*(){let e=!1,n=!1;this.room.on(Q.SignalConnected,()=>{var i;const r=this.room.engine.client.onTrickle;this.room.engine.client.onTrickle=(a,o)=>{if(a.candidate){const s=new RTCIceCandidate(a);let l="".concat(s.protocol," ").concat(s.address,":").concat(s.port," ").concat(s.type);s.address&&(mP(s.address)?l+=" (private)":s.protocol==="tcp"&&s.tcpType==="passive"?(e=!0,l+=" (passive)"):s.protocol==="udp"&&(n=!0)),this.appendMessage(l)}r&&r(a,o)},!((i=this.room.engine.pcManager)===null||i===void 0)&&i.subscriber&&(this.room.engine.pcManager.subscriber.onIceCandidateError=a=>{a instanceof RTCPeerConnectionIceErrorEvent&&this.appendWarning("error with ICE candidate: ".concat(a.errorCode," ").concat(a.errorText," ").concat(a.url))})});try{yield this.connect(),Re.info("now the room is connected")}catch(i){throw this.appendWarning("ports need to be open on firewall in order to connect."),i}e||this.appendWarning("Server is not configured for ICE/TCP"),n||this.appendWarning("No public IPv4 UDP candidates were found. Your server is likely not configured correctly")})}}function mP(t){const e=t.split(".");if(e.length===4){if(e[0]==="10")return!0;if(e[0]==="192"&&e[1]==="168")return!0;if(e[0]==="172"){const n=parseInt(e[1],10);if(n>=16&&n<=31)return!0}}return!1}class gP extends Ga{get description(){return"Connecting to signal connection via WebSocket"}perform(){return E(this,void 0,void 0,function*(){var e,n,i;(this.url.startsWith("ws:")||this.url.startsWith("http:"))&&this.appendWarning("Server is insecure, clients may block connections to it");let r=new ig,a;try{a=yield r.join(this.url,this.token,{autoSubscribe:!0,maxRetries:0,e2eeEnabled:!1,websocketTimeout:15e3,singlePeerConnection:!1})}catch(o){if(Ls(new URL(this.url))){this.appendMessage("Initial connection failed with error ".concat(o.message,". Retrying with region fallback"));const l=yield new Ke(this.url,this.token).getNextBestRegionUrl();l&&(a=yield r.join(l,this.token,{autoSubscribe:!0,maxRetries:0,e2eeEnabled:!1,websocketTimeout:15e3,singlePeerConnection:!1}),this.appendMessage("Fallback to region worked. To avoid initial connections failing, ensure you're calling room.prepareConnection() ahead of time"))}}a?(this.appendMessage("Connected to server, version ".concat(a.serverVersion,".")),((e=a.serverInfo)===null||e===void 0?void 0:e.edition)===J_.Cloud&&(!((n=a.serverInfo)===null||n===void 0)&&n.region)&&this.appendMessage("LiveKit Cloud: ".concat((i=a.serverInfo)===null||i===void 0?void 0:i.region))):this.appendError("Websocket connection could not be established"),yield r.close()})}}class cW extends Rr.EventEmitter{constructor(e,n){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};super(),this.options={},this.checkResults=new Map,this.url=e,this.token=n,this.options=i}getNextCheckId(){const e=this.checkResults.size;return this.checkResults.set(e,{logs:[],status:sr.IDLE,name:"",description:""}),e}updateCheck(e,n){this.checkResults.set(e,n),this.emit("checkUpdate",e,n)}isSuccess(){return Array.from(this.checkResults.values()).every(e=>e.status!==sr.FAILED)}getResults(){return Array.from(this.checkResults.values())}createAndRunCheck(e){return E(this,void 0,void 0,function*(){const n=this.getNextCheckId(),i=new e(this.url,this.token,this.options),r=o=>{this.updateCheck(n,o)};i.on("update",r);const a=yield i.run();return i.off("update",r),a})}checkWebsocket(){return E(this,void 0,void 0,function*(){return this.createAndRunCheck(gP)})}checkWebRTC(){return E(this,void 0,void 0,function*(){return this.createAndRunCheck(pP)})}checkTURN(){return E(this,void 0,void 0,function*(){return this.createAndRunCheck(fP)})}checkReconnect(){return E(this,void 0,void 0,function*(){return this.createAndRunCheck(hP)})}checkPublishAudio(){return E(this,void 0,void 0,function*(){return this.createAndRunCheck(uP)})}checkPublishVideo(){return E(this,void 0,void 0,function*(){return this.createAndRunCheck(dP)})}checkConnectionProtocol(){return E(this,void 0,void 0,function*(){const e=yield this.createAndRunCheck(cP);if(e.data&&"protocol"in e.data){const n=e.data;this.options.protocol=n.protocol}return e})}checkCloudRegion(){return E(this,void 0,void 0,function*(){return this.createAndRunCheck(lP)})}}function Ue(t,e,n){return(e=bP(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function vP(t,e){if(typeof t!="object"||!t)return t;var n=t[Symbol.toPrimitive];if(n!==void 0){var i=n.call(t,e);if(typeof i!="object")return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function bP(t){var e=vP(t,"string");return typeof e=="symbol"?e:e+""}new TextEncoder,new TextDecoder;class Un extends Error{constructor(e,n){var i;super(e,n),Ue(this,"code","ERR_JOSE_GENERIC"),this.name=this.constructor.name,(i=Error.captureStackTrace)===null||i===void 0||i.call(Error,this,this.constructor)}}Ue(Un,"code","ERR_JOSE_GENERIC");class yP extends Un{constructor(e,n){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:"unspecified",r=arguments.length>3&&arguments[3]!==void 0?arguments[3]:"unspecified";super(e,{cause:{claim:i,reason:r,payload:n}}),Ue(this,"code","ERR_JWT_CLAIM_VALIDATION_FAILED"),Ue(this,"claim",void 0),Ue(this,"reason",void 0),Ue(this,"payload",void 0),this.claim=i,this.reason=r,this.payload=n}}Ue(yP,"code","ERR_JWT_CLAIM_VALIDATION_FAILED");class _P extends Un{constructor(e,n){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:"unspecified",r=arguments.length>3&&arguments[3]!==void 0?arguments[3]:"unspecified";super(e,{cause:{claim:i,reason:r,payload:n}}),Ue(this,"code","ERR_JWT_EXPIRED"),Ue(this,"claim",void 0),Ue(this,"reason",void 0),Ue(this,"payload",void 0),this.claim=i,this.reason=r,this.payload=n}}Ue(_P,"code","ERR_JWT_EXPIRED");class xP extends Un{constructor(){super(...arguments),Ue(this,"code","ERR_JOSE_ALG_NOT_ALLOWED")}}Ue(xP,"code","ERR_JOSE_ALG_NOT_ALLOWED");class SP extends Un{constructor(){super(...arguments),Ue(this,"code","ERR_JOSE_NOT_SUPPORTED")}}Ue(SP,"code","ERR_JOSE_NOT_SUPPORTED");class kP extends Un{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:"decryption operation failed",n=arguments.length>1?arguments[1]:void 0;super(e,n),Ue(this,"code","ERR_JWE_DECRYPTION_FAILED")}}Ue(kP,"code","ERR_JWE_DECRYPTION_FAILED");class TP extends Un{constructor(){super(...arguments),Ue(this,"code","ERR_JWE_INVALID")}}Ue(TP,"code","ERR_JWE_INVALID");class wP extends Un{constructor(){super(...arguments),Ue(this,"code","ERR_JWS_INVALID")}}Ue(wP,"code","ERR_JWS_INVALID");class CP extends Un{constructor(){super(...arguments),Ue(this,"code","ERR_JWT_INVALID")}}Ue(CP,"code","ERR_JWT_INVALID");class EP extends Un{constructor(){super(...arguments),Ue(this,"code","ERR_JWK_INVALID")}}Ue(EP,"code","ERR_JWK_INVALID");class RP extends Un{constructor(){super(...arguments),Ue(this,"code","ERR_JWKS_INVALID")}}Ue(RP,"code","ERR_JWKS_INVALID");class AP extends Un{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:"no applicable key found in the JSON Web Key Set",n=arguments.length>1?arguments[1]:void 0;super(e,n),Ue(this,"code","ERR_JWKS_NO_MATCHING_KEY")}}Ue(AP,"code","ERR_JWKS_NO_MATCHING_KEY");class NP extends Un{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:"multiple matching keys found in the JSON Web Key Set",n=arguments.length>1?arguments[1]:void 0;super(e,n),Ue(this,Symbol.asyncIterator,void 0),Ue(this,"code","ERR_JWKS_MULTIPLE_MATCHING_KEYS")}}Ue(NP,"code","ERR_JWKS_MULTIPLE_MATCHING_KEYS");class OP extends Un{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:"request timed out",n=arguments.length>1?arguments[1]:void 0;super(e,n),Ue(this,"code","ERR_JWKS_TIMEOUT")}}Ue(OP,"code","ERR_JWKS_TIMEOUT");class MP extends Un{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:"signature verification failed",n=arguments.length>1?arguments[1]:void 0;super(e,n),Ue(this,"code","ERR_JWS_SIGNATURE_VERIFICATION_FAILED")}}Ue(MP,"code","ERR_JWS_SIGNATURE_VERIFICATION_FAILED");const DP=/\{[^{}]+\}/g;function PP(){return Math.random().toString(36).slice(2,11)}function LP(t){let{baseUrl:e="",Request:n=globalThis.Request,fetch:i=globalThis.fetch,querySerializer:r,bodySerializer:a,headers:o,...s}={...t};e=ok(e);const l=[];async function c(u,d){const{baseUrl:h,fetch:p=i,Request:b=n,headers:m,params:S={},parseAs:g="json",querySerializer:y,bodySerializer:x=a??jP,body:v,...k}=d||{};h&&(e=ok(h));let T=typeof r=="function"?r:ak(r);y&&(T=typeof y=="function"?y:ak({...typeof r=="object"?r:{},...y}));const C=v===void 0?void 0:x(v),R=C===void 0||C instanceof FormData?{}:{"Content-Type":"application/json"},A={redirect:"follow",...s,...k,body:C,headers:UP(R,o,m,S.header)};let N,O,z=new n(BP(u,{baseUrl:e,params:S,querySerializer:T}),A);for(const X in k)X in z||(z[X]=k[X]);if(l.length){N=PP(),O=Object.freeze({baseUrl:e,fetch:p,parseAs:g,querySerializer:T,bodySerializer:x});for(const X of l)if(X&&typeof X=="object"&&typeof X.onRequest=="function"){const P=await X.onRequest({request:z,schemaPath:u,params:S,options:O,id:N});if(P){if(!(P instanceof n))throw new Error("onRequest: must return new Request() when modifying the request");z=P}}}let Y=await p(z);if(l.length)for(let X=l.length-1;X>=0;X--){const P=l[X];if(P&&typeof P=="object"&&typeof P.onResponse=="function"){const G=await P.onResponse({request:z,response:Y,schemaPath:u,params:S,options:O,id:N});if(G){if(!(G instanceof Response))throw new Error("onResponse: must return new Response() when modifying the response");Y=G}}}if(Y.status===204||Y.headers.get("Content-Length")==="0")return Y.ok?{data:{},response:Y}:{error:{},response:Y};if(Y.ok)return g==="stream"?{data:Y.body,response:Y}:{data:await Y[g](),response:Y};let L=await Y.text();try{L=JSON.parse(L)}catch{}return{error:L,response:Y}}return{GET(u,d){return c(u,{...d,method:"GET"})},PUT(u,d){return c(u,{...d,method:"PUT"})},POST(u,d){return c(u,{...d,method:"POST"})},DELETE(u,d){return c(u,{...d,method:"DELETE"})},OPTIONS(u,d){return c(u,{...d,method:"OPTIONS"})},HEAD(u,d){return c(u,{...d,method:"HEAD"})},PATCH(u,d){return c(u,{...d,method:"PATCH"})},TRACE(u,d){return c(u,{...d,method:"TRACE"})},use(...u){for(const d of u)if(d){if(typeof d!="object"||!("onRequest"in d||"onResponse"in d))throw new Error("Middleware must be an object with one of `onRequest()` or `onResponse()`");l.push(d)}},eject(...u){for(const d of u){const h=l.indexOf(d);h!==-1&&l.splice(h,1)}}}}function gh(t,e,n){if(e==null)return"";if(typeof e=="object")throw new Error("Deeply-nested arrays/objects aren\u2019t supported. Provide your own `querySerializer()` to handle these.");return`${t}=${(n==null?void 0:n.allowReserved)===!0?e:encodeURIComponent(e)}`}function ik(t,e,n){if(!e||typeof e!="object")return"";const i=[],r={simple:",",label:".",matrix:";"}[n.style]||"&";if(n.style!=="deepObject"&&n.explode===!1){for(const s in e)i.push(s,n.allowReserved===!0?e[s]:encodeURIComponent(e[s]));const o=i.join(",");switch(n.style){case"form":return`${t}=${o}`;case"label":return`.${o}`;case"matrix":return`;${t}=${o}`;default:return o}}for(const o in e){const s=n.style==="deepObject"?`${t}[${o}]`:o;i.push(gh(s,e[o],n))}const a=i.join(r);return n.style==="label"||n.style==="matrix"?`${r}${a}`:a}function rk(t,e,n){if(!Array.isArray(e))return"";if(n.explode===!1){const a={form:",",spaceDelimited:"%20",pipeDelimited:"|"}[n.style]||",",o=(n.allowReserved===!0?e:e.map(s=>encodeURIComponent(s))).join(a);switch(n.style){case"simple":return o;case"label":return`.${o}`;case"matrix":return`;${t}=${o}`;default:return`${t}=${o}`}}const i={simple:",",label:".",matrix:";"}[n.style]||"&",r=[];for(const a of e)n.style==="simple"||n.style==="label"?r.push(n.allowReserved===!0?a:encodeURIComponent(a)):r.push(gh(t,a,n));return n.style==="label"||n.style==="matrix"?`${i}${r.join(i)}`:r.join(i)}function ak(t){return function(n){const i=[];if(n&&typeof n=="object")for(const r in n){const a=n[r];if(a!=null){if(Array.isArray(a)){if(a.length===0)continue;i.push(rk(r,a,{style:"form",explode:!0,...t==null?void 0:t.array,allowReserved:(t==null?void 0:t.allowReserved)||!1}));continue}if(typeof a=="object"){i.push(ik(r,a,{style:"deepObject",explode:!0,...t==null?void 0:t.object,allowReserved:(t==null?void 0:t.allowReserved)||!1}));continue}i.push(gh(r,a,t))}}return i.join("&")}}function IP(t,e){let n=t;for(const i of t.match(DP)??[]){let r=i.substring(1,i.length-1),a=!1,o="simple";if(r.endsWith("*")&&(a=!0,r=r.substring(0,r.length-1)),r.startsWith(".")?(o="label",r=r.substring(1)):r.startsWith(";")&&(o="matrix",r=r.substring(1)),!e||e[r]===void 0||e[r]===null)continue;const s=e[r];if(Array.isArray(s)){n=n.replace(i,rk(r,s,{style:o,explode:a}));continue}if(typeof s=="object"){n=n.replace(i,ik(r,s,{style:o,explode:a}));continue}if(o==="matrix"){n=n.replace(i,`;${gh(r,s)}`);continue}n=n.replace(i,o==="label"?`.${encodeURIComponent(s)}`:encodeURIComponent(s))}return n}function jP(t){return t instanceof FormData?t:JSON.stringify(t)}function BP(t,e){var r;let n=`${e.baseUrl}${t}`;(r=e.params)!=null&&r.path&&(n=IP(n,e.params.path));let i=e.querySerializer(e.params.query??{});return i.startsWith("?")&&(i=i.substring(1)),i&&(n+=`?${i}`),n}function UP(...t){const e=new Headers;for(const n of t){if(!n||typeof n!="object")continue;const i=n instanceof Headers?n.entries():Object.entries(n);for(const[r,a]of i)if(a===null)e.delete(r);else if(Array.isArray(a))for(const o of a)e.append(r,o);else a!==void 0&&e.set(r,a)}return e}function ok(t){return t.endsWith("/")?t.substring(0,t.length-1):t}const sk="Onboardee-Session-Token",lk="OnboardeeSessionToken";class ck{constructor(e){this.trackOnboardeeToken=e.trackOnboardeeToken??!0,this.client=LP({baseUrl:e.baseUrl,headers:e.headers,fetch:e.fetch}),this.client.use({onRequest:({request:n})=>{if(this.trackOnboardeeToken&&window.localStorage){const i=window.localStorage.getItem(lk);i&&n.headers.set(sk,i)}return n},onResponse:({response:n})=>{if(this.trackOnboardeeToken){const i=n.headers.get(sk);i&&window.localStorage&&window.localStorage.setItem(lk,i)}return n}})}setTrackOnboardeeToken(e){this.trackOnboardeeToken=e}setAuthToken(e){this.client.use({onRequest({request:n}){return n.headers.set("Authorization",`Bearer ${e}`),n}})}setApiToken(e){this.client.use({onRequest({request:n}){return n.headers.set("Authorization",`Token ${e}`),n}})}async getAuthUrl(e){return await this.client.GET("/api/auth/{type}",{params:{path:{type:e}}})}async getConnectUrl(e){return await this.client.GET("/api/connect/{type}",{params:{path:{type:e}}})}async logout(){return await this.client.POST("/api/logout")}async getCurrentUser(){return await this.client.GET("/api/me")}async listUsers(){return await this.client.GET("/api/users")}async createUser(e){return await this.client.POST("/api/users",{body:e})}async updateUser(e,n){return await this.client.PATCH("/api/users/{id}",{params:{path:{id:e}},body:n})}async deleteUser(e){return await this.client.DELETE("/api/users/{id}",{params:{path:{id:e}}})}async clientInitialise(e,n={}){return await this.client.POST("/api/client/{appToken}/initialise",{params:{path:{appToken:e}},body:n})}async clientStartSession(e,n){return await this.client.POST("/api/client/{appToken}/start-session",{params:{path:{appToken:e}},body:n})}async createPresignedUploadUrl(e){return await this.client.POST("/api/files",{body:e})}async createKnowledgeBlock(e){return await this.client.POST("/api/knowledge",{body:e})}async listOnboardees(){return await this.client.GET("/api/onboardees")}async getOnboardee(e){return await this.client.GET("/api/onboardees/{id}",{params:{path:{id:e}}})}async getOnboardeeWidgetConfig(e,n){return await this.client.GET("/api/onboardees/{id}/config",{params:{path:{id:e}},signal:n})}async listPlans(e){return await this.client.GET("/api/plans",{params:{query:{...e&&{client_type:e}}}})}async listPlansWithStatus(){return await this.client.GET("/api/plans-with-status")}async listPublishedPlansForProduct(e){return await this.client.GET("/api/products/{id}/published-plans",{params:{path:{id:String(e)}}})}async listProducts(){return await this.client.GET("/api/products")}async getProduct(e){return await this.client.GET("/api/products/{id}",{params:{path:{id:e}}})}async getProductAnalytics(e,n,i,r){return await this.client.GET("/api/products/{id}/analytics",{params:{path:{id:e},query:{...n&&{start_date:n},...i&&{end_date:i},...r&&{course_id:r}}}})}async createProduct(e){return await this.client.POST("/api/products",{body:e})}async updateProduct(e,n){return await this.client.PATCH("/api/products/{id}",{params:{path:{id:e}},body:n})}async getProductAppToken(e){return await this.client.GET("/api/products/{id}/app-token",{params:{path:{id:e}}})}async getProductMeetAppToken(e){return await this.client.GET("/api/products/{id}/meet-app-token",{params:{path:{id:e}}})}async setProductMeetAppToken(e,n){return await this.client.POST("/api/products/{id}/meet-app-token",{params:{path:{id:e}},body:n})}async getProductNavigationIndex(e){return await this.client.GET("/api/products/{id}/navigation-index",{params:{path:{id:e}}})}async replaceProductNavigationIndex(e,n){return await this.client.PUT("/api/products/{id}/navigation-index",{params:{path:{id:e}},body:{content:n.content||""}})}async listProductKnowledgeBlocks(e){return await this.client.GET("/api/products/{id}/knowledge-blocks",{params:{path:{id:e}}})}async createProductKnowledgeBlock(e,n){return await this.client.POST("/api/products/{id}/knowledge-blocks",{params:{path:{id:e}},body:n})}async searchProductKnowledgeBlocks(e,n,i){return await this.client.GET("/api/products/{id}/knowledge-blocks/search",{params:{path:{id:e},query:{q:n,...i&&{limit:i.toString()}}}})}async listAudiences(e,n){return await this.client.GET("/api/products/{id}/audiences",{params:{path:{id:String(e)},...n?{query:n}:{}}})}async createAudience(e,n){return await this.client.POST("/api/products/{id}/audiences",{params:{path:{id:String(e)}},body:n})}async getAudience(e,n){return await this.client.GET("/api/products/{id}/audiences/{audienceId}",{params:{path:{id:String(e),audienceId:n}}})}async updateAudience(e,n,i){return await this.client.PATCH("/api/products/{id}/audiences/{audienceId}",{params:{path:{id:String(e),audienceId:n}},body:i})}async deleteAudience(e,n){return await this.client.DELETE("/api/products/{id}/audiences/{audienceId}",{params:{path:{id:String(e),audienceId:n}}})}async replaceAudiencePlans(e,n,i){return await this.client.PUT("/api/products/{id}/audiences/{audienceId}/plans",{params:{path:{id:String(e),audienceId:n}},body:{plans:i}})}async updateProductKnowledgeBlock(e,n,i){return await this.client.PATCH("/api/products/{id}/knowledge-blocks/{blockId}",{params:{path:{id:e,blockId:n}},body:i})}async deleteProductKnowledgeBlock(e,n){return await this.client.DELETE("/api/products/{id}/knowledge-blocks/{blockId}",{params:{path:{id:e,blockId:n}}})}async listProductPronunciationRules(e){return await this.client.GET("/api/products/{id}/pronunciation-dictionary",{params:{path:{id:e}}})}async bulkCreateProductPronunciationRules(e,n){return await this.client.POST("/api/products/{id}/pronunciation-dictionary",{params:{path:{id:e}},body:n})}async bulkUpdateProductPronunciationRules(e,n){return await this.client.PATCH("/api/products/{id}/pronunciation-dictionary",{params:{path:{id:e}},body:n})}async deleteProductPronunciationRule(e,n){return await this.client.DELETE("/api/products/{id}/pronunciation-dictionary/{ruleId}",{params:{path:{id:e,ruleId:n}}})}async listProductExternalKnowledge(e){return await this.client.GET("/api/products/{id}/external-knowledge",{params:{path:{id:e}}})}async createProductExternalKnowledge(e,n){return await this.client.POST("/api/products/{id}/external-knowledge",{params:{path:{id:e}},body:n})}async updateProductExternalKnowledge(e,n,i){return await this.client.PATCH("/api/products/{id}/external-knowledge/{entryId}",{params:{path:{id:e,entryId:n}},body:i})}async deleteProductExternalKnowledge(e,n){return await this.client.DELETE("/api/products/{id}/external-knowledge/{entryId}",{params:{path:{id:e,entryId:n}}})}async refreshProductExternalKnowledge(e,n){return await this.client.POST("/api/products/{id}/external-knowledge/{entryId}/refresh",{params:{path:{id:e,entryId:n}}})}async listExternalKnowledgePages(e,n){return await this.client.GET("/api/products/{id}/external-knowledge/{entryId}/pages",{params:{path:{id:e,entryId:n}}})}async createPlan(e){return await this.client.POST("/api/plans",{body:e})}async getPlan(e){return await this.client.GET("/api/plans/{id}",{params:{path:{id:e}}})}async getAdminPlan(e){return await this.client.GET("/api/admin/plans/{id}",{params:{path:{id:e}}})}async getAdminPlanMeetAppToken(e){return await this.client.GET("/api/admin/plans/{id}/meet-app-token",{params:{path:{id:e}}})}async setAdminPlanMeetAppToken(e,n){return await this.client.POST("/api/admin/plans/{id}/meet-app-token",{params:{path:{id:e}},body:n})}async getPlanAnalytics(e,n,i){return await this.client.GET("/api/plans/{id}/analytics",{params:{path:{id:e},query:{...n&&{start_date:n},...i&&{end_date:i}}}})}async replacePlan(e,n){return await this.client.PUT("/api/plans/{id}",{params:{path:{id:e}},body:n})}async updatePlan(e,n){return await this.client.PATCH("/api/plans/{id}",{params:{path:{id:e}},body:n})}async getPlanVideoUrl(e){return await this.client.GET("/api/plans/{id}/video-url",{params:{path:{id:e}}})}async getPlanVideoMetadata(e){return await this.client.GET("/api/plans/{id}/video-metadata",{params:{path:{id:e}}})}async deletePlan(e){return await this.client.DELETE("/api/admin/plans/{id}",{params:{path:{id:e}}})}async duplicatePlan(e){return await this.client.POST("/api/plans/{id}/duplicate",{params:{path:{id:e}}})}async listAdminUsers(e){const n={};return e!=null&&e.search&&(n.search=e.search),e!=null&&e.page&&(n.page=e.page),e!=null&&e.limit&&(n.limit=e.limit),await this.client.GET("/api/admin/users",{params:Object.keys(n).length>0?{query:n}:void 0})}async createAdminUser(e){return await this.client.POST("/api/users",{body:e})}async publishPlanRevision(e,n){return await this.client.POST("/api/plans/{id}/publish",{params:{path:{id:e}},body:n})}async getPlanAutosave(e){return await this.client.GET("/api/plans/{id}/autosave",{params:{path:{id:e}}})}async upsertPlanAutosave(e,n,i){return await this.client.PUT("/api/plans/{id}/autosave",{params:{path:{id:e}},body:n,signal:i})}async deletePlanAutosave(e){return await this.client.DELETE("/api/plans/{id}/autosave",{params:{path:{id:e}}})}async listPlanRevisions(e){return await this.client.GET("/api/plans/{id}/revisions",{params:{path:{id:e}}})}async listPlanKnowledgeBlocks(e){return await this.client.GET("/api/plans/{id}/knowledge-blocks",{params:{path:{id:e}}})}async createPlanKnowledgeBlock(e,n){return await this.client.POST("/api/plans/{id}/knowledge-blocks",{params:{path:{id:e}},body:n})}async updatePlanKnowledgeBlock(e,n,i){return await this.client.PUT("/api/plans/{id}/knowledge-blocks/{blockId}",{params:{path:{id:e,blockId:n}},body:i})}async deletePlanKnowledgeBlock(e,n){return await this.client.DELETE("/api/plans/{id}/knowledge-blocks/{blockId}",{params:{path:{id:e,blockId:n}}})}async getPlanNavigationIndex(e){return await this.client.GET("/api/plans/{id}/navigation-index",{params:{path:{id:e}}})}async replacePlanNavigationIndex(e,n){return await this.client.POST("/api/plans/{id}/navigation-index",{params:{path:{id:e}},body:{content:n.content||""}})}async getRevisionNavigationIndex(e){return await this.client.GET("/api/revisions/{id}/navigation-index",{params:{path:{id:e}}})}async replaceRevisionNavigationIndex(e,n){return await this.client.PUT("/api/revisions/{id}/navigation-index",{params:{path:{id:e}},body:n})}async getPlanFAQ(e){return await this.client.GET("/api/plans/{id}/faq",{params:{path:{id:e}}})}async listPlanFAQs(e,n=!1){return await this.client.GET("/api/plans/{id}/faqs",{params:{path:{id:e},query:{include_drafts:String(n)}}})}async listPlanDraftFAQs(e){return await this.client.GET("/api/plans/{id}/draft-faqs",{params:{path:{id:e}}})}async getRevisionFAQ(e){return await this.client.GET("/api/revisions/{id}/faq",{params:{path:{id:e}}})}async replaceRevisionFAQ(e,n){return await this.client.PUT("/api/revisions/{id}/faq",{params:{path:{id:e}},body:n})}async listRevisionFAQs(e,n){return await this.client.GET("/api/revisions/{id}/faqs",{params:{path:{id:e},query:{...n!==void 0&&{include_drafts:n.toString()}}}})}async createRevisionFAQ(e,n){return await this.client.POST("/api/revisions/{id}/faqs",{params:{path:{id:e}},body:n})}async updateFAQ(e,n){return await this.client.PUT("/api/faqs/{id}",{params:{path:{id:e}},body:n})}async deleteFAQ(e){return await this.client.DELETE("/api/faqs/{id}",{params:{path:{id:e}}})}async promoteFAQ(e){return await this.client.POST("/api/faqs/{id}/promote",{params:{path:{id:e}}})}async promoteFAQs(e){return await this.client.POST("/api/faqs/promote",{body:{faq_ids:e}})}async listRevisionKnowledgeBlocks(e){return await this.client.GET("/api/revisions/{id}/knowledge-blocks",{params:{path:{id:e}}})}async getRevisionSteps(e){return await this.client.GET("/api/revisions/{id}/steps",{params:{path:{id:e}}})}async replaceRevisionKnowledgeBlocks(e,n){return await this.client.PUT("/api/revisions/{id}/knowledge-blocks",{params:{path:{id:e}},body:n})}async createRevisionKnowledgeBlock(e,n){return await this.client.POST("/api/revisions/{id}/knowledge-blocks",{params:{path:{id:e}},body:n})}async updateRevisionKnowledgeBlock(e,n,i){return await this.client.PUT("/api/revisions/{id}/knowledge-blocks/{blockId}",{params:{path:{id:e,blockId:n}},body:i})}async deleteRevisionKnowledgeBlock(e,n){return await this.client.DELETE("/api/revisions/{id}/knowledge-blocks/{blockId}",{params:{path:{id:e,blockId:n}}})}async listSessions(e,n){const i={token:e};return n!=null&&n.productId&&(i.product_id=n.productId),n!=null&&n.startDate&&(i.start_date=n.startDate),n!=null&&n.endDate&&(i.end_date=n.endDate),await this.client.GET("/api/sessions",{params:{query:i}})}async createSession(e){return await this.client.POST("/api/sessions",{body:e})}async getSession(e){return await this.client.GET("/api/sessions/{id}",{params:{path:{id:e}}})}async startSession(e,n){return await this.client.GET("/api/sessions/{id}/start-session",{params:{path:{id:e},query:{token:n}}})}async getSessionRecording(e){return await this.client.GET("/api/sessions/{id}/recording",{params:{path:{id:e}}})}async getSessionSummary(e){return await this.client.GET("/api/sessions/{id}/summary",{params:{path:{id:e}}})}async getSessionProductUrl(e){return await this.client.GET("/api/sessions/{id}/product-url",{params:{path:{id:e}}})}async listUserSessions(e){const n={};return e!=null&&e.productId&&(n.product_id=e.productId),e!=null&&e.courseId&&(n.course_id=e.courseId),e!=null&&e.startDate&&(n.start_date=e.startDate),e!=null&&e.endDate&&(n.end_date=e.endDate),e!=null&&e.page&&(n.page=e.page),e!=null&&e.limit&&(n.limit=e.limit),e!=null&&e.courseName&&(n.course_name=e.courseName),e!=null&&e.userName&&(n.user_name=e.userName),e!=null&&e.company&&(n.company=e.company),e!=null&&e.email&&(n.email=e.email),e!=null&&e.sortBy&&(n.sort_by=e.sortBy),e!=null&&e.sortOrder&&(n.sort_order=e.sortOrder),await this.client.GET("/api/user-sessions",{params:Object.keys(n).length>0?{query:n}:void 0})}async listUserSessionsAggregate(e){const n={};return e!=null&&e.productId&&(n.product_id=e.productId),e!=null&&e.courseId&&(n.course_id=e.courseId),e!=null&&e.startDate&&(n.start_date=e.startDate),e!=null&&e.endDate&&(n.end_date=e.endDate),await this.client.GET("/api/user-sessions-aggregate",{params:Object.keys(n).length>0?{query:n}:void 0})}async queryTranscriptChat(e){return await this.client.POST("/api/performance/transcript-chat",{body:e})}streamTranscriptChat(e,n={},i={}){var s;const r=new AbortController,a=()=>{var l;return r.abort((l=i.signal)==null?void 0:l.reason)};(s=i.signal)!=null&&s.aborted?r.abort(i.signal.reason):i.signal&&i.signal.addEventListener("abort",a);const o=this.runTranscriptChatStream(e,n,r);return i.signal&&o.finally(()=>{var l;return(l=i.signal)==null?void 0:l.removeEventListener("abort",a)}),{cancel:()=>r.abort(),close:()=>r.abort(),signal:r.signal,closed:o}}async runTranscriptChatStream(e,n,i){const r=h=>{var p,b,m,S,g,y;switch((p=n.onEvent)==null||p.call(n,h),h.type){case"started":(b=n.onStarted)==null||b.call(n,h.data);break;case"batch_complete":(m=n.onBatchComplete)==null||m.call(n,h.data);break;case"answer_chunk":(S=n.onAnswerChunk)==null||S.call(n,h.data);break;case"completed":(g=n.onCompleted)==null||g.call(n,h.data);break;case"error":(y=n.onError)==null||y.call(n,h.data);break}},a=h=>{r({type:"error",data:h})};let o;try{o=await this.client.POST("/api/performance/transcript-chat/stream",{body:e,parseAs:"stream",signal:i.signal})}catch(h){throw console.error("[TranscriptChat] Network error:",h),a(Zr(h,0,"network_error",`Failed to start transcript chat stream: ${h instanceof Error?h.message:String(h)}`)),h}const s=o.response;if(!s){console.error("[TranscriptChat] No response object"),a(Zr(null,0,"no_response","No response returned from transcript chat"));return}if(s.status,s.statusText,s.headers.get("Content-Type"),!s.ok){const h=await uk(s);console.error("[TranscriptChat] HTTP error:",{status:s.status,payload:h}),a(Zr(h??o.error,s.status,"http_error",`Transcript chat stream failed with status ${s.status}`));return}const l=s.headers.get("Content-Type")||"";if(!l.toLowerCase().includes("text/event-stream")){const h=await uk(s);console.error("[TranscriptChat] Invalid content type:",l),a(Zr(h??o.error,s.status,"invalid_content_type","Transcript chat stream did not return an event stream"));return}if(!s.body){console.error("[TranscriptChat] Response body is null"),a(Zr(null,s.status,"stream_unavailable","Streaming is not supported by this environment"));return}const c=s.body.getReader(),u=new TextDecoder;let d="";try{for(;;){const{value:h,done:p}=await c.read();d+=u.decode(h||new Uint8Array,{stream:!p});const b=d.split(`
43
43
 
44
44
  `);d=b.pop()??"";for(const m of b){const S=dk(m);if(!S)continue;let g;try{g=S.data?JSON.parse(S.data):void 0}catch(x){throw console.error("[TranscriptChat] Failed to parse SSE event:",{event:S.event,data:S.data,error:x}),a(Zr(x,s.status,"stream_parse_error",`Failed to parse transcript chat stream event: ${S.event}`)),x}const y=hk(S.event,g);if(!y){console.warn("[TranscriptChat] Unknown event type received:",S.event,g);continue}if(y.type,y.data,r(y),y.type==="error")return}if(p){if(d.trim()){const m=dk(d);if(m){let S;try{S=m.data?JSON.parse(m.data):void 0}catch(y){throw console.error("[TranscriptChat] Failed to parse final SSE event:",{event:m.event,data:m.data,error:y}),a(Zr(y,s.status,"stream_parse_error",`Failed to parse final transcript chat stream event: ${m.event}`)),y}const g=hk(m.event,S);g&&(g.type,g.data,r(g))}}return}}}catch(h){if(!i.signal.aborted)throw console.error("[TranscriptChat] Stream error:",h),a(Zr(h,s.status,"stream_error",`Transcript chat stream failed: ${h instanceof Error?h.message:String(h)}`)),h}finally{c.releaseLock()}}async getJoinToken(e,{clientType:n,user:i}={}){return await this.client.GET("/api/join-token",{params:{query:{token:e,...n&&{client_type:n},...i&&{user:encodeURIComponent(i)}}}})}async getSessionPlan(e){return await this.client.GET("/api/sessions/{id}/plan",{params:{path:{id:e}}})}async getPlanSDK(e){return await this.client.GET("/api/plans/{uuid}/sdk",{params:{path:{uuid:e}}})}async getGraphemes(){return await this.client.GET("/api/graphemes")}async listVoices(){return await this.client.GET("/api/voices")}async generateVoiceSample(e,n){return await this.client.POST("/api/voices/generate-sample",{body:{product_id:n,voice_id:e},parseAs:"stream"})}async getFeatureFlags(e){return await this.client.GET("/api/features",{params:e?{query:e}:void 0})}getClient(){return this.client}}async function uk(t){try{return await t.clone().json()}catch{return null}}function Zr(t,e,n,i){const r=typeof t=="object"&&t!==null?t:{},a=Wa(r.status_code??r.statusCode??r.status)??(typeof e=="number"?e:0),o=typeof r.code=="string"?r.code:typeof r.error=="string"?r.error:n,s=typeof r.message=="string"?r.message:i,l=r.details;return{statusCode:a,code:o,message:s,details:l,raw:t??void 0}}function dk(t){const e=t.split(/\r?\n/);let n="";const i=[];for(const r of e){const a=r.trimEnd();!a||a.startsWith(":")||(a.startsWith("event:")?n=a.slice(6).trim():a.startsWith("data:")&&i.push(a.slice(5).trim()))}return!n||i.length===0?null:{event:n,data:i.join(`
45
- `)}}function hk(t,e){switch(t){case"started":return{type:"started",data:zP(e)};case"batch_complete":return{type:"batch_complete",data:FP(e)};case"answer_chunk":return{type:"answer_chunk",data:qP(e)};case"completed":return{type:"completed",data:HP(e)};case"error":return{type:"error",data:Zr(e,0,"stream_error","Transcript chat stream error")};default:return null}}function zP(t){return{sessionCount:Wa((t==null?void 0:t.sessionCount)??(t==null?void 0:t.SessionCount))??0,batchCount:Wa((t==null?void 0:t.batchCount)??(t==null?void 0:t.BatchCount))??0,timeframe:typeof((t==null?void 0:t.timeframe)??(t==null?void 0:t.Timeframe))=="string"?t.timeframe??t.Timeframe:void 0}}function FP(t){return{batchNumber:Wa((t==null?void 0:t.batchNumber)??(t==null?void 0:t.BatchNumber))??0,totalBatches:Wa((t==null?void 0:t.totalBatches)??(t==null?void 0:t.TotalBatches))??0,sessionsInBatch:Wa((t==null?void 0:t.sessionsInBatch)??(t==null?void 0:t.SessionsInBatch))??0}}function qP(t){return{content:typeof(t==null?void 0:t.content)=="string"?t.content:typeof(t==null?void 0:t.Content)=="string"?t.Content:""}}function HP(t){const e=fk((t==null?void 0:t.sessionUuids)??(t==null?void 0:t.SessionUUIDs)),n=fk((t==null?void 0:t.mapSummaries)??(t==null?void 0:t.MapSummaries));return{answer:typeof(t==null?void 0:t.answer)=="string"?t.answer:typeof(t==null?void 0:t.Answer)=="string"?t.Answer:"",sessionCount:Wa((t==null?void 0:t.sessionCount)??(t==null?void 0:t.SessionCount))??0,sessionUuids:e,batchCount:Wa((t==null?void 0:t.batchCount)??(t==null?void 0:t.BatchCount))??void 0,model:typeof(t==null?void 0:t.model)=="string"?t.model:typeof(t==null?void 0:t.Model)=="string"?t.Model:void 0,mapSummaries:n}}function Wa(t){if(typeof t=="number"&&!Number.isNaN(t))return t;if(typeof t=="string"&&t.trim()!==""){const e=Number(t);if(!Number.isNaN(e))return e}}function fk(t){if(Array.isArray(t))return t.map(e=>String(e))}const pk="https://app.coragents.ai";class vh extends _p{constructor(e,n,i,r){super(),this.state=null,this.isPaused=!1,this.preferredMicrophoneDeviceId=null,this.isAudioTrackPublished=!1,this.speakingState=null,this.captureScreen=null,this.sessionUuid=null,this.roomId=null,this.joinToken=null,this.roomUrl=null,this.room=null,this.startedAt=null,this.isMultilingual=!1,this.languageCodes=null,this.defaultLanguageCode=null,this.voiceId=null,this.selectedLanguage=null,this.agentAnalyser=null,this.userAnalyser=null,this.agentAudioContext=null,this.userAudioContext=null,this.frequencyDataBuffer=null,this.humanJoinAcked=!1,this.humanJoinRetryTimeout=null,this.humanJoinRetryCount=0,this.humanJoinInFlight=!1,this.humanJoinPayload=null,this.chatMessages=[],this.publishedAudioStream=null,this.publishedAudioTrack=null,this.transcriptionStreams=[],this.appToken=e,this.planId=n,this.clientType=i,this.api=r.api||new ck({baseUrl:pk}),this.identity=r.identity||null,this.roomFactory=r.roomFactory||(a=>new zs(a)),this.captureScreen=r.captureScreen||null,this.preferredMicrophoneDeviceId=r.preferredMicrophoneDeviceId||null}async start(e){this.planId,e==null||e.roomId,this.setState("connecting"),this.speakingStateChanged("thinking");try{const i=(await this.api.clientStartSession(this.appToken,{client_type:this.clientType,...this.planId&&{onboarding_plan:this.planId},...this.planId&&(e==null?void 0:e.roomId)&&{room_id:e.roomId}})).data;if(!(i!=null&&i.url)||!(i!=null&&i.token)||!(i!=null&&i.room)||!(i!=null&&i.session_uuid))throw new Error("Invalid room info");this.sessionUuid=i==null?void 0:i.session_uuid,this.roomId=i==null?void 0:i.room,this.joinToken=i==null?void 0:i.token,this.roomUrl=i==null?void 0:i.url,this.startedAt=Date.now(),this.isMultilingual=(i==null?void 0:i.is_multilingual)||!1,this.languageCodes=(i==null?void 0:i.language_codes)||null,this.defaultLanguageCode=(i==null?void 0:i.default_language_code)||null,this.voiceId=(i==null?void 0:i.voice_id)||null,await this.joinRoom({withMicrophone:e==null?void 0:e.withMicrophone}),this.setState("volume-check"),this.planId,this.sessionUuid}catch(n){console.error("[obi] error starting session",{error:n}),this.setState("error")}}async joinRoom({withMicrophone:e=!1,withStateRecovery:n=!1}={}){if(this.room=this.roomFactory({adaptiveStream:!0,dynacast:!0}),this.resetHumanJoinHandshake(),this.room.on(Q.Disconnected,i=>{if(!this.room)return;this.transcriptionStreams=[],this.emit("captions",[]);let r=null;switch(i){case 12:r="invalid-room";break}this.shutdown(r)}),this.room.on(Q.TrackSubscribed,i=>{if(console.info("[obi] track subscribed kind=",i.kind,"source=",i.source),i.kind==="audio"&&(i.attach(),i.source===V.Source.Microphone)){this.agentAnalyser&&(this.agentAnalyser.disconnect(),this.agentAnalyser=null),this.agentAudioContext&&(this.agentAudioContext.close(),this.agentAudioContext=null);const{analyser:r,context:a}=this.createFFT(i.mediaStream);this.agentAnalyser=r,this.agentAudioContext=a}}),this.room.on(Q.LocalTrackPublished,i=>{if(console.info("[obi] local track published kind=",i.kind,"source=",i.source),i.kind==="audio"){this.userAnalyser&&(this.userAnalyser.disconnect(),this.userAnalyser=null),this.userAudioContext&&(this.userAudioContext.close(),this.userAudioContext=null);const{analyser:r,context:a}=this.createFFT(i.audioTrack.mediaStream);this.userAnalyser=r,this.userAudioContext=a}}),this.room.on(Q.ParticipantAttributesChanged,i=>{if(!i["lk.agent.state"])return;const r=i["lk.agent.state"];switch(r){case"speaking":this.speakingStateChanged("speaking");break;case"listening":this.speakingStateChanged("listening");break;case"thinking":this.speakingStateChanged("thinking");break;default:console.warn("[obi] unknown speaking state",r)}}),this.room.on(Q.DataReceived,async i=>{try{const r=new TextDecoder().decode(i),a=JSON.parse(r);switch(a.status||a.request||a.type){case"course_progress":typeof a.current_step=="number"&&typeof a.total_steps=="number"&&Array.isArray(a.step_names)&&this.emit("courseProgress",{currentStep:Math.max(1,a.current_step),totalSteps:Math.max(1,a.total_steps),stepNames:a.step_names});break;case"introduction_complete":this.emit("introductionComplete");break;case"course_selection":if(Array.isArray(a.courses)){const s=a.courses.map(l=>{if(typeof(l==null?void 0:l.uuid)!="string"||typeof(l==null?void 0:l.name)!="string")return console.warn("[obi] skipping invalid course in course_selection",l),null;const c={uuid:l.uuid,name:l.name};return typeof l.description=="string"&&(c.description=l.description),typeof l.overview=="string"&&(c.overview=l.overview),typeof l.goal=="string"&&(c.goal=l.goal),typeof l.agent_type=="string"&&(c.agent_type=l.agent_type),typeof l.duration=="number"&&(c.duration=l.duration),typeof l.order=="number"&&(c.order=l.order),typeof l.completed=="boolean"&&(c.completed=l.completed),c}).filter(l=>l!==null);this.emit("courseSelection",{courses:s})}break;case"open_text_input":this.emit("textInputRequested");break;case"using_tool":this.speakingStateChanged("busy");break;case"using_tool_ended":this.speakingStateChanged("speaking");break;case"prompt_user":this.setState("volume-check");break;case"mic_check":this.setState("mic-check");break;case"share_mic":this.setState("mic-share");break;case"share_screen":this.setState("screen-share");break;case"navigate":this.setState("navigate");break;case"in_progress":this.setState("in-progress");break;case"shutdown":this.shutdown("server-sent");break;case"mute_microphone":this.muteMicrophone();break;case"unmute_microphone":this.unmuteMicrophone();break;case"transcript":this.emit("transcript",a.transcript,a.role);break;case"screen_capture":this.captureScreenshareFrame().then(s=>{this.emit("screenCaptureNotification",s)}).catch(s=>{console.error("[obi] failed to capture screenshare frame on notification",s),this.emit("screenCaptureNotification",null)});break;case"human_joined_ack":this.handleHumanJoinedAck();break;default:console.warn("[obi] unknown data received",a)}}catch(r){console.error("[obi] error parsing data",r)}}),this.room.localParticipant.registerRpcMethod("mic_check",async i=>(this.sessionUuid,await this.checkMicrophone()?"ok":"error")),this.room.localParticipant.registerRpcMethod("screen_capture",async i=>{if(!this.captureScreen)return console.error("[obi] no captureScreen function provided"),"error";let r=null,a=null;try{r=await this.captureScreen()}catch(o){r=null,a=o}if(!r||a)return console.error("[obi] error capturing screen",{error:a}),"error";try{return await this.room.localParticipant.sendFile(new File([r],"screen_capture.png",{type:"image/png"}),{mimeType:"image/png",topic:"screen_capture"}),this.emit("screenCaptured",r),"ok"}catch(o){return console.error("[obi] error sending screen capture",{error:o}),"error"}}),this.room.localParticipant.registerRpcMethod("send_chat_message",async i=>{var r,a;try{const o=i!=null&&i.payload?JSON.parse(i.payload):{},s=typeof(o==null?void 0:o.message)=="string"&&o.message.trim().length>0?o.message.trim():null;if(!s)return console.warn("[obi] received send_chat_message with empty payload"),"error";const l=typeof o.timestamp=="number"&&!Number.isNaN(o.timestamp)?o.timestamp:Date.now();let c=null,u=null;const d=(r=this.room)==null?void 0:r.remoteParticipants.get("agent-avatar");if(d)c=d.identity,u=d.name??null;else if(this.room){for(const p of this.room.remoteParticipants.values())if((a=p.identity)!=null&&a.startsWith("agent-")){c=p.identity,u=p.name??null;break}}const h=typeof o.sender_name=="string"&&o.sender_name.trim().length>0?o.sender_name.trim():u||"Agent";return this.appendChatMessage({id:typeof o.id=="string"&&o.id.length>0?o.id:`agent-${i.requestId||Date.now()}`,timestamp:l,message:s,from:{identity:c||"agent-avatar",name:h},attributes:{senderName:h,source:"agent-rpc"},isAgent:!0}),"ok"}catch(o){return console.error("[obi] failed to handle send_chat_message RPC",o),"error"}}),this.room.registerTextStreamHandler("lk.transcription",async(i,r)=>{var l;const o=((l=i.info.attributes)==null?void 0:l["lk.segment_id"])||i.info.id;let s="";for await(const c of i){s+=c;const u=this.transcriptionStreams.findIndex(h=>{var m;return(((m=h.streamInfo.attributes)==null?void 0:m["lk.segment_id"])||h.streamInfo.id)===o}),d={text:s,participantInfo:{identity:r.identity},streamInfo:i.info};u>=0?this.transcriptionStreams[u]=d:this.transcriptionStreams.push(d),this.emit("captions",[...this.transcriptionStreams])}}),await this.room.connect(this.roomUrl,this.joinToken),e){this.isPaused;try{await this.room.localParticipant.setMicrophoneEnabled(!0,{deviceId:this.preferredMicrophoneDeviceId||void 0}),this.isMicShared=!0}catch(i){if(this.preferredMicrophoneDeviceId)console.warn("[obi] joinRoom: failed to set microphone with preferred device, retrying with default",i),await this.room.localParticipant.setMicrophoneEnabled(!0),this.isMicShared=!0;else throw i}this.isPaused,this.isPaused&&this.muteMicrophone()}if(n){let i=!1;for(const r of this.room.remoteParticipants.values())r.isSpeaking&&(i=!0);i?this.speakingStateChanged("speaking"):this.speakingStateChanged("listening"),this.selectedLanguage&&this.setLanguage(this.selectedLanguage).catch(r=>{console.error("[obi] failed to restore language selection",r)})}}async continue(){this.sessionUuid,this.speakingStateChanged("thinking"),await this.sendData({request:"prompt_user",success:!0})}async checkMicrophone(){let e=!1;try{e=(await navigator.permissions.query({name:"microphone"})).state==="granted"}catch(n){console.error("[obi] error checking microphone permission:",n)}return e?(this.sessionUuid,await this.room.localParticipant.setMicrophoneEnabled(!0),this.isMicShared=!0):this.sessionUuid,e&&this.clientType==="sdk"&&this.setState("in-progress"),this.emit("micCheckComplete",e),e}async shareMicrophone(){this.sessionUuid;let e=null,n=null;try{e=await this.room.localParticipant.setMicrophoneEnabled(!0,{deviceId:this.preferredMicrophoneDeviceId||void 0}),this.isMicShared=!0}catch(i){if(this.preferredMicrophoneDeviceId){console.warn("[obi] failed to share microphone with preferred device, retrying with default",i);try{e=await this.room.localParticipant.setMicrophoneEnabled(!0),this.isMicShared=!0}catch(r){n=r,this.isMicShared=!1}}else n=i,this.isMicShared=!1}e?this.sessionUuid:console.error("[obi] failed to share microphone",{error:n}),await this.sendData({request:"share_mic",success:!!e}),this.clientType==="sdk"&&this.setState("in-progress")}async shareMicrophoneFailed(){this.isMicShared=!1,await this.sendData({request:"share_mic",success:!1}),this.clientType==="sdk"&&this.setState("in-progress")}async sendHumanJoined(e){if(this.clientType!=="meet")return;const n=this.buildHumanJoinedPayload(e);if(!this.isSameHumanJoinPayload(n,this.humanJoinPayload)){if(this.humanJoinPayload=n,this.humanJoinAcked){if(this.humanJoinInFlight)return;await this.publishHumanJoinedUpdate(n);return}this.humanJoinRetryTimeout||this.humanJoinInFlight||(this.humanJoinRetryCount=0,await this.trySendHumanJoined())}}async publishAudioTrack(){if(this.sessionUuid,!this.room)return console.error("[obi] cannot publish audio track: room not connected"),!1;let e=!1;try{if(!navigator.mediaDevices||!navigator.mediaDevices.getUserMedia){const c=!!navigator.mediaDevices;return console.error("[obi] getUserMedia not available in this environment",c),!1}console.log("[obi] requesting audio track via getUserMedia");try{const c=this.preferredMicrophoneDeviceId?{deviceId:{exact:this.preferredMicrophoneDeviceId}}:!0;this.publishedAudioStream=await navigator.mediaDevices.getUserMedia({audio:c})}catch(c){if(this.preferredMicrophoneDeviceId)console.warn("[obi] failed to get user media with preferred device, retrying with default",c),this.publishedAudioStream=await navigator.mediaDevices.getUserMedia({audio:!0});else throw c}const n=this.publishedAudioStream.getAudioTracks().map(c=>{var u,d;return{id:c.id,label:c.label,enabled:c.enabled,muted:c.muted,readyState:c.readyState,constraints:(u=c.getConstraints)==null?void 0:u.call(c),settings:(d=c.getSettings)==null?void 0:d.call(c)}});console.log("[obi] getUserMedia resolved",n);const i=this.publishedAudioStream.getAudioTracks()[0];if(!i){const c=this.publishedAudioStream.getAudioTracks().length;return console.warn("[obi] no audio track found from getUserMedia stream",c),!1}this.publishedAudioTrack=i;const r={id:i.id,label:i.label,kind:i.kind,readyState:i.readyState},a=this.room.localParticipant.identity;console.log("[obi] publishing audio track to LiveKit",r,a);const o=await this.room.localParticipant.publishTrack(i,{name:"microphone",source:V.Source.Microphone});console.log("[obi] published audio track to LiveKit",i.id,a,o.isEnabled),this.userAnalyser&&(this.userAnalyser.disconnect(),this.userAnalyser=null),this.userAudioContext&&(this.userAudioContext.close(),this.userAudioContext=null);const{analyser:s,context:l}=this.createFFT(this.publishedAudioStream);this.userAnalyser=s,this.userAudioContext=l,this.isAudioTrackPublished=!0,e=!0}catch(n){if(console.error("[obi] failed to publish audio track",n),this.isAudioTrackPublished=!1,this.publishedAudioStream){try{this.publishedAudioStream.getTracks().forEach(i=>i.stop())}catch(i){console.warn("[obi] error stopping tracks during cleanup",i)}this.publishedAudioStream=null}this.publishedAudioTrack=null}return e}async setScreenShareEnabled(e){var i,r;if(this.sessionUuid,this.room,(i=this.room)==null||i.state,!this.room){console.warn("[obi] cannot set screen share: room not connected");return}const n=await this.room.localParticipant.setScreenShareEnabled(e,e?{video:{displaySurface:"window"}}:void 0);if(e&&n){const a=n.track,o=a==null?void 0:a.mediaStreamTrack;console.info("[obi] screen share track published",{trackSid:n.trackSid,trackName:n.trackName,source:n.source,isEnabled:n.isEnabled,isMuted:n.isMuted,isSubscribed:n.isSubscribed,mediaTrackEnabled:o==null?void 0:o.enabled,mediaTrackMuted:o==null?void 0:o.muted,mediaTrackReadyState:o==null?void 0:o.readyState,mediaTrackLabel:o==null?void 0:o.label,mediaTrackContentHint:o==null?void 0:o.contentHint,videoSettings:(r=o==null?void 0:o.getSettings)==null?void 0:r.call(o)})}await this.sendData({request:"share_screen",success:e}),e&&this.setState("navigate")}async shareScreen(){this.sessionUuid,await this.setScreenShareEnabled(!0)}async captureScreenshareFrame(){if(!this.room)return console.warn("[obi] cannot capture screenshare frame: no room"),null;const e=this.room.localParticipant.getTrackPublications();let n=null;for(const i of e)if(i.kind==="video"&&i.source===V.Source.ScreenShare&&i.track){n=i.track.mediaStreamTrack;break}if(!n)return console.warn("[obi] no screenshare track found to capture frame from"),null;try{const i=document.createElement("video");i.srcObject=new MediaStream([n]),i.muted=!0,await new Promise((s,l)=>{i.onloadedmetadata=()=>s(),i.onerror=()=>l(new Error("Failed to load video metadata")),setTimeout(()=>l(new Error("Video metadata load timeout")),5e3)}),await i.play();const r=document.createElement("canvas");r.width=i.videoWidth,r.height=i.videoHeight;const a=r.getContext("2d");if(!a)return console.error("[obi] failed to get canvas context"),null;a.drawImage(i,0,0,r.width,r.height);const o=r.toDataURL("image/png");return i.pause(),i.srcObject=null,r.width,r.height,o.length,o}catch(i){return console.error("[obi] failed to capture screenshare frame",i),null}}async pause(){this.muteMicrophone(),this.isPaused=!0,this.emit("paused"),await this.sendData({request:"pause"}),console.log("[obi] paused session",{sessionUuid:this.sessionUuid})}async unpause(){this.unmuteMicrophone(),this.isPaused=!1,this.emit("unpaused"),await this.sendData({request:"unpause"}),console.log("[obi] unpaused session",{sessionUuid:this.sessionUuid})}async endCourse(){await this.sendData({request:"end_course"})}async switchMicrophoneDevice(e){var n;if(this.sessionUuid,this.room,(n=this.room)==null||n.state,this.isMicShared,!this.room)return console.warn("[obi] cannot switch microphone device: room not connected"),!1;try{const i=await this.room.switchActiveDevice("audioinput",e);return i?(this.preferredMicrophoneDeviceId=e,this.sessionUuid):console.warn("[obi] failed to switch microphone device",{deviceId:e}),i}catch(i){return console.error("[obi] error switching microphone device",{err:i,deviceId:e}),!1}}muteMicrophone(){this.sessionUuid,this.room.localParticipant.getTrackPublications().forEach(e=>{var n,i;e.kind==="audio"&&e.source===V.Source.Microphone&&(e.handleMuted(),(i=(n=e.track)==null?void 0:n.mediaStream)==null||i.getTracks().forEach(r=>r.enabled=!1))})}unmuteMicrophone(){this.sessionUuid,this.room.localParticipant.getTrackPublications().forEach(e=>{var n,i;e.kind==="audio"&&e.source===V.Source.Microphone&&(e.handleUnmuted(),(i=(n=e.track)==null?void 0:n.mediaStream)==null||i.getTracks().forEach(r=>r.enabled=!0))})}async stop(){this.emit("stopped"),await this.shutdown()}async shutdown(e=null){if(this.resetHumanJoinHandshake({clearPayload:!0}),this.room){if(this.sessionUuid,this.publishedAudioTrack&&this.isAudioTrackPublished)try{console.log("[obi] unpublishing audio track",this.publishedAudioTrack.id,this.room.localParticipant.identity),this.room.localParticipant.unpublishTrack(this.publishedAudioTrack)}catch(i){console.warn("[obi] failed to unpublish audio track",i)}if(this.publishedAudioStream)try{const i=this.publishedAudioStream.getAudioTracks().length;console.log("[obi] stopping published audio stream tracks",i),this.publishedAudioStream.getTracks().forEach(r=>r.stop())}catch(i){console.warn("[obi] error stopping published audio tracks",i)}try{this.room.unregisterTextStreamHandler("lk.transcription")}catch(i){console.warn("[obi] failed to unregister text stream handler",i)}e!=="server-sent"&&await this.sendData({request:"shutdown"});const n=this.room;this.room=null,await n.disconnect(),this.sessionUuid}this.transcriptionStreams=[],this.agentAnalyser&&(this.agentAnalyser.disconnect(),this.agentAnalyser=null),this.agentAudioContext&&(this.agentAudioContext.close(),this.agentAudioContext=null),this.userAnalyser&&(this.userAnalyser.disconnect(),this.userAnalyser=null),this.userAudioContext&&(this.userAudioContext.close(),this.userAudioContext=null),this.isAudioTrackPublished=!1,this.publishedAudioStream=null,this.publishedAudioTrack=null,this.clearChatMessages(),this.sessionUuid=null,this.roomId=null,this.joinToken=null,this.roomUrl=null,this.frequencyDataBuffer=null,this.emit("shutdown",e)}async say(e){this.speakingStateChanged("thinking"),this.isPaused&&await this.unpause(),await this.sendData({request:"say",message:e})}async startAma(){await this.sendData({request:"start_ama"})}appendChatMessage(e){const n={...e,from:e.from?{...e.from}:e.from,attributes:e.attributes?{...e.attributes}:e.attributes};this.chatMessages=[...this.chatMessages,n],this.emit("chatMessagesChanged",[...this.chatMessages]),this.emit("chatMessageReceived",n)}clearChatMessages(){this.chatMessages.length&&(this.chatMessages=[],this.emit("chatMessagesChanged",[]))}async setLanguage(e){var n;this.selectedLanguage=e,(n=this.room)!=null&&n.localParticipant&&await this.sendData({request:"set_language",language_code:e})}serialise(){return JSON.stringify({state:this.state,speakingState:this.speakingState,appToken:this.appToken,planId:this.planId,clientType:this.clientType,isPaused:this.isPaused,identity:this.identity,sessionUuid:this.sessionUuid,roomId:this.roomId,joinToken:this.joinToken,roomUrl:this.roomUrl,startedAt:this.startedAt,isMultilingual:this.isMultilingual,languageCodes:this.languageCodes,defaultLanguageCode:this.defaultLanguageCode,voiceId:this.voiceId,selectedLanguage:this.selectedLanguage,preferredMicrophoneDeviceId:this.preferredMicrophoneDeviceId,chatMessages:this.chatMessages.map(e=>({...e,from:e.from?{...e.from}:e.from,attributes:e.attributes?{...e.attributes}:e.attributes}))})}audioSpectrum(){return this.speakingState==="speaking"&&this.agentAnalyser?this.normaliseSpectrum(this.agentAnalyser):this.speakingState==="listening"&&this.userAnalyser?this.normaliseSpectrum(this.userAnalyser):null}agentAudioSpectrum(){return this.agentAnalyser?this.normaliseSpectrum(this.agentAnalyser):null}normaliseSpectrum(e){const i=e.context.sampleRate/2/e.frequencyBinCount;(!this.frequencyDataBuffer||this.frequencyDataBuffer.length!==e.frequencyBinCount)&&(this.frequencyDataBuffer=new Uint8Array(new ArrayBuffer(e.frequencyBinCount))),e.getByteFrequencyData(this.frequencyDataBuffer);const r=[],a=50,o=5e3,s=8,l=Math.pow(o/a,1/s);for(let c=0;c<s;c++){const u=a*Math.pow(l,c),d=a*Math.pow(l,c+1),h=Math.floor(u/i),p=Math.floor(d/i),b=Math.min(p,this.frequencyDataBuffer.length),m=Math.min(h,b);if(m<b){let S=0;for(let y=m;y<b;y++)S+=this.frequencyDataBuffer[y];const g=S/(b-m)/255;r.push(g)}else r.push(0)}return r}setState(e){this.state;const n=this.state;this.state=e,this.emit("stateChanged",e,n)}static deserialise(e,n,i,r={}){const a=JSON.parse(e),o=new vh(n,a.planId,i,r);return o.state=a.state,o.speakingState=a.speakingState,o.identity=a.identity||null,o.isPaused=a.isPaused||!1,o.sessionUuid=a.sessionUuid||null,o.roomId=a.roomId||null,o.joinToken=a.joinToken||null,o.roomUrl=a.roomUrl||null,o.startedAt=a.startedAt||null,o.isMultilingual=a.isMultilingual||!1,o.languageCodes=a.languageCodes||null,o.defaultLanguageCode=a.defaultLanguageCode||null,o.voiceId=a.voiceId||null,o.selectedLanguage=a.selectedLanguage||null,o.preferredMicrophoneDeviceId=a.preferredMicrophoneDeviceId||r.preferredMicrophoneDeviceId||null,o.chatMessages=(a.chatMessages||[]).map(s=>({...s,from:s.from?{...s.from}:s.from,attributes:s.attributes?{...s.attributes}:s.attributes})),o}buildHumanJoinedPayload(e){const n={request:"human_joined"};return e!=null&&e.name&&e.name.trim().length>0&&(n.name=e.name.trim()),e!=null&&e.email&&e.email.trim().length>0&&(n.email=e.email.trim()),typeof(e==null?void 0:e.screenShareSupported)=="boolean"&&(n.screen_share_supported=e.screenShareSupported),n}isSameHumanJoinPayload(e,n){return!e||!n?!1:(e.name??void 0)===(n.name??void 0)&&(e.email??void 0)===(n.email??void 0)&&e.screen_share_supported===n.screen_share_supported}async trySendHumanJoined(){if(this.clientType!=="meet"||this.humanJoinAcked||this.humanJoinInFlight)return;if(this.humanJoinInFlight=!0,!this.room||this.room.state!==Xe.Connected||!this.room.localParticipant){this.humanJoinInFlight=!1,this.scheduleHumanJoinRetry();return}const e=this.humanJoinPayload||{request:"human_joined"};try{await this.room.localParticipant.publishData(new TextEncoder().encode(JSON.stringify(e)),{reliable:!0})}catch(n){console.warn("[obi] failed to publish human_joined message",n)}finally{this.humanJoinInFlight=!1}this.humanJoinAcked||this.scheduleHumanJoinRetry()}async publishHumanJoinedUpdate(e){if(!(!this.room||this.room.state!==Xe.Connected||!this.room.localParticipant)){this.humanJoinInFlight=!0;try{await this.room.localParticipant.publishData(new TextEncoder().encode(JSON.stringify(e)),{reliable:!0})}catch(n){console.warn("[obi] failed to publish human_joined message",n)}finally{this.humanJoinInFlight=!1}}}scheduleHumanJoinRetry(){if(this.humanJoinAcked||this.humanJoinRetryTimeout)return;const e=Math.min(500*Math.pow(2,this.humanJoinRetryCount),5e3);this.humanJoinRetryCount+=1,this.humanJoinRetryTimeout=setTimeout(()=>{this.humanJoinRetryTimeout=null,this.trySendHumanJoined()},e)}clearHumanJoinRetryTimer(){this.humanJoinRetryTimeout&&(clearTimeout(this.humanJoinRetryTimeout),this.humanJoinRetryTimeout=null)}resetHumanJoinHandshake(e={}){this.clearHumanJoinRetryTimer(),this.humanJoinAcked=!1,this.humanJoinInFlight=!1,this.humanJoinRetryCount=0,e.clearPayload&&(this.humanJoinPayload=null)}handleHumanJoinedAck(){this.humanJoinAcked||(this.humanJoinAcked=!0,this.humanJoinInFlight=!1,this.humanJoinRetryCount=0,this.clearHumanJoinRetryTimer())}speakingStateChanged(e){this.speakingState;const n=this.speakingState;this.speakingState=e,this.emit("speakingStateChanged",e,n)}async sendData(e){await this.room.localParticipant.publishData(new TextEncoder().encode(JSON.stringify(e)),{reliable:!0})}createFFT(e){const n=new AudioContext,i=n.createAnalyser();return n.createMediaStreamSource(e).connect(i),i.fftSize=2048,i.smoothingTimeConstant=.6,{analyser:i,context:n}}}class bh extends _p{constructor(e,n,i={}){super(),this.state="loading",this.error=null,this.identity=null,this.product=null,this.engagement=null,this.plans=[],this.planIsCompleted=[],this.selectedPlan=null,this.selectedPlanUuid=null,this.showWidget=!1,this.session=null,this.captureScreen=null,this.preferredMicrophoneDeviceId=null,this.appToken=e,this.clientType=n,this.api=i.api||new ck({baseUrl:i.apiBaseUrl||pk}),this.sessionFactory=i.sessionFactory||((r,a,o,s)=>new vh(r,a,o,s)),this.captureScreen=i.captureScreen||null}async initialise(e={}){var n,i,r,a,o,s,l;if(!this.appToken)throw new Error("App token is required");this.setState("loading");try{const c=await this.api.clientInitialise(this.appToken,{identity:e.identity,client_type:this.clientType});this.identity=e.identity||null,this.product=((n=c.data)==null?void 0:n.product)||null,this.plans=((i=c.data)==null?void 0:i.onboarding_plans)||[],this.selectedPlan=((r=c.data)==null?void 0:r.selected_plan)||null,this.planIsCompleted=((a=c.data)==null?void 0:a.plan_is_completed)||[],this.showWidget=((o=c.data)==null?void 0:o.show_widget)||!1,this.engagement=((s=c.data)==null?void 0:s.engagement)||null;const u=((l=this.product)==null?void 0:l.track_onboardee_token)??!0;if(this.api.setTrackOnboardeeToken(u),e.planUuid){let d=null,h=!1;try{const p=await this.api.getPlanSDK(e.planUuid);if(p.error)throw new Error(`Plan not found: ${p.error}`);p.data&&(d=p.data)}catch(p){try{const b=await this.api.getSessionPlan(e.planUuid);if(b.error)throw new Error(`Session plan not found: ${b.error}`);b.data&&(d=b.data,h=!0)}catch(b){console.error("[obi] error getting plan via both endpoints",{planErr:p,sessionErr:b})}}d?(this.selectedPlan=d,this.selectedPlanUuid=h?d.uuid:e.planUuid):console.warn("[obi] plan not found",{planUuid:e.planUuid})}this.identity,this.product,this.plans,this.selectedPlan,this.showWidget}catch(c){throw this.error=c instanceof Error?c:new Error(String(c)),this.setState("error"),c}finally{this.setState("ready")}}selectPlan(e){this.selectedPlan=e,this.selectedPlanUuid=(e==null?void 0:e.uuid)||null,this.emit("planSelected",e)}setPreferredMicrophoneDeviceId(e){this.preferredMicrophoneDeviceId=e,this.session&&(this.session.preferredMicrophoneDeviceId=e)}async startSession(e,n,i){return await this._stopSession(),this.session=this.sessionFactory(this.appToken,e,this.clientType,{api:this.api,identity:this.identity,captureScreen:this.captureScreen,preferredMicrophoneDeviceId:this.preferredMicrophoneDeviceId}),this.prepareSession(n),this.session.start(i).then(()=>{this.emit("sessionStarted",this.session)}).catch(r=>{this.session=null,console.error("[obi] error starting session",r)}),this.session}async resumeSession(e){var n,i;return this.state,(n=this.session)==null||n.state,(i=this.session)==null||i.speakingState,this.session.captureScreen=this.captureScreen,this.prepareSession(e),this.session.joinRoom({withMicrophone:!0,withStateRecovery:!0}).then(()=>{this.emit("sessionResumed",this.session)}).catch(r=>{console.error("[obi] error joining room",{error:r}),r instanceof Error&&r.message==="Room is not connected"&&this.session.stop()}),this.session}prepareSession(e){if(!this.session)throw new Error("No session to prepare");return e(this.session),this.session.on("stopped",()=>{this.emit("sessionStopped")}),this.session.on("shutdown",n=>{var i,r,a;if((i=this.session)!=null&&i.startedAt&&this.session.startedAt+5*60*1e3<Date.now()){const o=this.plans.findIndex(s=>{var l;return s.uuid===((l=this.selectedPlan)==null?void 0:l.uuid)});o!==-1&&(this.planIsCompleted[o]=!0)}(a=(r=this.session)==null?void 0:r.removeAllListeners)==null||a.call(r),this.selectedPlan=null,this.selectedPlanUuid=null,this.emit("sessionShutdown",n),this.session=null}),this.session}async stopSession(){await this._stopSession(),this.selectedPlan&&this.selectPlan(null)}async _stopSession(){this.session&&(this.trackEvent("session-stopped",{sessionUuid:this.session.sessionUuid}),await this.session.stop(),this.session=null)}isLoading(){return this.state==="loading"}isReady(){return this.state==="ready"}serialise(){var e;return JSON.stringify({state:this.state,appToken:this.appToken,clientType:this.clientType,identity:this.identity,product:this.product,engagement:this.engagement,plans:this.plans,selectedPlan:this.selectedPlan,selectedPlanUuid:this.selectedPlanUuid,showWidget:this.showWidget,session:(e=this.session)==null?void 0:e.serialise(),preferredMicrophoneDeviceId:this.preferredMicrophoneDeviceId,serialisedAt:new Date().toISOString()})}static deserialise(e,n,i,r={}){const a=JSON.parse(e),o=new bh(n,i,r);return o.state=a.state,o.identity=a.identity||null,o.product=a.product||null,o.engagement=a.engagement||null,o.plans=a.plans||[],o.selectedPlan=a.selectedPlan||null,o.selectedPlanUuid=a.selectedPlanUuid||null,o.showWidget=a.showWidget||!1,o.preferredMicrophoneDeviceId=a.preferredMicrophoneDeviceId||null,a.session&&(o.session=vh.deserialise(a.session,n,i,{api:o.api,preferredMicrophoneDeviceId:o.preferredMicrophoneDeviceId})),o}setState(e){const n=this.state;this.state=e,this.emit("stateChanged",e,n)}trackEvent(e,n={}){var i,r,a;this.emit("trackEvent",e,{...n,clientType:this.clientType,planId:(i=this.selectedPlan)==null?void 0:i.uuid,productId:(r=this.product)==null?void 0:r.uuid,sessionId:(a=this.session)==null?void 0:a.sessionUuid})}}var mk={exports:{}},yh={};var VP=Symbol.for("react.transitional.element"),GP=Symbol.for("react.fragment");function gk(t,e,n){var i=null;if(n!==void 0&&(i=""+n),e.key!==void 0&&(i=""+e.key),"key"in e){n={};for(var r in e)r!=="key"&&(n[r]=e[r])}else n=e;return e=n.ref,{$$typeof:VP,type:t,key:i,ref:e!==void 0?e:null,props:n}}yh.Fragment=GP,yh.jsx=gk,yh.jsxs=gk,mk.exports=yh;var f=mk.exports,vk={exports:{}},ke={};var kg=Symbol.for("react.transitional.element"),WP=Symbol.for("react.portal"),YP=Symbol.for("react.fragment"),KP=Symbol.for("react.strict_mode"),XP=Symbol.for("react.profiler"),JP=Symbol.for("react.consumer"),$P=Symbol.for("react.context"),QP=Symbol.for("react.forward_ref"),ZP=Symbol.for("react.suspense"),eL=Symbol.for("react.memo"),bk=Symbol.for("react.lazy"),tL=Symbol.for("react.activity"),yk=Symbol.iterator;function nL(t){return t===null||typeof t!="object"?null:(t=yk&&t[yk]||t["@@iterator"],typeof t=="function"?t:null)}var _k={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},xk=Object.assign,Sk={};function Fs(t,e,n){this.props=t,this.context=e,this.refs=Sk,this.updater=n||_k}Fs.prototype.isReactComponent={},Fs.prototype.setState=function(t,e){if(typeof t!="object"&&typeof t!="function"&&t!=null)throw Error("takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,t,e,"setState")},Fs.prototype.forceUpdate=function(t){this.updater.enqueueForceUpdate(this,t,"forceUpdate")};function kk(){}kk.prototype=Fs.prototype;function Tg(t,e,n){this.props=t,this.context=e,this.refs=Sk,this.updater=n||_k}var wg=Tg.prototype=new kk;wg.constructor=Tg,xk(wg,Fs.prototype),wg.isPureReactComponent=!0;var Tk=Array.isArray;function Cg(){}var St={H:null,A:null,T:null,S:null},wk=Object.prototype.hasOwnProperty;function Eg(t,e,n){var i=n.ref;return{$$typeof:kg,type:t,key:e,ref:i!==void 0?i:null,props:n}}function iL(t,e){return Eg(t.type,e,t.props)}function Rg(t){return typeof t=="object"&&t!==null&&t.$$typeof===kg}function rL(t){var e={"=":"=0",":":"=2"};return"$"+t.replace(/[=:]/g,function(n){return e[n]})}var Ck=/\/+/g;function Ag(t,e){return typeof t=="object"&&t!==null&&t.key!=null?rL(""+t.key):e.toString(36)}function aL(t){switch(t.status){case"fulfilled":return t.value;case"rejected":throw t.reason;default:switch(typeof t.status=="string"?t.then(Cg,Cg):(t.status="pending",t.then(function(e){t.status==="pending"&&(t.status="fulfilled",t.value=e)},function(e){t.status==="pending"&&(t.status="rejected",t.reason=e)})),t.status){case"fulfilled":return t.value;case"rejected":throw t.reason}}throw t}function qs(t,e,n,i,r){var a=typeof t;(a==="undefined"||a==="boolean")&&(t=null);var o=!1;if(t===null)o=!0;else switch(a){case"bigint":case"string":case"number":o=!0;break;case"object":switch(t.$$typeof){case kg:case WP:o=!0;break;case bk:return o=t._init,qs(o(t._payload),e,n,i,r)}}if(o)return r=r(t),o=i===""?"."+Ag(t,0):i,Tk(r)?(n="",o!=null&&(n=o.replace(Ck,"$&/")+"/"),qs(r,e,n,"",function(c){return c})):r!=null&&(Rg(r)&&(r=iL(r,n+(r.key==null||t&&t.key===r.key?"":(""+r.key).replace(Ck,"$&/")+"/")+o)),e.push(r)),1;o=0;var s=i===""?".":i+":";if(Tk(t))for(var l=0;l<t.length;l++)i=t[l],a=s+Ag(i,l),o+=qs(i,e,n,a,r);else if(l=nL(t),typeof l=="function")for(t=l.call(t),l=0;!(i=t.next()).done;)i=i.value,a=s+Ag(i,l++),o+=qs(i,e,n,a,r);else if(a==="object"){if(typeof t.then=="function")return qs(aL(t),e,n,i,r);throw e=String(t),Error("Objects are not valid as a React child (found: "+(e==="[object Object]"?"object with keys {"+Object.keys(t).join(", ")+"}":e)+"). If you meant to render a collection of children, use an array instead.")}return o}function _h(t,e,n){if(t==null)return t;var i=[],r=0;return qs(t,i,"","",function(a){return e.call(n,a,r++)}),i}function oL(t){if(t._status===-1){var e=t._result;e=e(),e.then(function(n){(t._status===0||t._status===-1)&&(t._status=1,t._result=n)},function(n){(t._status===0||t._status===-1)&&(t._status=2,t._result=n)}),t._status===-1&&(t._status=0,t._result=e)}if(t._status===1)return t._result.default;throw t._result}var Ek=typeof reportError=="function"?reportError:function(t){if(typeof window=="object"&&typeof window.ErrorEvent=="function"){var e=new window.ErrorEvent("error",{bubbles:!0,cancelable:!0,message:typeof t=="object"&&t!==null&&typeof t.message=="string"?String(t.message):String(t),error:t});if(!window.dispatchEvent(e))return}else if(typeof process=="object"&&typeof process.emit=="function"){process.emit("uncaughtException",t);return}console.error(t)},sL={map:_h,forEach:function(t,e,n){_h(t,function(){e.apply(this,arguments)},n)},count:function(t){var e=0;return _h(t,function(){e++}),e},toArray:function(t){return _h(t,function(e){return e})||[]},only:function(t){if(!Rg(t))throw Error("React.Children.only expected to receive a single React element child.");return t}};ke.Activity=tL,ke.Children=sL,ke.Component=Fs,ke.Fragment=YP,ke.Profiler=XP,ke.PureComponent=Tg,ke.StrictMode=KP,ke.Suspense=ZP,ke.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE=St,ke.__COMPILER_RUNTIME={__proto__:null,c:function(t){return St.H.useMemoCache(t)}},ke.cache=function(t){return function(){return t.apply(null,arguments)}},ke.cacheSignal=function(){return null},ke.cloneElement=function(t,e,n){if(t==null)throw Error("The argument must be a React element, but you passed "+t+".");var i=xk({},t.props),r=t.key;if(e!=null)for(a in e.key!==void 0&&(r=""+e.key),e)!wk.call(e,a)||a==="key"||a==="__self"||a==="__source"||a==="ref"&&e.ref===void 0||(i[a]=e[a]);var a=arguments.length-2;if(a===1)i.children=n;else if(1<a){for(var o=Array(a),s=0;s<a;s++)o[s]=arguments[s+2];i.children=o}return Eg(t.type,r,i)},ke.createContext=function(t){return t={$$typeof:$P,_currentValue:t,_currentValue2:t,_threadCount:0,Provider:null,Consumer:null},t.Provider=t,t.Consumer={$$typeof:JP,_context:t},t},ke.createElement=function(t,e,n){var i,r={},a=null;if(e!=null)for(i in e.key!==void 0&&(a=""+e.key),e)wk.call(e,i)&&i!=="key"&&i!=="__self"&&i!=="__source"&&(r[i]=e[i]);var o=arguments.length-2;if(o===1)r.children=n;else if(1<o){for(var s=Array(o),l=0;l<o;l++)s[l]=arguments[l+2];r.children=s}if(t&&t.defaultProps)for(i in o=t.defaultProps,o)r[i]===void 0&&(r[i]=o[i]);return Eg(t,a,r)},ke.createRef=function(){return{current:null}},ke.forwardRef=function(t){return{$$typeof:QP,render:t}},ke.isValidElement=Rg,ke.lazy=function(t){return{$$typeof:bk,_payload:{_status:-1,_result:t},_init:oL}},ke.memo=function(t,e){return{$$typeof:eL,type:t,compare:e===void 0?null:e}},ke.startTransition=function(t){var e=St.T,n={};St.T=n;try{var i=t(),r=St.S;r!==null&&r(n,i),typeof i=="object"&&i!==null&&typeof i.then=="function"&&i.then(Cg,Ek)}catch(a){Ek(a)}finally{e!==null&&n.types!==null&&(e.types=n.types),St.T=e}},ke.unstable_useCacheRefresh=function(){return St.H.useCacheRefresh()},ke.use=function(t){return St.H.use(t)},ke.useActionState=function(t,e,n){return St.H.useActionState(t,e,n)},ke.useCallback=function(t,e){return St.H.useCallback(t,e)},ke.useContext=function(t){return St.H.useContext(t)},ke.useDebugValue=function(){},ke.useDeferredValue=function(t,e){return St.H.useDeferredValue(t,e)},ke.useEffect=function(t,e){return St.H.useEffect(t,e)},ke.useEffectEvent=function(t){return St.H.useEffectEvent(t)},ke.useId=function(){return St.H.useId()},ke.useImperativeHandle=function(t,e,n){return St.H.useImperativeHandle(t,e,n)},ke.useInsertionEffect=function(t,e){return St.H.useInsertionEffect(t,e)},ke.useLayoutEffect=function(t,e){return St.H.useLayoutEffect(t,e)},ke.useMemo=function(t,e){return St.H.useMemo(t,e)},ke.useOptimistic=function(t,e){return St.H.useOptimistic(t,e)},ke.useReducer=function(t,e,n){return St.H.useReducer(t,e,n)},ke.useRef=function(t){return St.H.useRef(t)},ke.useState=function(t){return St.H.useState(t)},ke.useSyncExternalStore=function(t,e,n){return St.H.useSyncExternalStore(t,e,n)},ke.useTransition=function(){return St.H.useTransition()},ke.version="19.2.3",vk.exports=ke;var w=vk.exports;const ai=ry(w);function lL(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var Rk={exports:{}};(function(t){(function(){var e={}.hasOwnProperty;function n(){for(var a="",o=0;o<arguments.length;o++){var s=arguments[o];s&&(a=r(a,i(s)))}return a}function i(a){if(typeof a=="string"||typeof a=="number")return a;if(typeof a!="object")return"";if(Array.isArray(a))return n.apply(null,a);if(a.toString!==Object.prototype.toString&&!a.toString.toString().includes("[native code]"))return a.toString();var o="";for(var s in a)e.call(a,s)&&a[s]&&(o=r(o,s));return o}function r(a,o){return o?a?a+" "+o:a+o:a}t.exports?(n.default=n,t.exports=n):window.classNames=n})()})(Rk);var cL=Rk.exports;const xh=lL(cL),uL="_box_1r6by_1",dL={box:uL},Ak={none:"0px",xxs:"var(--space-xxs)",xs:"var(--space-xs)",sm:"var(--space-sm)",md:"var(--space-md)",lg:"var(--space-lg)",xl:"var(--space-xl)","2xl":"var(--space-2xl)","3xl":"var(--space-3xl)","4xl":"var(--space-4xl)","5xl":"var(--space-5xl)"};function lr(t){if(t!==void 0){if(typeof t=="number")return`${t}px`;if(t in Ak)return Ak[t];if(typeof t=="string"&&t.trim().length>0)return t}}const Nk={none:"0px",panel:"var(--radius-panel)",card:"var(--radius-card)"},Ok={surface:"var(--color-surface)",surfaceMuted:"var(--color-surface-muted)",surfaceAlt:"var(--color-surface-alt)",primarySoft:"var(--color-primary-soft)",primarySofter:"var(--color-primary-softer)",dangerSurface:"var(--color-danger-surface)"};function hL(t){if(t!==void 0){if(typeof t=="number")return`${t}px`;if(t in Nk)return Nk[t];if(typeof t=="string"&&t.trim().length>0)return t}}function fL(t){if(t!==void 0){if(t in Ok)return Ok[t];if(typeof t=="string"&&t.trim().length>0)return t}}function pL(t,e){const{as:n,className:i,padding:r,paddingX:a,paddingY:o,paddingTop:s,paddingBottom:l,paddingLeft:c,paddingRight:u,paddingSm:d,paddingMd:h,paddingLg:p,paddingXl:b,margin:m,marginX:S,marginY:g,marginTop:y,marginBottom:x,marginLeft:v,marginRight:k,radius:T,radiusTop:C,radiusBottom:R,radiusLeft:A,radiusRight:N,radiusTopLeft:O,radiusTopRight:z,radiusBottomLeft:Y,radiusBottomRight:L,background:X,gap:P,style:G,...J}=t,te=n??"div",Z={...G},q=Z,ee={},$=(j,me)=>{if(me===void 0)return;const be=lr(me);be&&(Z[j]=be)},ue=(j,me)=>{if(me===void 0)return;const be=lr(me);be&&(Z[j]=be)},B=(j,me)=>{if(me===void 0)return;const be=hL(me);be&&(Z[j]=be)};if(r!==void 0){const j=lr(r);j&&(q["--box-padding"]=j)}if(a!==void 0){const j=lr(a);j&&(Z.paddingLeft=j,Z.paddingRight=j)}if(o!==void 0){const j=lr(o);j&&(Z.paddingTop=j,Z.paddingBottom=j)}$("paddingTop",s),$("paddingBottom",l),$("paddingLeft",c),$("paddingRight",u);const ve=[["sm",d],["md",h],["lg",p],["xl",b]];for(const[j,me]of ve){if(me===void 0)continue;const be=lr(me);be&&(q[`--box-padding-${j}`]=be,ee[`data-padding-${j}`]="")}if(m!==void 0){const j=lr(m);j&&(Z.margin=j)}if(S!==void 0){const j=lr(S);j&&(Z.marginLeft=j,Z.marginRight=j)}if(g!==void 0){const j=lr(g);j&&(Z.marginTop=j,Z.marginBottom=j)}if(ue("marginTop",y),ue("marginBottom",x),ue("marginLeft",v),ue("marginRight",k),P!==void 0){const j=lr(P);j&&(Z.gap=j)}if(B("borderRadius",T),C!==void 0&&(B("borderTopLeftRadius",C),B("borderTopRightRadius",C)),R!==void 0&&(B("borderBottomLeftRadius",R),B("borderBottomRightRadius",R)),A!==void 0&&(B("borderTopLeftRadius",A),B("borderBottomLeftRadius",A)),N!==void 0&&(B("borderTopRightRadius",N),B("borderBottomRightRadius",N)),B("borderTopLeftRadius",O),B("borderTopRightRadius",z),B("borderBottomLeftRadius",Y),B("borderBottomRightRadius",L),X!==void 0){const j=fL(X);j&&(Z.background=j)}return f.jsx(te,{ref:e,className:xh(dL.box,i),style:Z,...ee,...J})}const mL=ai.forwardRef(pL);mL.displayName="Box";const gL="_inline_1gpyx_1",vL="_vertical_1gpyx_6",bL="_divider_1gpyx_10",yL="_dividerVertical_1gpyx_16",_L="_customDivider_1gpyx_21",_c={inline:gL,vertical:vL,divider:bL,dividerVertical:yL,customDivider:_L};function xL(t,e){const{as:n,direction:i="horizontal",gap:r,align:a="center",justify:o,wrap:s=!1,divider:l,className:c,style:u,children:d,...h}=t,p=n??"div",b={display:"flex",flexDirection:i==="horizontal"?"row":"column",flexWrap:s?"wrap":"nowrap",alignItems:a,...o?{justifyContent:o}:{},...u};if(r!==void 0){const y=lr(r);y&&(b.gap=y)}const m=ai.Children.toArray(d).filter(y=>y!=null&&typeof y!="boolean"),S=y=>!l||y===0?null:l===!0||l==="line"?f.jsx("span",{"aria-hidden":"true",className:xh(_c.divider,i==="vertical"&&_c.dividerVertical)},`inline-divider-${y}`):f.jsx("span",{"aria-hidden":"true",className:_c.customDivider,children:l},`inline-divider-${y}`),g=[];return m.forEach((y,x)=>{if(x>0){const v=S(x);v&&g.push(v)}g.push(y)}),f.jsx(p,{ref:e,className:xh(_c.inline,i==="vertical"&&_c.vertical,c),style:b,...h,children:g})}const SL=ai.forwardRef(xL);SL.displayName="Inline",w.createContext("vertical");function kL({size:t=24,color:e="#000"}){return f.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",width:t,height:t,viewBox:"0 0 24 24",fill:"none",stroke:e,strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:"lucide lucide-x-icon lucide-x",children:[f.jsx("path",{d:"M18 6 6 18"}),f.jsx("path",{d:"m6 6 12 12"})]})}function Mk({onClose:t}){return f.jsx("button",{className:"obi-button obi-close-button",onClick:t,"aria-label":"Close",type:"button",style:{outline:"none"},autoFocus:!1,children:f.jsx(kL,{})})}function Dk({open:t=!1,children:e,onClose:n,size:i="medium",preventOutsideClick:r=!1}){const a=w.useRef(null),o=w.useRef(null);w.useEffect(()=>{const u=a.current;u&&(t&&!u.open?u.showModal():!t&&u.open&&(o.current="programmatic",u.close()))},[t]);const s=u=>{const d=a.current;u.target===d&&!r&&(o.current="user-initiated",d==null||d.close())},l=u=>{u.preventDefault(),o.current||(o.current="user-initiated");const d=o.current;o.current=null,n==null||n(d)},c=()=>{var u;o.current="user-initiated",(u=a.current)==null||u.close()};return w.useEffect(()=>{const u=a.current;if(u)return u.addEventListener("click",s),u.addEventListener("close",l),()=>{u.removeEventListener("click",s),u.removeEventListener("close",l)}},[n]),f.jsxs("dialog",{ref:a,className:`modal-${i}`,children:[f.jsx(Mk,{onClose:c}),f.jsx("div",{className:"modal-content",children:t?typeof e=="function"?e():e:null})]})}const Pk=8,Sh=8,TL=100,wL=.7,Hs=3;function Lk({getBands:t,color:e="white"}){const n=w.useRef(null);return w.useEffect(()=>{if(!t)return;let i=0,r;const a=o=>{try{if(o-i>=TL){const s=t();if(n.current){const l=n.current.querySelectorAll(".bar"),c=s&&s.length>0?s.slice(0,Sh).map(u=>{const d=Math.abs(u);return Math.min(d/wL*Pk,Pk)||Hs}):Array(Sh).fill(Hs);for(;c.length<Sh;)c.push(Hs);c.forEach((u,d)=>{if(u<Hs&&(u=Hs),l[d]){const h=u*2;l[d].style.height=`${h}px`,l[d].style.display=u>0?"block":"none"}})}i=o}r=requestAnimationFrame(a)}catch(s){console.warn("Error updating equaliser:",s),r=requestAnimationFrame(a)}};return r=requestAnimationFrame(a),()=>{cancelAnimationFrame(r)}},[t]),f.jsx("div",{className:"obi-equaliser",ref:n,children:Array.from({length:Sh},(i,r)=>f.jsx("div",{className:"column",children:f.jsx("div",{className:"bar",style:{height:`${Hs}px`,backgroundColor:e,display:"block"}})},r))})}function kh({className:t="",isActive:e=!1,speakingStatus:n,onClick:i,onMouseEnter:r,onMouseLeave:a,children:o}){let s=`obi-pill container ${e&&"active"}`;return n==="user-speaking"&&(s+=" user-speaking"),n==="busy"&&(s+=" busy"),f.jsx("div",{className:s,onMouseEnter:r,onMouseLeave:a,children:f.jsx("div",{className:`obi-pill pill ${t}`,onClick:i,children:o})})}function CL({className:t="",active:e,speakingStatus:n,onClick:i,onMouseEnter:r,onMouseLeave:a,children:o,...s}){const l=`obi-pill2 container ${e?"active":""} ${n==="user-speaking"?"user-speaking":""} ${t}`;return f.jsx("div",{className:l,...s,children:f.jsx("div",{className:"pill",onClick:i,onMouseEnter:r,onMouseLeave:a,children:o})})}function EL({className:t="",active:e,speakingStatus:n,onClick:i,onMouseEnter:r,onMouseLeave:a,children:o,...s}){const l=`obi-pill-up container ${e?"active":""} ${n==="user-speaking"?"user-speaking":""} ${t}`;return f.jsx("div",{className:l,...s,children:f.jsx("div",{className:"pill",onClick:i,onMouseEnter:r,onMouseLeave:a,children:o})})}function RL(t){const{spectrum:e}=t;return f.jsx(kh,{isActive:!0,children:f.jsx(Lk,{getBands:e})})}function Ng(t){const{children:e,className:n="",...i}=t;return f.jsx("div",{className:`${n} obi-panel`,...i,children:e})}function Ik({className:t="",size:e=64}){return f.jsx("svg",{width:e,height:e,viewBox:"0 0 256 256",fill:"none",xmlns:"http://www.w3.org/2000/svg",className:t,children:f.jsx("path",{d:"M158.803 0L160.352 0.0399439C176.267 0.844061 188.922 13.9634 188.922 30.0311C188.922 46.6174 175.438 60.0653 158.803 60.0656H99.0263L98.9061 60.0722C78.8071 61.4795 62.6269 77.004 60.2644 96.7673L60.241 96.9704V158.93L60.2644 159.13C62.7406 179.86 80.4234 195.934 101.881 195.935H153.842C176.993 195.935 195.759 177.223 195.759 154.14V96.9138L195.799 95.3693C196.606 79.5009 209.766 66.8827 225.881 66.8827C242.515 66.8834 256 80.328 256 96.9138V159.086L255.963 160.564C255.225 175.748 243.176 187.971 228.038 189.038V189.214C207.121 190.591 190.4 207.263 189.019 228.119H188.842C187.738 243.7 174.712 256 158.803 256H96.4491C79.8147 256 66.3309 242.555 66.3302 225.969C66.3302 225.673 66.3349 225.375 66.3436 225.077H66.3503H66.3035C63.3344 206.008 47.4427 190.589 27.8321 189.231L27.8354 189.031C12.2702 187.868 0.000167669 174.905 0 159.086V96.9138L0.0367222 95.4192C0.791087 80.0787 13.0909 67.7634 28.453 66.9293C47.7697 65.3039 63.3522 50.3234 66.2969 31.4658L66.3469 31.1595L66.3369 30.85C66.3301 30.5933 66.3302 30.3238 66.3302 30.0311C66.3309 13.4454 79.8148 0.000165137 96.4491 0H158.803Z",fill:"currentColor"})})}function AL(t){const{currentStep:e,totalSteps:n,stepNames:i,className:r,onStepClick:a}=t,[o,s]=w.useState(null),l=Array.from({length:n},(d,h)=>({isCompleted:h<e,isFuture:h>=e,stepNumber:h+1})),c=i[e-1]&&i[e-1].trim().length>0?i[e-1]:`Step ${e}`,u=(()=>{if(o!==null){const d=i[o]&&i[o].trim().length>0?i[o]:`Step ${o+1}`;return`${o+1}/${n} \u2022 ${d}`}return`${e}/${n} \u2022 ${c}`})();return f.jsxs("div",{className:`obi-course-progress ${r||""}`,children:[f.jsx("div",{className:"obi-course-progress-steps",children:l.map((d,h)=>{const p=i[h]&&i[h].trim().length>0?i[h]:`Step ${h+1}`,b=d.isCompleted?"completed":"future";function m(){a&&a(h,p)}function S(g){a&&(g.key==="Enter"||g.key===" ")&&(g.preventDefault(),m())}return f.jsx("div",{className:"obi-course-progress-container","data-testid":`course-progress-step-${h}`,onMouseEnter:()=>s(h),onMouseLeave:()=>s(null),onClick:a?m:void 0,onKeyDown:a?S:void 0,role:a?"button":void 0,tabIndex:a?0:void 0,children:f.jsx("div",{className:`obi-course-progress-step ${b}`,"aria-label":p})},h)})}),f.jsx("div",{className:"obi-course-progress-description",children:u})]})}function NL({onContinue:t,onWrapUp:e}){return f.jsx(Ng,{className:"obi-exit-survey",children:f.jsx(ML,{onContinue:t,onWrapUp:()=>{e()}})})}function OL({onOtherSelect:t,onReasonSelect:e,onClose:n}){const[i,r]=w.useState("reason"),a=o=>{o==="other"?(t(),r("other-reason")):e(o)};return f.jsx(Ng,{className:`obi-exit-survey ${i==="reason"?"obi-exit-survey-reason":""}`,children:i==="reason"?f.jsx(DL,{onReasonSelect:a}):f.jsx(PL,{onReasonSelect:a,onClose:n})})}function ML({onContinue:t,onWrapUp:e}){return f.jsxs("div",{className:"obi-exit-survey-container",children:[f.jsx("h2",{className:"obi-exit-survey-title",children:"Wrapping up early?"}),f.jsxs("div",{className:"obi-exit-survey-options",children:[f.jsx("button",{className:"obi-button obi-exit-survey-button obi-exit-survey-button-continue",onClick:t,type:"button",children:"No, let's continue"}),f.jsx("button",{className:"obi-button obi-exit-survey-button obi-exit-survey-button-wrap-up",onClick:e,type:"button",children:"Yes, let's wrap up"})]})]})}function DL({onReasonSelect:t}){return f.jsxs("div",{className:"obi-exit-survey-container obi-exit-survey-reason-container",children:[f.jsx("div",{className:"obi-exit-survey-header",children:f.jsx("h2",{className:"obi-exit-survey-title obi-exit-survey-reason-title",children:"Quick feedback?"})}),f.jsxs("div",{className:"obi-exit-survey-options obi-exit-survey-reason-options",children:[f.jsx("button",{className:"obi-button obi-exit-survey-button obi-exit-survey-reason-button",onClick:()=>t("do-later"),type:"button",children:"Will do later"}),f.jsx("button",{className:"obi-button obi-exit-survey-button obi-exit-survey-reason-button",onClick:()=>t("cant-talk"),type:"button",children:"Can't talk right now"}),f.jsx("button",{className:"obi-button obi-exit-survey-button obi-exit-survey-reason-button",onClick:()=>t("prefer-written"),type:"button",children:"Prefer written instructions"}),f.jsx("button",{className:"obi-button obi-exit-survey-button obi-exit-survey-reason-button",onClick:()=>t("technical-issues"),type:"button",children:"Experienced technical issues"})]})]})}function PL({onReasonSelect:t,onClose:e}){const[n,i]=w.useState("");return f.jsxs("div",{className:"obi-exit-survey-container obi-exit-survey-reason-container",children:[f.jsxs("div",{className:"obi-exit-survey-header",children:[f.jsx(Mk,{onClose:e}),f.jsx("h2",{className:"obi-exit-survey-title obi-exit-survey-reason-title",children:"Tell us more"})]}),f.jsxs("div",{className:"obi-exit-survey-options obi-exit-survey-reason-options",children:[f.jsx("textarea",{className:"obi-exit-survey-button obi-exit-survey-reason-button",placeholder:"What's on your mind?",value:n,onChange:r=>i(r.target.value)}),f.jsx("button",{className:"obi-button obi-exit-survey-button obi-exit-survey-button-wrap-up",onClick:()=>t("other-feedback",n),type:"button",children:"Send feedback"})]})]})}const LL=8;function jk({color:t="white"}){return f.jsx("div",{className:"obi-loading-dots",children:Array.from({length:LL},(e,n)=>f.jsxs("div",{className:"column",children:[f.jsx("div",{className:"bar",style:{backgroundColor:t,animationDelay:`${n*.15}s`}}),f.jsx("div",{className:"dot",style:{backgroundColor:t}})]},n))})}function ea({className:t,children:e,onClick:n}){return n?f.jsx("button",{className:`obi-button obi-message ${t} clickable`,onClick:n,children:e}):f.jsx("div",{className:`obi-message ${t}`,children:e})}function IL(t){const{placeholder:e="Type your message...",value:n,defaultValue:i,onChange:r,onSend:a,onCancel:o,onExpand:s,isLoading:l=!1,disabled:c=!1,maxLength:u=500,children:d}=t,[h,p]=w.useState(n||i||""),[b,m]=w.useState((n||i||"").length>24),S=w.useRef(null);w.useLayoutEffect(()=>{b&&(s==null||s(!0))},[]);const g=n!==void 0?n:h,y=k=>{const T=k.currentTarget.value;n===void 0&&p(T),r==null||r(T)},x=k=>{k.key==="Escape"&&(p(n||i||""),m(!1),o==null||o()),k.key==="Enter"&&!k.shiftKey&&g.trim()&&(k.preventDefault(),p(n||i||""),m(!1),v()),(g||"").length>=24&&!b&&(m(!0),s==null||s(!0))};w.useEffect(()=>{S.current&&S.current.focus()},[S.current]);const v=()=>{!g.trim()||l||c||(a==null||a(g.trim()),n===void 0&&p(""))};return f.jsxs("div",{className:`obi-message-input ${b?"expanded":""}`,children:[f.jsx("div",{className:"container",children:f.jsx("textarea",{ref:S,className:"field",placeholder:e,value:g,onInput:y,onKeyDown:x,disabled:c||l,maxLength:u,rows:1})}),f.jsxs("div",{className:"button-container",children:[b&&f.jsx("div",{children:d}),f.jsx("button",{className:"obi-button send",onClick:v,disabled:!g.trim()||l||c,type:"button",children:f.jsx("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:f.jsx("path",{d:"M6.00016 10.6673V1.33398M6.00016 1.33398L1.3335 6.00065M6.00016 1.33398L10.6668 6.00065",stroke:"#F3F3F3","stroke-width":"1.6","stroke-linecap":"round","stroke-linejoin":"round"})})})]})]})}const Og=w.createContext(null);function jL({children:t}){const e=w.useContext(Og);if(!e)throw new Error("PopoutTarget must be used within a Popout component");const{controlledOpen:n,isOpen:i,setIsOpen:r,setAnimating:a,targetRef:o,trigger:s,onChange:l,delayMs:c}=e,u=w.useRef(null),d=Bk(o,a),[h,p]=w.useState(!1);w.useEffect(()=>{n!==void 0&&n!==h&&(n?m():S()),p(n)},[n]),w.useEffect(()=>()=>{u.current&&clearTimeout(u.current)},[]);function b(){u.current&&(clearTimeout(u.current),u.current=null)}function m(){b(),c>0?u.current=setTimeout(()=>{l==null||l(!0),r(!0),u.current=null},c):(l==null||l(!0),r(!0))}function S(){b(),l==null||l(!1),r(!1)}const g=()=>{s==="click"&&(i?S():m())};function y(){s==="hover"&&m()}function x(){s==="hover"&&S()}return f.jsx("div",{ref:d,className:"target",onClick:g,onMouseEnter:y,onMouseLeave:x,children:t})}function BL({children:t}){const e=w.useContext(Og);if(!e)throw new Error("PopoutContent must be used within a Popout component");const{isOpen:n,animating:i,setAnimating:r,targetRef:a,contentRef:o}=e,s=Bk(o,r);return w.useLayoutEffect(()=>{if(n&&!i&&a.current&&o.current){const l=o.current;if(!l)return;const c=a.current;if(!c)return;const u=l.getBoundingClientRect(),d=c.getBoundingClientRect(),h=d.right-d.left;l.style.top=`${u.top-u.bottom-(8+e.offset)}px`,l.style.left=`${-(u.right-u.left-h)/2}px`}},[n,i]),n?f.jsx("div",{ref:s,className:"content",style:{opacity:i?0:1},children:t}):null}function oi({trigger:t="click",open:e,onChange:n,children:i,delayMs:r=0,offset:a=0,className:o=""}){const[s,l]=w.useState(!1),[c,u]=w.useState(!1),d=w.useRef(null),h=w.useRef(null),p={controlledOpen:e,isOpen:s,setIsOpen:l,animating:c,setAnimating:u,targetRef:d,contentRef:h,trigger:t,onChange:n,delayMs:r,offset:a};return f.jsx(Og.Provider,{value:p,children:f.jsx("div",{className:`obi-popout ${o}`,children:i})})}oi.Target=jL,oi.Content=BL;function Bk(t,e){const n=w.useRef(null),i=w.useRef(null),r=w.useRef(!0),a=w.useCallback(o=>{if(t.current=o,!o){i.current&&(i.current.disconnect(),i.current=null),r.current=!0;return}function s(){if(r.current){r.current=!1;return}n.current?clearTimeout(n.current):e(!0),n.current=setTimeout(()=>{e(!1),n.current=null},200)}i.current=new ResizeObserver(s),i.current.observe(o,{box:"border-box"})},[]);return w.useEffect(()=>()=>{i.current&&(i.current.disconnect(),i.current=null)},[]),a}function Wo({type:t,size:e=24}){return f.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2","stroke-linecap":"round","stroke-linejoin":"round",children:UL(t)})}function UL(t){switch(t){case"pause":return f.jsxs(f.Fragment,{children:[f.jsx("rect",{x:"14",y:"3",width:"5",height:"18",rx:"1"}),f.jsx("rect",{x:"5",y:"3",width:"5",height:"18",rx:"1"})]});case"play":return f.jsx(f.Fragment,{children:f.jsx("path",{d:"M5 5a2 2 0 0 1 3.008-1.728l11.997 6.998a2 2 0 0 1 .003 3.458l-12 7A2 2 0 0 1 5 19z"})});case"close":return f.jsxs(f.Fragment,{children:[f.jsx("path",{d:"M18 6 6 18"}),f.jsx("path",{d:"m6 6 12 12"})]});case"message":return f.jsx(f.Fragment,{children:f.jsx("path",{d:"M22 17a2 2 0 0 1-2 2H6.828a2 2 0 0 0-1.414.586l-2.202 2.202A.71.71 0 0 1 2 21.286V5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2z"})});case"minimize":return f.jsxs(f.Fragment,{children:[f.jsx("path",{d:"m14 10 7-7"}),f.jsx("path",{d:"M20 10h-6V4"}),f.jsx("path",{d:"m3 21 7-7"}),f.jsx("path",{d:"M4 14h6v6"})]});case"voice":return f.jsxs(f.Fragment,{children:[f.jsx("path",{d:"M2 10v3"}),f.jsx("path",{d:"M6 6v11"}),f.jsx("path",{d:"M10 3v18"}),f.jsx("path",{d:"M14 8v7"}),f.jsx("path",{d:"M18 5v13"}),f.jsx("path",{d:"M22 10v3"})]});case"open":return f.jsxs(f.Fragment,{children:[f.jsx("path",{d:"M12 7v14"}),f.jsx("path",{d:"M3 18a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1h5a4 4 0 0 1 4 4 4 4 0 0 1 4-4h5a1 1 0 0 1 1 1v13a1 1 0 0 1-1 1h-6a3 3 0 0 0-3 3 3 3 0 0 0-3-3z"})]})}}function cr({className:t,onClick:e,type:n,disabled:i,title:r}){const a={cancel:f.jsx(Wo,{type:"close",size:16}),pause:f.jsx(Wo,{type:"pause",size:16}),play:f.jsx(Wo,{type:"play",size:16}),message:f.jsx(Wo,{type:"message",size:16}),minimize:f.jsx(Wo,{type:"minimize",size:16}),voice:f.jsx(Wo,{type:"voice",size:16}),open:f.jsx(Wo,{type:"open",size:16})}[n],o={cancel:"",pause:"",play:"",message:"",minimize:"",voice:"",open:""}[n],s=f.jsx("button",{className:`obi-button obi-round-button ${o} ${t}`,onClick:i?void 0:e,disabled:i,children:a});return r?f.jsxs(oi,{className:"obi-round-button-popout",trigger:"hover",delayMs:200,offset:9,children:[f.jsx(oi.Target,{children:s}),f.jsx(oi.Content,{children:f.jsx("div",{className:"obi-round-button-title",children:r})})]}):s}function zL(t){const{disabled:e,inPlan:n,isPaused:i}=t,[r,a]=w.useState(null),[o,s]=w.useState(t.isActive??t.defaultIsActive??!1),[l,c]=w.useState(!1),[u,d]=w.useState(t.cancelling??!1),[h,p]=w.useState(t.messaging??!1),[b,m]=w.useState(!1),[S,g]=w.useState(h),[y,x]=w.useState(!1);function v(){s(!0),c(!1),x(!0)}function k(){}function T(){r&&(clearTimeout(r),a(null))}function C(){a(setTimeout(()=>{s(t.defaultIsActive??!1),x(!1)},400))}function R(Te){var Le;m(!1),(Le=t.onMessage)==null||Le.call(t,Te)}function A(){var Te;p(!1),m(!1),s(!1),c(!0),(Te=t.onMinimize)==null||Te.call(t)}function N(){var Te;p(!1),d(!0),m(!1),(Te=t.onCancelClick)==null||Te.call(t)}function O(){var Te;n||((Te=t.onOpen)==null||Te.call(t))}function z(Te){var Le,ht,lt,hn,fn,At;switch(Te){case"need-help":(Le=t.onMessage)==null||Le.call(t,"I'm struggling, can you look at my screen and help me out."),(ht=t.onOneClickAction)==null||ht.call(t,"need-help");break;case"continue":(lt=t.onMessage)==null||lt.call(t,"Okay, let's continue."),(hn=t.onOneClickAction)==null||hn.call(t,"continue");break;case"say-again":(fn=t.onMessage)==null||fn.call(t,"Please say that again."),(At=t.onOneClickAction)==null||At.call(t,"say-again");break}}function Y(Te){var Le,ht;t.messaging===void 0?((Le=t.onMessagingChange)==null||Le.call(t,Te),p(Te)):((ht=t.onMessagingChange)==null||ht.call(t,!t.messaging),p(!t.messaging)),Te||m(!1)}const L=t.isActive??((o||n)&&!l&&!e),X=L&&n,P=L&&n&&!b,G=t.speakingStatus==="user-speaking",J=t.speakingStatus==="thinking",te=t.speakingStatus==="busy",Z=L&&!n&&!u&&y,q=L&&n&&i&&!G&&!u,ee=L&&n&&!q&&!G&&h!==S&&!u,$=L&&n&&i&&G&&!u,ue=L&&n&&!i&&G&&!u,B=L&&n&&!i&&te&&!u,ve=t.messaging!==void 0?t.messaging:h,j=ve&&G,me=Z||q||$||ue||ee||u,be=400,qt=!!t.courseProgress&&!l,En=Z?5:10;return w.useLayoutEffect(()=>{g(h)},[G]),!n&&!u?f.jsx(FL,{...t}):!n&&u?f.jsx(qL,{onOtherSelect:()=>{var Te;(Te=t.onCancelReasonOther)==null||Te.call(t)},onCancelReason:Te=>{var Le;s(t.defaultIsActive??!1),d(!1),(Le=t.onCancelReason)==null||Le.call(t,Te)},onClose:()=>{s(t.defaultIsActive??!1),d(!1)}}):f.jsxs(Ng,{className:`obi-widget-panel ${X?"expanded":""} ${b?"maximized":""} ${ve?"messaging":""} ${te?"tool-usage":""}`,children:[f.jsxs("div",{className:`obi-widget ${L?"active":""} ${n?"in-plan":""}`,onMouseEnter:T,onMouseLeave:C,children:[P&&f.jsx(cr,{type:"cancel",onClick:N,disabled:u,title:"Cancel session"}),P&&!i&&f.jsx(cr,{type:"pause",onClick:t.onPause,title:"Pause session"}),P&&i&&f.jsx(cr,{type:"play",onClick:t.onUnpause,title:"Unpause session"}),f.jsxs(oi,{className:"obi-widget-popout",open:me,trigger:null,delayMs:be,offset:En,children:[f.jsxs(oi.Target,{children:[j&&f.jsx(IL,{value:t.message,onCancel:()=>Y(!1),onSend:R,onExpand:m,onChange:t.onMessageChange,children:f.jsxs("div",{className:"obi-widget-buttons",children:[f.jsx(cr,{type:"cancel",onClick:N,disabled:u,title:"Cancel session"}),!i&&f.jsx(cr,{type:"pause",onClick:t.onPause,title:"Pause session"}),i&&f.jsx(cr,{type:"play",onClick:t.onUnpause,title:"Unpause session"}),f.jsx(cr,{type:ve?"voice":"message",onClick:()=>Y(!ve),title:ve?"Voice input":"Text input"}),f.jsx(cr,{type:"minimize",onClick:A,title:"Minimize widget"})]})}),!j&&f.jsxs(kh,{className:L&&!n?"button":"",isActive:L,speakingStatus:t.speakingStatus,onClick:O,onMouseEnter:v,onMouseLeave:k,children:[L&&!n&&!B&&f.jsx("span",{className:"obi-widget-pill-text",children:"Tutorials"}),L&&n&&B&&f.jsx("span",{className:"obi-widget-pill-text",children:"Searching knowledge ..."}),L&&n&&!J&&!B&&f.jsx(Lk,{getBands:t.spectrum}),L&&J&&!B&&f.jsx(jk,{})]})]}),f.jsx(oi.Content,{children:f.jsxs("div",{onMouseLeave:C,children:[Z&&f.jsx(ea,{onClick:O,children:"Click to see all"}),q&&f.jsx(ea,{children:"Session will pause shortly"}),ee&&f.jsxs(ea,{children:["Switched to ",ve?"chat":"voice"]}),$&&f.jsx(ea,{children:"Paused"}),ue&&f.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:"4px"},children:[f.jsx(ea,{onClick:()=>z("need-help"),children:"Need help"}),f.jsx(ea,{onClick:()=>z("continue"),children:"Continue"}),f.jsx(ea,{onClick:()=>z("say-again"),children:"Say again"})]}),u&&f.jsx(NL,{onContinue:()=>{var Te;(Te=t.onCancelAbort)==null||Te.call(t),d(!1),t.messaging!==void 0&&p(t.messaging)},onWrapUp:()=>{var Te;(Te=t.onCancel)==null||Te.call(t)}})]})})]}),P&&f.jsx(cr,{type:ve?"voice":"message",onClick:()=>Y(!ve),title:ve?"Voice input":"Text input"}),P&&f.jsx(cr,{type:"minimize",onClick:A,title:"Minimize widget"})]}),qt&&t.courseProgress&&f.jsx("div",{className:`obi-widget-course-progress ${ve?"expanded":""}`,children:f.jsx(AL,{currentStep:t.courseProgress.currentStep,totalSteps:t.courseProgress.totalSteps,stepNames:t.courseProgress.stepNames,onStepClick:(Te,Le)=>{var lt;const ht=`Can we please jump to the steps related to: ${Le}`;(lt=t.onMessage)==null||lt.call(t,ht)}})})]})}function FL(t){const{disabled:e,completedTutorials:n,totalTutorials:i,agentName:r}=t,[a,o]=w.useState(null),[s,l]=w.useState(t.isActive??t.defaultIsActive??!1),[c,u]=w.useState(!1),[d,h]=w.useState(t.hovered??!1),[p,b]=w.useState(null),[m,S]=w.useState(null);function g(){m&&(clearTimeout(m),S(null)),p&&b(null)}function y(){var Y;l(!0),u(!1),h(!0),(Y=t.onHover)==null||Y.call(t,!0)}function x(){}function v(){a&&(clearTimeout(a),o(null))}function k(){s&&o(setTimeout(()=>{var Y;l(t.defaultIsActive??!1),h(!1),(Y=t.onHover)==null||Y.call(t,!1)},400))}function T(){g(),l(!1),u(!0)}function C(){var Y;g(),(Y=t.onOpen)==null||Y.call(t)}const R=t.hovered??(d&&!c),A=t.isActive??(s&&!e&&!c),N=A&&R||!!p,O=`round-button ${A?"active":""}`;let z=`${r||"Obi"}`;return n!==void 0&&i!==void 0&&n>=0&&i>0&&(z=`${n}/${i} completed`),w.useLayoutEffect(()=>{if(t.toastMessage&&t.toastMessage.text){m&&clearTimeout(m);const Y=t.toastMessage.autoCloseMs??3e3;b({text:t.toastMessage.text,autoCloseMs:Y});const L=setTimeout(()=>{b(null)},Y);S(L)}else t.toastMessage===null&&(m&&clearTimeout(m),b(null))},[t.toastMessage]),f.jsx("div",{className:"obi-widget-out-of-plan-container",children:f.jsxs("div",{className:`obi-widget-out-of-plan ${R?"hover":""} ${A?"active":""}`,onMouseEnter:v,onMouseLeave:k,onClickCapture:g,children:[f.jsx("div",{className:O,style:{width:"30px",height:"30px"}}),f.jsxs(oi,{className:"obi-widget-popout",open:N,trigger:null,delayMs:400,offset:5,children:[f.jsx(oi.Target,{children:f.jsx(EL,{className:A?"button":"",active:A,onClick:C,onMouseEnter:y,onMouseLeave:x,children:f.jsxs("span",{className:"text",children:[f.jsx(Ik,{size:16}),z]})})}),f.jsxs(oi.Content,{children:[!!p&&f.jsx(ea,{onClick:()=>{g(),C()},children:p.text}),!p&&f.jsx("div",{onMouseLeave:k,children:f.jsx(ea,{className:"message",onClick:C,children:"Click to see all"})})]})]}),f.jsx(cr,{className:O,type:"minimize",onClick:T,title:"Minimize widget"})]})})}function qL(t){return f.jsx("div",{className:"obi-widget-out-of-plan-container",children:f.jsx("div",{className:"obi-widget-out-of-plan",children:f.jsxs(oi,{className:"obi-widget-popout",open:!0,trigger:null,delayMs:100,offset:5,children:[f.jsx(oi.Target,{children:f.jsx(CL,{active:!1})}),f.jsx(oi.Content,{children:f.jsx(OL,{onOtherSelect:()=>{var e;(e=t.onOtherSelect)==null||e.call(t)},onReasonSelect:(e,n)=>{var i;(i=t.onCancelReason)==null||i.call(t,e,n)},onClose:()=>{var e;(e=t.onClose)==null||e.call(t)}})})]})})})}function HL({open:t=!1,children:e,onClose:n,preventOutsideClick:i=!1}){return f.jsx(Dk,{open:t,onClose:n,preventOutsideClick:i,size:"medium",children:f.jsx("div",{className:"tour content-area",children:t?typeof e=="function"?e():e:null})})}function VL({logoUrl:t="",appName:e="App"}){const[n,i]=w.useState(!1),[r,a]=w.useState(!1),o=()=>{i(!0)},s=()=>{a(!0),i(!1)},l={container:{display:"block"},logoContainer:{width:"480px",height:"240px",borderRadius:"12px",display:"flex",alignItems:"center",justifyContent:"center",position:"relative",overflow:"hidden"},backgroundPattern:{position:"absolute",inset:0,zIndex:0,background:"#F5F5F5",backgroundImage:`url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='277' height='195' viewBox='0 0 277 195' fill='none'%3E%3Cpath opacity='0.4' d='M341.308 0.75C380.279 0.750001 411.872 24.3772 411.872 53.5229C411.872 82.6685 380.279 106.296 341.308 106.296H215.792C176.964 108.335 145.691 130.837 141.128 159.475V256.616C145.912 286.659 180.089 309.954 221.548 309.954H330.872C375.607 309.954 411.872 282.833 411.872 249.377V159.069C411.872 129.923 443.465 106.296 482.436 106.296C521.407 106.296 553 129.923 553 159.069V257.181C553 285.058 524.099 307.88 487.483 309.815C489.264 309.902 491.061 309.954 492.871 309.954C448.137 309.954 411.872 337.076 411.872 370.532C411.872 369.177 411.803 367.834 411.686 366.502C409.098 393.885 378.582 415.5 341.308 415.5H210.118C171.147 415.5 139.554 391.873 139.554 362.727C139.554 362.204 139.565 361.683 139.585 361.163C133.564 332.156 100.023 309.954 59.5488 309.954C61.4544 309.954 63.3441 309.9 65.2169 309.803C28.7434 307.76 -8.57239e-07 284.982 0 257.181V159.069C1.64632e-06 130.901 29.5078 107.89 66.6662 106.377C64.3207 106.224 61.9472 106.141 59.5488 106.141C100.012 106.141 133.54 83.951 139.575 54.9552C139.558 54.4793 139.554 54.0018 139.554 53.5229C139.554 24.3772 171.147 0.75 210.118 0.75H341.308Z' fill='white'/%3E%3C/svg%3E")`,backgroundRepeat:"no-repeat",backgroundPosition:"190px 60px",backgroundSize:"300px 225px"},logoWrapper:{background:"#888888",width:"120px",height:"120px",display:"flex",alignItems:"center",justifyContent:"center",borderRadius:"4px",boxShadow:"0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06)",zIndex:10,overflow:"hidden"},appLogo:{width:"120px",height:"120px",objectFit:"cover",display:t&&!n&&r?"block":"none"},placeholderLogo:{width:"60px",height:"60px",background:"rgba(255, 255, 255, 0.2)",borderRadius:"4px",display:!t||n||!r?"flex":"none",alignItems:"center",justifyContent:"center",color:"rgba(255, 255, 255, 0.8)",fontSize:"24px",fontWeight:"bold"}};return f.jsx("div",{style:l.container,children:f.jsxs("div",{style:l.logoContainer,children:[f.jsx("div",{style:l.backgroundPattern}),f.jsxs("div",{style:l.logoWrapper,children:[t&&f.jsx("img",{style:l.appLogo,src:t,alt:`${e} logo`,onError:o,onLoad:s}),f.jsx("div",{style:l.placeholderLogo,children:e.charAt(0).toUpperCase()})]})]})})}function Vs({className:t,title:e="",agentName:n="Obi",buttonText:i="Continue",speakingState:r=null,actionDisabled:a=!1,footer:o,href:s=null,glow:l=!1,centerVisual:c,description:u,button:d,onAction:h}){const[p,b]=w.useState(a),[m,S]=w.useState(!1),[g,y]=w.useState(r);w.useEffect(()=>{m||(r==="listening"&&g!=="listening"&&p&&b(!1),r!=="listening"&&!p&&b(!0)),y(r)},[r,p]),w.useEffect(()=>{b(a)},[a]);const x=()=>{p||(b(!0),S(!0),h==null||h())},v=()=>{switch(r){case"thinking":return"Loading...";case"speaking":return`${n} is speaking`;default:return i}},k=s?"a":"button",T=s?{href:s,target:"_blank",rel:"noopener noreferrer"}:{type:"button"};return f.jsx("div",{className:xh("tour-content",t),children:f.jsxs("div",{className:"container",children:[f.jsx("div",{className:`visual ${l?"glow":""}`,children:c}),f.jsxs("div",{className:"header",children:[f.jsx("h1",{className:"title",children:e}),f.jsx("div",{className:"description",children:u})]}),f.jsx("div",{className:"button-container",children:d||f.jsx(k,{className:`action-button ${p?"disabled":""}`,onClick:x,disabled:p,...T,children:f.jsx("span",{className:"button-text",children:v()})})}),o&&f.jsx("div",{className:"tour-footer",children:o})]})})}function GL({session:t,speakingState:e,onAction:n}){const i=t.appName?`Navigate to ${t.appName}`:"Navigate to app",r=t.appName?`Open ${t.appName}`:"Open app",a=t.appName?`Enjoy the tutorial in ${t.appName}`:"Enjoy the tutorial";return f.jsx(Vs,{title:i,subtitle:"Click the button below to open the app",agentName:t.agentName||"Obi",buttonText:r,speakingState:e,actionDisabled:!0,href:t.url,description:a,centerVisual:f.jsx(VL,{logoUrl:t.appLogoUrl,appName:t.appName}),onAction:n})}const{entries:Uk,setPrototypeOf:zk,isFrozen:WL,getPrototypeOf:YL,getOwnPropertyDescriptor:KL}=Object;let{freeze:zn,seal:ji,create:Mg}=Object,{apply:Dg,construct:Pg}=typeof Reflect<"u"&&Reflect;zn||(zn=function(t){return t}),ji||(ji=function(t){return t}),Dg||(Dg=function(t,e){for(var n=arguments.length,i=new Array(n>2?n-2:0),r=2;r<n;r++)i[r-2]=arguments[r];return t.apply(e,i)}),Pg||(Pg=function(t){for(var e=arguments.length,n=new Array(e>1?e-1:0),i=1;i<e;i++)n[i-1]=arguments[i];return new t(...n)});const Th=qn(Array.prototype.forEach),XL=qn(Array.prototype.lastIndexOf),Fk=qn(Array.prototype.pop),xc=qn(Array.prototype.push),JL=qn(Array.prototype.splice),wh=qn(String.prototype.toLowerCase),Lg=qn(String.prototype.toString),Ig=qn(String.prototype.match),Sc=qn(String.prototype.replace),$L=qn(String.prototype.indexOf),QL=qn(String.prototype.trim),ur=qn(Object.prototype.hasOwnProperty),Fn=qn(RegExp.prototype.test),kc=ZL(TypeError);function qn(t){return function(e){e instanceof RegExp&&(e.lastIndex=0);for(var n=arguments.length,i=new Array(n>1?n-1:0),r=1;r<n;r++)i[r-1]=arguments[r];return Dg(t,e,i)}}function ZL(t){return function(){for(var e=arguments.length,n=new Array(e),i=0;i<e;i++)n[i]=arguments[i];return Pg(t,n)}}function De(t,e){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:wh;zk&&zk(t,null);let i=e.length;for(;i--;){let r=e[i];if(typeof r=="string"){const a=n(r);a!==r&&(WL(e)||(e[i]=a),r=a)}t[r]=!0}return t}function eI(t){for(let e=0;e<t.length;e++)ur(t,e)||(t[e]=null);return t}function Dr(t){const e=Mg(null);for(const[n,i]of Uk(t))ur(t,n)&&(Array.isArray(i)?e[n]=eI(i):i&&typeof i=="object"&&i.constructor===Object?e[n]=Dr(i):e[n]=i);return e}function Tc(t,e){for(;t!==null;){const i=KL(t,e);if(i){if(i.get)return qn(i.get);if(typeof i.value=="function")return qn(i.value)}t=YL(t)}function n(){return null}return n}const qk=zn(["a","abbr","acronym","address","area","article","aside","audio","b","bdi","bdo","big","blink","blockquote","body","br","button","canvas","caption","center","cite","code","col","colgroup","content","data","datalist","dd","decorator","del","details","dfn","dialog","dir","div","dl","dt","element","em","fieldset","figcaption","figure","font","footer","form","h1","h2","h3","h4","h5","h6","head","header","hgroup","hr","html","i","img","input","ins","kbd","label","legend","li","main","map","mark","marquee","menu","menuitem","meter","nav","nobr","ol","optgroup","option","output","p","picture","pre","progress","q","rp","rt","ruby","s","samp","search","section","select","shadow","slot","small","source","spacer","span","strike","strong","style","sub","summary","sup","table","tbody","td","template","textarea","tfoot","th","thead","time","tr","track","tt","u","ul","var","video","wbr"]),jg=zn(["svg","a","altglyph","altglyphdef","altglyphitem","animatecolor","animatemotion","animatetransform","circle","clippath","defs","desc","ellipse","enterkeyhint","exportparts","filter","font","g","glyph","glyphref","hkern","image","inputmode","line","lineargradient","marker","mask","metadata","mpath","part","path","pattern","polygon","polyline","radialgradient","rect","stop","style","switch","symbol","text","textpath","title","tref","tspan","view","vkern"]),Bg=zn(["feBlend","feColorMatrix","feComponentTransfer","feComposite","feConvolveMatrix","feDiffuseLighting","feDisplacementMap","feDistantLight","feDropShadow","feFlood","feFuncA","feFuncB","feFuncG","feFuncR","feGaussianBlur","feImage","feMerge","feMergeNode","feMorphology","feOffset","fePointLight","feSpecularLighting","feSpotLight","feTile","feTurbulence"]),tI=zn(["animate","color-profile","cursor","discard","font-face","font-face-format","font-face-name","font-face-src","font-face-uri","foreignobject","hatch","hatchpath","mesh","meshgradient","meshpatch","meshrow","missing-glyph","script","set","solidcolor","unknown","use"]),Ug=zn(["math","menclose","merror","mfenced","mfrac","mglyph","mi","mlabeledtr","mmultiscripts","mn","mo","mover","mpadded","mphantom","mroot","mrow","ms","mspace","msqrt","mstyle","msub","msup","msubsup","mtable","mtd","mtext","mtr","munder","munderover","mprescripts"]),nI=zn(["maction","maligngroup","malignmark","mlongdiv","mscarries","mscarry","msgroup","mstack","msline","msrow","semantics","annotation","annotation-xml","mprescripts","none"]),Hk=zn(["#text"]),Vk=zn(["accept","action","align","alt","autocapitalize","autocomplete","autopictureinpicture","autoplay","background","bgcolor","border","capture","cellpadding","cellspacing","checked","cite","class","clear","color","cols","colspan","controls","controlslist","coords","crossorigin","datetime","decoding","default","dir","disabled","disablepictureinpicture","disableremoteplayback","download","draggable","enctype","enterkeyhint","exportparts","face","for","headers","height","hidden","high","href","hreflang","id","inert","inputmode","integrity","ismap","kind","label","lang","list","loading","loop","low","max","maxlength","media","method","min","minlength","multiple","muted","name","nonce","noshade","novalidate","nowrap","open","optimum","part","pattern","placeholder","playsinline","popover","popovertarget","popovertargetaction","poster","preload","pubdate","radiogroup","readonly","rel","required","rev","reversed","role","rows","rowspan","spellcheck","scope","selected","shape","size","sizes","slot","span","srclang","start","src","srcset","step","style","summary","tabindex","title","translate","type","usemap","valign","value","width","wrap","xmlns","slot"]),zg=zn(["accent-height","accumulate","additive","alignment-baseline","amplitude","ascent","attributename","attributetype","azimuth","basefrequency","baseline-shift","begin","bias","by","class","clip","clippathunits","clip-path","clip-rule","color","color-interpolation","color-interpolation-filters","color-profile","color-rendering","cx","cy","d","dx","dy","diffuseconstant","direction","display","divisor","dur","edgemode","elevation","end","exponent","fill","fill-opacity","fill-rule","filter","filterunits","flood-color","flood-opacity","font-family","font-size","font-size-adjust","font-stretch","font-style","font-variant","font-weight","fx","fy","g1","g2","glyph-name","glyphref","gradientunits","gradienttransform","height","href","id","image-rendering","in","in2","intercept","k","k1","k2","k3","k4","kerning","keypoints","keysplines","keytimes","lang","lengthadjust","letter-spacing","kernelmatrix","kernelunitlength","lighting-color","local","marker-end","marker-mid","marker-start","markerheight","markerunits","markerwidth","maskcontentunits","maskunits","max","mask","mask-type","media","method","mode","min","name","numoctaves","offset","operator","opacity","order","orient","orientation","origin","overflow","paint-order","path","pathlength","patterncontentunits","patterntransform","patternunits","points","preservealpha","preserveaspectratio","primitiveunits","r","rx","ry","radius","refx","refy","repeatcount","repeatdur","restart","result","rotate","scale","seed","shape-rendering","slope","specularconstant","specularexponent","spreadmethod","startoffset","stddeviation","stitchtiles","stop-color","stop-opacity","stroke-dasharray","stroke-dashoffset","stroke-linecap","stroke-linejoin","stroke-miterlimit","stroke-opacity","stroke","stroke-width","style","surfacescale","systemlanguage","tabindex","tablevalues","targetx","targety","transform","transform-origin","text-anchor","text-decoration","text-rendering","textlength","type","u1","u2","unicode","values","viewbox","visibility","version","vert-adv-y","vert-origin-x","vert-origin-y","width","word-spacing","wrap","writing-mode","xchannelselector","ychannelselector","x","x1","x2","xmlns","y","y1","y2","z","zoomandpan"]),Gk=zn(["accent","accentunder","align","bevelled","close","columnsalign","columnlines","columnspan","denomalign","depth","dir","display","displaystyle","encoding","fence","frame","height","href","id","largeop","length","linethickness","lspace","lquote","mathbackground","mathcolor","mathsize","mathvariant","maxsize","minsize","movablelimits","notation","numalign","open","rowalign","rowlines","rowspacing","rowspan","rspace","rquote","scriptlevel","scriptminsize","scriptsizemultiplier","selection","separator","separators","stretchy","subscriptshift","supscriptshift","symmetric","voffset","width","xmlns"]),Ch=zn(["xlink:href","xml:id","xlink:title","xml:space","xmlns:xlink"]),iI=ji(/\{\{[\w\W]*|[\w\W]*\}\}/gm),rI=ji(/<%[\w\W]*|[\w\W]*%>/gm),aI=ji(/\$\{[\w\W]*/gm),oI=ji(/^data-[\-\w.\u00B7-\uFFFF]+$/),sI=ji(/^aria-[\-\w]+$/),Wk=ji(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),lI=ji(/^(?:\w+script|data):/i),cI=ji(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),Yk=ji(/^html$/i),uI=ji(/^[a-z][.\w]*(-[.\w]+)+$/i);var Kk=Object.freeze({__proto__:null,ARIA_ATTR:sI,ATTR_WHITESPACE:cI,CUSTOM_ELEMENT:uI,DATA_ATTR:oI,DOCTYPE_NAME:Yk,ERB_EXPR:rI,IS_ALLOWED_URI:Wk,IS_SCRIPT_OR_DATA:lI,MUSTACHE_EXPR:iI,TMPLIT_EXPR:aI});const wc={element:1,text:3,progressingInstruction:7,comment:8,document:9},dI=function(){return typeof window>"u"?null:window},hI=function(t,e){if(typeof t!="object"||typeof t.createPolicy!="function")return null;let n=null;const i="data-tt-policy-suffix";e&&e.hasAttribute(i)&&(n=e.getAttribute(i));const r="dompurify"+(n?"#"+n:"");try{return t.createPolicy(r,{createHTML(a){return a},createScriptURL(a){return a}})}catch{return console.warn("TrustedTypes policy "+r+" could not be created."),null}},Xk=function(){return{afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]}};function Jk(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:dI();const e=_=>Jk(_);if(e.version="3.3.1",e.removed=[],!t||!t.document||t.document.nodeType!==wc.document||!t.Element)return e.isSupported=!1,e;let{document:n}=t;const i=n,r=i.currentScript,{DocumentFragment:a,HTMLTemplateElement:o,Node:s,Element:l,NodeFilter:c,NamedNodeMap:u=t.NamedNodeMap||t.MozNamedAttrMap,HTMLFormElement:d,DOMParser:h,trustedTypes:p}=t,b=l.prototype,m=Tc(b,"cloneNode"),S=Tc(b,"remove"),g=Tc(b,"nextSibling"),y=Tc(b,"childNodes"),x=Tc(b,"parentNode");if(typeof o=="function"){const _=n.createElement("template");_.content&&_.content.ownerDocument&&(n=_.content.ownerDocument)}let v,k="";const{implementation:T,createNodeIterator:C,createDocumentFragment:R,getElementsByTagName:A}=n,{importNode:N}=i;let O=Xk();e.isSupported=typeof Uk=="function"&&typeof x=="function"&&T&&T.createHTMLDocument!==void 0;const{MUSTACHE_EXPR:z,ERB_EXPR:Y,TMPLIT_EXPR:L,DATA_ATTR:X,ARIA_ATTR:P,IS_SCRIPT_OR_DATA:G,ATTR_WHITESPACE:J,CUSTOM_ELEMENT:te}=Kk;let{IS_ALLOWED_URI:Z}=Kk,q=null;const ee=De({},[...qk,...jg,...Bg,...Ug,...Hk]);let $=null;const ue=De({},[...Vk,...zg,...Gk,...Ch]);let B=Object.seal(Mg(null,{tagNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},allowCustomizedBuiltInElements:{writable:!0,configurable:!1,enumerable:!0,value:!1}})),ve=null,j=null;const me=Object.seal(Mg(null,{tagCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeCheck:{writable:!0,configurable:!1,enumerable:!0,value:null}}));let be=!0,qt=!0,En=!1,Te=!0,Le=!1,ht=!0,lt=!1,hn=!1,fn=!1,At=!1,tn=!1,Nn=!1,Ri=!0,$i=!1;const fe="user-content-";let He=!0,we=!1,rt={},ft=null;const nn=De({},["annotation-xml","audio","colgroup","desc","foreignobject","head","iframe","math","mi","mn","mo","ms","mtext","noembed","noframes","noscript","plaintext","script","style","svg","template","thead","title","video","xmp"]);let Jn=null;const Ai=De({},["audio","video","img","source","image","track"]);let F=null;const oe=De({},["alt","class","for","id","label","name","pattern","placeholder","role","summary","title","value","style","xmlns"]),le="http://www.w3.org/1998/Math/MathML",Oe="http://www.w3.org/2000/svg",Ne="http://www.w3.org/1999/xhtml";let vt=Ne,On=!1,mi=null;const ka=De({},[le,Oe,Ne],Lg);let $n=De({},["mi","mo","mn","ms","mtext"]),Qn=De({},["annotation-xml"]);const Qi=De({},["title","style","font","a","script"]);let gi=null;const jl=["application/xhtml+xml","text/html"],Bl="text/html";let Ee=null,Mn=null;const Ul=n.createElement("form"),To=function(_){return _ instanceof RegExp||_ instanceof Function},qr=function(){let _=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(!(Mn&&Mn===_)){if((!_||typeof _!="object")&&(_={}),_=Dr(_),gi=jl.indexOf(_.PARSER_MEDIA_TYPE)===-1?Bl:_.PARSER_MEDIA_TYPE,Ee=gi==="application/xhtml+xml"?Lg:wh,q=ur(_,"ALLOWED_TAGS")?De({},_.ALLOWED_TAGS,Ee):ee,$=ur(_,"ALLOWED_ATTR")?De({},_.ALLOWED_ATTR,Ee):ue,mi=ur(_,"ALLOWED_NAMESPACES")?De({},_.ALLOWED_NAMESPACES,Lg):ka,F=ur(_,"ADD_URI_SAFE_ATTR")?De(Dr(oe),_.ADD_URI_SAFE_ATTR,Ee):oe,Jn=ur(_,"ADD_DATA_URI_TAGS")?De(Dr(Ai),_.ADD_DATA_URI_TAGS,Ee):Ai,ft=ur(_,"FORBID_CONTENTS")?De({},_.FORBID_CONTENTS,Ee):nn,ve=ur(_,"FORBID_TAGS")?De({},_.FORBID_TAGS,Ee):Dr({}),j=ur(_,"FORBID_ATTR")?De({},_.FORBID_ATTR,Ee):Dr({}),rt=ur(_,"USE_PROFILES")?_.USE_PROFILES:!1,be=_.ALLOW_ARIA_ATTR!==!1,qt=_.ALLOW_DATA_ATTR!==!1,En=_.ALLOW_UNKNOWN_PROTOCOLS||!1,Te=_.ALLOW_SELF_CLOSE_IN_ATTR!==!1,Le=_.SAFE_FOR_TEMPLATES||!1,ht=_.SAFE_FOR_XML!==!1,lt=_.WHOLE_DOCUMENT||!1,At=_.RETURN_DOM||!1,tn=_.RETURN_DOM_FRAGMENT||!1,Nn=_.RETURN_TRUSTED_TYPE||!1,fn=_.FORCE_BODY||!1,Ri=_.SANITIZE_DOM!==!1,$i=_.SANITIZE_NAMED_PROPS||!1,He=_.KEEP_CONTENT!==!1,we=_.IN_PLACE||!1,Z=_.ALLOWED_URI_REGEXP||Wk,vt=_.NAMESPACE||Ne,$n=_.MATHML_TEXT_INTEGRATION_POINTS||$n,Qn=_.HTML_INTEGRATION_POINTS||Qn,B=_.CUSTOM_ELEMENT_HANDLING||{},_.CUSTOM_ELEMENT_HANDLING&&To(_.CUSTOM_ELEMENT_HANDLING.tagNameCheck)&&(B.tagNameCheck=_.CUSTOM_ELEMENT_HANDLING.tagNameCheck),_.CUSTOM_ELEMENT_HANDLING&&To(_.CUSTOM_ELEMENT_HANDLING.attributeNameCheck)&&(B.attributeNameCheck=_.CUSTOM_ELEMENT_HANDLING.attributeNameCheck),_.CUSTOM_ELEMENT_HANDLING&&typeof _.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements=="boolean"&&(B.allowCustomizedBuiltInElements=_.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements),Le&&(qt=!1),tn&&(At=!0),rt&&(q=De({},Hk),$=[],rt.html===!0&&(De(q,qk),De($,Vk)),rt.svg===!0&&(De(q,jg),De($,zg),De($,Ch)),rt.svgFilters===!0&&(De(q,Bg),De($,zg),De($,Ch)),rt.mathMl===!0&&(De(q,Ug),De($,Gk),De($,Ch))),_.ADD_TAGS&&(typeof _.ADD_TAGS=="function"?me.tagCheck=_.ADD_TAGS:(q===ee&&(q=Dr(q)),De(q,_.ADD_TAGS,Ee))),_.ADD_ATTR&&(typeof _.ADD_ATTR=="function"?me.attributeCheck=_.ADD_ATTR:($===ue&&($=Dr($)),De($,_.ADD_ATTR,Ee))),_.ADD_URI_SAFE_ATTR&&De(F,_.ADD_URI_SAFE_ATTR,Ee),_.FORBID_CONTENTS&&(ft===nn&&(ft=Dr(ft)),De(ft,_.FORBID_CONTENTS,Ee)),_.ADD_FORBID_CONTENTS&&(ft===nn&&(ft=Dr(ft)),De(ft,_.ADD_FORBID_CONTENTS,Ee)),He&&(q["#text"]=!0),lt&&De(q,["html","head","body"]),q.table&&(De(q,["tbody"]),delete ve.tbody),_.TRUSTED_TYPES_POLICY){if(typeof _.TRUSTED_TYPES_POLICY.createHTML!="function")throw kc('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');if(typeof _.TRUSTED_TYPES_POLICY.createScriptURL!="function")throw kc('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');v=_.TRUSTED_TYPES_POLICY,k=v.createHTML("")}else v===void 0&&(v=hI(p,r)),v!==null&&typeof k=="string"&&(k=v.createHTML(""));zn&&zn(_),Mn=_}},wo=De({},[...jg,...Bg,...tI]),Co=De({},[...Ug,...nI]),zl=function(_){let I=x(_);(!I||!I.tagName)&&(I={namespaceURI:vt,tagName:"template"});const M=wh(_.tagName),ge=wh(I.tagName);return mi[_.namespaceURI]?_.namespaceURI===Oe?I.namespaceURI===Ne?M==="svg":I.namespaceURI===le?M==="svg"&&(ge==="annotation-xml"||$n[ge]):!!wo[M]:_.namespaceURI===le?I.namespaceURI===Ne?M==="math":I.namespaceURI===Oe?M==="math"&&Qn[ge]:!!Co[M]:_.namespaceURI===Ne?I.namespaceURI===Oe&&!Qn[ge]||I.namespaceURI===le&&!$n[ge]?!1:!Co[M]&&(Qi[M]||!wo[M]):!!(gi==="application/xhtml+xml"&&mi[_.namespaceURI]):!1},pn=function(_){xc(e.removed,{element:_});try{x(_).removeChild(_)}catch{S(_)}},mn=function(_,I){try{xc(e.removed,{attribute:I.getAttributeNode(_),from:I})}catch{xc(e.removed,{attribute:null,from:I})}if(I.removeAttribute(_),_==="is")if(At||tn)try{pn(I)}catch{}else try{I.setAttribute(_,"")}catch{}},Eo=function(_){let I=null,M=null;if(fn)_="<remove></remove>"+_;else{const ye=Ig(_,/^[\r\n\t ]+/);M=ye&&ye[0]}gi==="application/xhtml+xml"&&vt===Ne&&(_='<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>'+_+"</body></html>");const ge=v?v.createHTML(_):_;if(vt===Ne)try{I=new h().parseFromString(ge,gi)}catch{}if(!I||!I.documentElement){I=T.createDocument(vt,"template",null);try{I.documentElement.innerHTML=On?k:ge}catch{}}const Ie=I.body||I.documentElement;return _&&M&&Ie.insertBefore(n.createTextNode(M),Ie.childNodes[0]||null),vt===Ne?A.call(I,lt?"html":"body")[0]:lt?I.documentElement:Ie},Ro=function(_){return C.call(_.ownerDocument||_,_,c.SHOW_ELEMENT|c.SHOW_COMMENT|c.SHOW_TEXT|c.SHOW_PROCESSING_INSTRUCTION|c.SHOW_CDATA_SECTION,null)},Hr=function(_){return _ instanceof d&&(typeof _.nodeName!="string"||typeof _.textContent!="string"||typeof _.removeChild!="function"||!(_.attributes instanceof u)||typeof _.removeAttribute!="function"||typeof _.setAttribute!="function"||typeof _.namespaceURI!="string"||typeof _.insertBefore!="function"||typeof _.hasChildNodes!="function")},Ao=function(_){return typeof s=="function"&&_ instanceof s};function It(_,I,M){Th(_,ge=>{ge.call(e,I,M,Mn)})}const No=function(_){let I=null;if(It(O.beforeSanitizeElements,_,null),Hr(_))return pn(_),!0;const M=Ee(_.nodeName);if(It(O.uponSanitizeElement,_,{tagName:M,allowedTags:q}),ht&&_.hasChildNodes()&&!Ao(_.firstElementChild)&&Fn(/<[/\w!]/g,_.innerHTML)&&Fn(/<[/\w!]/g,_.textContent)||_.nodeType===wc.progressingInstruction||ht&&_.nodeType===wc.comment&&Fn(/<[/\w]/g,_.data))return pn(_),!0;if(!(me.tagCheck instanceof Function&&me.tagCheck(M))&&(!q[M]||ve[M])){if(!ve[M]&&Mo(M)&&(B.tagNameCheck instanceof RegExp&&Fn(B.tagNameCheck,M)||B.tagNameCheck instanceof Function&&B.tagNameCheck(M)))return!1;if(He&&!ft[M]){const ge=x(_)||_.parentNode,Ie=y(_)||_.childNodes;if(Ie&&ge){const ye=Ie.length;for(let U=ye-1;U>=0;--U){const W=m(Ie[U],!0);W.__removalCount=(_.__removalCount||0)+1,ge.insertBefore(W,g(_))}}}return pn(_),!0}return _ instanceof l&&!zl(_)||(M==="noscript"||M==="noembed"||M==="noframes")&&Fn(/<\/no(script|embed|frames)/i,_.innerHTML)?(pn(_),!0):(Le&&_.nodeType===wc.text&&(I=_.textContent,Th([z,Y,L],ge=>{I=Sc(I,ge," ")}),_.textContent!==I&&(xc(e.removed,{element:_.cloneNode()}),_.textContent=I)),It(O.afterSanitizeElements,_,null),!1)},Oo=function(_,I,M){if(Ri&&(I==="id"||I==="name")&&(M in n||M in Ul))return!1;if(!(qt&&!j[I]&&Fn(X,I))&&!(be&&Fn(P,I))&&!(me.attributeCheck instanceof Function&&me.attributeCheck(I,_))){if(!$[I]||j[I]){if(!(Mo(_)&&(B.tagNameCheck instanceof RegExp&&Fn(B.tagNameCheck,_)||B.tagNameCheck instanceof Function&&B.tagNameCheck(_))&&(B.attributeNameCheck instanceof RegExp&&Fn(B.attributeNameCheck,I)||B.attributeNameCheck instanceof Function&&B.attributeNameCheck(I,_))||I==="is"&&B.allowCustomizedBuiltInElements&&(B.tagNameCheck instanceof RegExp&&Fn(B.tagNameCheck,M)||B.tagNameCheck instanceof Function&&B.tagNameCheck(M))))return!1}else if(!F[I]&&!Fn(Z,Sc(M,J,""))&&!((I==="src"||I==="xlink:href"||I==="href")&&_!=="script"&&$L(M,"data:")===0&&Jn[_])&&!(En&&!Fn(G,Sc(M,J,"")))&&M)return!1}return!0},Mo=function(_){return _!=="annotation-xml"&&Ig(_,te)},Do=function(_){It(O.beforeSanitizeAttributes,_,null);const{attributes:I}=_;if(!I||Hr(_))return;const M={attrName:"",attrValue:"",keepAttr:!0,allowedAttributes:$,forceKeepAttr:void 0};let ge=I.length;for(;ge--;){const Ie=I[ge],{name:ye,namespaceURI:U,value:W}=Ie,pe=Ee(ye),je=W;let ae=ye==="value"?je:QL(je);if(M.attrName=pe,M.attrValue=ae,M.keepAttr=!0,M.forceKeepAttr=void 0,It(O.uponSanitizeAttribute,_,M),ae=M.attrValue,$i&&(pe==="id"||pe==="name")&&(mn(ye,_),ae=fe+ae),ht&&Fn(/((--!?|])>)|<\/(style|title|textarea)/i,ae)){mn(ye,_);continue}if(pe==="attributename"&&Ig(ae,"href")){mn(ye,_);continue}if(M.forceKeepAttr)continue;if(!M.keepAttr){mn(ye,_);continue}if(!Te&&Fn(/\/>/i,ae)){mn(ye,_);continue}Le&&Th([z,Y,L],Qe=>{ae=Sc(ae,Qe," ")});const Se=Ee(_.nodeName);if(!Oo(Se,pe,ae)){mn(ye,_);continue}if(v&&typeof p=="object"&&typeof p.getAttributeType=="function"&&!U)switch(p.getAttributeType(Se,pe)){case"TrustedHTML":{ae=v.createHTML(ae);break}case"TrustedScriptURL":{ae=v.createScriptURL(ae);break}}if(ae!==je)try{U?_.setAttributeNS(U,ye,ae):_.setAttribute(ye,ae),Hr(_)?pn(_):Fk(e.removed)}catch{mn(ye,_)}}It(O.afterSanitizeAttributes,_,null)},Fl=function _(I){let M=null;const ge=Ro(I);for(It(O.beforeSanitizeShadowDOM,I,null);M=ge.nextNode();)It(O.uponSanitizeShadowNode,M,null),No(M),Do(M),M.content instanceof a&&_(M.content);It(O.afterSanitizeShadowDOM,I,null)};return e.sanitize=function(_){let I=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},M=null,ge=null,Ie=null,ye=null;if(On=!_,On&&(_="<!-->"),typeof _!="string"&&!Ao(_))if(typeof _.toString=="function"){if(_=_.toString(),typeof _!="string")throw kc("dirty is not a string, aborting")}else throw kc("toString is not a function");if(!e.isSupported)return _;if(hn||qr(I),e.removed=[],typeof _=="string"&&(we=!1),we){if(_.nodeName){const pe=Ee(_.nodeName);if(!q[pe]||ve[pe])throw kc("root node is forbidden and cannot be sanitized in-place")}}else if(_ instanceof s)M=Eo("<!---->"),ge=M.ownerDocument.importNode(_,!0),ge.nodeType===wc.element&&ge.nodeName==="BODY"||ge.nodeName==="HTML"?M=ge:M.appendChild(ge);else{if(!At&&!Le&&!lt&&_.indexOf("<")===-1)return v&&Nn?v.createHTML(_):_;if(M=Eo(_),!M)return At?null:Nn?k:""}M&&fn&&pn(M.firstChild);const U=Ro(we?_:M);for(;Ie=U.nextNode();)No(Ie),Do(Ie),Ie.content instanceof a&&Fl(Ie.content);if(we)return _;if(At){if(tn)for(ye=R.call(M.ownerDocument);M.firstChild;)ye.appendChild(M.firstChild);else ye=M;return($.shadowroot||$.shadowrootmode)&&(ye=N.call(i,ye,!0)),ye}let W=lt?M.outerHTML:M.innerHTML;return lt&&q["!doctype"]&&M.ownerDocument&&M.ownerDocument.doctype&&M.ownerDocument.doctype.name&&Fn(Yk,M.ownerDocument.doctype.name)&&(W="<!DOCTYPE "+M.ownerDocument.doctype.name+`>
45
+ `)}}function hk(t,e){switch(t){case"started":return{type:"started",data:zP(e)};case"batch_complete":return{type:"batch_complete",data:FP(e)};case"answer_chunk":return{type:"answer_chunk",data:qP(e)};case"completed":return{type:"completed",data:HP(e)};case"error":return{type:"error",data:Zr(e,0,"stream_error","Transcript chat stream error")};default:return null}}function zP(t){return{sessionCount:Wa((t==null?void 0:t.sessionCount)??(t==null?void 0:t.SessionCount))??0,batchCount:Wa((t==null?void 0:t.batchCount)??(t==null?void 0:t.BatchCount))??0,timeframe:typeof((t==null?void 0:t.timeframe)??(t==null?void 0:t.Timeframe))=="string"?t.timeframe??t.Timeframe:void 0}}function FP(t){return{batchNumber:Wa((t==null?void 0:t.batchNumber)??(t==null?void 0:t.BatchNumber))??0,totalBatches:Wa((t==null?void 0:t.totalBatches)??(t==null?void 0:t.TotalBatches))??0,sessionsInBatch:Wa((t==null?void 0:t.sessionsInBatch)??(t==null?void 0:t.SessionsInBatch))??0}}function qP(t){return{content:typeof(t==null?void 0:t.content)=="string"?t.content:typeof(t==null?void 0:t.Content)=="string"?t.Content:""}}function HP(t){const e=fk((t==null?void 0:t.sessionUuids)??(t==null?void 0:t.SessionUUIDs)),n=fk((t==null?void 0:t.mapSummaries)??(t==null?void 0:t.MapSummaries));return{answer:typeof(t==null?void 0:t.answer)=="string"?t.answer:typeof(t==null?void 0:t.Answer)=="string"?t.Answer:"",sessionCount:Wa((t==null?void 0:t.sessionCount)??(t==null?void 0:t.SessionCount))??0,sessionUuids:e,batchCount:Wa((t==null?void 0:t.batchCount)??(t==null?void 0:t.BatchCount))??void 0,model:typeof(t==null?void 0:t.model)=="string"?t.model:typeof(t==null?void 0:t.Model)=="string"?t.Model:void 0,mapSummaries:n}}function Wa(t){if(typeof t=="number"&&!Number.isNaN(t))return t;if(typeof t=="string"&&t.trim()!==""){const e=Number(t);if(!Number.isNaN(e))return e}}function fk(t){if(Array.isArray(t))return t.map(e=>String(e))}const pk="https://app.coragents.ai";class vh extends _p{constructor(e,n,i,r){super(),this.state=null,this.isPaused=!1,this.preferredMicrophoneDeviceId=null,this.isAudioTrackPublished=!1,this.speakingState=null,this.captureScreen=null,this.sessionUuid=null,this.roomId=null,this.joinToken=null,this.roomUrl=null,this.room=null,this.startedAt=null,this.isMultilingual=!1,this.languageCodes=null,this.defaultLanguageCode=null,this.voiceId=null,this.selectedLanguage=null,this.agentAnalyser=null,this.userAnalyser=null,this.agentAudioContext=null,this.userAudioContext=null,this.frequencyDataBuffer=null,this.humanJoinAcked=!1,this.humanJoinRetryTimeout=null,this.humanJoinRetryCount=0,this.humanJoinInFlight=!1,this.humanJoinPayload=null,this.chatMessages=[],this.publishedAudioStream=null,this.publishedAudioTrack=null,this.transcriptionStreams=[],this.appToken=e,this.planId=n,this.clientType=i,this.api=r.api||new ck({baseUrl:pk}),this.identity=r.identity||null,this.roomFactory=r.roomFactory||(a=>new zs(a)),this.captureScreen=r.captureScreen||null,this.preferredMicrophoneDeviceId=r.preferredMicrophoneDeviceId||null}async start(e){this.planId,e==null||e.roomId,this.setState("connecting"),this.speakingStateChanged("thinking");try{const i=(await this.api.clientStartSession(this.appToken,{client_type:this.clientType,...this.planId&&{onboarding_plan:this.planId},...this.planId&&(e==null?void 0:e.roomId)&&{room_id:e.roomId}})).data;if(!(i!=null&&i.url)||!(i!=null&&i.token)||!(i!=null&&i.room)||!(i!=null&&i.session_uuid))throw new Error("Invalid room info");this.sessionUuid=i==null?void 0:i.session_uuid,this.roomId=i==null?void 0:i.room,this.joinToken=i==null?void 0:i.token,this.roomUrl=i==null?void 0:i.url,this.startedAt=Date.now(),this.isMultilingual=(i==null?void 0:i.is_multilingual)||!1,this.languageCodes=(i==null?void 0:i.language_codes)||null,this.defaultLanguageCode=(i==null?void 0:i.default_language_code)||null,this.voiceId=(i==null?void 0:i.voice_id)||null,await this.joinRoom({withMicrophone:e==null?void 0:e.withMicrophone}),this.setState("volume-check"),this.planId,this.sessionUuid}catch(n){console.error("[obi] error starting session",{error:n}),this.setState("error")}}async joinRoom({withMicrophone:e=!1,withStateRecovery:n=!1}={}){if(this.room=this.roomFactory({adaptiveStream:!0,dynacast:!0}),this.resetHumanJoinHandshake(),this.room.on(Q.Disconnected,i=>{if(!this.room)return;this.transcriptionStreams=[],this.emit("captions",[]);let r=null;switch(i){case 12:r="invalid-room";break}this.shutdown(r)}),this.room.on(Q.TrackSubscribed,i=>{if(console.info("[obi] track subscribed kind=",i.kind,"source=",i.source),i.kind==="audio"&&(i.attach(),i.source===V.Source.Microphone)){this.agentAnalyser&&(this.agentAnalyser.disconnect(),this.agentAnalyser=null),this.agentAudioContext&&(this.agentAudioContext.close(),this.agentAudioContext=null);const{analyser:r,context:a}=this.createFFT(i.mediaStream);this.agentAnalyser=r,this.agentAudioContext=a}}),this.room.on(Q.LocalTrackPublished,i=>{if(console.info("[obi] local track published kind=",i.kind,"source=",i.source),i.kind==="audio"){this.userAnalyser&&(this.userAnalyser.disconnect(),this.userAnalyser=null),this.userAudioContext&&(this.userAudioContext.close(),this.userAudioContext=null);const{analyser:r,context:a}=this.createFFT(i.audioTrack.mediaStream);this.userAnalyser=r,this.userAudioContext=a}}),this.room.on(Q.ParticipantAttributesChanged,i=>{if(!i["lk.agent.state"])return;const r=i["lk.agent.state"];switch(r){case"speaking":this.speakingStateChanged("speaking");break;case"listening":this.speakingStateChanged("listening");break;case"thinking":this.speakingStateChanged("thinking");break;default:console.warn("[obi] unknown speaking state",r)}}),this.room.on(Q.DataReceived,async i=>{try{const r=new TextDecoder().decode(i),a=JSON.parse(r);switch(a.status||a.request||a.type){case"course_progress":typeof a.current_step=="number"&&typeof a.total_steps=="number"&&Array.isArray(a.step_names)&&this.emit("courseProgress",{currentStep:Math.max(1,a.current_step),totalSteps:Math.max(1,a.total_steps),stepNames:a.step_names});break;case"introduction_complete":this.emit("introductionComplete");break;case"course_selection":if(Array.isArray(a.courses)){const s=a.courses.map(l=>{if(typeof(l==null?void 0:l.uuid)!="string"||typeof(l==null?void 0:l.name)!="string")return console.warn("[obi] skipping invalid course in course_selection",l),null;const c={uuid:l.uuid,name:l.name};return typeof l.description=="string"&&(c.description=l.description),typeof l.overview=="string"&&(c.overview=l.overview),typeof l.goal=="string"&&(c.goal=l.goal),typeof l.agent_type=="string"&&(c.agent_type=l.agent_type),typeof l.duration=="number"&&(c.duration=l.duration),typeof l.order=="number"&&(c.order=l.order),typeof l.completed=="boolean"&&(c.completed=l.completed),c}).filter(l=>l!==null);this.emit("courseSelection",{courses:s})}break;case"open_text_input":this.emit("textInputRequested");break;case"using_tool":this.speakingStateChanged("busy");break;case"using_tool_ended":this.speakingStateChanged("speaking");break;case"prompt_user":this.setState("volume-check");break;case"mic_check":this.setState("mic-check");break;case"share_mic":this.setState("mic-share");break;case"share_screen":this.setState("screen-share");break;case"navigate":this.setState("navigate");break;case"in_progress":this.setState("in-progress");break;case"shutdown":this.shutdown("server-sent");break;case"mute_microphone":this.muteMicrophone();break;case"unmute_microphone":this.unmuteMicrophone();break;case"transcript":this.emit("transcript",a.transcript,a.role);break;case"screen_capture":this.captureScreenshareFrame().then(s=>{this.emit("screenCaptureNotification",s)}).catch(s=>{console.error("[obi] failed to capture screenshare frame on notification",s),this.emit("screenCaptureNotification",null)});break;case"human_joined_ack":this.handleHumanJoinedAck();break;default:console.warn("[obi] unknown data received",a)}}catch(r){console.error("[obi] error parsing data",r)}}),this.room.localParticipant.registerRpcMethod("mic_check",async i=>(this.sessionUuid,await this.checkMicrophone()?"ok":"error")),this.room.localParticipant.registerRpcMethod("screen_capture",async i=>{if(!this.captureScreen)return console.error("[obi] no captureScreen function provided"),"error";let r=null,a=null;try{r=await this.captureScreen()}catch(o){r=null,a=o}if(!r||a)return console.error("[obi] error capturing screen",{error:a}),"error";try{return await this.room.localParticipant.sendFile(new File([r],"screen_capture.png",{type:"image/png"}),{mimeType:"image/png",topic:"screen_capture"}),this.emit("screenCaptured",r),"ok"}catch(o){return console.error("[obi] error sending screen capture",{error:o}),"error"}}),this.room.localParticipant.registerRpcMethod("send_chat_message",async i=>{var r,a;try{const o=i!=null&&i.payload?JSON.parse(i.payload):{},s=typeof(o==null?void 0:o.message)=="string"&&o.message.trim().length>0?o.message.trim():null;if(!s)return console.warn("[obi] received send_chat_message with empty payload"),"error";const l=typeof o.timestamp=="number"&&!Number.isNaN(o.timestamp)?o.timestamp:Date.now();let c=null,u=null;const d=(r=this.room)==null?void 0:r.remoteParticipants.get("agent-avatar");if(d)c=d.identity,u=d.name??null;else if(this.room){for(const p of this.room.remoteParticipants.values())if((a=p.identity)!=null&&a.startsWith("agent-")){c=p.identity,u=p.name??null;break}}const h=typeof o.sender_name=="string"&&o.sender_name.trim().length>0?o.sender_name.trim():u||"Agent";return this.appendChatMessage({id:typeof o.id=="string"&&o.id.length>0?o.id:`agent-${i.requestId||Date.now()}`,timestamp:l,message:s,from:{identity:c||"agent-avatar",name:h},attributes:{senderName:h,source:"agent-rpc"},isAgent:!0}),"ok"}catch(o){return console.error("[obi] failed to handle send_chat_message RPC",o),"error"}}),this.room.registerTextStreamHandler("lk.transcription",async(i,r)=>{var l;const o=((l=i.info.attributes)==null?void 0:l["lk.segment_id"])||i.info.id;let s="";for await(const c of i){s+=c;const u=this.transcriptionStreams.findIndex(h=>{var m;return(((m=h.streamInfo.attributes)==null?void 0:m["lk.segment_id"])||h.streamInfo.id)===o}),d={text:s,participantInfo:{identity:r.identity},streamInfo:i.info};u>=0?this.transcriptionStreams[u]=d:this.transcriptionStreams.push(d),this.emit("captions",[...this.transcriptionStreams])}}),await this.room.connect(this.roomUrl,this.joinToken),e){this.isPaused;try{await this.room.localParticipant.setMicrophoneEnabled(!0,{deviceId:this.preferredMicrophoneDeviceId||void 0}),this.isMicShared=!0}catch(i){if(this.preferredMicrophoneDeviceId)console.warn("[obi] joinRoom: failed to set microphone with preferred device, retrying with default",i),await this.room.localParticipant.setMicrophoneEnabled(!0),this.isMicShared=!0;else throw i}this.isPaused,this.isPaused&&this.muteMicrophone()}if(n){let i=!1;for(const r of this.room.remoteParticipants.values())r.isSpeaking&&(i=!0);i?this.speakingStateChanged("speaking"):this.speakingStateChanged("listening"),this.selectedLanguage&&this.setLanguage(this.selectedLanguage).catch(r=>{console.error("[obi] failed to restore language selection",r)})}}async continue(){this.sessionUuid,this.speakingStateChanged("thinking"),await this.sendData({request:"prompt_user",success:!0})}async checkMicrophone(){let e=!1;try{e=(await navigator.permissions.query({name:"microphone"})).state==="granted"}catch(n){console.error("[obi] error checking microphone permission:",n)}return e?(this.sessionUuid,await this.room.localParticipant.setMicrophoneEnabled(!0),this.isMicShared=!0):this.sessionUuid,e&&this.clientType==="sdk"&&this.setState("in-progress"),this.emit("micCheckComplete",e),e}async shareMicrophone(){this.sessionUuid;let e=null,n=null;try{e=await this.room.localParticipant.setMicrophoneEnabled(!0,{deviceId:this.preferredMicrophoneDeviceId||void 0}),this.isMicShared=!0}catch(i){if(this.preferredMicrophoneDeviceId){console.warn("[obi] failed to share microphone with preferred device, retrying with default",i);try{e=await this.room.localParticipant.setMicrophoneEnabled(!0),this.isMicShared=!0}catch(r){n=r,this.isMicShared=!1}}else n=i,this.isMicShared=!1}e?this.sessionUuid:console.error("[obi] failed to share microphone",{error:n}),await this.sendData({request:"share_mic",success:!!e}),this.clientType==="sdk"&&this.setState("in-progress")}async shareMicrophoneFailed(){this.isMicShared=!1,await this.sendData({request:"share_mic",success:!1}),this.clientType==="sdk"&&this.setState("in-progress")}async sendHumanJoined(e){if(this.clientType!=="meet")return;const n=this.buildHumanJoinedPayload(e);if(!this.isSameHumanJoinPayload(n,this.humanJoinPayload)){if(this.humanJoinPayload=n,this.humanJoinAcked){if(this.humanJoinInFlight)return;await this.publishHumanJoinedUpdate(n);return}this.humanJoinRetryTimeout||this.humanJoinInFlight||(this.humanJoinRetryCount=0,await this.trySendHumanJoined())}}async publishAudioTrack(){if(this.sessionUuid,!this.room)return console.error("[obi] cannot publish audio track: room not connected"),!1;let e=!1;try{if(!navigator.mediaDevices||!navigator.mediaDevices.getUserMedia){const c=!!navigator.mediaDevices;return console.error("[obi] getUserMedia not available in this environment",c),!1}console.log("[obi] requesting audio track via getUserMedia");try{const c=this.preferredMicrophoneDeviceId?{deviceId:{exact:this.preferredMicrophoneDeviceId}}:!0;this.publishedAudioStream=await navigator.mediaDevices.getUserMedia({audio:c})}catch(c){if(this.preferredMicrophoneDeviceId)console.warn("[obi] failed to get user media with preferred device, retrying with default",c),this.publishedAudioStream=await navigator.mediaDevices.getUserMedia({audio:!0});else throw c}const n=this.publishedAudioStream.getAudioTracks().map(c=>{var u,d;return{id:c.id,label:c.label,enabled:c.enabled,muted:c.muted,readyState:c.readyState,constraints:(u=c.getConstraints)==null?void 0:u.call(c),settings:(d=c.getSettings)==null?void 0:d.call(c)}});console.log("[obi] getUserMedia resolved",n);const i=this.publishedAudioStream.getAudioTracks()[0];if(!i){const c=this.publishedAudioStream.getAudioTracks().length;return console.warn("[obi] no audio track found from getUserMedia stream",c),!1}this.publishedAudioTrack=i;const r={id:i.id,label:i.label,kind:i.kind,readyState:i.readyState},a=this.room.localParticipant.identity;console.log("[obi] publishing audio track to LiveKit",r,a);const o=await this.room.localParticipant.publishTrack(i,{name:"microphone",source:V.Source.Microphone});console.log("[obi] published audio track to LiveKit",i.id,a,o.isEnabled),this.userAnalyser&&(this.userAnalyser.disconnect(),this.userAnalyser=null),this.userAudioContext&&(this.userAudioContext.close(),this.userAudioContext=null);const{analyser:s,context:l}=this.createFFT(this.publishedAudioStream);this.userAnalyser=s,this.userAudioContext=l,this.isAudioTrackPublished=!0,e=!0}catch(n){if(console.error("[obi] failed to publish audio track",n),this.isAudioTrackPublished=!1,this.publishedAudioStream){try{this.publishedAudioStream.getTracks().forEach(i=>i.stop())}catch(i){console.warn("[obi] error stopping tracks during cleanup",i)}this.publishedAudioStream=null}this.publishedAudioTrack=null}return e}async setScreenShareEnabled(e){var i,r;if(this.sessionUuid,this.room,(i=this.room)==null||i.state,!this.room){console.warn("[obi] cannot set screen share: room not connected");return}const n=await this.room.localParticipant.setScreenShareEnabled(e,e?{video:{displaySurface:"window"}}:void 0);if(e&&n){const a=n.track,o=a==null?void 0:a.mediaStreamTrack;console.info("[obi] screen share track published",{trackSid:n.trackSid,trackName:n.trackName,source:n.source,isEnabled:n.isEnabled,isMuted:n.isMuted,isSubscribed:n.isSubscribed,mediaTrackEnabled:o==null?void 0:o.enabled,mediaTrackMuted:o==null?void 0:o.muted,mediaTrackReadyState:o==null?void 0:o.readyState,mediaTrackLabel:o==null?void 0:o.label,mediaTrackContentHint:o==null?void 0:o.contentHint,videoSettings:(r=o==null?void 0:o.getSettings)==null?void 0:r.call(o)})}await this.sendData({request:"share_screen",success:e}),e&&this.setState("navigate")}async shareScreen(){this.sessionUuid,await this.setScreenShareEnabled(!0)}async captureScreenshareFrame(){if(!this.room)return console.warn("[obi] cannot capture screenshare frame: no room"),null;const e=this.room.localParticipant.getTrackPublications();let n=null;for(const i of e)if(i.kind==="video"&&i.source===V.Source.ScreenShare&&i.track){n=i.track.mediaStreamTrack;break}if(!n)return console.warn("[obi] no screenshare track found to capture frame from"),null;try{const i=document.createElement("video");i.srcObject=new MediaStream([n]),i.muted=!0,await new Promise((s,l)=>{i.onloadedmetadata=()=>s(),i.onerror=()=>l(new Error("Failed to load video metadata")),setTimeout(()=>l(new Error("Video metadata load timeout")),5e3)}),await i.play();const r=document.createElement("canvas");r.width=i.videoWidth,r.height=i.videoHeight;const a=r.getContext("2d");if(!a)return console.error("[obi] failed to get canvas context"),null;a.drawImage(i,0,0,r.width,r.height);const o=r.toDataURL("image/png");return i.pause(),i.srcObject=null,r.width,r.height,o.length,o}catch(i){return console.error("[obi] failed to capture screenshare frame",i),null}}async pause(){this.muteMicrophone(),this.isPaused=!0,this.emit("paused"),await this.sendData({request:"pause"}),console.log("[obi] paused session",{sessionUuid:this.sessionUuid})}async unpause(){this.unmuteMicrophone(),this.isPaused=!1,this.emit("unpaused"),await this.sendData({request:"unpause"}),console.log("[obi] unpaused session",{sessionUuid:this.sessionUuid})}async endCourse(){await this.sendData({request:"end_course"})}async switchMicrophoneDevice(e){var n;if(this.sessionUuid,this.room,(n=this.room)==null||n.state,this.isMicShared,!this.room)return console.warn("[obi] cannot switch microphone device: room not connected"),!1;try{const i=await this.room.switchActiveDevice("audioinput",e);return i?(this.preferredMicrophoneDeviceId=e,this.sessionUuid):console.warn("[obi] failed to switch microphone device",{deviceId:e}),i}catch(i){return console.error("[obi] error switching microphone device",{err:i,deviceId:e}),!1}}muteMicrophone(){this.sessionUuid,this.room.localParticipant.getTrackPublications().forEach(e=>{var n,i;e.kind==="audio"&&e.source===V.Source.Microphone&&(e.handleMuted(),(i=(n=e.track)==null?void 0:n.mediaStream)==null||i.getTracks().forEach(r=>r.enabled=!1))})}unmuteMicrophone(){this.sessionUuid,this.room.localParticipant.getTrackPublications().forEach(e=>{var n,i;e.kind==="audio"&&e.source===V.Source.Microphone&&(e.handleUnmuted(),(i=(n=e.track)==null?void 0:n.mediaStream)==null||i.getTracks().forEach(r=>r.enabled=!0))})}async stop(){this.emit("stopped"),await this.shutdown()}async shutdown(e=null){if(this.resetHumanJoinHandshake({clearPayload:!0}),this.room){if(this.sessionUuid,this.publishedAudioTrack&&this.isAudioTrackPublished)try{console.log("[obi] unpublishing audio track",this.publishedAudioTrack.id,this.room.localParticipant.identity),this.room.localParticipant.unpublishTrack(this.publishedAudioTrack)}catch(i){console.warn("[obi] failed to unpublish audio track",i)}if(this.publishedAudioStream)try{const i=this.publishedAudioStream.getAudioTracks().length;console.log("[obi] stopping published audio stream tracks",i),this.publishedAudioStream.getTracks().forEach(r=>r.stop())}catch(i){console.warn("[obi] error stopping published audio tracks",i)}try{this.room.unregisterTextStreamHandler("lk.transcription")}catch(i){console.warn("[obi] failed to unregister text stream handler",i)}e!=="server-sent"&&await this.sendData({request:"shutdown"});const n=this.room;this.room=null,await n.disconnect(),this.sessionUuid}this.transcriptionStreams=[],this.agentAnalyser&&(this.agentAnalyser.disconnect(),this.agentAnalyser=null),this.agentAudioContext&&(this.agentAudioContext.close(),this.agentAudioContext=null),this.userAnalyser&&(this.userAnalyser.disconnect(),this.userAnalyser=null),this.userAudioContext&&(this.userAudioContext.close(),this.userAudioContext=null),this.isAudioTrackPublished=!1,this.publishedAudioStream=null,this.publishedAudioTrack=null,this.clearChatMessages(),this.sessionUuid=null,this.roomId=null,this.joinToken=null,this.roomUrl=null,this.frequencyDataBuffer=null,this.emit("shutdown",e)}async say(e){this.speakingStateChanged("thinking"),this.isPaused&&await this.unpause(),await this.sendData({request:"say",message:e})}appendChatMessage(e){const n={...e,from:e.from?{...e.from}:e.from,attributes:e.attributes?{...e.attributes}:e.attributes};this.chatMessages=[...this.chatMessages,n],this.emit("chatMessagesChanged",[...this.chatMessages]),this.emit("chatMessageReceived",n)}clearChatMessages(){this.chatMessages.length&&(this.chatMessages=[],this.emit("chatMessagesChanged",[]))}async setLanguage(e){var n;this.selectedLanguage=e,(n=this.room)!=null&&n.localParticipant&&await this.sendData({request:"set_language",language_code:e})}serialise(){return JSON.stringify({state:this.state,speakingState:this.speakingState,appToken:this.appToken,planId:this.planId,clientType:this.clientType,isPaused:this.isPaused,identity:this.identity,sessionUuid:this.sessionUuid,roomId:this.roomId,joinToken:this.joinToken,roomUrl:this.roomUrl,startedAt:this.startedAt,isMultilingual:this.isMultilingual,languageCodes:this.languageCodes,defaultLanguageCode:this.defaultLanguageCode,voiceId:this.voiceId,selectedLanguage:this.selectedLanguage,preferredMicrophoneDeviceId:this.preferredMicrophoneDeviceId,chatMessages:this.chatMessages.map(e=>({...e,from:e.from?{...e.from}:e.from,attributes:e.attributes?{...e.attributes}:e.attributes}))})}audioSpectrum(){return this.speakingState==="speaking"&&this.agentAnalyser?this.normaliseSpectrum(this.agentAnalyser):this.speakingState==="listening"&&this.userAnalyser?this.normaliseSpectrum(this.userAnalyser):null}agentAudioSpectrum(){return this.agentAnalyser?this.normaliseSpectrum(this.agentAnalyser):null}normaliseSpectrum(e){const i=e.context.sampleRate/2/e.frequencyBinCount;(!this.frequencyDataBuffer||this.frequencyDataBuffer.length!==e.frequencyBinCount)&&(this.frequencyDataBuffer=new Uint8Array(new ArrayBuffer(e.frequencyBinCount))),e.getByteFrequencyData(this.frequencyDataBuffer);const r=[],a=50,o=5e3,s=8,l=Math.pow(o/a,1/s);for(let c=0;c<s;c++){const u=a*Math.pow(l,c),d=a*Math.pow(l,c+1),h=Math.floor(u/i),p=Math.floor(d/i),b=Math.min(p,this.frequencyDataBuffer.length),m=Math.min(h,b);if(m<b){let S=0;for(let y=m;y<b;y++)S+=this.frequencyDataBuffer[y];const g=S/(b-m)/255;r.push(g)}else r.push(0)}return r}setState(e){this.state;const n=this.state;this.state=e,this.emit("stateChanged",e,n)}static deserialise(e,n,i,r={}){const a=JSON.parse(e),o=new vh(n,a.planId,i,r);return o.state=a.state,o.speakingState=a.speakingState,o.identity=a.identity||null,o.isPaused=a.isPaused||!1,o.sessionUuid=a.sessionUuid||null,o.roomId=a.roomId||null,o.joinToken=a.joinToken||null,o.roomUrl=a.roomUrl||null,o.startedAt=a.startedAt||null,o.isMultilingual=a.isMultilingual||!1,o.languageCodes=a.languageCodes||null,o.defaultLanguageCode=a.defaultLanguageCode||null,o.voiceId=a.voiceId||null,o.selectedLanguage=a.selectedLanguage||null,o.preferredMicrophoneDeviceId=a.preferredMicrophoneDeviceId||r.preferredMicrophoneDeviceId||null,o.chatMessages=(a.chatMessages||[]).map(s=>({...s,from:s.from?{...s.from}:s.from,attributes:s.attributes?{...s.attributes}:s.attributes})),o}buildHumanJoinedPayload(e){const n={request:"human_joined"};return e!=null&&e.name&&e.name.trim().length>0&&(n.name=e.name.trim()),e!=null&&e.email&&e.email.trim().length>0&&(n.email=e.email.trim()),typeof(e==null?void 0:e.screenShareSupported)=="boolean"&&(n.screen_share_supported=e.screenShareSupported),n}isSameHumanJoinPayload(e,n){return!e||!n?!1:(e.name??void 0)===(n.name??void 0)&&(e.email??void 0)===(n.email??void 0)&&e.screen_share_supported===n.screen_share_supported}async trySendHumanJoined(){if(this.clientType!=="meet"||this.humanJoinAcked||this.humanJoinInFlight)return;if(this.humanJoinInFlight=!0,!this.room||this.room.state!==Xe.Connected||!this.room.localParticipant){this.humanJoinInFlight=!1,this.scheduleHumanJoinRetry();return}const e=this.humanJoinPayload||{request:"human_joined"};try{await this.room.localParticipant.publishData(new TextEncoder().encode(JSON.stringify(e)),{reliable:!0})}catch(n){console.warn("[obi] failed to publish human_joined message",n)}finally{this.humanJoinInFlight=!1}this.humanJoinAcked||this.scheduleHumanJoinRetry()}async publishHumanJoinedUpdate(e){if(!(!this.room||this.room.state!==Xe.Connected||!this.room.localParticipant)){this.humanJoinInFlight=!0;try{await this.room.localParticipant.publishData(new TextEncoder().encode(JSON.stringify(e)),{reliable:!0})}catch(n){console.warn("[obi] failed to publish human_joined message",n)}finally{this.humanJoinInFlight=!1}}}scheduleHumanJoinRetry(){if(this.humanJoinAcked||this.humanJoinRetryTimeout)return;const e=Math.min(500*Math.pow(2,this.humanJoinRetryCount),5e3);this.humanJoinRetryCount+=1,this.humanJoinRetryTimeout=setTimeout(()=>{this.humanJoinRetryTimeout=null,this.trySendHumanJoined()},e)}clearHumanJoinRetryTimer(){this.humanJoinRetryTimeout&&(clearTimeout(this.humanJoinRetryTimeout),this.humanJoinRetryTimeout=null)}resetHumanJoinHandshake(e={}){this.clearHumanJoinRetryTimer(),this.humanJoinAcked=!1,this.humanJoinInFlight=!1,this.humanJoinRetryCount=0,e.clearPayload&&(this.humanJoinPayload=null)}handleHumanJoinedAck(){this.humanJoinAcked||(this.humanJoinAcked=!0,this.humanJoinInFlight=!1,this.humanJoinRetryCount=0,this.clearHumanJoinRetryTimer())}speakingStateChanged(e){this.speakingState;const n=this.speakingState;this.speakingState=e,this.emit("speakingStateChanged",e,n)}async sendData(e){await this.room.localParticipant.publishData(new TextEncoder().encode(JSON.stringify(e)),{reliable:!0})}createFFT(e){const n=new AudioContext,i=n.createAnalyser();return n.createMediaStreamSource(e).connect(i),i.fftSize=2048,i.smoothingTimeConstant=.6,{analyser:i,context:n}}}class bh extends _p{constructor(e,n,i={}){super(),this.state="loading",this.error=null,this.identity=null,this.product=null,this.engagement=null,this.plans=[],this.planIsCompleted=[],this.selectedPlan=null,this.selectedPlanUuid=null,this.showWidget=!1,this.session=null,this.captureScreen=null,this.preferredMicrophoneDeviceId=null,this.appToken=e,this.clientType=n,this.api=i.api||new ck({baseUrl:i.apiBaseUrl||pk}),this.sessionFactory=i.sessionFactory||((r,a,o,s)=>new vh(r,a,o,s)),this.captureScreen=i.captureScreen||null}async initialise(e={}){var n,i,r,a,o,s,l;if(!this.appToken)throw new Error("App token is required");this.setState("loading");try{const c=await this.api.clientInitialise(this.appToken,{identity:e.identity,client_type:this.clientType});this.identity=e.identity||null,this.product=((n=c.data)==null?void 0:n.product)||null,this.plans=((i=c.data)==null?void 0:i.onboarding_plans)||[],this.selectedPlan=((r=c.data)==null?void 0:r.selected_plan)||null,this.planIsCompleted=((a=c.data)==null?void 0:a.plan_is_completed)||[],this.showWidget=((o=c.data)==null?void 0:o.show_widget)||!1,this.engagement=((s=c.data)==null?void 0:s.engagement)||null;const u=((l=this.product)==null?void 0:l.track_onboardee_token)??!0;if(this.api.setTrackOnboardeeToken(u),e.planUuid){let d=null,h=!1;try{const p=await this.api.getPlanSDK(e.planUuid);if(p.error)throw new Error(`Plan not found: ${p.error}`);p.data&&(d=p.data)}catch(p){try{const b=await this.api.getSessionPlan(e.planUuid);if(b.error)throw new Error(`Session plan not found: ${b.error}`);b.data&&(d=b.data,h=!0)}catch(b){console.error("[obi] error getting plan via both endpoints",{planErr:p,sessionErr:b})}}d?(this.selectedPlan=d,this.selectedPlanUuid=h?d.uuid:e.planUuid):console.warn("[obi] plan not found",{planUuid:e.planUuid})}this.identity,this.product,this.plans,this.selectedPlan,this.showWidget}catch(c){throw this.error=c instanceof Error?c:new Error(String(c)),this.setState("error"),c}finally{this.setState("ready")}}selectPlan(e){this.selectedPlan=e,this.selectedPlanUuid=(e==null?void 0:e.uuid)||null,this.emit("planSelected",e)}setPreferredMicrophoneDeviceId(e){this.preferredMicrophoneDeviceId=e,this.session&&(this.session.preferredMicrophoneDeviceId=e)}async startSession(e,n,i){return await this._stopSession(),this.session=this.sessionFactory(this.appToken,e,this.clientType,{api:this.api,identity:this.identity,captureScreen:this.captureScreen,preferredMicrophoneDeviceId:this.preferredMicrophoneDeviceId}),this.prepareSession(n),this.session.start(i).then(()=>{this.emit("sessionStarted",this.session)}).catch(r=>{this.session=null,console.error("[obi] error starting session",r)}),this.session}async resumeSession(e){var n,i;return this.state,(n=this.session)==null||n.state,(i=this.session)==null||i.speakingState,this.session.captureScreen=this.captureScreen,this.prepareSession(e),this.session.joinRoom({withMicrophone:!0,withStateRecovery:!0}).then(()=>{this.emit("sessionResumed",this.session)}).catch(r=>{console.error("[obi] error joining room",{error:r}),r instanceof Error&&r.message==="Room is not connected"&&this.session.stop()}),this.session}prepareSession(e){if(!this.session)throw new Error("No session to prepare");return e(this.session),this.session.on("stopped",()=>{this.emit("sessionStopped")}),this.session.on("shutdown",n=>{var i,r,a;if((i=this.session)!=null&&i.startedAt&&this.session.startedAt+5*60*1e3<Date.now()){const o=this.plans.findIndex(s=>{var l;return s.uuid===((l=this.selectedPlan)==null?void 0:l.uuid)});o!==-1&&(this.planIsCompleted[o]=!0)}(a=(r=this.session)==null?void 0:r.removeAllListeners)==null||a.call(r),this.selectedPlan=null,this.selectedPlanUuid=null,this.emit("sessionShutdown",n),this.session=null}),this.session}async stopSession(){await this._stopSession(),this.selectedPlan&&this.selectPlan(null)}async _stopSession(){this.session&&(this.trackEvent("session-stopped",{sessionUuid:this.session.sessionUuid}),await this.session.stop(),this.session=null)}isLoading(){return this.state==="loading"}isReady(){return this.state==="ready"}serialise(){var e;return JSON.stringify({state:this.state,appToken:this.appToken,clientType:this.clientType,identity:this.identity,product:this.product,engagement:this.engagement,plans:this.plans,selectedPlan:this.selectedPlan,selectedPlanUuid:this.selectedPlanUuid,showWidget:this.showWidget,session:(e=this.session)==null?void 0:e.serialise(),preferredMicrophoneDeviceId:this.preferredMicrophoneDeviceId,serialisedAt:new Date().toISOString()})}static deserialise(e,n,i,r={}){const a=JSON.parse(e),o=new bh(n,i,r);return o.state=a.state,o.identity=a.identity||null,o.product=a.product||null,o.engagement=a.engagement||null,o.plans=a.plans||[],o.selectedPlan=a.selectedPlan||null,o.selectedPlanUuid=a.selectedPlanUuid||null,o.showWidget=a.showWidget||!1,o.preferredMicrophoneDeviceId=a.preferredMicrophoneDeviceId||null,a.session&&(o.session=vh.deserialise(a.session,n,i,{api:o.api,preferredMicrophoneDeviceId:o.preferredMicrophoneDeviceId})),o}setState(e){const n=this.state;this.state=e,this.emit("stateChanged",e,n)}trackEvent(e,n={}){var i,r,a;this.emit("trackEvent",e,{...n,clientType:this.clientType,planId:(i=this.selectedPlan)==null?void 0:i.uuid,productId:(r=this.product)==null?void 0:r.uuid,sessionId:(a=this.session)==null?void 0:a.sessionUuid})}}var mk={exports:{}},yh={};var VP=Symbol.for("react.transitional.element"),GP=Symbol.for("react.fragment");function gk(t,e,n){var i=null;if(n!==void 0&&(i=""+n),e.key!==void 0&&(i=""+e.key),"key"in e){n={};for(var r in e)r!=="key"&&(n[r]=e[r])}else n=e;return e=n.ref,{$$typeof:VP,type:t,key:i,ref:e!==void 0?e:null,props:n}}yh.Fragment=GP,yh.jsx=gk,yh.jsxs=gk,mk.exports=yh;var f=mk.exports,vk={exports:{}},ke={};var kg=Symbol.for("react.transitional.element"),WP=Symbol.for("react.portal"),YP=Symbol.for("react.fragment"),KP=Symbol.for("react.strict_mode"),XP=Symbol.for("react.profiler"),JP=Symbol.for("react.consumer"),$P=Symbol.for("react.context"),QP=Symbol.for("react.forward_ref"),ZP=Symbol.for("react.suspense"),eL=Symbol.for("react.memo"),bk=Symbol.for("react.lazy"),tL=Symbol.for("react.activity"),yk=Symbol.iterator;function nL(t){return t===null||typeof t!="object"?null:(t=yk&&t[yk]||t["@@iterator"],typeof t=="function"?t:null)}var _k={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},xk=Object.assign,Sk={};function Fs(t,e,n){this.props=t,this.context=e,this.refs=Sk,this.updater=n||_k}Fs.prototype.isReactComponent={},Fs.prototype.setState=function(t,e){if(typeof t!="object"&&typeof t!="function"&&t!=null)throw Error("takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,t,e,"setState")},Fs.prototype.forceUpdate=function(t){this.updater.enqueueForceUpdate(this,t,"forceUpdate")};function kk(){}kk.prototype=Fs.prototype;function Tg(t,e,n){this.props=t,this.context=e,this.refs=Sk,this.updater=n||_k}var wg=Tg.prototype=new kk;wg.constructor=Tg,xk(wg,Fs.prototype),wg.isPureReactComponent=!0;var Tk=Array.isArray;function Cg(){}var St={H:null,A:null,T:null,S:null},wk=Object.prototype.hasOwnProperty;function Eg(t,e,n){var i=n.ref;return{$$typeof:kg,type:t,key:e,ref:i!==void 0?i:null,props:n}}function iL(t,e){return Eg(t.type,e,t.props)}function Rg(t){return typeof t=="object"&&t!==null&&t.$$typeof===kg}function rL(t){var e={"=":"=0",":":"=2"};return"$"+t.replace(/[=:]/g,function(n){return e[n]})}var Ck=/\/+/g;function Ag(t,e){return typeof t=="object"&&t!==null&&t.key!=null?rL(""+t.key):e.toString(36)}function aL(t){switch(t.status){case"fulfilled":return t.value;case"rejected":throw t.reason;default:switch(typeof t.status=="string"?t.then(Cg,Cg):(t.status="pending",t.then(function(e){t.status==="pending"&&(t.status="fulfilled",t.value=e)},function(e){t.status==="pending"&&(t.status="rejected",t.reason=e)})),t.status){case"fulfilled":return t.value;case"rejected":throw t.reason}}throw t}function qs(t,e,n,i,r){var a=typeof t;(a==="undefined"||a==="boolean")&&(t=null);var o=!1;if(t===null)o=!0;else switch(a){case"bigint":case"string":case"number":o=!0;break;case"object":switch(t.$$typeof){case kg:case WP:o=!0;break;case bk:return o=t._init,qs(o(t._payload),e,n,i,r)}}if(o)return r=r(t),o=i===""?"."+Ag(t,0):i,Tk(r)?(n="",o!=null&&(n=o.replace(Ck,"$&/")+"/"),qs(r,e,n,"",function(c){return c})):r!=null&&(Rg(r)&&(r=iL(r,n+(r.key==null||t&&t.key===r.key?"":(""+r.key).replace(Ck,"$&/")+"/")+o)),e.push(r)),1;o=0;var s=i===""?".":i+":";if(Tk(t))for(var l=0;l<t.length;l++)i=t[l],a=s+Ag(i,l),o+=qs(i,e,n,a,r);else if(l=nL(t),typeof l=="function")for(t=l.call(t),l=0;!(i=t.next()).done;)i=i.value,a=s+Ag(i,l++),o+=qs(i,e,n,a,r);else if(a==="object"){if(typeof t.then=="function")return qs(aL(t),e,n,i,r);throw e=String(t),Error("Objects are not valid as a React child (found: "+(e==="[object Object]"?"object with keys {"+Object.keys(t).join(", ")+"}":e)+"). If you meant to render a collection of children, use an array instead.")}return o}function _h(t,e,n){if(t==null)return t;var i=[],r=0;return qs(t,i,"","",function(a){return e.call(n,a,r++)}),i}function oL(t){if(t._status===-1){var e=t._result;e=e(),e.then(function(n){(t._status===0||t._status===-1)&&(t._status=1,t._result=n)},function(n){(t._status===0||t._status===-1)&&(t._status=2,t._result=n)}),t._status===-1&&(t._status=0,t._result=e)}if(t._status===1)return t._result.default;throw t._result}var Ek=typeof reportError=="function"?reportError:function(t){if(typeof window=="object"&&typeof window.ErrorEvent=="function"){var e=new window.ErrorEvent("error",{bubbles:!0,cancelable:!0,message:typeof t=="object"&&t!==null&&typeof t.message=="string"?String(t.message):String(t),error:t});if(!window.dispatchEvent(e))return}else if(typeof process=="object"&&typeof process.emit=="function"){process.emit("uncaughtException",t);return}console.error(t)},sL={map:_h,forEach:function(t,e,n){_h(t,function(){e.apply(this,arguments)},n)},count:function(t){var e=0;return _h(t,function(){e++}),e},toArray:function(t){return _h(t,function(e){return e})||[]},only:function(t){if(!Rg(t))throw Error("React.Children.only expected to receive a single React element child.");return t}};ke.Activity=tL,ke.Children=sL,ke.Component=Fs,ke.Fragment=YP,ke.Profiler=XP,ke.PureComponent=Tg,ke.StrictMode=KP,ke.Suspense=ZP,ke.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE=St,ke.__COMPILER_RUNTIME={__proto__:null,c:function(t){return St.H.useMemoCache(t)}},ke.cache=function(t){return function(){return t.apply(null,arguments)}},ke.cacheSignal=function(){return null},ke.cloneElement=function(t,e,n){if(t==null)throw Error("The argument must be a React element, but you passed "+t+".");var i=xk({},t.props),r=t.key;if(e!=null)for(a in e.key!==void 0&&(r=""+e.key),e)!wk.call(e,a)||a==="key"||a==="__self"||a==="__source"||a==="ref"&&e.ref===void 0||(i[a]=e[a]);var a=arguments.length-2;if(a===1)i.children=n;else if(1<a){for(var o=Array(a),s=0;s<a;s++)o[s]=arguments[s+2];i.children=o}return Eg(t.type,r,i)},ke.createContext=function(t){return t={$$typeof:$P,_currentValue:t,_currentValue2:t,_threadCount:0,Provider:null,Consumer:null},t.Provider=t,t.Consumer={$$typeof:JP,_context:t},t},ke.createElement=function(t,e,n){var i,r={},a=null;if(e!=null)for(i in e.key!==void 0&&(a=""+e.key),e)wk.call(e,i)&&i!=="key"&&i!=="__self"&&i!=="__source"&&(r[i]=e[i]);var o=arguments.length-2;if(o===1)r.children=n;else if(1<o){for(var s=Array(o),l=0;l<o;l++)s[l]=arguments[l+2];r.children=s}if(t&&t.defaultProps)for(i in o=t.defaultProps,o)r[i]===void 0&&(r[i]=o[i]);return Eg(t,a,r)},ke.createRef=function(){return{current:null}},ke.forwardRef=function(t){return{$$typeof:QP,render:t}},ke.isValidElement=Rg,ke.lazy=function(t){return{$$typeof:bk,_payload:{_status:-1,_result:t},_init:oL}},ke.memo=function(t,e){return{$$typeof:eL,type:t,compare:e===void 0?null:e}},ke.startTransition=function(t){var e=St.T,n={};St.T=n;try{var i=t(),r=St.S;r!==null&&r(n,i),typeof i=="object"&&i!==null&&typeof i.then=="function"&&i.then(Cg,Ek)}catch(a){Ek(a)}finally{e!==null&&n.types!==null&&(e.types=n.types),St.T=e}},ke.unstable_useCacheRefresh=function(){return St.H.useCacheRefresh()},ke.use=function(t){return St.H.use(t)},ke.useActionState=function(t,e,n){return St.H.useActionState(t,e,n)},ke.useCallback=function(t,e){return St.H.useCallback(t,e)},ke.useContext=function(t){return St.H.useContext(t)},ke.useDebugValue=function(){},ke.useDeferredValue=function(t,e){return St.H.useDeferredValue(t,e)},ke.useEffect=function(t,e){return St.H.useEffect(t,e)},ke.useEffectEvent=function(t){return St.H.useEffectEvent(t)},ke.useId=function(){return St.H.useId()},ke.useImperativeHandle=function(t,e,n){return St.H.useImperativeHandle(t,e,n)},ke.useInsertionEffect=function(t,e){return St.H.useInsertionEffect(t,e)},ke.useLayoutEffect=function(t,e){return St.H.useLayoutEffect(t,e)},ke.useMemo=function(t,e){return St.H.useMemo(t,e)},ke.useOptimistic=function(t,e){return St.H.useOptimistic(t,e)},ke.useReducer=function(t,e,n){return St.H.useReducer(t,e,n)},ke.useRef=function(t){return St.H.useRef(t)},ke.useState=function(t){return St.H.useState(t)},ke.useSyncExternalStore=function(t,e,n){return St.H.useSyncExternalStore(t,e,n)},ke.useTransition=function(){return St.H.useTransition()},ke.version="19.2.3",vk.exports=ke;var w=vk.exports;const ai=ry(w);function lL(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var Rk={exports:{}};(function(t){(function(){var e={}.hasOwnProperty;function n(){for(var a="",o=0;o<arguments.length;o++){var s=arguments[o];s&&(a=r(a,i(s)))}return a}function i(a){if(typeof a=="string"||typeof a=="number")return a;if(typeof a!="object")return"";if(Array.isArray(a))return n.apply(null,a);if(a.toString!==Object.prototype.toString&&!a.toString.toString().includes("[native code]"))return a.toString();var o="";for(var s in a)e.call(a,s)&&a[s]&&(o=r(o,s));return o}function r(a,o){return o?a?a+" "+o:a+o:a}t.exports?(n.default=n,t.exports=n):window.classNames=n})()})(Rk);var cL=Rk.exports;const xh=lL(cL),uL="_box_1r6by_1",dL={box:uL},Ak={none:"0px",xxs:"var(--space-xxs)",xs:"var(--space-xs)",sm:"var(--space-sm)",md:"var(--space-md)",lg:"var(--space-lg)",xl:"var(--space-xl)","2xl":"var(--space-2xl)","3xl":"var(--space-3xl)","4xl":"var(--space-4xl)","5xl":"var(--space-5xl)"};function lr(t){if(t!==void 0){if(typeof t=="number")return`${t}px`;if(t in Ak)return Ak[t];if(typeof t=="string"&&t.trim().length>0)return t}}const Nk={none:"0px",panel:"var(--radius-panel)",card:"var(--radius-card)"},Ok={surface:"var(--color-surface)",surfaceMuted:"var(--color-surface-muted)",surfaceAlt:"var(--color-surface-alt)",primarySoft:"var(--color-primary-soft)",primarySofter:"var(--color-primary-softer)",dangerSurface:"var(--color-danger-surface)"};function hL(t){if(t!==void 0){if(typeof t=="number")return`${t}px`;if(t in Nk)return Nk[t];if(typeof t=="string"&&t.trim().length>0)return t}}function fL(t){if(t!==void 0){if(t in Ok)return Ok[t];if(typeof t=="string"&&t.trim().length>0)return t}}function pL(t,e){const{as:n,className:i,padding:r,paddingX:a,paddingY:o,paddingTop:s,paddingBottom:l,paddingLeft:c,paddingRight:u,paddingSm:d,paddingMd:h,paddingLg:p,paddingXl:b,margin:m,marginX:S,marginY:g,marginTop:y,marginBottom:x,marginLeft:v,marginRight:k,radius:T,radiusTop:C,radiusBottom:R,radiusLeft:A,radiusRight:N,radiusTopLeft:O,radiusTopRight:z,radiusBottomLeft:Y,radiusBottomRight:L,background:X,gap:P,style:G,...J}=t,te=n??"div",Z={...G},q=Z,ee={},$=(j,me)=>{if(me===void 0)return;const be=lr(me);be&&(Z[j]=be)},ue=(j,me)=>{if(me===void 0)return;const be=lr(me);be&&(Z[j]=be)},B=(j,me)=>{if(me===void 0)return;const be=hL(me);be&&(Z[j]=be)};if(r!==void 0){const j=lr(r);j&&(q["--box-padding"]=j)}if(a!==void 0){const j=lr(a);j&&(Z.paddingLeft=j,Z.paddingRight=j)}if(o!==void 0){const j=lr(o);j&&(Z.paddingTop=j,Z.paddingBottom=j)}$("paddingTop",s),$("paddingBottom",l),$("paddingLeft",c),$("paddingRight",u);const ve=[["sm",d],["md",h],["lg",p],["xl",b]];for(const[j,me]of ve){if(me===void 0)continue;const be=lr(me);be&&(q[`--box-padding-${j}`]=be,ee[`data-padding-${j}`]="")}if(m!==void 0){const j=lr(m);j&&(Z.margin=j)}if(S!==void 0){const j=lr(S);j&&(Z.marginLeft=j,Z.marginRight=j)}if(g!==void 0){const j=lr(g);j&&(Z.marginTop=j,Z.marginBottom=j)}if(ue("marginTop",y),ue("marginBottom",x),ue("marginLeft",v),ue("marginRight",k),P!==void 0){const j=lr(P);j&&(Z.gap=j)}if(B("borderRadius",T),C!==void 0&&(B("borderTopLeftRadius",C),B("borderTopRightRadius",C)),R!==void 0&&(B("borderBottomLeftRadius",R),B("borderBottomRightRadius",R)),A!==void 0&&(B("borderTopLeftRadius",A),B("borderBottomLeftRadius",A)),N!==void 0&&(B("borderTopRightRadius",N),B("borderBottomRightRadius",N)),B("borderTopLeftRadius",O),B("borderTopRightRadius",z),B("borderBottomLeftRadius",Y),B("borderBottomRightRadius",L),X!==void 0){const j=fL(X);j&&(Z.background=j)}return f.jsx(te,{ref:e,className:xh(dL.box,i),style:Z,...ee,...J})}const mL=ai.forwardRef(pL);mL.displayName="Box";const gL="_inline_1gpyx_1",vL="_vertical_1gpyx_6",bL="_divider_1gpyx_10",yL="_dividerVertical_1gpyx_16",_L="_customDivider_1gpyx_21",_c={inline:gL,vertical:vL,divider:bL,dividerVertical:yL,customDivider:_L};function xL(t,e){const{as:n,direction:i="horizontal",gap:r,align:a="center",justify:o,wrap:s=!1,divider:l,className:c,style:u,children:d,...h}=t,p=n??"div",b={display:"flex",flexDirection:i==="horizontal"?"row":"column",flexWrap:s?"wrap":"nowrap",alignItems:a,...o?{justifyContent:o}:{},...u};if(r!==void 0){const y=lr(r);y&&(b.gap=y)}const m=ai.Children.toArray(d).filter(y=>y!=null&&typeof y!="boolean"),S=y=>!l||y===0?null:l===!0||l==="line"?f.jsx("span",{"aria-hidden":"true",className:xh(_c.divider,i==="vertical"&&_c.dividerVertical)},`inline-divider-${y}`):f.jsx("span",{"aria-hidden":"true",className:_c.customDivider,children:l},`inline-divider-${y}`),g=[];return m.forEach((y,x)=>{if(x>0){const v=S(x);v&&g.push(v)}g.push(y)}),f.jsx(p,{ref:e,className:xh(_c.inline,i==="vertical"&&_c.vertical,c),style:b,...h,children:g})}const SL=ai.forwardRef(xL);SL.displayName="Inline",w.createContext("vertical");function kL({size:t=24,color:e="#000"}){return f.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",width:t,height:t,viewBox:"0 0 24 24",fill:"none",stroke:e,strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:"lucide lucide-x-icon lucide-x",children:[f.jsx("path",{d:"M18 6 6 18"}),f.jsx("path",{d:"m6 6 12 12"})]})}function Mk({onClose:t}){return f.jsx("button",{className:"obi-button obi-close-button",onClick:t,"aria-label":"Close",type:"button",style:{outline:"none"},autoFocus:!1,children:f.jsx(kL,{})})}function Dk({open:t=!1,children:e,onClose:n,size:i="medium",preventOutsideClick:r=!1}){const a=w.useRef(null),o=w.useRef(null);w.useEffect(()=>{const u=a.current;u&&(t&&!u.open?u.showModal():!t&&u.open&&(o.current="programmatic",u.close()))},[t]);const s=u=>{const d=a.current;u.target===d&&!r&&(o.current="user-initiated",d==null||d.close())},l=u=>{u.preventDefault(),o.current||(o.current="user-initiated");const d=o.current;o.current=null,n==null||n(d)},c=()=>{var u;o.current="user-initiated",(u=a.current)==null||u.close()};return w.useEffect(()=>{const u=a.current;if(u)return u.addEventListener("click",s),u.addEventListener("close",l),()=>{u.removeEventListener("click",s),u.removeEventListener("close",l)}},[n]),f.jsxs("dialog",{ref:a,className:`modal-${i}`,children:[f.jsx(Mk,{onClose:c}),f.jsx("div",{className:"modal-content",children:t?typeof e=="function"?e():e:null})]})}const Pk=8,Sh=8,TL=100,wL=.7,Hs=3;function Lk({getBands:t,color:e="white"}){const n=w.useRef(null);return w.useEffect(()=>{if(!t)return;let i=0,r;const a=o=>{try{if(o-i>=TL){const s=t();if(n.current){const l=n.current.querySelectorAll(".bar"),c=s&&s.length>0?s.slice(0,Sh).map(u=>{const d=Math.abs(u);return Math.min(d/wL*Pk,Pk)||Hs}):Array(Sh).fill(Hs);for(;c.length<Sh;)c.push(Hs);c.forEach((u,d)=>{if(u<Hs&&(u=Hs),l[d]){const h=u*2;l[d].style.height=`${h}px`,l[d].style.display=u>0?"block":"none"}})}i=o}r=requestAnimationFrame(a)}catch(s){console.warn("Error updating equaliser:",s),r=requestAnimationFrame(a)}};return r=requestAnimationFrame(a),()=>{cancelAnimationFrame(r)}},[t]),f.jsx("div",{className:"obi-equaliser",ref:n,children:Array.from({length:Sh},(i,r)=>f.jsx("div",{className:"column",children:f.jsx("div",{className:"bar",style:{height:`${Hs}px`,backgroundColor:e,display:"block"}})},r))})}function kh({className:t="",isActive:e=!1,speakingStatus:n,onClick:i,onMouseEnter:r,onMouseLeave:a,children:o}){let s=`obi-pill container ${e&&"active"}`;return n==="user-speaking"&&(s+=" user-speaking"),n==="busy"&&(s+=" busy"),f.jsx("div",{className:s,onMouseEnter:r,onMouseLeave:a,children:f.jsx("div",{className:`obi-pill pill ${t}`,onClick:i,children:o})})}function CL({className:t="",active:e,speakingStatus:n,onClick:i,onMouseEnter:r,onMouseLeave:a,children:o,...s}){const l=`obi-pill2 container ${e?"active":""} ${n==="user-speaking"?"user-speaking":""} ${t}`;return f.jsx("div",{className:l,...s,children:f.jsx("div",{className:"pill",onClick:i,onMouseEnter:r,onMouseLeave:a,children:o})})}function EL({className:t="",active:e,speakingStatus:n,onClick:i,onMouseEnter:r,onMouseLeave:a,children:o,...s}){const l=`obi-pill-up container ${e?"active":""} ${n==="user-speaking"?"user-speaking":""} ${t}`;return f.jsx("div",{className:l,...s,children:f.jsx("div",{className:"pill",onClick:i,onMouseEnter:r,onMouseLeave:a,children:o})})}function RL(t){const{spectrum:e}=t;return f.jsx(kh,{isActive:!0,children:f.jsx(Lk,{getBands:e})})}function Ng(t){const{children:e,className:n="",...i}=t;return f.jsx("div",{className:`${n} obi-panel`,...i,children:e})}function Ik({className:t="",size:e=64}){return f.jsx("svg",{width:e,height:e,viewBox:"0 0 256 256",fill:"none",xmlns:"http://www.w3.org/2000/svg",className:t,children:f.jsx("path",{d:"M158.803 0L160.352 0.0399439C176.267 0.844061 188.922 13.9634 188.922 30.0311C188.922 46.6174 175.438 60.0653 158.803 60.0656H99.0263L98.9061 60.0722C78.8071 61.4795 62.6269 77.004 60.2644 96.7673L60.241 96.9704V158.93L60.2644 159.13C62.7406 179.86 80.4234 195.934 101.881 195.935H153.842C176.993 195.935 195.759 177.223 195.759 154.14V96.9138L195.799 95.3693C196.606 79.5009 209.766 66.8827 225.881 66.8827C242.515 66.8834 256 80.328 256 96.9138V159.086L255.963 160.564C255.225 175.748 243.176 187.971 228.038 189.038V189.214C207.121 190.591 190.4 207.263 189.019 228.119H188.842C187.738 243.7 174.712 256 158.803 256H96.4491C79.8147 256 66.3309 242.555 66.3302 225.969C66.3302 225.673 66.3349 225.375 66.3436 225.077H66.3503H66.3035C63.3344 206.008 47.4427 190.589 27.8321 189.231L27.8354 189.031C12.2702 187.868 0.000167669 174.905 0 159.086V96.9138L0.0367222 95.4192C0.791087 80.0787 13.0909 67.7634 28.453 66.9293C47.7697 65.3039 63.3522 50.3234 66.2969 31.4658L66.3469 31.1595L66.3369 30.85C66.3301 30.5933 66.3302 30.3238 66.3302 30.0311C66.3309 13.4454 79.8148 0.000165137 96.4491 0H158.803Z",fill:"currentColor"})})}function AL(t){const{currentStep:e,totalSteps:n,stepNames:i,className:r,onStepClick:a}=t,[o,s]=w.useState(null),l=Array.from({length:n},(d,h)=>({isCompleted:h<e,isFuture:h>=e,stepNumber:h+1})),c=i[e-1]&&i[e-1].trim().length>0?i[e-1]:`Step ${e}`,u=(()=>{if(o!==null){const d=i[o]&&i[o].trim().length>0?i[o]:`Step ${o+1}`;return`${o+1}/${n} \u2022 ${d}`}return`${e}/${n} \u2022 ${c}`})();return f.jsxs("div",{className:`obi-course-progress ${r||""}`,children:[f.jsx("div",{className:"obi-course-progress-steps",children:l.map((d,h)=>{const p=i[h]&&i[h].trim().length>0?i[h]:`Step ${h+1}`,b=d.isCompleted?"completed":"future";function m(){a&&a(h,p)}function S(g){a&&(g.key==="Enter"||g.key===" ")&&(g.preventDefault(),m())}return f.jsx("div",{className:"obi-course-progress-container","data-testid":`course-progress-step-${h}`,onMouseEnter:()=>s(h),onMouseLeave:()=>s(null),onClick:a?m:void 0,onKeyDown:a?S:void 0,role:a?"button":void 0,tabIndex:a?0:void 0,children:f.jsx("div",{className:`obi-course-progress-step ${b}`,"aria-label":p})},h)})}),f.jsx("div",{className:"obi-course-progress-description",children:u})]})}function NL({onContinue:t,onWrapUp:e}){return f.jsx(Ng,{className:"obi-exit-survey",children:f.jsx(ML,{onContinue:t,onWrapUp:()=>{e()}})})}function OL({onOtherSelect:t,onReasonSelect:e,onClose:n}){const[i,r]=w.useState("reason"),a=o=>{o==="other"?(t(),r("other-reason")):e(o)};return f.jsx(Ng,{className:`obi-exit-survey ${i==="reason"?"obi-exit-survey-reason":""}`,children:i==="reason"?f.jsx(DL,{onReasonSelect:a}):f.jsx(PL,{onReasonSelect:a,onClose:n})})}function ML({onContinue:t,onWrapUp:e}){return f.jsxs("div",{className:"obi-exit-survey-container",children:[f.jsx("h2",{className:"obi-exit-survey-title",children:"Wrapping up early?"}),f.jsxs("div",{className:"obi-exit-survey-options",children:[f.jsx("button",{className:"obi-button obi-exit-survey-button obi-exit-survey-button-continue",onClick:t,type:"button",children:"No, let's continue"}),f.jsx("button",{className:"obi-button obi-exit-survey-button obi-exit-survey-button-wrap-up",onClick:e,type:"button",children:"Yes, let's wrap up"})]})]})}function DL({onReasonSelect:t}){return f.jsxs("div",{className:"obi-exit-survey-container obi-exit-survey-reason-container",children:[f.jsx("div",{className:"obi-exit-survey-header",children:f.jsx("h2",{className:"obi-exit-survey-title obi-exit-survey-reason-title",children:"Quick feedback?"})}),f.jsxs("div",{className:"obi-exit-survey-options obi-exit-survey-reason-options",children:[f.jsx("button",{className:"obi-button obi-exit-survey-button obi-exit-survey-reason-button",onClick:()=>t("do-later"),type:"button",children:"Will do later"}),f.jsx("button",{className:"obi-button obi-exit-survey-button obi-exit-survey-reason-button",onClick:()=>t("cant-talk"),type:"button",children:"Can't talk right now"}),f.jsx("button",{className:"obi-button obi-exit-survey-button obi-exit-survey-reason-button",onClick:()=>t("prefer-written"),type:"button",children:"Prefer written instructions"}),f.jsx("button",{className:"obi-button obi-exit-survey-button obi-exit-survey-reason-button",onClick:()=>t("technical-issues"),type:"button",children:"Experienced technical issues"})]})]})}function PL({onReasonSelect:t,onClose:e}){const[n,i]=w.useState("");return f.jsxs("div",{className:"obi-exit-survey-container obi-exit-survey-reason-container",children:[f.jsxs("div",{className:"obi-exit-survey-header",children:[f.jsx(Mk,{onClose:e}),f.jsx("h2",{className:"obi-exit-survey-title obi-exit-survey-reason-title",children:"Tell us more"})]}),f.jsxs("div",{className:"obi-exit-survey-options obi-exit-survey-reason-options",children:[f.jsx("textarea",{className:"obi-exit-survey-button obi-exit-survey-reason-button",placeholder:"What's on your mind?",value:n,onChange:r=>i(r.target.value)}),f.jsx("button",{className:"obi-button obi-exit-survey-button obi-exit-survey-button-wrap-up",onClick:()=>t("other-feedback",n),type:"button",children:"Send feedback"})]})]})}const LL=8;function jk({color:t="white"}){return f.jsx("div",{className:"obi-loading-dots",children:Array.from({length:LL},(e,n)=>f.jsxs("div",{className:"column",children:[f.jsx("div",{className:"bar",style:{backgroundColor:t,animationDelay:`${n*.15}s`}}),f.jsx("div",{className:"dot",style:{backgroundColor:t}})]},n))})}function ea({className:t,children:e,onClick:n}){return n?f.jsx("button",{className:`obi-button obi-message ${t} clickable`,onClick:n,children:e}):f.jsx("div",{className:`obi-message ${t}`,children:e})}function IL(t){const{placeholder:e="Type your message...",value:n,defaultValue:i,onChange:r,onSend:a,onCancel:o,onExpand:s,isLoading:l=!1,disabled:c=!1,maxLength:u=500,children:d}=t,[h,p]=w.useState(n||i||""),[b,m]=w.useState((n||i||"").length>24),S=w.useRef(null);w.useLayoutEffect(()=>{b&&(s==null||s(!0))},[]);const g=n!==void 0?n:h,y=k=>{const T=k.currentTarget.value;n===void 0&&p(T),r==null||r(T)},x=k=>{k.key==="Escape"&&(p(n||i||""),m(!1),o==null||o()),k.key==="Enter"&&!k.shiftKey&&g.trim()&&(k.preventDefault(),p(n||i||""),m(!1),v()),(g||"").length>=24&&!b&&(m(!0),s==null||s(!0))};w.useEffect(()=>{S.current&&S.current.focus()},[S.current]);const v=()=>{!g.trim()||l||c||(a==null||a(g.trim()),n===void 0&&p(""))};return f.jsxs("div",{className:`obi-message-input ${b?"expanded":""}`,children:[f.jsx("div",{className:"container",children:f.jsx("textarea",{ref:S,className:"field",placeholder:e,value:g,onInput:y,onKeyDown:x,disabled:c||l,maxLength:u,rows:1})}),f.jsxs("div",{className:"button-container",children:[b&&f.jsx("div",{children:d}),f.jsx("button",{className:"obi-button send",onClick:v,disabled:!g.trim()||l||c,type:"button",children:f.jsx("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:f.jsx("path",{d:"M6.00016 10.6673V1.33398M6.00016 1.33398L1.3335 6.00065M6.00016 1.33398L10.6668 6.00065",stroke:"#F3F3F3","stroke-width":"1.6","stroke-linecap":"round","stroke-linejoin":"round"})})})]})]})}const Og=w.createContext(null);function jL({children:t}){const e=w.useContext(Og);if(!e)throw new Error("PopoutTarget must be used within a Popout component");const{controlledOpen:n,isOpen:i,setIsOpen:r,setAnimating:a,targetRef:o,trigger:s,onChange:l,delayMs:c}=e,u=w.useRef(null),d=Bk(o,a),[h,p]=w.useState(!1);w.useEffect(()=>{n!==void 0&&n!==h&&(n?m():S()),p(n)},[n]),w.useEffect(()=>()=>{u.current&&clearTimeout(u.current)},[]);function b(){u.current&&(clearTimeout(u.current),u.current=null)}function m(){b(),c>0?u.current=setTimeout(()=>{l==null||l(!0),r(!0),u.current=null},c):(l==null||l(!0),r(!0))}function S(){b(),l==null||l(!1),r(!1)}const g=()=>{s==="click"&&(i?S():m())};function y(){s==="hover"&&m()}function x(){s==="hover"&&S()}return f.jsx("div",{ref:d,className:"target",onClick:g,onMouseEnter:y,onMouseLeave:x,children:t})}function BL({children:t}){const e=w.useContext(Og);if(!e)throw new Error("PopoutContent must be used within a Popout component");const{isOpen:n,animating:i,setAnimating:r,targetRef:a,contentRef:o}=e,s=Bk(o,r);return w.useLayoutEffect(()=>{if(n&&!i&&a.current&&o.current){const l=o.current;if(!l)return;const c=a.current;if(!c)return;const u=l.getBoundingClientRect(),d=c.getBoundingClientRect(),h=d.right-d.left;l.style.top=`${u.top-u.bottom-(8+e.offset)}px`,l.style.left=`${-(u.right-u.left-h)/2}px`}},[n,i]),n?f.jsx("div",{ref:s,className:"content",style:{opacity:i?0:1},children:t}):null}function oi({trigger:t="click",open:e,onChange:n,children:i,delayMs:r=0,offset:a=0,className:o=""}){const[s,l]=w.useState(!1),[c,u]=w.useState(!1),d=w.useRef(null),h=w.useRef(null),p={controlledOpen:e,isOpen:s,setIsOpen:l,animating:c,setAnimating:u,targetRef:d,contentRef:h,trigger:t,onChange:n,delayMs:r,offset:a};return f.jsx(Og.Provider,{value:p,children:f.jsx("div",{className:`obi-popout ${o}`,children:i})})}oi.Target=jL,oi.Content=BL;function Bk(t,e){const n=w.useRef(null),i=w.useRef(null),r=w.useRef(!0),a=w.useCallback(o=>{if(t.current=o,!o){i.current&&(i.current.disconnect(),i.current=null),r.current=!0;return}function s(){if(r.current){r.current=!1;return}n.current?clearTimeout(n.current):e(!0),n.current=setTimeout(()=>{e(!1),n.current=null},200)}i.current=new ResizeObserver(s),i.current.observe(o,{box:"border-box"})},[]);return w.useEffect(()=>()=>{i.current&&(i.current.disconnect(),i.current=null)},[]),a}function Wo({type:t,size:e=24}){return f.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2","stroke-linecap":"round","stroke-linejoin":"round",children:UL(t)})}function UL(t){switch(t){case"pause":return f.jsxs(f.Fragment,{children:[f.jsx("rect",{x:"14",y:"3",width:"5",height:"18",rx:"1"}),f.jsx("rect",{x:"5",y:"3",width:"5",height:"18",rx:"1"})]});case"play":return f.jsx(f.Fragment,{children:f.jsx("path",{d:"M5 5a2 2 0 0 1 3.008-1.728l11.997 6.998a2 2 0 0 1 .003 3.458l-12 7A2 2 0 0 1 5 19z"})});case"close":return f.jsxs(f.Fragment,{children:[f.jsx("path",{d:"M18 6 6 18"}),f.jsx("path",{d:"m6 6 12 12"})]});case"message":return f.jsx(f.Fragment,{children:f.jsx("path",{d:"M22 17a2 2 0 0 1-2 2H6.828a2 2 0 0 0-1.414.586l-2.202 2.202A.71.71 0 0 1 2 21.286V5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2z"})});case"minimize":return f.jsxs(f.Fragment,{children:[f.jsx("path",{d:"m14 10 7-7"}),f.jsx("path",{d:"M20 10h-6V4"}),f.jsx("path",{d:"m3 21 7-7"}),f.jsx("path",{d:"M4 14h6v6"})]});case"voice":return f.jsxs(f.Fragment,{children:[f.jsx("path",{d:"M2 10v3"}),f.jsx("path",{d:"M6 6v11"}),f.jsx("path",{d:"M10 3v18"}),f.jsx("path",{d:"M14 8v7"}),f.jsx("path",{d:"M18 5v13"}),f.jsx("path",{d:"M22 10v3"})]});case"open":return f.jsxs(f.Fragment,{children:[f.jsx("path",{d:"M12 7v14"}),f.jsx("path",{d:"M3 18a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1h5a4 4 0 0 1 4 4 4 4 0 0 1 4-4h5a1 1 0 0 1 1 1v13a1 1 0 0 1-1 1h-6a3 3 0 0 0-3 3 3 3 0 0 0-3-3z"})]})}}function cr({className:t,onClick:e,type:n,disabled:i,title:r}){const a={cancel:f.jsx(Wo,{type:"close",size:16}),pause:f.jsx(Wo,{type:"pause",size:16}),play:f.jsx(Wo,{type:"play",size:16}),message:f.jsx(Wo,{type:"message",size:16}),minimize:f.jsx(Wo,{type:"minimize",size:16}),voice:f.jsx(Wo,{type:"voice",size:16}),open:f.jsx(Wo,{type:"open",size:16})}[n],o={cancel:"",pause:"",play:"",message:"",minimize:"",voice:"",open:""}[n],s=f.jsx("button",{className:`obi-button obi-round-button ${o} ${t}`,onClick:i?void 0:e,disabled:i,children:a});return r?f.jsxs(oi,{className:"obi-round-button-popout",trigger:"hover",delayMs:200,offset:9,children:[f.jsx(oi.Target,{children:s}),f.jsx(oi.Content,{children:f.jsx("div",{className:"obi-round-button-title",children:r})})]}):s}function zL(t){const{disabled:e,inPlan:n,isPaused:i}=t,[r,a]=w.useState(null),[o,s]=w.useState(t.isActive??t.defaultIsActive??!1),[l,c]=w.useState(!1),[u,d]=w.useState(t.cancelling??!1),[h,p]=w.useState(t.messaging??!1),[b,m]=w.useState(!1),[S,g]=w.useState(h),[y,x]=w.useState(!1);function v(){s(!0),c(!1),x(!0)}function k(){}function T(){r&&(clearTimeout(r),a(null))}function C(){a(setTimeout(()=>{s(t.defaultIsActive??!1),x(!1)},400))}function R(Te){var Le;m(!1),(Le=t.onMessage)==null||Le.call(t,Te)}function A(){var Te;p(!1),m(!1),s(!1),c(!0),(Te=t.onMinimize)==null||Te.call(t)}function N(){var Te;p(!1),d(!0),m(!1),(Te=t.onCancelClick)==null||Te.call(t)}function O(){var Te;n||((Te=t.onOpen)==null||Te.call(t))}function z(Te){var Le,ht,lt,hn,fn,At;switch(Te){case"need-help":(Le=t.onMessage)==null||Le.call(t,"I'm struggling, can you look at my screen and help me out."),(ht=t.onOneClickAction)==null||ht.call(t,"need-help");break;case"continue":(lt=t.onMessage)==null||lt.call(t,"Okay, let's continue."),(hn=t.onOneClickAction)==null||hn.call(t,"continue");break;case"say-again":(fn=t.onMessage)==null||fn.call(t,"Please say that again."),(At=t.onOneClickAction)==null||At.call(t,"say-again");break}}function Y(Te){var Le,ht;t.messaging===void 0?((Le=t.onMessagingChange)==null||Le.call(t,Te),p(Te)):((ht=t.onMessagingChange)==null||ht.call(t,!t.messaging),p(!t.messaging)),Te||m(!1)}const L=t.isActive??((o||n)&&!l&&!e),X=L&&n,P=L&&n&&!b,G=t.speakingStatus==="user-speaking",J=t.speakingStatus==="thinking",te=t.speakingStatus==="busy",Z=L&&!n&&!u&&y,q=L&&n&&i&&!G&&!u,ee=L&&n&&!q&&!G&&h!==S&&!u,$=L&&n&&i&&G&&!u,ue=L&&n&&!i&&G&&!u,B=L&&n&&!i&&te&&!u,ve=t.messaging!==void 0?t.messaging:h,j=ve&&G,me=Z||q||$||ue||ee||u,be=400,qt=!!t.courseProgress&&!l,En=Z?5:10;return w.useLayoutEffect(()=>{g(h)},[G]),!n&&!u?f.jsx(FL,{...t}):!n&&u?f.jsx(qL,{onOtherSelect:()=>{var Te;(Te=t.onCancelReasonOther)==null||Te.call(t)},onCancelReason:Te=>{var Le;s(t.defaultIsActive??!1),d(!1),(Le=t.onCancelReason)==null||Le.call(t,Te)},onClose:()=>{s(t.defaultIsActive??!1),d(!1)}}):f.jsxs(Ng,{className:`obi-widget-panel ${X?"expanded":""} ${b?"maximized":""} ${ve?"messaging":""} ${te?"tool-usage":""}`,children:[f.jsxs("div",{className:`obi-widget ${L?"active":""} ${n?"in-plan":""}`,onMouseEnter:T,onMouseLeave:C,children:[P&&f.jsx(cr,{type:"cancel",onClick:N,disabled:u,title:"Cancel session"}),P&&!i&&f.jsx(cr,{type:"pause",onClick:t.onPause,title:"Pause session"}),P&&i&&f.jsx(cr,{type:"play",onClick:t.onUnpause,title:"Unpause session"}),f.jsxs(oi,{className:"obi-widget-popout",open:me,trigger:null,delayMs:be,offset:En,children:[f.jsxs(oi.Target,{children:[j&&f.jsx(IL,{value:t.message,onCancel:()=>Y(!1),onSend:R,onExpand:m,onChange:t.onMessageChange,children:f.jsxs("div",{className:"obi-widget-buttons",children:[f.jsx(cr,{type:"cancel",onClick:N,disabled:u,title:"Cancel session"}),!i&&f.jsx(cr,{type:"pause",onClick:t.onPause,title:"Pause session"}),i&&f.jsx(cr,{type:"play",onClick:t.onUnpause,title:"Unpause session"}),f.jsx(cr,{type:ve?"voice":"message",onClick:()=>Y(!ve),title:ve?"Voice input":"Text input"}),f.jsx(cr,{type:"minimize",onClick:A,title:"Minimize widget"})]})}),!j&&f.jsxs(kh,{className:L&&!n?"button":"",isActive:L,speakingStatus:t.speakingStatus,onClick:O,onMouseEnter:v,onMouseLeave:k,children:[L&&!n&&!B&&f.jsx("span",{className:"obi-widget-pill-text",children:"Tutorials"}),L&&n&&B&&f.jsx("span",{className:"obi-widget-pill-text",children:"Searching knowledge ..."}),L&&n&&!J&&!B&&f.jsx(Lk,{getBands:t.spectrum}),L&&J&&!B&&f.jsx(jk,{})]})]}),f.jsx(oi.Content,{children:f.jsxs("div",{onMouseLeave:C,children:[Z&&f.jsx(ea,{onClick:O,children:"Click to see all"}),q&&f.jsx(ea,{children:"Session will pause shortly"}),ee&&f.jsxs(ea,{children:["Switched to ",ve?"chat":"voice"]}),$&&f.jsx(ea,{children:"Paused"}),ue&&f.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:"4px"},children:[f.jsx(ea,{onClick:()=>z("need-help"),children:"Need help"}),f.jsx(ea,{onClick:()=>z("continue"),children:"Continue"}),f.jsx(ea,{onClick:()=>z("say-again"),children:"Say again"})]}),u&&f.jsx(NL,{onContinue:()=>{var Te;(Te=t.onCancelAbort)==null||Te.call(t),d(!1),t.messaging!==void 0&&p(t.messaging)},onWrapUp:()=>{var Te;(Te=t.onCancel)==null||Te.call(t)}})]})})]}),P&&f.jsx(cr,{type:ve?"voice":"message",onClick:()=>Y(!ve),title:ve?"Voice input":"Text input"}),P&&f.jsx(cr,{type:"minimize",onClick:A,title:"Minimize widget"})]}),qt&&t.courseProgress&&f.jsx("div",{className:`obi-widget-course-progress ${ve?"expanded":""}`,children:f.jsx(AL,{currentStep:t.courseProgress.currentStep,totalSteps:t.courseProgress.totalSteps,stepNames:t.courseProgress.stepNames,onStepClick:(Te,Le)=>{var lt;const ht=`Can we please jump to the steps related to: ${Le}`;(lt=t.onMessage)==null||lt.call(t,ht)}})})]})}function FL(t){const{disabled:e,completedTutorials:n,totalTutorials:i,agentName:r}=t,[a,o]=w.useState(null),[s,l]=w.useState(t.isActive??t.defaultIsActive??!1),[c,u]=w.useState(!1),[d,h]=w.useState(t.hovered??!1),[p,b]=w.useState(null),[m,S]=w.useState(null);function g(){m&&(clearTimeout(m),S(null)),p&&b(null)}function y(){var Y;l(!0),u(!1),h(!0),(Y=t.onHover)==null||Y.call(t,!0)}function x(){}function v(){a&&(clearTimeout(a),o(null))}function k(){s&&o(setTimeout(()=>{var Y;l(t.defaultIsActive??!1),h(!1),(Y=t.onHover)==null||Y.call(t,!1)},400))}function T(){g(),l(!1),u(!0)}function C(){var Y;g(),(Y=t.onOpen)==null||Y.call(t)}const R=t.hovered??(d&&!c),A=t.isActive??(s&&!e&&!c),N=A&&R||!!p,O=`round-button ${A?"active":""}`;let z=`${r||"Obi"}`;return n!==void 0&&i!==void 0&&n>=0&&i>0&&(z=`${n}/${i} completed`),w.useLayoutEffect(()=>{if(t.toastMessage&&t.toastMessage.text){m&&clearTimeout(m);const Y=t.toastMessage.autoCloseMs??3e3;b({text:t.toastMessage.text,autoCloseMs:Y});const L=setTimeout(()=>{b(null)},Y);S(L)}else t.toastMessage===null&&(m&&clearTimeout(m),b(null))},[t.toastMessage]),f.jsx("div",{className:"obi-widget-out-of-plan-container",children:f.jsxs("div",{className:`obi-widget-out-of-plan ${R?"hover":""} ${A?"active":""}`,onMouseEnter:v,onMouseLeave:k,onClickCapture:g,children:[f.jsx("div",{className:O,style:{width:"30px",height:"30px"}}),f.jsxs(oi,{className:"obi-widget-popout",open:N,trigger:null,delayMs:400,offset:5,children:[f.jsx(oi.Target,{children:f.jsx(EL,{className:A?"button":"",active:A,onClick:C,onMouseEnter:y,onMouseLeave:x,children:f.jsxs("span",{className:"text",children:[f.jsx(Ik,{size:16}),z]})})}),f.jsxs(oi.Content,{children:[!!p&&f.jsx(ea,{onClick:()=>{g(),C()},children:p.text}),!p&&f.jsx("div",{onMouseLeave:k,children:f.jsx(ea,{className:"message",onClick:C,children:"Click to see all"})})]})]}),f.jsx(cr,{className:O,type:"minimize",onClick:T,title:"Minimize widget"})]})})}function qL(t){return f.jsx("div",{className:"obi-widget-out-of-plan-container",children:f.jsx("div",{className:"obi-widget-out-of-plan",children:f.jsxs(oi,{className:"obi-widget-popout",open:!0,trigger:null,delayMs:100,offset:5,children:[f.jsx(oi.Target,{children:f.jsx(CL,{active:!1})}),f.jsx(oi.Content,{children:f.jsx(OL,{onOtherSelect:()=>{var e;(e=t.onOtherSelect)==null||e.call(t)},onReasonSelect:(e,n)=>{var i;(i=t.onCancelReason)==null||i.call(t,e,n)},onClose:()=>{var e;(e=t.onClose)==null||e.call(t)}})})]})})})}function HL({open:t=!1,children:e,onClose:n,preventOutsideClick:i=!1}){return f.jsx(Dk,{open:t,onClose:n,preventOutsideClick:i,size:"medium",children:f.jsx("div",{className:"tour content-area",children:t?typeof e=="function"?e():e:null})})}function VL({logoUrl:t="",appName:e="App"}){const[n,i]=w.useState(!1),[r,a]=w.useState(!1),o=()=>{i(!0)},s=()=>{a(!0),i(!1)},l={container:{display:"block"},logoContainer:{width:"480px",height:"240px",borderRadius:"12px",display:"flex",alignItems:"center",justifyContent:"center",position:"relative",overflow:"hidden"},backgroundPattern:{position:"absolute",inset:0,zIndex:0,background:"#F5F5F5",backgroundImage:`url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='277' height='195' viewBox='0 0 277 195' fill='none'%3E%3Cpath opacity='0.4' d='M341.308 0.75C380.279 0.750001 411.872 24.3772 411.872 53.5229C411.872 82.6685 380.279 106.296 341.308 106.296H215.792C176.964 108.335 145.691 130.837 141.128 159.475V256.616C145.912 286.659 180.089 309.954 221.548 309.954H330.872C375.607 309.954 411.872 282.833 411.872 249.377V159.069C411.872 129.923 443.465 106.296 482.436 106.296C521.407 106.296 553 129.923 553 159.069V257.181C553 285.058 524.099 307.88 487.483 309.815C489.264 309.902 491.061 309.954 492.871 309.954C448.137 309.954 411.872 337.076 411.872 370.532C411.872 369.177 411.803 367.834 411.686 366.502C409.098 393.885 378.582 415.5 341.308 415.5H210.118C171.147 415.5 139.554 391.873 139.554 362.727C139.554 362.204 139.565 361.683 139.585 361.163C133.564 332.156 100.023 309.954 59.5488 309.954C61.4544 309.954 63.3441 309.9 65.2169 309.803C28.7434 307.76 -8.57239e-07 284.982 0 257.181V159.069C1.64632e-06 130.901 29.5078 107.89 66.6662 106.377C64.3207 106.224 61.9472 106.141 59.5488 106.141C100.012 106.141 133.54 83.951 139.575 54.9552C139.558 54.4793 139.554 54.0018 139.554 53.5229C139.554 24.3772 171.147 0.75 210.118 0.75H341.308Z' fill='white'/%3E%3C/svg%3E")`,backgroundRepeat:"no-repeat",backgroundPosition:"190px 60px",backgroundSize:"300px 225px"},logoWrapper:{background:"#888888",width:"120px",height:"120px",display:"flex",alignItems:"center",justifyContent:"center",borderRadius:"4px",boxShadow:"0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06)",zIndex:10,overflow:"hidden"},appLogo:{width:"120px",height:"120px",objectFit:"cover",display:t&&!n&&r?"block":"none"},placeholderLogo:{width:"60px",height:"60px",background:"rgba(255, 255, 255, 0.2)",borderRadius:"4px",display:!t||n||!r?"flex":"none",alignItems:"center",justifyContent:"center",color:"rgba(255, 255, 255, 0.8)",fontSize:"24px",fontWeight:"bold"}};return f.jsx("div",{style:l.container,children:f.jsxs("div",{style:l.logoContainer,children:[f.jsx("div",{style:l.backgroundPattern}),f.jsxs("div",{style:l.logoWrapper,children:[t&&f.jsx("img",{style:l.appLogo,src:t,alt:`${e} logo`,onError:o,onLoad:s}),f.jsx("div",{style:l.placeholderLogo,children:e.charAt(0).toUpperCase()})]})]})})}function Vs({className:t,title:e="",agentName:n="Obi",buttonText:i="Continue",speakingState:r=null,actionDisabled:a=!1,footer:o,href:s=null,glow:l=!1,centerVisual:c,description:u,button:d,onAction:h}){const[p,b]=w.useState(a),[m,S]=w.useState(!1),[g,y]=w.useState(r);w.useEffect(()=>{m||(r==="listening"&&g!=="listening"&&p&&b(!1),r!=="listening"&&!p&&b(!0)),y(r)},[r,p]),w.useEffect(()=>{b(a)},[a]);const x=()=>{p||(b(!0),S(!0),h==null||h())},v=()=>{switch(r){case"thinking":return"Loading...";case"speaking":return`${n} is speaking`;default:return i}},k=s?"a":"button",T=s?{href:s,target:"_blank",rel:"noopener noreferrer"}:{type:"button"};return f.jsx("div",{className:xh("tour-content",t),children:f.jsxs("div",{className:"container",children:[f.jsx("div",{className:`visual ${l?"glow":""}`,children:c}),f.jsxs("div",{className:"header",children:[f.jsx("h1",{className:"title",children:e}),f.jsx("div",{className:"description",children:u})]}),f.jsx("div",{className:"button-container",children:d||f.jsx(k,{className:`action-button ${p?"disabled":""}`,onClick:x,disabled:p,...T,children:f.jsx("span",{className:"button-text",children:v()})})}),o&&f.jsx("div",{className:"tour-footer",children:o})]})})}function GL({session:t,speakingState:e,onAction:n}){const i=t.appName?`Navigate to ${t.appName}`:"Navigate to app",r=t.appName?`Open ${t.appName}`:"Open app",a=t.appName?`Enjoy the tutorial in ${t.appName}`:"Enjoy the tutorial";return f.jsx(Vs,{title:i,subtitle:"Click the button below to open the app",agentName:t.agentName||"Obi",buttonText:r,speakingState:e,actionDisabled:!0,href:t.url,description:a,centerVisual:f.jsx(VL,{logoUrl:t.appLogoUrl,appName:t.appName}),onAction:n})}const{entries:Uk,setPrototypeOf:zk,isFrozen:WL,getPrototypeOf:YL,getOwnPropertyDescriptor:KL}=Object;let{freeze:zn,seal:ji,create:Mg}=Object,{apply:Dg,construct:Pg}=typeof Reflect<"u"&&Reflect;zn||(zn=function(t){return t}),ji||(ji=function(t){return t}),Dg||(Dg=function(t,e){for(var n=arguments.length,i=new Array(n>2?n-2:0),r=2;r<n;r++)i[r-2]=arguments[r];return t.apply(e,i)}),Pg||(Pg=function(t){for(var e=arguments.length,n=new Array(e>1?e-1:0),i=1;i<e;i++)n[i-1]=arguments[i];return new t(...n)});const Th=qn(Array.prototype.forEach),XL=qn(Array.prototype.lastIndexOf),Fk=qn(Array.prototype.pop),xc=qn(Array.prototype.push),JL=qn(Array.prototype.splice),wh=qn(String.prototype.toLowerCase),Lg=qn(String.prototype.toString),Ig=qn(String.prototype.match),Sc=qn(String.prototype.replace),$L=qn(String.prototype.indexOf),QL=qn(String.prototype.trim),ur=qn(Object.prototype.hasOwnProperty),Fn=qn(RegExp.prototype.test),kc=ZL(TypeError);function qn(t){return function(e){e instanceof RegExp&&(e.lastIndex=0);for(var n=arguments.length,i=new Array(n>1?n-1:0),r=1;r<n;r++)i[r-1]=arguments[r];return Dg(t,e,i)}}function ZL(t){return function(){for(var e=arguments.length,n=new Array(e),i=0;i<e;i++)n[i]=arguments[i];return Pg(t,n)}}function De(t,e){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:wh;zk&&zk(t,null);let i=e.length;for(;i--;){let r=e[i];if(typeof r=="string"){const a=n(r);a!==r&&(WL(e)||(e[i]=a),r=a)}t[r]=!0}return t}function eI(t){for(let e=0;e<t.length;e++)ur(t,e)||(t[e]=null);return t}function Dr(t){const e=Mg(null);for(const[n,i]of Uk(t))ur(t,n)&&(Array.isArray(i)?e[n]=eI(i):i&&typeof i=="object"&&i.constructor===Object?e[n]=Dr(i):e[n]=i);return e}function Tc(t,e){for(;t!==null;){const i=KL(t,e);if(i){if(i.get)return qn(i.get);if(typeof i.value=="function")return qn(i.value)}t=YL(t)}function n(){return null}return n}const qk=zn(["a","abbr","acronym","address","area","article","aside","audio","b","bdi","bdo","big","blink","blockquote","body","br","button","canvas","caption","center","cite","code","col","colgroup","content","data","datalist","dd","decorator","del","details","dfn","dialog","dir","div","dl","dt","element","em","fieldset","figcaption","figure","font","footer","form","h1","h2","h3","h4","h5","h6","head","header","hgroup","hr","html","i","img","input","ins","kbd","label","legend","li","main","map","mark","marquee","menu","menuitem","meter","nav","nobr","ol","optgroup","option","output","p","picture","pre","progress","q","rp","rt","ruby","s","samp","search","section","select","shadow","slot","small","source","spacer","span","strike","strong","style","sub","summary","sup","table","tbody","td","template","textarea","tfoot","th","thead","time","tr","track","tt","u","ul","var","video","wbr"]),jg=zn(["svg","a","altglyph","altglyphdef","altglyphitem","animatecolor","animatemotion","animatetransform","circle","clippath","defs","desc","ellipse","enterkeyhint","exportparts","filter","font","g","glyph","glyphref","hkern","image","inputmode","line","lineargradient","marker","mask","metadata","mpath","part","path","pattern","polygon","polyline","radialgradient","rect","stop","style","switch","symbol","text","textpath","title","tref","tspan","view","vkern"]),Bg=zn(["feBlend","feColorMatrix","feComponentTransfer","feComposite","feConvolveMatrix","feDiffuseLighting","feDisplacementMap","feDistantLight","feDropShadow","feFlood","feFuncA","feFuncB","feFuncG","feFuncR","feGaussianBlur","feImage","feMerge","feMergeNode","feMorphology","feOffset","fePointLight","feSpecularLighting","feSpotLight","feTile","feTurbulence"]),tI=zn(["animate","color-profile","cursor","discard","font-face","font-face-format","font-face-name","font-face-src","font-face-uri","foreignobject","hatch","hatchpath","mesh","meshgradient","meshpatch","meshrow","missing-glyph","script","set","solidcolor","unknown","use"]),Ug=zn(["math","menclose","merror","mfenced","mfrac","mglyph","mi","mlabeledtr","mmultiscripts","mn","mo","mover","mpadded","mphantom","mroot","mrow","ms","mspace","msqrt","mstyle","msub","msup","msubsup","mtable","mtd","mtext","mtr","munder","munderover","mprescripts"]),nI=zn(["maction","maligngroup","malignmark","mlongdiv","mscarries","mscarry","msgroup","mstack","msline","msrow","semantics","annotation","annotation-xml","mprescripts","none"]),Hk=zn(["#text"]),Vk=zn(["accept","action","align","alt","autocapitalize","autocomplete","autopictureinpicture","autoplay","background","bgcolor","border","capture","cellpadding","cellspacing","checked","cite","class","clear","color","cols","colspan","controls","controlslist","coords","crossorigin","datetime","decoding","default","dir","disabled","disablepictureinpicture","disableremoteplayback","download","draggable","enctype","enterkeyhint","exportparts","face","for","headers","height","hidden","high","href","hreflang","id","inert","inputmode","integrity","ismap","kind","label","lang","list","loading","loop","low","max","maxlength","media","method","min","minlength","multiple","muted","name","nonce","noshade","novalidate","nowrap","open","optimum","part","pattern","placeholder","playsinline","popover","popovertarget","popovertargetaction","poster","preload","pubdate","radiogroup","readonly","rel","required","rev","reversed","role","rows","rowspan","spellcheck","scope","selected","shape","size","sizes","slot","span","srclang","start","src","srcset","step","style","summary","tabindex","title","translate","type","usemap","valign","value","width","wrap","xmlns","slot"]),zg=zn(["accent-height","accumulate","additive","alignment-baseline","amplitude","ascent","attributename","attributetype","azimuth","basefrequency","baseline-shift","begin","bias","by","class","clip","clippathunits","clip-path","clip-rule","color","color-interpolation","color-interpolation-filters","color-profile","color-rendering","cx","cy","d","dx","dy","diffuseconstant","direction","display","divisor","dur","edgemode","elevation","end","exponent","fill","fill-opacity","fill-rule","filter","filterunits","flood-color","flood-opacity","font-family","font-size","font-size-adjust","font-stretch","font-style","font-variant","font-weight","fx","fy","g1","g2","glyph-name","glyphref","gradientunits","gradienttransform","height","href","id","image-rendering","in","in2","intercept","k","k1","k2","k3","k4","kerning","keypoints","keysplines","keytimes","lang","lengthadjust","letter-spacing","kernelmatrix","kernelunitlength","lighting-color","local","marker-end","marker-mid","marker-start","markerheight","markerunits","markerwidth","maskcontentunits","maskunits","max","mask","mask-type","media","method","mode","min","name","numoctaves","offset","operator","opacity","order","orient","orientation","origin","overflow","paint-order","path","pathlength","patterncontentunits","patterntransform","patternunits","points","preservealpha","preserveaspectratio","primitiveunits","r","rx","ry","radius","refx","refy","repeatcount","repeatdur","restart","result","rotate","scale","seed","shape-rendering","slope","specularconstant","specularexponent","spreadmethod","startoffset","stddeviation","stitchtiles","stop-color","stop-opacity","stroke-dasharray","stroke-dashoffset","stroke-linecap","stroke-linejoin","stroke-miterlimit","stroke-opacity","stroke","stroke-width","style","surfacescale","systemlanguage","tabindex","tablevalues","targetx","targety","transform","transform-origin","text-anchor","text-decoration","text-rendering","textlength","type","u1","u2","unicode","values","viewbox","visibility","version","vert-adv-y","vert-origin-x","vert-origin-y","width","word-spacing","wrap","writing-mode","xchannelselector","ychannelselector","x","x1","x2","xmlns","y","y1","y2","z","zoomandpan"]),Gk=zn(["accent","accentunder","align","bevelled","close","columnsalign","columnlines","columnspan","denomalign","depth","dir","display","displaystyle","encoding","fence","frame","height","href","id","largeop","length","linethickness","lspace","lquote","mathbackground","mathcolor","mathsize","mathvariant","maxsize","minsize","movablelimits","notation","numalign","open","rowalign","rowlines","rowspacing","rowspan","rspace","rquote","scriptlevel","scriptminsize","scriptsizemultiplier","selection","separator","separators","stretchy","subscriptshift","supscriptshift","symmetric","voffset","width","xmlns"]),Ch=zn(["xlink:href","xml:id","xlink:title","xml:space","xmlns:xlink"]),iI=ji(/\{\{[\w\W]*|[\w\W]*\}\}/gm),rI=ji(/<%[\w\W]*|[\w\W]*%>/gm),aI=ji(/\$\{[\w\W]*/gm),oI=ji(/^data-[\-\w.\u00B7-\uFFFF]+$/),sI=ji(/^aria-[\-\w]+$/),Wk=ji(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),lI=ji(/^(?:\w+script|data):/i),cI=ji(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),Yk=ji(/^html$/i),uI=ji(/^[a-z][.\w]*(-[.\w]+)+$/i);var Kk=Object.freeze({__proto__:null,ARIA_ATTR:sI,ATTR_WHITESPACE:cI,CUSTOM_ELEMENT:uI,DATA_ATTR:oI,DOCTYPE_NAME:Yk,ERB_EXPR:rI,IS_ALLOWED_URI:Wk,IS_SCRIPT_OR_DATA:lI,MUSTACHE_EXPR:iI,TMPLIT_EXPR:aI});const wc={element:1,text:3,progressingInstruction:7,comment:8,document:9},dI=function(){return typeof window>"u"?null:window},hI=function(t,e){if(typeof t!="object"||typeof t.createPolicy!="function")return null;let n=null;const i="data-tt-policy-suffix";e&&e.hasAttribute(i)&&(n=e.getAttribute(i));const r="dompurify"+(n?"#"+n:"");try{return t.createPolicy(r,{createHTML(a){return a},createScriptURL(a){return a}})}catch{return console.warn("TrustedTypes policy "+r+" could not be created."),null}},Xk=function(){return{afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]}};function Jk(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:dI();const e=_=>Jk(_);if(e.version="3.3.1",e.removed=[],!t||!t.document||t.document.nodeType!==wc.document||!t.Element)return e.isSupported=!1,e;let{document:n}=t;const i=n,r=i.currentScript,{DocumentFragment:a,HTMLTemplateElement:o,Node:s,Element:l,NodeFilter:c,NamedNodeMap:u=t.NamedNodeMap||t.MozNamedAttrMap,HTMLFormElement:d,DOMParser:h,trustedTypes:p}=t,b=l.prototype,m=Tc(b,"cloneNode"),S=Tc(b,"remove"),g=Tc(b,"nextSibling"),y=Tc(b,"childNodes"),x=Tc(b,"parentNode");if(typeof o=="function"){const _=n.createElement("template");_.content&&_.content.ownerDocument&&(n=_.content.ownerDocument)}let v,k="";const{implementation:T,createNodeIterator:C,createDocumentFragment:R,getElementsByTagName:A}=n,{importNode:N}=i;let O=Xk();e.isSupported=typeof Uk=="function"&&typeof x=="function"&&T&&T.createHTMLDocument!==void 0;const{MUSTACHE_EXPR:z,ERB_EXPR:Y,TMPLIT_EXPR:L,DATA_ATTR:X,ARIA_ATTR:P,IS_SCRIPT_OR_DATA:G,ATTR_WHITESPACE:J,CUSTOM_ELEMENT:te}=Kk;let{IS_ALLOWED_URI:Z}=Kk,q=null;const ee=De({},[...qk,...jg,...Bg,...Ug,...Hk]);let $=null;const ue=De({},[...Vk,...zg,...Gk,...Ch]);let B=Object.seal(Mg(null,{tagNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},allowCustomizedBuiltInElements:{writable:!0,configurable:!1,enumerable:!0,value:!1}})),ve=null,j=null;const me=Object.seal(Mg(null,{tagCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeCheck:{writable:!0,configurable:!1,enumerable:!0,value:null}}));let be=!0,qt=!0,En=!1,Te=!0,Le=!1,ht=!0,lt=!1,hn=!1,fn=!1,At=!1,tn=!1,Nn=!1,Ri=!0,$i=!1;const fe="user-content-";let He=!0,we=!1,rt={},ft=null;const nn=De({},["annotation-xml","audio","colgroup","desc","foreignobject","head","iframe","math","mi","mn","mo","ms","mtext","noembed","noframes","noscript","plaintext","script","style","svg","template","thead","title","video","xmp"]);let Jn=null;const Ai=De({},["audio","video","img","source","image","track"]);let F=null;const oe=De({},["alt","class","for","id","label","name","pattern","placeholder","role","summary","title","value","style","xmlns"]),le="http://www.w3.org/1998/Math/MathML",Oe="http://www.w3.org/2000/svg",Ne="http://www.w3.org/1999/xhtml";let vt=Ne,On=!1,mi=null;const ka=De({},[le,Oe,Ne],Lg);let $n=De({},["mi","mo","mn","ms","mtext"]),Qn=De({},["annotation-xml"]);const Qi=De({},["title","style","font","a","script"]);let gi=null;const jl=["application/xhtml+xml","text/html"],Bl="text/html";let Ee=null,Mn=null;const Ul=n.createElement("form"),To=function(_){return _ instanceof RegExp||_ instanceof Function},qr=function(){let _=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(!(Mn&&Mn===_)){if((!_||typeof _!="object")&&(_={}),_=Dr(_),gi=jl.indexOf(_.PARSER_MEDIA_TYPE)===-1?Bl:_.PARSER_MEDIA_TYPE,Ee=gi==="application/xhtml+xml"?Lg:wh,q=ur(_,"ALLOWED_TAGS")?De({},_.ALLOWED_TAGS,Ee):ee,$=ur(_,"ALLOWED_ATTR")?De({},_.ALLOWED_ATTR,Ee):ue,mi=ur(_,"ALLOWED_NAMESPACES")?De({},_.ALLOWED_NAMESPACES,Lg):ka,F=ur(_,"ADD_URI_SAFE_ATTR")?De(Dr(oe),_.ADD_URI_SAFE_ATTR,Ee):oe,Jn=ur(_,"ADD_DATA_URI_TAGS")?De(Dr(Ai),_.ADD_DATA_URI_TAGS,Ee):Ai,ft=ur(_,"FORBID_CONTENTS")?De({},_.FORBID_CONTENTS,Ee):nn,ve=ur(_,"FORBID_TAGS")?De({},_.FORBID_TAGS,Ee):Dr({}),j=ur(_,"FORBID_ATTR")?De({},_.FORBID_ATTR,Ee):Dr({}),rt=ur(_,"USE_PROFILES")?_.USE_PROFILES:!1,be=_.ALLOW_ARIA_ATTR!==!1,qt=_.ALLOW_DATA_ATTR!==!1,En=_.ALLOW_UNKNOWN_PROTOCOLS||!1,Te=_.ALLOW_SELF_CLOSE_IN_ATTR!==!1,Le=_.SAFE_FOR_TEMPLATES||!1,ht=_.SAFE_FOR_XML!==!1,lt=_.WHOLE_DOCUMENT||!1,At=_.RETURN_DOM||!1,tn=_.RETURN_DOM_FRAGMENT||!1,Nn=_.RETURN_TRUSTED_TYPE||!1,fn=_.FORCE_BODY||!1,Ri=_.SANITIZE_DOM!==!1,$i=_.SANITIZE_NAMED_PROPS||!1,He=_.KEEP_CONTENT!==!1,we=_.IN_PLACE||!1,Z=_.ALLOWED_URI_REGEXP||Wk,vt=_.NAMESPACE||Ne,$n=_.MATHML_TEXT_INTEGRATION_POINTS||$n,Qn=_.HTML_INTEGRATION_POINTS||Qn,B=_.CUSTOM_ELEMENT_HANDLING||{},_.CUSTOM_ELEMENT_HANDLING&&To(_.CUSTOM_ELEMENT_HANDLING.tagNameCheck)&&(B.tagNameCheck=_.CUSTOM_ELEMENT_HANDLING.tagNameCheck),_.CUSTOM_ELEMENT_HANDLING&&To(_.CUSTOM_ELEMENT_HANDLING.attributeNameCheck)&&(B.attributeNameCheck=_.CUSTOM_ELEMENT_HANDLING.attributeNameCheck),_.CUSTOM_ELEMENT_HANDLING&&typeof _.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements=="boolean"&&(B.allowCustomizedBuiltInElements=_.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements),Le&&(qt=!1),tn&&(At=!0),rt&&(q=De({},Hk),$=[],rt.html===!0&&(De(q,qk),De($,Vk)),rt.svg===!0&&(De(q,jg),De($,zg),De($,Ch)),rt.svgFilters===!0&&(De(q,Bg),De($,zg),De($,Ch)),rt.mathMl===!0&&(De(q,Ug),De($,Gk),De($,Ch))),_.ADD_TAGS&&(typeof _.ADD_TAGS=="function"?me.tagCheck=_.ADD_TAGS:(q===ee&&(q=Dr(q)),De(q,_.ADD_TAGS,Ee))),_.ADD_ATTR&&(typeof _.ADD_ATTR=="function"?me.attributeCheck=_.ADD_ATTR:($===ue&&($=Dr($)),De($,_.ADD_ATTR,Ee))),_.ADD_URI_SAFE_ATTR&&De(F,_.ADD_URI_SAFE_ATTR,Ee),_.FORBID_CONTENTS&&(ft===nn&&(ft=Dr(ft)),De(ft,_.FORBID_CONTENTS,Ee)),_.ADD_FORBID_CONTENTS&&(ft===nn&&(ft=Dr(ft)),De(ft,_.ADD_FORBID_CONTENTS,Ee)),He&&(q["#text"]=!0),lt&&De(q,["html","head","body"]),q.table&&(De(q,["tbody"]),delete ve.tbody),_.TRUSTED_TYPES_POLICY){if(typeof _.TRUSTED_TYPES_POLICY.createHTML!="function")throw kc('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');if(typeof _.TRUSTED_TYPES_POLICY.createScriptURL!="function")throw kc('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');v=_.TRUSTED_TYPES_POLICY,k=v.createHTML("")}else v===void 0&&(v=hI(p,r)),v!==null&&typeof k=="string"&&(k=v.createHTML(""));zn&&zn(_),Mn=_}},wo=De({},[...jg,...Bg,...tI]),Co=De({},[...Ug,...nI]),zl=function(_){let I=x(_);(!I||!I.tagName)&&(I={namespaceURI:vt,tagName:"template"});const M=wh(_.tagName),ge=wh(I.tagName);return mi[_.namespaceURI]?_.namespaceURI===Oe?I.namespaceURI===Ne?M==="svg":I.namespaceURI===le?M==="svg"&&(ge==="annotation-xml"||$n[ge]):!!wo[M]:_.namespaceURI===le?I.namespaceURI===Ne?M==="math":I.namespaceURI===Oe?M==="math"&&Qn[ge]:!!Co[M]:_.namespaceURI===Ne?I.namespaceURI===Oe&&!Qn[ge]||I.namespaceURI===le&&!$n[ge]?!1:!Co[M]&&(Qi[M]||!wo[M]):!!(gi==="application/xhtml+xml"&&mi[_.namespaceURI]):!1},pn=function(_){xc(e.removed,{element:_});try{x(_).removeChild(_)}catch{S(_)}},mn=function(_,I){try{xc(e.removed,{attribute:I.getAttributeNode(_),from:I})}catch{xc(e.removed,{attribute:null,from:I})}if(I.removeAttribute(_),_==="is")if(At||tn)try{pn(I)}catch{}else try{I.setAttribute(_,"")}catch{}},Eo=function(_){let I=null,M=null;if(fn)_="<remove></remove>"+_;else{const ye=Ig(_,/^[\r\n\t ]+/);M=ye&&ye[0]}gi==="application/xhtml+xml"&&vt===Ne&&(_='<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>'+_+"</body></html>");const ge=v?v.createHTML(_):_;if(vt===Ne)try{I=new h().parseFromString(ge,gi)}catch{}if(!I||!I.documentElement){I=T.createDocument(vt,"template",null);try{I.documentElement.innerHTML=On?k:ge}catch{}}const Ie=I.body||I.documentElement;return _&&M&&Ie.insertBefore(n.createTextNode(M),Ie.childNodes[0]||null),vt===Ne?A.call(I,lt?"html":"body")[0]:lt?I.documentElement:Ie},Ro=function(_){return C.call(_.ownerDocument||_,_,c.SHOW_ELEMENT|c.SHOW_COMMENT|c.SHOW_TEXT|c.SHOW_PROCESSING_INSTRUCTION|c.SHOW_CDATA_SECTION,null)},Hr=function(_){return _ instanceof d&&(typeof _.nodeName!="string"||typeof _.textContent!="string"||typeof _.removeChild!="function"||!(_.attributes instanceof u)||typeof _.removeAttribute!="function"||typeof _.setAttribute!="function"||typeof _.namespaceURI!="string"||typeof _.insertBefore!="function"||typeof _.hasChildNodes!="function")},Ao=function(_){return typeof s=="function"&&_ instanceof s};function It(_,I,M){Th(_,ge=>{ge.call(e,I,M,Mn)})}const No=function(_){let I=null;if(It(O.beforeSanitizeElements,_,null),Hr(_))return pn(_),!0;const M=Ee(_.nodeName);if(It(O.uponSanitizeElement,_,{tagName:M,allowedTags:q}),ht&&_.hasChildNodes()&&!Ao(_.firstElementChild)&&Fn(/<[/\w!]/g,_.innerHTML)&&Fn(/<[/\w!]/g,_.textContent)||_.nodeType===wc.progressingInstruction||ht&&_.nodeType===wc.comment&&Fn(/<[/\w]/g,_.data))return pn(_),!0;if(!(me.tagCheck instanceof Function&&me.tagCheck(M))&&(!q[M]||ve[M])){if(!ve[M]&&Mo(M)&&(B.tagNameCheck instanceof RegExp&&Fn(B.tagNameCheck,M)||B.tagNameCheck instanceof Function&&B.tagNameCheck(M)))return!1;if(He&&!ft[M]){const ge=x(_)||_.parentNode,Ie=y(_)||_.childNodes;if(Ie&&ge){const ye=Ie.length;for(let U=ye-1;U>=0;--U){const W=m(Ie[U],!0);W.__removalCount=(_.__removalCount||0)+1,ge.insertBefore(W,g(_))}}}return pn(_),!0}return _ instanceof l&&!zl(_)||(M==="noscript"||M==="noembed"||M==="noframes")&&Fn(/<\/no(script|embed|frames)/i,_.innerHTML)?(pn(_),!0):(Le&&_.nodeType===wc.text&&(I=_.textContent,Th([z,Y,L],ge=>{I=Sc(I,ge," ")}),_.textContent!==I&&(xc(e.removed,{element:_.cloneNode()}),_.textContent=I)),It(O.afterSanitizeElements,_,null),!1)},Oo=function(_,I,M){if(Ri&&(I==="id"||I==="name")&&(M in n||M in Ul))return!1;if(!(qt&&!j[I]&&Fn(X,I))&&!(be&&Fn(P,I))&&!(me.attributeCheck instanceof Function&&me.attributeCheck(I,_))){if(!$[I]||j[I]){if(!(Mo(_)&&(B.tagNameCheck instanceof RegExp&&Fn(B.tagNameCheck,_)||B.tagNameCheck instanceof Function&&B.tagNameCheck(_))&&(B.attributeNameCheck instanceof RegExp&&Fn(B.attributeNameCheck,I)||B.attributeNameCheck instanceof Function&&B.attributeNameCheck(I,_))||I==="is"&&B.allowCustomizedBuiltInElements&&(B.tagNameCheck instanceof RegExp&&Fn(B.tagNameCheck,M)||B.tagNameCheck instanceof Function&&B.tagNameCheck(M))))return!1}else if(!F[I]&&!Fn(Z,Sc(M,J,""))&&!((I==="src"||I==="xlink:href"||I==="href")&&_!=="script"&&$L(M,"data:")===0&&Jn[_])&&!(En&&!Fn(G,Sc(M,J,"")))&&M)return!1}return!0},Mo=function(_){return _!=="annotation-xml"&&Ig(_,te)},Do=function(_){It(O.beforeSanitizeAttributes,_,null);const{attributes:I}=_;if(!I||Hr(_))return;const M={attrName:"",attrValue:"",keepAttr:!0,allowedAttributes:$,forceKeepAttr:void 0};let ge=I.length;for(;ge--;){const Ie=I[ge],{name:ye,namespaceURI:U,value:W}=Ie,pe=Ee(ye),je=W;let ae=ye==="value"?je:QL(je);if(M.attrName=pe,M.attrValue=ae,M.keepAttr=!0,M.forceKeepAttr=void 0,It(O.uponSanitizeAttribute,_,M),ae=M.attrValue,$i&&(pe==="id"||pe==="name")&&(mn(ye,_),ae=fe+ae),ht&&Fn(/((--!?|])>)|<\/(style|title|textarea)/i,ae)){mn(ye,_);continue}if(pe==="attributename"&&Ig(ae,"href")){mn(ye,_);continue}if(M.forceKeepAttr)continue;if(!M.keepAttr){mn(ye,_);continue}if(!Te&&Fn(/\/>/i,ae)){mn(ye,_);continue}Le&&Th([z,Y,L],Qe=>{ae=Sc(ae,Qe," ")});const Se=Ee(_.nodeName);if(!Oo(Se,pe,ae)){mn(ye,_);continue}if(v&&typeof p=="object"&&typeof p.getAttributeType=="function"&&!U)switch(p.getAttributeType(Se,pe)){case"TrustedHTML":{ae=v.createHTML(ae);break}case"TrustedScriptURL":{ae=v.createScriptURL(ae);break}}if(ae!==je)try{U?_.setAttributeNS(U,ye,ae):_.setAttribute(ye,ae),Hr(_)?pn(_):Fk(e.removed)}catch{mn(ye,_)}}It(O.afterSanitizeAttributes,_,null)},Fl=function _(I){let M=null;const ge=Ro(I);for(It(O.beforeSanitizeShadowDOM,I,null);M=ge.nextNode();)It(O.uponSanitizeShadowNode,M,null),No(M),Do(M),M.content instanceof a&&_(M.content);It(O.afterSanitizeShadowDOM,I,null)};return e.sanitize=function(_){let I=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},M=null,ge=null,Ie=null,ye=null;if(On=!_,On&&(_="<!-->"),typeof _!="string"&&!Ao(_))if(typeof _.toString=="function"){if(_=_.toString(),typeof _!="string")throw kc("dirty is not a string, aborting")}else throw kc("toString is not a function");if(!e.isSupported)return _;if(hn||qr(I),e.removed=[],typeof _=="string"&&(we=!1),we){if(_.nodeName){const pe=Ee(_.nodeName);if(!q[pe]||ve[pe])throw kc("root node is forbidden and cannot be sanitized in-place")}}else if(_ instanceof s)M=Eo("<!---->"),ge=M.ownerDocument.importNode(_,!0),ge.nodeType===wc.element&&ge.nodeName==="BODY"||ge.nodeName==="HTML"?M=ge:M.appendChild(ge);else{if(!At&&!Le&&!lt&&_.indexOf("<")===-1)return v&&Nn?v.createHTML(_):_;if(M=Eo(_),!M)return At?null:Nn?k:""}M&&fn&&pn(M.firstChild);const U=Ro(we?_:M);for(;Ie=U.nextNode();)No(Ie),Do(Ie),Ie.content instanceof a&&Fl(Ie.content);if(we)return _;if(At){if(tn)for(ye=R.call(M.ownerDocument);M.firstChild;)ye.appendChild(M.firstChild);else ye=M;return($.shadowroot||$.shadowrootmode)&&(ye=N.call(i,ye,!0)),ye}let W=lt?M.outerHTML:M.innerHTML;return lt&&q["!doctype"]&&M.ownerDocument&&M.ownerDocument.doctype&&M.ownerDocument.doctype.name&&Fn(Yk,M.ownerDocument.doctype.name)&&(W="<!DOCTYPE "+M.ownerDocument.doctype.name+`>
46
46
  `+W),Le&&Th([z,Y,L],pe=>{W=Sc(W,pe," ")}),v&&Nn?v.createHTML(W):W},e.setConfig=function(){let _=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};qr(_),hn=!0},e.clearConfig=function(){Mn=null,hn=!1},e.isValidAttribute=function(_,I,M){Mn||qr({});const ge=Ee(_),Ie=Ee(I);return Oo(ge,Ie,M)},e.addHook=function(_,I){typeof I=="function"&&xc(O[_],I)},e.removeHook=function(_,I){if(I!==void 0){const M=XL(O[_],I);return M===-1?void 0:JL(O[_],M,1)[0]}return Fk(O[_])},e.removeHooks=function(_){O[_]=[]},e.removeAllHooks=function(){O=Xk()},e}var fI=Jk();function pI(t){return f.jsxs("div",{className:"obi-static-voice",children:[f.jsx("div",{className:"obi-static-voice-visual-title",children:"AI Guided Tutorial"}),f.jsx("div",{style:{transform:"scale(1.25) translateY(-4px)"},children:f.jsx(kh,{isActive:!0,children:f.jsxs("div",{className:"obi-static-voice-visual",children:[f.jsx("div",{className:"column",children:f.jsx("div",{className:"bar bar-1"})}),f.jsx("div",{className:"column",children:f.jsx("div",{className:"bar bar-2"})}),f.jsx("div",{className:"column",children:f.jsx("div",{className:"bar bar-3"})}),f.jsx("div",{className:"column",children:f.jsx("div",{className:"bar bar-4"})}),f.jsx("div",{className:"column",children:f.jsx("div",{className:"bar bar-5"})}),f.jsx("div",{className:"column",children:f.jsx("div",{className:"bar bar-6"})}),f.jsx("div",{className:"column",children:f.jsx("div",{className:"bar bar-7"})}),f.jsx("div",{className:"column",children:f.jsx("div",{className:"bar bar-8"})})]})})})]})}function mI({session:t,speakingState:e,onAction:n}){const i="Sessions are securely recorded for quality improvement purposes.",r=w.useMemo(()=>{var l;const s=(l=t.legalFooter)==null?void 0:l.trim();return s?fI.sanitize(s):null},[t.legalFooter]),a=w.useRef(null);w.useEffect(()=>{if(!r)return;const s=a.current;s&&s.querySelectorAll("a").forEach(l=>{l.setAttribute("target","_blank");const c=(l.getAttribute("rel")||"").split(/\s+/);c.includes("noopener")||c.push("noopener"),c.includes("noreferrer")||c.push("noreferrer"),l.setAttribute("rel",c.filter(Boolean).join(" ")),l.style.color="black"})},[r]);const o=r?f.jsx("span",{ref:a,dangerouslySetInnerHTML:{__html:r}}):i;return f.jsx(Vs,{className:"session-start-content",title:t.name,subtitle:"AI voice-guided tutorial",description:t.description,footer:o,buttonText:"Get started",agentName:t.agentName||"Obi",speakingState:e,centerVisual:f.jsx(pI,{}),onAction:n})}function gI(){const t={host:{display:"block",position:"relative",width:"100%",height:"161px"},container:{position:"relative",width:"100%",height:"100%",display:"flex",alignItems:"center",justifyContent:"center"},permissionDialog:{boxSizing:"border-box",display:"flex",flexDirection:"row",justifyContent:"flex-start",alignItems:"center",padding:"16px 20px",gap:"16px",position:"absolute",width:"344px",height:"125px",left:"calc(50% - 344px/2)",top:"calc(50% - 125px/2)",background:"#FFFFFF",border:"1px solid #E5E7EB",boxShadow:"0px 10px 15px -3px rgba(0, 0, 0, 0.1), 0px 4px 6px -2px rgba(0, 0, 0, 0.05)",borderRadius:"8px"},permissionContent:{width:"100%",display:"flex",flexDirection:"column",gap:"16px"},permissionContentTop:{display:"flex",flexDirection:"row",alignItems:"center",padding:"0px",gap:"16px"},micIconContainer:{color:"var(--obi-color-text)",boxSizing:"border-box",display:"flex",flexDirection:"row",justifyContent:"center",alignItems:"center",padding:"12px",gap:"8px",width:"48px",height:"48px",background:"#F9FAFB",border:"1px solid #D1D5DB",borderRadius:"6px",flex:"none",order:0,flexGrow:0},micIcon:{width:"24px",height:"24px",flex:"none",order:0,flexGrow:0},permissionText:{flex:1,height:"24px",fontFamily:"'Inter', sans-serif",fontStyle:"normal",fontWeight:500,fontSize:"16px",lineHeight:"24px",display:"flex",alignItems:"center",color:"#111827",flexGrow:1,order:1},allowButton:{alignSelf:"flex-end",boxSizing:"border-box",display:"flex",flexDirection:"row",justifyContent:"center",alignItems:"center",padding:"10px 20px",gap:"8px",minWidth:"80px",height:"40px",background:"#F9FAFB",border:"1px solid #D1D5DB",borderRadius:"6px",flex:"none",order:2,flexGrow:0,cursor:"pointer",fontFamily:"'Inter', sans-serif",fontStyle:"normal",fontWeight:500,fontSize:"14px",lineHeight:"20px",color:"#374151"},cursorPointer:{position:"absolute",width:"24px",height:"24px",right:"80px",bottom:"60px",zIndex:3,animation:"pointToAllow 2s ease-in-out infinite"},cursorSvg:{width:"100%",height:"100%",filter:"drop-shadow(0px 1px 1.8px rgba(0, 0, 0, 0.65))"}};return f.jsxs("div",{style:t.host,children:[f.jsx("style",{children:`
47
47
  @keyframes pointToAllow {
48
48
  0%, 100% { transform: translate(0, 0); }
@@ -130,4 +130,4 @@ ${t}</tr>
130
130
  `}tablecell(t){let e=this.parser.parseInline(t.tokens),n=t.header?"th":"td";return(t.align?`<${n} align="${t.align}">`:`<${n}>`)+e+`</${n}>
131
131
  `}strong({tokens:t}){return`<strong>${this.parser.parseInline(t)}</strong>`}em({tokens:t}){return`<em>${this.parser.parseInline(t)}</em>`}codespan({text:t}){return`<code>${xa(t,!0)}</code>`}br(t){return"<br>"}del({tokens:t}){return`<del>${this.parser.parseInline(t)}</del>`}link({href:t,title:e,tokens:n}){let i=this.parser.parseInline(n),r=u3(t);if(r===null)return i;t=r;let a='<a href="'+t+'"';return e&&(a+=' title="'+xa(e)+'"'),a+=">"+i+"</a>",a}image({href:t,title:e,text:n,tokens:i}){i&&(n=this.parser.parseInline(i,this.parser.textRenderer));let r=u3(t);if(r===null)return xa(n);t=r;let a=`<img src="${t}" alt="${n}"`;return e&&(a+=` title="${xa(e)}"`),a+=">",a}text(t){return"tokens"in t&&t.tokens?this.parser.parseInline(t.tokens):"escaped"in t&&t.escaped?t.text:xa(t.text)}},Bb=class{strong({text:t}){return t}em({text:t}){return t}codespan({text:t}){return t}del({text:t}){return t}html({text:t}){return t}text({text:t}){return t}link({text:t}){return""+t}image({text:t}){return""+t}br(){return""}checkbox({raw:t}){return t}},gr=class $b{constructor(e){gt(this,"options"),gt(this,"renderer"),gt(this,"textRenderer"),this.options=e||ms,this.options.renderer=this.options.renderer||new up,this.renderer=this.options.renderer,this.renderer.options=this.options,this.renderer.parser=this,this.textRenderer=new Bb}static parse(e,n){return new $b(n).parse(e)}static parseInline(e,n){return new $b(n).parseInline(e)}parse(e){var i,r;let n="";for(let a=0;a<e.length;a++){let o=e[a];if((r=(i=this.options.extensions)==null?void 0:i.renderers)!=null&&r[o.type]){let l=o,c=this.options.extensions.renderers[l.type].call({parser:this},l);if(c!==!1||!["space","hr","heading","code","table","blockquote","list","html","def","paragraph","text"].includes(l.type)){n+=c||"";continue}}let s=o;switch(s.type){case"space":{n+=this.renderer.space(s);break}case"hr":{n+=this.renderer.hr(s);break}case"heading":{n+=this.renderer.heading(s);break}case"code":{n+=this.renderer.code(s);break}case"table":{n+=this.renderer.table(s);break}case"blockquote":{n+=this.renderer.blockquote(s);break}case"list":{n+=this.renderer.list(s);break}case"checkbox":{n+=this.renderer.checkbox(s);break}case"html":{n+=this.renderer.html(s);break}case"def":{n+=this.renderer.def(s);break}case"paragraph":{n+=this.renderer.paragraph(s);break}case"text":{n+=this.renderer.text(s);break}default:{let l='Token with "'+s.type+'" type was not found.';if(this.options.silent)return console.error(l),"";throw new Error(l)}}}return n}parseInline(e,n=this.renderer){var r,a;let i="";for(let o=0;o<e.length;o++){let s=e[o];if((a=(r=this.options.extensions)==null?void 0:r.renderers)!=null&&a[s.type]){let c=this.options.extensions.renderers[s.type].call({parser:this},s);if(c!==!1||!["escape","html","link","image","strong","em","codespan","br","del","text"].includes(s.type)){i+=c||"";continue}}let l=s;switch(l.type){case"escape":{i+=n.text(l);break}case"html":{i+=n.html(l);break}case"link":{i+=n.link(l);break}case"image":{i+=n.image(l);break}case"checkbox":{i+=n.checkbox(l);break}case"strong":{i+=n.strong(l);break}case"em":{i+=n.em(l);break}case"codespan":{i+=n.codespan(l);break}case"br":{i+=n.br(l);break}case"del":{i+=n.del(l);break}case"text":{i+=n.text(l);break}default:{let c='Token with "'+l.type+'" type was not found.';if(this.options.silent)return console.error(c),"";throw new Error(c)}}}return i}},dp,Du=(dp=class{constructor(t){gt(this,"options"),gt(this,"block"),this.options=t||ms}preprocess(t){return t}postprocess(t){return t}processAllTokens(t){return t}emStrongMask(t){return t}provideLexer(){return this.block?mr.lex:mr.lexInline}provideParser(){return this.block?gr.parse:gr.parseInline}},gt(dp,"passThroughHooks",new Set(["preprocess","postprocess","processAllTokens","emStrongMask"])),gt(dp,"passThroughHooksRespectAsync",new Set(["preprocess","postprocess","processAllTokens"])),dp),Hz=class{constructor(...t){gt(this,"defaults",Ab()),gt(this,"options",this.setOptions),gt(this,"parse",this.parseMarkdown(!0)),gt(this,"parseInline",this.parseMarkdown(!1)),gt(this,"Parser",gr),gt(this,"Renderer",up),gt(this,"TextRenderer",Bb),gt(this,"Lexer",mr),gt(this,"Tokenizer",cp),gt(this,"Hooks",Du),this.use(...t)}walkTokens(t,e){var i,r;let n=[];for(let a of t)switch(n=n.concat(e.call(this,a)),a.type){case"table":{let o=a;for(let s of o.header)n=n.concat(this.walkTokens(s.tokens,e));for(let s of o.rows)for(let l of s)n=n.concat(this.walkTokens(l.tokens,e));break}case"list":{let o=a;n=n.concat(this.walkTokens(o.items,e));break}default:{let o=a;(r=(i=this.defaults.extensions)==null?void 0:i.childTokens)!=null&&r[o.type]?this.defaults.extensions.childTokens[o.type].forEach(s=>{let l=o[s].flat(1/0);n=n.concat(this.walkTokens(l,e))}):o.tokens&&(n=n.concat(this.walkTokens(o.tokens,e)))}}return n}use(...t){let e=this.defaults.extensions||{renderers:{},childTokens:{}};return t.forEach(n=>{let i={...n};if(i.async=this.defaults.async||i.async||!1,n.extensions&&(n.extensions.forEach(r=>{if(!r.name)throw new Error("extension name required");if("renderer"in r){let a=e.renderers[r.name];a?e.renderers[r.name]=function(...o){let s=r.renderer.apply(this,o);return s===!1&&(s=a.apply(this,o)),s}:e.renderers[r.name]=r.renderer}if("tokenizer"in r){if(!r.level||r.level!=="block"&&r.level!=="inline")throw new Error("extension level must be 'block' or 'inline'");let a=e[r.level];a?a.unshift(r.tokenizer):e[r.level]=[r.tokenizer],r.start&&(r.level==="block"?e.startBlock?e.startBlock.push(r.start):e.startBlock=[r.start]:r.level==="inline"&&(e.startInline?e.startInline.push(r.start):e.startInline=[r.start]))}"childTokens"in r&&r.childTokens&&(e.childTokens[r.name]=r.childTokens)}),i.extensions=e),n.renderer){let r=this.defaults.renderer||new up(this.defaults);for(let a in n.renderer){if(!(a in r))throw new Error(`renderer '${a}' does not exist`);if(["options","parser"].includes(a))continue;let o=a,s=n.renderer[o],l=r[o];r[o]=(...c)=>{let u=s.apply(r,c);return u===!1&&(u=l.apply(r,c)),u||""}}i.renderer=r}if(n.tokenizer){let r=this.defaults.tokenizer||new cp(this.defaults);for(let a in n.tokenizer){if(!(a in r))throw new Error(`tokenizer '${a}' does not exist`);if(["options","rules","lexer"].includes(a))continue;let o=a,s=n.tokenizer[o],l=r[o];r[o]=(...c)=>{let u=s.apply(r,c);return u===!1&&(u=l.apply(r,c)),u}}i.tokenizer=r}if(n.hooks){let r=this.defaults.hooks||new Du;for(let a in n.hooks){if(!(a in r))throw new Error(`hook '${a}' does not exist`);if(["options","block"].includes(a))continue;let o=a,s=n.hooks[o],l=r[o];Du.passThroughHooks.has(a)?r[o]=c=>{if(this.defaults.async&&Du.passThroughHooksRespectAsync.has(a))return(async()=>{let d=await s.call(r,c);return l.call(r,d)})();let u=s.call(r,c);return l.call(r,u)}:r[o]=(...c)=>{if(this.defaults.async)return(async()=>{let d=await s.apply(r,c);return d===!1&&(d=await l.apply(r,c)),d})();let u=s.apply(r,c);return u===!1&&(u=l.apply(r,c)),u}}i.hooks=r}if(n.walkTokens){let r=this.defaults.walkTokens,a=n.walkTokens;i.walkTokens=function(o){let s=[];return s.push(a.call(this,o)),r&&(s=s.concat(r.call(this,o))),s}}this.defaults={...this.defaults,...i}}),this}setOptions(t){return this.defaults={...this.defaults,...t},this}lexer(t,e){return mr.lex(t,e??this.defaults)}parser(t,e){return gr.parse(t,e??this.defaults)}parseMarkdown(t){return(e,n)=>{let i={...n},r={...this.defaults,...i},a=this.onError(!!r.silent,!!r.async);if(this.defaults.async===!0&&i.async===!1)return a(new Error("marked(): The async option was set to true by an extension. Remove async: false from the parse options object to return a Promise."));if(typeof e>"u"||e===null)return a(new Error("marked(): input parameter is undefined or null"));if(typeof e!="string")return a(new Error("marked(): input parameter is of type "+Object.prototype.toString.call(e)+", string expected"));if(r.hooks&&(r.hooks.options=r,r.hooks.block=t),r.async)return(async()=>{let o=r.hooks?await r.hooks.preprocess(e):e,s=await(r.hooks?await r.hooks.provideLexer():t?mr.lex:mr.lexInline)(o,r),l=r.hooks?await r.hooks.processAllTokens(s):s;r.walkTokens&&await Promise.all(this.walkTokens(l,r.walkTokens));let c=await(r.hooks?await r.hooks.provideParser():t?gr.parse:gr.parseInline)(l,r);return r.hooks?await r.hooks.postprocess(c):c})().catch(a);try{r.hooks&&(e=r.hooks.preprocess(e));let o=(r.hooks?r.hooks.provideLexer():t?mr.lex:mr.lexInline)(e,r);r.hooks&&(o=r.hooks.processAllTokens(o)),r.walkTokens&&this.walkTokens(o,r.walkTokens);let s=(r.hooks?r.hooks.provideParser():t?gr.parse:gr.parseInline)(o,r);return r.hooks&&(s=r.hooks.postprocess(s)),s}catch(o){return a(o)}}}onError(t,e){return n=>{if(n.message+=`
132
132
  Please report this to https://github.com/markedjs/marked.`,t){let i="<p>An error occurred:</p><pre>"+xa(n.message+"",!0)+"</pre>";return e?Promise.resolve(i):i}if(e)return Promise.reject(n);throw n}}},gs=new Hz;function it(t,e){return gs.parse(t,e)}it.options=it.setOptions=function(t){return gs.setOptions(t),it.defaults=gs.defaults,JE(it.defaults),it},it.getDefaults=Ab,it.defaults=ms,it.use=function(...t){return gs.use(...t),it.defaults=gs.defaults,JE(it.defaults),it},it.walkTokens=function(t,e){return gs.walkTokens(t,e)},it.parseInline=gs.parseInline,it.Parser=gr,it.parser=gr.parse,it.Renderer=up,it.TextRenderer=Bb,it.Lexer=mr,it.lexer=mr.lex,it.Tokenizer=cp,it.Hooks=Du,it.parse=it,it.options,it.setOptions,it.use,it.walkTokens,it.parseInline,gr.parse,mr.lex;const Vz="_base_1ne03_1",Gz={base:Vz},Wz=["p","br","strong","em","u","a","ul","ol","li","h1","h2","h3","h4","h5","h6","code","pre","blockquote","hr"],Yz=["href","title","target","rel"];it.setOptions({breaks:!0,gfm:!0});function Kz(t){const{content:e,className:n,...i}=t,r=w.useMemo(()=>{if(!e)return"";const a=it.parse(e,{async:!1});return oz.sanitize(a,{ALLOWED_TAGS:[...Wz],ALLOWED_ATTR:[...Yz],ALLOW_DATA_ATTR:!1})},[e]);return r?f.jsx("div",{className:he(Gz.base,n),dangerouslySetInnerHTML:{__html:r},...i}):null}const Xz="_controlBar_6shmw_1",Jz="_popoverAnchor_6shmw_11",$z="_confirmationPopover_6shmw_15",Qz="_confirmationPopoverAlignRight_6shmw_30",Zz="_confirmationPopoverAlignCenter_6shmw_33",eF="_confirmationMessage_6shmw_53",tF="_confirmationActions_6shmw_60",nF="_confirmationButton_6shmw_65",iF="_confirmationButtonCancel_6shmw_83",rF="_confirmationButtonNeutral_6shmw_91",aF="_confirmationButtonDanger_6shmw_99",oF="_controlButton_6shmw_108",sF="_controlButtonIconOnly_6shmw_130",lF="_controlButtonDisabled_6shmw_135",cF="_controlButtonDanger_6shmw_162",uF="_controlButtonContent_6shmw_178",dF="_controlButtonIcon_6shmw_130",hF="_controlButtonLabel_6shmw_194",fF="_controlButtonChevron_6shmw_201",pF="_controlButtonNotificationDot_6shmw_210",mF="_deviceSplitButton_6shmw_222",gF="_deviceSplitButtonEnabled_6shmw_226",vF="_dualButtonContent_6shmw_307",bF="_dualButtonIcon_6shmw_317",yF="_dualButtonLabel_6shmw_326",_F="_screenShareButton_6shmw_340",xF="_screenShareButtonCompact_6shmw_351",We={controlBar:Xz,popoverAnchor:Jz,confirmationPopover:$z,confirmationPopoverAlignRight:Qz,confirmationPopoverAlignCenter:Zz,confirmationMessage:eF,confirmationActions:tF,confirmationButton:nF,confirmationButtonCancel:iF,confirmationButtonNeutral:rF,confirmationButtonDanger:aF,controlButton:oF,controlButtonIconOnly:sF,controlButtonDisabled:lF,controlButtonDanger:cF,controlButtonContent:uF,controlButtonIcon:dF,controlButtonLabel:hF,controlButtonChevron:fF,controlButtonNotificationDot:pF,deviceSplitButton:mF,deviceSplitButtonEnabled:gF,dualButtonContent:vF,dualButtonIcon:bF,dualButtonLabel:yF,screenShareButton:_F,screenShareButtonCompact:xF},SF="_inline_1gpyx_1",kF="_vertical_1gpyx_6",TF="_divider_1gpyx_10",wF="_dividerVertical_1gpyx_16",CF="_customDivider_1gpyx_21",Pu={inline:SF,vertical:kF,divider:TF,dividerVertical:wF,customDivider:CF},f3={none:"0px",xxs:"var(--space-xxs)",xs:"var(--space-xs)",sm:"var(--space-sm)",md:"var(--space-md)",lg:"var(--space-lg)",xl:"var(--space-xl)","2xl":"var(--space-2xl)","3xl":"var(--space-3xl)","4xl":"var(--space-4xl)","5xl":"var(--space-5xl)"};function vr(t){if(t!==void 0){if(typeof t=="number")return`${t}px`;if(t in f3)return f3[t];if(typeof t=="string"&&t.trim().length>0)return t}}function EF(t,e){const{as:n,direction:i="horizontal",gap:r,align:a="center",justify:o,wrap:s=!1,divider:l,className:c,style:u,children:d,...h}=t,p=n??"div",b={display:"flex",flexDirection:i==="horizontal"?"row":"column",flexWrap:s?"wrap":"nowrap",alignItems:a,...o?{justifyContent:o}:{},...u};if(r!==void 0){const y=vr(r);y&&(b.gap=y)}const m=ai.Children.toArray(d).filter(y=>y!=null&&typeof y!="boolean"),S=y=>!l||y===0?null:l===!0||l==="line"?f.jsx("span",{"aria-hidden":"true",className:he(Pu.divider,i==="vertical"&&Pu.dividerVertical)},`inline-divider-${y}`):f.jsx("span",{"aria-hidden":"true",className:Pu.customDivider,children:l},`inline-divider-${y}`),g=[];return m.forEach((y,x)=>{if(x>0){const v=S(x);v&&g.push(v)}g.push(y)}),f.jsx(p,{ref:e,className:he(Pu.inline,i==="vertical"&&Pu.vertical,c),style:b,...h,children:g})}const Ub=ai.forwardRef(EF);Ub.displayName="Inline";function RF(){const[t,e]=w.useState(()=>typeof window>"u"?!1:window.innerWidth<768);return w.useEffect(()=>{if(typeof window>"u"||typeof window.matchMedia!="function")return;const n=window.matchMedia("(max-width: 767px)"),i=()=>{e(n.matches)};return i(),typeof n.addEventListener=="function"?(n.addEventListener("change",i),()=>n.removeEventListener("change",i)):(n.addListener(i),()=>n.removeListener(i))},[]),t}function zb(t){const{icon:e,label:n,showChevron:i=!1,variant:r="default",disabled:a,className:o="",size:s="md",iconOnly:l=!1,showNotificationDot:c=!1,isOn:u,"aria-label":d,...h}=t,p=he(We.controlButton,a&&We.controlButtonDisabled,l&&We.controlButtonIconOnly,r==="danger"&&We.controlButtonDanger,o),b=Number.parseInt(vb[s],10),m=r==="danger"?"outline":"primary",S=r==="danger"?"danger":"default",g=f.jsxs(f.Fragment,{children:[f.jsxs("span",{className:We.controlButtonContent,children:[e?f.jsx("span",{className:We.controlButtonIcon,children:ai.isValidElement(e)&&e.props.size===void 0?ai.cloneElement(e,{size:b}):e}):null,l?null:f.jsx("span",{className:We.controlButtonLabel,children:n}),l||!i?null:f.jsx("span",{className:We.controlButtonChevron,"aria-hidden":"true",children:f.jsx(bb,{size:16})})]}),c?f.jsx("span",{className:We.controlButtonNotificationDot,"aria-hidden":"true"}):null]});return typeof u=="boolean"?f.jsx(ep,{...h,type:"button",disabled:a,variant:m,color:S,isOn:u,"aria-label":d||n,className:p,"data-has-notification":c?"true":void 0,children:g}):f.jsx(ps,{...h,type:"button",disabled:a,variant:m,color:S,"aria-label":d||n,className:p,"data-has-notification":c?"true":void 0,children:g})}function AF(t){const{audioDevices:e,currentMicrophoneId:n,isMicrophoneEnabled:i,isScreenShareActive:r,widgetState:a,canPublishData:o,browserSupportsScreenSharing:s,screenShareButtonVariant:l="default",onMicDeviceSelect:c,onMicToggle:u,onChatToggle:d,onLeave:h,onScreenShareToggle:p,showChatNotification:b=!1,isLanguageSelectorEnabled:m=!0,languages:S=[],selectedLanguage:g=null,defaultLanguageCode:y=null,isMultilingual:x=!1,onLanguageChange:v,isChatOpen:k=a==="chat"}=t,T=S.length,C=!m||T===0,R=RF(),A=R?"xs":"sm",N=R,[O,z]=w.useState(!1),[Y,L]=w.useState(!1),X=w.useRef(null),P=w.useRef(null);w.useEffect(()=>{const j=be=>{const qt=be.composedPath();O&&X.current&&!qt.includes(X.current)&&z(!1),Y&&P.current&&!qt.includes(P.current)&&L(!1)},me=be=>{be.key==="Escape"&&(O&&z(!1),Y&&L(!1))};if(O||Y)return document.addEventListener("mousedown",j),document.addEventListener("keydown",me),()=>{document.removeEventListener("mousedown",j),document.removeEventListener("keydown",me)}},[O,Y]),w.useEffect(()=>{r||z(!1)},[r]);const G=w.useMemo(()=>e.map(j=>({label:j.label||`Microphone ${j.deviceId.slice(0,8)}`,value:j.deviceId})),[e]),J=w.useMemo(()=>n?G.find(j=>j.value===n)??null:null,[n,G]),te=w.useCallback(j=>{j.value,c(j.value)},[c]),Z={microphone:!0,screenShare:s,chat:o},q=w.useCallback(()=>{if(r){z(!0);return}p()},[r,p]),ee=w.useCallback(()=>{z(!1),p()},[p]),$=w.useCallback(()=>{z(!1)},[]),ue=w.useCallback(()=>{L(!0)},[]),B=w.useCallback(()=>{L(!1),h()},[h]),ve=w.useCallback(()=>{L(!1)},[]);return f.jsx("div",{className:We.controlBar,"data-testid":"control-bar","data-controls":JSON.stringify(Z),"data-language-option-count":T>0?String(T):void 0,"data-default-language-code":y??void 0,children:f.jsxs(Ub,{gap:A,align:"center",justify:"center",wrap:N,children:[f.jsx(mU,{onClick:u,buttonAriaLabel:i?"Mute microphone":"Unmute microphone",options:G,value:J,onChange:te,variant:"primary",menuPlacement:"top",menuDisabled:G.length===0,menuAriaLabel:"Select microphone device",listboxAriaLabel:"Microphone devices",ariaPressed:i,className:he(We.deviceSplitButton,i&&We.deviceSplitButtonEnabled),children:f.jsxs("span",{className:We.dualButtonContent,children:[f.jsx("span",{className:We.dualButtonIcon,children:i?f.jsx(kE,{}):f.jsx(TE,{})}),f.jsx("span",{className:We.dualButtonLabel,children:"Microphone"})]})}),o?f.jsx(zb,{icon:f.jsx(yE,{}),label:"Chat",onClick:d,isOn:k,"aria-label":"Toggle chat",showNotificationDot:b}):null,s?f.jsxs("div",{ref:X,className:We.popoverAnchor,children:[f.jsx(zb,{icon:f.jsx(wE,{}),label:r?"Share screen off":"Share screen",className:l==="compact"?We.screenShareButtonCompact:We.screenShareButton,iconOnly:l==="compact",onClick:q,isOn:r,"aria-label":r?"Stop screen sharing":"Start screen sharing"}),O?f.jsxs("div",{className:he(We.confirmationPopover,We.confirmationPopoverAlignCenter),role:"dialog","aria-label":"Stop screen sharing confirmation","data-testid":"confirm-stop-share",children:[f.jsx("p",{className:We.confirmationMessage,children:"Stop screen sharing?"}),f.jsxs("div",{className:We.confirmationActions,children:[f.jsx("button",{type:"button",className:he(We.confirmationButton,We.confirmationButtonCancel),onClick:$,children:"Cancel"}),f.jsx("button",{type:"button",className:he(We.confirmationButton,We.confirmationButtonNeutral),onClick:ee,children:"Stop"})]})]}):null]}):null,f.jsx(DE,{languages:S,value:g,onChange:v,defaultLanguageCode:y,variant:"control-bar",disabled:C}),f.jsxs("div",{ref:P,className:We.popoverAnchor,children:[f.jsx(zb,{icon:f.jsx(SE,{}),label:"Leave",variant:"danger",onClick:ue,"aria-label":"Leave meeting"}),Y?f.jsxs("div",{className:he(We.confirmationPopover,We.confirmationPopoverAlignRight),role:"dialog","aria-label":"Leave meeting confirmation","data-testid":"confirm-leave",children:[f.jsx("p",{className:We.confirmationMessage,children:"Would you like to end the call?"}),f.jsxs("div",{className:We.confirmationActions,children:[f.jsx("button",{type:"button",className:he(We.confirmationButton,We.confirmationButtonCancel),onClick:ve,children:"Cancel"}),f.jsx("button",{type:"button",className:he(We.confirmationButton,We.confirmationButtonDanger),onClick:B,children:"Leave"})]})]}):null]})]})})}function NF(t){return f.jsx(AF,{...t})}const OF="_controlBar_1n8jn_1",MF="_controlButton_1n8jn_12",DF="_controlButtonDisabled_1n8jn_35",PF="_controlButtonDanger_1n8jn_62",LF="_controlButtonIconOnly_1n8jn_78",IF="_screenShareButton_1n8jn_83",jF="_controlButtonContent_1n8jn_88",BF="_controlButtonIcon_1n8jn_78",UF="_controlButtonLabel_1n8jn_103",zF="_controlButtonNotificationDot_1n8jn_108",FF="_popoverAnchor_1n8jn_198",qF="_confirmationPopover_1n8jn_202",HF="_confirmationMessage_1n8jn_216",VF="_confirmationActions_1n8jn_223",GF="_confirmationButton_1n8jn_228",WF="_confirmationButtonCancel_1n8jn_246",YF="_confirmationButtonDanger_1n8jn_254",dn={controlBar:OF,controlButton:MF,controlButtonDisabled:DF,controlButtonDanger:PF,controlButtonIconOnly:LF,screenShareButton:IF,controlButtonContent:jF,controlButtonIcon:BF,controlButtonLabel:UF,controlButtonNotificationDot:zF,popoverAnchor:FF,confirmationPopover:qF,confirmationMessage:HF,confirmationActions:VF,confirmationButton:GF,confirmationButtonCancel:WF,confirmationButtonDanger:YF};function hp(t){const{icon:e,label:n,variant:i="default",disabled:r,className:a="",iconOnly:o=!1,showNotificationDot:s=!1,isOn:l,"aria-label":c,...u}=t,d=he(dn.controlButton,r&&dn.controlButtonDisabled,o&&dn.controlButtonIconOnly,i==="danger"&&dn.controlButtonDanger,a),h=i==="danger"?"outline":"primary",p=i==="danger"?"danger":"default",b=f.jsxs(f.Fragment,{children:[f.jsxs("span",{className:dn.controlButtonContent,children:[e?f.jsx("span",{className:dn.controlButtonIcon,children:ai.isValidElement(e)&&e.props.size===void 0?ai.cloneElement(e,{size:20}):e}):null,o?null:f.jsx("span",{className:dn.controlButtonLabel,children:n})]}),s?f.jsx("span",{className:dn.controlButtonNotificationDot,"aria-hidden":"true"}):null]});return typeof l=="boolean"?f.jsx(ep,{...u,type:"button",disabled:r,variant:h,color:p,size:"xs",isOn:l,"aria-label":c||n,className:d,"data-has-notification":s?"true":void 0,children:b}):f.jsx(ps,{...u,type:"button",disabled:r,variant:h,color:p,size:"xs","aria-label":c||n,className:d,"data-has-notification":s?"true":void 0,children:b})}function KF(t){const{isMicrophoneEnabled:e,isChatOpen:n,isScreenShareActive:i,showChatNotification:r=!1,onMicToggle:a,onChatToggle:o,onScreenShareToggle:s,onLeave:l,languages:c=[],selectedLanguage:u=null,defaultLanguageCode:d=null,isMultilingual:h=!1,onLanguageChange:p,isLanguageSelectorEnabled:b=!0,className:m,testId:S,...g}=t,y=!b||c.length===0,[x,v]=w.useState(!1),k=w.useRef(null);w.useEffect(()=>{const O=Y=>{const L=Y.composedPath();x&&k.current&&!L.includes(k.current)&&v(!1)},z=Y=>{Y.key==="Escape"&&x&&v(!1)};if(x)return document.addEventListener("mousedown",O),document.addEventListener("keydown",z),()=>{document.removeEventListener("mousedown",O),document.removeEventListener("keydown",z)}},[x]);const T=w.useCallback(()=>{a()},[a]),C=w.useCallback(()=>{s()},[s]),R=w.useCallback(()=>{v(!0)},[]),A=w.useCallback(()=>{v(!1),l()},[l]),N=w.useCallback(()=>{v(!1)},[]);return f.jsx("div",{...g,className:he(dn.controlBar,m),"data-testid":S,children:f.jsxs(Ub,{gap:"xs",align:"center",justify:"center",wrap:!1,children:[f.jsx(hp,{icon:e?f.jsx(kE,{size:18}):f.jsx(TE,{size:18}),label:"Microphone",iconOnly:!0,isOn:e,onClick:T,"aria-label":e?"Mute microphone":"Unmute microphone"}),f.jsx(hp,{icon:f.jsx(yE,{}),label:"Chat",iconOnly:!0,isOn:n,onClick:o,"aria-label":"Toggle chat",showNotificationDot:r}),f.jsx(hp,{icon:f.jsx(wE,{}),label:"Screen share",iconOnly:!0,className:dn.screenShareButton,isOn:i,onClick:C,"aria-label":i?"Stop screen sharing":"Start screen sharing"}),f.jsx(DE,{languages:c,value:u,onChange:p,defaultLanguageCode:d,variant:"pip",disabled:y}),f.jsxs("div",{ref:k,className:dn.popoverAnchor,children:[f.jsx(hp,{icon:f.jsx(SE,{size:16}),label:"Hang up",iconOnly:!0,variant:"danger",onClick:R,"aria-label":"Hang up"}),x?f.jsxs("div",{className:dn.confirmationPopover,role:"dialog","aria-label":"Hang up confirmation","data-testid":"confirm-leave",children:[f.jsx("p",{className:dn.confirmationMessage,children:"Would you like to end the call?"}),f.jsxs("div",{className:dn.confirmationActions,children:[f.jsx("button",{type:"button",className:he(dn.confirmationButton,dn.confirmationButtonCancel),onClick:N,children:"Cancel"}),f.jsx("button",{type:"button",className:he(dn.confirmationButton,dn.confirmationButtonDanger),onClick:A,children:"Leave"})]})]}):null]})]})})}function XF(t){return f.jsx(KF,{...t})}const JF="_container_zht0b_1",$F="_containerGradient_zht0b_14",QF="_containerFlat_zht0b_24",ZF="_halo_zht0b_28",eq="_outerRing_zht0b_38",tq="_circle_zht0b_42",nq="_image_zht0b_72",iq="_captionContainer_zht0b_88",rq="_captionRegion_zht0b_99",Sa={container:JF,containerGradient:$F,containerFlat:QF,halo:ZF,outerRing:eq,circle:tq,image:nq,captionContainer:iq,captionRegion:rq},aq="_statusText_1dkze_6",oq={statusText:aq},sq={idle:null,thinking:"Thinking...",searching:"Searching..."};function lq(t){const{status:e,size:n="md"}=t,i=e?sq[e]:null,r=i!==null;return f.jsx("div",{className:oq.statusText,"data-visible":r,"data-size":n,"aria-live":"polite",children:i})}const cq="https://obi-static.s3.ap-southeast-2.amazonaws.com/images/obi-avatar.png",uq={sm:{haloSize:"4.5rem",maxBorderWidth:5,outerRingScalePower:.55,glowSize:"20px"},md:{haloSize:"8rem",maxBorderWidth:8,outerRingScalePower:.7,glowSize:"35px"},lg:{haloSize:"10rem",maxBorderWidth:10,outerRingScalePower:.75,glowSize:"42px"}};function p3(t){const{audioPower:e,size:n="md",background:i="gradient",imageSrc:r=cq,accentColor:a,ariaLabel:o="Avatar placeholder",status:s,captionsText:l,className:c,style:u,...d}=t,h=uq[n],p=Math.min(1,Math.max(0,e)),b=p>.01,m=b?Math.min(1,p/.5):0,S=b?Math.max(1,m*h.maxBorderWidth):0,g=1.02,y=b?g+p*h.outerRingScalePower:g,x=b?.2+p*.35:0,v={...u??{},...a?{"--avatar-fallback-accent":a}:{}},k={"--avatar-fallback-halo-size":h.haloSize,"--avatar-fallback-border-width":`${S}px`,"--avatar-fallback-secondary-border-scale":y.toString(),"--avatar-fallback-secondary-border-opacity":x.toString(),"--avatar-fallback-glow-size":h.glowSize},T=l!=null&&l!=="";return f.jsxs("div",{...d,className:he(Sa.container,i==="gradient"?Sa.containerGradient:Sa.containerFlat,c),style:v,"data-testid":"avatar-fallback","aria-label":o,role:"img",children:[f.jsxs("div",{className:Sa.halo,style:k,children:[f.jsx("div",{className:Sa.outerRing,"aria-hidden":"true"}),f.jsx("div",{className:Sa.circle,children:f.jsx("img",{className:Sa.image,src:r,alt:"","aria-hidden":"true"})}),f.jsx(lq,{status:s,size:n})]}),T&&f.jsx("div",{className:Sa.captionContainer,children:f.jsx("div",{className:Sa.captionRegion,"data-size":n,role:"status","aria-live":"polite","aria-atomic":"true",children:l})})]})}const dq="_container_1k3qg_11",hq="_screenshot_1k3qg_20",fq="_flash_1k3qg_30",Fb={container:dq,screenshot:hq,flash:fq};function pq(t){const{isActive:e,imageUrl:n,onComplete:i,duration:r=2e3}=t,[a,o]=w.useState(!1),s=w.useRef(null),l=w.useRef(i);return w.useEffect(()=>{l.current=i},[i]),w.useEffect(()=>{if(!e){o(!1),s.current&&(clearTimeout(s.current),s.current=null);return}if(!s.current)return o(!0),s.current=setTimeout(()=>{var c;o(!1),s.current=null,(c=l.current)==null||c.call(l)},r),()=>{s.current&&(clearTimeout(s.current),s.current=null)}},[e,r]),a?f.jsxs("div",{className:Fb.container,"aria-live":"polite","aria-label":"Screenshot captured",children:[n&&f.jsx("img",{src:n,alt:"Captured screenshot",className:Fb.screenshot}),f.jsx("div",{className:Fb.flash})]}):null}const mq="_container_13ukq_1",gq="_dragging_13ukq_5",vq="_placeholder_13ukq_9",bq="_handleButton_13ukq_15",yq="_customHandle_13ukq_105",Ll={container:mq,dragging:gq,placeholder:vq,handleButton:bq,"handle-top":"_handle-top_13ukq_65","handle-bottom":"_handle-bottom_13ukq_75","handle-left":"_handle-left_13ukq_85","handle-right":"_handle-right_13ukq_95",customHandle:yq};function _q(t){const{disabled:e,lingerMs:n,isDragging:i}=t,[r,a]=w.useState(!1),o=w.useRef(null),s=w.useCallback(()=>{o.current!==null&&(window.clearTimeout(o.current),o.current=null)},[]),l=w.useCallback(()=>{e||(s(),a(!0))},[s,e]),c=w.useCallback(()=>{e||i||(s(),o.current=window.setTimeout(()=>{a(!1),o.current=null},n))},[s,e,i,n]);return w.useEffect(()=>{i&&l()},[i,l]),w.useEffect(()=>s,[s]),{isHandleVisible:r,showHandle:l,scheduleHideHandle:c}}function xq(t){const{initialPosition:e,preserveSpace:n,onPositionChange:i}=t,r=w.useRef(null),[a,o]=w.useState(!!e),[s,l]=w.useState(!1),[c,u]=w.useState(null),[d,h]=w.useState(()=>e??{x:0,y:0}),p=w.useRef(d);s||(p.current=d);const b=w.useRef(null),m=w.useRef(!1),S=w.useRef(!1);w.useEffect(()=>{e&&(S.current||(o(!0),h(e),p.current=e))},[e==null?void 0:e.x,e==null?void 0:e.y]),w.useEffect(()=>{if(e||m.current)return;const v=r.current;if(!v)return;const k=v.getBoundingClientRect(),T={x:k.left,y:k.top};m.current=!0,o(!0),h(T),p.current=T,u(n?{width:k.width,height:k.height}:null)},[e,n]);const g=w.useCallback(v=>{const k=b.current;if(!(!k||v.pointerId!==k.pointerId)){b.current=null,S.current=!0,h(p.current),l(!1);try{v.currentTarget.releasePointerCapture(k.pointerId)}catch{}}},[]),y=w.useCallback(v=>{v.button===0&&(v.preventDefault(),v.currentTarget.setPointerCapture(v.pointerId),b.current={pointerId:v.pointerId,startClientX:v.clientX,startClientY:v.clientY,startX:p.current.x,startY:p.current.y},l(!0))},[]),x=w.useCallback(v=>{const k=b.current;if(!k||v.pointerId!==k.pointerId)return;const T={x:k.startX+(v.clientX-k.startClientX),y:k.startY+(v.clientY-k.startClientY)};p.current=T,r.current&&(r.current.style.transform=`translate3d(${T.x}px, ${T.y}px, 0)`),i==null||i(T)},[i]);return{containerRef:r,isFixed:a,isDragging:s,position:d,placeholderSize:c,onPointerDown:y,onPointerMove:x,endDrag:g}}function Sq(t){const{children:e,className:n,handle:i="top",initialPosition:r,disabled:a=!1,preserveSpace:o=!0,zIndex:s=1e3,onPositionChange:l,handleAriaLabel:c="Drag",handleLingerMs:u=350,style:d,...h}=t,{containerRef:p,isFixed:b,isDragging:m,position:S,placeholderSize:g,onPointerDown:y,onPointerMove:x,endDrag:v}=xq({initialPosition:r,preserveSpace:o,onPositionChange:l}),{isHandleVisible:k,showHandle:T,scheduleHideHandle:C}=_q({disabled:a,lingerMs:u,isDragging:m}),R=typeof e=="function",A=w.useMemo(()=>{const O=z=>f.jsx("div",{className:he(Ll.customHandle,z.className),onPointerDown:y,onPointerMove:x,onPointerUp:v,onPointerCancel:v,children:z.children});return O.displayName="Draggable.Handle",O},[y,x,v]),N={...d,position:b?"fixed":"relative",top:b?0:d==null?void 0:d.top,left:b?0:d==null?void 0:d.left,transform:b?`translate3d(${S.x}px, ${S.y}px, 0)`:d==null?void 0:d.transform,zIndex:b?s:d==null?void 0:d.zIndex};return f.jsxs(f.Fragment,{children:[o&&b&&g?f.jsx("div",{className:Ll.placeholder,style:{width:g.width,height:g.height}}):null,f.jsxs("div",{ref:p,className:he(Ll.container,m?Ll.dragging:null,n),"data-handle-visible":R?void 0:a?"false":k||m?"true":"false",style:N,onMouseEnter:R?void 0:T,onMouseLeave:R?void 0:C,...h,children:[!R&&!a?f.jsx("button",{type:"button",className:he(Ll.handleButton,Ll[`handle-${i}`]),"aria-label":c,onMouseEnter:T,onMouseLeave:C,onPointerDown:O=>{T(),y(O)},onPointerMove:x,onPointerUp:v,onPointerCancel:v}):null,R?e({Handle:A}):e]})]})}const kq="_container_gzwdo_1",Tq="_captionRegion_gzwdo_14",wq="_status_gzwdo_22",Cq="_captionText_gzwdo_29",fp={container:kq,captionRegion:Tq,status:wq,captionText:Cq},Eq={idle:null,thinking:"Thinking...",searching:"Searching..."};function Rq(t){const{text:e,status:n,className:i,...r}=t,a=n?Eq[n]:null;return f.jsx("div",{...r,className:he(fp.container,i),"data-testid":"pip-captions-panel",children:f.jsxs("div",{className:fp.captionRegion,role:"status","aria-live":"polite","aria-atomic":"true",children:[a?f.jsx("div",{className:fp.status,children:a}):null,f.jsx("div",{className:fp.captionText,children:e})]})})}const Aq="_panel_1laxg_1",Nq="_row_1laxg_22",Oq="_stepContent_1laxg_29",Mq="_stepLabel_1laxg_37",Dq="_currentStep_1laxg_44",Pq="_nextStep_1laxg_51",Lq="_skipButtonContainer_1laxg_65",Iq="_circleButton_1laxg_73",jq="_arrowPlaceholder_1laxg_100",Bq="_skipButton_1laxg_65",Xi={panel:Aq,row:Nq,stepContent:Oq,stepLabel:Mq,currentStep:Dq,nextStep:Pq,skipButtonContainer:Lq,circleButton:Iq,arrowPlaceholder:jq,skipButton:Bq},Uq="_truncatedText_1u580_1",zq={truncatedText:Uq};function m3(t){const{children:e,maxLines:n=2,className:i,"data-testid":r}=t;return f.jsx("div",{className:`${zq.truncatedText} ${i||""}`,style:{WebkitLineClamp:n},"data-testid":r,children:e})}function Fq(t,e,n){var c;const i=t.length,r=n&&i>0&&((c=t[i-1])==null?void 0:c.title)==="Conclusion",a=r?t.slice(0,-1):t.slice(),o=a.length;if(o===0)return{visibleSteps:a,currentIndex:null};const s=typeof e=="number"&&Number.isFinite(e)?e:1;if(r&&s===i)return{visibleSteps:a,currentIndex:null};const l=Math.min(Math.max(s,1),o)-1;return{visibleSteps:a,currentIndex:l}}function qb(t,e){return e<=0||typeof t!="number"||!Number.isFinite(t)?0:Math.min(Math.max(Math.trunc(t),1),e)-1}function qq(t){var C;const{steps:e,currentStep:n,onStepClick:i,hideTrailingConclusionStep:r=!0,className:a,testId:o,...s}=t,{visibleSteps:l,currentIndex:c}=w.useMemo(()=>Fq(e,n,r),[n,r,e]),[u,d]=w.useState(()=>qb(n,l.length)),h=w.useRef(!1);w.useEffect(()=>{if(!h.current)d(qb(n,l.length));else{const R=qb(n,l.length);u===R&&(h.current=!1)}},[n,l,u]);const p=l.length,b=l[u],m=u>0,S=u<p-1,g=S?(C=l[u+1])==null?void 0:C.title:void 0,y=p===0?0:u+1,x=c!==null&&b&&u!==c,v=()=>{m&&(h.current=!0,d(R=>Math.max(R-1,0)))},k=()=>{S&&(h.current=!0,d(R=>Math.min(R+1,p-1)))},T=()=>{!x||!b||!i||(h.current=!1,i(u,b))};return f.jsxs("div",{...s,className:he(Xi.panel,a),"data-testid":o,role:"group","aria-label":"Course progress",children:[f.jsxs("div",{className:Xi.row,children:[m?f.jsx("button",{type:"button",className:Xi.circleButton,"aria-label":"Previous step",onClick:v,children:f.jsx(_E,{size:14})}):f.jsx("span",{className:Xi.arrowPlaceholder,"aria-hidden":"true"}),f.jsxs("div",{className:Xi.stepContent,children:[f.jsxs(pi,{className:Xi.stepLabel,"aria-live":"polite",children:["Step ",y,"/",p]}),f.jsx(m3,{maxLines:2,children:f.jsx(pi,{className:Xi.currentStep,"data-testid":"pip-outline-current-step",children:(b==null?void 0:b.title)??"No steps available"})}),g?f.jsx(m3,{maxLines:2,children:f.jsxs(pi,{variant:"muted",className:Xi.nextStep,children:["Next: ",g]})}):null]}),S?f.jsx("button",{type:"button",className:Xi.circleButton,"aria-label":"Next step",onClick:k,children:f.jsx(IB,{size:14})}):f.jsx("span",{className:Xi.arrowPlaceholder,"aria-hidden":"true"})]}),x?f.jsx("div",{className:Xi.skipButtonContainer,children:f.jsx("button",{type:"button",className:Xi.skipButton,"aria-label":"Skip to this step",onClick:T,children:f.jsx(FB,{size:14})})}):null]})}const Hq="_window_zm5au_1",Vq="_exitButton_zm5au_14",Gq="_content_zm5au_47",Wq="_contentTopOverlay_zm5au_58",Yq="_dragHandle_zm5au_68",Kq="_contentBottomOverlay_zm5au_78",Xq="_controls_zm5au_87",Jq="_messagesPanelWrapper_zm5au_95",So={window:Hq,exitButton:Vq,content:Gq,contentTopOverlay:Wq,dragHandle:Yq,contentBottomOverlay:Kq,controls:Xq,messagesPanelWrapper:Jq};function $q(t){return t==null?!1:typeof t=="string"?t.trim().length>0:!0}function Qq(t){const{onExit:e,controlBarProps:n,isCourseOutlineSelected:i,onCourseOutlineToggle:r,isCaptionsEnabled:a=!1,onCaptionsToggle:o,courseOutline:s,messagesPanel:l,avatarFallbackProps:c,contentTopOverlaySlot:u,screenshotUrl:d,cameraShotTrigger:h,className:p,testId:b,...m}=t,S=i,g=n.isChatOpen&&!S&&l,y=c==null?void 0:c.captionsText,x=a&&$q(y),[v,k]=w.useState(!1),T=w.useRef(h),C=w.useCallback(()=>{k(!1)},[]);w.useEffect(()=>{h&&h>0&&h!==T.current&&k(!0),T.current=h},[h]);const R=w.useCallback(()=>f.jsx(p3,{audioPower:(c==null?void 0:c.audioPower)??0,size:"sm",background:"flat",imageSrc:c==null?void 0:c.imageSrc,ariaLabel:c==null?void 0:c.ariaLabel,status:c==null?void 0:c.status}),[c]),A=S?s?f.jsx(qq,{steps:s.steps,currentStep:s.currentStep,onStepClick:s.onStepClick,hideTrailingConclusionStep:s.hideTrailingConclusionStep}):R():g?f.jsx("div",{className:So.messagesPanelWrapper,children:l}):x?f.jsx(Rq,{text:y}):R();return f.jsxs("div",{...m,className:he(So.window,p),"data-testid":b,role:"group","aria-label":"Picture-in-Picture",children:[f.jsxs("div",{className:So.content,children:[f.jsx("div",{className:So.contentTopOverlay,children:u}),f.jsx("button",{type:"button",className:So.exitButton,onClick:e,"aria-label":"Exit PiP",children:f.jsx(BB,{size:14})}),A,!g&&f.jsxs("div",{className:So.contentBottomOverlay,children:[f.jsx(ep,{isOn:i,onClick:r,variant:"primary",size:"xs","aria-label":"Toggle course outline",children:f.jsx(qB,{size:18})}),f.jsx(ep,{isOn:a,onClick:o,variant:"primary",size:"xs","aria-label":"Toggle captions",children:f.jsx(LB,{size:18})})]}),f.jsx(pq,{isActive:v,imageUrl:d??null,onComplete:C})]}),f.jsx("div",{className:So.controls,children:f.jsx(XF,{...n})})]})}function Zq(t){const{initialPosition:e,onPositionChange:n,zIndex:i=1e3,...r}=t;return f.jsx(Sq,{initialPosition:e,onPositionChange:n,zIndex:i,preserveSpace:!1,children:({Handle:a})=>f.jsx(Qq,{...r,contentTopOverlaySlot:f.jsx(a,{className:So.dragHandle})})})}const eH="_root_ygi3o_1",tH="_overlay_ygi3o_7",nH="_caption_ygi3o_17",Hb={root:eH,overlay:tH,caption:nH};function iH(t){return t==null?!1:typeof t=="string"?t.trim().length>0:!0}function rH(t){const{children:e,className:n,text:i}=t,r=iH(i);return f.jsxs("div",{className:he(Hb.root,n),children:[e,r?f.jsx("div",{className:Hb.overlay,role:"status","aria-live":"polite","aria-atomic":"true",children:f.jsx("div",{className:Hb.caption,children:i})}):null]})}const aH="_box_dc9yv_1",oH={box:aH},g3={none:"0px",panel:"var(--radius-panel)",card:"var(--radius-card)"},v3={surface:"var(--color-surface)",surfaceMuted:"var(--color-surface-muted)",surfaceAlt:"var(--color-surface-alt)",primarySoft:"var(--color-primary-soft)",primarySofter:"var(--color-primary-softer)",dangerSurface:"var(--color-danger-surface)"};function sH(t){if(t!==void 0){if(typeof t=="number")return`${t}px`;if(t in g3)return g3[t];if(typeof t=="string"&&t.trim().length>0)return t}}function lH(t){if(t!==void 0){if(t in v3)return v3[t];if(typeof t=="string"&&t.trim().length>0)return t}}function cH(t,e){const{as:n,className:i,padding:r,paddingX:a,paddingY:o,paddingTop:s,paddingBottom:l,paddingLeft:c,paddingRight:u,paddingSm:d,paddingMd:h,paddingLg:p,paddingXl:b,margin:m,marginX:S,marginY:g,marginTop:y,marginBottom:x,marginLeft:v,marginRight:k,radius:T,radiusTop:C,radiusBottom:R,radiusLeft:A,radiusRight:N,radiusTopLeft:O,radiusTopRight:z,radiusBottomLeft:Y,radiusBottomRight:L,background:X,gap:P,style:G,...J}=t,te=n??"div",Z={...G},q=Z,ee={},$=(j,me)=>{if(me===void 0)return;const be=vr(me);be&&(Z[j]=be)},ue=(j,me)=>{if(me===void 0)return;const be=vr(me);be&&(Z[j]=be)},B=(j,me)=>{if(me===void 0)return;const be=sH(me);be&&(Z[j]=be)},ve={sm:d,md:h,lg:p,xl:b};if(r!==void 0){const j=vr(r);j&&(q["--box-padding"]=j)}for(const[j,me]of Object.entries(ve)){if(me===void 0)continue;const be=vr(me);be&&(q[`--box-padding-${j}`]=be,ee[`data-padding-${j}`]="")}if(a!==void 0){const j=vr(a);j&&(Z.paddingLeft=j,Z.paddingRight=j)}if(o!==void 0){const j=vr(o);j&&(Z.paddingTop=j,Z.paddingBottom=j)}if($("paddingTop",s),$("paddingBottom",l),$("paddingLeft",c),$("paddingRight",u),m!==void 0){const j=vr(m);j&&(Z.margin=j)}if(S!==void 0){const j=vr(S);j&&(Z.marginLeft=j,Z.marginRight=j)}if(g!==void 0){const j=vr(g);j&&(Z.marginTop=j,Z.marginBottom=j)}if(ue("marginTop",y),ue("marginBottom",x),ue("marginLeft",v),ue("marginRight",k),P!==void 0){const j=vr(P);j&&(Z.gap=j)}if(B("borderRadius",T),C!==void 0&&(B("borderTopLeftRadius",C),B("borderTopRightRadius",C)),R!==void 0&&(B("borderBottomLeftRadius",R),B("borderBottomRightRadius",R)),A!==void 0&&(B("borderTopLeftRadius",A),B("borderBottomLeftRadius",A)),N!==void 0&&(B("borderTopRightRadius",N),B("borderBottomRightRadius",N)),B("borderTopLeftRadius",O),B("borderTopRightRadius",z),B("borderBottomLeftRadius",Y),B("borderBottomRightRadius",L),X!==void 0){const j=lH(X);j&&(Z.background=j)}return f.jsx(te,{ref:e,className:he(oH.box,i),style:Z,...ee,...J})}const pp=ai.forwardRef(cH);pp.displayName="Box";const uH="_panel_eawk4_1",dH="_selected_eawk4_10",b3={panel:uH,selected:dH};function Lu(t){const{children:e,className:n,selected:i,...r}=t;return f.jsx("div",{className:he(b3.panel,i?b3.selected:null,n),...r,children:e})}const hH="_root_yccm8_1",fH="_header_yccm8_8",pH="_icon_yccm8_15",mH="_text_yccm8_26",gH="_heading_yccm8_33",vH="_description_yccm8_41",bH="_body_yccm8_47",yH="_footer_yccm8_54",ko={root:hH,header:fH,icon:pH,text:mH,heading:gH,description:vH,body:bH,footer:yH};function y3(t){const{className:e,...n}=t;return f.jsx("div",{className:he(ko.icon,e),...n})}function _3(t){const{className:e,...n}=t;return f.jsx("h3",{className:he(ko.heading,e),...n})}function x3(t){const{className:e,...n}=t;return f.jsx("p",{className:he(ko.description,e),...n})}function S3(t){const{className:e,...n}=t;return f.jsx("div",{className:he(ko.footer,e),...n})}function _H(t){const e=w.Children.toArray(t),n=[];let i,r,a,o;for(const s of e){if(w.isValidElement(s)&&s.type===y3&&i===void 0){i=s;continue}if(w.isValidElement(s)&&s.type===_3&&r===void 0){r=s;continue}if(w.isValidElement(s)&&s.type===x3&&a===void 0){a=s;continue}if(w.isValidElement(s)&&s.type===S3&&o===void 0){o=s;continue}n.push(s)}return{icon:i,heading:r,description:a,footer:o,body:n}}function xH(t){const{children:e,className:n,...i}=t,r=_H(e),a=r.icon||r.heading||r.description;return f.jsxs(Lu,{className:he(ko.root,n),...i,children:[a?f.jsxs("div",{className:ko.header,children:[r.icon,r.heading||r.description?f.jsxs("div",{className:ko.text,children:[r.heading,r.description]}):null]}):null,r.body.length?f.jsx("div",{className:ko.body,children:r.body}):null,r.footer]})}const Vb=Object.assign(xH,{Icon:y3,Heading:_3,Description:x3,Footer:S3}),SH="_panel_1ts1h_1",kH="_header_1ts1h_10",TH="_title_1ts1h_19",wH="_scrollArea_1ts1h_29",CH="_scrollable_1ts1h_34",EH="_list_1ts1h_39",RH="_courseButton_1ts1h_45",AH="_courseCard_1ts1h_56",NH="_courseHeading_1ts1h_65",OH="_courseDescription_1ts1h_71",MH="_empty_1ts1h_80",br={panel:SH,header:kH,title:TH,scrollArea:wH,scrollable:CH,list:EH,courseButton:RH,courseCard:AH,courseHeading:NH,courseDescription:OH,empty:MH};function DH(t){const{selectionMode:e,selectedCourseIds:n,defaultSelectedCourseIds:i,onSelectedCourseIdsChange:r}=t,a=n!==void 0,[o,s]=w.useState(()=>i??[]),l=a?n:o,c=w.useCallback(d=>{a||s(d),r==null||r(d)},[a,r]),u=w.useCallback(d=>{const h=l.includes(d);if(e==="single"){c(h?[]:[d]);return}if(h){c(l.filter(p=>p!==d));return}c([...l,d])},[l,e,c]);return{selectedCourseIds:l,toggleCourseId:u}}function PH(t){const{title:e="Courses",ariaLabel:n,className:i,courses:r,selectionMode:a="multiple",selectedCourseIds:o,onCourseToggle:s,emptyMessage:l="No courses available",testId:c,...u}=t;return f.jsxs(Lu,{...u,className:he(br.panel,i),role:"region","aria-label":n??e,"data-testid":c,children:[f.jsx("div",{className:br.header,children:f.jsx(pi,{as:"h2",className:br.title,children:e})}),f.jsx("div",{className:br.scrollArea,children:f.jsx(Dl,{className:br.scrollable,children:r.length===0?f.jsx(pi,{variant:"muted",className:br.empty,"data-testid":"course-panel-empty",children:l}):f.jsx("div",{className:br.list,"data-testid":"course-panel-list",children:r.map(d=>{const h=o.includes(d.id),p=d.disabled===!0;return f.jsx("button",{type:"button",className:br.courseButton,"aria-pressed":h,"aria-disabled":p,disabled:p,onClick:()=>s==null?void 0:s(d.id,d),"data-testid":`course-panel-item-${d.id}`,children:f.jsxs(Vb,{selected:h,className:br.courseCard,children:[f.jsx(Vb.Heading,{className:br.courseHeading,children:d.title}),d.description?f.jsx(Vb.Description,{className:br.courseDescription,children:d.description}):null]})},d.id)})})})})]})}function LH(t){const{selectionMode:e="multiple",selectedCourseIds:n,defaultSelectedCourseIds:i,onSelectedCourseIdsChange:r,onCourseToggle:a,...o}=t,{selectedCourseIds:s,toggleCourseId:l}=DH({selectionMode:e,selectedCourseIds:n,defaultSelectedCourseIds:i,onSelectedCourseIdsChange:r}),c=w.useCallback((u,d)=>{l(u),a==null||a(u,d)},[a,l]);return f.jsx(PH,{...o,selectionMode:e,selectedCourseIds:s,onCourseToggle:c})}const IH="_panel_1je0q_1",jH="_header_1je0q_10",BH="_headerActions_1je0q_19",UH="_popoverAnchor_1je0q_27",zH="_backButton_1je0q_31",FH="_divider_1je0q_38",qH="_title_1je0q_44",HH="_scrollArea_1je0q_54",VH="_scrollable_1je0q_59",GH="_list_1je0q_64",WH="_section_1je0q_70",YH="_sectionHeader_1je0q_76",KH="_sectionTitle_1je0q_80",XH="_sectionTitleCompact_1je0q_88",JH="_item_1je0q_92",$H="_itemClickable_1je0q_106",QH="_itemCompleted_1je0q_110",ZH="_itemCurrent_1je0q_114",eV="_itemFuture_1je0q_118",tV="_itemDisabled_1je0q_123",nV="_row_1je0q_137",iV="_stepHeader_1je0q_144",rV="_stepNumber_1je0q_153",aV="_stepTitle_1je0q_159",oV="_checkIcon_1je0q_171",sV="_empty_1je0q_175",lV="_confirmationPopover_1je0q_180",cV="_confirmationMessage_1je0q_204",uV="_confirmationActions_1je0q_211",dV="_confirmationButton_1je0q_216",hV="_confirmationButtonCancel_1je0q_234",fV="_confirmationButtonNeutral_1je0q_242",Ae={panel:IH,header:jH,headerActions:BH,popoverAnchor:UH,backButton:zH,divider:FH,title:qH,scrollArea:HH,scrollable:VH,list:GH,section:WH,sectionHeader:YH,sectionTitle:KH,sectionTitleCompact:XH,item:JH,itemClickable:$H,itemCompleted:QH,itemCurrent:ZH,itemFuture:eV,itemDisabled:tV,row:nV,stepHeader:iV,stepNumber:rV,stepTitle:aV,checkIcon:oV,empty:sV,confirmationPopover:lV,confirmationMessage:cV,confirmationActions:uV,confirmationButton:dV,confirmationButtonCancel:hV,confirmationButtonNeutral:fV};function pV(t){var p;const{steps:e,currentStep:n,hideTrailingConclusionStep:i}=t,r=e.length,a=i&&r>0&&((p=e[r-1])==null?void 0:p.title)==="Conclusion",o=a?e.slice(0,-1):e.slice(),s=o.length,l=typeof n=="number"&&isFinite(n)?n:1;if(s===0)return{visibleSteps:o,completedIndices:[],currentIndex:null,futureIndices:[]};if(a&&l===r)return{visibleSteps:o,completedIndices:Array.from({length:s},(b,m)=>m),currentIndex:null,futureIndices:[]};const c=Math.min(Math.max(l,1),s)-1,u=Array.from({length:Math.max(0,c)},(b,m)=>m),d=Math.min(c,s-1),h=Array.from({length:Math.max(0,s-(d+1))},(b,m)=>d+1+m);return{visibleSteps:o,completedIndices:u,currentIndex:d,futureIndices:h}}function mV(t){const{title:e="Course Outline",ariaLabel:n,className:i,steps:r,currentStep:a,onStepClick:o,hideTrailingConclusionStep:s=!0,emptyMessage:l="No steps available",density:c="default",testId:u,onBackToCoursesConfirm:d,backToCoursesDisabled:h=!1,backToCoursesLabel:p="Back to courses",backToCoursesConfirmMessage:b="Going back will end this course. You can start another course from the list.",backToCoursesConfirmLabel:m="Back",backToCoursesCancelLabel:S="Cancel",showBackToCourses:g=!0,...y}=t,[x,v]=w.useState(!1),k=w.useRef(null),T=h||!d,C=w.useCallback(G=>(G+1).toString().padStart(2,"0"),[]),{visibleSteps:R,completedIndices:A,currentIndex:N,futureIndices:O}=w.useMemo(()=>pV({steps:r,currentStep:a,hideTrailingConclusionStep:s}),[a,s,r]),z=c==="compact"?"md":"lg",Y=w.useCallback(()=>{T||v(G=>!G)},[T]),L=w.useCallback(()=>{v(!1)},[]),X=w.useCallback(()=>{v(!1),d&&d()},[d]);w.useEffect(()=>{if(!x)return;const G=te=>{const Z=te.composedPath();k.current&&!Z.includes(k.current)&&v(!1)},J=te=>{te.key==="Escape"&&v(!1)};return document.addEventListener("mousedown",G),document.addEventListener("keydown",J),()=>{document.removeEventListener("mousedown",G),document.removeEventListener("keydown",J)}},[x]),w.useEffect(()=>{T&&x&&v(!1)},[T,x]);const P=w.useCallback((G,J)=>{const te=R[G];if(!te)return null;const Z=typeof o=="function",q=Z&&te.disabled===!0,ee=Z&&!q,$=he(Ae.item,{[Ae.itemClickable]:ee,[Ae.itemCompleted]:J==="completed",[Ae.itemCurrent]:J==="current",[Ae.itemFuture]:J==="future",[Ae.itemDisabled]:q}),ue=f.jsxs("div",{className:Ae.row,children:[f.jsxs("div",{className:Ae.stepHeader,children:[f.jsx("span",{className:Ae.stepNumber,children:C(G)}),f.jsx("span",{className:Ae.stepTitle,children:te.title})]}),J==="completed"?f.jsx(Qf,{size:20,className:Ae.checkIcon}):null]});return Z?f.jsx(pp,{as:"button",type:"button",className:$,onClick:()=>{ee&&o(G,te)},disabled:q,"aria-current":J==="current"?"step":void 0,"aria-label":`Step ${C(G)}: ${te.title}`,"data-testid":`course-outline-item-${te.id}`,padding:z,radius:"panel",gap:"sm",children:ue},te.id):f.jsx(pp,{className:$,"aria-current":J==="current"?"step":void 0,"aria-label":`Step ${C(G)}: ${te.title}`,"data-testid":`course-outline-item-${te.id}`,padding:z,radius:"panel",gap:"sm",children:ue},te.id)},[C,z,o,R]);return f.jsxs(Lu,{...y,className:he(Ae.panel,i),role:"region","aria-label":n??e,"data-testid":u,children:[f.jsxs("div",{className:Ae.header,children:[f.jsx(pi,{as:"h2",className:Ae.title,children:e}),g?f.jsx("div",{className:Ae.headerActions,children:f.jsxs("div",{ref:k,className:Ae.popoverAnchor,children:[f.jsxs(ps,{type:"button",variant:"secondary",color:"default",size:"sm",className:Ae.backButton,onClick:Y,disabled:T,"aria-label":p,"data-testid":"course-outline-back-button",children:[f.jsx(_E,{size:16,"aria-hidden":"true"}),f.jsx("span",{children:p})]}),x?f.jsxs("div",{className:Ae.confirmationPopover,role:"dialog","aria-label":"Back to courses confirmation","data-testid":"course-outline-back-confirm",children:[f.jsx("p",{className:Ae.confirmationMessage,children:b}),f.jsxs("div",{className:Ae.confirmationActions,children:[f.jsx("button",{type:"button",className:he(Ae.confirmationButton,Ae.confirmationButtonCancel),onClick:L,"data-testid":"course-outline-back-cancel",children:S}),f.jsx("button",{type:"button",className:he(Ae.confirmationButton,Ae.confirmationButtonNeutral),onClick:X,"data-testid":"course-outline-back-confirm-action",children:m})]})]}):null]})}):null]}),f.jsx("div",{className:Ae.divider,"aria-hidden":"true"}),f.jsx("div",{className:Ae.scrollArea,children:f.jsx(Dl,{className:Ae.scrollable,children:R.length===0?f.jsx(pi,{variant:"muted",className:Ae.empty,"data-testid":"course-outline-empty",children:l}):f.jsxs("div",{className:Ae.list,"data-testid":"course-outline-list",children:[A.length>0?f.jsxs("div",{className:Ae.section,"data-testid":"course-outline-section-completed",children:[f.jsx("div",{className:Ae.sectionHeader,children:f.jsx("span",{className:he(Ae.sectionTitle,c==="compact"?Ae.sectionTitleCompact:null),children:"Completed"})}),A.map(G=>P(G,"completed"))]}):null,N!==null?f.jsxs("div",{className:Ae.section,"data-testid":"course-outline-section-current",children:[f.jsx("div",{className:Ae.sectionHeader,children:f.jsx("span",{className:he(Ae.sectionTitle,c==="compact"?Ae.sectionTitleCompact:null),children:"Current"})}),P(N,"current")]}):null,O.length>0?f.jsxs("div",{className:Ae.section,"data-testid":"course-outline-section-upcoming",children:[f.jsx("div",{className:Ae.sectionHeader,children:f.jsx("span",{className:he(Ae.sectionTitle,c==="compact"?Ae.sectionTitleCompact:null),children:"Upcoming"})}),O.map(G=>P(G,"future"))]}):null]})})})]})}function gV(t){return f.jsx(mV,{...t})}const vV="_panel_h7cuf_1",bV="_messagesArea_h7cuf_20",yV="_messagesList_h7cuf_46",_V="_messageItem_h7cuf_53",xV="_messageMetadata_h7cuf_59",SV="_senderName_h7cuf_67",kV="_timestamp_h7cuf_71",TV="_messageBubble_h7cuf_75",wV="_agentMessage_h7cuf_85",CV="_agentActions_h7cuf_89",EV="_copyButton_h7cuf_95",RV="_copyButtonCopied_h7cuf_129",AV="_empty_h7cuf_133",NV="_composer_h7cuf_140",OV="_composerDisabled_h7cuf_160",MV="_composerInput_h7cuf_165",DV="_sendButton_h7cuf_180",Cn={panel:vV,messagesArea:bV,messagesList:yV,messageItem:_V,messageMetadata:xV,senderName:SV,timestamp:kV,messageBubble:TV,agentMessage:wV,agentActions:CV,copyButton:EV,copyButtonCopied:RV,empty:AV,composer:NV,composerDisabled:OV,composerInput:MV,sendButton:DV};function PV(t){const e=new Date(t),n=e.getHours(),i=e.getMinutes(),r=n>=12?"PM":"AM",a=n%12||12,o=i.toString().padStart(2,"0");return`${a}:${o}${r}`}function LV(t,e){var i,r;if(typeof t.isAgent=="boolean")return t.isAgent;const n=((i=t.from)==null?void 0:i.identity)??void 0;return n&&e&&n===e?!1:((r=t.attributes)==null?void 0:r.source)==="agent-rpc"?!0:n?n==="agent-avatar"||n.startsWith("agent-"):!1}function IV(t,e){var i,r,a;const n=(i=t.from)==null?void 0:i.identity;return n&&e&&n===e?"You":((r=t.from)==null?void 0:r.name)??((a=t.attributes)==null?void 0:a.senderName)??n??"Unknown"}async function jV(t){var n;if(typeof navigator<"u"&&((n=navigator.clipboard)!=null&&n.writeText)){await navigator.clipboard.writeText(t);return}if(typeof document>"u")throw new Error("Clipboard unavailable");const e=document.createElement("textarea");e.value=t,e.style.position="fixed",e.style.left="-9999px",e.style.top="0",e.setAttribute("readonly","true"),document.body.appendChild(e),e.select(),document.execCommand("copy"),document.body.removeChild(e)}function BV(t){const{messages:e,localIdentity:n,onSend:i,isSending:r=!1,inputPlaceholder:a="Type a message...",className:o,testId:s,...l}=t,[c,u]=w.useState(""),[d,h]=w.useState(null),p=w.useRef(null),b=w.useRef(null),m=w.useMemo(()=>{const v=e[e.length-1];return v?v.id??`${v.timestamp}-${e.length-1}`:null},[e]);w.useEffect(()=>{var v,k;(k=(v=p.current)==null?void 0:v.scrollIntoView)==null||k.call(v,{behavior:"smooth"})},[m]),w.useEffect(()=>()=>{b.current&&(window.clearTimeout(b.current),b.current=null)},[]);const S=w.useCallback(async()=>{const v=c.trim();v.length!==0&&(await i(v),u(""))},[c,i]),g=w.useCallback(v=>{v.key==="Enter"&&(v.preventDefault(),S())},[S]),y=w.useCallback(async(v,k)=>{try{await jV(v.message??""),h(k),b.current&&window.clearTimeout(b.current),b.current=window.setTimeout(()=>{h(null),b.current=null},2e3)}catch(T){console.warn("[PiPChatPanel] Failed to copy message",T)}},[]),x=c.trim().length>0&&!r;return f.jsxs("div",{...l,className:he(Cn.panel,o),"data-testid":s,role:"region","aria-label":"Chat",children:[f.jsx("div",{className:Cn.messagesArea,children:e.length===0?f.jsx("div",{className:Cn.empty,"data-testid":"pip-chat-panel-empty",children:"No messages yet"}):f.jsxs("div",{className:Cn.messagesList,"data-testid":"pip-chat-panel-list",children:[e.map((v,k)=>{const T=v.id??`${v.timestamp}-${k}`,C=LV(v,n),R=d===T;return f.jsxs("div",{className:he(Cn.messageItem,C&&Cn.agentMessage),"data-testid":`pip-chat-panel-message-${T}`,children:[f.jsxs("div",{className:Cn.messageMetadata,children:[f.jsx("span",{className:Cn.senderName,children:IV(v,n)}),f.jsx("span",{className:Cn.timestamp,children:PV(v.timestamp)})]}),f.jsx("div",{className:Cn.messageBubble,children:v.message}),C?f.jsx("div",{className:Cn.agentActions,children:f.jsx("button",{type:"button",className:he(Cn.copyButton,R&&Cn.copyButtonCopied),onClick:()=>void y(v,T),"aria-label":R?"Copied":"Copy message",title:R?"Copied":"Copy message","data-testid":"pip-copy-agent-message","data-copied":R?"true":"false",children:f.jsx(xE,{size:14})})}):null]},T)}),f.jsx("div",{ref:p})]})}),f.jsxs("div",{className:he(Cn.composer,r&&Cn.composerDisabled),children:[f.jsx("input",{type:"text",className:Cn.composerInput,value:c,onChange:v=>u(v.target.value),onKeyDown:g,placeholder:a,disabled:r,"aria-label":"Message"}),f.jsx("button",{type:"button",className:Cn.sendButton,onClick:()=>void S(),disabled:!x,"aria-label":"Send message",children:f.jsx(CE,{size:16})})]})]})}const UV="_panel_k5ick_1",zV="_header_k5ick_11",FV="_title_k5ick_19",qV="_titleCompact_k5ick_29",HV="_headerActions_k5ick_33",VV="_closeButton_k5ick_39",GV="_divider_k5ick_67",WV="_body_k5ick_73",YV="_messagesArea_k5ick_81",KV="_scrollable_k5ick_86",XV="_messagesList_k5ick_90",JV="_messageItem_k5ick_98",$V="_messageMetadata_k5ick_104",QV="_senderName_k5ick_112",ZV="_timestamp_k5ick_116",eG="_messageBubble_k5ick_120",tG="_messageText_k5ick_124",nG="_agentMessage_k5ick_130",iG="_agentActions_k5ick_134",rG="_copyButton_k5ick_140",aG="_copyButtonCopied_k5ick_174",oG="_inputRow_k5ick_178",sG="_empty_k5ick_182",lG="_composer_k5ick_188",cG="_composerDefault_k5ick_203",uG="_composerCompact_k5ick_208",dG="_composerDisabled_k5ick_218",hG="_composerInputWrapper_k5ick_223",fG="_composerInput_k5ick_223",pG="_sendButton_k5ick_240",mG="_sendButtonCompact_k5ick_257",tt={panel:UV,header:zV,title:FV,titleCompact:qV,headerActions:HV,closeButton:VV,divider:GV,body:WV,messagesArea:YV,scrollable:KV,messagesList:XV,messageItem:JV,messageMetadata:$V,senderName:QV,timestamp:ZV,messageBubble:eG,messageText:tG,agentMessage:nG,agentActions:iG,copyButton:rG,copyButtonCopied:aG,inputRow:oG,empty:sG,composer:lG,composerDefault:cG,composerCompact:uG,composerDisabled:dG,composerInputWrapper:hG,composerInput:fG,sendButton:pG,sendButtonCompact:mG};function gG(t){const e=new Date(t),n=e.getHours(),i=e.getMinutes(),r=n>=12?"PM":"AM",a=n%12||12,o=i.toString().padStart(2,"0");return`${a}:${o}${r}`}function vG(t,e){var i,r;if(typeof t.isAgent=="boolean")return t.isAgent;const n=((i=t.from)==null?void 0:i.identity)??void 0;return n&&e&&n===e?!1:((r=t.attributes)==null?void 0:r.source)==="agent-rpc"?!0:n?n==="agent-avatar"||n.startsWith("agent-"):!1}function bG(t,e){var i,r,a;const n=(i=t.from)==null?void 0:i.identity;return n&&e&&n===e?"You":((r=t.from)==null?void 0:r.name)??((a=t.attributes)==null?void 0:a.senderName)??n??"Unknown"}async function yG(t){var n;if(typeof navigator<"u"&&((n=navigator.clipboard)!=null&&n.writeText)){await navigator.clipboard.writeText(t);return}if(typeof document>"u")throw new Error("Clipboard unavailable");const e=document.createElement("textarea");e.value=t,e.style.position="fixed",e.style.left="-9999px",e.style.top="0",e.setAttribute("readonly","true"),document.body.appendChild(e),e.select(),document.execCommand("copy"),document.body.removeChild(e)}function _G(t){const{disabled:e,placeholder:n,size:i="md",autoFocus:r,onSend:a}=t,[o,s]=w.useState(""),l=w.useCallback(async()=>{const p=o.trim();p.length!==0&&(await a(p),s(""))},[a,o]),c=w.useCallback(p=>{p.key==="Enter"&&(p.preventDefault(),l())},[l]),u=i==="sm"||i==="xs",d=u?18:24,h=o.trim().length>0&&e!==!0;return f.jsxs("div",{className:he(tt.composer,u?tt.composerCompact:tt.composerDefault,e?tt.composerDisabled:null),children:[f.jsx("div",{className:tt.composerInputWrapper,children:f.jsx(RE,{value:o,onChange:s,onKeyDown:c,className:tt.composerInput,placeholder:n??"Send a message ...",disabled:e,size:i,autoFocus:r,"aria-label":"Message"})}),f.jsx("button",{type:"button",className:he(tt.sendButton,u?tt.sendButtonCompact:null),onClick:()=>void l(),disabled:!h,"aria-label":"Send message",children:f.jsx(CE,{size:d})})]})}function k3(t){const{title:e="Messages",ariaLabel:n,className:i,messages:r,isSending:a=!1,localIdentity:o,onSend:s,onClose:l,showCloseButton:c=!0,emptyMessage:u="No messages yet",density:d="default",testId:h,formatTimestamp:p=gG,getSenderName:b,isAgentMessage:m,copyResetDelayMs:S=2e3,showAgentCopyButton:g=!0,inputPlaceholder:y,inputAutoFocus:x,...v}=t,k=w.useRef(null),[T,C]=w.useState(null),R=w.useRef(null),A=w.useCallback(X=>b?b(X):bG(X,o),[b,o]),N=w.useCallback(X=>m?m(X,o):vG(X,o),[m,o]),O=w.useMemo(()=>{const X=r[r.length-1];return X?X.id??`${X.timestamp}-${r.length-1}`:null},[r]);w.useEffect(()=>{var X,P;(P=(X=k.current)==null?void 0:X.scrollIntoView)==null||P.call(X,{behavior:"smooth"})},[O]),w.useEffect(()=>()=>{R.current&&(window.clearTimeout(R.current),R.current=null)},[]);const z=w.useCallback(X=>{C(X),R.current&&window.clearTimeout(R.current),R.current=window.setTimeout(()=>{C(null),R.current=null},S)},[S]),Y=w.useCallback(async(X,P)=>{try{await yG(X.message??""),z(P)}catch(G){console.warn("[ChatPanel] Failed to copy message",G)}},[z]),L=d==="compact"?"sm":"md";return f.jsxs(Lu,{...v,className:he(tt.panel,i),role:"region","aria-label":n??e,"data-testid":h,children:[f.jsxs("div",{className:tt.header,children:[f.jsx(pi,{as:"h2",className:he(tt.title,d==="compact"?tt.titleCompact:null),children:e}),l&&c?f.jsx("div",{className:tt.headerActions,children:f.jsx("button",{type:"button",className:tt.closeButton,onClick:l,"aria-label":`Close ${e}`,children:f.jsx(Zf,{size:d==="compact"?18:20})})}):null]}),f.jsx("div",{className:tt.divider,"aria-hidden":"true"}),f.jsxs("div",{className:tt.body,children:[f.jsx("div",{className:tt.messagesArea,children:f.jsx(Dl,{className:tt.scrollable,children:r.length===0?f.jsx(pi,{variant:"muted",className:tt.empty,"data-testid":"chat-panel-empty",children:u}):f.jsxs("div",{className:tt.messagesList,"data-testid":"chat-panel-list",children:[r.map((X,P)=>{const G=X.id??`${X.timestamp}-${P}`,J=N(X),te=T===G;return f.jsxs("div",{className:he(tt.messageItem,J?tt.agentMessage:null),"data-testid":`chat-panel-message-${G}`,children:[f.jsxs("div",{className:tt.messageMetadata,children:[f.jsx("span",{className:tt.senderName,children:A(X)}),f.jsx("span",{className:tt.timestamp,children:p(X.timestamp)})]}),f.jsx(pp,{className:tt.messageBubble,padding:"md",radius:"panel",background:J?"surfaceMuted":"surface",children:f.jsx("div",{className:tt.messageText,children:X.message})}),J&&g?f.jsx("div",{className:tt.agentActions,children:f.jsx("button",{type:"button",className:he(tt.copyButton,te?tt.copyButtonCopied:null),onClick:()=>void Y(X,G),"aria-label":te?"Copied":"Copy agent message",title:te?"Copied":"Copy agent message","data-testid":"copy-agent-message","data-copied":te?"true":"false",children:f.jsx(xE,{size:18})})}):null]},G)}),f.jsx("div",{ref:k})]})})}),f.jsx("div",{className:tt.inputRow,children:f.jsx(_G,{onSend:s,disabled:a,placeholder:y,size:L,autoFocus:x})})]})]})}const xG="_responsive_14d0j_2",Iu={responsive:xG,"showAboveWidth-sm":"_showAboveWidth-sm_14d0j_15","showAboveWidth-md":"_showAboveWidth-md_14d0j_24","showAboveWidth-lg":"_showAboveWidth-lg_14d0j_33","showAboveWidth-xl":"_showAboveWidth-xl_14d0j_42","hideAboveWidth-sm":"_hideAboveWidth-sm_14d0j_53","hideAboveWidth-md":"_hideAboveWidth-md_14d0j_59","hideAboveWidth-lg":"_hideAboveWidth-lg_14d0j_65","hideAboveWidth-xl":"_hideAboveWidth-xl_14d0j_71","showAboveHeight-short":"_showAboveHeight-short_14d0j_84","showAboveHeight-medium":"_showAboveHeight-medium_14d0j_93","hideAboveHeight-short":"_hideAboveHeight-short_14d0j_104","hideAboveHeight-medium":"_hideAboveHeight-medium_14d0j_110"};function SG(t){const{as:e,children:n,showAboveWidth:i,hideAboveWidth:r,showAboveHeight:a,hideAboveHeight:o,className:s,...l}=t,c=[Iu.responsive];return i&&c.push(Iu[`showAboveWidth-${i}`]),r&&c.push(Iu[`hideAboveWidth-${r}`]),a&&c.push(Iu[`showAboveHeight-${a}`]),o&&c.push(Iu[`hideAboveHeight-${o}`]),f.jsx(e??"div",{...l,className:he(c,s),children:n})}w.createContext("vertical");const kG="_container_1v6ko_1",TG="_video_1v6ko_7",wG="_chip_1v6ko_16",CG="_logo_1v6ko_34",mp={container:kG,video:TG,chip:wG,logo:CG},EG="https://obi-static.s3.ap-southeast-2.amazonaws.com/videos/greeting.mp4";function RG(t){const{agentName:e="Obi",greetingVideoSrc:n,className:i,...r}=t,a=w.useRef(null),o=()=>{var s;try{(s=a.current)==null||s.pause()}catch{}};return f.jsxs("div",{className:he(mp.container,i),...r,children:[f.jsx("video",{ref:a,className:mp.video,src:n??EG,autoPlay:!0,muted:!0,playsInline:!0,onEnded:o}),f.jsxs("div",{className:mp.chip,children:[f.jsx(UB,{size:12,className:mp.logo}),f.jsx("span",{children:e})]})]})}typeof __SENTRY_DEBUG__>"u"||__SENTRY_DEBUG__;const T3=50,Il="?",w3=/\(error: (.*)\)/,C3=/captureMessage|captureException/;function AG(...t){const e=t.sort((n,i)=>n[0]-i[0]).map(n=>n[1]);return(n,i=0,r=0)=>{const a=[],o=n.split(`
133
- `);for(let s=i;s<o.length;s++){const l=o[s];if(l.length>1024)continue;const c=w3.test(l)?l.replace(w3,"$1"):l;if(!c.match(/\S*Error: /)){for(const u of e){const d=u(c);if(d){a.push(d);break}}if(a.length>=T3+r)break}}return NG(a.slice(r))}}function NG(t){if(!t.length)return[];const e=Array.from(t);return/sentryWrapped/.test(gp(e).function||"")&&e.pop(),e.reverse(),C3.test(gp(e).function||"")&&(e.pop(),C3.test(gp(e).function||"")&&e.pop()),e.slice(0,T3).map(n=>({...n,filename:n.filename||gp(e).filename,function:n.function||Il}))}function gp(t){return t[t.length-1]||{}}typeof __SENTRY_DEBUG__>"u"||__SENTRY_DEBUG__;const OG=30,MG=50;function Gb(t,e,n,i){const r={filename:t,function:e==="<anonymous>"?Il:e,in_app:!0};return n!==void 0&&(r.lineno=n),i!==void 0&&(r.colno=i),r}const DG=/^\s*at (\S+?)(?::(\d+))(?::(\d+))\s*$/i,PG=/^\s*at (?:(.+?\)(?: \[.+\])?|.*?) ?\((?:address at )?)?(?:async )?((?:<anonymous>|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,LG=/\((\S*)(?::(\d+))(?::(\d+))\)/,IG=t=>{const e=DG.exec(t);if(e){const[,i,r,a]=e;return Gb(i,Il,+r,+a)}const n=PG.exec(t);if(n){if(n[2]&&n[2].indexOf("eval")===0){const a=LG.exec(n[2]);a&&(n[2]=a[1],n[3]=a[2],n[4]=a[3])}const[i,r]=E3(n[1]||Il,n[2]);return Gb(r,i,n[3]?+n[3]:void 0,n[4]?+n[4]:void 0)}},jG=[OG,IG],BG=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:[-a-z]+)?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i,UG=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i;AG(...[jG,[MG,t=>{const e=BG.exec(t);if(e){if(e[3]&&e[3].indexOf(" > eval")>-1){const r=UG.exec(e[3]);r&&(e[1]=e[1]||"eval",e[3]=r[1],e[4]=r[2],e[5]="")}let n=e[3],i=e[1]||Il;return[i,n]=E3(i,n),Gb(n,i,e[4]?+e[4]:void 0,e[5]?+e[5]:void 0)}}]]);const E3=(t,e)=>{const n=t.indexOf("safari-extension")!==-1,i=t.indexOf("safari-web-extension")!==-1;return n||i?[t.indexOf("@")!==-1?t.split("@")[0]:Il,n?`safari-extension:${e}`:`safari-web-extension:${e}`]:[t,e]};typeof __SENTRY_DEBUG__>"u"||__SENTRY_DEBUG__;const Ji={shell:"_shell_8bsnr_1",layout:"_layout_8bsnr_11",layoutThree:"_layoutThree_8bsnr_23",leftPanel:"_leftPanel_8bsnr_27",middlePanel:"_middlePanel_8bsnr_36",rightPanel:"_rightPanel_8bsnr_37",videoFrame:"_videoFrame_8bsnr_41",captions:"_captions_8bsnr_52",controls:"_controls_8bsnr_58",coursePanel:"_coursePanel_8bsnr_71",returnToPiPOverlay:"_returnToPiPOverlay_8bsnr_82",returnToPiPButton:"_returnToPiPButton_8bsnr_94"};function Wb(...t){return t.filter(Boolean).join(" ")}function zG(t){const{captionsText:e,avatarAudioPower:n=0,avatarImageSrc:i,avatarAriaLabel:r,avatarStatus:a,controlBarProps:o,courses:s,coursePanelProps:l,middlePanel:c,rightPanel:u,isCourseOutlineOpen:d,onReturnToPiP:h,className:p}=t;return f.jsx("div",{className:Wb(Ji.shell,p),"data-testid":"course-dialog-content",children:f.jsxs("div",{className:Wb(Ji.layout,u?Ji.layoutThree:null),children:[f.jsxs("div",{className:Ji.leftPanel,children:[f.jsxs("div",{className:Ji.videoFrame,children:[d&&h&&f.jsx("div",{className:Ji.returnToPiPOverlay,children:f.jsx("button",{type:"button",className:Ji.returnToPiPButton,onClick:h,"aria-label":"Return to PiP","data-testid":"course-return-to-pip",children:f.jsx(jB,{size:14})})}),f.jsx(rH,{className:Ji.captions,text:e,children:f.jsx(p3,{audioPower:n,size:"lg",background:"flat",imageSrc:i,ariaLabel:r??"Agent avatar placeholder",status:a})})]}),f.jsx("div",{className:Ji.controls,children:f.jsx(NF,{...o})})]}),u?f.jsx("div",{className:Ji.rightPanel,"data-testid":"course-dialog-right-panel",children:u}):null,f.jsx("div",{className:Ji.middlePanel,"data-testid":"course-dialog-middle-panel",children:c??f.jsx(LH,{...l,courses:s,className:Wb(Ji.coursePanel,l==null?void 0:l.className)})})]})})}function R3(t){const{open:e,onClose:n,dialogProps:i,...r}=t;return f.jsx(IE,{open:e,onClose:n,variant:"ghost",...i,children:f.jsx(zG,{...r})})}const FG=80,qG=500,HG=1e3;function VG(t,e){const{delayMs:n=0}=e??{},r=t.filter(m=>{var g;const S=(g=m.participantInfo)==null?void 0:g.identity;return(S==null?void 0:S.startsWith("agent-"))??!1}).map(m=>m.text??"").join(" ").trim(),[a,o]=w.useState(""),[s,l]=w.useState(!1),c=w.useRef(""),u=w.useRef(null),d=w.useRef(null),h=w.useRef(null),p=m=>{h.current&&(clearTimeout(h.current),h.current=null),n>0?h.current=setTimeout(()=>{o(m)},n):o(m)},b=(m,S)=>m.startsWith(S)?m.slice(S.length).trim():m.trim();return w.useEffect(()=>{if(d.current&&(clearTimeout(d.current),d.current=null),s)return;const m=b(r,c.current);p(m),m.length>FG?(l(!0),u.current=setTimeout(()=>{l(!1),c.current=r},qG+n)):m.length>0&&(d.current=setTimeout(()=>{c.current=r,p("")},HG+n))},[r,s,n]),w.useEffect(()=>()=>{u.current&&clearTimeout(u.current),d.current&&clearTimeout(d.current),h.current&&clearTimeout(h.current)},[]),{caption:a,hasCaption:a.length>0}}const yr={layout:"_layout_k1q6c_1",left:"_left_k1q6c_10",copy:"_copy_k1q6c_17",description:"_description_k1q6c_25",descriptionScroller:"_descriptionScroller_k1q6c_31",cta:"_cta_k1q6c_36",disclaimer:"_disclaimer_k1q6c_43",right:"_right_k1q6c_47",mediaPanel:"_mediaPanel_k1q6c_56",agentStill:"_agentStill_k1q6c_63",dialogWithSmallClose:"_dialogWithSmallClose_k1q6c_88"};function GG(t){const{open:e,onClose:n,onStart:i,agentName:r,agentSubtitle:a,description:o,startLabel:s="Start Now",disclaimer:l="Sessions are securely recorded for quality improvement purposes.",showCloseButton:c=!1,isStarting:u=!1,greetingVideoSrc:d}=t;return f.jsx(IE,{open:e,onClose:n,size:"large",showCloseButton:c,className:yr.dialogWithSmallClose,children:f.jsxs("div",{className:yr.layout,children:[f.jsxs("div",{className:yr.left,children:[f.jsxs("div",{className:yr.copy,children:[f.jsx(pi,{variant:"heading",children:r}),f.jsx(pi,{variant:"subheading",children:a}),f.jsx(pi,{variant:"muted",as:"div",className:yr.description,children:f.jsx(Dl,{className:yr.descriptionScroller,children:f.jsx(Kz,{content:o})})})]}),f.jsxs("div",{className:yr.cta,children:[f.jsx(ps,{type:"button",size:"lg",fullWidth:!0,onClick:i,isLoading:u,children:s}),f.jsx(pi,{variant:"subscript",as:"p",className:yr.disclaimer,children:l})]})]}),f.jsx(SG,{showAboveWidth:"md",children:f.jsx("div",{className:yr.right,children:f.jsx(Lu,{className:yr.mediaPanel,children:f.jsx(RG,{agentName:r,greetingVideoSrc:d,className:yr.agentStill})})})})]})})}const WG={launcherPill:"_launcherPill_1fhyr_1"};function YG(t){const{label:e,onClick:n}=t;return f.jsx("button",{type:"button",className:WG.launcherPill,onClick:n,"data-testid":"ai-coach-pill",children:e})}const A3="__ama_course__",KG="ama_course";function XG(t){var gi,jl,Bl,Ee,Mn,Ul,To,qr,wo,Co,zl,pn,mn,Eo,Ro,Hr,Ao,It,No,Oo,Mo,Do,Fl,_,I,M,ge,Ie,ye;const{sdk:e,shadowHost:n}=t,i=!!e.passivePlanUuid,r=i?((gi=e.client)==null?void 0:gi.selectedPlanUuid)??null:null,a=((jl=e.client)==null?void 0:jl.session)??null,o=!!a&&(i&&!!r||!!((Bl=e.client)!=null&&Bl.selectedPlanUuid)),[s,l]=w.useState(()=>a),[c,u]=w.useState(()=>a!=null&&a.sessionUuid?$G(a.sessionUuid):null),d=(()=>{var U;return a?((U=a.roomId)==null?void 0:U.startsWith("obs-"))&&!c?"course-selection":"pip":r?"start-session":"hidden"})(),[h,p]=w.useState(()=>d),[b,m]=w.useState(!1),[S,g]=w.useState(!1),[y,x]=w.useState(!1),[v,k]=w.useState([]),[T,C]=w.useState(null),[R,A]=w.useState(0),[N,O]=w.useState(!1),[z,Y]=w.useState(!1),[L,X]=w.useState(0),[P,G]=w.useState(null),[J,te]=w.useState([]),[Z,q]=w.useState(!1),[ee,$]=w.useState(!1),[ue,B]=w.useState(()=>o),ve=w.useRef(o),j=w.useRef(!1),me=()=>{p(U=>{const W=U==="course-selection",pe=U==="course-outline"&&j.current;return W||pe?(j.current=!1,O(!1),"pip"):U})},be=QG((Mn=(Ee=e.client)==null?void 0:Ee.product)==null?void 0:Mn.widget_url_blacklist),qt=ZG(s),{audioDevices:En}=eW();w.useEffect(()=>{s!=null&&s.sessionUuid&&N3(s.sessionUuid,c)},[c,s==null?void 0:s.sessionUuid]);const{caption:Te}=VG(J,{delayMs:0}),Le=typeof navigator<"u"&&!!((Ul=navigator.mediaDevices)!=null&&Ul.getDisplayMedia),ht=((qr=(To=s==null?void 0:s.room)==null?void 0:To.localParticipant)==null?void 0:qr.isScreenShareEnabled)??!1,lt=U=>{var Se;const W=((Se=e.client)==null?void 0:Se.identity)??U.identity,pe=typeof(W==null?void 0:W.first_name)=="string"?W.first_name.trim():"",je=typeof(W==null?void 0:W.last_name)=="string"?W.last_name.trim():"",ae=typeof(W==null?void 0:W.email)=="string"&&W.email.trim().length>0?W.email.trim():"";return{firstName:pe,lastName:je,email:ae}},hn=U=>{const{firstName:W,lastName:pe,email:je}=lt(U),ae=[W,pe,je].map(Qe=>Qe.trim());return ae.some(Qe=>Qe.length>0)?ae.join(":"):""},fn=U=>{const{firstName:W,lastName:pe,email:je}=lt(U),ae=[W,pe].filter(Boolean).join(" ").trim();return{name:ae.length>0?ae:void 0,email:je.length>0?je:void 0,screenShareSupported:Le}},At=(()=>{if(s!=null&&s.speakingState){if(s.speakingState==="thinking")return"thinking";if(s.speakingState==="busy")return"searching"}})(),tn=((Co=(wo=e.client)==null?void 0:wo.product)==null?void 0:Co.avatar_image_url)||((pn=(zl=e.client)==null?void 0:zl.product)==null?void 0:pn.logo_url)||void 0,Nn=((Eo=(mn=e.client)==null?void 0:mn.product)==null?void 0:Eo.greeting_video_url)||void 0,Ri=JG({sdk:e,session:s,isBlacklisted:be}),$i=!i&&Ri,fe=!!(s??((Ro=e.client)==null?void 0:Ro.session)??null),He=(s==null?void 0:s.clientType)==="meet"?hn(s):"",we=(Ao=(Hr=e.client)==null?void 0:Hr.product)==null?void 0:Ao.assistant_subtitle,ft=typeof we=="string"&&we.trim().length>0?we:"AI Coach",nn=()=>A(U=>U+1),Jn=async()=>{var W,pe;if(!s)return;const U=((pe=(W=s.room)==null?void 0:W.localParticipant)==null?void 0:pe.isScreenShareEnabled)??!1;try{U?await s.setScreenShareEnabled(!1):await s.shareScreen()}catch(je){console.error("[obi-sdk] failed to toggle screen share",je)}finally{nn()}},Ai=w.useRef(null),F=w.useRef(null),oe=w.useRef(!1),le=w.useRef({session:null,sessionUuid:null,started:!1}),Oe=w.useRef(null),Ne=w.useRef(new WeakMap),vt=(U,W)=>{if(!W)return;let pe=Ne.current.get(U);pe||(pe=new Set,Ne.current.set(U,pe)),pe.add(W)},On=U=>{if(!U||Ai.current===U)return;F.current&&(F.current(),F.current=null);const W=()=>nn(),pe=ie=>{u(ie),U!=null&&U.sessionUuid&&N3(U.sessionUuid,ie),Array.isArray(ie.stepNames)&&ie.stepNames.length>0&&ie.totalSteps>0&&p(bt=>bt==="pip"||bt==="course-outline"?bt:bt==="course-selection"?(j.current=!0,"course-outline"):bt)},je=ie=>{k(ie.courses),p("course-selection"),j.current=!1,u(null),U!=null&&U.sessionUuid&&O3(U.sessionUuid),C(null),Y(!1)},ae=(ie,Ye)=>{},Se=ie=>{ie.isAgent},Qe=ie=>{G(ie),X(Date.now())},Xt=ie=>{if(!ie){G(null);return}G(ie),X(Date.now())};U.on("stateChanged",W),U.on("speakingStateChanged",W),U.on("paused",W),U.on("unpaused",W),U.on("chatMessagesChanged",W),U.on("chatMessageReceived",Se),U.on("courseProgress",pe),U.on("courseSelection",je),U.on("transcript",ae),U.on("screenCaptured",Qe),U.on("screenCaptureNotification",Xt),U.on("captions",te),U.on("introductionComplete",me),Ai.current=U,F.current=()=>{U.off("stateChanged",W),U.off("speakingStateChanged",W),U.off("paused",W),U.off("unpaused",W),U.off("chatMessagesChanged",W),U.off("chatMessageReceived",Se),U.off("courseProgress",pe),U.off("courseSelection",je),U.off("transcript",ae),U.off("screenCaptured",Qe),U.off("screenCaptureNotification",Xt),U.off("captions",te),U.off("introductionComplete",me)}},mi=U=>{var pe;return U?((pe=U.roomId)==null?void 0:pe.startsWith("obs-"))&&!c?"course-selection":"pip":"hidden"};w.useEffect(()=>{const U=()=>{Oe.current&&(Oe.current(),Oe.current=null)},W=ae=>{if(ae.clientType!=="meet")return;if(le.current.session&&le.current.session===ae||!!le.current.sessionUuid&&!!ae.sessionUuid&&le.current.sessionUuid===ae.sessionUuid){if(le.current.started||Oe.current)return}else le.current={session:ae,sessionUuid:ae.sessionUuid??null,started:!1},U();const Qe=async()=>{le.current={session:ae,sessionUuid:ae.sessionUuid??null,started:!0};const Ye=hn(ae);Ye&&vt(ae,Ye);try{await ae.sendHumanJoined(fn(ae))}catch(bt){console.error("[obi-sdk] failed to send human_joined handshake",bt)}},Xt=(Ye,bt)=>{Ye==="connecting"||Ye==="error"||(U(),Qe())},ie=ae.state;if(ie&&ie!=="connecting"&&ie!=="error"){Qe();return}ae.on("stateChanged",Xt),Oe.current=()=>{ae.off("stateChanged",Xt)}},pe=ae=>{var Se,Qe,Xt,ie;if(ae)if((Se=e.client)!=null&&Se.session)p(mi(((Xt=e.client)==null?void 0:Xt.session)??null));else{const bt=!!e.passivePlanUuid,Dn=bt&&!!((Qe=e.client)!=null&&Qe.selectedPlanUuid);if(bt&&!Dn)return;p("start-session")}else(ie=e.client)!=null&&ie.session||p("hidden")},je=()=>nn();if(e.on("showMenu",pe),e.on("configUpdated",je),e.client){e.client.session&&(l(e.client.session),On(e.client.session),p(mi(e.client.session))),e.client.on("sessionStarted",Se=>{l(Se),On(Se),oe.current=!1,m(!1),g(!1),x(!1),Y(!1);const Qe=ve.current;ve.current=!1,Qe?(j.current=!0,p("course-outline")):(j.current=!1,p(mi(Se))),ta().track("session-started",{planId:Se.planId}),W(Se)}),e.client.on("sessionResumed",Se=>{l(Se),On(Se),oe.current=!1,m(!1),g(!1),x(!1),Y(!1),j.current=!1,p(mi(Se)),W(Se)});const ae=()=>{var Xt;const Se=(Xt=e.client)==null?void 0:Xt.session;Se!=null&&Se.sessionUuid&&O3(Se.sessionUuid);const Qe=Ai.current;F.current&&(F.current(),F.current=null),l(null),Ai.current=null,m(!1),g(!1),x(!1),Y(!1),B(!1),ve.current=!1,j.current=!1,U(),le.current={session:null,sessionUuid:null,started:!1},Qe&&Ne.current.delete(Qe),oe.current||p("hidden")};e.client.on("sessionStopped",ae),e.client.on("sessionShutdown",ae),e.client.on("stateChanged",nn)}return()=>{e.off("showMenu",pe),e.off("configUpdated",je),F.current&&F.current(),U()}},[e]),w.useEffect(()=>{const U=s;if(!U||U.clientType!=="meet")return;const W=U.state;if(!W||W==="connecting"||W==="error"||!He)return;const pe=Ne.current.get(U);pe!=null&&pe.has(He)||(vt(U,He),U.sendHumanJoined(fn(U)).catch(je=>console.error("[obi-sdk] failed to send human_joined update",je)))},[Le,He,s,s==null?void 0:s.state]),w.useLayoutEffect(()=>{var U,W;(W=(U=e.client)==null?void 0:U.product)!=null&&W.primary_color&&n.style.setProperty("--obi-color-primary",e.client.product.primary_color)},[(No=(It=e.client)==null?void 0:It.product)==null?void 0:No.primary_color,n]),w.useEffect(()=>{if(i&&!be&&!fe){if(!r){p("hidden");return}p("start-session")}},[fe,i,be,r]),w.useEffect(()=>{var Xt,ie;$(!1);const U=(Xt=e.client)==null?void 0:Xt.api,W=(ie=e.client)==null?void 0:ie.product;if(!U||!W)return;const pe=(W==null?void 0:W.uuid)??(W==null?void 0:W.product_uuid),je=(W==null?void 0:W.slug)??(W==null?void 0:W.product_slug),ae=(W==null?void 0:W.id)??(W==null?void 0:W.product_id),Se={};if(pe?Se.product_uuid=pe:je?Se.product_slug=je:ae!=null&&(Se.product_id=String(ae)),Object.keys(Se).length===0)return;let Qe=!1;return U.getFeatureFlags(Se).then(Ye=>{if(Qe)return;const Dn=((Ye==null?void 0:Ye.data)??[]).find(Xb=>(Xb==null?void 0:Xb.slug)===KG);if(!Dn)return;const{user_enabled:Zn,product_enabled:Pn,global_enabled:_r}=Dn;let Kb=!!_r;Pn!=null&&(Kb=!!Pn),Zn!=null&&(Kb=!!Zn),$(Kb)}).catch(Ye=>{console.error("[obi-sdk] failed to load AMA feature flag",Ye)}),()=>{Qe=!0}},[(Oo=e.client)==null?void 0:Oo.api,(Mo=e.client)==null?void 0:Mo.product]);const ka=(c==null?void 0:c.stepNames.map((U,W)=>({id:`step-${W+1}`,title:U})))??[],$n=(c==null?void 0:c.currentStep)??null,Qn=!0,Qi=(U,W)=>{s==null||s.say(`Can we jump to the section about ${W.title}?`)};if(be||i&&!r&&!fe)return null;if(h==="hidden")return $i?f.jsx(YG,{label:ft,onClick:()=>{e.updateShowMenu(!0)}}):null;if(h==="start-session"){const U=(Do=e.client)==null?void 0:Do.product,W=(Fl=e.client)==null?void 0:Fl.selectedPlan,pe=i&&!!r,je=i&&!!r||!!((_=e.client)!=null&&_.selectedPlanUuid),ae=(U==null?void 0:U.agent_name)||"Obi",Se=(U==null?void 0:U.assistant_subtitle)||"AI Assistant",Qe=pe?(W==null?void 0:W.description)||(U==null?void 0:U.assistant_description)||(U==null?void 0:U.description)||"I'm here to help you.":(U==null?void 0:U.assistant_description)||(W==null?void 0:W.description)||(U==null?void 0:U.description)||"I'm here to help you.";return f.jsx(GG,{open:!0,onClose:()=>{m(!1),p("hidden")},onStart:()=>{ve.current=je,B(je),m(!0),e.startSession({withMicrophone:!0})},agentName:ae,agentSubtitle:Se,description:Qe,showCloseButton:!1,startLabel:"Start Session",isStarting:b,greetingVideoSrc:Nn})}if(h==="course-selection"){const U=(I=s==null?void 0:s.roomId)==null?void 0:I.startsWith("obs-"),W=((M=e.client)==null?void 0:M.plans)||[],pe=U&&v.length>0,je=pe?v.slice().sort((ie,Ye)=>ie.order!==void 0&&Ye.order!==void 0?ie.order-Ye.order:ie.order!==void 0?-1:Ye.order!==void 0?1:ie.name.localeCompare(Ye.name)).map(ie=>({id:ie.uuid,title:ie.name,description:ie.description||ie.overview||"",status:ie.completed?"completed":"available",duration:typeof ie.duration=="number"?`${ie.duration} min`:ie.duration})):W.map(ie=>{var Ye,bt;return{id:ie.uuid,title:ie.name,description:ie.description,status:(bt=(Ye=e.client)==null?void 0:Ye.planIsCompleted)!=null&&bt[W.indexOf(ie)]?"completed":"available",duration:ie.estimated_duration?`${ie.estimated_duration} min`:void 0}});pe&&ee&&je.push({id:A3,title:"Ask me anything",description:"Ask questions before choosing a course.",status:"available"});const ae=(s==null?void 0:s.languageCodes)||[],Se=(s==null?void 0:s.selectedLanguage)||(s==null?void 0:s.defaultLanguageCode)||null,Qe={audioDevices:En,currentMicrophoneId:(s==null?void 0:s.preferredMicrophoneDeviceId)||null,isMicrophoneEnabled:!S&&((s==null?void 0:s.isMicShared)??!1),isScreenShareActive:ht,widgetState:y?"chat":null,canPublishData:!0,browserSupportsScreenSharing:Le,onMicDeviceSelect:async ie=>{e.client&&(e.client.preferredMicrophoneDeviceId=ie),s&&ie&&await s.switchMicrophoneDevice(ie),nn()},onMicToggle:async()=>{s!=null&&s.isMicShared?S?(s.unmuteMicrophone(),g(!1)):(s.muteMicrophone(),g(!0)):await(s==null?void 0:s.shareMicrophone())},onChatToggle:()=>{x(!y)},onLeave:()=>{s==null||s.stop()},onScreenShareToggle:Jn,languages:ae,selectedLanguage:Se,defaultLanguageCode:s==null?void 0:s.defaultLanguageCode,isMultilingual:(s==null?void 0:s.isMultilingual)??!1,onLanguageChange:ie=>{s==null||s.setLanguage(ie)},isLanguageSelectorEnabled:!0,...y?{screenShareButtonVariant:"compact"}:{}},Xt=y?f.jsx(k3,{messages:(s==null?void 0:s.chatMessages)??[],localIdentity:((ge=s==null?void 0:s.room)==null?void 0:ge.localParticipant.identity)??(typeof(s==null?void 0:s.identity)=="string"?s.identity:null),onSend:async ie=>{var Ye,bt,Dn,Zn;if(s){const Pn=Date.now();s.appendChatMessage({timestamp:Pn,message:ie,from:{identity:((bt=(Ye=s.room)==null?void 0:Ye.localParticipant)==null?void 0:bt.identity)??null,name:((Zn=(Dn=s.room)==null?void 0:Dn.localParticipant)==null?void 0:Zn.name)??null},isAgent:!1}),await s.say(ie)}},onClose:()=>x(!1)}):void 0;return f.jsx(R3,{open:!0,onClose:()=>s==null?void 0:s.stop(),courses:je,controlBarProps:Qe,coursePanelProps:{selectedCourseIds:T?[T]:void 0,onCourseToggle:async ie=>{var Ye,bt,Dn,Zn;if(pe){if(ie===A3){try{await((Ye=s==null?void 0:s.startAma)==null?void 0:Ye.call(s))}catch(_r){console.error("[obi-sdk] failed to start AMA course",_r)}return}const Pn=v.find(_r=>_r.uuid===ie);if(Pn){C(ie);try{await((bt=s==null?void 0:s.say)==null?void 0:bt.call(s,`I'd like to take the ${Pn.name} course.`))}catch(_r){console.error("[obi-sdk] failed to send course selection",_r),C(null)}}}else{const Pn=W.find(_r=>_r.uuid===ie);if(Pn){(Dn=e.client)==null||Dn.selectPlan(Pn),p("pip");try{await((Zn=s==null?void 0:s.say)==null?void 0:Zn.call(s,`I'd like to take the ${Pn.name} course.`))}catch(_r){console.error("[obi-sdk] failed to send course selection",_r),p("course-selection")}}}}},rightPanel:Xt,avatarImageSrc:tn,avatarAudioPower:qt,avatarStatus:At,captionsText:Te})}if(h==="course-outline"){const U=(s==null?void 0:s.languageCodes)||[],W=(s==null?void 0:s.selectedLanguage)||(s==null?void 0:s.defaultLanguageCode)||null,pe={audioDevices:En,currentMicrophoneId:(s==null?void 0:s.preferredMicrophoneDeviceId)||null,isMicrophoneEnabled:!S&&((s==null?void 0:s.isMicShared)??!1),isScreenShareActive:ht,widgetState:y?"chat":null,canPublishData:!0,browserSupportsScreenSharing:Le,onMicDeviceSelect:async ie=>{e.client&&(e.client.preferredMicrophoneDeviceId=ie),s&&ie&&await s.switchMicrophoneDevice(ie),nn()},onMicToggle:async()=>{s!=null&&s.isMicShared?S?(s.unmuteMicrophone(),g(!1)):(s.muteMicrophone(),g(!0)):await(s==null?void 0:s.shareMicrophone())},onChatToggle:()=>{x(!y)},onLeave:()=>{s==null||s.stop()},onScreenShareToggle:Jn,languages:U,selectedLanguage:W,defaultLanguageCode:s==null?void 0:s.defaultLanguageCode,isMultilingual:(s==null?void 0:s.isMultilingual)??!1,onLanguageChange:ie=>{s==null||s.setLanguage(ie)},isLanguageSelectorEnabled:!0,...y?{screenShareButtonVariant:"compact"}:{}},je=y?f.jsx(k3,{messages:(s==null?void 0:s.chatMessages)??[],localIdentity:((Ie=s==null?void 0:s.room)==null?void 0:Ie.localParticipant.identity)??(typeof(s==null?void 0:s.identity)=="string"?s.identity:null),onSend:async ie=>{var Ye,bt,Dn,Zn;if(s){const Pn=Date.now();s.appendChatMessage({timestamp:Pn,message:ie,from:{identity:((bt=(Ye=s.room)==null?void 0:Ye.localParticipant)==null?void 0:bt.identity)??null,name:((Zn=(Dn=s.room)==null?void 0:Dn.localParticipant)==null?void 0:Zn.name)??null},isAgent:!1}),await s.say(ie)}},onClose:()=>x(!1)}):void 0,ae=!!c,Se=!ue,Qe=async()=>{if(!(!(s!=null&&s.endCourse)||z)){Y(!0);try{await s.endCourse()}catch(ie){console.error("[obi-sdk] failed to end course",ie),Y(!1)}}},Xt=f.jsx(gV,{steps:ka,currentStep:$n,hideTrailingConclusionStep:Qn,onStepClick:Qi,showBackToCourses:Se,...Se?{onBackToCoursesConfirm:Qe,backToCoursesDisabled:z}:{}});return f.jsx(R3,{open:!0,onClose:()=>s==null?void 0:s.stop(),courses:[],controlBarProps:pe,middlePanel:Xt,rightPanel:je,isCourseOutlineOpen:ae,onReturnToPiP:ae?()=>p("pip"):void 0,avatarImageSrc:tn,avatarAudioPower:qt,avatarStatus:At,captionsText:Te})}if(h==="pip"){const U=(s==null?void 0:s.languageCodes)||[],W=(s==null?void 0:s.selectedLanguage)||(s==null?void 0:s.defaultLanguageCode)||null,pe=280,je=250,ae=16,Se={x:window.innerWidth-pe-ae,y:window.innerHeight-je-ae},Qe={isMicrophoneEnabled:!S&&((s==null?void 0:s.isMicShared)??!1),isChatOpen:y,isScreenShareActive:ht,onMicToggle:async()=>{s!=null&&s.isMicShared?S?(s.unmuteMicrophone(),g(!1)):(s.muteMicrophone(),g(!0)):await(s==null?void 0:s.shareMicrophone())},onChatToggle:()=>x(ie=>!ie),onScreenShareToggle:Jn,onLeave:()=>{s==null||s.stop()},languages:U,selectedLanguage:W,defaultLanguageCode:s==null?void 0:s.defaultLanguageCode,isMultilingual:(s==null?void 0:s.isMultilingual)??!1,onLanguageChange:ie=>{s==null||s.setLanguage(ie)},isLanguageSelectorEnabled:!0},Xt=y?f.jsx(BV,{messages:(s==null?void 0:s.chatMessages)??[],localIdentity:((ye=s==null?void 0:s.room)==null?void 0:ye.localParticipant.identity)??(typeof(s==null?void 0:s.identity)=="string"?s.identity:null),onSend:async ie=>{var Ye,bt,Dn,Zn;if(s){const Pn=Date.now();s.appendChatMessage({timestamp:Pn,message:ie,from:{identity:((bt=(Ye=s.room)==null?void 0:Ye.localParticipant)==null?void 0:bt.identity)??null,name:((Zn=(Dn=s.room)==null?void 0:Dn.localParticipant)==null?void 0:Zn.name)??null},isAgent:!1}),await s.say(ie)}},testId:"pip-chat-panel"}):void 0;return f.jsx(Zq,{initialPosition:Se,onExit:()=>{j.current=!1,p("course-outline")},controlBarProps:Qe,isCourseOutlineSelected:N&&!!c,onCourseOutlineToggle:c?()=>{O(ie=>!ie)}:void 0,isCaptionsEnabled:Z,onCaptionsToggle:()=>q(ie=>!ie),courseOutline:c?{steps:ka,currentStep:$n,onStepClick:Qi,hideTrailingConclusionStep:Qn}:void 0,messagesPanel:Xt,avatarFallbackProps:{audioPower:qt,imageSrc:tn,status:At,captionsText:Te},screenshotUrl:P,cameraShotTrigger:L})}return null}function JG(t){var l,c;const{sdk:e,session:n,isBlacklisted:i}=t;if(i)return!1;const r=e.client;if(!r||r.state!=="ready"||(n??r.session??null))return!1;let o=e.isActive;return((l=r.product)==null?void 0:l.name)==="Canibuild"&&(o=!0),!(!o||(e.widgetDisplay??((c=r.product)==null?void 0:c.widget_display))==="invisible")}function N3(t,e){if(!t)return;const n=`obi-widget-course-progress-${t}`;if(e===null){localStorage.removeItem(n);return}try{const i={...e,timestamp:Date.now()};localStorage.setItem(n,JSON.stringify(i))}catch(i){console.error("[obi-sdk] failed to save course progress",i)}}function $G(t){if(!t)return null;const e=`obi-widget-course-progress-${t}`;try{const n=localStorage.getItem(e);if(!n)return null;const i=JSON.parse(n);if(typeof i.currentStep!="number"||typeof i.totalSteps!="number"||!Array.isArray(i.stepNames))return console.warn("[obi-sdk] invalid course progress data, clearing",i),localStorage.removeItem(e),null;const r=24*60*60*1e3;return i.timestamp&&Date.now()-i.timestamp>r?(localStorage.removeItem(e),null):{currentStep:i.currentStep,totalSteps:i.totalSteps,stepNames:i.stepNames}}catch(n){return console.error("[obi-sdk] failed to load course progress",n),localStorage.removeItem(e),null}}function O3(t){if(!t)return;const e=`obi-widget-course-progress-${t}`;try{localStorage.removeItem(e)}catch(n){console.error("[obi-sdk] failed to clear course progress",n)}}function QG(t){const[e,n]=w.useState(()=>fs(t));return w.useEffect(()=>{n(fs(t))},[t]),w.useEffect(()=>{const i=()=>{n(fs(t))};return window.addEventListener("popstate",i),window.addEventListener("hashchange",i),()=>{window.removeEventListener("popstate",i),window.removeEventListener("hashchange",i)}},[t]),e}function ZG(t){const[e,n]=w.useState(0),i=w.useRef(null),r=w.useRef(0),a=w.useRef(0);return w.useEffect(()=>{if(!t){n(0),r.current=0,a.current=0;return}const o=()=>{const s=t.audioSpectrum();let l=0;if(s&&s.length>0){let b=0;for(let m=0;m<s.length;m++)b+=s[m];l=Math.min(1,Math.max(0,b/s.length))}const c=r.current,d=l>=c?.7:.15,h=c*d+l*(1-d);r.current=h;const p=h<.05?0:Math.min(1,h);Math.abs(p-a.current)>.01&&(a.current=p,n(p)),i.current=requestAnimationFrame(o)};return i.current=requestAnimationFrame(o),()=>{i.current&&cancelAnimationFrame(i.current)}},[t]),e}function eW(){const[t,e]=w.useState({audioDevices:[]});return w.useEffect(()=>{var i;if(typeof navigator>"u"||!((i=navigator.mediaDevices)!=null&&i.enumerateDevices))return;const n=()=>{navigator.mediaDevices.enumerateDevices().then(r=>{e({audioDevices:r.filter(a=>a.kind==="audioinput")})})};return n(),navigator.mediaDevices.addEventListener("devicechange",n),()=>navigator.mediaDevices.removeEventListener("devicechange",n)},[]),t}function M3(){const t=window.location.hostname;return t.endsWith(".getcor.ai")||t.endsWith(".getcor.io")||t==="getcor.ai"||t==="getcor.io"||t==="localhost"||t==="127.0.0.1"||t==="::1"}const D3=M3();function tW(t){if(document.querySelector("#obi-host")||document.querySelector("obi-widget"))return;nW();const e=document.createElement("div");e.id="obi-host",e.style.position="fixed",e.style.zIndex="9999",document.body.appendChild(e);const n=e.attachShadow({mode:"open"}),i=document.createElement("div");i.id="obi-container",n.appendChild(i);const r=new CSSStyleSheet;r.replaceSync(TB);const a=[r];if(D3){const s=new CSSStyleSheet;s.replaceSync(xB),a.push(s);const l=new CSSStyleSheet;l.replaceSync(kB),a.push(l)}else{const s=new CSSStyleSheet;s.replaceSync(SB),a.push(s)}n.adoptedStyleSheets=a;const o=_B.createRoot(i);D3?o.render(f.jsx(XG,{sdk:t,shadowHost:e})):o.render(f.jsx(EB,{sdk:t,shadowHost:e})),console.log("[obi-sdk] widget mounted")}function nW(){P3("https://fonts.cdnfonts.com/css/satoshi"),P3("https://fonts.googleapis.com/css2?family=Inter:ital,opsz,wght@0,14..32,100..900;1,14..32,100..900&display=swap")}function P3(t){const e=document.createElement("link");e.href=t,e.rel="stylesheet",document.head.appendChild(e)}const L3="49206C6F7665204F6269_session",I3="obi-url-params",Yb="obi-client-heartbeat",iW=5e3,j3=4e4,B3=15e3;function rW(){return M3()?"meet":"sdk"}class aW extends _p{constructor(e){super(),this.client=null,this.isActive=!1,this.primaryColour="#9500FF",this.passivePlanUuid=null,this.commandLog=[],this.commandQueue=[],this._resumed=!1,this.heartbeatInterval=null,this.dispatchCommand=(n,i)=>{var r,a,o,s,l;switch(this.commandLog.push({commandType:n,args:i}),n){case"update":this.updateConfig(i);break;case"startSession":{if(i!=null&&i.planUuid){const c=(((r=this.client)==null?void 0:r.plans)||[]).find(u=>u.uuid===i.planUuid)||null;if(!c){console.warn("[obi] startSession command requires a valid planUuid",i);return}(o=(a=this.client)==null?void 0:a.selectPlan)==null||o.call(a,c)}this.updateActive(!0);break}case"stopSession":(l=(s=this.client)==null?void 0:s.stopSession)==null||l.call(s);break;case"say":this.say(i);break;default:console.warn("[obi] unknown command",{commandType:n,args:i})}},e&&this.createClient(e),this.parsePassiveParams()}async createClient(e){if(this.client){this.client.appToken!==e&&console.warn("[obi] client already exists with different app token");return}let n=null;const i=rW(),r=this.load();if(r)try{const a=this.parsePersistedSessionMetadata(r),o=a&&this.isPersistedSessionStale(a);o!=null&&o.stale&&a?(this.trackStaleSessionDiscard(a.sessionUuid,o.ageMs,o.reason),this.clearCachedClient()):(n=bh.deserialise(r,e,i,{apiBaseUrl:"https://staging.coragents.ai",captureScreen:this.captureScreen.bind(this)}),n?this._resumed=!0:this.clearCachedClient())}catch(a){console.error("[obi] error loading cached client",a),this.clearCachedClient()}n||(n=new bh(e,i,{apiBaseUrl:"https://staging.coragents.ai",captureScreen:this.captureScreen.bind(this)})),this.client=n,this.client.session&&this.startHeartbeat(this.client.session.sessionUuid),this.client.on("stateChanged",a=>{var o,s,l,c,u,d,h,p,b,m;a==="ready"&&this.updateConfig({isActive:((o=window==null?void 0:window.obiWidgetConfig)==null?void 0:o.isActive)??((s=this.client)==null?void 0:s.showWidget),primaryColour:((c=(l=this.client)==null?void 0:l.product)==null?void 0:c.primary_color)||"#9500FF",widgetDisplay:((u=window==null?void 0:window.obiWidgetConfig)==null?void 0:u.widgetDisplay)||((h=(d=this.client)==null?void 0:d.product)==null?void 0:h.widget_display)||"regular",completedWidgetDisplay:((p=window==null?void 0:window.obiWidgetConfig)==null?void 0:p.completedWidgetDisplay)||((m=(b=this.client)==null?void 0:b.product)==null?void 0:m.completed_widget_display)||"regular"})}),this.client.on("sessionStarted",()=>{var a,o;this.save(),this.startHeartbeat(((o=(a=this.client)==null?void 0:a.session)==null?void 0:o.sessionUuid)||null),this.passivePlanUuid=null}),this.client.on("sessionStopped",()=>{this.clearCachedClient(),this.passivePlanUuid=null}),this.client.on("sessionShutdown",()=>{this.clearCachedClient()}),this.client.on("trackEvent",(a,o)=>{}),this.client.session&&(this.client.session.isPaused,this.client.resumeSession(a=>{a.on("stateChanged",o=>{o!=="disconnecting"&&o!=="disconnected"&&o!=="error"&&o!=="connecting"&&this.save()}),a.on("paused",()=>{this.save()}),a.on("unpaused",()=>{this.save()})}))}_maybeActOnServerEngagement(){var s;const e=this.client;if(!e||e.state!=="ready")return;const n=e.product,i=(s=e.engagement)==null?void 0:s.style;if(!i||n&&fs(n.widget_url_blacklist||[])||!e.showWidget)return;const r=e.plans||[],a=e.planIsCompleted||[],o=r.length>0&&a.filter(Boolean).length===r.length;if(!(r.length===0||o)){if(i==="modal"){const l=a.findIndex(u=>!u),c=l>=0?r[l]:null;c&&e.selectPlan(c)}else i==="popover"&&setTimeout(()=>{this.showMessage("Don't forget to complete your onboarding",{autoCloseMs:1e4})},1e3);try{ta().track("engagement-prompt-shown",{style:i})}catch{}}}async initialise(e={}){var n;this.commandQueue=e.queuedCommands||[],this._resumed?(this._resumed=!1,this.dispatchCommandQueue()):this.client?this.client.initialise({planUuid:this.passivePlanUuid||void 0,identity:((n=window==null?void 0:window.obiWidgetConfig)==null?void 0:n.user)||void 0}).then(()=>{this.emit("initialised");try{this._maybeActOnServerEngagement()}catch{}this.dispatchCommandQueue()}).catch(i=>{console.error("[obi] error initialising client",i),this.emit("error",i)}):this.dispatchCommandQueue()}async updateConfig(e){await this.updateAppToken(e.apiKey),this.updateActive(e.isActive),this.updatePrimaryColour(e.primaryColour),this.updateWidgetDisplay(e.widgetDisplay),this.updateCompletedWidgetDisplay(e.completedWidgetDisplay),this.updateWidgetPosition(e.widgetPosition),await this.updateIdentity(e.user),this.updateShowMenu(e.showMenu),this.emit("configUpdated")}async updateAppToken(e){var n;e===void 0||e==((n=this.client)==null?void 0:n.appToken)||(this.passivePlanUuid,await this.createClient(e),this.client&&await this.client.initialise({planUuid:this.passivePlanUuid||void 0}).then(()=>{this.emit("initialised");try{this._maybeActOnServerEngagement()}catch{}}).catch(i=>{console.error("[obi] error initialising client",i),this.emit("error",i)}))}updateActive(e){e===void 0||e==this.isActive||(this.isActive=e)}updatePrimaryColour(e){e===void 0||e==this.primaryColour||(this.primaryColour=e)}updateWidgetDisplay(e){e===void 0||e==this.widgetDisplay||(this.widgetDisplay=e)}updateCompletedWidgetDisplay(e){e===void 0||e==this.completedWidgetDisplay||(this.completedWidgetDisplay=e)}updateWidgetPosition(e){e===void 0||e==this.widgetPosition||(this.widgetPosition=e)}async updateIdentity(e){var i,r;if(e===void 0||e==((i=this.client)==null?void 0:i.identity))return;(r=this.client)==null||r.identity;let n=e?{...e,extra:{...e,...(e==null?void 0:e.extra)||{}}}:void 0;await this.client.initialise({identity:n,planUuid:this.passivePlanUuid||void 0}).then(()=>{this.emit("initialised");try{this._maybeActOnServerEngagement()}catch{}}).catch(a=>{console.error("[obi] error initialising client",a),this.emit("error",a)}),e!=null&&e.email&&ta().identify((e==null?void 0:e.email)||"",n)}updateShowMenu(e){e!==void 0&&this.emit("showMenu",e)}async say(e){var n,i,r;await((r=(i=(n=this.client)==null?void 0:n.session)==null?void 0:i.say)==null?void 0:r.call(i,e))}async startSession(e){await this.client.startSession(this.client.selectedPlanUuid||null,n=>{n.on("stateChanged",i=>{i!=="disconnecting"&&i!=="disconnected"&&i!=="error"&&i!=="connecting"&&this.save()}),n.on("paused",()=>{this.save()}),n.on("unpaused",()=>{this.save()})},e)}dispatchCommandQueue(){const e=this.commandQueue;this.commandQueue=[],e.forEach(n=>{try{this.dispatchCommand(n[0],n[1]||[])}catch(i){console.error("[obi] error dispatching command",i)}})}parsePassiveParams(){if(this.passivePlanUuid){this.passivePlanUuid;return}let e={};e=JSON.parse(localStorage.getItem(I3)||"{}"),Object.keys(e).length===0&&new URLSearchParams(window.location.search).forEach((a,o)=>{e[o]=a});const n=e[L3];if(!n)return null;const i=new URL(window.location.href);i.searchParams.delete(L3),window.history.replaceState({},"",i.toString()),i.toString(),localStorage.removeItem(I3),this.passivePlanUuid=n}mountWidget(){tW(this)}showMessage(e,n){try{this.emit("showMessage",{text:e,autoCloseMs:n==null?void 0:n.autoCloseMs})}catch{}}async captureScreen(){try{await fO(async()=>(this.graphemes||(this.graphemes=await this.client.api.getGraphemes()),this.graphemes.data.text_segmentation)),await sR(async()=>(this.graphemes||(this.graphemes=await this.client.api.getGraphemes()),this.graphemes.data.css_line_breaks))}catch(e){throw console.error("[obi] error initialising unicode trie",e),e}try{return(await GN(document.documentElement,{useCORS:!0,allowTaint:!0,foreignObjectRendering:!0})).toDataURL("image/png")}catch(e){throw console.error("[obi] error capturing screen",e),e}}save(){var n;const e=((n=this.client)==null?void 0:n.serialise())||"";localStorage.setItem("obi-client",e)}load(){return localStorage.getItem("obi-client")}parsePersistedSessionMetadata(e){const n=JSON.parse(e),i=this.parseTimestampMs(n.serialisedAt);if(!n.session)return null;let r=null;if(typeof n.session=="string")try{r=JSON.parse(n.session)}catch{return null}else typeof n.session=="object"&&(r=n.session);return r?{sessionUuid:typeof r.sessionUuid=="string"?r.sessionUuid:null,startedAtMs:this.parseTimestampMs(r.startedAt),serialisedAtMs:i}:null}isPersistedSessionStale(e){const n=Date.now(),i=this.readHeartbeat();if(i&&i.sessionUuid&&e.sessionUuid&&i.sessionUuid===e.sessionUuid){const s=Math.max(0,n-i.updatedAtMs);return{stale:s>j3,reason:s>j3?"heartbeat-stale":"heartbeat-fresh",ageMs:s}}const r=[e.serialisedAtMs,e.startedAtMs].filter(s=>typeof s=="number"&&Number.isFinite(s));if(r.length===0)return{stale:!0,reason:"fallback-missing-timestamps",ageMs:null};const a=Math.max(...r),o=Math.max(0,n-a);return{stale:o>B3,reason:o>B3?"fallback-too-old":"fallback-recent",ageMs:o}}parseTimestampMs(e){if(typeof e=="number")return e;if(typeof e=="string"){const n=Number(e);if(!Number.isNaN(n))return n;const i=Date.parse(e);return Number.isFinite(i)?i:null}return null}readHeartbeat(){const e=localStorage.getItem(Yb);if(!e)return null;try{return JSON.parse(e)}catch{return null}}trackStaleSessionDiscard(e,n,i){try{ta().track("stale-session-discarded",{sessionUuid:e||void 0,ageMs:n??void 0,reason:i})}catch{}}startHeartbeat(e){if(!e){this.clearHeartbeat();return}this.stopHeartbeat(),this.writeHeartbeat(e),this.heartbeatInterval=setInterval(()=>{this.writeHeartbeat(e)},iW)}stopHeartbeat(){this.heartbeatInterval&&(clearInterval(this.heartbeatInterval),this.heartbeatInterval=null)}writeHeartbeat(e){const n={sessionUuid:e,updatedAtMs:Date.now()};localStorage.setItem(Yb,JSON.stringify(n))}clearHeartbeat(){this.stopHeartbeat(),localStorage.removeItem(Yb)}clearCachedClient(){this.clearHeartbeat(),localStorage.removeItem("obi-client")}}async function U3(t,e){let n;try{n=window}catch{console.warn("[obi] no window object found"),n={}}return oW({appToken:t,window:n,init:e})}async function oW({appToken:t,window:e,init:n}){var a,o;if(e.obi){console.warn("[obi] obi object already found on window, skipping");return}n&&n(),t||(t=(a=e==null?void 0:e.obiWidgetConfig)==null?void 0:a.apiKey);let i;try{i=((o=e.ObiSDK)==null?void 0:o.q)||[]}catch{i=[]}const r=new aW(t);return e.ObiSDK=r.dispatchCommand,await r.initialise({queuedCommands:i}),e.obi=r,r.mountWidget(),r}function z3(){}document.readyState==="loading"?document.addEventListener("DOMContentLoaded",()=>{U3(void 0,z3)}):U3(void 0,z3)})();
133
+ `);for(let s=i;s<o.length;s++){const l=o[s];if(l.length>1024)continue;const c=w3.test(l)?l.replace(w3,"$1"):l;if(!c.match(/\S*Error: /)){for(const u of e){const d=u(c);if(d){a.push(d);break}}if(a.length>=T3+r)break}}return NG(a.slice(r))}}function NG(t){if(!t.length)return[];const e=Array.from(t);return/sentryWrapped/.test(gp(e).function||"")&&e.pop(),e.reverse(),C3.test(gp(e).function||"")&&(e.pop(),C3.test(gp(e).function||"")&&e.pop()),e.slice(0,T3).map(n=>({...n,filename:n.filename||gp(e).filename,function:n.function||Il}))}function gp(t){return t[t.length-1]||{}}typeof __SENTRY_DEBUG__>"u"||__SENTRY_DEBUG__;const OG=30,MG=50;function Gb(t,e,n,i){const r={filename:t,function:e==="<anonymous>"?Il:e,in_app:!0};return n!==void 0&&(r.lineno=n),i!==void 0&&(r.colno=i),r}const DG=/^\s*at (\S+?)(?::(\d+))(?::(\d+))\s*$/i,PG=/^\s*at (?:(.+?\)(?: \[.+\])?|.*?) ?\((?:address at )?)?(?:async )?((?:<anonymous>|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,LG=/\((\S*)(?::(\d+))(?::(\d+))\)/,IG=t=>{const e=DG.exec(t);if(e){const[,i,r,a]=e;return Gb(i,Il,+r,+a)}const n=PG.exec(t);if(n){if(n[2]&&n[2].indexOf("eval")===0){const a=LG.exec(n[2]);a&&(n[2]=a[1],n[3]=a[2],n[4]=a[3])}const[i,r]=E3(n[1]||Il,n[2]);return Gb(r,i,n[3]?+n[3]:void 0,n[4]?+n[4]:void 0)}},jG=[OG,IG],BG=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:[-a-z]+)?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i,UG=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i;AG(...[jG,[MG,t=>{const e=BG.exec(t);if(e){if(e[3]&&e[3].indexOf(" > eval")>-1){const r=UG.exec(e[3]);r&&(e[1]=e[1]||"eval",e[3]=r[1],e[4]=r[2],e[5]="")}let n=e[3],i=e[1]||Il;return[i,n]=E3(i,n),Gb(n,i,e[4]?+e[4]:void 0,e[5]?+e[5]:void 0)}}]]);const E3=(t,e)=>{const n=t.indexOf("safari-extension")!==-1,i=t.indexOf("safari-web-extension")!==-1;return n||i?[t.indexOf("@")!==-1?t.split("@")[0]:Il,n?`safari-extension:${e}`:`safari-web-extension:${e}`]:[t,e]};typeof __SENTRY_DEBUG__>"u"||__SENTRY_DEBUG__;const Ji={shell:"_shell_8bsnr_1",layout:"_layout_8bsnr_11",layoutThree:"_layoutThree_8bsnr_23",leftPanel:"_leftPanel_8bsnr_27",middlePanel:"_middlePanel_8bsnr_36",rightPanel:"_rightPanel_8bsnr_37",videoFrame:"_videoFrame_8bsnr_41",captions:"_captions_8bsnr_52",controls:"_controls_8bsnr_58",coursePanel:"_coursePanel_8bsnr_71",returnToPiPOverlay:"_returnToPiPOverlay_8bsnr_82",returnToPiPButton:"_returnToPiPButton_8bsnr_94"};function Wb(...t){return t.filter(Boolean).join(" ")}function zG(t){const{captionsText:e,avatarAudioPower:n=0,avatarImageSrc:i,avatarAriaLabel:r,avatarStatus:a,controlBarProps:o,courses:s,coursePanelProps:l,middlePanel:c,rightPanel:u,isCourseOutlineOpen:d,onReturnToPiP:h,className:p}=t;return f.jsx("div",{className:Wb(Ji.shell,p),"data-testid":"course-dialog-content",children:f.jsxs("div",{className:Wb(Ji.layout,u?Ji.layoutThree:null),children:[f.jsxs("div",{className:Ji.leftPanel,children:[f.jsxs("div",{className:Ji.videoFrame,children:[d&&h&&f.jsx("div",{className:Ji.returnToPiPOverlay,children:f.jsx("button",{type:"button",className:Ji.returnToPiPButton,onClick:h,"aria-label":"Return to PiP","data-testid":"course-return-to-pip",children:f.jsx(jB,{size:14})})}),f.jsx(rH,{className:Ji.captions,text:e,children:f.jsx(p3,{audioPower:n,size:"lg",background:"flat",imageSrc:i,ariaLabel:r??"Agent avatar placeholder",status:a})})]}),f.jsx("div",{className:Ji.controls,children:f.jsx(NF,{...o})})]}),u?f.jsx("div",{className:Ji.rightPanel,"data-testid":"course-dialog-right-panel",children:u}):null,f.jsx("div",{className:Ji.middlePanel,"data-testid":"course-dialog-middle-panel",children:c??f.jsx(LH,{...l,courses:s,className:Wb(Ji.coursePanel,l==null?void 0:l.className)})})]})})}function R3(t){const{open:e,onClose:n,dialogProps:i,...r}=t;return f.jsx(IE,{open:e,onClose:n,variant:"ghost",...i,children:f.jsx(zG,{...r})})}const FG=80,qG=500,HG=1e3;function VG(t,e){const{delayMs:n=0}=e??{},r=t.filter(m=>{var g;const S=(g=m.participantInfo)==null?void 0:g.identity;return(S==null?void 0:S.startsWith("agent-"))??!1}).map(m=>m.text??"").join(" ").trim(),[a,o]=w.useState(""),[s,l]=w.useState(!1),c=w.useRef(""),u=w.useRef(null),d=w.useRef(null),h=w.useRef(null),p=m=>{h.current&&(clearTimeout(h.current),h.current=null),n>0?h.current=setTimeout(()=>{o(m)},n):o(m)},b=(m,S)=>m.startsWith(S)?m.slice(S.length).trim():m.trim();return w.useEffect(()=>{if(d.current&&(clearTimeout(d.current),d.current=null),s)return;const m=b(r,c.current);p(m),m.length>FG?(l(!0),u.current=setTimeout(()=>{l(!1),c.current=r},qG+n)):m.length>0&&(d.current=setTimeout(()=>{c.current=r,p("")},HG+n))},[r,s,n]),w.useEffect(()=>()=>{u.current&&clearTimeout(u.current),d.current&&clearTimeout(d.current),h.current&&clearTimeout(h.current)},[]),{caption:a,hasCaption:a.length>0}}const yr={layout:"_layout_k1q6c_1",left:"_left_k1q6c_10",copy:"_copy_k1q6c_17",description:"_description_k1q6c_25",descriptionScroller:"_descriptionScroller_k1q6c_31",cta:"_cta_k1q6c_36",disclaimer:"_disclaimer_k1q6c_43",right:"_right_k1q6c_47",mediaPanel:"_mediaPanel_k1q6c_56",agentStill:"_agentStill_k1q6c_63",dialogWithSmallClose:"_dialogWithSmallClose_k1q6c_88"};function GG(t){const{open:e,onClose:n,onStart:i,agentName:r,agentSubtitle:a,description:o,startLabel:s="Start Now",disclaimer:l="Sessions are securely recorded for quality improvement purposes.",showCloseButton:c=!1,isStarting:u=!1,greetingVideoSrc:d}=t;return f.jsx(IE,{open:e,onClose:n,size:"large",showCloseButton:c,className:yr.dialogWithSmallClose,children:f.jsxs("div",{className:yr.layout,children:[f.jsxs("div",{className:yr.left,children:[f.jsxs("div",{className:yr.copy,children:[f.jsx(pi,{variant:"heading",children:r}),f.jsx(pi,{variant:"subheading",children:a}),f.jsx(pi,{variant:"muted",as:"div",className:yr.description,children:f.jsx(Dl,{className:yr.descriptionScroller,children:f.jsx(Kz,{content:o})})})]}),f.jsxs("div",{className:yr.cta,children:[f.jsx(ps,{type:"button",size:"lg",fullWidth:!0,onClick:i,isLoading:u,children:s}),f.jsx(pi,{variant:"subscript",as:"p",className:yr.disclaimer,children:l})]})]}),f.jsx(SG,{showAboveWidth:"md",children:f.jsx("div",{className:yr.right,children:f.jsx(Lu,{className:yr.mediaPanel,children:f.jsx(RG,{agentName:r,greetingVideoSrc:d,className:yr.agentStill})})})})]})})}const WG={launcherPill:"_launcherPill_1fhyr_1"};function YG(t){const{label:e,onClick:n}=t;return f.jsx("button",{type:"button",className:WG.launcherPill,onClick:n,"data-testid":"ai-coach-pill",children:e})}const A3="__ama_course__",KG="ama_course";function XG(t){var gi,jl,Bl,Ee,Mn,Ul,To,qr,wo,Co,zl,pn,mn,Eo,Ro,Hr,Ao,It,No,Oo,Mo,Do,Fl,_,I,M,ge,Ie,ye;const{sdk:e,shadowHost:n}=t,i=!!e.passivePlanUuid,r=i?((gi=e.client)==null?void 0:gi.selectedPlanUuid)??null:null,a=((jl=e.client)==null?void 0:jl.session)??null,o=!!a&&(i&&!!r||!!((Bl=e.client)!=null&&Bl.selectedPlanUuid)),[s,l]=w.useState(()=>a),[c,u]=w.useState(()=>a!=null&&a.sessionUuid?$G(a.sessionUuid):null),d=(()=>{var U;return a?((U=a.roomId)==null?void 0:U.startsWith("obs-"))&&!c?"course-selection":"pip":r?"start-session":"hidden"})(),[h,p]=w.useState(()=>d),[b,m]=w.useState(!1),[S,g]=w.useState(!1),[y,x]=w.useState(!1),[v,k]=w.useState([]),[T,C]=w.useState(null),[R,A]=w.useState(0),[N,O]=w.useState(!1),[z,Y]=w.useState(!1),[L,X]=w.useState(0),[P,G]=w.useState(null),[J,te]=w.useState([]),[Z,q]=w.useState(!1),[ee,$]=w.useState(!1),[ue,B]=w.useState(()=>o),ve=w.useRef(o),j=w.useRef(!1),me=()=>{p(U=>{const W=U==="course-selection",pe=U==="course-outline"&&j.current;return W||pe?(j.current=!1,O(!1),"pip"):U})},be=QG((Mn=(Ee=e.client)==null?void 0:Ee.product)==null?void 0:Mn.widget_url_blacklist),qt=ZG(s),{audioDevices:En}=eW();w.useEffect(()=>{s!=null&&s.sessionUuid&&N3(s.sessionUuid,c)},[c,s==null?void 0:s.sessionUuid]);const{caption:Te}=VG(J,{delayMs:0}),Le=typeof navigator<"u"&&!!((Ul=navigator.mediaDevices)!=null&&Ul.getDisplayMedia),ht=((qr=(To=s==null?void 0:s.room)==null?void 0:To.localParticipant)==null?void 0:qr.isScreenShareEnabled)??!1,lt=U=>{var Se;const W=((Se=e.client)==null?void 0:Se.identity)??U.identity,pe=typeof(W==null?void 0:W.first_name)=="string"?W.first_name.trim():"",je=typeof(W==null?void 0:W.last_name)=="string"?W.last_name.trim():"",ae=typeof(W==null?void 0:W.email)=="string"&&W.email.trim().length>0?W.email.trim():"";return{firstName:pe,lastName:je,email:ae}},hn=U=>{const{firstName:W,lastName:pe,email:je}=lt(U),ae=[W,pe,je].map(Qe=>Qe.trim());return ae.some(Qe=>Qe.length>0)?ae.join(":"):""},fn=U=>{const{firstName:W,lastName:pe,email:je}=lt(U),ae=[W,pe].filter(Boolean).join(" ").trim();return{name:ae.length>0?ae:void 0,email:je.length>0?je:void 0,screenShareSupported:Le}},At=(()=>{if(s!=null&&s.speakingState){if(s.speakingState==="thinking")return"thinking";if(s.speakingState==="busy")return"searching"}})(),tn=((Co=(wo=e.client)==null?void 0:wo.product)==null?void 0:Co.avatar_image_url)||((pn=(zl=e.client)==null?void 0:zl.product)==null?void 0:pn.logo_url)||void 0,Nn=((Eo=(mn=e.client)==null?void 0:mn.product)==null?void 0:Eo.greeting_video_url)||void 0,Ri=JG({sdk:e,session:s,isBlacklisted:be}),$i=!i&&Ri,fe=!!(s??((Ro=e.client)==null?void 0:Ro.session)??null),He=(s==null?void 0:s.clientType)==="meet"?hn(s):"",we=(Ao=(Hr=e.client)==null?void 0:Hr.product)==null?void 0:Ao.assistant_subtitle,ft=typeof we=="string"&&we.trim().length>0?we:"AI Coach",nn=()=>A(U=>U+1),Jn=async()=>{var W,pe;if(!s)return;const U=((pe=(W=s.room)==null?void 0:W.localParticipant)==null?void 0:pe.isScreenShareEnabled)??!1;try{U?await s.setScreenShareEnabled(!1):await s.shareScreen()}catch(je){console.error("[obi-sdk] failed to toggle screen share",je)}finally{nn()}},Ai=w.useRef(null),F=w.useRef(null),oe=w.useRef(!1),le=w.useRef({session:null,sessionUuid:null,started:!1}),Oe=w.useRef(null),Ne=w.useRef(new WeakMap),vt=(U,W)=>{if(!W)return;let pe=Ne.current.get(U);pe||(pe=new Set,Ne.current.set(U,pe)),pe.add(W)},On=U=>{if(!U||Ai.current===U)return;F.current&&(F.current(),F.current=null);const W=()=>nn(),pe=ie=>{u(ie),U!=null&&U.sessionUuid&&N3(U.sessionUuid,ie),Array.isArray(ie.stepNames)&&ie.stepNames.length>0&&ie.totalSteps>0&&p(bt=>bt==="pip"||bt==="course-outline"?bt:bt==="course-selection"?(j.current=!0,"course-outline"):bt)},je=ie=>{k(ie.courses),p("course-selection"),j.current=!1,u(null),U!=null&&U.sessionUuid&&O3(U.sessionUuid),C(null),Y(!1)},ae=(ie,Ye)=>{},Se=ie=>{ie.isAgent},Qe=ie=>{G(ie),X(Date.now())},Xt=ie=>{if(!ie){G(null);return}G(ie),X(Date.now())};U.on("stateChanged",W),U.on("speakingStateChanged",W),U.on("paused",W),U.on("unpaused",W),U.on("chatMessagesChanged",W),U.on("chatMessageReceived",Se),U.on("courseProgress",pe),U.on("courseSelection",je),U.on("transcript",ae),U.on("screenCaptured",Qe),U.on("screenCaptureNotification",Xt),U.on("captions",te),U.on("introductionComplete",me),Ai.current=U,F.current=()=>{U.off("stateChanged",W),U.off("speakingStateChanged",W),U.off("paused",W),U.off("unpaused",W),U.off("chatMessagesChanged",W),U.off("chatMessageReceived",Se),U.off("courseProgress",pe),U.off("courseSelection",je),U.off("transcript",ae),U.off("screenCaptured",Qe),U.off("screenCaptureNotification",Xt),U.off("captions",te),U.off("introductionComplete",me)}},mi=U=>{var pe;return U?((pe=U.roomId)==null?void 0:pe.startsWith("obs-"))&&!c?"course-selection":"pip":"hidden"};w.useEffect(()=>{const U=()=>{Oe.current&&(Oe.current(),Oe.current=null)},W=ae=>{if(ae.clientType!=="meet")return;if(le.current.session&&le.current.session===ae||!!le.current.sessionUuid&&!!ae.sessionUuid&&le.current.sessionUuid===ae.sessionUuid){if(le.current.started||Oe.current)return}else le.current={session:ae,sessionUuid:ae.sessionUuid??null,started:!1},U();const Qe=async()=>{le.current={session:ae,sessionUuid:ae.sessionUuid??null,started:!0};const Ye=hn(ae);Ye&&vt(ae,Ye);try{await ae.sendHumanJoined(fn(ae))}catch(bt){console.error("[obi-sdk] failed to send human_joined handshake",bt)}},Xt=(Ye,bt)=>{Ye==="connecting"||Ye==="error"||(U(),Qe())},ie=ae.state;if(ie&&ie!=="connecting"&&ie!=="error"){Qe();return}ae.on("stateChanged",Xt),Oe.current=()=>{ae.off("stateChanged",Xt)}},pe=ae=>{var Se,Qe,Xt,ie;if(ae)if((Se=e.client)!=null&&Se.session)p(mi(((Xt=e.client)==null?void 0:Xt.session)??null));else{const bt=!!e.passivePlanUuid,Dn=bt&&!!((Qe=e.client)!=null&&Qe.selectedPlanUuid);if(bt&&!Dn)return;p("start-session")}else(ie=e.client)!=null&&ie.session||p("hidden")},je=()=>nn();if(e.on("showMenu",pe),e.on("configUpdated",je),e.client){e.client.session&&(l(e.client.session),On(e.client.session),p(mi(e.client.session))),e.client.on("sessionStarted",Se=>{l(Se),On(Se),oe.current=!1,m(!1),g(!1),x(!1),Y(!1);const Qe=ve.current;ve.current=!1,Qe?(j.current=!0,p("course-outline")):(j.current=!1,p(mi(Se))),ta().track("session-started",{planId:Se.planId}),W(Se)}),e.client.on("sessionResumed",Se=>{l(Se),On(Se),oe.current=!1,m(!1),g(!1),x(!1),Y(!1),j.current=!1,p(mi(Se)),W(Se)});const ae=()=>{var Xt;const Se=(Xt=e.client)==null?void 0:Xt.session;Se!=null&&Se.sessionUuid&&O3(Se.sessionUuid);const Qe=Ai.current;F.current&&(F.current(),F.current=null),l(null),Ai.current=null,m(!1),g(!1),x(!1),Y(!1),B(!1),ve.current=!1,j.current=!1,U(),le.current={session:null,sessionUuid:null,started:!1},Qe&&Ne.current.delete(Qe),oe.current||p("hidden")};e.client.on("sessionStopped",ae),e.client.on("sessionShutdown",ae),e.client.on("stateChanged",nn)}return()=>{e.off("showMenu",pe),e.off("configUpdated",je),F.current&&F.current(),U()}},[e]),w.useEffect(()=>{const U=s;if(!U||U.clientType!=="meet")return;const W=U.state;if(!W||W==="connecting"||W==="error"||!He)return;const pe=Ne.current.get(U);pe!=null&&pe.has(He)||(vt(U,He),U.sendHumanJoined(fn(U)).catch(je=>console.error("[obi-sdk] failed to send human_joined update",je)))},[Le,He,s,s==null?void 0:s.state]),w.useLayoutEffect(()=>{var U,W;(W=(U=e.client)==null?void 0:U.product)!=null&&W.primary_color&&n.style.setProperty("--obi-color-primary",e.client.product.primary_color)},[(No=(It=e.client)==null?void 0:It.product)==null?void 0:No.primary_color,n]),w.useEffect(()=>{if(i&&!be&&!fe){if(!r){p("hidden");return}p("start-session")}},[fe,i,be,r]),w.useEffect(()=>{var Xt,ie;$(!1);const U=(Xt=e.client)==null?void 0:Xt.api,W=(ie=e.client)==null?void 0:ie.product;if(!U||!W)return;const pe=(W==null?void 0:W.uuid)??(W==null?void 0:W.product_uuid),je=(W==null?void 0:W.slug)??(W==null?void 0:W.product_slug),ae=(W==null?void 0:W.id)??(W==null?void 0:W.product_id),Se={};if(pe?Se.product_uuid=pe:je?Se.product_slug=je:ae!=null&&(Se.product_id=String(ae)),Object.keys(Se).length===0)return;let Qe=!1;return U.getFeatureFlags(Se).then(Ye=>{if(Qe)return;const Dn=((Ye==null?void 0:Ye.data)??[]).find(Xb=>(Xb==null?void 0:Xb.slug)===KG);if(!Dn)return;const{user_enabled:Zn,product_enabled:Pn,global_enabled:_r}=Dn;let Kb=!!_r;Pn!=null&&(Kb=!!Pn),Zn!=null&&(Kb=!!Zn),$(Kb)}).catch(Ye=>{console.error("[obi-sdk] failed to load AMA feature flag",Ye)}),()=>{Qe=!0}},[(Oo=e.client)==null?void 0:Oo.api,(Mo=e.client)==null?void 0:Mo.product]);const ka=(c==null?void 0:c.stepNames.map((U,W)=>({id:`step-${W+1}`,title:U})))??[],$n=(c==null?void 0:c.currentStep)??null,Qn=!0,Qi=(U,W)=>{s==null||s.say(`Can we jump to the section about ${W.title}?`)};if(be||i&&!r&&!fe)return null;if(h==="hidden")return $i?f.jsx(YG,{label:ft,onClick:()=>{e.updateShowMenu(!0)}}):null;if(h==="start-session"){const U=(Do=e.client)==null?void 0:Do.product,W=(Fl=e.client)==null?void 0:Fl.selectedPlan,pe=i&&!!r,je=i&&!!r||!!((_=e.client)!=null&&_.selectedPlanUuid),ae=(U==null?void 0:U.agent_name)||"Obi",Se=(U==null?void 0:U.assistant_subtitle)||"AI Assistant",Qe=pe?(W==null?void 0:W.description)||(U==null?void 0:U.assistant_description)||(U==null?void 0:U.description)||"I'm here to help you.":(U==null?void 0:U.assistant_description)||(W==null?void 0:W.description)||(U==null?void 0:U.description)||"I'm here to help you.";return f.jsx(GG,{open:!0,onClose:()=>{m(!1),p("hidden")},onStart:()=>{ve.current=je,B(je),m(!0),e.startSession({withMicrophone:!0})},agentName:ae,agentSubtitle:Se,description:Qe,showCloseButton:!1,startLabel:"Start Session",isStarting:b,greetingVideoSrc:Nn})}if(h==="course-selection"){const U=(I=s==null?void 0:s.roomId)==null?void 0:I.startsWith("obs-"),W=((M=e.client)==null?void 0:M.plans)||[],pe=U&&v.length>0,je=pe?v.slice().sort((ie,Ye)=>ie.order!==void 0&&Ye.order!==void 0?ie.order-Ye.order:ie.order!==void 0?-1:Ye.order!==void 0?1:ie.name.localeCompare(Ye.name)).map(ie=>({id:ie.uuid,title:ie.name,description:ie.description||ie.overview||"",status:ie.completed?"completed":"available",duration:typeof ie.duration=="number"?`${ie.duration} min`:ie.duration})):W.map(ie=>{var Ye,bt;return{id:ie.uuid,title:ie.name,description:ie.description,status:(bt=(Ye=e.client)==null?void 0:Ye.planIsCompleted)!=null&&bt[W.indexOf(ie)]?"completed":"available",duration:ie.estimated_duration?`${ie.estimated_duration} min`:void 0}});pe&&ee&&je.push({id:A3,title:"Ask me anything",description:"Ask questions before choosing a course.",status:"available"});const ae=(s==null?void 0:s.languageCodes)||[],Se=(s==null?void 0:s.selectedLanguage)||(s==null?void 0:s.defaultLanguageCode)||null,Qe={audioDevices:En,currentMicrophoneId:(s==null?void 0:s.preferredMicrophoneDeviceId)||null,isMicrophoneEnabled:!S&&((s==null?void 0:s.isMicShared)??!1),isScreenShareActive:ht,widgetState:y?"chat":null,canPublishData:!0,browserSupportsScreenSharing:Le,onMicDeviceSelect:async ie=>{e.client&&(e.client.preferredMicrophoneDeviceId=ie),s&&ie&&await s.switchMicrophoneDevice(ie),nn()},onMicToggle:async()=>{s!=null&&s.isMicShared?S?(s.unmuteMicrophone(),g(!1)):(s.muteMicrophone(),g(!0)):await(s==null?void 0:s.shareMicrophone())},onChatToggle:()=>{x(!y)},onLeave:()=>{s==null||s.stop()},onScreenShareToggle:Jn,languages:ae,selectedLanguage:Se,defaultLanguageCode:s==null?void 0:s.defaultLanguageCode,isMultilingual:(s==null?void 0:s.isMultilingual)??!1,onLanguageChange:ie=>{s==null||s.setLanguage(ie)},isLanguageSelectorEnabled:!0,...y?{screenShareButtonVariant:"compact"}:{}},Xt=y?f.jsx(k3,{messages:(s==null?void 0:s.chatMessages)??[],localIdentity:((ge=s==null?void 0:s.room)==null?void 0:ge.localParticipant.identity)??(typeof(s==null?void 0:s.identity)=="string"?s.identity:null),onSend:async ie=>{var Ye,bt,Dn,Zn;if(s){const Pn=Date.now();s.appendChatMessage({timestamp:Pn,message:ie,from:{identity:((bt=(Ye=s.room)==null?void 0:Ye.localParticipant)==null?void 0:bt.identity)??null,name:((Zn=(Dn=s.room)==null?void 0:Dn.localParticipant)==null?void 0:Zn.name)??null},isAgent:!1}),await s.say(ie)}},onClose:()=>x(!1)}):void 0;return f.jsx(R3,{open:!0,onClose:()=>s==null?void 0:s.stop(),courses:je,controlBarProps:Qe,coursePanelProps:{selectedCourseIds:T?[T]:void 0,onCourseToggle:async ie=>{var Ye,bt,Dn,Zn;if(pe){if(ie===A3){try{await((Ye=s==null?void 0:s.say)==null?void 0:Ye.call(s,"Please start an AMA session."))}catch(_r){console.error("[obi-sdk] failed to start AMA course",_r)}return}const Pn=v.find(_r=>_r.uuid===ie);if(Pn){C(ie);try{await((bt=s==null?void 0:s.say)==null?void 0:bt.call(s,`I'd like to take the ${Pn.name} course.`))}catch(_r){console.error("[obi-sdk] failed to send course selection",_r),C(null)}}}else{const Pn=W.find(_r=>_r.uuid===ie);if(Pn){(Dn=e.client)==null||Dn.selectPlan(Pn),p("pip");try{await((Zn=s==null?void 0:s.say)==null?void 0:Zn.call(s,`I'd like to take the ${Pn.name} course.`))}catch(_r){console.error("[obi-sdk] failed to send course selection",_r),p("course-selection")}}}}},rightPanel:Xt,avatarImageSrc:tn,avatarAudioPower:qt,avatarStatus:At,captionsText:Te})}if(h==="course-outline"){const U=(s==null?void 0:s.languageCodes)||[],W=(s==null?void 0:s.selectedLanguage)||(s==null?void 0:s.defaultLanguageCode)||null,pe={audioDevices:En,currentMicrophoneId:(s==null?void 0:s.preferredMicrophoneDeviceId)||null,isMicrophoneEnabled:!S&&((s==null?void 0:s.isMicShared)??!1),isScreenShareActive:ht,widgetState:y?"chat":null,canPublishData:!0,browserSupportsScreenSharing:Le,onMicDeviceSelect:async ie=>{e.client&&(e.client.preferredMicrophoneDeviceId=ie),s&&ie&&await s.switchMicrophoneDevice(ie),nn()},onMicToggle:async()=>{s!=null&&s.isMicShared?S?(s.unmuteMicrophone(),g(!1)):(s.muteMicrophone(),g(!0)):await(s==null?void 0:s.shareMicrophone())},onChatToggle:()=>{x(!y)},onLeave:()=>{s==null||s.stop()},onScreenShareToggle:Jn,languages:U,selectedLanguage:W,defaultLanguageCode:s==null?void 0:s.defaultLanguageCode,isMultilingual:(s==null?void 0:s.isMultilingual)??!1,onLanguageChange:ie=>{s==null||s.setLanguage(ie)},isLanguageSelectorEnabled:!0,...y?{screenShareButtonVariant:"compact"}:{}},je=y?f.jsx(k3,{messages:(s==null?void 0:s.chatMessages)??[],localIdentity:((Ie=s==null?void 0:s.room)==null?void 0:Ie.localParticipant.identity)??(typeof(s==null?void 0:s.identity)=="string"?s.identity:null),onSend:async ie=>{var Ye,bt,Dn,Zn;if(s){const Pn=Date.now();s.appendChatMessage({timestamp:Pn,message:ie,from:{identity:((bt=(Ye=s.room)==null?void 0:Ye.localParticipant)==null?void 0:bt.identity)??null,name:((Zn=(Dn=s.room)==null?void 0:Dn.localParticipant)==null?void 0:Zn.name)??null},isAgent:!1}),await s.say(ie)}},onClose:()=>x(!1)}):void 0,ae=!!c,Se=!ue,Qe=async()=>{if(!(!(s!=null&&s.endCourse)||z)){Y(!0);try{await s.endCourse()}catch(ie){console.error("[obi-sdk] failed to end course",ie),Y(!1)}}},Xt=f.jsx(gV,{steps:ka,currentStep:$n,hideTrailingConclusionStep:Qn,onStepClick:Qi,showBackToCourses:Se,...Se?{onBackToCoursesConfirm:Qe,backToCoursesDisabled:z}:{}});return f.jsx(R3,{open:!0,onClose:()=>s==null?void 0:s.stop(),courses:[],controlBarProps:pe,middlePanel:Xt,rightPanel:je,isCourseOutlineOpen:ae,onReturnToPiP:ae?()=>p("pip"):void 0,avatarImageSrc:tn,avatarAudioPower:qt,avatarStatus:At,captionsText:Te})}if(h==="pip"){const U=(s==null?void 0:s.languageCodes)||[],W=(s==null?void 0:s.selectedLanguage)||(s==null?void 0:s.defaultLanguageCode)||null,pe=280,je=250,ae=16,Se={x:window.innerWidth-pe-ae,y:window.innerHeight-je-ae},Qe={isMicrophoneEnabled:!S&&((s==null?void 0:s.isMicShared)??!1),isChatOpen:y,isScreenShareActive:ht,onMicToggle:async()=>{s!=null&&s.isMicShared?S?(s.unmuteMicrophone(),g(!1)):(s.muteMicrophone(),g(!0)):await(s==null?void 0:s.shareMicrophone())},onChatToggle:()=>x(ie=>!ie),onScreenShareToggle:Jn,onLeave:()=>{s==null||s.stop()},languages:U,selectedLanguage:W,defaultLanguageCode:s==null?void 0:s.defaultLanguageCode,isMultilingual:(s==null?void 0:s.isMultilingual)??!1,onLanguageChange:ie=>{s==null||s.setLanguage(ie)},isLanguageSelectorEnabled:!0},Xt=y?f.jsx(BV,{messages:(s==null?void 0:s.chatMessages)??[],localIdentity:((ye=s==null?void 0:s.room)==null?void 0:ye.localParticipant.identity)??(typeof(s==null?void 0:s.identity)=="string"?s.identity:null),onSend:async ie=>{var Ye,bt,Dn,Zn;if(s){const Pn=Date.now();s.appendChatMessage({timestamp:Pn,message:ie,from:{identity:((bt=(Ye=s.room)==null?void 0:Ye.localParticipant)==null?void 0:bt.identity)??null,name:((Zn=(Dn=s.room)==null?void 0:Dn.localParticipant)==null?void 0:Zn.name)??null},isAgent:!1}),await s.say(ie)}},testId:"pip-chat-panel"}):void 0;return f.jsx(Zq,{initialPosition:Se,onExit:()=>{j.current=!1,p("course-outline")},controlBarProps:Qe,isCourseOutlineSelected:N&&!!c,onCourseOutlineToggle:c?()=>{O(ie=>!ie)}:void 0,isCaptionsEnabled:Z,onCaptionsToggle:()=>q(ie=>!ie),courseOutline:c?{steps:ka,currentStep:$n,onStepClick:Qi,hideTrailingConclusionStep:Qn}:void 0,messagesPanel:Xt,avatarFallbackProps:{audioPower:qt,imageSrc:tn,status:At,captionsText:Te},screenshotUrl:P,cameraShotTrigger:L})}return null}function JG(t){var l,c;const{sdk:e,session:n,isBlacklisted:i}=t;if(i)return!1;const r=e.client;if(!r||r.state!=="ready"||(n??r.session??null))return!1;let o=e.isActive;return((l=r.product)==null?void 0:l.name)==="Canibuild"&&(o=!0),!(!o||(e.widgetDisplay??((c=r.product)==null?void 0:c.widget_display))==="invisible")}function N3(t,e){if(!t)return;const n=`obi-widget-course-progress-${t}`;if(e===null){localStorage.removeItem(n);return}try{const i={...e,timestamp:Date.now()};localStorage.setItem(n,JSON.stringify(i))}catch(i){console.error("[obi-sdk] failed to save course progress",i)}}function $G(t){if(!t)return null;const e=`obi-widget-course-progress-${t}`;try{const n=localStorage.getItem(e);if(!n)return null;const i=JSON.parse(n);if(typeof i.currentStep!="number"||typeof i.totalSteps!="number"||!Array.isArray(i.stepNames))return console.warn("[obi-sdk] invalid course progress data, clearing",i),localStorage.removeItem(e),null;const r=24*60*60*1e3;return i.timestamp&&Date.now()-i.timestamp>r?(localStorage.removeItem(e),null):{currentStep:i.currentStep,totalSteps:i.totalSteps,stepNames:i.stepNames}}catch(n){return console.error("[obi-sdk] failed to load course progress",n),localStorage.removeItem(e),null}}function O3(t){if(!t)return;const e=`obi-widget-course-progress-${t}`;try{localStorage.removeItem(e)}catch(n){console.error("[obi-sdk] failed to clear course progress",n)}}function QG(t){const[e,n]=w.useState(()=>fs(t));return w.useEffect(()=>{n(fs(t))},[t]),w.useEffect(()=>{const i=()=>{n(fs(t))};return window.addEventListener("popstate",i),window.addEventListener("hashchange",i),()=>{window.removeEventListener("popstate",i),window.removeEventListener("hashchange",i)}},[t]),e}function ZG(t){const[e,n]=w.useState(0),i=w.useRef(null),r=w.useRef(0),a=w.useRef(0);return w.useEffect(()=>{if(!t){n(0),r.current=0,a.current=0;return}const o=()=>{const s=t.audioSpectrum();let l=0;if(s&&s.length>0){let b=0;for(let m=0;m<s.length;m++)b+=s[m];l=Math.min(1,Math.max(0,b/s.length))}const c=r.current,d=l>=c?.7:.15,h=c*d+l*(1-d);r.current=h;const p=h<.05?0:Math.min(1,h);Math.abs(p-a.current)>.01&&(a.current=p,n(p)),i.current=requestAnimationFrame(o)};return i.current=requestAnimationFrame(o),()=>{i.current&&cancelAnimationFrame(i.current)}},[t]),e}function eW(){const[t,e]=w.useState({audioDevices:[]});return w.useEffect(()=>{var i;if(typeof navigator>"u"||!((i=navigator.mediaDevices)!=null&&i.enumerateDevices))return;const n=()=>{navigator.mediaDevices.enumerateDevices().then(r=>{e({audioDevices:r.filter(a=>a.kind==="audioinput")})})};return n(),navigator.mediaDevices.addEventListener("devicechange",n),()=>navigator.mediaDevices.removeEventListener("devicechange",n)},[]),t}function M3(){const t=window.location.hostname;return t.endsWith(".getcor.ai")||t.endsWith(".getcor.io")||t==="getcor.ai"||t==="getcor.io"||t==="localhost"||t==="127.0.0.1"||t==="::1"}const D3=M3();function tW(t){if(document.querySelector("#obi-host")||document.querySelector("obi-widget"))return;nW();const e=document.createElement("div");e.id="obi-host",e.style.position="fixed",e.style.zIndex="9999",document.body.appendChild(e);const n=e.attachShadow({mode:"open"}),i=document.createElement("div");i.id="obi-container",n.appendChild(i);const r=new CSSStyleSheet;r.replaceSync(TB);const a=[r];if(D3){const s=new CSSStyleSheet;s.replaceSync(xB),a.push(s);const l=new CSSStyleSheet;l.replaceSync(kB),a.push(l)}else{const s=new CSSStyleSheet;s.replaceSync(SB),a.push(s)}n.adoptedStyleSheets=a;const o=_B.createRoot(i);D3?o.render(f.jsx(XG,{sdk:t,shadowHost:e})):o.render(f.jsx(EB,{sdk:t,shadowHost:e})),console.log("[obi-sdk] widget mounted")}function nW(){P3("https://fonts.cdnfonts.com/css/satoshi"),P3("https://fonts.googleapis.com/css2?family=Inter:ital,opsz,wght@0,14..32,100..900;1,14..32,100..900&display=swap")}function P3(t){const e=document.createElement("link");e.href=t,e.rel="stylesheet",document.head.appendChild(e)}const L3="49206C6F7665204F6269_session",I3="obi-url-params",Yb="obi-client-heartbeat",iW=5e3,j3=4e4,B3=15e3;function rW(){return M3()?"meet":"sdk"}class aW extends _p{constructor(e){super(),this.client=null,this.isActive=!1,this.primaryColour="#9500FF",this.passivePlanUuid=null,this.commandLog=[],this.commandQueue=[],this._resumed=!1,this.heartbeatInterval=null,this.dispatchCommand=(n,i)=>{var r,a,o,s,l;switch(this.commandLog.push({commandType:n,args:i}),n){case"update":this.updateConfig(i);break;case"startSession":{if(i!=null&&i.planUuid){const c=(((r=this.client)==null?void 0:r.plans)||[]).find(u=>u.uuid===i.planUuid)||null;if(!c){console.warn("[obi] startSession command requires a valid planUuid",i);return}(o=(a=this.client)==null?void 0:a.selectPlan)==null||o.call(a,c)}this.updateActive(!0);break}case"stopSession":(l=(s=this.client)==null?void 0:s.stopSession)==null||l.call(s);break;case"say":this.say(i);break;default:console.warn("[obi] unknown command",{commandType:n,args:i})}},e&&this.createClient(e),this.parsePassiveParams()}async createClient(e){if(this.client){this.client.appToken!==e&&console.warn("[obi] client already exists with different app token");return}let n=null;const i=rW(),r=this.load();if(r)try{const a=this.parsePersistedSessionMetadata(r),o=a&&this.isPersistedSessionStale(a);o!=null&&o.stale&&a?(this.trackStaleSessionDiscard(a.sessionUuid,o.ageMs,o.reason),this.clearCachedClient()):(n=bh.deserialise(r,e,i,{apiBaseUrl:"https://staging.coragents.ai",captureScreen:this.captureScreen.bind(this)}),n?this._resumed=!0:this.clearCachedClient())}catch(a){console.error("[obi] error loading cached client",a),this.clearCachedClient()}n||(n=new bh(e,i,{apiBaseUrl:"https://staging.coragents.ai",captureScreen:this.captureScreen.bind(this)})),this.client=n,this.client.session&&this.startHeartbeat(this.client.session.sessionUuid),this.client.on("stateChanged",a=>{var o,s,l,c,u,d,h,p,b,m;a==="ready"&&this.updateConfig({isActive:((o=window==null?void 0:window.obiWidgetConfig)==null?void 0:o.isActive)??((s=this.client)==null?void 0:s.showWidget),primaryColour:((c=(l=this.client)==null?void 0:l.product)==null?void 0:c.primary_color)||"#9500FF",widgetDisplay:((u=window==null?void 0:window.obiWidgetConfig)==null?void 0:u.widgetDisplay)||((h=(d=this.client)==null?void 0:d.product)==null?void 0:h.widget_display)||"regular",completedWidgetDisplay:((p=window==null?void 0:window.obiWidgetConfig)==null?void 0:p.completedWidgetDisplay)||((m=(b=this.client)==null?void 0:b.product)==null?void 0:m.completed_widget_display)||"regular"})}),this.client.on("sessionStarted",()=>{var a,o;this.save(),this.startHeartbeat(((o=(a=this.client)==null?void 0:a.session)==null?void 0:o.sessionUuid)||null),this.passivePlanUuid=null}),this.client.on("sessionStopped",()=>{this.clearCachedClient(),this.passivePlanUuid=null}),this.client.on("sessionShutdown",()=>{this.clearCachedClient()}),this.client.on("trackEvent",(a,o)=>{}),this.client.session&&(this.client.session.isPaused,this.client.resumeSession(a=>{a.on("stateChanged",o=>{o!=="disconnecting"&&o!=="disconnected"&&o!=="error"&&o!=="connecting"&&this.save()}),a.on("paused",()=>{this.save()}),a.on("unpaused",()=>{this.save()})}))}_maybeActOnServerEngagement(){var s;const e=this.client;if(!e||e.state!=="ready")return;const n=e.product,i=(s=e.engagement)==null?void 0:s.style;if(!i||n&&fs(n.widget_url_blacklist||[])||!e.showWidget)return;const r=e.plans||[],a=e.planIsCompleted||[],o=r.length>0&&a.filter(Boolean).length===r.length;if(!(r.length===0||o)){if(i==="modal"){const l=a.findIndex(u=>!u),c=l>=0?r[l]:null;c&&e.selectPlan(c)}else i==="popover"&&setTimeout(()=>{this.showMessage("Don't forget to complete your onboarding",{autoCloseMs:1e4})},1e3);try{ta().track("engagement-prompt-shown",{style:i})}catch{}}}async initialise(e={}){var n;this.commandQueue=e.queuedCommands||[],this._resumed?(this._resumed=!1,this.dispatchCommandQueue()):this.client?this.client.initialise({planUuid:this.passivePlanUuid||void 0,identity:((n=window==null?void 0:window.obiWidgetConfig)==null?void 0:n.user)||void 0}).then(()=>{this.emit("initialised");try{this._maybeActOnServerEngagement()}catch{}this.dispatchCommandQueue()}).catch(i=>{console.error("[obi] error initialising client",i),this.emit("error",i)}):this.dispatchCommandQueue()}async updateConfig(e){await this.updateAppToken(e.apiKey),this.updateActive(e.isActive),this.updatePrimaryColour(e.primaryColour),this.updateWidgetDisplay(e.widgetDisplay),this.updateCompletedWidgetDisplay(e.completedWidgetDisplay),this.updateWidgetPosition(e.widgetPosition),await this.updateIdentity(e.user),this.updateShowMenu(e.showMenu),this.emit("configUpdated")}async updateAppToken(e){var n;e===void 0||e==((n=this.client)==null?void 0:n.appToken)||(this.passivePlanUuid,await this.createClient(e),this.client&&await this.client.initialise({planUuid:this.passivePlanUuid||void 0}).then(()=>{this.emit("initialised");try{this._maybeActOnServerEngagement()}catch{}}).catch(i=>{console.error("[obi] error initialising client",i),this.emit("error",i)}))}updateActive(e){e===void 0||e==this.isActive||(this.isActive=e)}updatePrimaryColour(e){e===void 0||e==this.primaryColour||(this.primaryColour=e)}updateWidgetDisplay(e){e===void 0||e==this.widgetDisplay||(this.widgetDisplay=e)}updateCompletedWidgetDisplay(e){e===void 0||e==this.completedWidgetDisplay||(this.completedWidgetDisplay=e)}updateWidgetPosition(e){e===void 0||e==this.widgetPosition||(this.widgetPosition=e)}async updateIdentity(e){var i,r;if(e===void 0||e==((i=this.client)==null?void 0:i.identity))return;(r=this.client)==null||r.identity;let n=e?{...e,extra:{...e,...(e==null?void 0:e.extra)||{}}}:void 0;await this.client.initialise({identity:n,planUuid:this.passivePlanUuid||void 0}).then(()=>{this.emit("initialised");try{this._maybeActOnServerEngagement()}catch{}}).catch(a=>{console.error("[obi] error initialising client",a),this.emit("error",a)}),e!=null&&e.email&&ta().identify((e==null?void 0:e.email)||"",n)}updateShowMenu(e){e!==void 0&&this.emit("showMenu",e)}async say(e){var n,i,r;await((r=(i=(n=this.client)==null?void 0:n.session)==null?void 0:i.say)==null?void 0:r.call(i,e))}async startSession(e){await this.client.startSession(this.client.selectedPlanUuid||null,n=>{n.on("stateChanged",i=>{i!=="disconnecting"&&i!=="disconnected"&&i!=="error"&&i!=="connecting"&&this.save()}),n.on("paused",()=>{this.save()}),n.on("unpaused",()=>{this.save()})},e)}dispatchCommandQueue(){const e=this.commandQueue;this.commandQueue=[],e.forEach(n=>{try{this.dispatchCommand(n[0],n[1]||[])}catch(i){console.error("[obi] error dispatching command",i)}})}parsePassiveParams(){if(this.passivePlanUuid){this.passivePlanUuid;return}let e={};e=JSON.parse(localStorage.getItem(I3)||"{}"),Object.keys(e).length===0&&new URLSearchParams(window.location.search).forEach((a,o)=>{e[o]=a});const n=e[L3];if(!n)return null;const i=new URL(window.location.href);i.searchParams.delete(L3),window.history.replaceState({},"",i.toString()),i.toString(),localStorage.removeItem(I3),this.passivePlanUuid=n}mountWidget(){tW(this)}showMessage(e,n){try{this.emit("showMessage",{text:e,autoCloseMs:n==null?void 0:n.autoCloseMs})}catch{}}async captureScreen(){try{await fO(async()=>(this.graphemes||(this.graphemes=await this.client.api.getGraphemes()),this.graphemes.data.text_segmentation)),await sR(async()=>(this.graphemes||(this.graphemes=await this.client.api.getGraphemes()),this.graphemes.data.css_line_breaks))}catch(e){throw console.error("[obi] error initialising unicode trie",e),e}try{return(await GN(document.documentElement,{useCORS:!0,allowTaint:!0,foreignObjectRendering:!0})).toDataURL("image/png")}catch(e){throw console.error("[obi] error capturing screen",e),e}}save(){var n;const e=((n=this.client)==null?void 0:n.serialise())||"";localStorage.setItem("obi-client",e)}load(){return localStorage.getItem("obi-client")}parsePersistedSessionMetadata(e){const n=JSON.parse(e),i=this.parseTimestampMs(n.serialisedAt);if(!n.session)return null;let r=null;if(typeof n.session=="string")try{r=JSON.parse(n.session)}catch{return null}else typeof n.session=="object"&&(r=n.session);return r?{sessionUuid:typeof r.sessionUuid=="string"?r.sessionUuid:null,startedAtMs:this.parseTimestampMs(r.startedAt),serialisedAtMs:i}:null}isPersistedSessionStale(e){const n=Date.now(),i=this.readHeartbeat();if(i&&i.sessionUuid&&e.sessionUuid&&i.sessionUuid===e.sessionUuid){const s=Math.max(0,n-i.updatedAtMs);return{stale:s>j3,reason:s>j3?"heartbeat-stale":"heartbeat-fresh",ageMs:s}}const r=[e.serialisedAtMs,e.startedAtMs].filter(s=>typeof s=="number"&&Number.isFinite(s));if(r.length===0)return{stale:!0,reason:"fallback-missing-timestamps",ageMs:null};const a=Math.max(...r),o=Math.max(0,n-a);return{stale:o>B3,reason:o>B3?"fallback-too-old":"fallback-recent",ageMs:o}}parseTimestampMs(e){if(typeof e=="number")return e;if(typeof e=="string"){const n=Number(e);if(!Number.isNaN(n))return n;const i=Date.parse(e);return Number.isFinite(i)?i:null}return null}readHeartbeat(){const e=localStorage.getItem(Yb);if(!e)return null;try{return JSON.parse(e)}catch{return null}}trackStaleSessionDiscard(e,n,i){try{ta().track("stale-session-discarded",{sessionUuid:e||void 0,ageMs:n??void 0,reason:i})}catch{}}startHeartbeat(e){if(!e){this.clearHeartbeat();return}this.stopHeartbeat(),this.writeHeartbeat(e),this.heartbeatInterval=setInterval(()=>{this.writeHeartbeat(e)},iW)}stopHeartbeat(){this.heartbeatInterval&&(clearInterval(this.heartbeatInterval),this.heartbeatInterval=null)}writeHeartbeat(e){const n={sessionUuid:e,updatedAtMs:Date.now()};localStorage.setItem(Yb,JSON.stringify(n))}clearHeartbeat(){this.stopHeartbeat(),localStorage.removeItem(Yb)}clearCachedClient(){this.clearHeartbeat(),localStorage.removeItem("obi-client")}}async function U3(t,e){let n;try{n=window}catch{console.warn("[obi] no window object found"),n={}}return oW({appToken:t,window:n,init:e})}async function oW({appToken:t,window:e,init:n}){var a,o;if(e.obi){console.warn("[obi] obi object already found on window, skipping");return}n&&n(),t||(t=(a=e==null?void 0:e.obiWidgetConfig)==null?void 0:a.apiKey);let i;try{i=((o=e.ObiSDK)==null?void 0:o.q)||[]}catch{i=[]}const r=new aW(t);return e.ObiSDK=r.dispatchCommand,await r.initialise({queuedCommands:i}),e.obi=r,r.mountWidget(),r}function z3(){}document.readyState==="loading"?document.addEventListener("DOMContentLoaded",()=>{U3(void 0,z3)}):U3(void 0,z3)})();