@realsee/live 0.6.10 → 0.6.11
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs.js +1 -1
- package/dist/index.cjs.js.map +1 -1
- package/dist/index.es.js +27 -66
- package/dist/index.es.js.map +1 -1
- package/dist/live/controller.d.ts +4 -0
- package/dist/live/live.d.ts +1 -1
- package/dist/utils/RobustWebSocket.d.ts +1 -1
- package/package.json +1 -1
package/dist/index.cjs.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";var Ft=Object.defineProperty;var qt=(r,s,e)=>s in r?Ft(r,s,{enumerable:!0,configurable:!0,writable:!0,value:e}):r[s]=e;var o=(r,s,e)=>(qt(r,typeof s!="symbol"?s+"":s,e),e);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const Kt=require("@realsee/jsbridge-x"),Ae=require("trtc-js-sdk"),X=require("amazon-chime-sdk-js"),D=require("react"),ue=Symbol("$$REALSEE_LIVE_EVENT$$");function Ee(r){return r[ue]||(r[ue]={}),r[ue]}function Gt(r){r[ue]||delete r[ue]}class le{hasListener(s){const e=Ee(this);return e&&e[s]&&e[s].length>0}on(s,e,i){const n=Ee(this);return n[s]||(n[s]=[]),n[s].push([e,i||!1]),()=>this.off(s,e)}once(s,e){return this.on(s,e,!0)}off(s,e){if(s===void 0){Gt(this);return}const i=Ee(this);if(i[s]||(i[s]=[]),e===void 0){i[s].length=0;return}let n=0;for(;n<i[s].length&&i[s][n][0]!==e;n++);n<i[s].length&&i[s].splice(n,1)}emit(s,...e){let i=!1;const c=Ee(this)[s]||[];for(let u of c.slice()){const[d,g=!1]=u,v=d(...e);g&&this.off(s,d),v===!1&&(i=!0)}return i}}class Ce extends le{}var ee=(r=>(r.RealseeBrowserRTC="RealseeBrowserRTC",r.RealseeVRWebViewRTC="RealseeVRWebViewRTC",r.RealseeBrowserChimeRTC="RealseeBrowserChimeRTC",r))(ee||{}),Ue=(r=>(r.RealseeXTRTC="trtc",r.RealseeXChimeRTC="chime",r))(Ue||{});const Yt=()=>{const r=new Date,s=r.getFullYear(),e=(r.getMonth()+1).toString().padStart(2,"0"),i=r.getDate().toString().padStart(2,"0"),n=r.getHours().toString().padStart(2,"0"),c=r.getMinutes().toString().padStart(2,"0"),u=r.getSeconds().toString().padStart(2,"0"),d=r.getMilliseconds();return`[${s}-${e}-${i} ${n}:${c}:${u}.${d}]`},we=(r,s=[])=>{switch(s.unshift(`Realsee Live ${Yt()} <${r}> `),r){case"INFO":return console.info(...s);case"ERROR":return console.error(...s);case"WARN":return console.warn(...s);default:return console.log(...s)}},Ht=(...r)=>we("LOG",r),Jt=(...r)=>we("INFO",r),zt=(...r)=>we("ERROR",r),Xt=(...r)=>we("WARN",r),Zt={log:Ht,info:Jt,error:zt,warn:Xt},O=Zt;function Z(){return((1+Math.random())*65536|0).toString(16).substring(1)}function ye(){return(Z()+Z()+"-"+Z()+"-4"+Z().substr(0,3)+"-"+Z()+"-"+Z()+Z()+Z()).toLowerCase()}class De extends Ce{constructor(e){super();o(this,"type",ee.RealseeBrowserRTC);o(this,"joined",!1);o(this,"micro",!1);o(this,"voiceId","");o(this,"_getVoiceSign",()=>{throw new Error("方法 getVoiceSign 未实现")});o(this,"_autoPlayConfirm");o(this,"checkRequirement",()=>Ae.checkSystemRequirements());o(this,"$dom",document.createElement("div"));o(this,"_trtc",{client:null,stream:null});o(this,"join",async e=>{var c;this.emit("joinWillStart");const i=await this._getVoiceSign({voiceId:e.voiceId,roomId:e.roomId,userId:e.userId});this._trtc.client=Ae.createClient({mode:"rtc",...i,enableAutoPlayDialog:typeof this._autoPlayConfirm!="function"}),(c=this._trtc.client)==null||c.enableAudioVolumeEvaluation(),this._registerRtcEvent();let n=await new Promise(u=>{var d;(d=this._trtc.client)==null||d.join({roomId:Number(e.voiceId)}).then(()=>u(!0)).catch(()=>u(!1))});return this.joined=n,n?(this._trtc.stream=Ae.createStream({userId:i.userId,audio:!0,video:!1}),n=await new Promise(u=>{var d;(d=this._trtc.stream)==null||d.initialize().then(()=>u(!0)).catch(()=>u(!1))}),n=await new Promise(u=>{var d;(d=this._trtc.client)==null||d.publish(this._trtc.stream).then(()=>u(!0)).catch(()=>u(!1))}),this.joined=n,this.joined&&this.emit("joined"),n):!1});o(this,"_handleStreamAdded",e=>{var n;const i=e.stream;console.log("远端流增加: "+i.getId()),(n=this._trtc.client)==null||n.subscribe(i)});o(this,"_handleStreamSubscribed",e=>{const i=e.stream;console.log("远端流订阅成功:"+i.getId());const c=`rs-rtc-remote_stream-${i.getId()}`,u=document.createElement("div");u.id=c,this.$dom.appendChild(u),typeof this._autoPlayConfirm=="function"?(i.play(c).catch(d=>{}),i.on("error",d=>{if(d.getCode()===16451){const v=()=>i.resume();this._autoPlayConfirm({onConfirm:v})}})):i.play(c)});this._getVoiceSign=e.getVoiceSign,this._autoPlayConfirm=e.autoPlayConfirm,this._initParentDom()}_initParentDom(){this.$dom.id=`rs-rtc-${ye()}`,this.$dom.style.display="none",document.body.appendChild(this.$dom)}quit(){return new Promise(async e=>{var i,n;this.joined=!1,this._trtc.stream&&(await((i=this._trtc.client)==null?void 0:i.unpublish(this._trtc.stream)),this._trtc.stream.stop(),this._trtc.stream.close(),this._trtc.stream=null),(n=this._trtc.client)==null||n.leave().then(()=>this._trtc.client=null).then(()=>e(!0)).catch(()=>e(!1)),e(!0)})}detectMicro(){return new Promise(e=>{const i={audio:!0,video:!1};try{navigator.mediaDevices.getUserMedia(i).then(()=>e(!0)).catch(n=>{O.error(n.message),e(!1)})}catch(n){console.error(n),e(!1)}})}toggleMicro(e){var i,n,c,u;return Promise.resolve((e?(n=(i=this._trtc)==null?void 0:i.stream)==null?void 0:n.unmuteAudio():(u=(c=this._trtc)==null?void 0:c.stream)==null?void 0:u.muteAudio())||!1)}shock(){throw new Error("Method not implemented.")}_registerRtcEvent(){var e,i,n,c;(e=this._trtc.client)==null||e.on("stream-added",this._handleStreamAdded),(i=this._trtc.client)==null||i.on("stream-subscribed",this._handleStreamSubscribed),(n=this._trtc.client)==null||n.on("audio-volume",u=>this.emit("userVolumes",u.result.map(({userId:d,audioVolume:g})=>({userId:d,audioVolume:g})))),(c=this._trtc.client)==null||c.on("error",u=>this.emit("error",u))}}class Ve extends Ce{constructor(e){super();o(this,"type",ee.RealseeBrowserChimeRTC);o(this,"joined",!1);o(this,"micro",!1);o(this,"voiceId","");o(this,"userId","");o(this,"logger");o(this,"deviceController");o(this,"meetingSession");o(this,"audioInput");o(this,"audioOutput");o(this,"deviceChangeObserver",{});o(this,"audioVideoObserver",{});o(this,"audioMixObserver");o(this,"_getVoiceSign",()=>{throw new Error("方法 getVoiceSign 未实现")});o(this,"_autoPlayConfirm");o(this,"$dom",document.createElement("div"));o(this,"$audio",document.createElement("audio"));o(this,"_initDom",()=>{this.$audio.id=`rs-rtc-${ye()}`,this.$dom.id=`rs-rtc-${ye()}`,this.$dom.appendChild(this.$audio),document.body.appendChild(this.$dom)});o(this,"initObservers",()=>{this.deviceChangeObserver={audioInputsChanged:e=>{this.logger.info(`audioInputsChanged ${typeof e}`),e==null||e.forEach(i=>{this.logger.info(`Device ID: ${i.deviceId} Microphone: ${i.label}`)})},audioOutputsChanged:e=>{this.logger.info(`audioOutputsChanged ${typeof e}`),e==null||e.forEach(i=>{this.logger.info(`Device ID: ${i.deviceId} Speaker: ${i.label}`)})},audioInputMuteStateChanged:(e,i)=>{this.logger.info(`Device ${e.toString()} ${i?"is muted in hardware":"is not muted"}`)}},this.audioVideoObserver={audioVideoDidStart:()=>{this.logger.info("Started")},audioVideoDidStop:e=>{this.logger.info(`Stopped with a session status code: ${e.statusCode()}`)},audioVideoDidStartConnecting:e=>{e&&this.logger.info("Attempting to reconnect")}},this.audioMixObserver={meetingAudioStreamBecameActive:e=>{if(this.$audio.paused){const i=()=>this.$audio.play().then(()=>{}).catch(n=>{if(O.error("播放远端流失败!",n),typeof this._autoPlayConfirm=="function"){const c=()=>i();this._autoPlayConfirm({onConfirm:c})}});i()}},meetingAudioStreamBecameInactive:e=>{}}});o(this,"_registerRtcEvent",()=>{var i,n,c,u,d,g;const e=((c=(n=(i=this.meetingSession)==null?void 0:i.configuration)==null?void 0:n.credentials)==null?void 0:c.attendeeId)||"";if(e){const v=new Map,E=()=>{const y=[];return v.forEach((I,_)=>{y.push({userId:I.userId,volume:I.muted||I.signalStrength===0||!Boolean(I.volume)?0:I.volume})}),y};(u=this.meetingSession)==null||u.audioVideo.realtimeSubscribeToAttendeeIdPresence((y,I,_)=>{var V;if(!I){v.delete(y),this.emit("userVolumes",E());return}(V=this.meetingSession)==null||V.audioVideo.realtimeSubscribeToVolumeIndicator(y,(C,k,B,P)=>{new X.DefaultModality(C).base()===C&&(v.set(C,{userId:_||C,volume:k,muted:B,signalStrength:P}),this.emit("userVolumes",E()))})}),(d=this.meetingSession)==null||d.audioVideo.realtimeSubscribeToVolumeIndicator(e,(y,I,_,V)=>{new X.DefaultModality(y).base()===y&&V!==null&&V!==1&&this.emit("weakNetwork")}),(g=this.meetingSession)==null||g.audioVideo.realtimeSubscribeToFatalError(y=>this.emit("error",y))}});this._getVoiceSign=e.getVoiceSign,this._autoPlayConfirm=e.autoPlayConfirm,this._initDom(),this.logger=new X.ConsoleLogger("WebRTCLogger",e.logLevel||X.LogLevel.INFO),this.deviceController=new X.DefaultDeviceController(this.logger),this.initObservers()}async join(e){return new Promise(async(i,n)=>{var c,u;this.emit("joinWillStart");try{const{sdkAppId:d,userId:g,roomId:v,userSig:E}=await this._getVoiceSign({...e,roomId:e.roomId||0});this.userId=g;const{attendence:y,vendor_wrapper:I}=JSON.parse(decodeURIComponent(E)),_=new X.MeetingSessionConfiguration({Meeting:I},{Attendee:{ExternalUserId:y.external_user_id,AttendeeId:y.attendee_id,JoinToken:y.join_token}});this.meetingSession=new X.DefaultMeetingSession(_,this.logger,this.deviceController),this._registerRtcEvent(),this.meetingSession.audioVideo.addDeviceChangeObserver(this.deviceChangeObserver),this.meetingSession.audioVideo.addObserver(this.audioVideoObserver),this.meetingSession.audioVideo.bindAudioElement(this.$audio);const V={audioVideoDidStart:()=>{var C;(C=this.meetingSession)==null||C.audioVideo.realtimeMuteLocalAudio(),this.joined=!0,this.emit("joined"),i(!0)},audioVideoDidStop:()=>{this.joined=!1,i(!1)}};this.meetingSession.audioVideo.addObserver(V),this.audioMixObserver&&this.meetingSession.audioVideo.addAudioMixObserver(this.audioMixObserver),this.meetingSession.audioVideo.setDeviceLabelTrigger(async()=>await navigator.mediaDevices.getUserMedia({audio:!0,video:!1}));try{const C=await this.meetingSession.audioVideo.listAudioInputDevices();O.info("audioInputDevices ===>",C);const k=((c=C[0])==null?void 0:c.deviceId)||"default";await this.meetingSession.audioVideo.startAudioInput(k)}catch(C){O.error(`设置语音输入设备失败:${C.message}`)}try{const C=await this.meetingSession.audioVideo.listAudioOutputDevices();O.info("audioOutputDevices ===>",C);const k=((u=C[0])==null?void 0:u.deviceId)||"default";await this.meetingSession.audioVideo.chooseAudioOutput(k)}catch(C){O.error(`设置语音输出设备失败:${C.message}`)}this.meetingSession.audioVideo.start()}catch(d){this.emit("error",d),this.logger.error(d.message),i(!1)}})}quit(){return this.joined?new Promise((e,i)=>{var c,u;this.joined=!1;const n={audioVideoDidStop:async d=>{var v;const g=d.statusCode();(v=this.meetingSession)==null||v.deviceController.destroy(),g===X.MeetingSessionStatusCode.Left?(this.logger.info("You left the session"),e(!0)):(this.logger.info(`Stopped with a session status code: ${g}`),e(!0))}};(c=this.meetingSession)==null||c.audioVideo.addObserver(n),(u=this.meetingSession)==null||u.audioVideo.stop()}):Promise.resolve(!0)}async detectMicro(){return new Promise(e=>{const i={audio:!0,video:!1};try{navigator.mediaDevices.getUserMedia(i).then(()=>e(!0)).catch(()=>e(!1))}catch(n){this.logger.error(n.message),e(!1)}})}async toggleMicro(e){var n,c,u;e?(n=this.meetingSession)==null||n.audioVideo.realtimeUnmuteLocalAudio():(c=this.meetingSession)==null||c.audioVideo.realtimeMuteLocalAudio();const i=(u=this.meetingSession)==null?void 0:u.audioVideo.realtimeIsLocalAudioMuted();return i!==void 0?e!==i:!1}shock(){throw new Error("Method not implemented.")}}var Be=(r=>(r[r.Success=0]="Success",r[r.Failure=1]="Failure",r[r.ReJoin=2]="ReJoin",r[r.NoMicroPermission=3]="NoMicroPermission",r))(Be||{});class $e extends Ce{constructor({jsBridge:e,getVoiceSign:i}){super();o(this,"type",ee.RealseeVRWebViewRTC);o(this,"joined",!1);o(this,"micro",!1);o(this,"voiceId","");o(this,"options");this.options={jsBridge:e,getVoiceSign:i},this.jsBridge.webViewType!=="WxMiniProgramWebView"&&this.jsBridge.callAndListen("live/userVolumes",n=>{this.emit("userVolumes",n)}),this.jsBridge.callAndListen("live/weakNetwork",n=>{n&&this.emit("weakNetwork")})}get jsBridge(){return this.options.jsBridge}async join(e){try{this.emit("joinWillStart");const{sdkAppId:i,userId:n,userSig:c}=await this.options.getVoiceSign(e);if(!(Boolean(i)&&Boolean(n)&&Boolean(c)))return this.emit("error",new Error("加入房间失败:rtc 签名请求异常")),this.joined=!1,this.joined;this.type=e.type;const[u,d]=await this.jsBridge.callAndBackfeed(`live/join?sdkAppID=${i}&userID=${n}&roomID=${Number(e.voiceId)}&userSig=${c}`);return u===!0?(this.emit("joined"),this.joined=!0):u?u.code===Be.Success?(this.emit("joined"),this.joined=!0):(this.emit("error",u),this.joined=!1):(this.emit("error",d||new Error("加入房间失败:未知异常。")),this.joined=!1),this.joined}catch(i){return this.emit("error",new Error("加入房间失败:"+i.message)),this.joined=!1,this.joined}}async quit(){const[e,i]=await this.jsBridge.callAndBackfeed("live/quit");return e===null&&this.emit("error",i||new Error("退出房间失败:未知异常。")),this.joined=!1,!!e}async detectMicro(){const[e,i]=await this.jsBridge.detectMicro();return e===null?(this.emit("error",i||new Error("麦克风监测异常!")),!1):e}async toggleMicro(e){const[i,n]=await this.jsBridge.callAndBackfeed(`live/toggleMicro?flag=${e?1:0}`);return i===null?(this.emit("error",n||new Error("麦克风监测异常!")),!1):(this.micro=i,i)}shock(){this.jsBridge.shock(1)}}var U=(r=>(r.SelfUserInfo="SELF_USER_INFO",r.RoomInfo="ROOM_INFO",r.RTCInfo="RTC_INFO",r.UserList="USER_LIST",r.BuiltinMsg="BUILTIN_MSG",r.CustomEvent="CUSTOM_EVENT",r.KeyframeSync="KEYFRAME_SYNC",r.UserKickOut="USER_KICK_OUT",r))(U||{}),K=(r=>(r.UserChange="user_change",r.RoomChange="room_change",r))(K||{}),Y=(r=>(r.UserMicroStatus="change_micro_status",r.UserMicroStatusSync="sync_micro_status",r.UserPermission="change_permission",r.UserStatus="change_status",r.UserInfo="change_info",r.RoomClose="close",r))(Y||{}),Q=(r=>(r.OPEN="OPEN",r.CLOSE="CLOSE",r))(Q||{});function Qt(r){try{const s=JSON.parse(r),e={code:s.code,message:s.message,command:s.command,roomCode:s.room_code,appID:s.app_id,requestId:s.request_id,frontRequestId:s.front_request_id,triggerUserID:s.trigger_user_id,data:s.data||{}},i=Object.keys(e).filter(n=>e[n]===void 0);return i.length>0&&console.warn(`推送数据格式异常:${i.join(" ")} 值不存在!`),e}catch(s){return!1}}var $=(r=>(r[r.NOTINITIALIZED=-1]="NOTINITIALIZED",r[r.CONNECTING=0]="CONNECTING",r[r.OPEN=1]="OPEN",r[r.CLOSED=3]="CLOSED",r))($||{}),ft=(r=>(r[r.Normal=0]="Normal",r[r.Removed=1]="Removed",r[r.Replaced=2]="Replaced",r))(ft||{}),dt=(r=>(r.WAIT_ENTER="WAIT_ENTER",r.ONLINE="ONLINE",r.LEAVE="LEAVE",r.KICK_OUT="KICK_OUT",r.BE_REPLACE="BE_REPLACE",r.EXCEPTION="EXCEPTION",r))(dt||{}),be=(r=>(r[r.NOTINITIALIZED=-1]="NOTINITIALIZED",r[r.CONNECTING=0]="CONNECTING",r[r.OPEN=1]="OPEN",r[r.CLOSING=2]="CLOSING",r[r.CLOSED=3]="CLOSED",r))(be||{}),ht=(r=>(r.Error="Error",r.Close="Close",r.MicroAuth="MicroAuth",r.DuplicateConnect="DuplicateConnect",r.IllegalURL="IllegalURL",r.Unknown="Unknown",r.IllegalArgs="IllegalArgs",r))(ht||{}),_t=(r=>(r.Err_1000="CLOSE_NORMAL",r.Err_1001="CLOSE_GOING_AWAY",r.Err_1002="CLOSE_PROTOCOL_ERROR",r.Err_1003="CLOSE_UNSUPPORTED",r.Err_1006="CLOSE_ABNORMAL",r.Err_1007="Unsupported Data",r.Err_1008="Policy Violation",r.Err_1009="CLOSE_TOO_LARGE",r.Err_unknown="unknown",r))(_t||{});function gt(r){switch(r){case 1e3:return"CLOSE_NORMAL";case 1001:return"CLOSE_GOING_AWAY";case 1002:return"CLOSE_PROTOCOL_ERROR";case 1003:return"CLOSE_UNSUPPORTED";case 1006:return"CLOSE_ABNORMAL";case 1007:return"Unsupported Data";case 1008:return"Policy Violation";case 1009:return"CLOSE_TOO_LARGE"}return"unknown"}function er(r){return r&&r.__esModule&&Object.prototype.hasOwnProperty.call(r,"default")?r.default:r}var mt={};(function(r){Object.defineProperty(r,"__esModule",{value:!0}),r.LogLevel=void 0;var s;(function(e){e[e.DEBUG=0]="DEBUG",e[e.INFO=1]="INFO",e[e.WARN=2]="WARN",e[e.ERROR=3]="ERROR",e[e.OFF=4]="OFF"})(s=r.LogLevel||(r.LogLevel={})),r.default=s})(mt);const at=er(mt);function tr(r,s={}){const e=r.indexOf("?")!==-1,i=Object.keys(s).reduce((n,c,u)=>`${n}${u===0&&!e?"?":"&"}${c}=${s[c]}`,"");return r+i}const fe=globalThis.navigator.userAgent,rr=/android/gi.test(fe),ir=/iPhone|iPad\s+OS/gi.test(fe),nr=/MicroMessenger/gi.test(fe)&&/miniProgram/gi.test(fe),sr=/realsee/gi.test(fe);function Se(r){return Object.prototype.toString.call(r)==="[object Object]"}function Re(r,s){return r===s?!0:typeof r!=typeof s?!1:!!(Number.isNaN(r)&&Number.isNaN(s))}function or(r,s){const e=Object.getOwnPropertyNames(r),i=Object.getOwnPropertyNames(s);if(e.length!==i.length)return!1;for(let n=0,c=e.length;n<c;n++){const u=e[n];if(!Re(r[u],s[u]))return!1}return!0}function ar(r,s){if(r.length!==s.length)return!1;for(let e=0,i=r.length;e<i;e++)if(!Re(r[e],s[e]))return!1;return!0}function cr(r,s){return Re(r,s)?!0:Se(r)&&Se(s)?or(r,s):Array.isArray(r)&&Array.isArray(s)?ar(r,s):!1}function We(r,s){return Re(r,s)?!0:Se(r)&&Se(s)?lr(r,s):Array.isArray(r)&&Array.isArray(s)?ur(r,s):!1}function ur(r,s){if(r.length!==s.length)return!1;for(let e=0,i=r.length;e<i;e++)if(!We(r[e],s[e]))return!1;return!0}function lr(r,s){const e=Object.getOwnPropertyNames(r),i=Object.getOwnPropertyNames(s);if(e.length!==i.length)return!1;for(let n=0,c=e.length;n<c;n++){const u=e[n];if(!We(r[u],s[u]))return!1}return!0}function ct(r,s,e={deep:!1}){return e.deep?We(r,s):cr(r,s)}class fr extends le{constructor(e){super();o(this,"_realWebSocket");o(this,"_url");o(this,"_protocols");o(this,"_readyState",be.NOTINITIALIZED);o(this,"_options",{timeout:1e4,shouldReconnect:(e,i)=>{if(!(e.code===1008||e.code===1011))return[1e3,3e3,6e3][i.attempts%3]},should1000Reconnect:!1,ignoreConnectivityEvents:!1,automaticOpen:!1});o(this,"_connectTimeout");o(this,"_attempts",0);o(this,"_reconnects",-1);o(this,"_reconnectWhenOnlineAgain",!1);o(this,"_explicitlyClosed",!1);o(this,"_pendingReconnect");o(this,"_connectivityEventsAttached",!1);o(this,"_heathCheckTimer");o(this,"_healthCheck",async()=>{this._realWebSocket&&this._realWebSocket.readyState!==this._readyState&&(this._readyState=this._realWebSocket.readyState,this._readyState===be.CLOSING&&this.emit("closing")),await new Promise(e=>setTimeout(e,2e3)),this._heathCheckTimer=requestAnimationFrame(this._healthCheck)});o(this,"_clearConnectTimeoutIfNeed",()=>{this._connectTimeout&&(clearTimeout(this._connectTimeout),this._connectTimeout=void 0)});o(this,"_clearHeathCheckIfNeed",()=>{this._heathCheckTimer&&(cancelAnimationFrame(this._heathCheckTimer),this._heathCheckTimer=void 0)});o(this,"_startHealthCheck",()=>{this._clearHeathCheckIfNeed(),this._heathCheckTimer=requestAnimationFrame(this._healthCheck)});o(this,"_stopHealthCheck",()=>{this._clearHeathCheckIfNeed()});o(this,"_clearPendingReconnectIfNeeded",()=>{this._pendingReconnect&&(clearTimeout(this._pendingReconnect),this._pendingReconnect=void 0)});o(this,"_online",e=>{this._reconnectWhenOnlineAgain&&(this._clearPendingReconnectIfNeeded(),this._reconnect(e))});o(this,"_offline",()=>{var e;this._reconnectWhenOnlineAgain=!0,(e=this._realWebSocket)==null||e.close(1e3,"offline")});o(this,"_detachConnectivityEvents",()=>{this._connectivityEventsAttached&&(globalThis==null||globalThis.removeEventListener("online",this._online),globalThis==null||globalThis.removeEventListener("offline",this._offline),this._connectivityEventsAttached=!1)});o(this,"_attachConnectivityEvents",()=>{this._connectivityEventsAttached||(globalThis==null||globalThis.addEventListener("online",this._online),globalThis==null||globalThis.addEventListener("offline",this._offline),this._connectivityEventsAttached=!0)});o(this,"send",e=>{var i,n,c;((i=this._realWebSocket)==null?void 0:i.readyState)===((n=this._realWebSocket)==null?void 0:n.OPEN)&&((c=this._realWebSocket)==null||c.send(e))});o(this,"close",(e,i)=>{var n;return typeof e!="number"&&(i=e,e=1e3),this._clearPendingReconnectIfNeeded(),this._reconnectWhenOnlineAgain=!1,this._explicitlyClosed=!0,this._detachConnectivityEvents(),(n=this._realWebSocket)==null?void 0:n.close(e,i)});o(this,"open",e=>{var i,n;e&&(this._url=e),((i=this._realWebSocket)==null?void 0:i.readyState)!==WebSocket.OPEN&&((n=this._realWebSocket)==null?void 0:n.readyState)!==WebSocket.CONNECTING&&(this._clearPendingReconnectIfNeeded(),this._reconnectWhenOnlineAgain=!1,this._explicitlyClosed=!1,this._createWebSocket())});o(this,"_createWebSocket",()=>{var n,c,u;const e=typeof this._url=="string"?this._url:(n=this._url)==null?void 0:n.call(this,this);if(!e)return;this._clearConnectTimeoutIfNeed(),this._clearPendingReconnectIfNeeded(),this._removeWebSocketEvent(),this._realWebSocket=new WebSocket(e,this._protocols||void 0),this._attempts=this._attempts+1,this.emit("connecting",new CustomEvent("connecting",{detail:{attempts:this._attempts,reconnects:this._reconnects}}));const i=()=>{this._connectTimeout=void 0,this._detachConnectivityEvents(),this.emit("timeout",new CustomEvent("timeout",{detail:{attempts:this._attempts,reconnects:this._reconnects}}))};this._connectTimeout=setTimeout(i,(c=this._options)==null?void 0:c.timeout),this._dispatchWebSocketEvent(),(u=this._options)!=null&&u.ignoreConnectivityEvents||this._attachConnectivityEvents()});o(this,"_removeWebSocketEvent",()=>{var e,i,n,c;(e=this._realWebSocket)==null||e.removeEventListener("open",this._webSocketOpenHandler),(i=this._realWebSocket)==null||i.removeEventListener("close",this._webSocketCloseHandler),(n=this._realWebSocket)==null||n.removeEventListener("error",this._webSocketErrorHandler),(c=this._realWebSocket)==null||c.removeEventListener("message",this._webSocketMessageHandler)});o(this,"_dispatchWebSocketEvent",()=>{var e,i,n,c;(e=this._realWebSocket)==null||e.addEventListener("open",this._webSocketOpenHandler),(i=this._realWebSocket)==null||i.addEventListener("close",this._webSocketCloseHandler),(n=this._realWebSocket)==null||n.addEventListener("error",this._webSocketErrorHandler),(c=this._realWebSocket)==null||c.addEventListener("message",this._webSocketMessageHandler)});o(this,"_webSocketOpenHandler",e=>{this._connectTimeout&&(clearTimeout(this._connectTimeout),this._connectTimeout=void 0);const i=++this._reconnects,n=this._attempts;return this._attempts=0,this._reconnectWhenOnlineAgain=!1,this._startHealthCheck(),this.emit("open",Object.assign(e,{detail:{reconnects:i,attempts:n}}))});o(this,"_webSocketCloseHandler",e=>(this._reconnect(e),this._stopHealthCheck(),this.emit("close",e)));o(this,"_webSocketErrorHandler",e=>this.emit("error",new CustomEvent("error",{detail:{error:e}})));o(this,"_webSocketMessageHandler",e=>this.emit("message",e));e&&this.setOptions(e),this._startHealthCheck()}get attempts(){return this._attempts}setOptions(e){if(!e)return;this._url=e.url,this._protocols=e.protocols;const i=Object.assign(this._options,e.robustOptions||{});if(typeof(i==null?void 0:i.timeout)!="number")throw new Error("timeout must be the number of milliseconds to timeout a connection attempt");if(typeof(i==null?void 0:i.shouldReconnect)!="function")throw new Error("shouldReconnect must be a function that returns the number of milliseconds to wait for a reconnect attempt, or null or undefined to not reconnect.");this._options=i,this._options.automaticOpen&&this._createWebSocket()}_reconnect(e){var n,c,u,d;if(!((n=this._options)!=null&&n.should1000Reconnect)&&e.code===1e3||this._explicitlyClosed){this._attempts=0;return}if(this._connectivityEventsAttached&&((c=globalThis==null?void 0:globalThis.navigator)==null?void 0:c.onLine)===!1){this._reconnectWhenOnlineAgain=!0;return}const i=(d=(u=this._options)==null?void 0:u.shouldReconnect)==null?void 0:d.call(u,e,this);typeof i=="number"&&(this._pendingReconnect=setTimeout(this._createWebSocket,i))}}class dr extends le{constructor(){super();o(this,"_ws",new fr({url:"",robustOptions:{should1000Reconnect:!0,ignoreConnectivityEvents:!0}}));o(this,"_state",$.NOTINITIALIZED);o(this,"_addWebSocketEventListeners",()=>{this._ws.on("close",this._handleCloseEvent),this._ws.on("closing",this._handleClosingEvent),this._ws.on("connecting",this._handleConnectingEvent),this._ws.on("error",this._handleErrorEvent),this._ws.on("message",this._handleMessageEvent),this._ws.on("open",this._handleOpenEvent),this._ws.on("timeout",this._handleTimeoutEvent)});o(this,"_removeWebSocketEventListeners",()=>{this._ws.off("close",this._handleCloseEvent),this._ws.off("closing",this._handleClosingEvent),this._ws.off("connecting",this._handleConnectingEvent),this._ws.off("error",this._handleErrorEvent),this._ws.off("message",this._handleMessageEvent),this._ws.off("open",this._handleOpenEvent),this._ws.off("timeout",this._handleTimeoutEvent)});o(this,"_handleCloseEvent",e=>{O.info(`live room closed bacause of ${e.code}-${e.reason||gt(e.code)}`),this.state=$.CLOSED});o(this,"_handleClosingEvent",()=>{var e;O.info("live room is closing, onLine:",(e=globalThis==null?void 0:globalThis.navigator)==null?void 0:e.onLine),this.state=$.CLOSED});o(this,"_handleConnectingEvent",()=>{O.info("live room is connecting"),this.state=$.CONNECTING});o(this,"_handleErrorEvent",e=>{O.error("live room error",e),this.state=$.CLOSED});o(this,"_handleMessageEvent",e=>{let i=(()=>{try{return JSON.parse(e.data)}catch(n){return e.data}})();this.emit("message",i)});o(this,"_handleOpenEvent",e=>{O.info("live room open",e.detail),this.state=$.OPEN,e.detail.reconnects>0&&this.emit("reconnected",e.detail)});o(this,"_handleTimeoutEvent",e=>{O.error("live room connect timeout!",e.detail),this.state=$.CLOSED});o(this,"dispose",async()=>(this._removeWebSocketEventListeners(),await this.close("live room close by controller disposed!")));o(this,"open",e=>this._ws.open(e));o(this,"close",(e,i)=>new Promise(n=>{this._ws.once("close",()=>n(!0)),this._ws.close(e,i)}));this._addWebSocketEventListeners()}set state(e){const i=JSON.parse(JSON.stringify(this._state));this._state=e,this.emit("stateChange",this.state,i)}get state(){return this._state}sendMessage(e=""){if(e==null||e==="")throw new Error("live message is empty!");if(this.state===$.OPEN)return this._ws.send(JSON.stringify(e));throw new Error("live has not yet been initialized!")}}const hr=r=>Promise.reject("unimplemented method GetVoiceSign"),Me=(r,s={},e=[])=>({command:r,front_request_id:ye(),data:{...s,to_user_ids:Array.isArray(e)?e:[e]}}),_r=()=>{var r,s;window!=null&&window.__Realsee_Live__&&((s=(r=window==null?void 0:window.__Realsee_Live__)==null?void 0:r.dispose)==null||s.call(r),window.__Realsee_Live__=null)};class gr extends le{constructor(e){var i;super();o(this,"_options",{});o(this,"keyframes",new le);o(this,"_buildInData",{keyframes:{}});o(this,"getFramesByKey",e=>this.snapshot[e]);o(this,"sendKeyframe",(e,i)=>{if(this.state!==$.OPEN)return!1;this._buildInData.keyframes={...this._buildInData.keyframes,[e]:i};const n=Me(U.KeyframeSync,this.snapshot);try{return this._controller.sendMessage(n),!0}catch(c){return O.error(c),!1}});o(this,"_controller",new dr);o(this,"_addLiveControllerEventListeners",()=>{this._controller.on("stateChange",this._handleStateChange),this._controller.on("message",this._handleMessage)});o(this,"_removeLiveControllerEventListeners",()=>{this._controller.off("stateChange",this._handleStateChange),this._controller.off("message",this._handleMessage)});o(this,"_handleStateChange",(e,i)=>this.emit("stateChange",e,i));o(this,"_handleMessage",async e=>{var i,n,c,u,d;if(typeof e=="object"){const{command:g,data:v={},frontRequestId:E,code:y,message:I}=e;if(y==="SUCCESS")switch(g){case U.SelfUserInfo:{const _=v;ct(this.selfInfo,_,{deep:!0})||(this._buildInData.selfInfo=_,this.emit("selfInfoUpdate",this._buildInData.selfInfo,E));break}case U.RoomInfo:{const _=v;this._buildInData.roomInfo=Object.assign({},_),this.emit("readyKeyframeSync",_.last_frame||{});break}case U.RTCInfo:{const{voice_id:_,type:V}=v;if(this._buildInData.rtcInfo={voiceId:_,type:V},(i=this.$RTC)!=null&&i.joined)O.warn("已加入语音房间,无需重复加入!");else if(await((u=this.$RTC)==null?void 0:u.join({voiceId:_,userId:((n=this.selfInfo)==null?void 0:n.id)||"",roomId:(c=this.roomInfo)==null?void 0:c.info.room_code,type:V}))){const k=(d=this._options.initialMicroStatus)!=null?d:Q.OPEN;await this.toggleMicro(k===Q.OPEN)}else O.error("加入语音房间失败");break}case U.UserList:{const _=v;this._buildInData.userList=_,this.emit("userListUpdate",this.userList,E);break}case U.CustomEvent:{const _=v;this.emit("broadcast",_,E);break}case U.KeyframeSync:{const _=v,V=Object.keys(_).reduce((C,k)=>{if(ct(_[k],this._buildInData.keyframes[k],{deep:!0}))return C;const B=[_[k],this._buildInData.keyframes[k],E],P=k;return this.keyframes.emit(P,...B),this._buildInData.keyframes[k]=_[k],C[k]=_[k],C},{});this.emit("keyframes",V,E);break}case U.BuiltinMsg:{const _=v;this.emit("builtinEvent",_),_.event_type===K.UserChange&&this.emit("userChange",_),_.event_type===K.RoomChange&&this.emit("roomChange",_),_.event_type===K.UserChange&&_.action===Y.UserMicroStatus&&await this.toggleMicro(_.data.status===Q.OPEN),_.event_type===K.RoomChange&&_.action===Y.RoomClose&&await this.exit();break}case U.UserKickOut:{this.emit("kickOut");break}default:console.warn("unknown command: ",g)}else this.emit("error",e)}});o(this,"_clearLiveData",()=>{this._buildInData={keyframes:{}}});o(this,"connect",async(e={})=>{var u,d,g,v;if(this._options.url=(d=(u=e.url)!=null?u:this._options.url)!=null?d:"",this._options.getTicket=(g=e.getTicket)!=null?g:this._options.getTicket,this._options.initialMicroStatus=(v=e.rtcMicStatus)!=null?v:this._options.initialMicroStatus,!/^ws(s):\/\//.test(this._options.url)||typeof this._options.getTicket!="function")return/^ws(s):\/\//.test(this._options.url)?typeof this._options.getTicket!="function"?new Error("getTicket muse be function"):!1:new Error("Illegal realsee live room link");const{force:i=!1}=e;if(this._options.rtc&&!await this._options.rtc.detectMicro())return new Error("Failed to obtain microphone authorization");const n=this.state;if(n===$.CONNECTING||n===$.OPEN)if(i)try{await this._controller.close("force close by connect")}catch(E){console.warn(E)}else return new Error("已有Live实例正在连接中,请勿重复连接!");this._clearLiveData();const c=tr(this._options.url,{ticket:await this._options.getTicket(),force:Number(!!i)});return this._controller.open(c),!0});o(this,"exit",async()=>{var e;if(this._clearLiveData(),this.state!==$.OPEN)return!0;try{await((e=this.$RTC)==null?void 0:e.quit())}catch(i){O.warn(i)}return await this._controller.close()});o(this,"close",async()=>await this.updateStatus(K.RoomChange,Y.RoomClose,{}));o(this,"dispose",async()=>(this._removeLiveControllerEventListeners(),this._clearLiveData(),await this._controller.dispose()));o(this,"setSelfInfo",async e=>await this.updateStatus(K.UserChange,Y.UserInfo,e));o(this,"toggleMicro",async e=>{var n,c,u;if(!((c=(n=this.selfInfo)==null?void 0:n.permission)!=null&&c.control_own_micro))return!1;const i=await((u=this.$RTC)==null?void 0:u.toggleMicro(e));return i&&await this.updateStatus(K.UserChange,Y.UserMicroStatus,{status:e?Q.OPEN:Q.CLOSE},[]),i});o(this,"forbidMicro",async(e,i)=>{var n,c;return typeof this._options.canForbidUserMicro=="function"&&!this._options.canForbidUserMicro(i)||!((c=(n=this.selfInfo)==null?void 0:n.permission)!=null&&c.control_other_micro)?!1:await this.updateStatus(K.UserChange,Y.UserMicroStatus,{status:e},i)});o(this,"forbidSync",async(e,i)=>{var n,c;return typeof this._options.canForbidUserSync=="function"&&!this._options.canForbidUserSync(i)||!((c=(n=this.selfInfo)==null?void 0:n.permission)!=null&&c.control_other_sync)?!1:await this.updateStatus(K.UserChange,Y.UserPermission,{sync_frame:e},i)});o(this,"kick",async e=>{var i,n;return typeof this._options.canForbidUserKick=="function"&&!this._options.canForbidUserKick(e)||!((n=(i=this.selfInfo)==null?void 0:i.permission)!=null&&n.change_other_status)?!1:await this.updateStatus(K.UserChange,Y.UserStatus,{status:"KICK_OUT"},e)});this._addLiveControllerEventListeners(),this._options=Object.assign({initialMicroStatus:Q.OPEN},e),this._options.jsBridge=(()=>{if(e.jsBridge)return e.jsBridge;if(e.useBuiltInJsBridge)return new Kt})(),this._options.getVoiceSign=(i=e.getVoiceSign)!=null?i:hr,this._options.autoPlayConfirm=e.autoPlayConfirm,this._options.rtc=(()=>{if(e.rtc)return e.rtc;if(e.rtcType)switch(e.getVoiceSign||O.error("GetVoiceSign method must be passed when using built-in RTC instances"),e.rtcType){case ee.RealseeVRWebViewRTC:{if(this._options.jsBridge)return new $e({jsBridge:this._options.jsBridge,getVoiceSign:this._options.getVoiceSign});O.error("JsBridge instance must be passed when using built-in VRWebViewRTC instances");return}case ee.RealseeBrowserChimeRTC:return new Ve({getVoiceSign:this._options.getVoiceSign,logLevel:e.__debug__?at.DEBUG:at.INFO});case ee.RealseeBrowserRTC:return this._options.autoPlayConfirm||O.error("autoPlayConfirm method must be passed when using built-in RealseeBrowserRTC instances"),new De({getVoiceSign:this._options.getVoiceSign,autoPlayConfirm:this._options.autoPlayConfirm});default:{O.error("unknown built-in RTC type");return}}if(e.useBuiltInRTC){if(e.getVoiceSign||O.error("GetVoiceSign method must be passed when using built-in RTC instances"),this._options.jsBridge)return sr&&(rr||ir)||nr?new $e({jsBridge:this._options.jsBridge,getVoiceSign:this._options.getVoiceSign}):e.builtInRTCType===Ue.RealseeXChimeRTC?new Ve({getVoiceSign:this._options.getVoiceSign}):new De({getVoiceSign:this._options.getVoiceSign,autoPlayConfirm:this._options.autoPlayConfirm});O.error("jsBridge instance must be passed when using built-in RTC instances");return}})(),this._options.rtc||O.warn("unused rtc"),this._options.url&&this._options.getTicket&&this.connect(),this._options.__debug__&&Object.assign(window,{$liveController:this._controller,$live:this})}get options(){return Object.freeze(this._options||{})}get state(){return this._controller.state}get readyState(){return this._controller.state}get url(){return this.options.url}get $RTC(){return this._options.rtc}get jsBridge(){return this._options.jsBridge}get snapshot(){return this._buildInData.keyframes}get selfInfo(){return this._buildInData.selfInfo}get userList(){return this._buildInData.userList||[]}get roomInfo(){return this._buildInData.roomInfo}async updateStatus(e,i,n,c){if(this.state!==$.OPEN)return!1;const u=Object.assign({event_type:e,action:i},{data:n}),d=Me(U.BuiltinMsg,u,c);try{return this._controller.sendMessage(d),!0}catch(g){return O.error(g),!1}}broadcast(e,i,n){return this.state!==$.OPEN?!1:new Promise((c,u)=>{const d=Me(U.CustomEvent,e,i),g=d.front_request_id,v=n?setTimeout(()=>{u(new Error("RESPONSE TIMEOUT")),this.off("broadcast",E)},n):void 0,E=(y,I)=>{I===g&&(v&&clearTimeout(v),this.off("broadcast",E),c(y))};this.on("broadcast",E);try{this._controller.sendMessage(d)}catch(y){u(y)}})}}const vt=r=>(_r(),new gr(r));var xe={},mr={get exports(){return xe},set exports(r){xe=r}},ae={};/**
|
|
1
|
+
"use strict";var Ft=Object.defineProperty;var qt=(r,s,e)=>s in r?Ft(r,s,{enumerable:!0,configurable:!0,writable:!0,value:e}):r[s]=e;var o=(r,s,e)=>(qt(r,typeof s!="symbol"?s+"":s,e),e);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const Kt=require("@realsee/jsbridge-x"),Ae=require("trtc-js-sdk"),X=require("amazon-chime-sdk-js"),D=require("react"),ue=Symbol("$$REALSEE_LIVE_EVENT$$");function Ee(r){return r[ue]||(r[ue]={}),r[ue]}function Gt(r){r[ue]||delete r[ue]}class le{hasListener(s){const e=Ee(this);return e&&e[s]&&e[s].length>0}on(s,e,i){const n=Ee(this);return n[s]||(n[s]=[]),n[s].push([e,i||!1]),()=>this.off(s,e)}once(s,e){return this.on(s,e,!0)}off(s,e){if(s===void 0){Gt(this);return}const i=Ee(this);if(i[s]||(i[s]=[]),e===void 0){i[s].length=0;return}let n=0;for(;n<i[s].length&&i[s][n][0]!==e;n++);n<i[s].length&&i[s].splice(n,1)}emit(s,...e){let i=!1;const c=Ee(this)[s]||[];for(let u of c.slice()){const[d,g=!1]=u,v=d(...e);g&&this.off(s,d),v===!1&&(i=!0)}return i}}class Ce extends le{}var ee=(r=>(r.RealseeBrowserRTC="RealseeBrowserRTC",r.RealseeVRWebViewRTC="RealseeVRWebViewRTC",r.RealseeBrowserChimeRTC="RealseeBrowserChimeRTC",r))(ee||{}),Ue=(r=>(r.RealseeXTRTC="trtc",r.RealseeXChimeRTC="chime",r))(Ue||{});const Yt=()=>{const r=new Date,s=r.getFullYear(),e=(r.getMonth()+1).toString().padStart(2,"0"),i=r.getDate().toString().padStart(2,"0"),n=r.getHours().toString().padStart(2,"0"),c=r.getMinutes().toString().padStart(2,"0"),u=r.getSeconds().toString().padStart(2,"0"),d=r.getMilliseconds();return`[${s}-${e}-${i} ${n}:${c}:${u}.${d}]`},we=(r,s=[])=>{switch(s.unshift(`Realsee Live ${Yt()} <${r}> `),r){case"INFO":return console.info(...s);case"ERROR":return console.error(...s);case"WARN":return console.warn(...s);default:return console.log(...s)}},Ht=(...r)=>we("LOG",r),Jt=(...r)=>we("INFO",r),zt=(...r)=>we("ERROR",r),Xt=(...r)=>we("WARN",r),Zt={log:Ht,info:Jt,error:zt,warn:Xt},O=Zt;function Z(){return((1+Math.random())*65536|0).toString(16).substring(1)}function ye(){return(Z()+Z()+"-"+Z()+"-4"+Z().substr(0,3)+"-"+Z()+"-"+Z()+Z()+Z()).toLowerCase()}class De extends Ce{constructor(e){super();o(this,"type",ee.RealseeBrowserRTC);o(this,"joined",!1);o(this,"micro",!1);o(this,"voiceId","");o(this,"_getVoiceSign",()=>{throw new Error("方法 getVoiceSign 未实现")});o(this,"_autoPlayConfirm");o(this,"checkRequirement",()=>Ae.checkSystemRequirements());o(this,"$dom",document.createElement("div"));o(this,"_trtc",{client:null,stream:null});o(this,"join",async e=>{var c;this.emit("joinWillStart");const i=await this._getVoiceSign({voiceId:e.voiceId,roomId:e.roomId,userId:e.userId});this._trtc.client=Ae.createClient({mode:"rtc",...i,enableAutoPlayDialog:typeof this._autoPlayConfirm!="function"}),(c=this._trtc.client)==null||c.enableAudioVolumeEvaluation(),this._registerRtcEvent();let n=await new Promise(u=>{var d;(d=this._trtc.client)==null||d.join({roomId:Number(e.voiceId)}).then(()=>u(!0)).catch(()=>u(!1))});return this.joined=n,n?(this._trtc.stream=Ae.createStream({userId:i.userId,audio:!0,video:!1}),n=await new Promise(u=>{var d;(d=this._trtc.stream)==null||d.initialize().then(()=>u(!0)).catch(()=>u(!1))}),n=await new Promise(u=>{var d;(d=this._trtc.client)==null||d.publish(this._trtc.stream).then(()=>u(!0)).catch(()=>u(!1))}),this.joined=n,this.joined&&this.emit("joined"),n):!1});o(this,"_handleStreamAdded",e=>{var n;const i=e.stream;console.log("远端流增加: "+i.getId()),(n=this._trtc.client)==null||n.subscribe(i)});o(this,"_handleStreamSubscribed",e=>{const i=e.stream;console.log("远端流订阅成功:"+i.getId());const c=`rs-rtc-remote_stream-${i.getId()}`,u=document.createElement("div");u.id=c,this.$dom.appendChild(u),typeof this._autoPlayConfirm=="function"?(i.play(c).catch(d=>{}),i.on("error",d=>{if(d.getCode()===16451){const v=()=>i.resume();this._autoPlayConfirm({onConfirm:v})}})):i.play(c)});this._getVoiceSign=e.getVoiceSign,this._autoPlayConfirm=e.autoPlayConfirm,this._initParentDom()}_initParentDom(){this.$dom.id=`rs-rtc-${ye()}`,this.$dom.style.display="none",document.body.appendChild(this.$dom)}quit(){return new Promise(async e=>{var i,n;this.joined=!1,this._trtc.stream&&(await((i=this._trtc.client)==null?void 0:i.unpublish(this._trtc.stream)),this._trtc.stream.stop(),this._trtc.stream.close(),this._trtc.stream=null),(n=this._trtc.client)==null||n.leave().then(()=>this._trtc.client=null).then(()=>e(!0)).catch(()=>e(!1)),e(!0)})}detectMicro(){return new Promise(e=>{const i={audio:!0,video:!1};try{navigator.mediaDevices.getUserMedia(i).then(()=>e(!0)).catch(n=>{O.error(n.message),e(!1)})}catch(n){console.error(n),e(!1)}})}toggleMicro(e){var i,n,c,u;return Promise.resolve((e?(n=(i=this._trtc)==null?void 0:i.stream)==null?void 0:n.unmuteAudio():(u=(c=this._trtc)==null?void 0:c.stream)==null?void 0:u.muteAudio())||!1)}shock(){throw new Error("Method not implemented.")}_registerRtcEvent(){var e,i,n,c;(e=this._trtc.client)==null||e.on("stream-added",this._handleStreamAdded),(i=this._trtc.client)==null||i.on("stream-subscribed",this._handleStreamSubscribed),(n=this._trtc.client)==null||n.on("audio-volume",u=>this.emit("userVolumes",u.result.map(({userId:d,audioVolume:g})=>({userId:d,audioVolume:g})))),(c=this._trtc.client)==null||c.on("error",u=>this.emit("error",u))}}class Ve extends Ce{constructor(e){super();o(this,"type",ee.RealseeBrowserChimeRTC);o(this,"joined",!1);o(this,"micro",!1);o(this,"voiceId","");o(this,"userId","");o(this,"logger");o(this,"deviceController");o(this,"meetingSession");o(this,"audioInput");o(this,"audioOutput");o(this,"deviceChangeObserver",{});o(this,"audioVideoObserver",{});o(this,"audioMixObserver");o(this,"_getVoiceSign",()=>{throw new Error("方法 getVoiceSign 未实现")});o(this,"_autoPlayConfirm");o(this,"$dom",document.createElement("div"));o(this,"$audio",document.createElement("audio"));o(this,"_initDom",()=>{this.$audio.id=`rs-rtc-${ye()}`,this.$dom.id=`rs-rtc-${ye()}`,this.$dom.appendChild(this.$audio),document.body.appendChild(this.$dom)});o(this,"initObservers",()=>{this.deviceChangeObserver={audioInputsChanged:e=>{this.logger.info(`audioInputsChanged ${typeof e}`),e==null||e.forEach(i=>{this.logger.info(`Device ID: ${i.deviceId} Microphone: ${i.label}`)})},audioOutputsChanged:e=>{this.logger.info(`audioOutputsChanged ${typeof e}`),e==null||e.forEach(i=>{this.logger.info(`Device ID: ${i.deviceId} Speaker: ${i.label}`)})},audioInputMuteStateChanged:(e,i)=>{this.logger.info(`Device ${e.toString()} ${i?"is muted in hardware":"is not muted"}`)}},this.audioVideoObserver={audioVideoDidStart:()=>{this.logger.info("Started")},audioVideoDidStop:e=>{this.logger.info(`Stopped with a session status code: ${e.statusCode()}`)},audioVideoDidStartConnecting:e=>{e&&this.logger.info("Attempting to reconnect")}},this.audioMixObserver={meetingAudioStreamBecameActive:e=>{if(this.$audio.paused){const i=()=>this.$audio.play().then(()=>{}).catch(n=>{if(O.error("播放远端流失败!",n),typeof this._autoPlayConfirm=="function"){const c=()=>i();this._autoPlayConfirm({onConfirm:c})}});i()}},meetingAudioStreamBecameInactive:e=>{}}});o(this,"_registerRtcEvent",()=>{var i,n,c,u,d,g;const e=((c=(n=(i=this.meetingSession)==null?void 0:i.configuration)==null?void 0:n.credentials)==null?void 0:c.attendeeId)||"";if(e){const v=new Map,E=()=>{const y=[];return v.forEach((I,_)=>{y.push({userId:I.userId,volume:I.muted||I.signalStrength===0||!Boolean(I.volume)?0:I.volume})}),y};(u=this.meetingSession)==null||u.audioVideo.realtimeSubscribeToAttendeeIdPresence((y,I,_)=>{var V;if(!I){v.delete(y),this.emit("userVolumes",E());return}(V=this.meetingSession)==null||V.audioVideo.realtimeSubscribeToVolumeIndicator(y,(C,k,B,P)=>{new X.DefaultModality(C).base()===C&&(v.set(C,{userId:_||C,volume:k,muted:B,signalStrength:P}),this.emit("userVolumes",E()))})}),(d=this.meetingSession)==null||d.audioVideo.realtimeSubscribeToVolumeIndicator(e,(y,I,_,V)=>{new X.DefaultModality(y).base()===y&&V!==null&&V!==1&&this.emit("weakNetwork")}),(g=this.meetingSession)==null||g.audioVideo.realtimeSubscribeToFatalError(y=>this.emit("error",y))}});this._getVoiceSign=e.getVoiceSign,this._autoPlayConfirm=e.autoPlayConfirm,this._initDom(),this.logger=new X.ConsoleLogger("WebRTCLogger",e.logLevel||X.LogLevel.INFO),this.deviceController=new X.DefaultDeviceController(this.logger),this.initObservers()}async join(e){return new Promise(async(i,n)=>{var c,u;this.emit("joinWillStart");try{const{sdkAppId:d,userId:g,roomId:v,userSig:E}=await this._getVoiceSign({...e,roomId:e.roomId||0});this.userId=g;const{attendence:y,vendor_wrapper:I}=JSON.parse(decodeURIComponent(E)),_=new X.MeetingSessionConfiguration({Meeting:I},{Attendee:{ExternalUserId:y.external_user_id,AttendeeId:y.attendee_id,JoinToken:y.join_token}});this.meetingSession=new X.DefaultMeetingSession(_,this.logger,this.deviceController),this._registerRtcEvent(),this.meetingSession.audioVideo.addDeviceChangeObserver(this.deviceChangeObserver),this.meetingSession.audioVideo.addObserver(this.audioVideoObserver),this.meetingSession.audioVideo.bindAudioElement(this.$audio);const V={audioVideoDidStart:()=>{var C;(C=this.meetingSession)==null||C.audioVideo.realtimeMuteLocalAudio(),this.joined=!0,this.emit("joined"),i(!0)},audioVideoDidStop:()=>{this.joined=!1,i(!1)}};this.meetingSession.audioVideo.addObserver(V),this.audioMixObserver&&this.meetingSession.audioVideo.addAudioMixObserver(this.audioMixObserver),this.meetingSession.audioVideo.setDeviceLabelTrigger(async()=>await navigator.mediaDevices.getUserMedia({audio:!0,video:!1}));try{const C=await this.meetingSession.audioVideo.listAudioInputDevices();O.info("audioInputDevices ===>",C);const k=((c=C[0])==null?void 0:c.deviceId)||"default";await this.meetingSession.audioVideo.startAudioInput(k)}catch(C){O.error(`设置语音输入设备失败:${C.message}`)}try{const C=await this.meetingSession.audioVideo.listAudioOutputDevices();O.info("audioOutputDevices ===>",C);const k=((u=C[0])==null?void 0:u.deviceId)||"default";await this.meetingSession.audioVideo.chooseAudioOutput(k)}catch(C){O.error(`设置语音输出设备失败:${C.message}`)}this.meetingSession.audioVideo.start()}catch(d){this.emit("error",d),this.logger.error(d.message),i(!1)}})}quit(){return this.joined?new Promise((e,i)=>{var c,u;this.joined=!1;const n={audioVideoDidStop:async d=>{var v;const g=d.statusCode();(v=this.meetingSession)==null||v.deviceController.destroy(),g===X.MeetingSessionStatusCode.Left?(this.logger.info("You left the session"),e(!0)):(this.logger.info(`Stopped with a session status code: ${g}`),e(!0))}};(c=this.meetingSession)==null||c.audioVideo.addObserver(n),(u=this.meetingSession)==null||u.audioVideo.stop()}):Promise.resolve(!0)}async detectMicro(){return new Promise(e=>{const i={audio:!0,video:!1};try{navigator.mediaDevices.getUserMedia(i).then(()=>e(!0)).catch(()=>e(!1))}catch(n){this.logger.error(n.message),e(!1)}})}async toggleMicro(e){var n,c,u;e?(n=this.meetingSession)==null||n.audioVideo.realtimeUnmuteLocalAudio():(c=this.meetingSession)==null||c.audioVideo.realtimeMuteLocalAudio();const i=(u=this.meetingSession)==null?void 0:u.audioVideo.realtimeIsLocalAudioMuted();return i!==void 0?e!==i:!1}shock(){throw new Error("Method not implemented.")}}var Be=(r=>(r[r.Success=0]="Success",r[r.Failure=1]="Failure",r[r.ReJoin=2]="ReJoin",r[r.NoMicroPermission=3]="NoMicroPermission",r))(Be||{});class $e extends Ce{constructor({jsBridge:e,getVoiceSign:i}){super();o(this,"type",ee.RealseeVRWebViewRTC);o(this,"joined",!1);o(this,"micro",!1);o(this,"voiceId","");o(this,"options");this.options={jsBridge:e,getVoiceSign:i},this.jsBridge.webViewType!=="WxMiniProgramWebView"&&this.jsBridge.callAndListen("live/userVolumes",n=>{this.emit("userVolumes",n)}),this.jsBridge.callAndListen("live/weakNetwork",n=>{n&&this.emit("weakNetwork")})}get jsBridge(){return this.options.jsBridge}async join(e){try{this.emit("joinWillStart");const{sdkAppId:i,userId:n,userSig:c}=await this.options.getVoiceSign(e);if(!(Boolean(i)&&Boolean(n)&&Boolean(c)))return this.emit("error",new Error("加入房间失败:rtc 签名请求异常")),this.joined=!1,this.joined;this.type=e.type;const[u,d]=await this.jsBridge.callAndBackfeed(`live/join?sdkAppID=${i}&userID=${n}&roomID=${Number(e.voiceId)}&userSig=${c}`);return u===!0?(this.emit("joined"),this.joined=!0):u?u.code===Be.Success?(this.emit("joined"),this.joined=!0):(this.emit("error",u),this.joined=!1):(this.emit("error",d||new Error("加入房间失败:未知异常。")),this.joined=!1),this.joined}catch(i){return this.emit("error",new Error("加入房间失败:"+i.message)),this.joined=!1,this.joined}}async quit(){const[e,i]=await this.jsBridge.callAndBackfeed("live/quit");return e===null&&this.emit("error",i||new Error("退出房间失败:未知异常。")),this.joined=!1,!!e}async detectMicro(){const[e,i]=await this.jsBridge.detectMicro();return e===null?(this.emit("error",i||new Error("麦克风监测异常!")),!1):e}async toggleMicro(e){const[i,n]=await this.jsBridge.callAndBackfeed(`live/toggleMicro?flag=${e?1:0}`);return i===null?(this.emit("error",n||new Error("麦克风监测异常!")),!1):(this.micro=i,i)}shock(){this.jsBridge.shock(1)}}var U=(r=>(r.SelfUserInfo="SELF_USER_INFO",r.RoomInfo="ROOM_INFO",r.RTCInfo="RTC_INFO",r.UserList="USER_LIST",r.BuiltinMsg="BUILTIN_MSG",r.CustomEvent="CUSTOM_EVENT",r.KeyframeSync="KEYFRAME_SYNC",r.UserKickOut="USER_KICK_OUT",r))(U||{}),K=(r=>(r.UserChange="user_change",r.RoomChange="room_change",r))(K||{}),Y=(r=>(r.UserMicroStatus="change_micro_status",r.UserMicroStatusSync="sync_micro_status",r.UserPermission="change_permission",r.UserStatus="change_status",r.UserInfo="change_info",r.RoomClose="close",r))(Y||{}),Q=(r=>(r.OPEN="OPEN",r.CLOSE="CLOSE",r))(Q||{});function Qt(r){try{const s=JSON.parse(r),e={code:s.code,message:s.message,command:s.command,roomCode:s.room_code,appID:s.app_id,requestId:s.request_id,frontRequestId:s.front_request_id,triggerUserID:s.trigger_user_id,data:s.data||{}},i=Object.keys(e).filter(n=>e[n]===void 0);return i.length>0&&console.warn(`推送数据格式异常:${i.join(" ")} 值不存在!`),e}catch(s){return!1}}var $=(r=>(r[r.NOTINITIALIZED=-1]="NOTINITIALIZED",r[r.CONNECTING=0]="CONNECTING",r[r.OPEN=1]="OPEN",r[r.CLOSED=3]="CLOSED",r))($||{}),ft=(r=>(r[r.Normal=0]="Normal",r[r.Removed=1]="Removed",r[r.Replaced=2]="Replaced",r))(ft||{}),dt=(r=>(r.WAIT_ENTER="WAIT_ENTER",r.ONLINE="ONLINE",r.LEAVE="LEAVE",r.KICK_OUT="KICK_OUT",r.BE_REPLACE="BE_REPLACE",r.EXCEPTION="EXCEPTION",r))(dt||{}),be=(r=>(r[r.NOTINITIALIZED=-1]="NOTINITIALIZED",r[r.CONNECTING=0]="CONNECTING",r[r.OPEN=1]="OPEN",r[r.CLOSING=2]="CLOSING",r[r.CLOSED=3]="CLOSED",r))(be||{}),ht=(r=>(r.Error="Error",r.Close="Close",r.MicroAuth="MicroAuth",r.DuplicateConnect="DuplicateConnect",r.IllegalURL="IllegalURL",r.Unknown="Unknown",r.IllegalArgs="IllegalArgs",r))(ht||{}),_t=(r=>(r.Err_1000="CLOSE_NORMAL",r.Err_1001="CLOSE_GOING_AWAY",r.Err_1002="CLOSE_PROTOCOL_ERROR",r.Err_1003="CLOSE_UNSUPPORTED",r.Err_1006="CLOSE_ABNORMAL",r.Err_1007="Unsupported Data",r.Err_1008="Policy Violation",r.Err_1009="CLOSE_TOO_LARGE",r.Err_unknown="unknown",r))(_t||{});function gt(r){switch(r){case 1e3:return"CLOSE_NORMAL";case 1001:return"CLOSE_GOING_AWAY";case 1002:return"CLOSE_PROTOCOL_ERROR";case 1003:return"CLOSE_UNSUPPORTED";case 1006:return"CLOSE_ABNORMAL";case 1007:return"Unsupported Data";case 1008:return"Policy Violation";case 1009:return"CLOSE_TOO_LARGE"}return"unknown"}function er(r){return r&&r.__esModule&&Object.prototype.hasOwnProperty.call(r,"default")?r.default:r}var mt={};(function(r){Object.defineProperty(r,"__esModule",{value:!0}),r.LogLevel=void 0;var s;(function(e){e[e.DEBUG=0]="DEBUG",e[e.INFO=1]="INFO",e[e.WARN=2]="WARN",e[e.ERROR=3]="ERROR",e[e.OFF=4]="OFF"})(s=r.LogLevel||(r.LogLevel={})),r.default=s})(mt);const at=er(mt);function tr(r,s={}){const e=r.indexOf("?")!==-1,i=Object.keys(s).reduce((n,c,u)=>`${n}${u===0&&!e?"?":"&"}${c}=${s[c]}`,"");return r+i}const fe=globalThis.navigator.userAgent,rr=/android/gi.test(fe),ir=/iPhone|iPad\s+OS/gi.test(fe),nr=/MicroMessenger/gi.test(fe)&&/miniProgram/gi.test(fe),sr=/realsee/gi.test(fe);function Se(r){return Object.prototype.toString.call(r)==="[object Object]"}function Re(r,s){return r===s?!0:typeof r!=typeof s?!1:!!(Number.isNaN(r)&&Number.isNaN(s))}function or(r,s){const e=Object.getOwnPropertyNames(r),i=Object.getOwnPropertyNames(s);if(e.length!==i.length)return!1;for(let n=0,c=e.length;n<c;n++){const u=e[n];if(!Re(r[u],s[u]))return!1}return!0}function ar(r,s){if(r.length!==s.length)return!1;for(let e=0,i=r.length;e<i;e++)if(!Re(r[e],s[e]))return!1;return!0}function cr(r,s){return Re(r,s)?!0:Se(r)&&Se(s)?or(r,s):Array.isArray(r)&&Array.isArray(s)?ar(r,s):!1}function We(r,s){return Re(r,s)?!0:Se(r)&&Se(s)?lr(r,s):Array.isArray(r)&&Array.isArray(s)?ur(r,s):!1}function ur(r,s){if(r.length!==s.length)return!1;for(let e=0,i=r.length;e<i;e++)if(!We(r[e],s[e]))return!1;return!0}function lr(r,s){const e=Object.getOwnPropertyNames(r),i=Object.getOwnPropertyNames(s);if(e.length!==i.length)return!1;for(let n=0,c=e.length;n<c;n++){const u=e[n];if(!We(r[u],s[u]))return!1}return!0}function ct(r,s,e={deep:!1}){return e.deep?We(r,s):cr(r,s)}class fr extends le{constructor(e){super();o(this,"_realWebSocket");o(this,"_url");o(this,"_protocols");o(this,"_readyState",be.NOTINITIALIZED);o(this,"_options",{timeout:1e4,shouldReconnect:(e,i)=>{if(!(e.code===1008||e.code===1011))return[0,1e3,2e3][i.attempts%3]},should1000Reconnect:!1,ignoreConnectivityEvents:!1,automaticOpen:!1});o(this,"_connectTimeout");o(this,"_attempts",0);o(this,"_reconnects",-1);o(this,"_reconnectWhenOnlineAgain",!1);o(this,"_explicitlyClosed",!1);o(this,"_pendingReconnect");o(this,"_connectivityEventsAttached",!1);o(this,"_heathCheckTimer");o(this,"_healthCheck",async()=>{this._realWebSocket&&this._realWebSocket.readyState!==this._readyState&&(this._readyState=this._realWebSocket.readyState,this._readyState===be.CLOSING&&this.emit("closing")),await new Promise(e=>setTimeout(e,2e3)),this._heathCheckTimer=requestAnimationFrame(this._healthCheck)});o(this,"_clearConnectTimeoutIfNeed",()=>{this._connectTimeout&&(clearTimeout(this._connectTimeout),this._connectTimeout=void 0)});o(this,"_clearHeathCheckIfNeed",()=>{this._heathCheckTimer&&(cancelAnimationFrame(this._heathCheckTimer),this._heathCheckTimer=void 0)});o(this,"_startHealthCheck",()=>{this._clearHeathCheckIfNeed(),this._heathCheckTimer=requestAnimationFrame(this._healthCheck)});o(this,"_stopHealthCheck",()=>{this._clearHeathCheckIfNeed()});o(this,"_clearPendingReconnectIfNeeded",()=>{this._pendingReconnect&&(clearTimeout(this._pendingReconnect),this._pendingReconnect=void 0)});o(this,"_online",e=>{this._reconnectWhenOnlineAgain&&(this._clearPendingReconnectIfNeeded(),this._reconnect(e))});o(this,"_offline",()=>{var e;this._reconnectWhenOnlineAgain=!0,(e=this._realWebSocket)==null||e.close(1e3,"offline")});o(this,"_detachConnectivityEvents",()=>{this._connectivityEventsAttached&&(globalThis==null||globalThis.removeEventListener("online",this._online),globalThis==null||globalThis.removeEventListener("offline",this._offline),this._connectivityEventsAttached=!1)});o(this,"_attachConnectivityEvents",()=>{this._connectivityEventsAttached||(globalThis==null||globalThis.addEventListener("online",this._online),globalThis==null||globalThis.addEventListener("offline",this._offline),this._connectivityEventsAttached=!0)});o(this,"send",e=>{var i,n,c;((i=this._realWebSocket)==null?void 0:i.readyState)===((n=this._realWebSocket)==null?void 0:n.OPEN)&&((c=this._realWebSocket)==null||c.send(e))});o(this,"close",(e,i)=>{var n;return typeof e!="number"&&(i=e,e=1e3),this._clearPendingReconnectIfNeeded(),this._reconnectWhenOnlineAgain=!1,this._explicitlyClosed=!0,this._detachConnectivityEvents(),(n=this._realWebSocket)==null?void 0:n.close(e,i)});o(this,"open",e=>{var i,n;e&&(this._url=e),((i=this._realWebSocket)==null?void 0:i.readyState)!==WebSocket.OPEN&&((n=this._realWebSocket)==null?void 0:n.readyState)!==WebSocket.CONNECTING&&(this._clearPendingReconnectIfNeeded(),this._reconnectWhenOnlineAgain=!1,this._explicitlyClosed=!1,this._createWebSocket())});o(this,"_createWebSocket",()=>{var n,c,u;const e=typeof this._url=="string"?this._url:(n=this._url)==null?void 0:n.call(this,this);if(!e)return;this._clearConnectTimeoutIfNeed(),this._clearPendingReconnectIfNeeded(),this._removeWebSocketEvent(),this._realWebSocket=new WebSocket(e,this._protocols||void 0),this._attempts=this._attempts+1,this.emit("connecting",new CustomEvent("connecting",{detail:{attempts:this._attempts,reconnects:this._reconnects}}));const i=()=>{this._connectTimeout=void 0,this._detachConnectivityEvents(),this.emit("timeout",new CustomEvent("timeout",{detail:{attempts:this._attempts,reconnects:this._reconnects}}))};this._connectTimeout=setTimeout(i,(c=this._options)==null?void 0:c.timeout),this._dispatchWebSocketEvent(),(u=this._options)!=null&&u.ignoreConnectivityEvents||this._attachConnectivityEvents()});o(this,"_removeWebSocketEvent",()=>{var e,i,n,c;(e=this._realWebSocket)==null||e.removeEventListener("open",this._webSocketOpenHandler),(i=this._realWebSocket)==null||i.removeEventListener("close",this._webSocketCloseHandler),(n=this._realWebSocket)==null||n.removeEventListener("error",this._webSocketErrorHandler),(c=this._realWebSocket)==null||c.removeEventListener("message",this._webSocketMessageHandler)});o(this,"_dispatchWebSocketEvent",()=>{var e,i,n,c;(e=this._realWebSocket)==null||e.addEventListener("open",this._webSocketOpenHandler),(i=this._realWebSocket)==null||i.addEventListener("close",this._webSocketCloseHandler),(n=this._realWebSocket)==null||n.addEventListener("error",this._webSocketErrorHandler),(c=this._realWebSocket)==null||c.addEventListener("message",this._webSocketMessageHandler)});o(this,"_webSocketOpenHandler",e=>{this._connectTimeout&&(clearTimeout(this._connectTimeout),this._connectTimeout=void 0);const i=++this._reconnects,n=this._attempts;return this._attempts=0,this._reconnectWhenOnlineAgain=!1,this._startHealthCheck(),this.emit("open",Object.assign(e,{detail:{reconnects:i,attempts:n}}))});o(this,"_webSocketCloseHandler",e=>(this._reconnect(e),this._stopHealthCheck(),this.emit("close",e)));o(this,"_webSocketErrorHandler",e=>this.emit("error",new CustomEvent("error",{detail:{error:e}})));o(this,"_webSocketMessageHandler",e=>this.emit("message",e));e&&this.setOptions(e),this._startHealthCheck()}get attempts(){return this._attempts}setOptions(e){if(!e)return;this._url=e.url,this._protocols=e.protocols;const i=Object.assign(this._options,e.robustOptions||{});if(typeof(i==null?void 0:i.timeout)!="number")throw new Error("timeout must be the number of milliseconds to timeout a connection attempt");if(typeof(i==null?void 0:i.shouldReconnect)!="function")throw new Error("shouldReconnect must be a function that returns the number of milliseconds to wait for a reconnect attempt, or null or undefined to not reconnect.");this._options=i,this._options.automaticOpen&&this._createWebSocket()}_reconnect(e){var n,c,u,d;if(!((n=this._options)!=null&&n.should1000Reconnect)&&e.code===1e3||this._explicitlyClosed){this._attempts=0;return}if(this._connectivityEventsAttached&&((c=globalThis==null?void 0:globalThis.navigator)==null?void 0:c.onLine)===!1){this._reconnectWhenOnlineAgain=!0;return}const i=(d=(u=this._options)==null?void 0:u.shouldReconnect)==null?void 0:d.call(u,e,this);typeof i=="number"&&(this._pendingReconnect=setTimeout(this._createWebSocket,i))}}class dr extends le{constructor(){super();o(this,"_ws",new fr({url:"",robustOptions:{should1000Reconnect:!0,ignoreConnectivityEvents:!0}}));o(this,"_state",$.NOTINITIALIZED);o(this,"_addWebSocketEventListeners",()=>{this._ws.on("close",this._handleCloseEvent),this._ws.on("closing",this._handleClosingEvent),this._ws.on("connecting",this._handleConnectingEvent),this._ws.on("error",this._handleErrorEvent),this._ws.on("message",this._handleMessageEvent),this._ws.on("open",this._handleOpenEvent),this._ws.on("timeout",this._handleTimeoutEvent)});o(this,"_removeWebSocketEventListeners",()=>{this._ws.off("close",this._handleCloseEvent),this._ws.off("closing",this._handleClosingEvent),this._ws.off("connecting",this._handleConnectingEvent),this._ws.off("error",this._handleErrorEvent),this._ws.off("message",this._handleMessageEvent),this._ws.off("open",this._handleOpenEvent),this._ws.off("timeout",this._handleTimeoutEvent)});o(this,"_handleCloseEvent",e=>{O.info(`live room closed bacause of ${e.code}-${e.reason||gt(e.code)}`),this.state=$.CLOSED});o(this,"_handleClosingEvent",()=>{var e;O.info("live room is closing, onLine:",(e=globalThis==null?void 0:globalThis.navigator)==null?void 0:e.onLine),this.state=$.CLOSED});o(this,"_handleConnectingEvent",()=>{O.info("live room is connecting"),this.state=$.CONNECTING});o(this,"_handleErrorEvent",e=>{O.error("live room error",e),this.state=$.CLOSED});o(this,"_handleMessageEvent",e=>{let i=(()=>{try{return JSON.parse(e.data)}catch(n){return e.data}})();this.emit("message",i)});o(this,"_handleOpenEvent",e=>{O.info("live room open",e.detail),this.state=$.OPEN,e.detail.reconnects>0&&this.emit("reconnected",e.detail)});o(this,"_handleTimeoutEvent",e=>{O.error("live room connect timeout!",e.detail),this.state=$.CLOSED});o(this,"dispose",async()=>(this._removeWebSocketEventListeners(),await this.close("live room close by controller disposed!")));o(this,"open",e=>this._ws.open(e));o(this,"close",(e,i)=>new Promise(n=>{this._ws.once("close",()=>n(!0)),this._ws.close(e,i)}));this._addWebSocketEventListeners()}set state(e){const i=JSON.parse(JSON.stringify(this._state));this._state=e,this.emit("stateChange",this.state,i)}get state(){return this._state}sendMessage(e=""){if(e==null||e==="")throw new Error("live message is empty!");if(this.state===$.OPEN)return this._ws.send(JSON.stringify(e));throw new Error("live has not yet been initialized!")}readyClose(){this._ws&&(this._ws._explicitlyClosed=!0)}}const hr=r=>Promise.reject("unimplemented method GetVoiceSign"),Me=(r,s={},e=[])=>({command:r,front_request_id:ye(),data:{...s,to_user_ids:Array.isArray(e)?e:[e]}}),_r=()=>{var r,s;window!=null&&window.__Realsee_Live__&&((s=(r=window==null?void 0:window.__Realsee_Live__)==null?void 0:r.dispose)==null||s.call(r),window.__Realsee_Live__=null)};class gr extends le{constructor(e){var i;super();o(this,"_options",{});o(this,"keyframes",new le);o(this,"_buildInData",{keyframes:{}});o(this,"getFramesByKey",e=>this.snapshot[e]);o(this,"sendKeyframe",(e,i)=>{if(this.state!==$.OPEN)return!1;this._buildInData.keyframes={...this._buildInData.keyframes,[e]:i};const n=Me(U.KeyframeSync,this.snapshot);try{return this._controller.sendMessage(n),!0}catch(c){return O.error(c),!1}});o(this,"_controller",new dr);o(this,"_addLiveControllerEventListeners",()=>{this._controller.on("stateChange",this._handleStateChange),this._controller.on("message",this._handleMessage)});o(this,"_removeLiveControllerEventListeners",()=>{this._controller.off("stateChange",this._handleStateChange),this._controller.off("message",this._handleMessage)});o(this,"_handleStateChange",(e,i)=>this.emit("stateChange",e,i));o(this,"_handleMessage",async e=>{var i,n,c,u,d;if(typeof e=="object"){const{command:g,data:v={},frontRequestId:E,code:y,message:I}=e;if(y==="SUCCESS")switch(g){case U.SelfUserInfo:{const _=v;ct(this.selfInfo,_,{deep:!0})||(this._buildInData.selfInfo=_,this.emit("selfInfoUpdate",this._buildInData.selfInfo,E));break}case U.RoomInfo:{const _=v;this._buildInData.roomInfo=Object.assign({},_),this.emit("readyKeyframeSync",_.last_frame||{});break}case U.RTCInfo:{const{voice_id:_,type:V}=v;if(this._buildInData.rtcInfo={voiceId:_,type:V},(i=this.$RTC)!=null&&i.joined)O.warn("已加入语音房间,无需重复加入!");else if(await((u=this.$RTC)==null?void 0:u.join({voiceId:_,userId:((n=this.selfInfo)==null?void 0:n.id)||"",roomId:(c=this.roomInfo)==null?void 0:c.info.room_code,type:V}))){const k=(d=this._options.initialMicroStatus)!=null?d:Q.OPEN;await this.toggleMicro(k===Q.OPEN)}else O.error("加入语音房间失败");break}case U.UserList:{const _=v;this._buildInData.userList=_,this.emit("userListUpdate",this.userList,E);break}case U.CustomEvent:{const _=v;this.emit("broadcast",_,E);break}case U.KeyframeSync:{const _=v,V=Object.keys(_).reduce((C,k)=>{if(ct(_[k],this._buildInData.keyframes[k],{deep:!0}))return C;const B=[_[k],this._buildInData.keyframes[k],E],P=k;return this.keyframes.emit(P,...B),this._buildInData.keyframes[k]=_[k],C[k]=_[k],C},{});this.emit("keyframes",V,E);break}case U.BuiltinMsg:{const _=v;this.emit("builtinEvent",_),_.event_type===K.UserChange&&this.emit("userChange",_),_.event_type===K.RoomChange&&this.emit("roomChange",_),_.event_type===K.UserChange&&_.action===Y.UserMicroStatus&&await this.toggleMicro(_.data.status===Q.OPEN),_.event_type===K.RoomChange&&_.action===Y.RoomClose&&await this.exit();break}case U.UserKickOut:{this.emit("kickOut");break}default:console.warn("unknown command: ",g)}else this.emit("error",e)}});o(this,"_clearLiveData",()=>{this._buildInData={keyframes:{}}});o(this,"connect",async(e={})=>{var u,d,g,v;if(this._options.url=(d=(u=e.url)!=null?u:this._options.url)!=null?d:"",this._options.getTicket=(g=e.getTicket)!=null?g:this._options.getTicket,this._options.initialMicroStatus=(v=e.rtcMicStatus)!=null?v:this._options.initialMicroStatus,!/^ws(s):\/\//.test(this._options.url)||typeof this._options.getTicket!="function")return/^ws(s):\/\//.test(this._options.url)?typeof this._options.getTicket!="function"?new Error("getTicket muse be function"):!1:new Error("Illegal realsee live room link");const{force:i=!1}=e;if(this._options.rtc&&!await this._options.rtc.detectMicro())return new Error("Failed to obtain microphone authorization");const n=this.state;if(n===$.CONNECTING||n===$.OPEN)if(i)try{await this._controller.close("force close by connect")}catch(E){console.warn(E)}else return new Error("已有Live实例正在连接中,请勿重复连接!");this._clearLiveData();const c=tr(this._options.url,{ticket:await this._options.getTicket(),force:Number(!!i)});return this._controller.open(c),!0});o(this,"exit",async()=>{var e;if(this._clearLiveData(),this.state!==$.OPEN)return!0;try{await((e=this.$RTC)==null?void 0:e.quit())}catch(i){O.warn(i)}return await this._controller.close()});o(this,"close",async()=>{await this._controller.readyClose(),await this.updateStatus(K.RoomChange,Y.RoomClose,{})});o(this,"dispose",async()=>(this._removeLiveControllerEventListeners(),this._clearLiveData(),await this._controller.dispose()));o(this,"setSelfInfo",async e=>await this.updateStatus(K.UserChange,Y.UserInfo,e));o(this,"toggleMicro",async e=>{var n,c,u;if(!((c=(n=this.selfInfo)==null?void 0:n.permission)!=null&&c.control_own_micro))return!1;const i=await((u=this.$RTC)==null?void 0:u.toggleMicro(e));return i&&await this.updateStatus(K.UserChange,Y.UserMicroStatus,{status:e?Q.OPEN:Q.CLOSE},[]),i});o(this,"forbidMicro",async(e,i)=>{var n,c;return typeof this._options.canForbidUserMicro=="function"&&!this._options.canForbidUserMicro(i)||!((c=(n=this.selfInfo)==null?void 0:n.permission)!=null&&c.control_other_micro)?!1:await this.updateStatus(K.UserChange,Y.UserMicroStatus,{status:e},i)});o(this,"forbidSync",async(e,i)=>{var n,c;return typeof this._options.canForbidUserSync=="function"&&!this._options.canForbidUserSync(i)||!((c=(n=this.selfInfo)==null?void 0:n.permission)!=null&&c.control_other_sync)?!1:await this.updateStatus(K.UserChange,Y.UserPermission,{sync_frame:e},i)});o(this,"kick",async e=>{var i,n;return typeof this._options.canForbidUserKick=="function"&&!this._options.canForbidUserKick(e)||!((n=(i=this.selfInfo)==null?void 0:i.permission)!=null&&n.change_other_status)?!1:await this.updateStatus(K.UserChange,Y.UserStatus,{status:"KICK_OUT"},e)});this._addLiveControllerEventListeners(),this._options=Object.assign({initialMicroStatus:Q.OPEN},e),this._options.jsBridge=(()=>{if(e.jsBridge)return e.jsBridge;if(e.useBuiltInJsBridge)return new Kt})(),this._options.getVoiceSign=(i=e.getVoiceSign)!=null?i:hr,this._options.autoPlayConfirm=e.autoPlayConfirm,this._options.rtc=(()=>{if(e.rtc)return e.rtc;if(e.rtcType)switch(e.getVoiceSign||O.error("GetVoiceSign method must be passed when using built-in RTC instances"),e.rtcType){case ee.RealseeVRWebViewRTC:{if(this._options.jsBridge)return new $e({jsBridge:this._options.jsBridge,getVoiceSign:this._options.getVoiceSign});O.error("JsBridge instance must be passed when using built-in VRWebViewRTC instances");return}case ee.RealseeBrowserChimeRTC:return new Ve({getVoiceSign:this._options.getVoiceSign,logLevel:e.__debug__?at.DEBUG:at.INFO});case ee.RealseeBrowserRTC:return this._options.autoPlayConfirm||O.error("autoPlayConfirm method must be passed when using built-in RealseeBrowserRTC instances"),new De({getVoiceSign:this._options.getVoiceSign,autoPlayConfirm:this._options.autoPlayConfirm});default:{O.error("unknown built-in RTC type");return}}if(e.useBuiltInRTC){if(e.getVoiceSign||O.error("GetVoiceSign method must be passed when using built-in RTC instances"),this._options.jsBridge)return sr&&(rr||ir)||nr?new $e({jsBridge:this._options.jsBridge,getVoiceSign:this._options.getVoiceSign}):e.builtInRTCType===Ue.RealseeXChimeRTC?new Ve({getVoiceSign:this._options.getVoiceSign}):new De({getVoiceSign:this._options.getVoiceSign,autoPlayConfirm:this._options.autoPlayConfirm});O.error("jsBridge instance must be passed when using built-in RTC instances");return}})(),this._options.rtc||O.warn("unused rtc"),this._options.url&&this._options.getTicket&&this.connect(),this._options.__debug__&&Object.assign(window,{$liveController:this._controller,$live:this})}get options(){return Object.freeze(this._options||{})}get state(){return this._controller.state}get readyState(){return this._controller.state}get url(){return this.options.url}get $RTC(){return this._options.rtc}get jsBridge(){return this._options.jsBridge}get snapshot(){return this._buildInData.keyframes}get selfInfo(){return this._buildInData.selfInfo}get userList(){return this._buildInData.userList||[]}get roomInfo(){return this._buildInData.roomInfo}async updateStatus(e,i,n,c){if(this.state!==$.OPEN)return!1;const u=Object.assign({event_type:e,action:i},{data:n}),d=Me(U.BuiltinMsg,u,c);try{return this._controller.sendMessage(d),!0}catch(g){return O.error(g),!1}}broadcast(e,i,n){return this.state!==$.OPEN?!1:new Promise((c,u)=>{const d=Me(U.CustomEvent,e,i),g=d.front_request_id,v=n?setTimeout(()=>{u(new Error("RESPONSE TIMEOUT")),this.off("broadcast",E)},n):void 0,E=(y,I)=>{I===g&&(v&&clearTimeout(v),this.off("broadcast",E),c(y))};this.on("broadcast",E);try{this._controller.sendMessage(d)}catch(y){u(y)}})}}const vt=r=>(_r(),new gr(r));var xe={},mr={get exports(){return xe},set exports(r){xe=r}},ae={};/**
|
|
2
2
|
* @license React
|
|
3
3
|
* react-jsx-runtime.production.min.js
|
|
4
4
|
*
|