@realsee/live 0.4.0-beta.8 → 0.5.0-alpha.3

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.
Files changed (33) hide show
  1. package/dist/live/controller.d.ts +75 -38
  2. package/dist/live/createLive.d.ts +5 -3
  3. package/dist/live/createLiveReact.d.ts +49 -3
  4. package/dist/live/live.d.ts +162 -0
  5. package/dist/realsee-live.cjs.development.js +1561 -1447
  6. package/dist/realsee-live.cjs.development.js.map +1 -1
  7. package/dist/realsee-live.cjs.production.js +1 -1
  8. package/dist/realsee-live.cjs.production.js.map +1 -1
  9. package/dist/realsee-live.esm.js +1564 -1450
  10. package/dist/realsee-live.esm.js.map +1 -1
  11. package/dist/realsee-live.umd.development.js +51492 -51332
  12. package/dist/realsee-live.umd.development.js.map +1 -1
  13. package/dist/realsee-live.umd.production.js +1 -1
  14. package/dist/realsee-live.umd.production.js.map +1 -1
  15. package/dist/typings/live/EventType.d.ts +17 -33
  16. package/dist/typings/live/LiveConnectOptions.d.ts +7 -0
  17. package/dist/typings/live/LiveErrorType.d.ts +9 -0
  18. package/dist/typings/live/LiveOptions.d.ts +5 -12
  19. package/dist/typings/live/LiveState.d.ts +15 -0
  20. package/dist/typings/live/index.d.ts +2 -1
  21. package/dist/typings/react/index.d.ts +0 -1
  22. package/dist/utils/RobustWebSocket.d.ts +130 -0
  23. package/dist/utils/logger.d.ts +16 -0
  24. package/docs/assets/search.js +1 -1
  25. package/docs/enums/LiveState.html +7 -0
  26. package/docs/index.html +1 -1
  27. package/docs/interfaces/LiveOptions.html +16 -19
  28. package/docs/modules.html +34 -40
  29. package/package.json +2 -2
  30. package/dist/typings/live/Live.d.ts +0 -128
  31. package/dist/typings/react/LiveReact.d.ts +0 -164
  32. package/docs/interfaces/Live.html +0 -116
  33. package/docs/interfaces/LiveReact.html +0 -52
@@ -1,2 +1,2 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("@realsee/jsbridge-x"),t=require("amazon-chime-sdk-js"),r=require("trtc-js-sdk"),n=require("react");function o(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var i=o(e),s=o(r),u=o(n),c=function(e,t){return c=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r])},c(e,t)};function a(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");function r(){this.constructor=e}c(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)}var d=function(){return d=Object.assign||function(e){for(var t,r=1,n=arguments.length;r<n;r++)for(var o in t=arguments[r])Object.prototype.hasOwnProperty.call(t,o)&&(e[o]=t[o]);return e},d.apply(this,arguments)};function l(e,t,r,n){return new(r||(r=Promise))((function(o,i){function s(e){try{c(n.next(e))}catch(e){i(e)}}function u(e){try{c(n.throw(e))}catch(e){i(e)}}function c(e){var t;e.done?o(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(s,u)}c((n=n.apply(e,t||[])).next())}))}function f(e,t){var r,n,o,i,s={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return i={next:u(0),throw:u(1),return:u(2)},"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this}),i;function u(i){return function(u){return function(i){if(r)throw new TypeError("Generator is already executing.");for(;s;)try{if(r=1,n&&(o=2&i[0]?n.return:i[0]?n.throw||((o=n.return)&&o.call(n),0):n.next)&&!(o=o.call(n,i[1])).done)return o;switch(n=0,o&&(i=[2&i[0],o.value]),i[0]){case 0:case 1:o=i;break;case 4:return s.label++,{value:i[1],done:!1};case 5:s.label++,n=i[1],i=[0];continue;case 7:i=s.ops.pop(),s.trys.pop();continue;default:if(!(o=s.trys,(o=o.length>0&&o[o.length-1])||6!==i[0]&&2!==i[0])){s=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]<o[3])){s.label=i[1];break}if(6===i[0]&&s.label<o[1]){s.label=o[1],o=i;break}if(o&&s.label<o[2]){s.label=o[2],s.ops.push(i);break}o[2]&&s.ops.pop(),s.trys.pop();continue}i=t.call(e,s)}catch(e){i=[6,e],n=0}finally{r=o=0}if(5&i[0])throw i[1];return{value:i[0]?i[1]:void 0,done:!0}}([i,u])}}}function p(e,t,r){if(r||2===arguments.length)for(var n,o=0,i=t.length;o<i;o++)!n&&o in t||(n||(n=Array.prototype.slice.call(t,0,o)),n[o]=t[o]);return e.concat(n||Array.prototype.slice.call(t))}var v=Symbol("$$REALSEE_LIVE_EVENT$$");function h(e){return e[v]||(e[v]={}),e[v]}var m,g,y=function(){function e(){}return e.prototype.hasListener=function(e){var t=h(this);return t&&t[e]&&t[e].length>0},e.prototype.on=function(e,t,r){var n=this,o=h(this);return o[e]||(o[e]=[]),o[e].push([t,r||!1]),function(){return n.off(e,t)}},e.prototype.once=function(e,t){return this.on(e,t,!0)},e.prototype.off=function(e,t){if(void 0!==e){var r,n=h(this);if(n[e]||(n[e]=[]),void 0!==t){for(var o=0;o<n[e].length&&n[e][o][0]!==t;o++);o<n[e].length&&n[e].splice(o,1)}else n[e].length=0}else(r=this)[v]||delete r[v]},e.prototype.emit=function(e){for(var t=[],r=1;r<arguments.length;r++)t[r-1]=arguments[r];for(var n=!1,o=h(this),i=o[e]||[],s=0,u=i.slice();s<u.length;s++){var c=u[s],a=c[0],d=c[1],l=void 0!==d&&d,f=a.apply(void 0,t);l&&this.off(e,a),!1===f&&(n=!0)}return n},e}(),S=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return a(t,e),t}(y);function b(){return(65536*(1+Math.random())|0).toString(16).substring(1)}function C(){return(b()+b()+"-"+b()+"-4"+b().substr(0,3)+"-"+b()+"-"+b()+b()+b()).toLowerCase()}exports.RTCType=void 0,(m=exports.RTCType||(exports.RTCType={})).RealseeBrowserRTC="RealseeBrowserRTC",m.RealseeVRWebViewRTC="RealseeVRWebViewRTC",m.RealseeBrowserChimeRTC="RealseeBrowserChimeRTC",exports.BuiltInRTCType=void 0,(g=exports.BuiltInRTCType||(exports.BuiltInRTCType={})).RealseeXTRTC="trtc",g.RealseeXChimeRTC="chime";var E,w=function(e){function t(t){var r=e.call(this)||this;return r.type=exports.RTCType.RealseeBrowserRTC,r.joined=!1,r.micro=!1,r.voiceId="",r._getVoiceSign=function(){throw new Error("方法 getVoiceSign 未实现")},r.$dom=document.createElement("div"),r._trtc={client:null,stream:null},r.join=function(e){return l(r,void 0,void 0,(function(){var t,r,n,o=this;return f(this,(function(i){switch(i.label){case 0:return this.emit("joinWillStart"),[4,this._getVoiceSign({voiceId:e.voiceId,roomId:e.roomId,userId:e.userId})];case 1:return t=i.sent(),this._trtc.client=s.default.createClient(d({mode:"rtc"},t)),null===(n=this._trtc.client)||void 0===n||n.enableAudioVolumeEvaluation(),this._registerRtcEvent(),[4,new Promise((function(t){var r;null===(r=o._trtc.client)||void 0===r||r.join({roomId:Number(e.voiceId)}).then((function(){return t(!0)})).catch((function(){return t(!1)}))}))];case 2:return r=i.sent(),this.joined=r,r?(this._trtc.stream=s.default.createStream({userId:t.userId,audio:!0,video:!1}),[4,new Promise((function(e){var t;null===(t=o._trtc.stream)||void 0===t||t.initialize().then((function(){return e(!0)})).catch((function(){return e(!1)}))}))]):[2,!1];case 3:return r=i.sent(),[4,new Promise((function(e){var t;null===(t=o._trtc.client)||void 0===t||t.publish(o._trtc.stream).then((function(){return e(!0)})).catch((function(){return e(!1)}))}))];case 4:return r=i.sent(),this.joined=r,this.joined&&this.emit("joined"),[2,r]}}))}))},r._handleStreamAdded=function(e){var t,n=e.stream;console.log("远端流增加: "+n.getId()),null===(t=r._trtc.client)||void 0===t||t.subscribe(n)},r._handleStreamSubscribed=function(e){var t=e.stream;console.log("远端流订阅成功:"+t.getId());var n=t.getId(),o="rs-rtc-remote_stream-".concat(n),i=document.createElement("div");i.id=o,r.$dom.appendChild(i),t.play(o)},r._getVoiceSign=t.getVoiceSign,r._initParentDom(),r}return a(t,e),t.prototype._initParentDom=function(){this.$dom.id="rs-rtc-".concat(C()),this.$dom.style.display="none",document.body.appendChild(this.$dom)},t.prototype.quit=function(){var e=this;return new Promise((function(t){return l(e,void 0,void 0,(function(){var e,r,n=this;return f(this,(function(o){switch(o.label){case 0:return this.joined=!1,this._trtc.stream?[4,null===(e=this._trtc.client)||void 0===e?void 0:e.unpublish(this._trtc.stream)]:[3,2];case 1:o.sent(),this._trtc.stream.stop(),this._trtc.stream.close(),this._trtc.stream=null,o.label=2;case 2:return null===(r=this._trtc.client)||void 0===r||r.leave().then((function(){return n._trtc.client=null})).then((function(){return t(!0)})).catch((function(){return t(!1)})),[2]}}))}))}))},t.prototype.detectMicro=function(){return new Promise((function(e){try{navigator.mediaDevices.getUserMedia({audio:!0,video:!1}).then((function(){return e(!0)})).catch((function(){return e(!1)}))}catch(t){console.error(t),e(!1)}}))},t.prototype.toggleMicro=function(e){var t,r,n,o;return Promise.resolve((e?null===(r=null===(t=this._trtc)||void 0===t?void 0:t.stream)||void 0===r?void 0:r.unmuteAudio():null===(o=null===(n=this._trtc)||void 0===n?void 0:n.stream)||void 0===o?void 0:o.muteAudio())||!1)},t.prototype.shock=function(){throw new Error("Method not implemented.")},t.prototype._registerRtcEvent=function(){var e,t,r,n,o=this;null===(e=this._trtc.client)||void 0===e||e.on("stream-added",this._handleStreamAdded),null===(t=this._trtc.client)||void 0===t||t.on("stream-subscribed",this._handleStreamSubscribed),null===(r=this._trtc.client)||void 0===r||r.on("audio-volume",(function(e){return o.emit("userVolumes",[{userId:e.userId,audioVolume:e.audioVolume}])})),null===(n=this._trtc.client)||void 0===n||n.on("error",(function(e){return o.emit("error",e)}))},t}(S),k=function(e){function r(r){var n=e.call(this)||this;return n.type=exports.RTCType.RealseeBrowserChimeRTC,n.joined=!1,n.micro=!1,n.voiceId="",n.userId="",n.deviceChangeObserver={},n.audioVideoObserver={},n._getVoiceSign=function(){throw new Error("方法 getVoiceSign 未实现")},n.$dom=document.createElement("div"),n.$audio=document.createElement("audio"),n._initDom=function(){n.$audio.id="rs-rtc-".concat(C()),n.$dom.id="rs-rtc-".concat(C()),n.$dom.appendChild(n.$audio),document.body.appendChild(n.$dom)},n.initObservers=function(){n.deviceChangeObserver={audioInputsChanged:function(e){null==e||e.forEach((function(e){n.logger.info("Device ID: ".concat(e.deviceId," Microphone: ").concat(e.label))}))},audioOutputsChanged:function(e){n.logger.info("Audio outputs updated: ".concat(e))},videoInputsChanged:function(e){n.logger.info("Video inputs updated: ".concat(e))},audioInputMuteStateChanged:function(e,t){n.logger.info("Device ".concat(e.toString()," ").concat(t?"is muted in hardware":"is not muted"))}},n.audioVideoObserver={audioVideoDidStart:function(){n.logger.info("Started")},audioVideoDidStop:function(e){n.logger.info("Stopped with a session status code: ".concat(e.statusCode()))},audioVideoDidStartConnecting:function(e){e&&n.logger.info("Attempting to reconnect")}}},n._registerRtcEvent=function(){var e,r,o,i,s,u,c=(null===(o=null===(r=null===(e=n.meetingSession)||void 0===e?void 0:e.configuration)||void 0===r?void 0:r.credentials)||void 0===o?void 0:o.attendeeId)||"";if(c){var a=new Map,d=function(){var e=[];return a.forEach((function(t,r){e.push({userId:t.userId,volume:t.muted||0===t.signalStrength||!Boolean(t.volume)?0:t.volume})})),e};null===(i=n.meetingSession)||void 0===i||i.audioVideo.realtimeSubscribeToAttendeeIdPresence((function(e,r,o){var i;if(!r)return a.delete(e),void n.emit("userVolumes",d());null===(i=n.meetingSession)||void 0===i||i.audioVideo.realtimeSubscribeToVolumeIndicator(e,(function(e,r,i,s){new t.DefaultModality(e).base()===e&&(a.set(e,{userId:o||e,volume:r,muted:i,signalStrength:s}),n.emit("userVolumes",d()))}))})),null===(s=n.meetingSession)||void 0===s||s.audioVideo.realtimeSubscribeToVolumeIndicator(c,(function(e,r,o,i){new t.DefaultModality(e).base()===e&&null!==i&&1!==i&&n.emit("weakNetwork")})),null===(u=n.meetingSession)||void 0===u||u.audioVideo.realtimeSubscribeToFatalError((function(e){return n.emit("error",e)}))}},n._getVoiceSign=r.getVoiceSign,n._initDom(),n.logger=new t.ConsoleLogger("WebRTCLogger",r.logLevel||t.LogLevel.OFF),n.deviceController=new t.DefaultDeviceController(n.logger),n.initObservers(),n}return a(r,e),r.prototype.join=function(e){return l(this,void 0,void 0,(function(){var r=this;return f(this,(function(n){return[2,new Promise((function(n,o){return l(r,void 0,void 0,(function(){var r,o,i,s,u,c,a,l,p,v,h,m,g,y=this;return f(this,(function(f){switch(f.label){case 0:this.emit("joinWillStart"),f.label=1;case 1:return f.trys.push([1,6,,7]),[4,this._getVoiceSign(d(d({},e),{roomId:e.roomId||0}))];case 2:return r=f.sent(),o=r.userId,i=r.userSig,this.userId=o,s=JSON.parse(decodeURIComponent(i)),u=s.attendence,c=s.vendor_wrapper,a=new t.MeetingSessionConfiguration({Meeting:c},{Attendee:{ExternalUserId:u.external_user_id,AttendeeId:u.attendee_id,JoinToken:u.join_token}}),this.meetingSession=new t.DefaultMeetingSession(a,this.logger,this.deviceController),this._registerRtcEvent(),this.meetingSession.audioVideo.addDeviceChangeObserver(this.deviceChangeObserver),this.meetingSession.audioVideo.addObserver(this.audioVideoObserver),this.meetingSession.audioVideo.bindAudioElement(this.$audio),l={audioVideoDidStart:function(){var e;null===(e=y.meetingSession)||void 0===e||e.audioVideo.realtimeMuteLocalAudio(),y.joined=!0,y.emit("joined"),n(!0)},audioVideoDidStop:function(){y.joined=!1,n(!1)}},this.meetingSession.audioVideo.addObserver(l),[4,this.deviceController.listAudioInputDevices(!0)];case 3:return p=f.sent(),v=p.find((function(e){return"default"===e.deviceId})),h=p.find((function(e){return""!==e.deviceId})),this.audioInput=v||h,[4,this.meetingSession.audioVideo.chooseVideoInputDevice(null)];case 4:return f.sent(),[4,this.meetingSession.audioVideo.chooseAudioInputDevice((null===(g=this.audioInput)||void 0===g?void 0:g.deviceId)||"default")];case 5:return f.sent(),this.meetingSession.audioVideo.start(),[3,7];case 6:return m=f.sent(),this.emit("error",m),this.logger.error(m.message),n(!1),[3,7];case 7:return[2]}}))}))}))]}))}))},r.prototype.quit=function(){var e=this;return this.joined?new Promise((function(r,n){var o,i;e.joined=!1;var s={audioVideoDidStop:function(n){var o=n.statusCode();o===t.MeetingSessionStatusCode.Left?(e.logger.info("You left the session"),r(!0)):(e.logger.info("Stopped with a session status code: ".concat(o)),r(!0))}};null===(o=e.meetingSession)||void 0===o||o.audioVideo.addObserver(s),null===(i=e.meetingSession)||void 0===i||i.audioVideo.stop()})):Promise.resolve(!0)},r.prototype.detectMicro=function(){return l(this,void 0,void 0,(function(){var e=this;return f(this,(function(t){return[2,new Promise((function(t){try{navigator.mediaDevices.getUserMedia({audio:!0,video:!1}).then((function(){return t(!0)})).catch((function(){return t(!1)}))}catch(r){e.logger.error(r.message),t(!1)}}))]}))}))},r.prototype.toggleMicro=function(e){var t,r,n;return l(this,void 0,void 0,(function(){var o;return f(this,(function(i){return e?null===(t=this.meetingSession)||void 0===t||t.audioVideo.realtimeUnmuteLocalAudio():null===(r=this.meetingSession)||void 0===r||r.audioVideo.realtimeMuteLocalAudio(),void 0!==(o=null===(n=this.meetingSession)||void 0===n?void 0:n.audioVideo.realtimeIsLocalAudioMuted())?[2,e!==o]:[2,!1]}))}))},r.prototype.shock=function(){throw new Error("Method not implemented.")},r}(S);exports.RTCJoinedInfoCodeEnum=void 0,(E=exports.RTCJoinedInfoCodeEnum||(exports.RTCJoinedInfoCodeEnum={}))[E.Success=0]="Success",E[E.Failure=1]="Failure",E[E.ReJoin=2]="ReJoin",E[E.NoMicroPermission=3]="NoMicroPermission";var T,I,_,R,x,O,L,j,M,U=function(e){function t(t){var r=t.jsBridge,n=t.getVoiceSign,o=e.call(this)||this;return o.type=exports.RTCType.RealseeVRWebViewRTC,o.joined=!1,o.micro=!1,o.voiceId="",o.options={jsBridge:r,getVoiceSign:n},o.jsBridge.callAndListen("live/userVolumes",(function(e){o.emit("userVolumes",e)})),o.jsBridge.callAndListen("live/weakNetwork",(function(e){e&&o.emit("weakNetwork")})),o}return a(t,e),Object.defineProperty(t.prototype,"jsBridge",{get:function(){return this.options.jsBridge},enumerable:!1,configurable:!0}),t.prototype.join=function(e){return l(this,void 0,void 0,(function(){var t,r,n,o,i,s,u;return f(this,(function(c){switch(c.label){case 0:return this.emit("joinWillStart"),[4,this.options.getVoiceSign(e)];case 1:return t=c.sent(),r=t.sdkAppId,n=t.userId,o=t.userSig,this.type=e.type,[4,this.jsBridge.callAndBackfeed("live/join?sdkAppID=".concat(r,"&userID=").concat(n,"&roomID=").concat(Number(e.voiceId),"&userSig=").concat(o))];case 2:return i=c.sent(),s=i[0],u=i[1],s?s.code===exports.RTCJoinedInfoCodeEnum.Success?(this.emit("joined"),this.joined=!0):(this.emit("error",s),this.joined=!1):(this.emit("error",u||new Error("加入房间失败:未知异常。")),this.joined=!1),[2,this.joined]}}))}))},t.prototype.quit=function(){return l(this,void 0,void 0,(function(){var e,t,r;return f(this,(function(n){switch(n.label){case 0:return[4,this.jsBridge.callAndBackfeed("live/quit")];case 1:return e=n.sent(),t=e[0],r=e[1],null===t&&this.emit("error",r||new Error("退出房间失败:未知异常。")),this.joined=!1,[2,!!t]}}))}))},t.prototype.detectMicro=function(){return l(this,void 0,void 0,(function(){var e,t,r;return f(this,(function(n){switch(n.label){case 0:return[4,this.jsBridge.detectMicro()];case 1:return e=n.sent(),t=e[0],r=e[1],null===t?(this.emit("error",r||new Error("麦克风监测异常!")),[2,!1]):[2,t]}}))}))},t.prototype.toggleMicro=function(e){return l(this,void 0,void 0,(function(){var t,r,n;return f(this,(function(o){switch(o.label){case 0:return[4,this.jsBridge.callAndBackfeed("live/toggleMicro?flag=".concat(e?1:0))];case 1:return t=o.sent(),r=t[0],n=t[1],null===r?(this.emit("error",n||new Error("麦克风监测异常!")),[2,!1]):(this.micro=r,[2,r])}}))}))},t.prototype.shock=function(){this.jsBridge.shock(1)},t}(S);function V(e){try{var t=JSON.parse(e),r={code:t.code,message:t.message,command:t.command,roomCode:t.room_code,appID:t.app_id,requestId:t.request_id,frontRequestId:t.front_request_id,triggerUserID:t.trigger_user_id,data:t.data||{}},n=Object.keys(r).filter((function(e){return void 0===r[e]}));return n.length>0&&console.warn("推送数据格式异常:".concat(n.join(" ")," 值不存在!")),r}catch(e){return!1}}function B(e){switch(e){case 1001:return exports.WebSocketCloseError.Err_1001;case 1002:return exports.WebSocketCloseError.Err_1002;case 1003:return exports.WebSocketCloseError.Err_1003;case 1006:return exports.WebSocketCloseError.Err_1006;case 1007:return exports.WebSocketCloseError.Err_1007;case 1008:return exports.WebSocketCloseError.Err_1008;case 1009:return exports.WebSocketCloseError.Err_1009}return exports.WebSocketCloseError.Err_unknown}function N(e,t){void 0===t&&(t={});var r=-1!==e.indexOf("?");return e+Object.keys(t).reduce((function(e,n,o){return"".concat(e).concat(0!==o||r?"&":"?").concat(n,"=").concat(t[n])}),"")}exports.Command=void 0,(T=exports.Command||(exports.Command={})).SelfUserInfo="SELF_USER_INFO",T.RoomInfo="ROOM_INFO",T.RTCInfo="RTC_INFO",T.UserList="USER_LIST",T.BuiltinMsg="BUILTIN_MSG",T.CustomEvent="CUSTOM_EVENT",T.KeyframeSync="KEYFRAME_SYNC",T.UserKickOut="USER_KICK_OUT",exports.BuiltinEventType=void 0,(I=exports.BuiltinEventType||(exports.BuiltinEventType={})).UserChange="user_change",I.RoomChange="room_change",exports.BuiltinActionType=void 0,(_=exports.BuiltinActionType||(exports.BuiltinActionType={})).UserMicroStatus="change_micro_status",_.UserMicroStatusSync="sync_micro_status",_.UserPermission="change_permission",_.UserStatus="change_status",_.UserInfo="change_info",_.RoomClose="close",exports.MicroStatus=void 0,(R=exports.MicroStatus||(exports.MicroStatus={})).OPEN="OPEN",R.CLOSE="CLOSE",exports.UserStatus=void 0,(x=exports.UserStatus||(exports.UserStatus={}))[x.Normal=0]="Normal",x[x.Removed=1]="Removed",x[x.Replaced=2]="Replaced",exports.MemUserStatus=void 0,(O=exports.MemUserStatus||(exports.MemUserStatus={})).WAIT_ENTER="WAIT_ENTER",O.ONLINE="ONLINE",O.LEAVE="LEAVE",O.KICK_OUT="KICK_OUT",O.BE_REPLACE="BE_REPLACE",O.EXCEPTION="EXCEPTION",exports.WebSocketState=void 0,(L=exports.WebSocketState||(exports.WebSocketState={}))[L.NOTINITIALIZED=-1]="NOTINITIALIZED",L[L.CONNECTING=0]="CONNECTING",L[L.OPEN=1]="OPEN",L[L.CLOSING=2]="CLOSING",L[L.CLOSED=3]="CLOSED",exports.WebSocketErrorType=void 0,(j=exports.WebSocketErrorType||(exports.WebSocketErrorType={})).Error="Error",j.Close="Close",j.MicroAuth="MicroAuth",j.DuplicateConnect="DuplicateConnect",j.IllegalURL="IllegalURL",j.Unknown="Unknown",j.IllegalArgs="IllegalArgs",exports.WebSocketCloseError=void 0,(M=exports.WebSocketCloseError||(exports.WebSocketCloseError={})).Err_1001="CLOSE_GOING_AWAY",M.Err_1002="CLOSE_PROTOCOL_ERROR",M.Err_1003="CLOSE_UNSUPPORTED",M.Err_1006="CLOSE_ABNORMAL",M.Err_1007="Unsupported Data",M.Err_1008="Policy Violation",M.Err_1009="CLOSE_TOO_LARGE",M.Err_unknown="unknown";var A=globalThis.navigator.userAgent,P=/android/gi.test(A),W=/iPhone|iPad\s+OS/gi.test(A),D=/MicroMessenger/gi.test(A)&&/miniProgram/gi.test(A),$=/realsee/gi.test(A);function K(e){return"[object Object]"===Object.prototype.toString.call(e)}function F(e,t){return e===t||typeof e==typeof t&&!(!Number.isNaN(e)||!Number.isNaN(t))}function q(e,t){return!!F(e,t)||(K(e)&&K(t)?function(e,t){var r=Object.getOwnPropertyNames(e),n=Object.getOwnPropertyNames(t);if(r.length!==n.length)return!1;for(var o=0,i=r.length;o<i;o++){var s=r[o];if(!F(e[s],t[s]))return!1}return!0}(e,t):!(!Array.isArray(e)||!Array.isArray(t))&&function(e,t){if(e.length!==t.length)return!1;for(var r=0,n=e.length;r<n;r++)if(!F(e[r],t[r]))return!1;return!0}(e,t))}function G(e,t){return!!F(e,t)||(K(e)&&K(t)?function(e,t){var r=Object.getOwnPropertyNames(e),n=Object.getOwnPropertyNames(t);if(r.length!==n.length)return!1;for(var o=0,i=r.length;o<i;o++){var s=r[o];if(!G(e[s],t[s]))return!1}return!0}(e,t):!(!Array.isArray(e)||!Array.isArray(t))&&function(e,t){if(e.length!==t.length)return!1;for(var r=0,n=e.length;r<n;r++)if(!G(e[r],t[r]))return!1;return!0}(e,t))}function J(e,t,r){return void 0===r&&(r={deep:!1}),r.deep?G(e,t):q(e,t)}var X=function(){function e(e){var t=this;this.readyState=exports.WebSocketState.NOTINITIALIZED,this.canSync=!0,this.connecting=!1,this.keyframes={},this.checkReadyState=function(e){do{if(!t.webSocket){t.readyState!==exports.WebSocketState.NOTINITIALIZED&&(t.readyState=exports.WebSocketState.NOTINITIALIZED,e.emit("ws.readyStateUpdate",t.readyState));break}var r=t.webSocket.readyState;r!==t.readyState&&(t.readyState=r,e.emit("ws.readyStateUpdate",t.readyState))}while(0);return t.readyState},this.dispose=function(){return t.disposeWebSocket(),t.connecting=!1,t.healthCheckId&&(clearInterval(t.healthCheckId),t.healthCheckId=void 0),!0},this.disposeWebSocket=function(){if(t.webSocket)return t.onEvtOpnListener&&(t.webSocket.removeEventListener("open",t.onEvtOpnListener),t.onEvtOpnListener=void 0),t.onEvtMsgListener&&(t.webSocket.removeEventListener("message",t.onEvtMsgListener),t.onEvtMsgListener=void 0),t.onEvtErrListener&&(t.webSocket.removeEventListener("error",t.onEvtErrListener),t.onEvtErrListener=void 0),t.onEvtCLEListener&&(t.webSocket.removeEventListener("close",t.onEvtCLEListener),t.onEvtCLEListener=void 0),t.webSocket.close(),t.webSocket=void 0,!0},this.options=Object.assign({autoConnect:!0,healthCheck:3e3},e)}return e.prototype.handleMessage=function(e,t){var r,n,o,i=this,s=e.command,u=e.data,c=e.frontRequestId;if("SUCCESS"===e.code)switch(s){case exports.Command.SelfUserInfo:var a=u;if(J(this.selfUserInfo,a,{deep:!0}))return;this.selfUserInfo=a,t.emit("selfInfoUpdate",this.selfUserInfo,c);break;case exports.Command.RoomInfo:var d=u;this.roomInfo=Object.assign({},d),t.emit("readyKeyframeSync",d.last_frame||{});break;case exports.Command.RTCInfo:var l=u,f=l.voice_id,v=l.type;if(t.$RTC.joined)break;t.$RTC.join({voiceId:f,userId:(null===(r=this.selfUserInfo)||void 0===r?void 0:r.id)||"",roomId:null===(n=this.roomInfo)||void 0===n?void 0:n.info.room_code,type:v}),t.updateStatus(exports.BuiltinEventType.UserChange,exports.BuiltinActionType.UserMicroStatus,{status:exports.MicroStatus.OPEN});break;case exports.Command.UserList:var h=u;this.userList=h,t.emit("userListUpdate",this.userList,c);break;case exports.Command.CustomEvent:var m=u;t.emit("broadcast",m,c);break;case exports.Command.KeyframeSync:var g=u,y=Object.keys(g).reduce((function(e,r){var n;if(J(g[r],i.keyframes[r],{deep:!0}))return e;var o=[g[r],i.keyframes[r],c],s=r;return(n=t.keyframes).emit.apply(n,p([s],o,!1)),i.keyframes[r]=g[r],e[r]=g[r],e}),{});t.emit("keyframes",y,c);break;case exports.Command.BuiltinMsg:var S=u;t.emit("builtinEvent",S),S.event_type===exports.BuiltinEventType.UserChange&&t.emit("userChange",S),S.event_type===exports.BuiltinEventType.RoomChange&&t.emit("roomChange",S),S.event_type===exports.BuiltinEventType.UserChange&&S.action===exports.BuiltinActionType.UserMicroStatus&&t.toggleMicro(S.data.status===exports.MicroStatus.OPEN),S.event_type===exports.BuiltinEventType.RoomChange&&S.action===exports.BuiltinActionType.RoomClose&&(null===(o=this.options.rtc)||void 0===o||o.quit(),this.disposeWebSocket());break;case exports.Command.UserKickOut:t.emit("kickOut");break;default:console.warn("unknown command: ",s)}else t.emit("error",e)},e.prototype.sendMessage=function(e){return this.webSocket?e?void this.webSocket.send(JSON.stringify(e)):console.warn("WebSocket messages is empty!"):console.warn("WebSocket has not yet been initialized!")},e}(),Z=function(e){return Promise.reject("unimplemented method GetVoiceSign")};function z(e){var r=new X(e),n=function(e,t,r){return void 0===t&&(t={}),(r=r?Array.isArray(r)?r:[r]:[])&&(t.to_user_ids=r),{command:e,front_request_id:C(),data:t}},o=function(o){function u(){var n,s,u=this;(u=o.call(this)||this).keyframes=new y;var c=e.jsBridge?e.jsBridge:e.useBuiltInJsBridge?new i.default:void 0;if(r.options.jsBridge=c,!e.rtc){if(e.rtcType){if(!e.getVoiceSign)throw new Error("GetVoiceSign method must be passed when using built-in RTC instances");var a=null!==(n=e.getVoiceSign)&&void 0!==n?n:Z;switch(e.rtcType){case exports.RTCType.RealseeVRWebViewRTC:if(!c)throw new Error("JsBridge instance must be passed when using built-in VRWebViewRTC instances");r.options.rtc=new U({jsBridge:c,getVoiceSign:a});break;case exports.RTCType.RealseeBrowserChimeRTC:r.options.rtc=new k({getVoiceSign:a,logLevel:e.__debug__?t.LogLevel.DEBUG:t.LogLevel.ERROR});break;case exports.RTCType.RealseeBrowserRTC:r.options.rtc=new w({getVoiceSign:a});break;default:throw new Error("unknown built-in RTC type")}}if(e.useBuiltInRTC){if(!e.getVoiceSign)throw new Error("GetVoiceSign method must be passed when using built-in RTC instances");a=null!==(s=e.getVoiceSign)&&void 0!==s?s:Z;if(!c)throw new Error("jsBridge instance must be passed when using built-in RTC instances");r.options.rtc=$&&(P||W)||D?new U({jsBridge:c,getVoiceSign:a}):e.builtInRTCType===exports.BuiltInRTCType.RealseeXChimeRTC?new k({getVoiceSign:a}):new w({getVoiceSign:a})}}r.options.rtc||console.warn("unused rtc"),r.options.url&&r.options.getTicket&&u.connect();var d=function(e){if(!e)return 0;if(!0===e)return 3e3;var t=Number(e);return t>0?t:3e3}(r.options.healthCheck);return d&&(r.healthCheckId=setInterval((function(){return r.checkReadyState(u)}),d)),u}return a(u,o),Object.defineProperty(u.prototype,"options",{get:function(){return Object.freeze(Object.assign({},r.options))},enumerable:!1,configurable:!0}),Object.defineProperty(u.prototype,"readyState",{get:function(){return r.checkReadyState(this),r.readyState},enumerable:!1,configurable:!0}),Object.defineProperty(u.prototype,"url",{get:function(){var e;return(null===(e=r.webSocket)||void 0===e?void 0:e.url)||""},enumerable:!1,configurable:!0}),Object.defineProperty(u.prototype,"selfInfo",{get:function(){return r.selfUserInfo},enumerable:!1,configurable:!0}),Object.defineProperty(u.prototype,"userList",{get:function(){return r.userList||[]},enumerable:!1,configurable:!0}),Object.defineProperty(u.prototype,"snapshot",{get:function(){return r.keyframes||{}},enumerable:!1,configurable:!0}),Object.defineProperty(u.prototype,"$RTC",{get:function(){return r.options.rtc},enumerable:!1,configurable:!0}),Object.defineProperty(u.prototype,"jsBridge",{get:function(){return r.options.jsBridge},enumerable:!1,configurable:!0}),u.prototype.setSelfInfo=function(e){return l(this,void 0,void 0,(function(){return f(this,(function(t){switch(t.label){case 0:if(this.readyState!==exports.WebSocketState.OPEN)return[2,new Error("The connection is not open and ready to communicate.")];t.label=1;case 1:return t.trys.push([1,3,,4]),[4,this.updateStatus(exports.BuiltinEventType.UserChange,exports.BuiltinActionType.UserInfo,e)];case 2:return[2,t.sent()];case 3:return[2,t.sent()];case 4:return[2]}}))}))},u.prototype.getFramesByKey=function(e){return r.keyframes[e]},u.prototype.sendKeyframe=function(e,t){if(this.readyState!==exports.WebSocketState.OPEN)return new Error("The connection is not open and ready to communicate.");r.keyframes[e]=t;var o=n(exports.Command.KeyframeSync,this.snapshot);return r.sendMessage(o),!0},u.prototype.broadcast=function(e,t,o){var i=this;return this.readyState!==exports.WebSocketState.OPEN?new Error("The connection is not open and ready to communicate."):new Promise((function(s,u){var c=n(exports.Command.CustomEvent,e,t),a=c.front_request_id;r.sendMessage(c);var d=o?setTimeout((function(){u(new Error("RESPONSE TIMEOUT")),i.off("broadcast",l)}),o):void 0,l=function(e,t){t===a&&(i.off("broadcast",l),s(e),d&&clearInterval(d))};i.on("broadcast",l)}))},u.prototype.updateStatus=function(e,t,o,i){return l(this,void 0,void 0,(function(){var s,u;return f(this,(function(c){return this.readyState!==exports.WebSocketState.OPEN?[2,!1]:(s=Object.assign({event_type:e,action:t},{data:o}),u=n(exports.Command.BuiltinMsg,s,i),r.sendMessage(u),[2,!0])}))}))},u.prototype.toggleMicro=function(e){var t,r;return l(this,void 0,void 0,(function(){return f(this,(function(n){switch(n.label){case 0:return(null===(r=null===(t=this.selfInfo)||void 0===t?void 0:t.permission)||void 0===r?void 0:r.control_own_micro)?[4,this.$RTC.toggleMicro(e)]:[2,!1];case 1:return n.sent(),[4,this.updateStatus(exports.BuiltinEventType.UserChange,exports.BuiltinActionType.UserMicroStatus,{status:e?exports.MicroStatus.OPEN:exports.MicroStatus.CLOSE},[])];case 2:return[2,n.sent()]}}))}))},u.prototype.forbidMicro=function(e,t){var n,o;return l(this,void 0,void 0,(function(){return f(this,(function(i){switch(i.label){case 0:return r.options.canForbidUserMicro&&!r.options.canForbidUserMicro(t)?[2,!1]:(null===(o=null===(n=this.selfInfo)||void 0===n?void 0:n.permission)||void 0===o?void 0:o.control_other_micro)?[4,this.updateStatus(exports.BuiltinEventType.UserChange,exports.BuiltinActionType.UserMicroStatus,{status:e},t)]:[2,!1];case 1:return[2,i.sent()]}}))}))},u.prototype.forbidSync=function(e,t){var n,o;return l(this,void 0,void 0,(function(){return f(this,(function(i){switch(i.label){case 0:return r.options.canForbidUserSync&&!r.options.canForbidUserSync(t)?[2,!1]:(null===(o=null===(n=this.selfInfo)||void 0===n?void 0:n.permission)||void 0===o?void 0:o.control_other_sync)?[4,this.updateStatus(exports.BuiltinEventType.UserChange,exports.BuiltinActionType.UserPermission,{sync_frame:e},t)]:[2,!1];case 1:return[2,i.sent()]}}))}))},u.prototype.kick=function(e){var t,n;return l(this,void 0,void 0,(function(){return f(this,(function(o){switch(o.label){case 0:return r.options.canForbidUserKick&&!r.options.canForbidUserKick(e)?[2,!1]:(null===(n=null===(t=this.selfInfo)||void 0===t?void 0:t.permission)||void 0===n?void 0:n.change_other_status)?[4,this.updateStatus(exports.BuiltinEventType.UserChange,exports.BuiltinActionType.UserStatus,{status:"KICK_OUT"},e)]:[2,!1];case 1:return[2,o.sent()]}}))}))},u.prototype.exit=function(){return l(this,void 0,void 0,(function(){var e;return f(this,(function(t){switch(t.label){case 0:return t.trys.push([0,2,,3]),this.$RTC.quit(),[4,this.updateStatus(exports.BuiltinEventType.RoomChange,exports.BuiltinActionType.RoomClose,{})];case 1:return t.sent(),[3,3];case 2:return e=t.sent(),console.log(e),[3,3];case 3:return[2,r.dispose()]}}))}))},u.prototype.connect=function(e){return void 0===e&&(e={}),l(this,void 0,void 0,(function(){var t,n,o,i,u,c,a,d=this;return f(this,(function(l){switch(l.label){case 0:return[4,this.$RTC.detectMicro()];case 1:return l.sent()?r.connecting?(n=new Error("WebSocket 正在连接中,请勿重复连接 ..."),this.emit("ws.error",{type:exports.WebSocketErrorType.DuplicateConnect,error:n}),[2,n]):(t=e.force)||this.readyState!==exports.WebSocketState.CONNECTING&&this.readyState!==exports.WebSocketState.OPEN?(e.url&&(r.options.url=e.url),e.getTicket&&(r.options.getTicket=e.getTicket),r.options.url&&r.options.url.startsWith("ws")?r.options.getTicket?(r.connecting=!0,r.disposeWebSocket(),this.emit("ws.beforeConnect"),t||e.url||!this.url?(u=N,c=[r.options.url],a={},[4,r.options.getTicket()]):[3,3]):(n=new Error("getTicket() 未配置!"),this.emit("ws.error",{type:exports.WebSocketErrorType.IllegalArgs,error:n}),[2,n]):(n=new Error('WebSocket URL 未配置或格式不合法:"'.concat(r.options.url,'"')),this.emit("ws.error",{type:exports.WebSocketErrorType.IllegalURL,error:n}),[2,n])):[2,!0]:(n=new Error("系统监测麦克风未授权~"),this.emit("ws.error",{type:exports.WebSocketErrorType.MicroAuth,error:n}),[2,n]);case 2:return i=u.apply(void 0,c.concat([(a.ticket=l.sent(),a.force=Number(!!t),a)])),[3,4];case 3:i=this.url,l.label=4;case 4:return o=i,r.webSocket=new WebSocket(o),r.onEvtOpnListener=function(){r.checkReadyState(d),d.emit("ws.afterConnect")},r.onEvtMsgListener=function(e){r.checkReadyState(d);try{var t=V(e.data);if(!1===t)return;r.handleMessage(t,d)}catch(t){d.emit("ws.error",{type:exports.WebSocketErrorType.Unknown,error:t,target:e})}},r.onEvtErrListener=function(e){s.emit("ws.error",{type:exports.WebSocketErrorType.Error,target:e}),r.checkReadyState(d)},r.onEvtCLEListener=function(e){r.checkReadyState(d);var t=Number(e.code);if(1e3!==t){var n=B(t);s.emit("ws.error",{target:e,type:exports.WebSocketErrorType.Close,closeError:n})}},r.webSocket.addEventListener("open",r.onEvtOpnListener),r.webSocket.addEventListener("message",r.onEvtMsgListener),r.webSocket.addEventListener("error",r.onEvtErrListener),r.webSocket.addEventListener("close",r.onEvtCLEListener),[4,new Promise((function(e,t){var n=function(){e(!0),r.connecting=!1,d.off("ws.error",o)},o=function(e){t(e.error?e.error:new Error("WebSocket connection failed!")),r.connecting=!1,d.off("ws.afterConnect",n)};d.once("ws.afterConnect",n),d.once("ws.error",o)}))];case 5:return[2,l.sent()]}}))}))},u.prototype.revoke=function(){return l(this,void 0,void 0,(function(){return f(this,(function(e){return[2,!0]}))}))},u}(y),s=new o;return e.__debug__&&(Object.assign(s,{__controller__:r}),Object.assign(window,{$live:s})),s}exports.BrowserRTC=w,exports.BrowserRTC4Chime=k,exports.CoreRTC=S,exports.VRWebViewRTC=U,exports.createLive=z,exports.createLiveReact=function(e){var t=u.default.createContext(null),r=z(e),n=r.jsBridge;function o(){var e=u.default.useContext(t);if(!e)throw new Error("LiveProvider never found.");return e}return{live:r,jsBridge:n,LiveProvider:function(e){return u.default.createElement(t.Provider,{value:e.live||r},e.children)},unsafe__useLiveInstance:function(){return o()},unsafe__useRTCInstance:function(){return o().$RTC},useCurrentWebSocketUrl:function(){var e=o(),t=u.default.useState(void 0),r=t[0],n=t[1];return u.default.useEffect((function(){var t=function(){return n(e.url)};return e.on("ws.beforeConnect",t),function(){return e.off("ws.beforeConnect",t)}}),[e]),r},useConnect:function(){var e=this,t=o();return function(r){return l(e,void 0,void 0,(function(){return f(this,(function(e){switch(e.label){case 0:return[4,t.connect(r)];case 1:return[2,e.sent()]}}))}))}},useKeyframe:function(e){var t=o(),r=u.default.useState(t.getFramesByKey(e)),n=r[0],i=r[1];return u.default.useEffect((function(){var r=e,n=function(e){return i(e)};return t.keyframes.on(r,n),function(){return t.keyframes.off(r,n)}}),[t]),[n,u.default.useCallback((function(r){return t.sendKeyframe(e,r)}),[t])]},useKeyframeUpdateCallback:function(e,t,r){void 0===r&&(r=[]);var n=o(),i=p([n,e],r,!0),s=function(){return n.keyframes.off(e,t)};return u.default.useEffect((function(){return n.keyframes.on(e,t),s}),i),s},useLiveAction:function(){var e=o(),t=u.default.useCallback((function(t){return e.toggleMicro(t)}),[e]),r=u.default.useCallback((function(t,r,n){return void 0===n&&(n=0),e.broadcast(t,r,n)}),[e]),n=u.default.useCallback((function(){return e.exit()}),[e]),i=u.default.useCallback((function(t){return e.kick(t)}),[e]),s=u.default.useCallback((function(t,r){return e.forbidMicro(t,r)}),[e]),c=u.default.useCallback((function(t){return e.getFramesByKey(t)}),[e]);return{broadcast:r,exit:n,kick:i,toggleMicro:t,forbidMicro:s,sendKeyframe:u.default.useCallback((function(t,r){return e.sendKeyframe(t,r)}),[e]),getFramesByKey:c,setSelfInfo:u.default.useCallback((function(t){return e.setSelfInfo(t)}),[e]),updateStatus:u.default.useCallback((function(t,r,n,o){return e.updateStatus(t,r,n,o)}),[e])}},useLiveEventCallback:function(e,t,r){void 0===r&&(r=[]);var n=o(),i=function(){return n.off(e,t)},s=p([n,e],r,!0);return u.default.useEffect((function(){return n.on(e,t),i}),s),i},useReadyState:function(){var e=o(),t=u.default.useState(e.readyState),r=t[0],n=t[1];return u.default.useEffect((function(){var t=function(e){return n(e)};return e.on("ws.readyStateUpdate",t),function(){return e.off("ws.readyStateUpdate",t)}}),[e]),r},useRTCAction:function(){var e=o(),t=u.default.useCallback((function(t){return e.$RTC.join(t)}),[e]);return{join:t,quit:u.default.useCallback((function(){return e.$RTC.quit()}),[e]),shock:u.default.useCallback((function(){var t,r;return null===(r=(t=e.$RTC).shock)||void 0===r?void 0:r.call(t)}),[e]),toggleMicro:u.default.useCallback((function(t){return e.$RTC.toggleMicro(t)}),[e]),detectMicro:u.default.useCallback((function(){return e.$RTC.detectMicro()}),[e])}},useRTCEventCallback:function(e,t,r){void 0===r&&(r=[]);var n=o(),i=function(){return n.$RTC.off(e,t)},s=p([n,e],r,!0);return u.default.useEffect((function(){return n.$RTC.on(e,t),i}),s),i},useSelfInfo:function(){var e=this,t=o(),r=u.default.useState(t.selfInfo||{}),n=r[0],i=r[1],s=function(e){return i(e)};u.default.useEffect((function(){return t.on("selfInfoUpdate",s),function(){return t.off("selfInfoUpdate",s)}}),[t]);var c=u.default.useCallback((function(r){return l(e,void 0,void 0,(function(){return f(this,(function(e){switch(e.label){case 0:return[4,t.setSelfInfo(r)];case 1:return[2,e.sent()]}}))}))}),[t]);return[n,c]},useSnapshot:function(){var e=o(),t=u.default.useState(e.snapshot),r=t[0],n=t[1];return u.default.useEffect((function(){var t=function(e){return n(e)};return e.on("keyframes",t),function(){return e.off("keyframes",t)}})),r},useUserList:function(){var e=o(),t=u.default.useState(e.userList),r=t[0],n=t[1],i=function(e){return n(e)};return u.default.useEffect((function(){return e.on("userListUpdate",i),function(){return e.off("userListUpdate",i)}}),[e]),r},useWebSocketEventCallback:function(e,t,r){void 0===r&&(r=[]);var n=o(),i=function(){return n.off(e,t)},s=p([n,e],r,!0);return u.default.useEffect((function(){return n.on(e,t),i}),s),i}}},exports.parseLiveMsg=V,exports.parseWSClsErr=B;
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("@realsee/jsbridge-x"),t=require("trtc-js-sdk"),i=require("amazon-chime-sdk-js"),o=require("react");function s(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var n=s(e),r=s(t),a=s(o);const l=Symbol("$$REALSEE_LIVE_EVENT$$");function c(e){return e[l]||(e[l]={}),e[l]}class d{hasListener(e){const t=c(this);return t&&t[e]&&t[e].length>0}on(e,t,i){const o=c(this);return o[e]||(o[e]=[]),o[e].push([t,i||!1]),()=>this.off(e,t)}once(e,t){return this.on(e,t,!0)}off(e,t){if(void 0===e)return void((i=this)[l]||delete i[l]);var i;const o=c(this);if(o[e]||(o[e]=[]),void 0===t)return void(o[e].length=0);let s=0;for(;s<o[e].length&&o[e][s][0]!==t;s++);s<o[e].length&&o[e].splice(s,1)}emit(e,...t){let i=!1;const o=c(this)[e]||[];for(let s of o.slice()){const[o,n=!1]=s,r=o(...t);n&&this.off(e,o),!1===r&&(i=!0)}return i}}class u extends d{}function h(e,t,i,o){return new(i||(i=Promise))((function(s,n){function r(e){try{l(o.next(e))}catch(e){n(e)}}function a(e){try{l(o.throw(e))}catch(e){n(e)}}function l(e){var t;e.done?s(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(r,a)}l((o=o.apply(e,t||[])).next())}))}var v,g,p,m,f,_,S,C,E,b,y,T,I;function w(){return(65536*(1+Math.random())|0).toString(16).substring(1)}function R(){return(w()+w()+"-"+w()+"-4"+w().substr(0,3)+"-"+w()+"-"+w()+w()+w()).toLowerCase()}exports.RTCType=void 0,(v=exports.RTCType||(exports.RTCType={})).RealseeBrowserRTC="RealseeBrowserRTC",v.RealseeVRWebViewRTC="RealseeVRWebViewRTC",v.RealseeBrowserChimeRTC="RealseeBrowserChimeRTC",exports.BuiltInRTCType=void 0,(g=exports.BuiltInRTCType||(exports.BuiltInRTCType={})).RealseeXTRTC="trtc",g.RealseeXChimeRTC="chime";class O extends u{constructor(e){super(),this.type=exports.RTCType.RealseeBrowserRTC,this.joined=!1,this.micro=!1,this.voiceId="",this._getVoiceSign=()=>{throw new Error("方法 getVoiceSign 未实现")},this.$dom=document.createElement("div"),this._trtc={client:null,stream:null},this.join=e=>h(this,void 0,void 0,(function*(){var t;this.emit("joinWillStart");const i=yield this._getVoiceSign({voiceId:e.voiceId,roomId:e.roomId,userId:e.userId});this._trtc.client=r.default.createClient(Object.assign({mode:"rtc"},i)),null===(t=this._trtc.client)||void 0===t||t.enableAudioVolumeEvaluation(),this._registerRtcEvent();let o=yield new Promise((t=>{var i;null===(i=this._trtc.client)||void 0===i||i.join({roomId:Number(e.voiceId)}).then((()=>t(!0))).catch((()=>t(!1)))}));return this.joined=o,!!o&&(this._trtc.stream=r.default.createStream({userId:i.userId,audio:!0,video:!1}),o=yield new Promise((e=>{var t;null===(t=this._trtc.stream)||void 0===t||t.initialize().then((()=>e(!0))).catch((()=>e(!1)))})),o=yield new Promise((e=>{var t;null===(t=this._trtc.client)||void 0===t||t.publish(this._trtc.stream).then((()=>e(!0))).catch((()=>e(!1)))})),this.joined=o,this.joined&&this.emit("joined"),o)})),this._handleStreamAdded=e=>{var t;const i=e.stream;console.log("远端流增加: "+i.getId()),null===(t=this._trtc.client)||void 0===t||t.subscribe(i)},this._handleStreamSubscribed=e=>{const t=e.stream;console.log("远端流订阅成功:"+t.getId());const i=`rs-rtc-remote_stream-${t.getId()}`,o=document.createElement("div");o.id=i,this.$dom.appendChild(o),t.play(i)},this._getVoiceSign=e.getVoiceSign,this._initParentDom()}_initParentDom(){this.$dom.id=`rs-rtc-${R()}`,this.$dom.style.display="none",document.body.appendChild(this.$dom)}quit(){return new Promise((e=>h(this,void 0,void 0,(function*(){var t,i;this.joined=!1,this._trtc.stream&&(yield null===(t=this._trtc.client)||void 0===t?void 0:t.unpublish(this._trtc.stream),this._trtc.stream.stop(),this._trtc.stream.close(),this._trtc.stream=null),null===(i=this._trtc.client)||void 0===i||i.leave().then((()=>this._trtc.client=null)).then((()=>e(!0))).catch((()=>e(!1)))}))))}detectMicro(){return new Promise((e=>{const t={audio:!0,video:!1};try{navigator.mediaDevices.getUserMedia(t).then((()=>e(!0))).catch((()=>e(!1)))}catch(t){console.error(t),e(!1)}}))}toggleMicro(e){var t,i,o,s;return Promise.resolve((e?null===(i=null===(t=this._trtc)||void 0===t?void 0:t.stream)||void 0===i?void 0:i.unmuteAudio():null===(s=null===(o=this._trtc)||void 0===o?void 0:o.stream)||void 0===s?void 0:s.muteAudio())||!1)}shock(){throw new Error("Method not implemented.")}_registerRtcEvent(){var e,t,i,o;null===(e=this._trtc.client)||void 0===e||e.on("stream-added",this._handleStreamAdded),null===(t=this._trtc.client)||void 0===t||t.on("stream-subscribed",this._handleStreamSubscribed),null===(i=this._trtc.client)||void 0===i||i.on("audio-volume",(e=>this.emit("userVolumes",[{userId:e.userId,audioVolume:e.audioVolume}]))),null===(o=this._trtc.client)||void 0===o||o.on("error",(e=>this.emit("error",e)))}}class k extends u{constructor(e){super(),this.type=exports.RTCType.RealseeBrowserChimeRTC,this.joined=!1,this.micro=!1,this.voiceId="",this.userId="",this.deviceChangeObserver={},this.audioVideoObserver={},this._getVoiceSign=()=>{throw new Error("方法 getVoiceSign 未实现")},this.$dom=document.createElement("div"),this.$audio=document.createElement("audio"),this._initDom=()=>{this.$audio.id=`rs-rtc-${R()}`,this.$dom.id=`rs-rtc-${R()}`,this.$dom.appendChild(this.$audio),document.body.appendChild(this.$dom)},this.initObservers=()=>{this.deviceChangeObserver={audioInputsChanged:e=>{null==e||e.forEach((e=>{this.logger.info(`Device ID: ${e.deviceId} Microphone: ${e.label}`)}))},audioOutputsChanged:e=>{this.logger.info(`Audio outputs updated: ${e}`)},videoInputsChanged:e=>{this.logger.info(`Video inputs updated: ${e}`)},audioInputMuteStateChanged:(e,t)=>{this.logger.info(`Device ${e.toString()} ${t?"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._registerRtcEvent=()=>{var e,t,o,s,n,r;const a=(null===(o=null===(t=null===(e=this.meetingSession)||void 0===e?void 0:e.configuration)||void 0===t?void 0:t.credentials)||void 0===o?void 0:o.attendeeId)||"";if(a){const e=new Map,t=()=>{const t=[];return e.forEach(((e,i)=>{t.push({userId:e.userId,volume:e.muted||0===e.signalStrength||!Boolean(e.volume)?0:e.volume})})),t};null===(s=this.meetingSession)||void 0===s||s.audioVideo.realtimeSubscribeToAttendeeIdPresence(((o,s,n)=>{var r;if(!s)return e.delete(o),void this.emit("userVolumes",t());null===(r=this.meetingSession)||void 0===r||r.audioVideo.realtimeSubscribeToVolumeIndicator(o,((o,s,r,a)=>{new i.DefaultModality(o).base()===o&&(e.set(o,{userId:n||o,volume:s,muted:r,signalStrength:a}),this.emit("userVolumes",t()))}))})),null===(n=this.meetingSession)||void 0===n||n.audioVideo.realtimeSubscribeToVolumeIndicator(a,((e,t,o,s)=>{new i.DefaultModality(e).base()===e&&null!==s&&1!==s&&this.emit("weakNetwork")})),null===(r=this.meetingSession)||void 0===r||r.audioVideo.realtimeSubscribeToFatalError((e=>this.emit("error",e)))}},this._getVoiceSign=e.getVoiceSign,this._initDom(),this.logger=new i.ConsoleLogger("WebRTCLogger",e.logLevel||i.LogLevel.OFF),this.deviceController=new i.DefaultDeviceController(this.logger),this.initObservers()}join(e){return h(this,void 0,void 0,(function*(){return new Promise(((t,o)=>h(this,void 0,void 0,(function*(){var o;this.emit("joinWillStart");try{const{sdkAppId:s,userId:n,roomId:r,userSig:a}=yield this._getVoiceSign(Object.assign(Object.assign({},e),{roomId:e.roomId||0}));this.userId=n;const{attendence:l,vendor_wrapper:c}=JSON.parse(decodeURIComponent(a)),d=new i.MeetingSessionConfiguration({Meeting:c},{Attendee:{ExternalUserId:l.external_user_id,AttendeeId:l.attendee_id,JoinToken:l.join_token}});this.meetingSession=new i.DefaultMeetingSession(d,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 u={audioVideoDidStart:()=>{var e;null===(e=this.meetingSession)||void 0===e||e.audioVideo.realtimeMuteLocalAudio(),this.joined=!0,this.emit("joined"),t(!0)},audioVideoDidStop:()=>{this.joined=!1,t(!1)}};this.meetingSession.audioVideo.addObserver(u);const h=yield this.deviceController.listAudioInputDevices(!0),v=h.find((e=>"default"===e.deviceId)),g=h.find((e=>""!==e.deviceId));this.audioInput=v||g,yield this.meetingSession.audioVideo.chooseVideoInputDevice(null),yield this.meetingSession.audioVideo.chooseAudioInputDevice((null===(o=this.audioInput)||void 0===o?void 0:o.deviceId)||"default"),this.meetingSession.audioVideo.start()}catch(e){this.emit("error",e),this.logger.error(e.message),t(!1)}}))))}))}quit(){return this.joined?new Promise(((e,t)=>{var o,s;this.joined=!1;const n={audioVideoDidStop:t=>{const o=t.statusCode();o===i.MeetingSessionStatusCode.Left?(this.logger.info("You left the session"),e(!0)):(this.logger.info(`Stopped with a session status code: ${o}`),e(!0))}};null===(o=this.meetingSession)||void 0===o||o.audioVideo.addObserver(n),null===(s=this.meetingSession)||void 0===s||s.audioVideo.stop()})):Promise.resolve(!0)}detectMicro(){return h(this,void 0,void 0,(function*(){return new Promise((e=>{const t={audio:!0,video:!1};try{navigator.mediaDevices.getUserMedia(t).then((()=>e(!0))).catch((()=>e(!1)))}catch(t){this.logger.error(t.message),e(!1)}}))}))}toggleMicro(e){var t,i,o;return h(this,void 0,void 0,(function*(){e?null===(t=this.meetingSession)||void 0===t||t.audioVideo.realtimeUnmuteLocalAudio():null===(i=this.meetingSession)||void 0===i||i.audioVideo.realtimeMuteLocalAudio();const s=null===(o=this.meetingSession)||void 0===o?void 0:o.audioVideo.realtimeIsLocalAudioMuted();return void 0!==s&&e!==s}))}shock(){throw new Error("Method not implemented.")}}exports.RTCJoinedInfoCodeEnum=void 0,(p=exports.RTCJoinedInfoCodeEnum||(exports.RTCJoinedInfoCodeEnum={}))[p.Success=0]="Success",p[p.Failure=1]="Failure",p[p.ReJoin=2]="ReJoin",p[p.NoMicroPermission=3]="NoMicroPermission";class x extends u{constructor({jsBridge:e,getVoiceSign:t}){super(),this.type=exports.RTCType.RealseeVRWebViewRTC,this.joined=!1,this.micro=!1,this.voiceId="",this.options={jsBridge:e,getVoiceSign:t},this.jsBridge.callAndListen("live/userVolumes",(e=>{this.emit("userVolumes",e)})),this.jsBridge.callAndListen("live/weakNetwork",(e=>{e&&this.emit("weakNetwork")}))}get jsBridge(){return this.options.jsBridge}join(e){return h(this,void 0,void 0,(function*(){this.emit("joinWillStart");const{sdkAppId:t,userId:i,userSig:o}=yield this.options.getVoiceSign(e);this.type=e.type;const[s,n]=yield this.jsBridge.callAndBackfeed(`live/join?sdkAppID=${t}&userID=${i}&roomID=${Number(e.voiceId)}&userSig=${o}`);return s?s.code===exports.RTCJoinedInfoCodeEnum.Success?(this.emit("joined"),this.joined=!0):(this.emit("error",s),this.joined=!1):(this.emit("error",n||new Error("加入房间失败:未知异常。")),this.joined=!1),this.joined}))}quit(){return h(this,void 0,void 0,(function*(){const[e,t]=yield this.jsBridge.callAndBackfeed("live/quit");return null===e&&this.emit("error",t||new Error("退出房间失败:未知异常。")),this.joined=!1,!!e}))}detectMicro(){return h(this,void 0,void 0,(function*(){const[e,t]=yield this.jsBridge.detectMicro();return null===e?(this.emit("error",t||new Error("麦克风监测异常!")),!1):e}))}toggleMicro(e){return h(this,void 0,void 0,(function*(){const[t,i]=yield this.jsBridge.callAndBackfeed("live/toggleMicro?flag="+(e?1:0));return null===t?(this.emit("error",i||new Error("麦克风监测异常!")),!1):(this.micro=t,t)}))}shock(){this.jsBridge.shock(1)}}function L(e){switch(e){case 1001:return exports.WebSocketCloseError.Err_1001;case 1002:return exports.WebSocketCloseError.Err_1002;case 1003:return exports.WebSocketCloseError.Err_1003;case 1006:return exports.WebSocketCloseError.Err_1006;case 1007:return exports.WebSocketCloseError.Err_1007;case 1008:return exports.WebSocketCloseError.Err_1008;case 1009:return exports.WebSocketCloseError.Err_1009}return exports.WebSocketCloseError.Err_unknown}function N(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}exports.Command=void 0,(m=exports.Command||(exports.Command={})).SelfUserInfo="SELF_USER_INFO",m.RoomInfo="ROOM_INFO",m.RTCInfo="RTC_INFO",m.UserList="USER_LIST",m.BuiltinMsg="BUILTIN_MSG",m.CustomEvent="CUSTOM_EVENT",m.KeyframeSync="KEYFRAME_SYNC",m.UserKickOut="USER_KICK_OUT",exports.BuiltinEventType=void 0,(f=exports.BuiltinEventType||(exports.BuiltinEventType={})).UserChange="user_change",f.RoomChange="room_change",exports.BuiltinActionType=void 0,(_=exports.BuiltinActionType||(exports.BuiltinActionType={})).UserMicroStatus="change_micro_status",_.UserMicroStatusSync="sync_micro_status",_.UserPermission="change_permission",_.UserStatus="change_status",_.UserInfo="change_info",_.RoomClose="close",exports.MicroStatus=void 0,(S=exports.MicroStatus||(exports.MicroStatus={})).OPEN="OPEN",S.CLOSE="CLOSE",exports.LiveState=void 0,(C=exports.LiveState||(exports.LiveState={}))[C.NOTINITIALIZED=-1]="NOTINITIALIZED",C[C.CONNECTING=0]="CONNECTING",C[C.OPEN=1]="OPEN",C[C.CLOSED=3]="CLOSED",exports.UserStatus=void 0,(E=exports.UserStatus||(exports.UserStatus={}))[E.Normal=0]="Normal",E[E.Removed=1]="Removed",E[E.Replaced=2]="Replaced",exports.MemUserStatus=void 0,(b=exports.MemUserStatus||(exports.MemUserStatus={})).WAIT_ENTER="WAIT_ENTER",b.ONLINE="ONLINE",b.LEAVE="LEAVE",b.KICK_OUT="KICK_OUT",b.BE_REPLACE="BE_REPLACE",b.EXCEPTION="EXCEPTION",exports.WebSocketState=void 0,(y=exports.WebSocketState||(exports.WebSocketState={}))[y.NOTINITIALIZED=-1]="NOTINITIALIZED",y[y.CONNECTING=0]="CONNECTING",y[y.OPEN=1]="OPEN",y[y.CLOSING=2]="CLOSING",y[y.CLOSED=3]="CLOSED",exports.WebSocketErrorType=void 0,(T=exports.WebSocketErrorType||(exports.WebSocketErrorType={})).Error="Error",T.Close="Close",T.MicroAuth="MicroAuth",T.DuplicateConnect="DuplicateConnect",T.IllegalURL="IllegalURL",T.Unknown="Unknown",T.IllegalArgs="IllegalArgs",exports.WebSocketCloseError=void 0,(I=exports.WebSocketCloseError||(exports.WebSocketCloseError={})).Err_1001="CLOSE_GOING_AWAY",I.Err_1002="CLOSE_PROTOCOL_ERROR",I.Err_1003="CLOSE_UNSUPPORTED",I.Err_1006="CLOSE_ABNORMAL",I.Err_1007="Unsupported Data",I.Err_1008="Policy Violation",I.Err_1009="CLOSE_TOO_LARGE",I.Err_unknown="unknown";var M,j,V=(M=function(e,t){var i;Object.defineProperty(t,"__esModule",{value:!0}),t.LogLevel=void 0,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"}(i=t.LogLevel||(t.LogLevel={})),t.default=i},M(j={exports:{}},j.exports),j.exports),A=N(V);const B=globalThis.navigator.userAgent,U=/android/gi.test(B),D=/iPhone|iPad\s+OS/gi.test(B),P=/MicroMessenger/gi.test(B)&&/miniProgram/gi.test(B),W=/realsee/gi.test(B);function $(e){return"[object Object]"===Object.prototype.toString.call(e)}function F(e,t){return e===t||typeof e==typeof t&&!(!Number.isNaN(e)||!Number.isNaN(t))}function K(e,t){return!!F(e,t)||($(e)&&$(t)?function(e,t){const i=Object.getOwnPropertyNames(e),o=Object.getOwnPropertyNames(t);if(i.length!==o.length)return!1;for(let o=0,s=i.length;o<s;o++){const s=i[o];if(!F(e[s],t[s]))return!1}return!0}(e,t):!(!Array.isArray(e)||!Array.isArray(t))&&function(e,t){if(e.length!==t.length)return!1;for(let i=0,o=e.length;i<o;i++)if(!F(e[i],t[i]))return!1;return!0}(e,t))}function G(e,t){return!!F(e,t)||($(e)&&$(t)?function(e,t){const i=Object.getOwnPropertyNames(e),o=Object.getOwnPropertyNames(t);if(i.length!==o.length)return!1;for(let o=0,s=i.length;o<s;o++){const s=i[o];if(!G(e[s],t[s]))return!1}return!0}(e,t):!(!Array.isArray(e)||!Array.isArray(t))&&function(e,t){if(e.length!==t.length)return!1;for(let i=0,o=e.length;i<o;i++)if(!G(e[i],t[i]))return!1;return!0}(e,t))}function q(e,t,i){return i.deep?G(e,t):K(e,t)}var J;!function(e){e.info="INFO",e.log="LOG",e.error="ERROR",e.warn="WARN"}(J||(J={}));const H=(e,t=[])=>{switch(t.unshift(`Realsee Live ${(()=>{const e=new Date;return`[${e.getFullYear()}-${(e.getMonth()+1).toString().padStart(2,"0")}-${e.getDate().toString().padStart(2,"0")} ${e.getHours().toString().padStart(2,"0")}:${e.getMinutes().toString().padStart(2,"0")}:${e.getSeconds().toString().padStart(2,"0")}.${e.getMilliseconds()}]`})()} <${e}> `),e){case J.info:return console.info(...t);case J.error:return console.error(...t);case J.warn:return console.warn(...t);default:return console.log(...t)}};var X={log:(...e)=>H(J.log,e),info:(...e)=>H(J.info,e),error:(...e)=>H(J.error,e),warn:(...e)=>H(J.warn,e)};class Y extends d{constructor(e){super(),this._options={timeout:1e4,shouldReconnect:(e,t)=>{if(1008!==e.code&&1011!==e.code)return[0,3e3,1e4][t.attempts]},should1000Reconnect:!1,ignoreConnectivityEvents:!1,automaticOpen:!1},this._attempts=0,this._reconnects=-1,this._reconnectWhenOnlineAgain=!1,this._explicitlyClosed=!1,this._connectivityEventsAttached=!1,this._clearPendingReconnectIfNeeded=()=>{this._pendingReconnect&&(clearTimeout(this._pendingReconnect),this._pendingReconnect=void 0)},this._online=e=>{this._reconnectWhenOnlineAgain&&(this._clearPendingReconnectIfNeeded(),this._reconnect(e))},this._offline=()=>{var e;this._reconnectWhenOnlineAgain=!0,null===(e=this._realWebSocket)||void 0===e||e.close(1e3)},this._detachConnectivityEvents=()=>{this._connectivityEventsAttached&&(null===globalThis||void 0===globalThis||globalThis.removeEventListener("online",this._online),null===globalThis||void 0===globalThis||globalThis.removeEventListener("offline",this._offline),this._connectivityEventsAttached=!1)},this._attachConnectivityEvents=()=>{this._connectivityEventsAttached||(null===globalThis||void 0===globalThis||globalThis.addEventListener("online",this._online),null===globalThis||void 0===globalThis||globalThis.addEventListener("offline",this._offline),this._connectivityEventsAttached=!0)},this.send=e=>{var t,i,o;(null===(t=this._realWebSocket)||void 0===t?void 0:t.readyState)===(null===(i=this._realWebSocket)||void 0===i?void 0:i.OPEN)&&(null===(o=this._realWebSocket)||void 0===o||o.send(e))},this.close=(e,t)=>{var i;return"number"!=typeof e&&(t=e,e=1e3),this._clearPendingReconnectIfNeeded(),this._reconnectWhenOnlineAgain=!1,this._explicitlyClosed=!0,this._detachConnectivityEvents(),null===(i=this._realWebSocket)||void 0===i?void 0:i.close(e,t)},this.open=e=>{var t,i;e&&(this._url=e),(null===(t=this._realWebSocket)||void 0===t?void 0:t.readyState)!==WebSocket.OPEN&&(null===(i=this._realWebSocket)||void 0===i?void 0:i.readyState)!==WebSocket.CONNECTING&&(this._clearPendingReconnectIfNeeded(),this._reconnectWhenOnlineAgain=!1,this._explicitlyClosed=!1,this._createWebSocket())},this._createWebSocket=()=>{var e,t,i;const o="string"==typeof this._url?this._url:null===(e=this._url)||void 0===e?void 0:e.call(this,this);if(!o)return;this._pendingReconnect=void 0,this._realWebSocket=new WebSocket(o,this._protocols||void 0),this._attempts=this._attempts+1,this.emit("connecting",new CustomEvent("connecting",{detail:{attempts:this._attempts,reconnects:this._reconnects}}));this._connectTimeout=setTimeout((()=>{this._connectTimeout=void 0,this._detachConnectivityEvents(),this.emit("timeout",new CustomEvent("connecting",{detail:{attempts:this._attempts,reconnects:this._reconnects}}))}),null===(t=this._options)||void 0===t?void 0:t.timeout),this._dispatchWebSocketEvent(),(null===(i=this._options)||void 0===i?void 0:i.ignoreConnectivityEvents)||this._attachConnectivityEvents()},this._dispatchWebSocketEvent=()=>{var e,t,i,o;null===(e=this._realWebSocket)||void 0===e||e.addEventListener("open",this._webSocketOpenHandler),null===(t=this._realWebSocket)||void 0===t||t.addEventListener("close",this._webSocketCloseHandler),null===(i=this._realWebSocket)||void 0===i||i.addEventListener("error",this._webSocketErrorHandler),null===(o=this._realWebSocket)||void 0===o||o.addEventListener("message",this._webSocketMessageHandler)},this._webSocketOpenHandler=e=>{this._connectTimeout&&(clearTimeout(this._connectTimeout),this._connectTimeout=void 0);const t=++this._reconnects,i=this._attempts;return this._attempts=0,this._reconnectWhenOnlineAgain=!1,this.emit("open",Object.assign(e,{detail:{reconnects:t,attempts:i}}))},this._webSocketCloseHandler=e=>(this._reconnect(e),this.emit("close",e)),this._webSocketErrorHandler=e=>this.emit("error",new CustomEvent("error",{detail:{error:e}})),this._webSocketMessageHandler=e=>this.emit("message",e),e&&this.setOptions(e)}get attempts(){return this._attempts}setOptions(e){if(!e)return;this._url=e.url,this._protocols=e.protocols;const t=Object.assign(this._options,e.robustOptions||{});if("number"!=typeof(null==t?void 0:t.timeout))throw new Error("timeout must be the number of milliseconds to timeout a connection attempt");if("function"!=typeof(null==t?void 0:t.shouldReconnect))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=t,this._options.automaticOpen&&this._createWebSocket()}_reconnect(e){var t,i,o,s;if(!(null===(t=this._options)||void 0===t?void 0:t.should1000Reconnect)&&1e3===e.code||this._explicitlyClosed)return void(this._attempts=0);if(!1===(null===(i=null===globalThis||void 0===globalThis?void 0:globalThis.navigator)||void 0===i?void 0:i.onLine))return void(this._reconnectWhenOnlineAgain=!0);const n=null===(s=null===(o=this._options)||void 0===o?void 0:o.shouldReconnect)||void 0===s?void 0:s.call(o,e,this);"number"==typeof n&&(this._pendingReconnect=setTimeout(this._createWebSocket,n))}}class Z extends d{constructor(){super(),this._ws=new Y,this._state=exports.LiveState.NOTINITIALIZED,this._addWebSocketEventListeners=()=>{this._ws.on("close",this._handleCloseEvent),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)},this._removeWebSocketEventListeners=()=>{this._ws.off("close",this._handleCloseEvent),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)},this._handleCloseEvent=e=>{X.info(`live room closed bacause of ${e.code}-${e.reason||L(e.code)}`),this.state=exports.LiveState.CLOSED},this._handleConnectingEvent=e=>{X.info("live room is connecting",e.detail),this.state=exports.LiveState.CONNECTING},this._handleErrorEvent=e=>{X.error("live room error",e),this.state=exports.LiveState.CLOSED},this._handleMessageEvent=e=>{let t=(()=>{try{return JSON.parse(e.data)}catch(t){return e.data}})();this.emit("message",t)},this._handleOpenEvent=e=>{X.info("live room open",e.detail),this.state=exports.LiveState.OPEN},this._handleTimeoutEvent=e=>{X.error("live room connect timeout!",e.detail),this.state=exports.LiveState.CLOSED},this.dispose=()=>h(this,void 0,void 0,(function*(){return this._removeWebSocketEventListeners(),yield this.close("live room close by controller disposed!")})),this.open=e=>this._ws.open(e),this.close=(e,t)=>new Promise((i=>{this._ws.once("close",(()=>i(!0))),this._ws.close(e,t)})),this._addWebSocketEventListeners()}set state(e){const t=JSON.parse(JSON.stringify(this._state));this._state=e,this.emit("stateChange",this.state,t)}get state(){return this._state}sendMessage(e=""){if(null==e||""===e)throw new Error("live message is empty!");if(this.state===exports.LiveState.OPEN)return this._ws.send(JSON.stringify(e));throw new Error("live has not yet been initialized!")}}const z=e=>Promise.reject("unimplemented method GetVoiceSign"),Q=(e,t={},i=[])=>({command:e,front_request_id:R(),data:Object.assign(Object.assign({},t),{to_user_ids:Array.isArray(i)?i:[i]})});class ee extends d{constructor(e){var t;super(),this._options={},this.keyframes=new d,this._buildInData={keyframes:{}},this.getFramesByKey=e=>this.snapshot[e],this.sendKeyframe=(e,t)=>{if(this.state!==exports.LiveState.OPEN)return!1;this._buildInData.keyframes=Object.assign(Object.assign({},this._buildInData.keyframes),{[e]:t});const i=Q(exports.Command.KeyframeSync,this.snapshot);try{return this._controller.sendMessage(i),!0}catch(e){return X.error(e),!1}},this._controller=new Z,this._addLiveControllerEventListeners=()=>{this._controller.on("stateChange",this._handleStateChange),this._controller.on("message",this._handleMessage)},this._removeLiveControllerEventListeners=()=>{this._controller.off("stateChange",this._handleStateChange),this._controller.off("message",this._handleMessage)},this._handleStateChange=(e,t)=>this.emit("stateChange",e,t),this._handleMessage=e=>h(this,void 0,void 0,(function*(){var t,i,o,s,n,r;if("object"==typeof e){const{command:a,data:l,frontRequestId:c,code:d,message:u}=e;if("SUCCESS"===d)switch(a){case exports.Command.SelfUserInfo:{const e=l;q(this.selfInfo,e,{deep:!0})||(this._buildInData.selfInfo=e,this.emit("selfInfoUpdate",this._buildInData.selfInfo,c));break}case exports.Command.RoomInfo:{const e=l;this._buildInData.roomInfo=Object.assign({},e),this.emit("readyKeyframeSync",e.last_frame||{});break}case exports.Command.RTCInfo:{const{voice_id:e,type:a}=l;if(null===(t=this.$RTC)||void 0===t?void 0:t.joined)X.warn("已加入语音房间,无需重复加入!");else{if(yield null===(i=this.$RTC)||void 0===i?void 0:i.join({voiceId:e,userId:(null===(o=this.selfInfo)||void 0===o?void 0:o.id)||"",roomId:null===(s=this.roomInfo)||void 0===s?void 0:s.info.room_code,type:a})){const e=null!==(n=this._options.initialMicroStatus)&&void 0!==n?n:exports.MicroStatus.OPEN;yield null===(r=this.$RTC)||void 0===r?void 0:r.toggleMicro(e===exports.MicroStatus.OPEN)}else X.error("加入语音房间失败")}break}case exports.Command.UserList:{const e=l;this._buildInData.userList=e,this.emit("userListUpdate",this.userList,c);break}case exports.Command.CustomEvent:{const e=l;this.emit("broadcast",e,c);break}case exports.Command.KeyframeSync:{const e=l,t=Object.keys(e).reduce(((t,i)=>{if(q(e[i],this._buildInData.keyframes[i],{deep:!0}))return t;const o=[e[i],this._buildInData.keyframes[i],c],s=i;return this.keyframes.emit(s,...o),this._buildInData.keyframes[i]=e[i],t[i]=e[i],t}),{});this.emit("keyframes",t,c);break}case exports.Command.BuiltinMsg:{const e=l;this.emit("builtinEvent",e),e.event_type===exports.BuiltinEventType.UserChange&&this.emit("userChange",e),e.event_type===exports.BuiltinEventType.RoomChange&&this.emit("roomChange",e),e.event_type===exports.BuiltinEventType.UserChange&&e.action===exports.BuiltinActionType.UserMicroStatus&&(yield this.toggleMicro(e.data.status===exports.MicroStatus.OPEN)),e.event_type===exports.BuiltinEventType.RoomChange&&e.action===exports.BuiltinActionType.RoomClose&&(yield this.exit());break}case exports.Command.UserKickOut:this.emit("kickOut");break;default:console.warn("unknown command: ",a)}else this.emit("error",e)}})),this._clearLiveData=()=>{this._buildInData={keyframes:{}}},this.connect=(e={})=>h(this,void 0,void 0,(function*(){var t,i,o,s;if(this._options.url=null!==(i=null!==(t=e.url)&&void 0!==t?t:this._options.url)&&void 0!==i?i:"",this._options.getTicket=null!==(o=e.getTicket)&&void 0!==o?o:this._options.getTicket,this._options.initialMicroStatus=null!==(s=e.rtcMicStatus)&&void 0!==s?s:this._options.initialMicroStatus,!/^ws(s):\/\//.test(this._options.url)||"function"!=typeof this._options.getTicket)return/^ws(s):\/\//.test(this._options.url)?"function"!=typeof this._options.getTicket&&new Error("getTicket muse be function"):new Error("Illegal realsee live room link");const{force:n=!1}=e,r=this.state;if(r===exports.LiveState.CONNECTING||r===exports.LiveState.OPEN){if(!n)return new Error("已有Live实例正在连接中,请勿重复连接!");try{yield this._controller.close("force close by connect")}catch(e){console.warn(e)}}this._clearLiveData();const a=function(e,t){const i=-1!==e.indexOf("?");return e+Object.keys(t).reduce(((e,o,s)=>`${e}${0!==s||i?"&":"?"}${o}=${t[o]}`),"")}(this._options.url,{ticket:yield this._options.getTicket(),force:Number(!!n)});return this._controller.open(a),!0})),this.exit=()=>h(this,void 0,void 0,(function*(){var e;this._clearLiveData();try{null===(e=this.$RTC)||void 0===e||e.quit(),yield this.updateStatus(exports.BuiltinEventType.RoomChange,exports.BuiltinActionType.RoomClose,{})}catch(e){X.warn(e)}return yield this._controller.close("user exit")})),this.dispose=()=>h(this,void 0,void 0,(function*(){return this._removeLiveControllerEventListeners(),this._clearLiveData(),yield this._controller.dispose()})),this.setSelfInfo=e=>h(this,void 0,void 0,(function*(){return yield this.updateStatus(exports.BuiltinEventType.UserChange,exports.BuiltinActionType.UserInfo,e)})),this.toggleMicro=e=>h(this,void 0,void 0,(function*(){var t,i,o;if(!(null===(i=null===(t=this.selfInfo)||void 0===t?void 0:t.permission)||void 0===i?void 0:i.control_own_micro))return!1;const s=yield null===(o=this.$RTC)||void 0===o?void 0:o.toggleMicro(e);return s&&(yield this.updateStatus(exports.BuiltinEventType.UserChange,exports.BuiltinActionType.UserMicroStatus,{status:e?exports.MicroStatus.OPEN:exports.MicroStatus.CLOSE},[])),s})),this.forbidMicro=(e,t)=>h(this,void 0,void 0,(function*(){var i,o;return!("function"==typeof this._options.canForbidUserMicro&&!this._options.canForbidUserMicro(t))&&(!!(null===(o=null===(i=this.selfInfo)||void 0===i?void 0:i.permission)||void 0===o?void 0:o.control_other_micro)&&(yield this.updateStatus(exports.BuiltinEventType.UserChange,exports.BuiltinActionType.UserMicroStatus,{status:e},t)))})),this.forbidSync=(e,t)=>h(this,void 0,void 0,(function*(){var i,o;return!("function"==typeof this._options.canForbidUserSync&&!this._options.canForbidUserSync(t))&&(!!(null===(o=null===(i=this.selfInfo)||void 0===i?void 0:i.permission)||void 0===o?void 0:o.control_other_sync)&&(yield this.updateStatus(exports.BuiltinEventType.UserChange,exports.BuiltinActionType.UserPermission,{sync_frame:e},t)))})),this.kick=e=>h(this,void 0,void 0,(function*(){var t,i;return!("function"==typeof this._options.canForbidUserKick&&!this._options.canForbidUserKick(e))&&(!!(null===(i=null===(t=this.selfInfo)||void 0===t?void 0:t.permission)||void 0===i?void 0:i.change_other_status)&&(yield this.updateStatus(exports.BuiltinEventType.UserChange,exports.BuiltinActionType.UserStatus,{status:"KICK_OUT"},e)))})),this._addLiveControllerEventListeners(),this._options=Object.assign({initialMicroStatus:exports.MicroStatus.OPEN},e),this._options.jsBridge=e.jsBridge?e.jsBridge:e.useBuiltInJsBridge?new n.default:void 0,this._options.getVoiceSign=null!==(t=e.getVoiceSign)&&void 0!==t?t:z,this._options.rtc=(()=>{if(e.rtc)return e.rtc;if(e.rtcType)switch(e.getVoiceSign||X.error("GetVoiceSign method must be passed when using built-in RTC instances"),e.rtcType){case exports.RTCType.RealseeVRWebViewRTC:return this._options.jsBridge?new x({jsBridge:this._options.jsBridge,getVoiceSign:this._options.getVoiceSign}):void X.error("JsBridge instance must be passed when using built-in VRWebViewRTC instances");case exports.RTCType.RealseeBrowserChimeRTC:return new k({getVoiceSign:this._options.getVoiceSign,logLevel:e.__debug__?A.DEBUG:A.ERROR});case exports.RTCType.RealseeBrowserRTC:return new O({getVoiceSign:this._options.getVoiceSign});default:return void X.error("unknown built-in RTC type")}return e.useBuiltInRTC?(e.getVoiceSign||X.error("GetVoiceSign method must be passed when using built-in RTC instances"),this._options.jsBridge?W&&(U||D)||P?new x({jsBridge:this._options.jsBridge,getVoiceSign:this._options.getVoiceSign}):e.builtInRTCType===exports.BuiltInRTCType.RealseeXChimeRTC?new k({getVoiceSign:this._options.getVoiceSign}):new O({getVoiceSign:this._options.getVoiceSign}):void X.error("jsBridge instance must be passed when using built-in RTC instances")):void 0})(),this._options.rtc||X.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}updateStatus(e,t,i,o){return h(this,void 0,void 0,(function*(){if(this.state!==exports.LiveState.OPEN)return!1;const s=Object.assign({event_type:e,action:t},{data:i}),n=Q(exports.Command.BuiltinMsg,s,o);try{return this._controller.sendMessage(n),!0}catch(e){return X.error(e),!1}}))}broadcast(e,t,i){return this.state===exports.LiveState.OPEN&&new Promise(((o,s)=>{const n=Q(exports.Command.CustomEvent,e,t),r=n.front_request_id,a=i?setTimeout((()=>{s(new Error("RESPONSE TIMEOUT")),this.off("broadcast",l)}),i):void 0,l=(e,t)=>{t===r&&(a&&clearTimeout(a),this.off("broadcast",l),o(e))};this.on("broadcast",l);try{this._controller.sendMessage(n)}catch(e){s(e)}}))}}const te=e=>{var t,i;return(null===window||void 0===window?void 0:window.__Realsee_Live__)&&(null===(i=null===(t=null===window||void 0===window?void 0:window.__Realsee_Live__)||void 0===t?void 0:t.dispose)||void 0===i||i.call(t),window.__Realsee_Live__=null),new ee(e)};exports.BrowserRTC=O,exports.BrowserRTC4Chime=k,exports.CoreRTC=u,exports.VRWebViewRTC=x,exports.createLive=te,exports.createLiveReact=function(e){const t=o.createContext(null),i=te(e),s=i.jsBridge,n=()=>{const e=a.default.useContext(t);if(!e)throw new Error("LiveProvider never found.");return e},r=o.useCallback((()=>n()),[n]),l=o.useCallback((()=>n().$RTC),[n]),c=o.useCallback((()=>l()),[l]),d=o.useCallback((e=>h(this,void 0,void 0,(function*(){return yield n().connect(e)}))),[]);return{live:i,jsBridge:s,LiveProvider:e=>a.default.createElement(t.Provider,{value:i},e.children),unsafe__useLiveInstance:r,unsafe__useRTCInstance:c,useConnect:d,useKeyframe:function(e){const t=n(),[i,o]=a.default.useState(t.getFramesByKey(e));return a.default.useEffect((()=>{const i=e,s=e=>o(e);return t.keyframes.on(i,s),()=>t.keyframes.off(i,s)}),[t]),[i,a.default.useCallback((i=>t.sendKeyframe(e,i)),[t])]},useKeyframeUpdateCallback:function(e,t,i=[]){const o=n(),s=[o,name,...i],r=()=>o.keyframes.off(e,t);return a.default.useEffect((()=>(o.keyframes.on(e,t),r)),s),r},useLiveAction:function(){const e=n(),t=a.default.useCallback((t=>h(this,void 0,void 0,(function*(){return yield e.connect(t)}))),[e]),i=a.default.useCallback((t=>e.toggleMicro(t)),[e]),o=a.default.useCallback(((t,i,o=0)=>h(this,void 0,void 0,(function*(){return yield e.broadcast(t,i,o)}))),[e]),s=a.default.useCallback((()=>h(this,void 0,void 0,(function*(){return yield e.exit()}))),[e]),r=a.default.useCallback((t=>h(this,void 0,void 0,(function*(){return yield e.kick(t)}))),[e]),l=a.default.useCallback(((t,i=[])=>h(this,void 0,void 0,(function*(){return yield e.forbidMicro(t,i)}))),[e]),c=a.default.useCallback(((t,i=[])=>e.forbidSync(t,i)),[e]),d=a.default.useCallback((t=>e.getFramesByKey(t)),[e]);return{connect:t,broadcast:o,exit:s,kick:r,toggleMicro:i,forbidMicro:l,forbidSync:c,sendKeyframe:a.default.useCallback(((t,i)=>e.sendKeyframe(t,i)),[e]),getFramesByKey:d,setSelfInfo:a.default.useCallback((t=>e.setSelfInfo(t)),[e]),updateStatus:a.default.useCallback(((t,i,o,s)=>e.updateStatus(t,i,o,s)),[e])}},useLiveEventCallback:function(e,t,i=[]){const o=n(),s=()=>o.off(e,t),r=[o,e,...i];return a.default.useEffect((()=>(o.on(e,t),s)),r),s},useLiveState:function(){const e=n(),[t,i]=a.default.useState(e.state);return a.default.useEffect((()=>{const t=e=>i(e);return e.on("stateChange",t),()=>e.off("stateChange",t)}),[e]),t},useRTCAction:function(){const e=n(),t=a.default.useCallback((t=>e.$RTC.join(t)),[e]);return{join:t,quit:a.default.useCallback((()=>e.$RTC.quit()),[e]),shock:a.default.useCallback((()=>{var t,i;return null===(i=(t=e.$RTC).shock)||void 0===i?void 0:i.call(t)}),[e]),toggleMicro:a.default.useCallback((t=>e.$RTC.toggleMicro(t)),[e]),detectMicro:a.default.useCallback((()=>e.$RTC.detectMicro()),[e])}},useRTCEventCallback:function(e,t,i=[]){const o=n(),s=()=>o.$RTC.off(e,t),r=[o,e,...i];return a.default.useEffect((()=>(o.$RTC.on(e,t),s)),r),s},useSelfInfo:function(){const e=n(),[t,i]=a.default.useState(e.selfInfo||{}),o=e=>i(e);return a.default.useEffect((()=>(e.on("selfInfoUpdate",o),()=>e.off("selfInfoUpdate",o))),[e]),[t,a.default.useCallback((t=>h(this,void 0,void 0,(function*(){return yield e.setSelfInfo(t)}))),[e])]},useKeyframesSnapshot:function(){const e=n(),[t,i]=a.default.useState(e.snapshot);return a.default.useEffect((()=>{const t=e=>i(e);return e.on("keyframes",t),()=>e.off("keyframes",t)})),t},useUserList:function(){const e=n(),[t,i]=a.default.useState(e.userList),o=e=>i(e);return a.default.useEffect((()=>(e.on("userListUpdate",o),()=>e.off("userListUpdate",o))),[e]),t}}},exports.parseLiveMsg=function(e){try{const t=JSON.parse(e),i={code:t.code,message:t.message,command:t.command,roomCode:t.room_code,appID:t.app_id,requestId:t.request_id,frontRequestId:t.front_request_id,triggerUserID:t.trigger_user_id,data:t.data||{}},o=Object.keys(i).filter((e=>void 0===i[e]));return o.length>0&&console.warn(`推送数据格式异常:${o.join(" ")} 值不存在!`),i}catch(e){return!1}},exports.parseWSClsErr=L;
2
2
  //# sourceMappingURL=realsee-live.cjs.production.js.map