@volcengine/vepusher 2.0.4-rc.8 → 2.0.4-rc.9

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.umd.js CHANGED
@@ -1,4 +1,4 @@
1
- (function($,I){typeof exports=="object"&&typeof module<"u"?module.exports=I():typeof define=="function"&&define.amd?define(I):($=typeof globalThis<"u"?globalThis:$||self,$["ve-pusher"]=I())})(this,function(){"use strict";var hh=Object.defineProperty;var ph=($,I,Z)=>I in $?hh($,I,{enumerable:!0,configurable:!0,writable:!0,value:Z}):$[I]=Z;var m=($,I,Z)=>ph($,typeof I!="symbol"?I+"":I,Z);var Ss,Ts,Es,bs,ks,Ps;function $(r,e){for(var t=0;t<e.length;t++){const i=e[t];if(typeof i!="string"&&!Array.isArray(i)){for(const s in i)if(s!=="default"&&!(s in r)){const n=Object.getOwnPropertyDescriptor(i,s);n&&Object.defineProperty(r,s,n.get?n:{enumerable:!0,get:()=>i[s]})}}}return Object.freeze(Object.defineProperty(r,Symbol.toStringTag,{value:"Module"}))}function I(r){return r&&r.__esModule&&Object.prototype.hasOwnProperty.call(r,"default")?r.default:r}var Z={exports:{}},er;function Zs(){return er||(er=1,function(r){var e=Object.prototype.hasOwnProperty,t="~";function i(){}Object.create&&(i.prototype=Object.create(null),new i().__proto__||(t=!1));function s(u,d,c){this.fn=u,this.context=d,this.once=c||!1}function n(u,d,c,h,p){if(typeof c!="function")throw new TypeError("The listener must be a function");var l=new s(c,h||u,p),f=t?t+d:d;return u._events[f]?u._events[f].fn?u._events[f]=[u._events[f],l]:u._events[f].push(l):(u._events[f]=l,u._eventsCount++),u}function a(u,d){--u._eventsCount===0?u._events=new i:delete u._events[d]}function o(){this._events=new i,this._eventsCount=0}o.prototype.eventNames=function(){var d=[],c,h;if(this._eventsCount===0)return d;for(h in c=this._events)e.call(c,h)&&d.push(t?h.slice(1):h);return Object.getOwnPropertySymbols?d.concat(Object.getOwnPropertySymbols(c)):d},o.prototype.listeners=function(d){var c=t?t+d:d,h=this._events[c];if(!h)return[];if(h.fn)return[h.fn];for(var p=0,l=h.length,f=new Array(l);p<l;p++)f[p]=h[p].fn;return f},o.prototype.listenerCount=function(d){var c=t?t+d:d,h=this._events[c];return h?h.fn?1:h.length:0},o.prototype.emit=function(d,c,h,p,l,f){var g=t?t+d:d;if(!this._events[g])return!1;var _=this._events[g],T=arguments.length,b,v;if(_.fn){switch(_.once&&this.removeListener(d,_.fn,void 0,!0),T){case 1:return _.fn.call(_.context),!0;case 2:return _.fn.call(_.context,c),!0;case 3:return _.fn.call(_.context,c,h),!0;case 4:return _.fn.call(_.context,c,h,p),!0;case 5:return _.fn.call(_.context,c,h,p,l),!0;case 6:return _.fn.call(_.context,c,h,p,l,f),!0}for(v=1,b=new Array(T-1);v<T;v++)b[v-1]=arguments[v];_.fn.apply(_.context,b)}else{var j=_.length,R;for(v=0;v<j;v++)switch(_[v].once&&this.removeListener(d,_[v].fn,void 0,!0),T){case 1:_[v].fn.call(_[v].context);break;case 2:_[v].fn.call(_[v].context,c);break;case 3:_[v].fn.call(_[v].context,c,h);break;case 4:_[v].fn.call(_[v].context,c,h,p);break;default:if(!b)for(R=1,b=new Array(T-1);R<T;R++)b[R-1]=arguments[R];_[v].fn.apply(_[v].context,b)}}return!0},o.prototype.on=function(d,c,h){return n(this,d,c,h,!1)},o.prototype.once=function(d,c,h){return n(this,d,c,h,!0)},o.prototype.removeListener=function(d,c,h,p){var l=t?t+d:d;if(!this._events[l])return this;if(!c)return a(this,l),this;var f=this._events[l];if(f.fn)f.fn===c&&(!p||f.once)&&(!h||f.context===h)&&a(this,l);else{for(var g=0,_=[],T=f.length;g<T;g++)(f[g].fn!==c||p&&!f[g].once||h&&f[g].context!==h)&&_.push(f[g]);_.length?this._events[l]=_.length===1?_[0]:_:a(this,l)}return this},o.prototype.removeAllListeners=function(d){var c;return d?(c=t?t+d:d,this._events[c]&&a(this,c)):(this._events=new i,this._eventsCount=0),this},o.prototype.off=o.prototype.removeListener,o.prototype.addListener=o.prototype.on,o.prefixed=t,o.EventEmitter=o,r.exports=o}(Z)),Z.exports}var Qs=Zs();const Q=I(Qs);var S=(r=>(r.Camera="camera",r.Screen="screen",r.VideoFile="videoFile",r.Microphone="microphone",r.AudioFile="audioFile",r.Image="image",r.MixAudio="mixAudio",r.MixVideo="mixVideo",r.CustomVideo="customVideo",r.CustomAudio="customAudio",r))(S||{}),z=(r=>(r.DeviceCaptured="deviceCaptured",r.DeviceStopCapture="deviceStopCapture",r.Error="error",r.Interrupted="interrupted",r))(z||{}),A=(r=>(r.PushStart="pushStart",r.PushStop="pushStop",r.PushError="pushError",r.RTCConnectStateChanged="rtcConnectStateChanged",r.CaptureFirstVideoFrame="capturefirstvideoframe",r.CaptureFirstAudioFrame="capturefirstaudioframe",r.NotAllowedAutoPlay="notallowedautoplay",r))(A||{}),tr=(r=>(r["120p"]="160x120x15x200",r["180p"]="320x180x15x350",r["240p"]="320x240x15x400",r["360p"]="640x360x15x800",r["480p"]="640x480x15x900",r["720p-1"]="1280x720x15x1500",r["720p-2"]="1280x720x25x1500",r["720p-3"]="1280x720x30x1500",r["1080p-1"]="1920x1080x15x2080",r["1080p-2"]="1920x1080x25x3000",r["1080p-3"]="1920x1080x30x3150",r))(tr||{}),rr=(r=>(r["120p"]="120x160x15x200",r["180p"]="180x320x15x350",r["240p"]="240x320x15x400",r["360p"]="360x640x15x800",r["480p"]="480x640x15x900",r["720p-1"]="720x1280x15x1500",r["720p-2"]="720x1280x25x1500",r["720p-3"]="720x1280x30x1500",r["1080p-1"]="1080x1920x15x2080",r["1080p-2"]="1080x1920x25x3000",r["1080p-3"]="1080x1920x30x3150",r))(rr||{}),ir=(r=>(r.STANDARD="48000x40",r.HIGH="48000x128",r))(ir||{}),ne=(r=>(r.VideoStreamChange="videoStreamChange",r.AudioStreamChange="audioStreamChange",r))(ne||{}),sr=(r=>(r[r.init=-1]="init",r[r.new=0]="new",r[r.connecting=1]="connecting",r[r.connected=2]="connected",r[r.disconnected=3]="disconnected",r[r.failed=4]="failed",r[r.closed=5]="closed",r))(sr||{}),it=(r=>(r.SizeChange="sizeChange",r))(it||{}),st=(r=>(r.Portrait="portrait",r.Landscape="landscape",r))(st||{});const nr="720p-1",or="STANDARD";var y=(r=>(r.TRACK_NOT_AVAILABLE="track-not-available",r.UNEXPECTED_TYPE="unexpected-type",r.PLAY_FAILED="play-failed",r.CAPTURE_FAILED="capture-failed",r.NOT_SUPPORTED="not-supported",r.UNEXPECTED_ERROR="unexpected-error",r))(y||{}),E=(r=>(r.AUDIO="audio",r.VIDEO="video",r))(E||{}),D=(r=>(r.ENDED="ended",r.MUTE="mute",r.UNMUTE="unmute",r.PLAY_FAILED="play-failed",r.SIZE_CHANGE="size-change",r))(D||{});const O=[];for(let r=0;r<256;++r)O.push((r+256).toString(16).slice(1));function en(r,e=0){return(O[r[e+0]]+O[r[e+1]]+O[r[e+2]]+O[r[e+3]]+"-"+O[r[e+4]]+O[r[e+5]]+"-"+O[r[e+6]]+O[r[e+7]]+"-"+O[r[e+8]]+O[r[e+9]]+"-"+O[r[e+10]]+O[r[e+11]]+O[r[e+12]]+O[r[e+13]]+O[r[e+14]]+O[r[e+15]]).toLowerCase()}let nt;const tn=new Uint8Array(16);function rn(){if(!nt){if(typeof crypto>"u"||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");nt=crypto.getRandomValues.bind(crypto)}return nt(tn)}const ar={randomUUID:typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};function oe(r,e,t){var s;if(ar.randomUUID&&!r)return ar.randomUUID();r=r||{};const i=r.random??((s=r.rng)==null?void 0:s.call(r))??rn();if(i.length<16)throw new Error("Random bytes length must be >= 16");return i[6]=i[6]&15|64,i[8]=i[8]&63|128,en(i)}class cr{constructor(){m(this,"id",oe());m(this,"_nextNode");m(this,"_track");m(this,"_destNode")}gain(e){if(this._nextNode instanceof dr)return this._nextNode.g=e,this._nextNode;const t=new dr(this,{g:e});return this._nextNode=t,t}connect(e,t){if(!this.available())return;let{_node:i}=this;i||(i=this.createNode(e)),this._node=i,this.previousNode&&this.previousNode.connect(e,i),t&&i.connect(t)}available(){var e;return((e=this.previousNode)==null?void 0:e.available())??!1}destroy(){var e;(e=this._node)==null||e.disconnect(),delete this._node}}class dr extends cr{constructor(t,i){super();m(this,"previousNode");m(this,"_node");m(this,"_g");this.previousNode=t,this._g=i.g}createNode(t){return new GainNode(t,{gain:this._g})}set g(t){this._g=t,this._node&&(this._node.gain.value=t)}}class sn extends cr{constructor(t){super();m(this,"previousNode",null);m(this,"source");this.source=t}available(){return this.source.available()}destroy(){super.destroy()}}class nn extends sn{constructor(){super(...arguments);m(this,"_node")}createNode(t){if(this._node)return this._node;let i;if(this.source instanceof vr){const s=this.source.element();i=new MediaElementAudioSourceNode(t,{mediaElement:s}),s.muted=!1}else{const s=this.source.track();i=new MediaStreamAudioSourceNode(t,{mediaStream:new MediaStream([s])})}return i}}class C extends Error{constructor(t,i,s){super(i);m(this,"code");m(this,"message");m(this,"error");this.code=t,this.message=i,this.error=s,Object.setPrototypeOf(this,C.prototype)}toString(){return`VeCapture Error: ${this.code} ${this.message}`}}const ur={info:{color:"rgba(93, 173, 226, 0)",text:"INFO"},warn:{color:"rgba(255, 119, 0, 0.3)",text:"WARN"},err:{color:"rgba(255, 0, 0, 0.3)",text:"ERR "},succ:{color:"rgba(0, 119, 0, 0.3)",text:"SUCC"}},hr="__debug__",on="[VE-CAPTURE]";function an(){if(typeof location>"u"||typeof localStorage>"u")return!1;let r=!1;return location.href.includes(hr)&&(r=!0),localStorage.getItem(hr)&&(r=!0),r}let L=class{constructor(e){m(this,"moduleName");this.moduleName=e}print(e,t,...i){const s=cn();an()&&console.log(`${s}-${on}%c[${ur[e].text}]%c[${this.moduleName}][${t}]`,`background-color:${ur[e].color};`,"background-color:rgba(0, 0, 0, 0)",...i)}info(e,...t){this.print("info",e,...t)}warn(e,...t){this.print("warn",e,...t)}error(e,...t){this.print("err",e,...t)}success(e,...t){this.print("succ",e,...t)}invoke(e,t){const i=this;return function(...n){i.info(`${t}-invoke`,...n);try{const a=e(...n);return typeof(a==null?void 0:a.then)=="function"?a.then(o=>(i.success(`${t}-result`,o),o)).catch(o=>{throw i.error(`${t}-result`,o),o}):(i.success(`${t}-result`,a),a)}catch(a){i.error(`[${t}-result`,a)}}}};function cn(){const r=new Date;return`${r.toTimeString().split(" ")[0]}:${r.getMilliseconds().toString().padStart(3,"0")}`}function ot(r,e){const t=document.createElement(r);return e.id&&(t.id=e.id),e.classList&&e.classList.forEach(i=>{t.classList.add(i)}),e.style&&Object.assign(t.style,e.style),e.attributes&&Object.entries(e.attributes).forEach(([i,s])=>{i==="muted"&&(t instanceof HTMLVideoElement||t instanceof HTMLAudioElement)?t.muted=!0:t.setAttribute(i,s)}),t}function pr({width:r,height:e}){const t=document.createElement("canvas"),i=t.getContext("2d");if(!i)throw new C(y.NOT_SUPPORTED,"CanvasRenderingContext2D is not supported by user agent");return t.width=r,t.height=e,t.style.width="100%",t.style.height="100%",{context:i,canvas:t}}class at{constructor(e){m(this,"target");m(this,"_eventDict",new Map);this.target=e}on(e,t){let i=this._eventDict.get(e);i||(i=[t]),this._eventDict.set(e,i),this.target.addEventListener(e,t)}off(e,t){let i=this._eventDict.get(e);i&&(i=i.filter(s=>s!==t),this._eventDict.set(e,i),this.target.removeEventListener(e,t))}once(e,t){const i=s=>{t(s),this.off(e,i)};this.on(e,i)}clear(e){const t=this._eventDict.get(e);t&&t.forEach(i=>{this.target.removeEventListener(e,i)})}clearAll(){for(const e of this._eventDict.keys())this.clear(e)}}const x=()=>typeof window>"u";function P(){return navigator.userAgent.toLowerCase()}function ct(r=P()){let e="none";return x()||(r.match("firefox")!==null?e="firefox":r.match("Chrome")!==null?(e="chrome",r.match("Electron")!==null&&(e="electron")):(r.match("Safari")!==null||r.match("AppleWebKit")!==null)&&(e="safari")),e}const lr=ct()==="firefox",Le=ct()==="safari";ct(),!x()&&/crios/i.test(P()),!x()&&/edg\//i.test(P()),!x()&&/edgA/i.test(P()),!x()&&/edgios/i.test(P()),!x()&&/dingtalk/i.test(P()),!x()&&/opr\//.test(P()),!x()&&/(iphone|ipod)/i.exec(P()),!x()&&(/(ipad)/i.exec(P())||/macintosh/i.test(P())&&"ontouchend"in document),!x()&&/macintosh/i.test(P()),!x()&&/micromessenger/i.test(P()),!x()&&P().includes("mobile"),!x()&&/sm-\w+/i.test(P());const dn=!x()&&!!/(iphone|ipad|ipod)/i.exec(P());!x()&&/android/i.test(P()),!x()&&/windows/i.test(P()),!x()&&/openharmony/i.test(P());let mr="0";const un=!x()&&((Ss=P().match(/version\/(\d+)/i))==null?void 0:Ss[1]);Le&&un&&(mr=(Ts=navigator.userAgent.match(/version\/(\d+\.\d+)/i))==null?void 0:Ts[1]),!x()&&((Es=P().match(/firefox\/(\d+)/i))==null||Es[1]);const dt=mr;!x()&&((ks=(bs=P().match(/ ([\d_]+) like mac os x/i))==null?void 0:bs[1])==null||ks.split("_").map(r=>parseInt(r))),!x()&&((Ps=P().match(/chrome\/(\d+)/i))==null||Ps[1]);function hn(){var r;return!!((r=navigator==null?void 0:navigator.permissions)!=null&&r.query)}function ut(){return!!(navigator!=null&&navigator.mediaDevices)}function pn(){var r;return ut()&&!!((r=navigator==null?void 0:navigator.mediaDevices)!=null&&r.getUserMedia)}function ln(){return!!Promise.withResolvers}function mn(){return!(Le&&dt==="16.1")}function fn(){return!(Le&&dt&&["16.1","16.2","16.3"].includes(dt))}function _n(){return!lr}function gn(){return typeof CanvasCaptureMediaStreamTrack<"u"}function vn(r){return typeof r.requestFrame=="function"}function Cn(){return!!ut()&&typeof navigator.mediaDevices.ondevicechange<"u"&&typeof navigator.mediaDevices.addEventListener=="function"}const q={permissionQuery:hn,mediaDevices:ut,settingResolutionInGetDisplayMedia:mn,promiseWithResolvers:ln,getUserMedia:pn,isolateEnumerateDevices:_n,supportIdealParamsInGetDisplayMedia:fn,canvasCaptureMediaStreamTrack:gn,requestFrameOnMediaStream:vn,ondevicechange:Cn};function yn(){if(q.promiseWithResolvers())return Promise.withResolvers();let r,e;const t=new Promise((i,s)=>{r=i,e=s});if(!r||!e)throw Error("resolver and rejector working unexpected");return{promise:t,resolve:r,reject:e}}function fr(r={}){const{timeout:e,message:t}={timeout:0,message:new C(y.UNEXPECTED_ERROR,"unexpected timeout"),...r},{promise:i,resolve:s,reject:n}=yn();if(e<=0)return{promise:i,resolve:s,reject:n};const a=setTimeout(()=>{n(t)},e);return{promise:i,resolve:u=>{clearTimeout(a),s(u)},reject:n}}const Sn={playsinline:"","webkit-playsinline":"","x5-playsinline":"","x5-video-player-type":"h5","x-webkit-airplay":"allow",preload:"metadata",muted:"",crossOrigin:"anonymous"},Tn={playsinline:"","webkit-playsinline":"",preload:"metadata",muted:"",crossOrigin:"anonymous"};class Ee{constructor(e,t=[]){m(this,"id",oe());m(this,"_referenceTracks",[]);m(this,"_element");m(this,"_volumeMode",0);m(this,"_readyLock");m(this,"_releaseReadyLock");m(this,"_throwReadyLock");m(this,"_stream");let i;if(e instanceof MediaStreamTrack){const o=new MediaStream([e]);i=En(o),this._stream=o}else if(e.url)i=bn(e);else throw new C(y.UNEXPECTED_TYPE,`got ${typeof e}, expected: MediaStreamTrack or constraints for creating element`);const{promise:s,resolve:n,reject:a}=fr({timeout:2e3,message:new C(y.PLAY_FAILED,"load media timeout")});this._readyLock=s,this._releaseReadyLock=n,this._throwReadyLock=a,this._element=new at(i),this._bindPlayerEvent(this._element),this._referenceTracks=[...t]}addReferenceTrack(e){this._referenceTracks.push(e)}track(e){this._playElement();let t=this._stream;if((!t||!t.active)&&(t=this._element.target.captureStream(),this._stream=t),e===E.AUDIO){this._upgradeVolumeMode(1e-4);const i=t.getAudioTracks();if(i.length<1)throw new C(y.UNEXPECTED_TYPE,"got empty list of audio tracks");return i[0]}if(e===E.VIDEO){const i=t.getVideoTracks();if(i.length<1)throw new C(y.UNEXPECTED_TYPE,"got empty list of video tracks");return i[0]}throw new C(y.UNEXPECTED_TYPE,`got ${e}, expected: audio, video`)}async _playElement(){if(!(!this._element.target.muted&&this._element.target.volume===this._volumeMode&&!this._element.target.paused))try{this._element.target.muted=!1,this._element.target.volume=this._volumeMode,await this._element.target.play()}catch(e){throw this._handlePlayFailed(),new C(y.PLAY_FAILED,"play element failed",e)}}_bindPlayerEvent(e){e.on("loadedmetadata",()=>{this._releaseReadyLock()}),e.on("error",()=>{this._throwReadyLock(new C(y.PLAY_FAILED,"HTMLMediaElement got error when loading file"))})}_handlePlayFailed(){this._referenceTracks.forEach(e=>{e.handlePlayFailed()})}_upgradeVolumeMode(e){console.warn("update volume mode",e);const t=this._volumeMode>e?this._volumeMode:e;this._volumeMode=t,this._playElement()}element(e=!1){return e&&this._upgradeVolumeMode(1),this._playElement(),this._element.target}isReady(){return this._readyLock}removeReference(e){const t=this._referenceTracks.indexOf(e);this._referenceTracks.splice(t,1),this._referenceTracks.length===0&&this.destroy()}destroy(){this._element.target.srcObject=null,this._element.target.src="",this._element.target.load();const e=[...this._referenceTracks];this._referenceTracks=[],e.forEach(t=>{try{t.destroy()}catch{}})}}function En(r){let e="audio";r.getVideoTracks().length>0&&(e="video");const t=_r(e==="video"?E.VIDEO:E.AUDIO);return t.srcObject=r,t}function bn(r){const{url:e,kind:t,loop:i}=r,s=_r(t);return s.src=e,s.loop=i,s}function _r(r){if(r===E.VIDEO)return ot(E.VIDEO,{style:{width:"100%",height:"100%"},attributes:Sn});if(r===E.AUDIO)return ot(E.AUDIO,{style:{display:"none"},attributes:Tn});throw new C(y.UNEXPECTED_TYPE,`got ${r}, expected: audio, video`)}class ht extends Q{emit(e,...t){const i=this.listenerCount(e);return Promise.resolve().then(()=>{super.emit(e,...t)}),!!i}on(e,t,i){const s=(...n)=>{try{return t(...n)}catch(a){console.error(`[SafeEventEmitter] event listener threw an error when handling [${e}] event: `,a)}};return super.on(e,s,i)}once(e,t,i){const s=(...n)=>{try{return t(...n)}catch(a){console.error(`[SafeEventEmitter] event listener threw an error when handling [${e}] event: `,a)}};return super.once(e,s,i)}}function pt(r){if(typeof r=="number")return r;if(typeof(r==null?void 0:r.exact)=="number")return r.exact;if(typeof(r==null?void 0:r.ideal)=="number")return r.ideal;if(typeof(r==null?void 0:r.max)=="number")return r.max;if(typeof(r==null?void 0:r.min)=="number")return r.min;throw new C(y.UNEXPECTED_TYPE,"unexpected constraints type")}const lt=1e3;class gr{constructor(e){m(this,"id",oe());m(this,"_context");m(this,"_canvas");m(this,"_image");m(this,"_config");m(this,"_readyLock");m(this,"_releaseReadyLock");m(this,"_throwReadyLock");m(this,"_loopTimer");m(this,"_referenceTracks",[]);m(this,"_stream");const t=pt(e.width),i=pt(e.height),s=pt(e.frameRate);this._config={width:t,height:i,frameRate:s};const{context:n,canvas:a}=pr({width:t,height:i});this._context=n,this._canvas=a;const o=kn({url:e.url,width:t,height:i});this._image=new at(o);const{promise:u,resolve:d,reject:c}=fr({timeout:2e3,message:new C(y.PLAY_FAILED,"load image timeout")});this._readyLock=u,this._releaseReadyLock=d,this._throwReadyLock=c,this._bindImageEvent(this._image)}track(){this._paint();const{frameRate:e}=this._config;let t=this._stream;(!t||!t.active)&&(t=this._canvas.captureStream(e),this._stream=t);const i=t.getVideoTracks();if(i.length<1)throw new C(y.UNEXPECTED_TYPE,"got empty list of video tracks");return i[0]}element(){return this._image.target}isReady(){return this._readyLock}_bindImageEvent(e){e.on("load",()=>{this._releaseReadyLock()}),e.on("error",()=>{this._throwReadyLock(new C(y.PLAY_FAILED,"HTMLMediaElement got error when loading file"))})}async _paint(){const{width:e,height:t,frameRate:i}=this._config;this._context.drawImage(this._image.target,0,0,e,t),this._loopTimer&&clearTimeout(this._loopTimer),this._loopTimer=setTimeout(this._paint.bind(this),lt/i)}addReferenceTrack(e){this._referenceTracks.push(e)}removeReference(e){const t=this._referenceTracks.indexOf(e);this._referenceTracks.splice(t,1),console.warn("reference length",this._referenceTracks),this._referenceTracks.length}}function kn({url:r,height:e,width:t}){const i=ot("img",{style:{width:`${t}px`,height:`${e}px`},attributes:{crossOrigin:"anonymous"}});return i.src=r,i}class mt extends ht{constructor(t){super();m(this,"id",oe());m(this,"_track");m(this,"_element");t instanceof MediaStreamTrack?(this._track=new at(t),this._bindTrackEvent(this._track)):t instanceof Ee?(this._element=t,t.addReferenceTrack(this)):t instanceof gr&&(this._element=t)}_bindTrackEvent(t){t.on("ended",this._handleTrackEnded.bind(this)),t.on("mute",()=>{this.emit(D.MUTE)}),t.on("unmute",()=>{this.emit(D.UNMUTE)})}_handleTrackEnded(){this.emit(D.ENDED),this.destroy()}handlePlayFailed(){this.emit(D.PLAY_FAILED)}track(){if(this.logger.info("track"),!this.available())throw new C(y.TRACK_NOT_AVAILABLE,"track is not available when creating MediaStreamTrack");if(this._track)return this._track.target;if(!this._element)throw new C(y.UNEXPECTED_TYPE,"got this._element falsy");const t=this._element.track(this.kind);return this.logger.success("track",t),t}element(){if(this.logger.info("element"),!this.available())throw new C(y.TRACK_NOT_AVAILABLE,"track is not available when creating HTMLMediaElement");if(this._element)return this._element.element();if(!this._track)throw new C(y.UNEXPECTED_TYPE,"got this._track falsy");const t=new Ee(this._track.target,[this]);this._element=t;const i=t.element();return this.logger.success("element",i),i}available(){return!!(this._track||this._element)}destroy(){var t,i,s;(t=this._track)==null||t.clearAll(),(i=this._track)==null||i.target.stop(),this._track&&delete this._track,(s=this._element)==null||s.removeReference(this),delete this._element}}class Fe extends mt{constructor(){super(...arguments);m(this,"kind",E.AUDIO);m(this,"_node")}node(){if(this.logger.info("node",this.id),!this.available())throw new C(y.TRACK_NOT_AVAILABLE,"track is not avaiable when creating node");if(this._node)return this._node;const t=new nn(this);return this._node=t,t}element(){if(this.logger.info("element",this.id),!this.available())throw new C(y.TRACK_NOT_AVAILABLE,"track is not available when creating HTMLMediaElement");if(this._element){const i=this._element.element(!0);if(!(i instanceof HTMLMediaElement))throw new C(y.UNEXPECTED_TYPE,"source should be HTMLMediaElement");return i}if(!this._track)throw new C(y.UNEXPECTED_TYPE,"got this._track falsy");const t=new Ee(this._track.target,[this]);return this._element=t,t.element()}destroy(){var t;this.logger.warn("destroy",this.id),(t=this._node)==null||t.destroy(),super.destroy()}}class Pn extends Fe{constructor(){super(...arguments);m(this,"logger",new L("MicrophoneAudioTrack"))}}class xn extends Fe{constructor(){super(...arguments);m(this,"logger",new L("ScreenAudioTrack"))}}class vr extends Fe{constructor(){super(...arguments);m(this,"logger",new L("MediaAudioTrack"))}handlePlayFailed(){this.emit(D.PLAY_FAILED)}async play(){if(this._element){if(!(this._element instanceof Ee))throw new C(y.UNEXPECTED_TYPE,"element is not TrackMediaElement");return this._element._playElement()}}}class Rn extends Fe{constructor(){super(...arguments);m(this,"logger",new L("CustomAudioTrack"))}}let An=1;const ft=new L("PromiseQueue");class wn{constructor(e){m(this,"lockingPromise",Promise.resolve());m(this,"locks",0);m(this,"name","");m(this,"lockId");m(this,"closeReason");this.lockId=An++,e&&(this.name=e),ft.info(`lock-${this.name}-${this.lockId}`,"is created.")}get isLocked(){return this.locks>0}lock(){this.locks+=1,ft.info(`lock-${this.name}-${this.lockId}`,`locked, current queue ${this.locks}.`);let e;const t=new Promise(s=>{e=()=>{this.locks-=1,ft.info(`lock-${this.name}-${this.lockId}`,`unlocked, current queue ${this.locks}.`),s()}}),i=this.lockingPromise.then(()=>e);return this.lockingPromise=this.lockingPromise.then(()=>t),i}}const On=300,In=3e3,G=new L("Devices");class Dn extends ht{constructor(){super();m(this,"_deviceMap",{audioinput:[],audiooutput:[],videoinput:[]});m(this,"_permissions",{[E.AUDIO]:!1,[E.VIDEO]:!1});m(this,"_changedQueue",new wn("device changed queue"));this._init()}async _init(){this._initDeviceChanged(),await this._initPermissionChanged();const t=Tr(this._permissions);t.length>0&&this._refreshDevices(t)}_initDeviceChanged(){if(G.info("_initDeviceChanged","invoked"),!q.ondevicechange()){G.error("_initDeviceChanged","no supported, use timer instead"),setInterval(()=>{this._handleDeviceChanged()},In);return}q.ondevicechange()&&navigator.mediaDevices.addEventListener("devicechange",()=>{G.info("devicechange"),setTimeout(()=>{this._handleDeviceChanged()},On)})}async _initPermissionChanged(){if(!q.permissionQuery()){G.error("_initPermissionChanged","permission query not supported, silent return");return}try{const t=await navigator.permissions.query({name:"microphone"});this._permissions.audio=t.state==="granted",t.addEventListener("change",()=>{G.info("_initPermissionChanged","update permission for audio"),this._permissions.audio=t.state==="granted"})}catch(t){G.error("_initPermissionChanged",t)}try{const t=await navigator.permissions.query({name:"camera"});this._permissions.video=t.state==="granted",t.addEventListener("change",()=>{G.info("_initPermissionChanged","update permission for video"),this._permissions.video=t.state==="granted"})}catch(t){G.error("_initPermissionChanged",t)}}async _refreshDevices(t){if(!q.mediaDevices())throw new C(y.NOT_SUPPORTED,"mediaDevices is not supported");if(t.length===0)throw new C(y.UNEXPECTED_TYPE,"kinds expect to containt values");let i;if(!q.isolateEnumerateDevices()){const a={};t.forEach(o=>{a[o]=!0}),i=await navigator.mediaDevices.getUserMedia(a)}let s=await navigator.mediaDevices.enumerateDevices();i&&Cr(i),s=s.filter(({deviceId:a})=>!!a);const n={audioinput:[],audiooutput:[],videoinput:[]};s.forEach(a=>{const{kind:o}=a;n[o].push(a)}),this._deviceMap=n}async _acquireUserPermission(t){let i=!1;if(t.forEach(s=>{i=i||!this._permissions[s]}),!i)return{grant:!0};if(!q.getUserMedia())return{grant:!1,reason:new C(y.NOT_SUPPORTED,"getUserMedia is not supported")};try{const s={};t.forEach(a=>{s[a]=!0});const n=await navigator.mediaDevices.getUserMedia(s);return n?(s.audio&&(this._permissions[E.AUDIO]=!0),s.video&&(this._permissions[E.VIDEO]=!0),Cr(n),{grant:!0}):{grant:!1,reason:new C(y.UNEXPECTED_TYPE,"get stream falsy")}}catch(s){return{grant:!1,reason:new C(y.CAPTURE_FAILED,"acquire user permission failed",s)}}}async _handleDeviceChanged(){G.info("_handleDeviceChanged",this._deviceMap,this._permissions);const t=await this._changedQueue.lock();try{const i=Sr(this._deviceMap);let s=[];const n=Tr(this._permissions);n.length===0?G.warn("_handleDeviceChanged","no permission, use empty list"):(await this._refreshDevices(n),s=Sr(this._deviceMap)),s.forEach(a=>{i.findIndex(u=>yr(u,a))!==-1||this.emit("onDeviceStateChanged",{deviceInfo:a,deviceState:"active"})}),i.forEach(a=>{s.findIndex(u=>yr(u,a))!==-1||this.emit("onDeviceStateChanged",{deviceInfo:a,deviceState:"inactive"})})}finally{t()}}async enumerateDevices(t){const i=[];t.forEach(o=>{if(o==="audioinput"||o==="audiooutput")i.push(E.AUDIO);else if(o==="videoinput")i.push(E.VIDEO);else throw new C(y.UNEXPECTED_TYPE,"kind in kinds should be enum MediaDeviceKind")});const{grant:s,reason:n}=await this._acquireUserPermission(i);if(!s)throw n;await this._refreshDevices(i);const a=[];return t.forEach(o=>{a.push(...this._deviceMap[o])}),a}async enableDevices(t){return this._acquireUserPermission(t)}}function Cr(r){r.getTracks().forEach(e=>e.stop())}function yr(r,e){return r.deviceId===e.deviceId}function Sr(r){return Array.from([...r.audioinput.values(),...r.videoinput.values(),...r.audiooutput.values()])}function Tr(r){const e=[];return r.audio&&e.push(E.AUDIO),r.video&&e.push(E.VIDEO),e}const _t=new Dn;class gt{constructor(){m(this,"id",oe())}position(e,t){return new Mn(this,{x:e,y:t})}scale(e){return new Ln(this,{s:e})}available(){var e;return((e=this.previousNode)==null?void 0:e.available())??!1}}class Mn extends gt{constructor(t,i){super();m(this,"previousNode");m(this,"_x");m(this,"_y");this.previousNode=t,this._x=i.x,this._y=i.y}paint(t){t.translate(this._x,this._y)}}class Ln extends gt{constructor(t,i){super();m(this,"previousNode");m(this,"_s");this.previousNode=t,this._s=i.s}paint(t){t.scale(this._s,this._s)}}class Fn extends gt{constructor(t){super();m(this,"previousNode",null);m(this,"_source");this._source=t}available(){return this._source.available()}}class Ne extends Fn{constructor(t,i){super(t);m(this,"_targetWidth");m(this,"_targetHeight");const{width:s,height:n}=i??{};this._targetWidth=s??this._source.width(),this._targetHeight=n??this._source.height()}size(t,i){return new Ne(this._source,{width:t,height:i})}paint(t){const i=this._targetWidth,s=this._targetHeight;t.drawImage(this._source.element(),-i/2,-s/2,i,s)}}class Nn extends mt{constructor(){super(...arguments);m(this,"logger",new L("PictureTrack"));m(this,"kind",E.VIDEO)}element(){const t=super.element();if(!(t instanceof HTMLImageElement))throw new C(y.UNEXPECTED_TYPE,"source should be HTMLVideoElement");return this.logger.info("element",t),t}height(){const{height:t}=this.element();return t??0}width(){const{width:t}=this.element();return t??0}node(){if(!this.available())throw new C(y.TRACK_NOT_AVAILABLE,"track is not avaiable when creating node");const t=new Ne(this);return this.logger.info("node",t),t}destroy(){this.logger.warn("destroy"),super.destroy()}}const Vn=500;class Ve extends mt{constructor(){super(...arguments);m(this,"kind",E.VIDEO);m(this,"sizeChangeTimer");m(this,"watchSizeChangeOnce",()=>{const t=this.width(),i=this.height();this.sizeChangeTimer=setTimeout(()=>{const s=this.width(),n=this.height();(i!==n||t!==s)&&this.emit(D.SIZE_CHANGE,{width:s,height:n})},Vn)})}element(){const t=super.element();if(!(t instanceof HTMLVideoElement))throw new C(y.UNEXPECTED_TYPE,"source should be HTMLVideoElement");return t}node(){if(!this.available())throw new C(y.TRACK_NOT_AVAILABLE,"track is not avaiable when creating node");return new Ne(this)}destroy(){clearTimeout(this.sizeChangeTimer),super.destroy()}}class Un extends Ve{constructor(t){super(t);m(this,"logger",new L("CameraVideoTrack"));this.watchSizeChangeOnce()}height(){const{height:t}=this.track().getSettings();return t??0}width(){const{width:t}=this.track().getSettings();return t??0}}class $n extends Ve{constructor(t){super(t);m(this,"logger",new L("ScreenVideoTrack"));this.watchSizeChangeOnce()}height(){const{height:t}=this.track().getSettings();return t??0}width(){const{width:t}=this.track().getSettings();return t??0}}class Bn extends Ve{constructor(){super(...arguments);m(this,"logger",new L("MediaVideoTrack"))}height(){const{videoHeight:t}=this.element();return t??0}width(){const{videoWidth:t}=this.element();return t??0}}class jn extends Ve{constructor(){super(...arguments);m(this,"logger",new L("CustomVideoTrack"))}height(){const{height:t}=this.track().getSettings();return t??0}width(){const{width:t}=this.track().getSettings();return t??0}}function Er(r,e){let t;if(e!=null&&e.frameRate&&typeof e.frameRate=="number"&&(t=e.frameRate),t)try{r.applyConstraints({...e,frameRate:{min:t,ideal:t}})}catch{}}const W=new L("Capture");async function zn(r){return _t.enumerateDevices(r)}async function Gn(r){_t.removeAllListeners("onDeviceStateChanged"),_t.on("onDeviceStateChanged",r)}async function Hn(r){let e;try{const i={video:r??!0};typeof i.video=="object"&&i.video.facingMode&&delete i.video.deviceId,e=await navigator.mediaDevices.getUserMedia(i)}catch(i){throw new C(y.CAPTURE_FAILED,"got error when capturing camera",i)}const t=e.getVideoTracks()[0];if(r!=null&&r.frameRate&&Er(t,r),!t)throw new C(y.UNEXPECTED_TYPE,"got falsy in track");return new Un(t)}async function qn(r,e){const{video:t,audio:i}=r;let s=t===!0?{}:t;e!=null&&e.displaySurface&&(s.displaySurface=e.displaySurface,delete e.displaySurface),q.settingResolutionInGetDisplayMedia()||(s=!0),!q.supportIdealParamsInGetDisplayMedia()&&typeof s!="boolean"&&(s.width&&typeof s.width=="number"&&(s.width={max:s.width}),s.height&&typeof s.height=="number"&&(s.height={max:s.height}));let n;try{n=await navigator.mediaDevices.getDisplayMedia({video:s,audio:i,...e})}catch(d){throw new C(y.CAPTURE_FAILED,"got error when capture screen",d)}const a=n.getVideoTracks()[0],o=n.getAudioTracks()[0];if(!a)throw new C(y.UNEXPECTED_TYPE,"got falsy in videoTrack");typeof s!="boolean"&&typeof s.frameRate=="number"&&Er(a,s);const u=[];return u.push(new $n(a)),o&&u.push(new xn(o)),u}async function Wn(r){const{url:e,audio:t,video:i,loop:s}=r,n=new Ee({url:e,kind:i?E.VIDEO:E.AUDIO,loop:s}),a=[];return t&&a.push(new vr(n)),i&&a.push(new Bn(n)),await n.isReady(),a}async function Xn(r){const e=new gr(r);return await e.isReady(),new Nn(e)}async function Kn(r){let e;try{const i={audio:r??!0};e=await navigator.mediaDevices.getUserMedia(i)}catch(i){throw new C(y.CAPTURE_FAILED,"got error when capturing microphone",i)}const t=e.getAudioTracks()[0];if(!t)throw new C(y.UNEXPECTED_TYPE,"got falsy in track");return new Pn(t)}function Jn(r){if(!r||r.kind!=="video")throw new C(y.UNEXPECTED_TYPE,"error custom video track type");return new jn(r)}function Yn(r){if(!r||r.kind!=="audio")throw new C(y.UNEXPECTED_TYPE,"error custom audio track type");return new Rn(r)}const Zn=W.invoke(zn,"enumerateInputDevices"),Qn=W.invoke(Hn,"createCameraTrack"),eo=W.invoke(Xn,"createPictureTrack"),br=W.invoke(Wn,"createMediaTracks"),to=W.invoke(Kn,"createMicrophoneTrack"),ro=W.invoke(qn,"createScreenTracks"),io=W.invoke(Gn,"onDeviceChanged"),so=W.invoke(Jn,"createCustomVideoTrack"),no=W.invoke(Yn,"createCustomAudioTrack");var vt=(r=>(r.PAUSING="pausing",r))(vt||{});const oo={sampleRate:48e3,keepAlive:!0},kr=new Map,be=new L("Mixer");class ao extends ht{constructor(t){super();m(this,"id",oe());m(this,"_context");m(this,"_config");m(this,"_nodeList",[]);m(this,"_destNode");m(this,"_bufferNode");m(this,"_track");be.info("ctor",t),this._config={...oo,...t},this._context=co(this._config),this._bindContextEvent(this._context)}mix(t){be.info("mix",t),Ct(this._context);for(const i of this._nodeList)t.includes(i)||i.destroy();this._nodeList=t,this._connect(t,this._destNode),this._nodeList.length===0&&this._appendSlience(this._context,this._destNode)}resume(){return be.info("resume"),this._context.resume()}_connect(t,i){for(const s of t)s.connect(this._context,i)}_appendSlience(t,i){if(!i||this._bufferNode)return;const{sampleRate:s}=t,n=new AudioBuffer({length:100,sampleRate:s}),a=new AudioBufferSourceNode(t,{buffer:n,loop:!0});a.connect(i),this._bufferNode=a}_bindContextEvent(t){t.addEventListener("statechange",this._handleContextStateChange.bind(this))}_handleContextStateChange(){const t=this._context;(t.state==="suspended"||t.state==="interrupted")&&(be.info("_emit_",vt.PAUSING),this.emit(vt.PAUSING))}track(){if(be.info("track"),Ct(this._context),this._track)return this._track;let t=this._destNode;t||(t=new MediaStreamAudioDestinationNode(this._context)),this._nodeList.length===0&&this._appendSlience(this._context,t),this._connect(this._nodeList,t);const i=t.stream.getAudioTracks()[0];return this._destNode=t,this._track=i,i}}function co(r){const{sampleRate:e,keepAlive:t}=r;let i=kr.get(e);return(!i||i.state==="closed")&&(i=new AudioContext({sampleRate:e}),kr.set(e,i)),t&&(i.onstatechange=()=>{Ct(i)}),i}function Ct(r){if(r.state==="suspended"||r.state==="interrupted")return r.resume()}const uo=r=>(e,t)=>(r.set(e,t),t),Pr=Number.MAX_SAFE_INTEGER===void 0?9007199254740991:Number.MAX_SAFE_INTEGER,xr=536870912,Rr=xr*2,ho=(r,e)=>t=>{const i=e.get(t);let s=i===void 0?t.size:i<Rr?i+1:0;if(!t.has(s))return r(t,s);if(t.size<xr){for(;t.has(s);)s=Math.floor(Math.random()*Rr);return r(t,s)}if(t.size>Pr)throw new Error("Congratulations, you created a collection of unique numbers which uses all available integers!");for(;t.has(s);)s=Math.floor(Math.random()*Pr);return r(t,s)},Ar=new WeakMap,po=uo(Ar),ee=ho(po,Ar),lo=r=>r.method!==void 0&&r.method==="call",mo=r=>typeof r.id=="number"&&typeof r.result=="boolean",wr=((r,e)=>{let t=null;return()=>{if(t!==null)return t;const i=new Blob([e],{type:"application/javascript; charset=utf-8"}),s=URL.createObjectURL(i);return t=r(s),setTimeout(()=>URL.revokeObjectURL(s)),t}})(r=>{const e=new Map([[0,()=>{}]]),t=new Map([[0,()=>{}]]),i=new Map,s=new Worker(r);return s.addEventListener("message",({data:d})=>{if(lo(d)){const{params:{timerId:c,timerType:h}}=d;if(h==="interval"){const p=e.get(c);if(typeof p===void 0)throw new Error("The timer is in an undefined state.");if(typeof p=="number"){const l=i.get(p);if(l===void 0||l.timerId!==c||l.timerType!==h)throw new Error("The timer is in an undefined state.")}else typeof p=="function"&&p()}else if(h==="timeout"){const p=t.get(c);if(typeof p===void 0)throw new Error("The timer is in an undefined state.");if(typeof p=="number"){const l=i.get(p);if(l===void 0||l.timerId!==c||l.timerType!==h)throw new Error("The timer is in an undefined state.")}else typeof p=="function"&&(p(),t.delete(c))}}else if(mo(d)){const{id:c}=d,h=i.get(c);if(h===void 0)throw new Error("The timer is in an undefined state.");const{timerId:p,timerType:l}=h;i.delete(c),l==="interval"?e.delete(p):t.delete(p)}else{const{error:{message:c}}=d;throw new Error(c)}}),{clearInterval:d=>{if(typeof e.get(d)=="function"){const c=ee(i);i.set(c,{timerId:d,timerType:"interval"}),e.set(d,c),s.postMessage({id:c,method:"clear",params:{timerId:d,timerType:"interval"}})}},clearTimeout:d=>{if(typeof t.get(d)=="function"){const c=ee(i);i.set(c,{timerId:d,timerType:"timeout"}),t.set(d,c),s.postMessage({id:c,method:"clear",params:{timerId:d,timerType:"timeout"}})}},setInterval:(d,c=0,...h)=>{const p=ee(e);return e.set(p,()=>{d(...h),typeof e.get(p)=="function"&&s.postMessage({id:null,method:"set",params:{delay:c,now:performance.timeOrigin+performance.now(),timerId:p,timerType:"interval"}})}),s.postMessage({id:null,method:"set",params:{delay:c,now:performance.timeOrigin+performance.now(),timerId:p,timerType:"interval"}}),p},setTimeout:(d,c=0,...h)=>{const p=ee(t);return t.set(p,()=>d(...h)),s.postMessage({id:null,method:"set",params:{delay:c,now:performance.timeOrigin+performance.now(),timerId:p,timerType:"timeout"}}),p}}},`(()=>{"use strict";const e=new Map,t=new Map,r=t=>{const r=e.get(t);return void 0!==r&&(clearTimeout(r),e.delete(t),!0)},s=e=>{const r=t.get(e);return void 0!==r&&(clearTimeout(r),t.delete(e),!0)},o=(e,t)=>{const r=performance.now(),s=e+t-r-performance.timeOrigin;return{expected:r+s,remainingDelay:s}},i=(e,t,r,s)=>{const o=r-performance.now();o>0?e.set(t,setTimeout(i,o,e,t,r,s)):(e.delete(t),postMessage({id:null,method:"call",params:{timerId:t,timerType:s}}))};addEventListener("message",(({data:n})=>{try{if("clear"===n.method){const{id:e,params:{timerId:t,timerType:o}}=n;if("interval"===o)postMessage({id:e,result:r(t)});else{if("timeout"!==o)throw new Error('The given type "'.concat(o,'" is not supported'));postMessage({id:e,result:s(t)})}}else{if("set"!==n.method)throw new Error('The given method "'.concat(n.method,'" is not supported'));{const{params:{delay:r,now:s,timerId:a,timerType:m}}=n;if("interval"===m)((t,r,s)=>{const{expected:n,remainingDelay:a}=o(t,s);e.set(r,setTimeout(i,a,e,r,n,"interval"))})(r,a,s);else{if("timeout"!==m)throw new Error('The given type "'.concat(m,'" is not supported'));((e,r,s)=>{const{expected:n,remainingDelay:a}=o(e,s);t.set(r,setTimeout(i,a,t,r,n,"timeout"))})(r,a,s)}}}}catch(e){postMessage({error:{message:e.message},id:n.id,result:null})}}))})();`),fo=r=>wr().clearTimeout(r),_o=(...r)=>wr().setTimeout(...r),go=r=>r.method!==void 0&&r.method==="call",vo=r=>typeof r.id=="number"&&typeof r.result=="boolean",Co=r=>{const e=new Map([[0,()=>{}]]),t=new Map([[0,()=>{}]]),i=new Map,s=new Worker(r,{credentials:"omit"});return s.addEventListener("message",({data:d})=>{if(go(d)){const{params:{timerId:c,timerType:h}}=d;if(h==="interval"){const p=e.get(c);if(typeof p===void 0)throw new Error("The timer is in an undefined state.");if(typeof p=="number"){const l=i.get(p);if(l===void 0||l.timerId!==c||l.timerType!==h)throw new Error("The timer is in an undefined state.")}else typeof p=="function"&&p()}else if(h==="timeout"){const p=t.get(c);if(typeof p===void 0)throw new Error("The timer is in an undefined state.");if(typeof p=="number"){const l=i.get(p);if(l===void 0||l.timerId!==c||l.timerType!==h)throw new Error("The timer is in an undefined state.")}else typeof p=="function"&&(p(),t.delete(c))}}else if(vo(d)){const{id:c}=d,h=i.get(c);if(h===void 0)throw new Error("The timer is in an undefined state.");const{timerId:p,timerType:l}=h;i.delete(c),l==="interval"?e.delete(p):t.delete(p)}else{const{error:{message:c}}=d;throw new Error(c)}}),{clearInterval:d=>{if(typeof e.get(d)=="function"){const c=ee(i);i.set(c,{timerId:d,timerType:"interval"}),e.set(d,c),s.postMessage({id:c,method:"clear",params:{timerId:d,timerType:"interval"}})}},clearTimeout:d=>{if(typeof t.get(d)=="function"){const c=ee(i);i.set(c,{timerId:d,timerType:"timeout"}),t.set(d,c),s.postMessage({id:c,method:"clear",params:{timerId:d,timerType:"timeout"}})}},setInterval:(d,c=0,...h)=>{const p=ee(e);return e.set(p,()=>{d(...h),typeof e.get(p)=="function"&&s.postMessage({id:null,method:"set",params:{delay:c,now:performance.timeOrigin+performance.now(),timerId:p,timerType:"interval"}})}),s.postMessage({id:null,method:"set",params:{delay:c,now:performance.timeOrigin+performance.now(),timerId:p,timerType:"interval"}}),p},setTimeout:(d,c=0,...h)=>{const p=ee(t);return t.set(p,()=>d(...h)),s.postMessage({id:null,method:"set",params:{delay:c,now:performance.timeOrigin+performance.now(),timerId:p,timerType:"timeout"}}),p}}},yo={width:640,height:480,frameRate:30,backgroundColor:"#000000"},Ue=new L("View");class So{constructor(e){m(this,"id",oe());m(this,"_context");m(this,"_canvas");m(this,"_config");m(this,"_nodeList",[]);m(this,"_track");m(this,"_stopped",!0);m(this,"_nextTime",Date.now());m(this,"_workerTimeoutId");m(this,"_raqId");m(this,"_workerTimerScriptUrl");m(this,"_customSetTimeout");m(this,"_customClearTimeout");m(this,"_loopTimer");m(this,"_paintLoop",()=>{if(this._stopped){this._workerTimeoutId&&(this._customClearTimeout(this._workerTimeoutId),this._workerTimeoutId=void 0);return}this._drawOnCanvas(),this._workerTimeoutId&&this._customClearTimeout(this._workerTimeoutId),this._workerTimeoutId=this._customSetTimeout(()=>{this._paintLoop(),this._raqId&&(cancelAnimationFrame(this._raqId),this._raqId=void 0)},lt/this._config.frameRate),this._raqId=requestAnimationFrame(this._paintLoop)});Ue.info("ctor",e),this._config={...yo,...e};const{context:t,canvas:i}=pr(this._config);this._context=t,this._canvas=i,this._customSetTimeout=_o,this._customClearTimeout=fo}setWorkerTimerScriptUrl(e){if(this._workerTimerScriptUrl=e,this._workerTimerScriptUrl){const t=Co(this._workerTimerScriptUrl);this._customSetTimeout=(...i)=>t.setTimeout(...i),this._customClearTimeout=i=>t.clearTimeout(i)}}_shouldDraw(e){if(e<this._nextTime)return!1;for(;e>this._nextTime;)this._nextTime+=lt/this._config.frameRate;return!0}updateConfig(e){this._config={...this._config,...e},this._canvas.width=this._config.width,this._canvas.height=this._config.height}draw(e=[]){Ue.info("draw",e),this._nodeList=e}_drawOnCanvas(){if(this._shouldDraw(Date.now())){this._drawBackground();for(const e of this._nodeList){let t=e;if(t.available()){for(;t;)t.paint(this._context),t=t.previousNode;this._context.setTransform(1,0,0,1,0,0)}}}}_drawBackground(){const{backgroundColor:e,width:t,height:i}=this._config;this._context.clearRect(0,0,t,i),e&&(this._context.fillStyle=e,this._context.fillRect(0,0,t,i))}track(){if(Ue.info("track"),this._track)return this._track;this._stopped=!1,this._paintLoop();const{frameRate:e}=this._config,t=this._canvas.captureStream(e);return this._track=t.getVideoTracks()[0],this._track}updateFps(){if(this._track){const{frameRate:e}=this._config,t=this._canvas.captureStream(e);return this._track=t.getVideoTracks()[0],this._track}else return this.track()}element(){return Ue.info("element"),this._paintLoop(),this._canvas}stop(){this._stopped=!0}}function To(){return Math.random().toString(36).slice(-8)}const Eo=`
1
+ (function(Ce,ae){typeof exports=="object"&&typeof module<"u"?module.exports=ae():typeof define=="function"&&define.amd?define(ae):(Ce=typeof globalThis<"u"?globalThis:Ce||self,Ce.vePusher=ae())})(this,function(){"use strict";var Fv=Object.defineProperty;var jv=(Ce,ae,We)=>ae in Ce?Fv(Ce,ae,{enumerable:!0,configurable:!0,writable:!0,value:We}):Ce[ae]=We;var S=(Ce,ae,We)=>jv(Ce,typeof ae!="symbol"?ae+"":ae,We);var iu,ru,nu,su,ou,au,Ke;function Ce(i,e){for(var t=0;t<e.length;t++){const r=e[t];if(typeof r!="string"&&!Array.isArray(r)){for(const n in r)if(n!=="default"&&!(n in i)){const s=Object.getOwnPropertyDescriptor(r,n);s&&Object.defineProperty(i,n,s.get?s:{enumerable:!0,get:()=>r[n]})}}}return Object.freeze(Object.defineProperty(i,Symbol.toStringTag,{value:"Module"}))}function ae(i){return i&&i.__esModule&&Object.prototype.hasOwnProperty.call(i,"default")?i.default:i}var We={exports:{}},us;function _u(){return us||(us=1,function(i){var e=Object.prototype.hasOwnProperty,t="~";function r(){}Object.create&&(r.prototype=Object.create(null),new r().__proto__||(t=!1));function n(d,c,u){this.fn=d,this.context=c,this.once=u||!1}function s(d,c,u,l,h){if(typeof u!="function")throw new TypeError("The listener must be a function");var p=new n(u,l||d,h),f=t?t+c:c;return d._events[f]?d._events[f].fn?d._events[f]=[d._events[f],p]:d._events[f].push(p):(d._events[f]=p,d._eventsCount++),d}function a(d,c){--d._eventsCount===0?d._events=new r:delete d._events[c]}function o(){this._events=new r,this._eventsCount=0}o.prototype.eventNames=function(){var c=[],u,l;if(this._eventsCount===0)return c;for(l in u=this._events)e.call(u,l)&&c.push(t?l.slice(1):l);return Object.getOwnPropertySymbols?c.concat(Object.getOwnPropertySymbols(u)):c},o.prototype.listeners=function(c){var u=t?t+c:c,l=this._events[u];if(!l)return[];if(l.fn)return[l.fn];for(var h=0,p=l.length,f=new Array(p);h<p;h++)f[h]=l[h].fn;return f},o.prototype.listenerCount=function(c){var u=t?t+c:c,l=this._events[u];return l?l.fn?1:l.length:0},o.prototype.emit=function(c,u,l,h,p,f){var v=t?t+c:c;if(!this._events[v])return!1;var m=this._events[v],b=arguments.length,y,_;if(m.fn){switch(m.once&&this.removeListener(c,m.fn,void 0,!0),b){case 1:return m.fn.call(m.context),!0;case 2:return m.fn.call(m.context,u),!0;case 3:return m.fn.call(m.context,u,l),!0;case 4:return m.fn.call(m.context,u,l,h),!0;case 5:return m.fn.call(m.context,u,l,h,p),!0;case 6:return m.fn.call(m.context,u,l,h,p,f),!0}for(_=1,y=new Array(b-1);_<b;_++)y[_-1]=arguments[_];m.fn.apply(m.context,y)}else{var E=m.length,z;for(_=0;_<E;_++)switch(m[_].once&&this.removeListener(c,m[_].fn,void 0,!0),b){case 1:m[_].fn.call(m[_].context);break;case 2:m[_].fn.call(m[_].context,u);break;case 3:m[_].fn.call(m[_].context,u,l);break;case 4:m[_].fn.call(m[_].context,u,l,h);break;default:if(!y)for(z=1,y=new Array(b-1);z<b;z++)y[z-1]=arguments[z];m[_].fn.apply(m[_].context,y)}}return!0},o.prototype.on=function(c,u,l){return s(this,c,u,l,!1)},o.prototype.once=function(c,u,l){return s(this,c,u,l,!0)},o.prototype.removeListener=function(c,u,l,h){var p=t?t+c:c;if(!this._events[p])return this;if(!u)return a(this,p),this;var f=this._events[p];if(f.fn)f.fn===u&&(!h||f.once)&&(!l||f.context===l)&&a(this,p);else{for(var v=0,m=[],b=f.length;v<b;v++)(f[v].fn!==u||h&&!f[v].once||l&&f[v].context!==l)&&m.push(f[v]);m.length?this._events[p]=m.length===1?m[0]:m:a(this,p)}return this},o.prototype.removeAllListeners=function(c){var u;return c?(u=t?t+c:c,this._events[u]&&a(this,u)):(this._events=new r,this._eventsCount=0),this},o.prototype.off=o.prototype.removeListener,o.prototype.addListener=o.prototype.on,o.prefixed=t,o.EventEmitter=o,i.exports=o}(We)),We.exports}var gu=_u();const Je=ae(gu);var ds=(i=>(i.LeftToRight="LeftToRight",i.UpToDown="UpToDown",i.All="All",i.None="None",i))(ds||{}),V=(i=>(i.Camera="camera",i.Screen="screen",i.VideoFile="videoFile",i.Microphone="microphone",i.AudioFile="audioFile",i.Image="image",i.MixAudio="mixAudio",i.MixVideo="mixVideo",i.CustomVideo="customVideo",i.CustomAudio="customAudio",i))(V||{}),Ae=(i=>(i.DeviceCaptured="deviceCaptured",i.DeviceStopCapture="deviceStopCapture",i.Error="error",i.Interrupted="interrupted",i))(Ae||{}),Z=(i=>(i.PushStart="pushStart",i.PushStop="pushStop",i.PushError="pushError",i.RTCConnectStateChanged="rtcConnectStateChanged",i.CaptureFirstVideoFrame="capturefirstvideoframe",i.CaptureFirstAudioFrame="capturefirstaudioframe",i.NotAllowedAutoPlay="notallowedautoplay",i.ReconnectStateChange="reconnectStateChange",i.LiveConnectStateChange="liveConnectStateChange",i))(Z||{}),hs=(i=>(i["120p"]="160x120x15x200",i["180p"]="320x180x15x350",i["240p"]="320x240x15x400",i["360p"]="640x360x15x800",i["480p"]="640x480x15x900",i["720p-1"]="1280x720x15x1500",i["720p-2"]="1280x720x25x1500",i["720p-3"]="1280x720x30x1500",i["1080p-1"]="1920x1080x15x2080",i["1080p-2"]="1920x1080x25x3000",i["1080p-3"]="1920x1080x30x3150",i))(hs||{}),ls=(i=>(i["120p"]="120x160x15x200",i["180p"]="180x320x15x350",i["240p"]="240x320x15x400",i["360p"]="360x640x15x800",i["480p"]="480x640x15x900",i["720p-1"]="720x1280x15x1500",i["720p-2"]="720x1280x25x1500",i["720p-3"]="720x1280x30x1500",i["1080p-1"]="1080x1920x15x2080",i["1080p-2"]="1080x1920x25x3000",i["1080p-3"]="1080x1920x30x3150",i))(ls||{}),ps=(i=>(i.STANDARD="48000x40",i.HIGH="48000x128",i))(ps||{}),ut=(i=>(i.VideoStreamChange="videoStreamChange",i.AudioStreamChange="audioStreamChange",i))(ut||{}),fs=(i=>(i[i.init=-1]="init",i[i.new=0]="new",i[i.connecting=1]="connecting",i[i.connected=2]="connected",i[i.disconnected=3]="disconnected",i[i.failed=4]="failed",i[i.closed=5]="closed",i))(fs||{});const ms={SizeChange:"sizeChange"};var yr=(i=>(i.Portrait="portrait",i.Landscape="landscape",i))(yr||{});const _s="720p-1",gs="STANDARD";var fe=(i=>(i[i.DISCONNECTED=0]="DISCONNECTED",i[i.CONNECTING=1]="CONNECTING",i[i.CONNECTED=2]="CONNECTED",i[i.RECONNECTING=3]="RECONNECTING",i))(fe||{}),wt=(i=>(i[i.START=1]="START",i[i.WAITING=2]="WAITING",i[i.RECONNECTING=3]="RECONNECTING",i[i.SUCCESS=4]="SUCCESS",i[i.FAILED=5]="FAILED",i))(wt||{}),br=(i=>(i[i.PushUrlInvalid=1001]="PushUrlInvalid",i[i.ReconnectTimeout=1002]="ReconnectTimeout",i))(br||{}),U=(i=>(i.TRACK_NOT_AVAILABLE="track-not-available",i.UNEXPECTED_TYPE="unexpected-type",i.PLAY_FAILED="play-failed",i.CAPTURE_FAILED="capture-failed",i.NOT_SUPPORTED="not-supported",i.UNEXPECTED_ERROR="unexpected-error",i))(U||{}),j=(i=>(i.AUDIO="audio",i.VIDEO="video",i))(j||{}),ce=(i=>(i.ENDED="ended",i.MUTE="mute",i.UNMUTE="unmute",i.PLAY_FAILED="play-failed",i.SIZE_CHANGE="size-change",i))(ce||{});const se=[];for(let i=0;i<256;++i)se.push((i+256).toString(16).slice(1));function vu(i,e=0){return(se[i[e+0]]+se[i[e+1]]+se[i[e+2]]+se[i[e+3]]+"-"+se[i[e+4]]+se[i[e+5]]+"-"+se[i[e+6]]+se[i[e+7]]+"-"+se[i[e+8]]+se[i[e+9]]+"-"+se[i[e+10]]+se[i[e+11]]+se[i[e+12]]+se[i[e+13]]+se[i[e+14]]+se[i[e+15]]).toLowerCase()}let Sr;const yu=new Uint8Array(16);function bu(){if(!Sr){if(typeof crypto>"u"||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");Sr=crypto.getRandomValues.bind(crypto)}return Sr(yu)}const vs={randomUUID:typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};function dt(i,e,t){var n;if(vs.randomUUID&&!i)return vs.randomUUID();i=i||{};const r=i.random??((n=i.rng)==null?void 0:n.call(i))??bu();if(r.length<16)throw new Error("Random bytes length must be >= 16");return r[6]=r[6]&15|64,r[8]=r[8]&63|128,vu(r)}class ys{constructor(){S(this,"id",dt());S(this,"_nextNode");S(this,"_track");S(this,"_destNode")}gain(e){if(this._nextNode instanceof bs)return this._nextNode.g=e,this._nextNode;const t=new bs(this,{g:e});return this._nextNode=t,t}connect(e,t){if(!this.available())return;let{_node:r}=this;r||(r=this.createNode(e)),this._node=r,this.previousNode&&this.previousNode.connect(e,r),t&&r.connect(t)}available(){var e;return((e=this.previousNode)==null?void 0:e.available())??!1}destroy(){var e;(e=this._node)==null||e.disconnect(),delete this._node}}class bs extends ys{constructor(t,r){super();S(this,"previousNode");S(this,"_node");S(this,"_g");this.previousNode=t,this._g=r.g}createNode(t){return new GainNode(t,{gain:this._g})}set g(t){this._g=t,this._node&&(this._node.gain.value=t)}}class Su extends ys{constructor(t){super();S(this,"previousNode",null);S(this,"source");this.source=t}available(){return this.source.available()}destroy(){super.destroy()}}class Eu extends Su{constructor(){super(...arguments);S(this,"_node")}createNode(t){if(this._node)return this._node;let r;if(this.source instanceof Rs){const n=this.source.element();r=new MediaElementAudioSourceNode(t,{mediaElement:n}),n.muted=!1}else{const n=this.source.track();r=new MediaStreamAudioSourceNode(t,{mediaStream:new MediaStream([n])})}return r}}class L extends Error{constructor(t,r,n){super(r);S(this,"code");S(this,"message");S(this,"error");this.code=t,this.message=r,this.error=n,Object.setPrototypeOf(this,L.prototype)}toString(){return`VeCapture Error: ${this.code} ${this.message}`}}const Ss={info:{color:"rgba(93, 173, 226, 0)",text:"INFO"},warn:{color:"rgba(255, 119, 0, 0.3)",text:"WARN"},err:{color:"rgba(255, 0, 0, 0.3)",text:"ERR "},succ:{color:"rgba(0, 119, 0, 0.3)",text:"SUCC"}},Es="__debug__",wu="[VE-CAPTURE]";function Cu(){if(typeof location>"u"||typeof localStorage>"u")return!1;let i=!1;return location.href.includes(Es)&&(i=!0),localStorage.getItem(Es)&&(i=!0),i}let he=class{constructor(e){S(this,"moduleName");this.moduleName=e}print(e,t,...r){const n=ku();Cu()&&console.log(`${n}-${wu}%c[${Ss[e].text}]%c[${this.moduleName}][${t}]`,`background-color:${Ss[e].color};`,"background-color:rgba(0, 0, 0, 0)",...r)}info(e,...t){this.print("info",e,...t)}warn(e,...t){this.print("warn",e,...t)}error(e,...t){this.print("err",e,...t)}success(e,...t){this.print("succ",e,...t)}invoke(e,t){const r=this;return function(...s){r.info(`${t}-invoke`,...s);try{const a=e(...s);return typeof(a==null?void 0:a.then)=="function"?a.then(o=>(r.success(`${t}-result`,o),o)).catch(o=>{throw r.error(`${t}-result`,o),o}):(r.success(`${t}-result`,a),a)}catch(a){r.error(`[${t}-result`,a)}}}};function ku(){const i=new Date;return`${i.toTimeString().split(" ")[0]}:${i.getMilliseconds().toString().padStart(3,"0")}`}function Er(i,e){const t=document.createElement(i);return e.id&&(t.id=e.id),e.classList&&e.classList.forEach(r=>{t.classList.add(r)}),e.style&&Object.assign(t.style,e.style),e.attributes&&Object.entries(e.attributes).forEach(([r,n])=>{r==="muted"&&(t instanceof HTMLVideoElement||t instanceof HTMLAudioElement)?t.muted=!0:t.setAttribute(r,n)}),t}function ws({width:i,height:e}){const t=document.createElement("canvas"),r=t.getContext("2d");if(!r)throw new L(U.NOT_SUPPORTED,"CanvasRenderingContext2D is not supported by user agent");return t.width=i,t.height=e,t.style.width="100%",t.style.height="100%",{context:r,canvas:t}}class wr{constructor(e){S(this,"target");S(this,"_eventDict",new Map);this.target=e}on(e,t){let r=this._eventDict.get(e);r||(r=[t]),this._eventDict.set(e,r),this.target.addEventListener(e,t)}off(e,t){let r=this._eventDict.get(e);r&&(r=r.filter(n=>n!==t),this._eventDict.set(e,r),this.target.removeEventListener(e,t))}once(e,t){const r=n=>{t(n),this.off(e,r)};this.on(e,r)}clear(e){const t=this._eventDict.get(e);t&&t.forEach(r=>{this.target.removeEventListener(e,r)})}clearAll(){for(const e of this._eventDict.keys())this.clear(e)}}const Q=()=>typeof window>"u";function W(){return navigator.userAgent.toLowerCase()}function Cr(i=W()){let e="none";return Q()||(i.match("firefox")!==null?e="firefox":i.match("Chrome")!==null?(e="chrome",i.match("Electron")!==null&&(e="electron")):(i.match("Safari")!==null||i.match("AppleWebKit")!==null)&&(e="safari")),e}const Cs=Cr()==="firefox",Ii=Cr()==="safari";Cr(),!Q()&&/crios/i.test(W()),!Q()&&/edg\//i.test(W()),!Q()&&/edgA/i.test(W()),!Q()&&/edgios/i.test(W()),!Q()&&/dingtalk/i.test(W()),!Q()&&/opr\//.test(W()),!Q()&&/(iphone|ipod)/i.exec(W()),!Q()&&(/(ipad)/i.exec(W())||/macintosh/i.test(W())&&"ontouchend"in document),!Q()&&/macintosh/i.test(W()),!Q()&&/micromessenger/i.test(W()),!Q()&&W().includes("mobile"),!Q()&&/sm-\w+/i.test(W());const Tu=!Q()&&!!/(iphone|ipad|ipod)/i.exec(W());!Q()&&/android/i.test(W()),!Q()&&/windows/i.test(W()),!Q()&&/openharmony/i.test(W());let ks="0";const zu=!Q()&&((iu=W().match(/version\/(\d+)/i))==null?void 0:iu[1]);Ii&&zu&&(ks=(ru=navigator.userAgent.match(/version\/(\d+\.\d+)/i))==null?void 0:ru[1]),!Q()&&((nu=W().match(/firefox\/(\d+)/i))==null||nu[1]);const kr=ks;!Q()&&((ou=(su=W().match(/ ([\d_]+) like mac os x/i))==null?void 0:su[1])==null||ou.split("_").map(i=>parseInt(i))),!Q()&&((au=W().match(/chrome\/(\d+)/i))==null||au[1]);function Au(){var i;return!!((i=navigator==null?void 0:navigator.permissions)!=null&&i.query)}function Tr(){return!!(navigator!=null&&navigator.mediaDevices)}function Ru(){var i;return Tr()&&!!((i=navigator==null?void 0:navigator.mediaDevices)!=null&&i.getUserMedia)}function Du(){return!!Promise.withResolvers}function xu(){return!(Ii&&kr==="16.1")}function Iu(){return!(Ii&&kr&&["16.1","16.2","16.3"].includes(kr))}function Ou(){return!Cs}function Mu(){return typeof CanvasCaptureMediaStreamTrack<"u"}function Pu(i){return typeof i.requestFrame=="function"}function Lu(){return!!Tr()&&typeof navigator.mediaDevices.ondevicechange<"u"&&typeof navigator.mediaDevices.addEventListener=="function"}const Pe={permissionQuery:Au,mediaDevices:Tr,settingResolutionInGetDisplayMedia:xu,promiseWithResolvers:Du,getUserMedia:Ru,isolateEnumerateDevices:Ou,supportIdealParamsInGetDisplayMedia:Iu,canvasCaptureMediaStreamTrack:Mu,requestFrameOnMediaStream:Pu,ondevicechange:Lu};function Uu(){if(Pe.promiseWithResolvers())return Promise.withResolvers();let i,e;const t=new Promise((r,n)=>{i=r,e=n});if(!i||!e)throw Error("resolver and rejector working unexpected");return{promise:t,resolve:i,reject:e}}function Ts(i={}){const{timeout:e,message:t}={timeout:0,message:new L(U.UNEXPECTED_ERROR,"unexpected timeout"),...i},{promise:r,resolve:n,reject:s}=Uu();if(e<=0)return{promise:r,resolve:n,reject:s};const a=setTimeout(()=>{s(t)},e);return{promise:r,resolve:d=>{clearTimeout(a),n(d)},reject:s}}const Gu={playsinline:"","webkit-playsinline":"","x5-playsinline":"","x5-video-player-type":"h5","x-webkit-airplay":"allow",preload:"metadata",muted:"",crossOrigin:"anonymous"},Nu={playsinline:"","webkit-playsinline":"",preload:"metadata",muted:"",crossOrigin:"anonymous"};class $t{constructor(e,t=[]){S(this,"id",dt());S(this,"_referenceTracks",[]);S(this,"_element");S(this,"_volumeMode",0);S(this,"_readyLock");S(this,"_releaseReadyLock");S(this,"_throwReadyLock");S(this,"_stream");let r;if(e instanceof MediaStreamTrack){const o=new MediaStream([e]);r=Bu(o),this._stream=o}else if(e.url)r=Vu(e);else throw new L(U.UNEXPECTED_TYPE,`got ${typeof e}, expected: MediaStreamTrack or constraints for creating element`);const{promise:n,resolve:s,reject:a}=Ts({timeout:2e3,message:new L(U.PLAY_FAILED,"load media timeout")});this._readyLock=n,this._releaseReadyLock=s,this._throwReadyLock=a,this._element=new wr(r),this._bindPlayerEvent(this._element),this._referenceTracks=[...t]}addReferenceTrack(e){this._referenceTracks.push(e)}track(e){this._playElement();let t=this._stream;if((!t||!t.active)&&(t=this._element.target.captureStream(),this._stream=t),e===j.AUDIO){this._upgradeVolumeMode(1e-4);const r=t.getAudioTracks();if(r.length<1)throw new L(U.UNEXPECTED_TYPE,"got empty list of audio tracks");return r[0]}if(e===j.VIDEO){const r=t.getVideoTracks();if(r.length<1)throw new L(U.UNEXPECTED_TYPE,"got empty list of video tracks");return r[0]}throw new L(U.UNEXPECTED_TYPE,`got ${e}, expected: audio, video`)}async _playElement(){if(!(!this._element.target.muted&&this._element.target.volume===this._volumeMode&&!this._element.target.paused))try{this._element.target.muted=!1,this._element.target.volume=this._volumeMode,await this._element.target.play()}catch(e){throw this._handlePlayFailed(),new L(U.PLAY_FAILED,"play element failed",e)}}_bindPlayerEvent(e){e.on("loadedmetadata",()=>{this._releaseReadyLock()}),e.on("error",()=>{this._throwReadyLock(new L(U.PLAY_FAILED,"HTMLMediaElement got error when loading file"))})}_handlePlayFailed(){this._referenceTracks.forEach(e=>{e.handlePlayFailed()})}_upgradeVolumeMode(e){console.warn("update volume mode",e);const t=this._volumeMode>e?this._volumeMode:e;this._volumeMode=t,this._playElement()}element(e=!1){return e&&this._upgradeVolumeMode(1),this._playElement(),this._element.target}isReady(){return this._readyLock}removeReference(e){const t=this._referenceTracks.indexOf(e);this._referenceTracks.splice(t,1),this._referenceTracks.length===0&&this.destroy()}destroy(){this._element.target.srcObject=null,this._element.target.src="",this._element.target.load();const e=[...this._referenceTracks];this._referenceTracks=[],e.forEach(t=>{try{t.destroy()}catch{}})}}function Bu(i){let e="audio";i.getVideoTracks().length>0&&(e="video");const t=zs(e==="video"?j.VIDEO:j.AUDIO);return t.srcObject=i,t}function Vu(i){const{url:e,kind:t,loop:r}=i,n=zs(t);return n.src=e,n.loop=r,n}function zs(i){if(i===j.VIDEO)return Er(j.VIDEO,{style:{width:"100%",height:"100%"},attributes:Gu});if(i===j.AUDIO)return Er(j.AUDIO,{style:{display:"none"},attributes:Nu});throw new L(U.UNEXPECTED_TYPE,`got ${i}, expected: audio, video`)}class zr extends Je{emit(e,...t){const r=this.listenerCount(e);return Promise.resolve().then(()=>{super.emit(e,...t)}),!!r}on(e,t,r){const n=(...s)=>{try{return t(...s)}catch(a){console.error(`[SafeEventEmitter] event listener threw an error when handling [${e}] event: `,a)}};return super.on(e,n,r)}once(e,t,r){const n=(...s)=>{try{return t(...s)}catch(a){console.error(`[SafeEventEmitter] event listener threw an error when handling [${e}] event: `,a)}};return super.once(e,n,r)}}function Ar(i){if(typeof i=="number")return i;if(typeof(i==null?void 0:i.exact)=="number")return i.exact;if(typeof(i==null?void 0:i.ideal)=="number")return i.ideal;if(typeof(i==null?void 0:i.max)=="number")return i.max;if(typeof(i==null?void 0:i.min)=="number")return i.min;throw new L(U.UNEXPECTED_TYPE,"unexpected constraints type")}const Oi=1e3;class As{constructor(e){S(this,"id",dt());S(this,"_context");S(this,"_canvas");S(this,"_image");S(this,"_config");S(this,"_readyLock");S(this,"_releaseReadyLock");S(this,"_throwReadyLock");S(this,"_loopTimer");S(this,"_referenceTracks",[]);S(this,"_stream");const t=Ar(e.width),r=Ar(e.height),n=Ar(e.frameRate);this._config={width:t,height:r,frameRate:n};const{context:s,canvas:a}=ws({width:t,height:r});this._context=s,this._canvas=a;const o=Fu({url:e.url,width:t,height:r});this._image=new wr(o);const{promise:d,resolve:c,reject:u}=Ts({timeout:2e3,message:new L(U.PLAY_FAILED,"load image timeout")});this._readyLock=d,this._releaseReadyLock=c,this._throwReadyLock=u,this._bindImageEvent(this._image)}track(){this._paint();const{frameRate:e}=this._config;let t=this._stream;(!t||!t.active)&&(t=this._canvas.captureStream(e),this._stream=t);const r=t.getVideoTracks();if(r.length<1)throw new L(U.UNEXPECTED_TYPE,"got empty list of video tracks");return r[0]}element(){return this._image.target}isReady(){return this._readyLock}_bindImageEvent(e){e.on("load",()=>{this._releaseReadyLock()}),e.on("error",()=>{this._throwReadyLock(new L(U.PLAY_FAILED,"HTMLMediaElement got error when loading file"))})}async _paint(){const{width:e,height:t,frameRate:r}=this._config;this._context.drawImage(this._image.target,0,0,e,t),this._loopTimer&&clearTimeout(this._loopTimer),this._loopTimer=setTimeout(this._paint.bind(this),Oi/r)}addReferenceTrack(e){this._referenceTracks.push(e)}removeReference(e){const t=this._referenceTracks.indexOf(e);this._referenceTracks.splice(t,1),console.warn("reference length",this._referenceTracks),this._referenceTracks.length}}function Fu({url:i,height:e,width:t}){const r=Er("img",{style:{width:`${t}px`,height:`${e}px`},attributes:{crossOrigin:"anonymous"}});return r.src=i,r}class Rr extends zr{constructor(t){super();S(this,"id",dt());S(this,"_track");S(this,"_element");t instanceof MediaStreamTrack?(this._track=new wr(t),this._bindTrackEvent(this._track)):t instanceof $t?(this._element=t,t.addReferenceTrack(this)):t instanceof As&&(this._element=t)}_bindTrackEvent(t){t.on("ended",this._handleTrackEnded.bind(this)),t.on("mute",()=>{this.emit(ce.MUTE)}),t.on("unmute",()=>{this.emit(ce.UNMUTE)})}_handleTrackEnded(){this.emit(ce.ENDED),this.destroy()}handlePlayFailed(){this.emit(ce.PLAY_FAILED)}track(){if(this.logger.info("track"),!this.available())throw new L(U.TRACK_NOT_AVAILABLE,"track is not available when creating MediaStreamTrack");if(this._track)return this._track.target;if(!this._element)throw new L(U.UNEXPECTED_TYPE,"got this._element falsy");const t=this._element.track(this.kind);return this.logger.success("track",t),t}element(){if(this.logger.info("element"),!this.available())throw new L(U.TRACK_NOT_AVAILABLE,"track is not available when creating HTMLMediaElement");if(this._element)return this._element.element();if(!this._track)throw new L(U.UNEXPECTED_TYPE,"got this._track falsy");const t=new $t(this._track.target,[this]);this._element=t;const r=t.element();return this.logger.success("element",r),r}available(){return!!(this._track||this._element)}destroy(){var t,r,n;(t=this._track)==null||t.clearAll(),(r=this._track)==null||r.target.stop(),this._track&&delete this._track,(n=this._element)==null||n.removeReference(this),delete this._element}}class Mi extends Rr{constructor(){super(...arguments);S(this,"kind",j.AUDIO);S(this,"_node")}node(){if(this.logger.info("node",this.id),!this.available())throw new L(U.TRACK_NOT_AVAILABLE,"track is not avaiable when creating node");if(this._node)return this._node;const t=new Eu(this);return this._node=t,t}element(){if(this.logger.info("element",this.id),!this.available())throw new L(U.TRACK_NOT_AVAILABLE,"track is not available when creating HTMLMediaElement");if(this._element){const r=this._element.element(!0);if(!(r instanceof HTMLMediaElement))throw new L(U.UNEXPECTED_TYPE,"source should be HTMLMediaElement");return r}if(!this._track)throw new L(U.UNEXPECTED_TYPE,"got this._track falsy");const t=new $t(this._track.target,[this]);return this._element=t,t.element()}destroy(){var t;this.logger.warn("destroy",this.id),(t=this._node)==null||t.destroy(),super.destroy()}}class ju extends Mi{constructor(){super(...arguments);S(this,"logger",new he("MicrophoneAudioTrack"))}}class Hu extends Mi{constructor(){super(...arguments);S(this,"logger",new he("ScreenAudioTrack"))}}class Rs extends Mi{constructor(){super(...arguments);S(this,"logger",new he("MediaAudioTrack"))}handlePlayFailed(){this.emit(ce.PLAY_FAILED)}async play(){if(this._element){if(!(this._element instanceof $t))throw new L(U.UNEXPECTED_TYPE,"element is not TrackMediaElement");return this._element._playElement()}}}class $u extends Mi{constructor(){super(...arguments);S(this,"logger",new he("CustomAudioTrack"))}}let qu=1;const Dr=new he("PromiseQueue");class Ku{constructor(e){S(this,"lockingPromise",Promise.resolve());S(this,"locks",0);S(this,"name","");S(this,"lockId");S(this,"closeReason");this.lockId=qu++,e&&(this.name=e),Dr.info(`lock-${this.name}-${this.lockId}`,"is created.")}get isLocked(){return this.locks>0}lock(){this.locks+=1,Dr.info(`lock-${this.name}-${this.lockId}`,`locked, current queue ${this.locks}.`);let e;const t=new Promise(n=>{e=()=>{this.locks-=1,Dr.info(`lock-${this.name}-${this.lockId}`,`unlocked, current queue ${this.locks}.`),n()}}),r=this.lockingPromise.then(()=>e);return this.lockingPromise=this.lockingPromise.then(()=>t),r}}const Wu=300,Ju=3e3,Re=new he("Devices");class Xu extends zr{constructor(){super();S(this,"_deviceMap",{audioinput:[],audiooutput:[],videoinput:[]});S(this,"_permissions",{[j.AUDIO]:!1,[j.VIDEO]:!1});S(this,"_changedQueue",new Ku("device changed queue"));this._init()}async _init(){this._initDeviceChanged(),await this._initPermissionChanged();const t=Os(this._permissions);t.length>0&&this._refreshDevices(t)}_initDeviceChanged(){if(Re.info("_initDeviceChanged","invoked"),!Pe.ondevicechange()){Re.error("_initDeviceChanged","no supported, use timer instead"),setInterval(()=>{this._handleDeviceChanged()},Ju);return}Pe.ondevicechange()&&navigator.mediaDevices.addEventListener("devicechange",()=>{Re.info("devicechange"),setTimeout(()=>{this._handleDeviceChanged()},Wu)})}async _initPermissionChanged(){if(!Pe.permissionQuery()){Re.error("_initPermissionChanged","permission query not supported, silent return");return}try{const t=await navigator.permissions.query({name:"microphone"});this._permissions.audio=t.state==="granted",t.addEventListener("change",()=>{Re.info("_initPermissionChanged","update permission for audio"),this._permissions.audio=t.state==="granted"})}catch(t){Re.error("_initPermissionChanged",t)}try{const t=await navigator.permissions.query({name:"camera"});this._permissions.video=t.state==="granted",t.addEventListener("change",()=>{Re.info("_initPermissionChanged","update permission for video"),this._permissions.video=t.state==="granted"})}catch(t){Re.error("_initPermissionChanged",t)}}async _refreshDevices(t){if(!Pe.mediaDevices())throw new L(U.NOT_SUPPORTED,"mediaDevices is not supported");if(t.length===0)throw new L(U.UNEXPECTED_TYPE,"kinds expect to containt values");let r;if(!Pe.isolateEnumerateDevices()){const a={};t.forEach(o=>{a[o]=!0}),r=await navigator.mediaDevices.getUserMedia(a)}let n=await navigator.mediaDevices.enumerateDevices();r&&Ds(r),n=n.filter(({deviceId:a})=>!!a);const s={audioinput:[],audiooutput:[],videoinput:[]};n.forEach(a=>{const{kind:o}=a;s[o].push(a)}),this._deviceMap=s}async _acquireUserPermission(t){let r=!1;if(t.forEach(n=>{r=r||!this._permissions[n]}),!r)return{grant:!0};if(!Pe.getUserMedia())return{grant:!1,reason:new L(U.NOT_SUPPORTED,"getUserMedia is not supported")};try{const n={};t.forEach(a=>{n[a]=!0});const s=await navigator.mediaDevices.getUserMedia(n);return s?(n.audio&&(this._permissions[j.AUDIO]=!0),n.video&&(this._permissions[j.VIDEO]=!0),Ds(s),{grant:!0}):{grant:!1,reason:new L(U.UNEXPECTED_TYPE,"get stream falsy")}}catch(n){return{grant:!1,reason:new L(U.CAPTURE_FAILED,"acquire user permission failed",n)}}}async _handleDeviceChanged(){Re.info("_handleDeviceChanged",this._deviceMap,this._permissions);const t=await this._changedQueue.lock();try{const r=Is(this._deviceMap);let n=[];const s=Os(this._permissions);s.length===0?Re.warn("_handleDeviceChanged","no permission, use empty list"):(await this._refreshDevices(s),n=Is(this._deviceMap)),n.forEach(a=>{r.findIndex(d=>xs(d,a))!==-1||this.emit("onDeviceStateChanged",{deviceInfo:a,deviceState:"active"})}),r.forEach(a=>{n.findIndex(d=>xs(d,a))!==-1||this.emit("onDeviceStateChanged",{deviceInfo:a,deviceState:"inactive"})})}finally{t()}}async enumerateDevices(t){const r=[];t.forEach(o=>{if(o==="audioinput"||o==="audiooutput")r.push(j.AUDIO);else if(o==="videoinput")r.push(j.VIDEO);else throw new L(U.UNEXPECTED_TYPE,"kind in kinds should be enum MediaDeviceKind")});const{grant:n,reason:s}=await this._acquireUserPermission(r);if(!n)throw s;await this._refreshDevices(r);const a=[];return t.forEach(o=>{a.push(...this._deviceMap[o])}),a}async enableDevices(t){return this._acquireUserPermission(t)}}function Ds(i){i.getTracks().forEach(e=>e.stop())}function xs(i,e){return i.deviceId===e.deviceId}function Is(i){return Array.from([...i.audioinput.values(),...i.videoinput.values(),...i.audiooutput.values()])}function Os(i){const e=[];return i.audio&&e.push(j.AUDIO),i.video&&e.push(j.VIDEO),e}const xr=new Xu,Ir={LeftToRight:"LeftToRight",UpToDown:"UpToDown",All:"All"};class Or{constructor(){S(this,"id",dt())}position(e,t){return new Zu(this,{x:e,y:t})}scale(e){return new Ms(this,{s:e})}mirror(e){return new Ms(this,{mirrorType:e})}available(){var e;return((e=this.previousNode)==null?void 0:e.available())??!1}}class Zu extends Or{constructor(t,r){super();S(this,"previousNode");S(this,"_x");S(this,"_y");this.previousNode=t,this._x=r.x,this._y=r.y}paint(t){t.translate(this._x,this._y)}}class Ms extends Or{constructor(t,r){super();S(this,"previousNode");S(this,"_scaleParams",[1,1]);if(this.previousNode=t,r.mirrorType)switch(r.mirrorType){case Ir.LeftToRight:this._scaleParams=[-1,1];break;case Ir.UpToDown:this._scaleParams=[1,-1];break;case Ir.All:this._scaleParams=[-1,-1];break;default:this._scaleParams=[1,1];break}else r.s&&(this._scaleParams=[r.s,r.s])}paint(t){t.scale(this._scaleParams[0],this._scaleParams[1])}}class Qu extends Or{constructor(t){super();S(this,"previousNode",null);S(this,"_source");this._source=t}available(){return this._source.available()}}class Pi extends Qu{constructor(t,r){super(t);S(this,"_targetWidth");S(this,"_targetHeight");const{width:n,height:s}=r??{};this._targetWidth=n??this._source.width(),this._targetHeight=s??this._source.height()}size(t,r){return new Pi(this._source,{width:t,height:r})}paint(t){const r=this._targetWidth,n=this._targetHeight;t.drawImage(this._source.element(),-r/2,-n/2,r,n)}}class Yu extends Rr{constructor(){super(...arguments);S(this,"logger",new he("PictureTrack"));S(this,"kind",j.VIDEO)}element(){const t=super.element();if(!(t instanceof HTMLImageElement))throw new L(U.UNEXPECTED_TYPE,"source should be HTMLVideoElement");return this.logger.info("element",t),t}height(){const{height:t}=this.element();return t??0}width(){const{width:t}=this.element();return t??0}node(){if(!this.available())throw new L(U.TRACK_NOT_AVAILABLE,"track is not avaiable when creating node");const t=new Pi(this);return this.logger.info("node",t),t}destroy(){this.logger.warn("destroy"),super.destroy()}}const ed=500;class Li extends Rr{constructor(){super(...arguments);S(this,"kind",j.VIDEO);S(this,"sizeChangeTimer");S(this,"watchSizeChangeOnce",()=>{const t=this.width(),r=this.height();this.sizeChangeTimer=setTimeout(()=>{const n=this.width(),s=this.height();(r!==s||t!==n)&&this.emit(ce.SIZE_CHANGE,{width:n,height:s})},ed)})}element(){const t=super.element();if(!(t instanceof HTMLVideoElement))throw new L(U.UNEXPECTED_TYPE,"source should be HTMLVideoElement");return t}node(){if(!this.available())throw new L(U.TRACK_NOT_AVAILABLE,"track is not avaiable when creating node");return new Pi(this)}destroy(){clearTimeout(this.sizeChangeTimer),super.destroy()}}class td extends Li{constructor(t){super(t);S(this,"logger",new he("CameraVideoTrack"));this.watchSizeChangeOnce()}height(){const{height:t}=this.track().getSettings();return t??0}width(){const{width:t}=this.track().getSettings();return t??0}}class id extends Li{constructor(t){super(t);S(this,"logger",new he("ScreenVideoTrack"));this.watchSizeChangeOnce()}height(){const{height:t}=this.track().getSettings();return t??0}width(){const{width:t}=this.track().getSettings();return t??0}}class rd extends Li{constructor(){super(...arguments);S(this,"logger",new he("MediaVideoTrack"))}height(){const{videoHeight:t}=this.element();return t??0}width(){const{videoWidth:t}=this.element();return t??0}}class nd extends Li{constructor(){super(...arguments);S(this,"logger",new he("CustomVideoTrack"))}height(){const{height:t}=this.track().getSettings();return t??0}width(){const{width:t}=this.track().getSettings();return t??0}}async function Ps(i,e){let t;if(e!=null&&e.frameRate&&typeof e.frameRate=="number"&&(t=e.frameRate),t)try{await i.applyConstraints({...e,frameRate:{min:t,ideal:t}})}catch(r){console.warn("[VePusher Error]: frameRate limit failed",r)}}const Le=new he("Capture");async function sd(i){return xr.enumerateDevices(i)}async function od(i){xr.removeAllListeners("onDeviceStateChanged"),xr.on("onDeviceStateChanged",i)}async function ad(i,e){let t;try{const n={video:i??!0};typeof n.video=="object"&&n.video.facingMode&&delete n.video.deviceId,t=await navigator.mediaDevices.getUserMedia(n)}catch(n){throw new L(U.CAPTURE_FAILED,"got error when capturing camera",n)}const r=t.getVideoTracks()[0];if(i!=null&&i.frameRate&&e&&Ps(r,i),!r)throw new L(U.UNEXPECTED_TYPE,"got falsy in track");return new td(r)}async function cd(i,e,t){const{video:r,audio:n}=i;let s=r===!0?{}:r;e!=null&&e.displaySurface&&(s.displaySurface=e.displaySurface,delete e.displaySurface),Pe.settingResolutionInGetDisplayMedia()||(s=!0),!Pe.supportIdealParamsInGetDisplayMedia()&&typeof s!="boolean"&&(s.width&&typeof s.width=="number"&&(s.width={max:s.width}),s.height&&typeof s.height=="number"&&(s.height={max:s.height}));let a;try{a=await navigator.mediaDevices.getDisplayMedia({video:s,audio:n,...e})}catch(u){throw new L(U.CAPTURE_FAILED,"got error when capture screen",u)}const o=a.getVideoTracks()[0],d=a.getAudioTracks()[0];if(!o)throw new L(U.UNEXPECTED_TYPE,"got falsy in videoTrack");typeof s!="boolean"&&typeof s.frameRate=="number"&&t&&Ps(o,s);const c=[];return c.push(new id(o)),d&&c.push(new Hu(d)),c}async function ud(i){const{url:e,audio:t,video:r,loop:n}=i,s=new $t({url:e,kind:r?j.VIDEO:j.AUDIO,loop:n}),a=[];return t&&a.push(new Rs(s)),r&&a.push(new rd(s)),await s.isReady(),a}async function dd(i){const e=new As(i);return await e.isReady(),new Yu(e)}async function hd(i){let e;try{const r={audio:i??!0};e=await navigator.mediaDevices.getUserMedia(r)}catch(r){throw new L(U.CAPTURE_FAILED,"got error when capturing microphone",r)}const t=e.getAudioTracks()[0];if(!t)throw new L(U.UNEXPECTED_TYPE,"got falsy in track");return new ju(t)}function ld(i){if(!i||i.kind!=="video")throw new L(U.UNEXPECTED_TYPE,"error custom video track type");return new nd(i)}function pd(i){if(!i||i.kind!=="audio")throw new L(U.UNEXPECTED_TYPE,"error custom audio track type");return new $u(i)}const fd=Le.invoke(sd,"enumerateInputDevices"),md=Le.invoke(ad,"createCameraTrack"),_d=Le.invoke(dd,"createPictureTrack"),Ls=Le.invoke(ud,"createMediaTracks"),gd=Le.invoke(hd,"createMicrophoneTrack"),vd=Le.invoke(cd,"createScreenTracks"),yd=Le.invoke(od,"onDeviceChanged"),bd=Le.invoke(ld,"createCustomVideoTrack"),Sd=Le.invoke(pd,"createCustomAudioTrack");var Mr=(i=>(i.PAUSING="pausing",i))(Mr||{});const Ed={sampleRate:48e3,keepAlive:!0},Us=new Map,qt=new he("Mixer");class wd extends zr{constructor(t){super();S(this,"id",dt());S(this,"_context");S(this,"_config");S(this,"_nodeList",[]);S(this,"_destNode");S(this,"_bufferNode");S(this,"_track");S(this,"unlockAudioContext",()=>{if(this._context.state!=="suspended")return;const t=document.body,r=["touchstart","touchend","mousedown","keydown"],n=()=>{r.forEach(a=>{t.removeEventListener(a,s)})},s=()=>{Kt(this._context).then(n)};r.forEach(a=>{t.addEventListener(a,s,!1)})});qt.info("ctor",t),this._config={...Ed,...t},this._context=Cd(this._config),this._bindContextEvent(this._context)}mix(t){qt.info("mix",t),Kt(this._context);for(const r of this._nodeList)t.includes(r)||r.destroy();this._nodeList=t,this._connect(t,this._destNode),this._nodeList.length===0&&this._appendSlience(this._context,this._destNode)}resume(){return qt.info("resume"),Kt(this._context)}_connect(t,r){for(const n of t)n.connect(this._context,r)}_appendSlience(t,r){if(!r||this._bufferNode)return;const{sampleRate:n}=t,s=new AudioBuffer({length:100,sampleRate:n}),a=new AudioBufferSourceNode(t,{buffer:s,loop:!0});a.connect(r),this._bufferNode=a}_bindContextEvent(t){t.addEventListener("statechange",this._handleContextStateChange.bind(this))}_handleContextStateChange(){const t=this._context;(t.state==="suspended"||t.state==="interrupted")&&(qt.info("_emit_",Mr.PAUSING),this.emit(Mr.PAUSING))}track(){if(qt.info("track"),Kt(this._context),this.unlockAudioContext(),this._track)return this._track;let t=this._destNode;t||(t=new MediaStreamAudioDestinationNode(this._context)),this._nodeList.length===0&&this._appendSlience(this._context,t),this._connect(this._nodeList,t);const r=t.stream.getAudioTracks()[0];return this._destNode=t,this._track=r,r}}function Cd(i){const{sampleRate:e,keepAlive:t}=i;let r=Us.get(e);return(!r||r.state==="closed")&&(r=new AudioContext({sampleRate:e}),Us.set(e,r)),t&&(r.onstatechange=()=>{Kt(r)}),r}function Kt(i){return i.state==="suspended"||i.state==="interrupted"?i.resume():Promise.resolve()}const kd=i=>(e,t)=>(i.set(e,t),t),Gs=Number.MAX_SAFE_INTEGER===void 0?9007199254740991:Number.MAX_SAFE_INTEGER,Ns=536870912,Bs=Ns*2,Td=(i,e)=>t=>{const r=e.get(t);let n=r===void 0?t.size:r<Bs?r+1:0;if(!t.has(n))return i(t,n);if(t.size<Ns){for(;t.has(n);)n=Math.floor(Math.random()*Bs);return i(t,n)}if(t.size>Gs)throw new Error("Congratulations, you created a collection of unique numbers which uses all available integers!");for(;t.has(n);)n=Math.floor(Math.random()*Gs);return i(t,n)},Vs=new WeakMap,zd=kd(Vs),Xe=Td(zd,Vs),Ad=i=>i.method!==void 0&&i.method==="call",Rd=i=>typeof i.id=="number"&&typeof i.result=="boolean",Fs=((i,e)=>{let t=null;return()=>{if(t!==null)return t;const r=new Blob([e],{type:"application/javascript; charset=utf-8"}),n=URL.createObjectURL(r);return t=i(n),setTimeout(()=>URL.revokeObjectURL(n)),t}})(i=>{const e=new Map([[0,()=>{}]]),t=new Map([[0,()=>{}]]),r=new Map,n=new Worker(i);return n.addEventListener("message",({data:c})=>{if(Ad(c)){const{params:{timerId:u,timerType:l}}=c;if(l==="interval"){const h=e.get(u);if(typeof h===void 0)throw new Error("The timer is in an undefined state.");if(typeof h=="number"){const p=r.get(h);if(p===void 0||p.timerId!==u||p.timerType!==l)throw new Error("The timer is in an undefined state.")}else typeof h=="function"&&h()}else if(l==="timeout"){const h=t.get(u);if(typeof h===void 0)throw new Error("The timer is in an undefined state.");if(typeof h=="number"){const p=r.get(h);if(p===void 0||p.timerId!==u||p.timerType!==l)throw new Error("The timer is in an undefined state.")}else typeof h=="function"&&(h(),t.delete(u))}}else if(Rd(c)){const{id:u}=c,l=r.get(u);if(l===void 0)throw new Error("The timer is in an undefined state.");const{timerId:h,timerType:p}=l;r.delete(u),p==="interval"?e.delete(h):t.delete(h)}else{const{error:{message:u}}=c;throw new Error(u)}}),{clearInterval:c=>{if(typeof e.get(c)=="function"){const u=Xe(r);r.set(u,{timerId:c,timerType:"interval"}),e.set(c,u),n.postMessage({id:u,method:"clear",params:{timerId:c,timerType:"interval"}})}},clearTimeout:c=>{if(typeof t.get(c)=="function"){const u=Xe(r);r.set(u,{timerId:c,timerType:"timeout"}),t.set(c,u),n.postMessage({id:u,method:"clear",params:{timerId:c,timerType:"timeout"}})}},setInterval:(c,u=0,...l)=>{const h=Xe(e);return e.set(h,()=>{c(...l),typeof e.get(h)=="function"&&n.postMessage({id:null,method:"set",params:{delay:u,now:performance.timeOrigin+performance.now(),timerId:h,timerType:"interval"}})}),n.postMessage({id:null,method:"set",params:{delay:u,now:performance.timeOrigin+performance.now(),timerId:h,timerType:"interval"}}),h},setTimeout:(c,u=0,...l)=>{const h=Xe(t);return t.set(h,()=>c(...l)),n.postMessage({id:null,method:"set",params:{delay:u,now:performance.timeOrigin+performance.now(),timerId:h,timerType:"timeout"}}),h}}},`(()=>{"use strict";const e=new Map,t=new Map,r=t=>{const r=e.get(t);return void 0!==r&&(clearTimeout(r),e.delete(t),!0)},s=e=>{const r=t.get(e);return void 0!==r&&(clearTimeout(r),t.delete(e),!0)},o=(e,t)=>{const r=performance.now(),s=e+t-r-performance.timeOrigin;return{expected:r+s,remainingDelay:s}},i=(e,t,r,s)=>{const o=r-performance.now();o>0?e.set(t,setTimeout(i,o,e,t,r,s)):(e.delete(t),postMessage({id:null,method:"call",params:{timerId:t,timerType:s}}))};addEventListener("message",(({data:n})=>{try{if("clear"===n.method){const{id:e,params:{timerId:t,timerType:o}}=n;if("interval"===o)postMessage({id:e,result:r(t)});else{if("timeout"!==o)throw new Error('The given type "'.concat(o,'" is not supported'));postMessage({id:e,result:s(t)})}}else{if("set"!==n.method)throw new Error('The given method "'.concat(n.method,'" is not supported'));{const{params:{delay:r,now:s,timerId:a,timerType:m}}=n;if("interval"===m)((t,r,s)=>{const{expected:n,remainingDelay:a}=o(t,s);e.set(r,setTimeout(i,a,e,r,n,"interval"))})(r,a,s);else{if("timeout"!==m)throw new Error('The given type "'.concat(m,'" is not supported'));((e,r,s)=>{const{expected:n,remainingDelay:a}=o(e,s);t.set(r,setTimeout(i,a,t,r,n,"timeout"))})(r,a,s)}}}}catch(e){postMessage({error:{message:e.message},id:n.id,result:null})}}))})();`),Dd=i=>Fs().clearTimeout(i),xd=(...i)=>Fs().setTimeout(...i),Id=i=>i.method!==void 0&&i.method==="call",Od=i=>typeof i.id=="number"&&typeof i.result=="boolean",Md=i=>{const e=new Map([[0,()=>{}]]),t=new Map([[0,()=>{}]]),r=new Map,n=new Worker(i,{credentials:"omit"});return n.addEventListener("message",({data:c})=>{if(Id(c)){const{params:{timerId:u,timerType:l}}=c;if(l==="interval"){const h=e.get(u);if(typeof h===void 0)throw new Error("The timer is in an undefined state.");if(typeof h=="number"){const p=r.get(h);if(p===void 0||p.timerId!==u||p.timerType!==l)throw new Error("The timer is in an undefined state.")}else typeof h=="function"&&h()}else if(l==="timeout"){const h=t.get(u);if(typeof h===void 0)throw new Error("The timer is in an undefined state.");if(typeof h=="number"){const p=r.get(h);if(p===void 0||p.timerId!==u||p.timerType!==l)throw new Error("The timer is in an undefined state.")}else typeof h=="function"&&(h(),t.delete(u))}}else if(Od(c)){const{id:u}=c,l=r.get(u);if(l===void 0)throw new Error("The timer is in an undefined state.");const{timerId:h,timerType:p}=l;r.delete(u),p==="interval"?e.delete(h):t.delete(h)}else{const{error:{message:u}}=c;throw new Error(u)}}),{clearInterval:c=>{if(typeof e.get(c)=="function"){const u=Xe(r);r.set(u,{timerId:c,timerType:"interval"}),e.set(c,u),n.postMessage({id:u,method:"clear",params:{timerId:c,timerType:"interval"}})}},clearTimeout:c=>{if(typeof t.get(c)=="function"){const u=Xe(r);r.set(u,{timerId:c,timerType:"timeout"}),t.set(c,u),n.postMessage({id:u,method:"clear",params:{timerId:c,timerType:"timeout"}})}},setInterval:(c,u=0,...l)=>{const h=Xe(e);return e.set(h,()=>{c(...l),typeof e.get(h)=="function"&&n.postMessage({id:null,method:"set",params:{delay:u,now:performance.timeOrigin+performance.now(),timerId:h,timerType:"interval"}})}),n.postMessage({id:null,method:"set",params:{delay:u,now:performance.timeOrigin+performance.now(),timerId:h,timerType:"interval"}}),h},setTimeout:(c,u=0,...l)=>{const h=Xe(t);return t.set(h,()=>c(...l)),n.postMessage({id:null,method:"set",params:{delay:u,now:performance.timeOrigin+performance.now(),timerId:h,timerType:"timeout"}}),h}}},Pd={width:640,height:480,frameRate:30,backgroundColor:"#000000"},Ui=new he("View");class Ld{constructor(e){S(this,"id",dt());S(this,"_context");S(this,"_canvas");S(this,"_config");S(this,"_nodeList",[]);S(this,"_track");S(this,"_stopped",!0);S(this,"_nextTime",Date.now());S(this,"_workerTimeoutId");S(this,"_raqId");S(this,"_workerTimerScriptUrl");S(this,"_customSetTimeout");S(this,"_customClearTimeout");S(this,"_drawCount",0);S(this,"_lastSecondDrawCount",0);S(this,"_lastCountResetTime",Date.now());S(this,"_loopTimer");S(this,"_paintLoop",()=>{if(this._stopped){this._workerTimeoutId&&(this._customClearTimeout(this._workerTimeoutId),this._workerTimeoutId=void 0);return}this._drawOnCanvas(),this._workerTimeoutId&&this._customClearTimeout(this._workerTimeoutId),this._workerTimeoutId=this._customSetTimeout(()=>{this._paintLoop(),this._raqId&&(cancelAnimationFrame(this._raqId),this._raqId=void 0)},Oi/this._config.frameRate),this._raqId=requestAnimationFrame(this._paintLoop)});Ui.info("ctor",e),this._config={...Pd,...e};const{context:t,canvas:r}=ws(this._config);this._context=t,this._canvas=r,this._customSetTimeout=xd,this._customClearTimeout=Dd}setWorkerTimerScriptUrl(e){if(this._workerTimerScriptUrl=e,this._workerTimerScriptUrl){const t=Md(this._workerTimerScriptUrl);this._customSetTimeout=(...r)=>t.setTimeout(...r),this._customClearTimeout=r=>t.clearTimeout(r)}}_shouldDraw(e){if(e<this._nextTime)return!1;for(;e>this._nextTime;)this._nextTime+=Oi/this._config.frameRate;return!0}updateConfig(e){this._config={...this._config,...e},this._canvas.width=this._config.width,this._canvas.height=this._config.height}draw(e=[]){Ui.info("draw",e),this._nodeList=e}_drawOnCanvas(){if(this._shouldDraw(Date.now())){this._drawCount++,this._updateDrawCountPerSecond(),this._drawBackground();for(const e of this._nodeList){let t=e;if(t.available()){for(;t;)t.paint(this._context),t=t.previousNode;this._context.setTransform(1,0,0,1,0,0)}}}}_updateDrawCountPerSecond(){const e=Date.now();e-this._lastCountResetTime>=Oi&&(this._lastSecondDrawCount=this._drawCount,this._drawCount=0,this._lastCountResetTime=e)}getDrawCountPerSecond(){return this._updateDrawCountPerSecond(),this._lastSecondDrawCount}_drawBackground(){const{backgroundColor:e,width:t,height:r}=this._config;this._context.clearRect(0,0,t,r),e&&(this._context.fillStyle=e,this._context.fillRect(0,0,t,r))}track(){if(Ui.info("track"),this._stopped&&(this._stopped=!1,this._paintLoop()),this._track)return this._track;const{frameRate:e}=this._config,t=this._canvas.captureStream(e);return this._track=t.getVideoTracks()[0],this._track}updateFps(){if(this._track){const e=this._track,{frameRate:t}=this._config,r=this._canvas.captureStream(t);return this._track=r.getVideoTracks()[0],e.stop(),this._track}else return this.track()}element(){return Ui.info("element"),this._paintLoop(),this._canvas}stop(){this._stopped=!0}}function Ud(){return Math.random().toString(36).slice(-8)}const Gd=`
2
2
  const SMOOTHING_FACTOR = 0.8;
3
3
  const MINIMUM_VALUE = 0.00001;
4
4
 
@@ -53,41 +53,61 @@ registerProcessor('vumeter', class extends AudioWorkletProcessor {
53
53
  return true;
54
54
  }
55
55
  });
56
- `,bo=URL.createObjectURL(new Blob([Eo],{type:"application/javascript"}));class ko{constructor(){this._audioCtx=null,this._volume=0}get volume(){return this._volume}async start(e,t){if(this._audioCtx)return;const i=new AudioContext;await i.audioWorklet.addModule(t||bo);const s=new MediaStream;s.addTrack(e);const n=i.createMediaStreamSource(s),a=new AudioWorkletNode(i,"vumeter");a.port.onmessage=o=>{const u=o.data.volume||0;this._volume=Math.min(u*100/2,10)},n.connect(a).connect(i.destination),this._audioCtx=i}stop(){var e;(e=this._audioCtx)==null||e.close(),this._audioCtx=null}}class $e{constructor(){this._volumeDetectScriptUrl=void 0}static get instance(){return this._instance||(this._instance=new $e),this._instance}get volumeDetectScriptUrl(){return this._volumeDetectScriptUrl}set volumeDetectScriptUrl(e){this._volumeDetectScriptUrl=e}}class Or extends Q{constructor(e){super(),this._width=0,this._height=0,this._mediaStream=null,this._nextStream=null,this._trackMap={},this.type=e.type,this.id=To(),this._source=e.stream}get source(){return this._source}get videoTrack(){return this._trackMap.video}get audioTrack(){return this._trackMap.audio}get width(){return this._width}get height(){return this._height}get isVideoStream(){return[S.Camera,S.Screen,S.VideoFile].includes(this.type)}get mediaStream(){if(this._mediaStream)return this._mediaStream;const e=new MediaStream;return this._trackMap.audio&&e.addTrack(this._trackMap.audio),this._trackMap.video&&e.addTrack(this._trackMap.video),this._mediaStream=e,e}async startVolumeDetect(){this.audioTrack&&(this._volumeDetector||(this._volumeDetector=new ko),await this._volumeDetector.start(this.audioTrack,$e.instance.volumeDetectScriptUrl))}stopVolumeDetect(){var e;(e=this._volumeDetector)==null||e.stop(),this._volumeDetector=null}get volume(){var e;return((e=this._volumeDetector)==null?void 0:e.volume)||0}}class le extends Or{get isVideoStream(){return!0}get isAudioStream(){return!1}bindTrackSizeChangeEvent(e){e.on(D.SIZE_CHANGE,({width:t,height:i})=>{this._width=t,this._height=i,this.emit(it.SizeChange,{width:t,height:i})})}}class Be extends Or{get isVideoStream(){return!1}get isAudioStream(){return!0}}class Po extends le{constructor(e){super({type:S.Camera,stream:e}),this._trackMap.video=e.track(),this._width=e.width(),this._height=e.height(),this.bindTrackSizeChangeEvent(e)}get source(){return this._source}get viewNode(){return this.source.node()}get mixerNode(){return null}bindTrackEnd(e){this.source.on(D.ENDED,e)}destroy(){this.source.destroy()}}var Ir=typeof global=="object"&&global&&global.Object===Object&&global,xo=typeof self=="object"&&self&&self.Object===Object&&self,X=Ir||xo||Function("return this")(),te=X.Symbol,Dr=Object.prototype,Ro=Dr.hasOwnProperty,Ao=Dr.toString,ke=te?te.toStringTag:void 0;function wo(r){var e=Ro.call(r,ke),t=r[ke];try{r[ke]=void 0;var i=!0}catch{}var s=Ao.call(r);return i&&(e?r[ke]=t:delete r[ke]),s}var Oo=Object.prototype,Io=Oo.toString;function Do(r){return Io.call(r)}var Mo="[object Null]",Lo="[object Undefined]",Mr=te?te.toStringTag:void 0;function me(r){return r==null?r===void 0?Lo:Mo:Mr&&Mr in Object(r)?wo(r):Do(r)}function fe(r){return r!=null&&typeof r=="object"}var Fo="[object Symbol]";function je(r){return typeof r=="symbol"||fe(r)&&me(r)==Fo}function Lr(r,e){for(var t=-1,i=r==null?0:r.length,s=Array(i);++t<i;)s[t]=e(r[t],t,r);return s}var F=Array.isArray,Fr=te?te.prototype:void 0,Nr=Fr?Fr.toString:void 0;function Vr(r){if(typeof r=="string")return r;if(F(r))return Lr(r,Vr)+"";if(je(r))return Nr?Nr.call(r):"";var e=r+"";return e=="0"&&1/r==-1/0?"-0":e}var No=/\s/;function Vo(r){for(var e=r.length;e--&&No.test(r.charAt(e)););return e}var Uo=/^\s+/;function $o(r){return r&&r.slice(0,Vo(r)+1).replace(Uo,"")}function Pe(r){var e=typeof r;return r!=null&&(e=="object"||e=="function")}var Ur=NaN,Bo=/^[-+]0x[0-9a-f]+$/i,jo=/^0b[01]+$/i,zo=/^0o[0-7]+$/i,Go=parseInt;function Ho(r){if(typeof r=="number")return r;if(je(r))return Ur;if(Pe(r)){var e=typeof r.valueOf=="function"?r.valueOf():r;r=Pe(e)?e+"":e}if(typeof r!="string")return r===0?r:+r;r=$o(r);var t=jo.test(r);return t||zo.test(r)?Go(r.slice(2),t?2:8):Bo.test(r)?Ur:+r}var qo=1/0,Wo=17976931348623157e292;function Xo(r){if(!r)return r===0?r:0;if(r=Ho(r),r===qo||r===-1/0){var e=r<0?-1:1;return e*Wo}return r===r?r:0}function Ko(r){var e=Xo(r),t=e%1;return e===e?t?e-t:e:0}function Jo(r){return r}var Yo="[object AsyncFunction]",Zo="[object Function]",Qo="[object GeneratorFunction]",ea="[object Proxy]";function $r(r){if(!Pe(r))return!1;var e=me(r);return e==Zo||e==Qo||e==Yo||e==ea}var yt=X["__core-js_shared__"],Br=function(){var r=/[^.]+$/.exec(yt&&yt.keys&&yt.keys.IE_PROTO||"");return r?"Symbol(src)_1."+r:""}();function ta(r){return!!Br&&Br in r}var ra=Function.prototype,ia=ra.toString;function ae(r){if(r!=null){try{return ia.call(r)}catch{}try{return r+""}catch{}}return""}var sa=/[\\^$.*+?()[\]{}|]/g,na=/^\[object .+?Constructor\]$/,oa=Function.prototype,aa=Object.prototype,ca=oa.toString,da=aa.hasOwnProperty,ua=RegExp("^"+ca.call(da).replace(sa,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function ha(r){if(!Pe(r)||ta(r))return!1;var e=$r(r)?ua:na;return e.test(ae(r))}function pa(r,e){return r==null?void 0:r[e]}function _e(r,e){var t=pa(r,e);return ha(t)?t:void 0}var St=_e(X,"WeakMap");function la(r,e,t,i){for(var s=r.length,n=t+-1;++n<s;)if(e(r[n],n,r))return n;return-1}var ma=9007199254740991,fa=/^(?:0|[1-9]\d*)$/;function jr(r,e){var t=typeof r;return e=e??ma,!!e&&(t=="number"||t!="symbol"&&fa.test(r))&&r>-1&&r%1==0&&r<e}function zr(r,e){return r===e||r!==r&&e!==e}var _a=9007199254740991;function Tt(r){return typeof r=="number"&&r>-1&&r%1==0&&r<=_a}function Et(r){return r!=null&&Tt(r.length)&&!$r(r)}var ga=Object.prototype;function va(r){var e=r&&r.constructor,t=typeof e=="function"&&e.prototype||ga;return r===t}function Ca(r,e){for(var t=-1,i=Array(r);++t<r;)i[t]=e(t);return i}var ya="[object Arguments]";function Gr(r){return fe(r)&&me(r)==ya}var Hr=Object.prototype,Sa=Hr.hasOwnProperty,Ta=Hr.propertyIsEnumerable,qr=Gr(function(){return arguments}())?Gr:function(r){return fe(r)&&Sa.call(r,"callee")&&!Ta.call(r,"callee")};function Ea(){return!1}var Wr=typeof exports=="object"&&exports&&!exports.nodeType&&exports,Xr=Wr&&typeof module=="object"&&module&&!module.nodeType&&module,ba=Xr&&Xr.exports===Wr,Kr=ba?X.Buffer:void 0,ka=Kr?Kr.isBuffer:void 0,bt=ka||Ea,Pa="[object Arguments]",xa="[object Array]",Ra="[object Boolean]",Aa="[object Date]",wa="[object Error]",Oa="[object Function]",Ia="[object Map]",Da="[object Number]",Ma="[object Object]",La="[object RegExp]",Fa="[object Set]",Na="[object String]",Va="[object WeakMap]",Ua="[object ArrayBuffer]",$a="[object DataView]",Ba="[object Float32Array]",ja="[object Float64Array]",za="[object Int8Array]",Ga="[object Int16Array]",Ha="[object Int32Array]",qa="[object Uint8Array]",Wa="[object Uint8ClampedArray]",Xa="[object Uint16Array]",Ka="[object Uint32Array]",k={};k[Ba]=k[ja]=k[za]=k[Ga]=k[Ha]=k[qa]=k[Wa]=k[Xa]=k[Ka]=!0,k[Pa]=k[xa]=k[Ua]=k[Ra]=k[$a]=k[Aa]=k[wa]=k[Oa]=k[Ia]=k[Da]=k[Ma]=k[La]=k[Fa]=k[Na]=k[Va]=!1;function Ja(r){return fe(r)&&Tt(r.length)&&!!k[me(r)]}function Ya(r){return function(e){return r(e)}}var Jr=typeof exports=="object"&&exports&&!exports.nodeType&&exports,xe=Jr&&typeof module=="object"&&module&&!module.nodeType&&module,Za=xe&&xe.exports===Jr,kt=Za&&Ir.process,Yr=function(){try{var r=xe&&xe.require&&xe.require("util").types;return r||kt&&kt.binding&&kt.binding("util")}catch{}}(),Zr=Yr&&Yr.isTypedArray,Qr=Zr?Ya(Zr):Ja,Qa=Object.prototype,ec=Qa.hasOwnProperty;function tc(r,e){var t=F(r),i=!t&&qr(r),s=!t&&!i&&bt(r),n=!t&&!i&&!s&&Qr(r),a=t||i||s||n,o=a?Ca(r.length,String):[],u=o.length;for(var d in r)ec.call(r,d)&&!(a&&(d=="length"||s&&(d=="offset"||d=="parent")||n&&(d=="buffer"||d=="byteLength"||d=="byteOffset")||jr(d,u)))&&o.push(d);return o}function rc(r,e){return function(t){return r(e(t))}}var ic=rc(Object.keys,Object),sc=Object.prototype,nc=sc.hasOwnProperty;function oc(r){if(!va(r))return ic(r);var e=[];for(var t in Object(r))nc.call(r,t)&&t!="constructor"&&e.push(t);return e}function Re(r){return Et(r)?tc(r):oc(r)}var ac=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,cc=/^\w*$/;function Pt(r,e){if(F(r))return!1;var t=typeof r;return t=="number"||t=="symbol"||t=="boolean"||r==null||je(r)?!0:cc.test(r)||!ac.test(r)||e!=null&&r in Object(e)}var Ae=_e(Object,"create");function dc(){this.__data__=Ae?Ae(null):{},this.size=0}function uc(r){var e=this.has(r)&&delete this.__data__[r];return this.size-=e?1:0,e}var hc="__lodash_hash_undefined__",pc=Object.prototype,lc=pc.hasOwnProperty;function mc(r){var e=this.__data__;if(Ae){var t=e[r];return t===hc?void 0:t}return lc.call(e,r)?e[r]:void 0}var fc=Object.prototype,_c=fc.hasOwnProperty;function gc(r){var e=this.__data__;return Ae?e[r]!==void 0:_c.call(e,r)}var vc="__lodash_hash_undefined__";function Cc(r,e){var t=this.__data__;return this.size+=this.has(r)?0:1,t[r]=Ae&&e===void 0?vc:e,this}function ce(r){var e=-1,t=r==null?0:r.length;for(this.clear();++e<t;){var i=r[e];this.set(i[0],i[1])}}ce.prototype.clear=dc,ce.prototype.delete=uc,ce.prototype.get=mc,ce.prototype.has=gc,ce.prototype.set=Cc;function yc(){this.__data__=[],this.size=0}function ze(r,e){for(var t=r.length;t--;)if(zr(r[t][0],e))return t;return-1}var Sc=Array.prototype,Tc=Sc.splice;function Ec(r){var e=this.__data__,t=ze(e,r);if(t<0)return!1;var i=e.length-1;return t==i?e.pop():Tc.call(e,t,1),--this.size,!0}function bc(r){var e=this.__data__,t=ze(e,r);return t<0?void 0:e[t][1]}function kc(r){return ze(this.__data__,r)>-1}function Pc(r,e){var t=this.__data__,i=ze(t,r);return i<0?(++this.size,t.push([r,e])):t[i][1]=e,this}function K(r){var e=-1,t=r==null?0:r.length;for(this.clear();++e<t;){var i=r[e];this.set(i[0],i[1])}}K.prototype.clear=yc,K.prototype.delete=Ec,K.prototype.get=bc,K.prototype.has=kc,K.prototype.set=Pc;var we=_e(X,"Map");function xc(){this.size=0,this.__data__={hash:new ce,map:new(we||K),string:new ce}}function Rc(r){var e=typeof r;return e=="string"||e=="number"||e=="symbol"||e=="boolean"?r!=="__proto__":r===null}function Ge(r,e){var t=r.__data__;return Rc(e)?t[typeof e=="string"?"string":"hash"]:t.map}function Ac(r){var e=Ge(this,r).delete(r);return this.size-=e?1:0,e}function wc(r){return Ge(this,r).get(r)}function Oc(r){return Ge(this,r).has(r)}function Ic(r,e){var t=Ge(this,r),i=t.size;return t.set(r,e),this.size+=t.size==i?0:1,this}function J(r){var e=-1,t=r==null?0:r.length;for(this.clear();++e<t;){var i=r[e];this.set(i[0],i[1])}}J.prototype.clear=xc,J.prototype.delete=Ac,J.prototype.get=wc,J.prototype.has=Oc,J.prototype.set=Ic;var Dc="Expected a function";function xt(r,e){if(typeof r!="function"||e!=null&&typeof e!="function")throw new TypeError(Dc);var t=function(){var i=arguments,s=e?e.apply(this,i):i[0],n=t.cache;if(n.has(s))return n.get(s);var a=r.apply(this,i);return t.cache=n.set(s,a)||n,a};return t.cache=new(xt.Cache||J),t}xt.Cache=J;var Mc=500;function Lc(r){var e=xt(r,function(i){return t.size===Mc&&t.clear(),i}),t=e.cache;return e}var Fc=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,Nc=/\\(\\)?/g,Vc=Lc(function(r){var e=[];return r.charCodeAt(0)===46&&e.push(""),r.replace(Fc,function(t,i,s,n){e.push(s?n.replace(Nc,"$1"):i||t)}),e});function Uc(r){return r==null?"":Vr(r)}function ei(r,e){return F(r)?r:Pt(r,e)?[r]:Vc(Uc(r))}function He(r){if(typeof r=="string"||je(r))return r;var e=r+"";return e=="0"&&1/r==-1/0?"-0":e}function ti(r,e){e=ei(e,r);for(var t=0,i=e.length;r!=null&&t<i;)r=r[He(e[t++])];return t&&t==i?r:void 0}function $c(r,e,t){var i=r==null?void 0:ti(r,e);return i===void 0?t:i}function Bc(r,e){for(var t=-1,i=e.length,s=r.length;++t<i;)r[s+t]=e[t];return r}function jc(){this.__data__=new K,this.size=0}function zc(r){var e=this.__data__,t=e.delete(r);return this.size=e.size,t}function Gc(r){return this.__data__.get(r)}function Hc(r){return this.__data__.has(r)}var qc=200;function Wc(r,e){var t=this.__data__;if(t instanceof K){var i=t.__data__;if(!we||i.length<qc-1)return i.push([r,e]),this.size=++t.size,this;t=this.__data__=new J(i)}return t.set(r,e),this.size=t.size,this}function Y(r){var e=this.__data__=new K(r);this.size=e.size}Y.prototype.clear=jc,Y.prototype.delete=zc,Y.prototype.get=Gc,Y.prototype.has=Hc,Y.prototype.set=Wc;function ri(r,e){for(var t=-1,i=r==null?0:r.length,s=0,n=[];++t<i;){var a=r[t];e(a,t,r)&&(n[s++]=a)}return n}function Xc(){return[]}var Kc=Object.prototype,Jc=Kc.propertyIsEnumerable,ii=Object.getOwnPropertySymbols,Yc=ii?function(r){return r==null?[]:(r=Object(r),ri(ii(r),function(e){return Jc.call(r,e)}))}:Xc;function Zc(r,e,t){var i=e(r);return F(r)?i:Bc(i,t(r))}function si(r){return Zc(r,Re,Yc)}var Rt=_e(X,"DataView"),At=_e(X,"Promise"),wt=_e(X,"Set"),ni="[object Map]",Qc="[object Object]",oi="[object Promise]",ai="[object Set]",ci="[object WeakMap]",di="[object DataView]",ed=ae(Rt),td=ae(we),rd=ae(At),id=ae(wt),sd=ae(St),re=me;(Rt&&re(new Rt(new ArrayBuffer(1)))!=di||we&&re(new we)!=ni||At&&re(At.resolve())!=oi||wt&&re(new wt)!=ai||St&&re(new St)!=ci)&&(re=function(r){var e=me(r),t=e==Qc?r.constructor:void 0,i=t?ae(t):"";if(i)switch(i){case ed:return di;case td:return ni;case rd:return oi;case id:return ai;case sd:return ci}return e});var ui=X.Uint8Array,nd="__lodash_hash_undefined__";function od(r){return this.__data__.set(r,nd),this}function ad(r){return this.__data__.has(r)}function qe(r){var e=-1,t=r==null?0:r.length;for(this.__data__=new J;++e<t;)this.add(r[e])}qe.prototype.add=qe.prototype.push=od,qe.prototype.has=ad;function cd(r,e){for(var t=-1,i=r==null?0:r.length;++t<i;)if(e(r[t],t,r))return!0;return!1}function dd(r,e){return r.has(e)}var ud=1,hd=2;function hi(r,e,t,i,s,n){var a=t&ud,o=r.length,u=e.length;if(o!=u&&!(a&&u>o))return!1;var d=n.get(r),c=n.get(e);if(d&&c)return d==e&&c==r;var h=-1,p=!0,l=t&hd?new qe:void 0;for(n.set(r,e),n.set(e,r);++h<o;){var f=r[h],g=e[h];if(i)var _=a?i(g,f,h,e,r,n):i(f,g,h,r,e,n);if(_!==void 0){if(_)continue;p=!1;break}if(l){if(!cd(e,function(T,b){if(!dd(l,b)&&(f===T||s(f,T,t,i,n)))return l.push(b)})){p=!1;break}}else if(!(f===g||s(f,g,t,i,n))){p=!1;break}}return n.delete(r),n.delete(e),p}function pd(r){var e=-1,t=Array(r.size);return r.forEach(function(i,s){t[++e]=[s,i]}),t}function ld(r){var e=-1,t=Array(r.size);return r.forEach(function(i){t[++e]=i}),t}var md=1,fd=2,_d="[object Boolean]",gd="[object Date]",vd="[object Error]",Cd="[object Map]",yd="[object Number]",Sd="[object RegExp]",Td="[object Set]",Ed="[object String]",bd="[object Symbol]",kd="[object ArrayBuffer]",Pd="[object DataView]",pi=te?te.prototype:void 0,Ot=pi?pi.valueOf:void 0;function xd(r,e,t,i,s,n,a){switch(t){case Pd:if(r.byteLength!=e.byteLength||r.byteOffset!=e.byteOffset)return!1;r=r.buffer,e=e.buffer;case kd:return!(r.byteLength!=e.byteLength||!n(new ui(r),new ui(e)));case _d:case gd:case yd:return zr(+r,+e);case vd:return r.name==e.name&&r.message==e.message;case Sd:case Ed:return r==e+"";case Cd:var o=pd;case Td:var u=i&md;if(o||(o=ld),r.size!=e.size&&!u)return!1;var d=a.get(r);if(d)return d==e;i|=fd,a.set(r,e);var c=hi(o(r),o(e),i,s,n,a);return a.delete(r),c;case bd:if(Ot)return Ot.call(r)==Ot.call(e)}return!1}var Rd=1,Ad=Object.prototype,wd=Ad.hasOwnProperty;function Od(r,e,t,i,s,n){var a=t&Rd,o=si(r),u=o.length,d=si(e),c=d.length;if(u!=c&&!a)return!1;for(var h=u;h--;){var p=o[h];if(!(a?p in e:wd.call(e,p)))return!1}var l=n.get(r),f=n.get(e);if(l&&f)return l==e&&f==r;var g=!0;n.set(r,e),n.set(e,r);for(var _=a;++h<u;){p=o[h];var T=r[p],b=e[p];if(i)var v=a?i(b,T,p,e,r,n):i(T,b,p,r,e,n);if(!(v===void 0?T===b||s(T,b,t,i,n):v)){g=!1;break}_||(_=p=="constructor")}if(g&&!_){var j=r.constructor,R=e.constructor;j!=R&&"constructor"in r&&"constructor"in e&&!(typeof j=="function"&&j instanceof j&&typeof R=="function"&&R instanceof R)&&(g=!1)}return n.delete(r),n.delete(e),g}var Id=1,li="[object Arguments]",mi="[object Array]",We="[object Object]",Dd=Object.prototype,fi=Dd.hasOwnProperty;function Md(r,e,t,i,s,n){var a=F(r),o=F(e),u=a?mi:re(r),d=o?mi:re(e);u=u==li?We:u,d=d==li?We:d;var c=u==We,h=d==We,p=u==d;if(p&&bt(r)){if(!bt(e))return!1;a=!0,c=!1}if(p&&!c)return n||(n=new Y),a||Qr(r)?hi(r,e,t,i,s,n):xd(r,e,u,t,i,s,n);if(!(t&Id)){var l=c&&fi.call(r,"__wrapped__"),f=h&&fi.call(e,"__wrapped__");if(l||f){var g=l?r.value():r,_=f?e.value():e;return n||(n=new Y),s(g,_,t,i,n)}}return p?(n||(n=new Y),Od(r,e,t,i,s,n)):!1}function It(r,e,t,i,s){return r===e?!0:r==null||e==null||!fe(r)&&!fe(e)?r!==r&&e!==e:Md(r,e,t,i,It,s)}var Ld=1,Fd=2;function Nd(r,e,t,i){var s=t.length,n=s;if(r==null)return!n;for(r=Object(r);s--;){var a=t[s];if(a[2]?a[1]!==r[a[0]]:!(a[0]in r))return!1}for(;++s<n;){a=t[s];var o=a[0],u=r[o],d=a[1];if(a[2]){if(u===void 0&&!(o in r))return!1}else{var c=new Y,h;if(!(h===void 0?It(d,u,Ld|Fd,i,c):h))return!1}}return!0}function _i(r){return r===r&&!Pe(r)}function Vd(r){for(var e=Re(r),t=e.length;t--;){var i=e[t],s=r[i];e[t]=[i,s,_i(s)]}return e}function gi(r,e){return function(t){return t==null?!1:t[r]===e&&(e!==void 0||r in Object(t))}}function Ud(r){var e=Vd(r);return e.length==1&&e[0][2]?gi(e[0][0],e[0][1]):function(t){return t===r||Nd(t,r,e)}}function $d(r,e){return r!=null&&e in Object(r)}function Bd(r,e,t){e=ei(e,r);for(var i=-1,s=e.length,n=!1;++i<s;){var a=He(e[i]);if(!(n=r!=null&&t(r,a)))break;r=r[a]}return n||++i!=s?n:(s=r==null?0:r.length,!!s&&Tt(s)&&jr(a,s)&&(F(r)||qr(r)))}function jd(r,e){return r!=null&&Bd(r,e,$d)}var zd=1,Gd=2;function Hd(r,e){return Pt(r)&&_i(e)?gi(He(r),e):function(t){var i=$c(t,r);return i===void 0&&i===e?jd(t,r):It(e,i,zd|Gd)}}function qd(r){return function(e){return e==null?void 0:e[r]}}function Wd(r){return function(e){return ti(e,r)}}function Xd(r){return Pt(r)?qd(He(r)):Wd(r)}function Dt(r){return typeof r=="function"?r:r==null?Jo:typeof r=="object"?F(r)?Hd(r[0],r[1]):Ud(r):Xd(r)}function Kd(r){return function(e,t,i){for(var s=-1,n=Object(e),a=i(e),o=a.length;o--;){var u=a[++s];if(t(n[u],u,n)===!1)break}return e}}var Jd=Kd();function Yd(r,e){return r&&Jd(r,e,Re)}function Zd(r,e){return function(t,i){if(t==null)return t;if(!Et(t))return r(t,i);for(var s=t.length,n=-1,a=Object(t);++n<s&&i(a[n],n,a)!==!1;);return t}}var Qd=Zd(Yd);function eu(r,e){var t=[];return Qd(r,function(i,s,n){e(i,s,n)&&t.push(i)}),t}function vi(r,e){var t=F(r)?ri:eu;return t(r,Dt(e))}function tu(r){return function(e,t,i){var s=Object(e);if(!Et(e)){var n=Dt(t);e=Re(e),t=function(o){return n(s[o],o,s)}}var a=r(e,t,i);return a>-1?s[n?e[a]:a]:void 0}}var ru=Math.max;function iu(r,e,t){var i=r==null?0:r.length;if(!i)return-1;var s=t==null?0:Ko(t);return s<0&&(s=ru(i+s,0)),la(r,Dt(e),s)}var Oe=tu(iu);function su(r,e){return Lr(e,function(t){return r[t]})}function ge(r){return r==null?[]:su(r,Re(r))}function nu(r){return r==null}class ou extends Be{constructor(e){super({type:S.Microphone,stream:e}),this._trackMap.audio=e.track()}get source(){return this._source}get mixerNode(){return this.source.node()}bindTrackEnd(e){this.source.on(D.ENDED,e)}destroy(){this.source.destroy()}}class au extends le{constructor(e){super({type:S.VideoFile,stream:e});const t=Oe(e,s=>s.kind===E.VIDEO),i=Oe(e,s=>s.kind===E.AUDIO);this._videoStream=t,this._audioStream=i,this._trackMap.video=t==null?void 0:t.track(),this._trackMap.audio=i==null?void 0:i.track(),t&&(this._height=t==null?void 0:t.height(),this._width=t==null?void 0:t.width())}get viewNode(){var e;return((e=this._videoStream)==null?void 0:e.node())??null}get mixerNode(){var e;return((e=this._audioStream)==null?void 0:e.node())??null}bindTrackEnd(e){var t;(t=this._videoStream)==null||t.on(D.ENDED,e)}destroy(){var e,t;(e=this._videoStream)==null||e.destroy(),(t=this._audioStream)==null||t.destroy(),delete this._trackMap.video,delete this._trackMap.audio}}class cu extends le{constructor(e){super({type:S.Screen,stream:e});const t=Oe(e,s=>s.kind===E.VIDEO),i=Oe(e,s=>s.kind===E.AUDIO);this._videoStream=t,this._audioStream=i,this._trackMap.video=t==null?void 0:t.track(),this._trackMap.audio=i==null?void 0:i.track(),t&&(this._height=t==null?void 0:t.height(),this._width=t==null?void 0:t.width(),this.bindTrackSizeChangeEvent(t))}get viewNode(){var e;return((e=this._videoStream)==null?void 0:e.node())??null}get mixerNode(){var e;return((e=this._audioStream)==null?void 0:e.node())??null}bindTrackEnd(e){var t;(t=this._videoStream)==null||t.on(D.ENDED,e)}destroy(){var e,t;(e=this._videoStream)==null||e.destroy(),(t=this._audioStream)==null||t.destroy(),delete this._trackMap.video,delete this._trackMap.audio}}class du extends Be{constructor(e){super({type:S.AudioFile,stream:e});const t=Oe(e,i=>i.kind===E.AUDIO);this._audioStream=t,this._trackMap.audio=t==null?void 0:t.track()}get mixerNode(){var e;return((e=this._audioStream)==null?void 0:e.node())??null}bindTrackEnd(e){var t;(t=this._audioStream)==null||t.on(D.ENDED,e)}destroy(){var e;(e=this._audioStream)==null||e.destroy()}}class uu extends le{constructor(e){super({type:S.Image,stream:e}),this._width=e.width(),this._height=e.height()}get source(){return this._source}get mixerNode(){return null}get viewNode(){return this.source.node()}bindTrackEnd(e){this.source.on(D.ENDED,e)}destroy(){this.source.destroy()}}class hu extends le{constructor(e){super({type:S.CustomVideo,stream:e}),this._trackMap.video=e.track(),this._width=e.width(),this._height=e.height()}get source(){return this._source}get viewNode(){return this.source.node()}get mixerNode(){return null}bindTrackEnd(e){this.source.on(D.ENDED,e)}destroy(){this.source.destroy()}}class pu extends Be{constructor(e){super({type:S.CustomAudio,stream:e}),this._trackMap.audio=e==null?void 0:e.track()}get source(){return this._source}get mixerNode(){var e;return((e=this.source)==null?void 0:e.node())??null}bindTrackEnd(e){var t;(t=this._audioStream)==null||t.on(D.ENDED,e)}destroy(){var e;(e=this._audioStream)==null||e.destroy()}}const lu=["user","environment"];var N=(r=>(r[r.OPEN_CAMERA_FAILED=1001]="OPEN_CAMERA_FAILED",r[r.OPEN_MICROPHONE_FAILED=1002]="OPEN_MICROPHONE_FAILED",r[r.OPEN_SCREEN_FAILED=1003]="OPEN_SCREEN_FAILED",r[r.VIDEO_FILE_CAPTURE_FAILED=1004]="VIDEO_FILE_CAPTURE_FAILED",r[r.AUDIO_FILE_CAPTURE_FAILED=1005]="AUDIO_FILE_CAPTURE_FAILED",r[r.IMAGE_FILE_CAPTURE_FAILED=1006]="IMAGE_FILE_CAPTURE_FAILED",r[r.VOLUME_DETECT_FAILED=1008]="VOLUME_DETECT_FAILED",r[r.PUBLISH_FAILED=2001]="PUBLISH_FAILED",r[r.UPDATE_PUBLISH_FAILED=2002]="UPDATE_PUBLISH_FAILED",r[r.PUSH_CONNECT_FAILED=2003]="PUSH_CONNECT_FAILED",r))(N||{});class Ie extends Error{constructor(e,t,i){super(),this.code=e,this.message=t,i&&(this.ext=i)}}function ve(r,e,t){const i=st.Landscape;if(e==="video"){const u=(i===st.Landscape?tr:rr)[r],[d,c,h,p]=u.split("x").map(l=>Number(l));return{width:d,height:c,frameRate:h,bitrate:p*1e3}}const s=ir[r],[n,a]=s.split("x").map(o=>Number(o));return{sampleRate:n,bitrate:a*1e3}}class mu extends Q{constructor(){super(),this._videoConstraints={width:1080,height:720,frameRate:30},this._cameraStreams={},this._screenStreams={},this._videoFileStreams={},this._microphoneStreams={},this._audioFileStreams={},this._imageStreams={},this._customVideoStreams={},this._customAudioStreams={};const{width:e,height:t,frameRate:i}=ve(nr,"video"),{sampleRate:s}=ve(or,"audio");this._videoConstraints={width:e,height:t,frameRate:i},this._audioConstraints={sampleRate:s,enableAutoGainControl:!0,enableNoiseSuppression:!0,enableEchoCancellation:!0}}_notifyCaptured(e){this.emit(z.DeviceCaptured,e)}_notifyStopCapture(e){this.emit(z.DeviceStopCapture,e)}_bindStreamEvent(e){e.bindTrackEnd(()=>{this.emit(z.Interrupted,e),this.stopCapture({streamId:e.id,type:e.type})})}_handleError(e,t){const i=new Ie(t,e.message);this.emit(z.Error,i)}setVideoResolution(e){this._videoConstraints={...this._videoConstraints,...e}}setVideoFps(e){this._videoConstraints={...this._videoConstraints,frameRate:e}}setAudioSampleRate(e){this._audioConstraints={...this._audioConstraints,sampleRate:e}}async getDevicesList(e){return Zn(e?[e]:["audioinput","videoinput"])}async getMicrophones(){return this.getDevicesList("audioinput")}async getCameras(){return this.getDevicesList("videoinput")}stopCapture({streamId:e,type:t}){let i;switch(t){case S.Camera:i="_cameraStreams";break;case S.Screen:i="_screenStreams";break;case S.VideoFile:i="_videoFileStreams";break;case S.Microphone:i="_microphoneStreams";break;case S.AudioFile:i="_audioFileStreams";break;case S.Image:i="_imageStreams";break;case S.CustomVideo:i="_customVideoStreams";break;case S.CustomAudio:i="_customAudioStreams";break}if(i){let s=[];if(e){const n=this[i][e];s.push(n)}else s=ge(this[i]);s.forEach(n=>{this._notifyStopCapture(n),n.destroy(),delete this[i][n.id]})}}async startCameraCapture(e){let t={};lu.includes(e)?t={facingMode:e}:t={deviceId:e};try{const i=await Qn({...t,...this._videoConstraints}),s=new Po(i);return this._cameraStreams[s.id]=s,this._notifyCaptured(s),this._bindStreamEvent(s),s.id}catch(i){throw this._handleError(i,N.OPEN_CAMERA_FAILED),i}}async startMicrophoneCapture(e){try{const t=await to({...this._audioConstraints,deviceId:e}),i=new ou(t);return this._microphoneStreams[i.id]=i,this._notifyCaptured(i),this._bindStreamEvent(i),i.id}catch(t){throw this._handleError(t,N.OPEN_MICROPHONE_FAILED),t}}async startScreenCapture(e){try{const t=await ro({audio:e,video:this._videoConstraints}),i=new cu(t);return this._screenStreams[i.id]=i,this._notifyCaptured(i),this._bindStreamEvent(i),i.id}catch(t){throw this._handleError(t,N.OPEN_SCREEN_FAILED),t}}async startVideoFileCapture(e){try{const t=await br({url:e,video:!0,audio:!0,loop:!0}),i=new au(t);return this._videoFileStreams[i.id]=i,this._notifyCaptured(i),this._bindStreamEvent(i),i.id}catch(t){throw this._handleError(t,N.VIDEO_FILE_CAPTURE_FAILED),t}}async startAudioFileCapture(e){try{const t=await br({url:e,video:!1,audio:!0,loop:!0}),i=new du(t);return this._audioFileStreams[i.id]=i,this._notifyCaptured(i),this._bindStreamEvent(i),i.id}catch(t){throw this._handleError(t,N.AUDIO_FILE_CAPTURE_FAILED),t}}async startImageCapture(e){try{const t=await eo({url:e,width:0,height:0,frameRate:30}),i=new uu(t);return this._imageStreams[i.id]=i,this._notifyCaptured(i),this._bindStreamEvent(i),i.id}catch(t){throw this._handleError(t,N.IMAGE_FILE_CAPTURE_FAILED),t}}startCustomVideoCapture(e){const t=so(e);if(t){const i=new hu(t);return this._customVideoStreams[i.id]=i,this._notifyCaptured(i),this._bindStreamEvent(i),i.id}}startCustomAudioCapture(e){const t=no(e);if(t){const i=new pu(t);return this._customAudioStreams[i.id]=i,this._notifyCaptured(i),this._bindStreamEvent(i),i.id}}async startVolumeDetect(e){const t=this.getStreamById(e);if(t)try{await t.startVolumeDetect()}catch(i){this._handleError(i,N.VOLUME_DETECT_FAILED)}}stopVolumeDetect(e){const t=this.getStreamById(e);t&&t.stopVolumeDetect()}getDefaultVideoStream(){return ge(this._cameraStreams)[0]||ge(this._screenStreams)[0]||ge(this._videoFileStreams)[0]}getDefaultAudioStream(){return ge(this._microphoneStreams)[0]||ge(this._audioFileStreams)[0]}getVideoStream(e){return this._cameraStreams[e]||this._screenStreams[e]||this._videoFileStreams[e]||this._imageStreams[e]}getAudioStream(e){return this._microphoneStreams[e]||this._audioFileStreams[e]}getStreamById(e){return this.getAudioStream(e)||this.getVideoStream(e)}getVolume(e){const t=this.getStreamById(e);return(t==null?void 0:t.volume)||0}destroy(){Object.values(S).forEach(e=>{this.stopCapture({type:e})})}}let de=class{constructor(e){this._enabled=!1,this.group=(...t)=>{this._enabled&&console.group(`[${this._prefix}]: `,...t)},this.groupCollapsed=(...t)=>{this._enabled&&console.groupCollapsed(`[${this._prefix}]: `,...t)},this.groupEnd=()=>{this._enabled&&console.groupEnd()},this.log=(...t)=>{this._enabled&&console.log(`[${this._prefix}]: `,...t)},this.warn=(...t)=>{this._enabled&&console.warn(`[${this._prefix}]: `,...t)},this.error=(...t)=>{this._enabled&&console.error(`[${this._prefix}]: `,...t)},this.table=(...t)=>{this._enabled&&console.table(...t)},this._prefix=e;try{this._enabled=location.href.indexOf("rtmdebug")!==-1}catch{}}};class Mt{constructor({streamManagerController:e,composedStream:t,streamComposeController:i}){this._streamManagerController=e,this._composedStream=t,this._streamComposeController=i,this._active=!1,this.bindStreamManagerControllerEvent()}bindStreamManagerControllerEvent(){this._streamManagerController.on(z.DeviceCaptured,e=>{this._active&&this.onStreamCapture(e)}),this._streamManagerController.on(z.DeviceStopCapture,e=>{this._active&&this.onStreamStopCapture(e)})}getComposedStream(){return this._composedStream}enable(){this._active=!0}disable(){this._active=!1}}const Ci=new de("SingleComposer");class fu extends Mt{onStreamCapture(e){e.isVideoStream?this._handleVideoStreamCapture(e):this._handleAudioStreamCapture(e)}onStreamStopCapture(e){e&&(e.isVideoStream?this._handleVideoStreamStopCapture(e):this._handleAudioStreamStopCapture(e))}enable(){if(super.enable(),this._composedStream.videoStream){const e=this._streamManagerController.getDefaultVideoStream();e&&this._handleVideoStreamCapture(e)}}async setVideoQuality({width:e,height:t,frameRate:i}){var s,n;if(this._active)try{await((n=(s=this._composedStream.videoStream)==null?void 0:s.videoTrack)==null?void 0:n.applyConstraints({width:{min:e,ideal:e},height:{min:t,ideal:t},frameRate:{min:i,ideal:i}}))}catch(a){Ci.error("setVideoQuality error",a)}}_handleVideoStreamCapture(e){const t=this._composedStream.videoStream;t!=null&&t.id&&this._streamComposeController.getMixerComposer().haveMixedStream(t.id)&&this._streamComposeController.removeAudioStream(t.id),e.audioTrack&&this._streamComposeController.addAudioStream({streamId:e.id,volume:100}),this._composedStream.setVideoStream(e)}_handleAudioStreamCapture(e){const t=this._streamComposeController.getMixerComposer().getMixedStreamByType(e.type);t.length>0&&t.forEach(i=>{this._streamComposeController.removeAudioStream(i.id)}),this._streamComposeController.addAudioStream({streamId:e.id,volume:100})}_handleVideoStreamStopCapture(e){const t=this._composedStream.videoStream;if((t==null?void 0:t.id)===e.id){const i=this._streamManagerController.getDefaultVideoStream();i?this._handleVideoStreamCapture(i):Ci.error("all video stream stop capture")}}_handleAudioStreamStopCapture(e){this._streamComposeController.removeAudioStream(e.id)}getComposedStream(){return this._composedStream}}class _u extends Q{constructor(e,{width:t,height:i,x:s,y:n,zOrder:a,keepRatio:o}){super(),this._rect={x:0,y:0,width:0,height:0,zOrder:0},this._isHidden=!1,this._paintSize={width:0,height:0},this._rect.width=t??e.width,this._rect.height=i??e.height,this._rect.x=s??0,this._rect.y=n??0,this._rect.zOrder=a??0,this._rect.sourceHeight=e.height,this._rect.sourceWidth=e.width,this._rect.keepRatio=o??!1,this._stream=e,this._bindVideoTrackSizeChange()}_getPaintSize({elementWidth:e,elementHeight:t}){const i=this._rect.width,s=this._rect.height;if(i===0&&s===0)return{width:0,height:0};if(i===0)return{height:s,width:e*(s/t)};if(s===0)return{width:i,height:t*(i/e)};const n=e/t,a=i/s;let o=i,u=s;return n>a?(o=i,u=2*Math.round(i/n/2)):n<a&&(o=2*Math.round(s*n/2),u=s),{width:o,height:u}}_bindVideoTrackSizeChange(){this._stream.on(it.SizeChange,({width:e,height:t})=>{this.setBaseProps("sourceWidth",e),this.setBaseProps("sourceHeight",t)})}getViewNode(){var i;if(!this._stream)return;let e={width:this._rect.width,height:this._rect.height};return this._rect.keepRatio&&(e=this._getPaintSize({elementWidth:this._stream.width,elementHeight:this._stream.height})),this._paintSize=e,(i=this._stream.viewNode)==null?void 0:i.size(e.width,e.height).position(this._rect.x,this._rect.y)}get x(){return this._rect.x}set x(e){this.setBaseProps("x",e)}get y(){return this._rect.y}set y(e){this.setBaseProps("y",e)}get width(){return this._rect.width}set width(e){this.setBaseProps("width",e)}get height(){return this._rect.height}set height(e){this.setBaseProps("height",e)}get zOrder(){return this._rect.zOrder}set zOrder(e){this.setBaseProps("zOrder",e)}get keepRatio(){return this._rect.keepRatio??!1}set keepRatio(e){this.setBaseProps("keepRatio",e)}get paintSize(){return this._paintSize}setBaseProps(e,t){const i=this._rect[e]!==t;switch(e){case"width":this._rect.width=t;break;case"height":this._rect.height=t;break;case"x":this._rect.x=t;break;case"y":this._rect.y=t;break;case"zOrder":this._rect.zOrder=t;break;case"keepRatio":this._rect.keepRatio=t;break}i&&this.emit("propsChange",{[e]:t})}show(){this._isHidden=!1}hide(){this._isHidden=!0}get stream(){return this._stream}get isHidden(){return this._isHidden}destroy(){}}class yi extends le{constructor(e){super({type:S.MixVideo,stream:e}),this._trackMap.video=e}get source(){return this._source}replaceVideoTrack(e){this._trackMap.video=e,this._source=e}get viewNode(){return null}get mixerNode(){return null}bindTrackEnd(e){this.source.onended=e}destroy(){this.source.stop(),delete this._trackMap.video}}var gu=Object.defineProperty,vu=Object.getOwnPropertyDescriptor,De=(r,e,t,i)=>{for(var s=vu(e,t),n=r.length-1,a;n>=0;n--)(a=r[n])&&(s=a(e,t,s)||s);return s&&gu(e,t,s),s};const Si=new de("composition-composer");function Me(r,e,t){const i=t.value;return t.value=function(...s){return this._active||Si.error("composer is not active"),i.apply(this,s)},t}class Ce extends Mt{constructor(e){super(e),this._compositionViewConfig={width:1080,height:720,frameRate:30,backgroundColor:"#000000"},this._sprites=[],this._videoMixer=new So}onStreamCapture(e){}onStreamStopCapture(e){e&&e.isVideoStream&&this.removeVideoStream(e.id)}enable(){super.enable();const e=this._videoMixer.track();this._mixedVideoStream?this._mixedVideoStream.replaceVideoTrack(e):this._mixedVideoStream=new yi(e),this._composedStream.setVideoStream(this._mixedVideoStream)}disable(){super.disable(),this._videoMixer.stop()}_updateSpriteToMixer(){const e=vi(this._sprites.map(t=>t.isHidden?null:t.getViewNode()));this._videoMixer.draw(e)}_removeSprite(e){this._sprites=this._sprites.filter(t=>t!==e),e.destroy(),this._updateSpriteToMixer()}_addSprite(e){this._sprites.push(e),this._sprites=this._sprites.sort((t,i)=>t.zOrder-i.zOrder),e.on("propsChange",t=>{nu(t.zOrder)||(this._sprites=this._sprites.sort((i,s)=>i.zOrder-s.zOrder)),this._updateSpriteToMixer()}),this._updateSpriteToMixer()}setMixingConfig(e){const t=e.frameRate&&e.frameRate!==this._compositionViewConfig.frameRate;if(this._compositionViewConfig={...this._compositionViewConfig,...e},this._compositionViewConfig.frameRate<1&&(this._compositionViewConfig.frameRate=1),this._videoMixer.updateConfig(this._compositionViewConfig),t&&this._mixedVideoStream){const i=this._videoMixer.updateFps();this._mixedVideoStream?this._mixedVideoStream.replaceVideoTrack(i):this._mixedVideoStream=new yi(i),this._composedStream.setVideoStream(this._mixedVideoStream)}}addVideoStream(e,t){if(!e.viewNode){Si.error("have no viewNode for composition");return}e.audioTrack&&this._streamComposeController.addAudioStream({streamId:e.id,volume:100});const i=new _u(e,t);this._addSprite(i)}_updateSingleVideoStream(e){const t=e.streamId;if(!t)return;const i=this._sprites.find(s=>s.stream.id===t);i&&(i.height=e.height,i.width=e.width,i.x=e.x,i.y=e.y,i.zOrder=e.zOrder,i.keepRatio=e.keepRatio??!1)}updateVideoStream(e){e.forEach(t=>{this._updateSingleVideoStream(t)}),this._updateSpriteToMixer()}removeVideoStream(e){if(!e)return;const t=this._sprites.find(i=>i.stream.id===e);t&&this._removeSprite(t)}muteVideoStream(e){if(e){const t=this._sprites.find(i=>i.stream.id===e);t&&t.hide()}else this._sprites.forEach(t=>{t.hide()});this._updateSpriteToMixer()}unmuteVideoStream(e){if(e){const t=this._sprites.find(i=>i.stream.id===e);t&&t.show()}else this._sprites.forEach(t=>{t.show()});this._updateSpriteToMixer()}setMixerWorkerScript(e){this._videoMixer.setWorkerTimerScriptUrl(e)}}De([Me],Ce.prototype,"addVideoStream"),De([Me],Ce.prototype,"updateVideoStream"),De([Me],Ce.prototype,"removeVideoStream"),De([Me],Ce.prototype,"muteVideoStream"),De([Me],Ce.prototype,"unmuteVideoStream");class Cu extends Q{constructor(e,{volume:t}){super(),this._volume=100,this._isMute=!1,this._volume=t??100,this._stream=e}get volume(){return this._volume}set volume(e){const t=this._volume!==e;this._volume=e,t&&this.emit("propsChange",{volume:e})}getMixerNode(){var e;return(e=this._stream.mixerNode)==null?void 0:e.gain(this._volume/100)}mute(){this._isMute=!0}unmute(){this._isMute=!1}get isMute(){return this._isMute}get stream(){return this._stream}}class yu extends Be{constructor(e){super({type:S.MixAudio,stream:e}),this._trackMap.audio=e}get source(){return this._source}hasVideoTrack(){return!1}get mixerNode(){return null}bindTrackEnd(e){this.source.onended=e}destroy(){var e;(e=this._trackMap.audio)==null||e.stop(),delete this._trackMap.audio}}class Su extends Mt{constructor(e){super(e),this._spriteList=[],this._audioMixer=new ao}onStreamCapture(e){}onStreamStopCapture(e){e&&this.removeAudioStream(e.id)}_updateSpriteToMixer(){const e=vi(this._spriteList.map(t=>t.isMute?null:t.getMixerNode()));this._audioMixer.mix(e)}_updateSingleAudioStream(e){const{streamId:t,volume:i}=e,s=this._spriteList.find(n=>n.stream.id===t);s?i!==void 0&&(s.volume=i):console.error("can not find stream"+t)}enable(){super.enable();const e=this._audioMixer.track(),t=new yu(e);this._composedStream.setAudioStream(t),this._audioMixer.mix([])}addAudioStream(e,t){const i=new Cu(e,t);this._spriteList.push(i),this._updateSpriteToMixer()}removeAudioStream(e){const t=this._spriteList.find(i=>i.stream.id===e);t&&(this._spriteList=this._spriteList.filter(i=>i!==t),this._updateSpriteToMixer())}updateAudioStream(e){e.forEach(t=>{this._updateSingleAudioStream(t)}),this._updateSpriteToMixer()}muteAudioStream(e){if(e){const t=this._spriteList.find(i=>i.stream.id===e);t&&t.mute()}else this._spriteList.forEach(t=>{t.mute()});this._updateSpriteToMixer()}unmuteAudioStream(e){if(e){const t=this._spriteList.find(i=>i.stream.id===e);t&&t.unmute()}else this._spriteList.forEach(t=>{t.unmute()});this._updateSpriteToMixer()}haveMixedStream(e){return this._spriteList.some(t=>t.stream.id===e)}getMixedStreamByType(e){return this._spriteList.filter(t=>t.stream.type===e).map(t=>t.stream)}}class Tu extends Q{constructor({videoStream:e,audioStream:t}={}){super(),this._videoStream=e,this._audioStream=t}setVideoStream(e){var t;((t=this._videoStream)==null?void 0:t.id)!==(e==null?void 0:e.id)&&(this._videoStream=e,this.emit(ne.VideoStreamChange,e))}setAudioStream(e){var t;((t=this._audioStream)==null?void 0:t.id)!==e.id&&(this._audioStream=e,this.emit(ne.AudioStreamChange,e))}get audioStream(){return this._audioStream}get videoStream(){return this._videoStream}get videoTrack(){var e;return(e=this._videoStream)==null?void 0:e.videoTrack}get audioTrack(){var e;return(e=this._audioStream)==null?void 0:e.audioTrack}}const Eu=new de("streamComposeController");class bu{constructor(e){this._streamManagerController=e,this._composedStream=new Tu,this.singleComposer=new fu({streamManagerController:this._streamManagerController,composedStream:this._composedStream,streamComposeController:this}),this.compositionComposer=new Ce({streamManagerController:this._streamManagerController,composedStream:this._composedStream,streamComposeController:this}),this.mixerComposer=new Su({streamManagerController:this._streamManagerController,composedStream:this._composedStream,streamComposeController:this}),this.singleComposer.enable(),this.mixerComposer.enable()}enableMixing(e){e?(this.compositionComposer.enable(),this.singleComposer.disable()):(this.compositionComposer.disable(),this.singleComposer.enable())}setVideoQuality({width:e,height:t,frameRate:i}){this.singleComposer.setVideoQuality({width:e,height:t,frameRate:i}),this.compositionComposer.setMixingConfig({width:e,height:t,frameRate:i})}setMixingConfig(e){this.compositionComposer.setMixingConfig(e)}addAudioStream(e){const t=this._streamManagerController.getStreamById(e.streamId);this.mixerComposer.addAudioStream(t,{volume:e.volume??100})}removeAudioStream(e){return this.mixerComposer.removeAudioStream(e)}updateAudioStream(e){this.mixerComposer.updateAudioStream(e)}addVideoStream(e){const t=this._streamManagerController.getVideoStream(e.streamId);if(!t){Eu.error("can not find video stream"+e.streamId);return}this.compositionComposer.addVideoStream(t,e)}updateVideoStream(e){this.compositionComposer.updateVideoStream(e);const t=e.map(i=>({streamId:i.streamId,volume:i.volume}));this.mixerComposer.updateAudioStream(t)}removeVideoStream(e){this.compositionComposer.removeVideoStream(e),this.mixerComposer.removeAudioStream(e)}getComposer(){return this.isEnableMixing?this.compositionComposer:this.singleComposer}getComposedStream(){return this._composedStream}muteVideoStream(e){this.isEnableMixing&&this.compositionComposer.muteVideoStream(e)}unmuteVideoStream(e){this.isEnableMixing&&this.compositionComposer.unmuteVideoStream(e)}muteAudioStream(e){this.mixerComposer.muteAudioStream(e)}unmuteAudioStream(e){this.mixerComposer.unmuteAudioStream(e)}get isEnableMixing(){return this.compositionComposer._active}getMixerComposer(){return this.mixerComposer}setMixerWorkerScript(e){this.compositionComposer.setMixerWorkerScript(e)}}class Ti{constructor(e){this._hasBindComposedStreamEvent=!1,this._composedStream=e}bindComposedStreamEvent(){this._hasBindComposedStreamEvent||(this._composedStream.on(ne.VideoStreamChange,this.handleVideoStreamChange),this._composedStream.on(ne.AudioStreamChange,this.handleAudioStreamChange),this._hasBindComposedStreamEvent=!0)}unbindComposedStreamEvent(){this._hasBindComposedStreamEvent&&(this._composedStream.off(ne.VideoStreamChange,this.handleVideoStreamChange),this._composedStream.off(ne.AudioStreamChange,this.handleAudioStreamChange),this._hasBindComposedStreamEvent=!1)}}const ye=new de("PreviewConsumer");class ku extends Ti{constructor(e,{streamConsumeController:t}){super(e),this._isPreviewing=!1,this._previewElement=null,this.handleAudioStreamChange=i=>{this.startPreview()},this.handleVideoStreamChange=i=>{this.startPreview()},this._streamConsumeController=t}start(){this.bindComposedStreamEvent()}stop(){this.unbindComposedStreamEvent()}setRenderView(e){if(!e)return;const t=document.getElementById(e);if(!t)throw new Error(`can not found element with id ${e}`);if(t===this._previewElement)return;if(this._previewElement){if(t.contains(this._previewElement))return;t.appendChild(this._previewElement);return}const i=document.createElement("video");i.style.width="100%",i.style.height="100%",i.autoplay=!0,i.playsInline=!0,i.setAttribute("webkit-playsinline",""),i.setAttribute("x5-playsinline",""),this._previewElement=i;const s={video:null,audio:null};i.addEventListener("loadeddata",()=>{const n=i.srcObject.getVideoTracks()[0],a=i.srcObject.getAudioTracks()[0];n&&n!==s.video&&(this._streamConsumeController.emit(A.CaptureFirstVideoFrame),s.video=n),a&&a!==s.audio&&(this._streamConsumeController.emit(A.CaptureFirstAudioFrame),s.audio=a)}),t.appendChild(i)}startPreview(){if(ye.log("startPreview"),!this._previewElement){ye.warn("preview element not found");return}this._isPreviewing||this.start();const e=this._composedStream.audioTrack,t=this._composedStream.videoTrack;e&&(this._appendTrack(this._previewElement,e),this._removeTrack(this._previewElement,null)),t&&(this._appendTrack(this._previewElement,t),this._removeTrack(this._previewElement,null)),this._previewElement.play().catch(i=>{this._streamConsumeController.emit(A.NotAllowedAutoPlay)}),this._isPreviewing=!0}stopPreview(){this._isPreviewing=!1;const e=this._composedStream.audioTrack,t=this._composedStream.videoTrack;e&&this._removeTrack(this._previewElement,e),t&&this._removeTrack(this._previewElement,t),this.stop()}destroy(){this.stopPreview(),this._previewElement=null,this.unbindComposedStreamEvent()}_appendTrack(e,t){if(!e||!t)return;const i=e.srcObject||new MediaStream;i.getTracks().find(s=>s.id===t.id)||(t.kind==="audio"&&i.getTracks().forEach(s=>{s.kind==="audio"&&(ye.log(`remove preview track, ${s.label}, readyState=${s.readyState}`),i.removeTrack(s))}),t.kind==="video"&&i.getTracks().forEach(s=>{s.kind==="video"&&(i.removeTrack(s),ye.log(`remove preview track, ${s.label}, readyState=${s.readyState}`))}),i.addTrack(t),e.srcObject?e.load():e.srcObject=i)}_removeTrack(e,t){if(!e)return;const i=e.srcObject;i&&(i.getTracks().forEach(s=>{(s.id===(t==null?void 0:t.id)||s.readyState==="ended")&&(ye.log(`remove preview track ${s.label}`),i.removeTrack(s))}),i.getTracks().length===0&&(e.srcObject=null,ye.log("set srcObject null")))}getPreviewElement(){if(this.isPreviewing)return this._previewElement}get isPreviewing(){return this._isPreviewing}}var B={},Lt={},Ft={exports:{}},Ei;function Nt(){if(Ei)return Ft.exports;Ei=1;var r=Ft.exports={v:[{name:"version",reg:/^(\d*)$/}],o:[{name:"origin",reg:/^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,names:["username","sessionId","sessionVersion","netType","ipVer","address"],format:"%s %s %d %s IP%d %s"}],s:[{name:"name"}],i:[{name:"description"}],u:[{name:"uri"}],e:[{name:"email"}],p:[{name:"phone"}],z:[{name:"timezones"}],r:[{name:"repeats"}],t:[{name:"timing",reg:/^(\d*) (\d*)/,names:["start","stop"],format:"%d %d"}],c:[{name:"connection",reg:/^IN IP(\d) (\S*)/,names:["version","ip"],format:"IN IP%d %s"}],b:[{push:"bandwidth",reg:/^(TIAS|AS|CT|RR|RS):(\d*)/,names:["type","limit"],format:"%s:%s"}],m:[{reg:/^(\w*) (\d*) ([\w/]*)(?: (.*))?/,names:["type","port","protocol","payloads"],format:"%s %d %s %s"}],a:[{push:"rtp",reg:/^rtpmap:(\d*) ([\w\-.]*)(?:\s*\/(\d*)(?:\s*\/(\S*))?)?/,names:["payload","codec","rate","encoding"],format:function(e){return e.encoding?"rtpmap:%d %s/%s/%s":e.rate?"rtpmap:%d %s/%s":"rtpmap:%d %s"}},{push:"fmtp",reg:/^fmtp:(\d*) ([\S| ]*)/,names:["payload","config"],format:"fmtp:%d %s"},{name:"control",reg:/^control:(.*)/,format:"control:%s"},{name:"rtcp",reg:/^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,names:["port","netType","ipVer","address"],format:function(e){return e.address!=null?"rtcp:%d %s IP%d %s":"rtcp:%d"}},{push:"rtcpFbTrrInt",reg:/^rtcp-fb:(\*|\d*) trr-int (\d*)/,names:["payload","value"],format:"rtcp-fb:%s trr-int %d"},{push:"rtcpFb",reg:/^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,names:["payload","type","subtype"],format:function(e){return e.subtype!=null?"rtcp-fb:%s %s %s":"rtcp-fb:%s %s"}},{push:"ext",reg:/^extmap:(\d+)(?:\/(\w+))?(?: (urn:ietf:params:rtp-hdrext:encrypt))? (\S*)(?: (\S*))?/,names:["value","direction","encrypt-uri","uri","config"],format:function(e){return"extmap:%d"+(e.direction?"/%s":"%v")+(e["encrypt-uri"]?" %s":"%v")+" %s"+(e.config?" %s":"")}},{name:"extmapAllowMixed",reg:/^(extmap-allow-mixed)/},{push:"crypto",reg:/^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,names:["id","suite","config","sessionConfig"],format:function(e){return e.sessionConfig!=null?"crypto:%d %s %s %s":"crypto:%d %s %s"}},{name:"setup",reg:/^setup:(\w*)/,format:"setup:%s"},{name:"connectionType",reg:/^connection:(new|existing)/,format:"connection:%s"},{name:"mid",reg:/^mid:([^\s]*)/,format:"mid:%s"},{name:"msid",reg:/^msid:(.*)/,format:"msid:%s"},{name:"ptime",reg:/^ptime:(\d*(?:\.\d*)*)/,format:"ptime:%d"},{name:"maxptime",reg:/^maxptime:(\d*(?:\.\d*)*)/,format:"maxptime:%d"},{name:"direction",reg:/^(sendrecv|recvonly|sendonly|inactive)/},{name:"icelite",reg:/^(ice-lite)/},{name:"iceUfrag",reg:/^ice-ufrag:(\S*)/,format:"ice-ufrag:%s"},{name:"icePwd",reg:/^ice-pwd:(\S*)/,format:"ice-pwd:%s"},{name:"fingerprint",reg:/^fingerprint:(\S*) (\S*)/,names:["type","hash"],format:"fingerprint:%s %s"},{push:"candidates",reg:/^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: tcptype (\S*))?(?: generation (\d*))?(?: network-id (\d*))?(?: network-cost (\d*))?/,names:["foundation","component","transport","priority","ip","port","type","raddr","rport","tcptype","generation","network-id","network-cost"],format:function(e){var t="candidate:%s %d %s %d %s %d typ %s";return t+=e.raddr!=null?" raddr %s rport %d":"%v%v",t+=e.tcptype!=null?" tcptype %s":"%v",e.generation!=null&&(t+=" generation %d"),t+=e["network-id"]!=null?" network-id %d":"%v",t+=e["network-cost"]!=null?" network-cost %d":"%v",t}},{name:"endOfCandidates",reg:/^(end-of-candidates)/},{name:"remoteCandidates",reg:/^remote-candidates:(.*)/,format:"remote-candidates:%s"},{name:"iceOptions",reg:/^ice-options:(\S*)/,format:"ice-options:%s"},{push:"ssrcs",reg:/^ssrc:(\d*) ([\w_-]*)(?::(.*))?/,names:["id","attribute","value"],format:function(e){var t="ssrc:%d";return e.attribute!=null&&(t+=" %s",e.value!=null&&(t+=":%s")),t}},{push:"ssrcGroups",reg:/^ssrc-group:([\x21\x23\x24\x25\x26\x27\x2A\x2B\x2D\x2E\w]*) (.*)/,names:["semantics","ssrcs"],format:"ssrc-group:%s %s"},{name:"msidSemantic",reg:/^msid-semantic:\s?(\w*) (\S*)/,names:["semantic","token"],format:"msid-semantic: %s %s"},{push:"groups",reg:/^group:(\w*) (.*)/,names:["type","mids"],format:"group:%s %s"},{name:"rtcpMux",reg:/^(rtcp-mux)/},{name:"rtcpRsize",reg:/^(rtcp-rsize)/},{name:"sctpmap",reg:/^sctpmap:([\w_/]*) (\S*)(?: (\S*))?/,names:["sctpmapNumber","app","maxMessageSize"],format:function(e){return e.maxMessageSize!=null?"sctpmap:%s %s %s":"sctpmap:%s %s"}},{name:"xGoogleFlag",reg:/^x-google-flag:([^\s]*)/,format:"x-google-flag:%s"},{push:"rids",reg:/^rid:([\d\w]+) (\w+)(?: ([\S| ]*))?/,names:["id","direction","params"],format:function(e){return e.params?"rid:%s %s %s":"rid:%s %s"}},{push:"imageattrs",reg:new RegExp("^imageattr:(\\d+|\\*)[\\s\\t]+(send|recv)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*)(?:[\\s\\t]+(recv|send)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*))?"),names:["pt","dir1","attrs1","dir2","attrs2"],format:function(e){return"imageattr:%s %s %s"+(e.dir2?" %s %s":"")}},{name:"simulcast",reg:new RegExp("^simulcast:(send|recv) ([a-zA-Z0-9\\-_~;,]+)(?:\\s?(send|recv) ([a-zA-Z0-9\\-_~;,]+))?$"),names:["dir1","list1","dir2","list2"],format:function(e){return"simulcast:%s %s"+(e.dir2?" %s %s":"")}},{name:"simulcast_03",reg:/^simulcast:[\s\t]+([\S+\s\t]+)$/,names:["value"],format:"simulcast: %s"},{name:"framerate",reg:/^framerate:(\d+(?:$|\.\d+))/,format:"framerate:%s"},{name:"sourceFilter",reg:/^source-filter: *(excl|incl) (\S*) (IP4|IP6|\*) (\S*) (.*)/,names:["filterMode","netType","addressTypes","destAddress","srcList"],format:"source-filter: %s %s %s %s %s"},{name:"bundleOnly",reg:/^(bundle-only)/},{name:"label",reg:/^label:(.+)/,format:"label:%s"},{name:"sctpPort",reg:/^sctp-port:(\d+)$/,format:"sctp-port:%s"},{name:"maxMessageSize",reg:/^max-message-size:(\d+)$/,format:"max-message-size:%s"},{push:"tsRefClocks",reg:/^ts-refclk:([^\s=]*)(?:=(\S*))?/,names:["clksrc","clksrcExt"],format:function(e){return"ts-refclk:%s"+(e.clksrcExt!=null?"=%s":"")}},{name:"mediaClk",reg:/^mediaclk:(?:id=(\S*))? *([^\s=]*)(?:=(\S*))?(?: *rate=(\d+)\/(\d+))?/,names:["id","mediaClockName","mediaClockValue","rateNumerator","rateDenominator"],format:function(e){var t="mediaclk:";return t+=e.id!=null?"id=%s %s":"%v%s",t+=e.mediaClockValue!=null?"=%s":"",t+=e.rateNumerator!=null?" rate=%s":"",t+=e.rateDenominator!=null?"/%s":"",t}},{name:"keywords",reg:/^keywds:(.+)$/,format:"keywds:%s"},{name:"content",reg:/^content:(.+)/,format:"content:%s"},{name:"bfcpFloorCtrl",reg:/^floorctrl:(c-only|s-only|c-s)/,format:"floorctrl:%s"},{name:"bfcpConfId",reg:/^confid:(\d+)/,format:"confid:%s"},{name:"bfcpUserId",reg:/^userid:(\d+)/,format:"userid:%s"},{name:"bfcpFloorId",reg:/^floorid:(.+) (?:m-stream|mstrm):(.+)/,names:["id","mStream"],format:"floorid:%s mstrm:%s"},{push:"invalid",names:["value"]}]};return Object.keys(r).forEach(function(e){var t=r[e];t.forEach(function(i){i.reg||(i.reg=/(.*)/),i.format||(i.format="%s")})}),Ft.exports}var bi;function Pu(){return bi||(bi=1,function(r){var e=function(o){return String(Number(o))===o?Number(o):o},t=function(o,u,d,c){if(c&&!d)u[c]=e(o[1]);else for(var h=0;h<d.length;h+=1)o[h+1]!=null&&(u[d[h]]=e(o[h+1]))},i=function(o,u,d){var c=o.name&&o.names;o.push&&!u[o.push]?u[o.push]=[]:c&&!u[o.name]&&(u[o.name]={});var h=o.push?{}:c?u[o.name]:u;t(d.match(o.reg),h,o.names,o.name),o.push&&u[o.push].push(h)},s=Nt(),n=RegExp.prototype.test.bind(/^([a-z])=(.*)/);r.parse=function(o){var u={},d=[],c=u;return o.split(/(\r\n|\r|\n)/).filter(n).forEach(function(h){var p=h[0],l=h.slice(2);p==="m"&&(d.push({rtp:[],fmtp:[]}),c=d[d.length-1]);for(var f=0;f<(s[p]||[]).length;f+=1){var g=s[p][f];if(g.reg.test(l))return i(g,c,l)}}),u.media=d,u};var a=function(o,u){var d=u.split(/=(.+)/,2);return d.length===2?o[d[0]]=e(d[1]):d.length===1&&u.length>1&&(o[d[0]]=void 0),o};r.parseParams=function(o){return o.split(/;\s?/).reduce(a,{})},r.parseFmtpConfig=r.parseParams,r.parsePayloads=function(o){return o.toString().split(" ").map(Number)},r.parseRemoteCandidates=function(o){for(var u=[],d=o.split(" ").map(e),c=0;c<d.length;c+=3)u.push({component:d[c],ip:d[c+1],port:d[c+2]});return u},r.parseImageAttributes=function(o){return o.split(" ").map(function(u){return u.substring(1,u.length-1).split(",").reduce(a,{})})},r.parseSimulcastStreamList=function(o){return o.split(";").map(function(u){return u.split(",").map(function(d){var c,h=!1;return d[0]!=="~"?c=e(d):(c=e(d.substring(1,d.length)),h=!0),{scid:c,paused:h}})})}}(Lt)),Lt}var Vt,ki;function xu(){if(ki)return Vt;ki=1;var r=Nt(),e=/%[sdv%]/g,t=function(a){var o=1,u=arguments,d=u.length;return a.replace(e,function(c){if(o>=d)return c;var h=u[o];switch(o+=1,c){case"%%":return"%";case"%s":return String(h);case"%d":return Number(h);case"%v":return""}})},i=function(a,o,u){var d=o.format instanceof Function?o.format(o.push?u:u[o.name]):o.format,c=[a+"="+d];if(o.names)for(var h=0;h<o.names.length;h+=1){var p=o.names[h];o.name?c.push(u[o.name][p]):c.push(u[o.names[h]])}else c.push(u[o.name]);return t.apply(null,c)},s=["v","o","s","i","u","e","p","c","b","t","r","z","a"],n=["i","c","b","a"];return Vt=function(a,o){o=o||{},a.version==null&&(a.version=0),a.name==null&&(a.name=" "),a.media.forEach(function(h){h.payloads==null&&(h.payloads="")});var u=o.outerOrder||s,d=o.innerOrder||n,c=[];return u.forEach(function(h){r[h].forEach(function(p){p.name in a&&a[p.name]!=null?c.push(i(h,p,a)):p.push in a&&a[p.push]!=null&&a[p.push].forEach(function(l){c.push(i(h,p,l))})})}),a.media.forEach(function(h){c.push(i("m",r.m[0],h)),d.forEach(function(p){r[p].forEach(function(l){l.name in h&&h[l.name]!=null?c.push(i(p,l,h)):l.push in h&&h[l.push]!=null&&h[l.push].forEach(function(f){c.push(i(p,l,f))})})})}),c.join(`\r
56
+ `,Nd=URL.createObjectURL(new Blob([Gd],{type:"application/javascript"}));class Bd{constructor(){this._audioCtx=null,this._volume=0}get volume(){return this._volume}async start(e,t){if(this._audioCtx)return;const r=new AudioContext;await r.audioWorklet.addModule(t||Nd);const n=new MediaStream;n.addTrack(e);const s=r.createMediaStreamSource(n),a=new AudioWorkletNode(r,"vumeter");a.port.onmessage=o=>{const d=o.data.volume||0;this._volume=Math.min(d*100/2,10)},s.connect(a).connect(r.destination),this._audioCtx=r}stop(){var e;(e=this._audioCtx)==null||e.close(),this._audioCtx=null}}class ht{constructor(){this._userId=void 0,this._deviceId=void 0,this._volumeDetectScriptUrl=void 0}static get instance(){return this._instance||(this._instance=new ht),this._instance}get userId(){return this._userId}set userId(e){this._userId=e}get deviceId(){return this._deviceId}set deviceId(e){this._deviceId=e}get volumeDetectScriptUrl(){return this._volumeDetectScriptUrl}set volumeDetectScriptUrl(e){this._volumeDetectScriptUrl=e}}class js extends Je{constructor(e){super(),this._width=0,this._height=0,this._mediaStream=null,this._nextStream=null,this._trackMap={},this.type=e.type,this.id=Ud(),this._source=e.stream}get source(){return this._source}get videoTrack(){return this._trackMap.video}get audioTrack(){return this._trackMap.audio}get width(){return this._width}get height(){return this._height}get isVideoStream(){return[V.Camera,V.Screen,V.VideoFile].includes(this.type)}get mediaStream(){if(this._mediaStream)return this._mediaStream;const e=new MediaStream;return this._trackMap.audio&&e.addTrack(this._trackMap.audio),this._trackMap.video&&e.addTrack(this._trackMap.video),this._mediaStream=e,e}async startVolumeDetect(){this.audioTrack&&(this._volumeDetector||(this._volumeDetector=new Bd),await this._volumeDetector.start(this.audioTrack,ht.instance.volumeDetectScriptUrl))}stopVolumeDetect(){var e;(e=this._volumeDetector)==null||e.stop(),this._volumeDetector=null}get volume(){var e;return((e=this._volumeDetector)==null?void 0:e.volume)||0}}class Ct extends js{constructor(){super(...arguments),this._frameRate=1}get isVideoStream(){return!0}get isAudioStream(){return!1}get frameRate(){return this._frameRate}bindTrackSizeChangeEvent(e){e.on(ce.SIZE_CHANGE,({width:t,height:r})=>{this._width=t,this._height=r,this.emit(ms.SizeChange,{width:t,height:r})})}}class Gi extends js{get isVideoStream(){return!1}get isAudioStream(){return!0}}class Vd extends Ct{constructor(e,t){super({type:V.Camera,stream:e}),this._trackMap.video=e.track(),this._width=e.width(),this._height=e.height(),this._frameRate=(t==null?void 0:t.frameRate)??1,this.bindTrackSizeChangeEvent(e)}get source(){return this._source}get viewNode(){return this.source.node()}get mixerNode(){return null}bindTrackEnd(e){this.source.on(ce.ENDED,e)}destroy(){this.source.destroy()}}var Hs=typeof global=="object"&&global&&global.Object===Object&&global,Fd=typeof self=="object"&&self&&self.Object===Object&&self,Ue=Hs||Fd||Function("return this")(),Ze=Ue.Symbol,$s=Object.prototype,jd=$s.hasOwnProperty,Hd=$s.toString,Wt=Ze?Ze.toStringTag:void 0;function $d(i){var e=jd.call(i,Wt),t=i[Wt];try{i[Wt]=void 0;var r=!0}catch{}var n=Hd.call(i);return r&&(e?i[Wt]=t:delete i[Wt]),n}var qd=Object.prototype,Kd=qd.toString;function Wd(i){return Kd.call(i)}var Jd="[object Null]",Xd="[object Undefined]",qs=Ze?Ze.toStringTag:void 0;function kt(i){return i==null?i===void 0?Xd:Jd:qs&&qs in Object(i)?$d(i):Wd(i)}function Tt(i){return i!=null&&typeof i=="object"}var Zd="[object Symbol]";function Ni(i){return typeof i=="symbol"||Tt(i)&&kt(i)==Zd}function Ks(i,e){for(var t=-1,r=i==null?0:i.length,n=Array(r);++t<r;)n[t]=e(i[t],t,i);return n}var ee=Array.isArray,Ws=Ze?Ze.prototype:void 0,Js=Ws?Ws.toString:void 0;function Xs(i){if(typeof i=="string")return i;if(ee(i))return Ks(i,Xs)+"";if(Ni(i))return Js?Js.call(i):"";var e=i+"";return e=="0"&&1/i==-1/0?"-0":e}var Qd=/\s/;function Yd(i){for(var e=i.length;e--&&Qd.test(i.charAt(e)););return e}var eh=/^\s+/;function th(i){return i&&i.slice(0,Yd(i)+1).replace(eh,"")}function Jt(i){var e=typeof i;return i!=null&&(e=="object"||e=="function")}var Zs=NaN,ih=/^[-+]0x[0-9a-f]+$/i,rh=/^0b[01]+$/i,nh=/^0o[0-7]+$/i,sh=parseInt;function oh(i){if(typeof i=="number")return i;if(Ni(i))return Zs;if(Jt(i)){var e=typeof i.valueOf=="function"?i.valueOf():i;i=Jt(e)?e+"":e}if(typeof i!="string")return i===0?i:+i;i=th(i);var t=rh.test(i);return t||nh.test(i)?sh(i.slice(2),t?2:8):ih.test(i)?Zs:+i}var ah=1/0,ch=17976931348623157e292;function uh(i){if(!i)return i===0?i:0;if(i=oh(i),i===ah||i===-1/0){var e=i<0?-1:1;return e*ch}return i===i?i:0}function dh(i){var e=uh(i),t=e%1;return e===e?t?e-t:e:0}function hh(i){return i}var lh="[object AsyncFunction]",ph="[object Function]",fh="[object GeneratorFunction]",mh="[object Proxy]";function Qs(i){if(!Jt(i))return!1;var e=kt(i);return e==ph||e==fh||e==lh||e==mh}var Pr=Ue["__core-js_shared__"],Ys=function(){var i=/[^.]+$/.exec(Pr&&Pr.keys&&Pr.keys.IE_PROTO||"");return i?"Symbol(src)_1."+i:""}();function _h(i){return!!Ys&&Ys in i}var gh=Function.prototype,vh=gh.toString;function lt(i){if(i!=null){try{return vh.call(i)}catch{}try{return i+""}catch{}}return""}var yh=/[\\^$.*+?()[\]{}|]/g,bh=/^\[object .+?Constructor\]$/,Sh=Function.prototype,Eh=Object.prototype,wh=Sh.toString,Ch=Eh.hasOwnProperty,kh=RegExp("^"+wh.call(Ch).replace(yh,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function Th(i){if(!Jt(i)||_h(i))return!1;var e=Qs(i)?kh:bh;return e.test(lt(i))}function zh(i,e){return i==null?void 0:i[e]}function zt(i,e){var t=zh(i,e);return Th(t)?t:void 0}var Lr=zt(Ue,"WeakMap");function Ah(i,e,t,r){for(var n=i.length,s=t+-1;++s<n;)if(e(i[s],s,i))return s;return-1}var Rh=9007199254740991,Dh=/^(?:0|[1-9]\d*)$/;function eo(i,e){var t=typeof i;return e=e??Rh,!!e&&(t=="number"||t!="symbol"&&Dh.test(i))&&i>-1&&i%1==0&&i<e}function to(i,e){return i===e||i!==i&&e!==e}var xh=9007199254740991;function Ur(i){return typeof i=="number"&&i>-1&&i%1==0&&i<=xh}function Bi(i){return i!=null&&Ur(i.length)&&!Qs(i)}var Ih=Object.prototype;function io(i){var e=i&&i.constructor,t=typeof e=="function"&&e.prototype||Ih;return i===t}function Oh(i,e){for(var t=-1,r=Array(i);++t<i;)r[t]=e(t);return r}var Mh="[object Arguments]";function ro(i){return Tt(i)&&kt(i)==Mh}var no=Object.prototype,Ph=no.hasOwnProperty,Lh=no.propertyIsEnumerable,Gr=ro(function(){return arguments}())?ro:function(i){return Tt(i)&&Ph.call(i,"callee")&&!Lh.call(i,"callee")};function Uh(){return!1}var so=typeof exports=="object"&&exports&&!exports.nodeType&&exports,oo=so&&typeof module=="object"&&module&&!module.nodeType&&module,Gh=oo&&oo.exports===so,ao=Gh?Ue.Buffer:void 0,Nh=ao?ao.isBuffer:void 0,Vi=Nh||Uh,Bh="[object Arguments]",Vh="[object Array]",Fh="[object Boolean]",jh="[object Date]",Hh="[object Error]",$h="[object Function]",qh="[object Map]",Kh="[object Number]",Wh="[object Object]",Jh="[object RegExp]",Xh="[object Set]",Zh="[object String]",Qh="[object WeakMap]",Yh="[object ArrayBuffer]",el="[object DataView]",tl="[object Float32Array]",il="[object Float64Array]",rl="[object Int8Array]",nl="[object Int16Array]",sl="[object Int32Array]",ol="[object Uint8Array]",al="[object Uint8ClampedArray]",cl="[object Uint16Array]",ul="[object Uint32Array]",$={};$[tl]=$[il]=$[rl]=$[nl]=$[sl]=$[ol]=$[al]=$[cl]=$[ul]=!0,$[Bh]=$[Vh]=$[Yh]=$[Fh]=$[el]=$[jh]=$[Hh]=$[$h]=$[qh]=$[Kh]=$[Wh]=$[Jh]=$[Xh]=$[Zh]=$[Qh]=!1;function dl(i){return Tt(i)&&Ur(i.length)&&!!$[kt(i)]}function hl(i){return function(e){return i(e)}}var co=typeof exports=="object"&&exports&&!exports.nodeType&&exports,Xt=co&&typeof module=="object"&&module&&!module.nodeType&&module,ll=Xt&&Xt.exports===co,Nr=ll&&Hs.process,uo=function(){try{var i=Xt&&Xt.require&&Xt.require("util").types;return i||Nr&&Nr.binding&&Nr.binding("util")}catch{}}(),ho=uo&&uo.isTypedArray,Br=ho?hl(ho):dl,pl=Object.prototype,fl=pl.hasOwnProperty;function ml(i,e){var t=ee(i),r=!t&&Gr(i),n=!t&&!r&&Vi(i),s=!t&&!r&&!n&&Br(i),a=t||r||n||s,o=a?Oh(i.length,String):[],d=o.length;for(var c in i)fl.call(i,c)&&!(a&&(c=="length"||n&&(c=="offset"||c=="parent")||s&&(c=="buffer"||c=="byteLength"||c=="byteOffset")||eo(c,d)))&&o.push(c);return o}function _l(i,e){return function(t){return i(e(t))}}var gl=_l(Object.keys,Object),vl=Object.prototype,yl=vl.hasOwnProperty;function lo(i){if(!io(i))return gl(i);var e=[];for(var t in Object(i))yl.call(i,t)&&t!="constructor"&&e.push(t);return e}function Zt(i){return Bi(i)?ml(i):lo(i)}var bl=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,Sl=/^\w*$/;function Vr(i,e){if(ee(i))return!1;var t=typeof i;return t=="number"||t=="symbol"||t=="boolean"||i==null||Ni(i)?!0:Sl.test(i)||!bl.test(i)||e!=null&&i in Object(e)}var Qt=zt(Object,"create");function El(){this.__data__=Qt?Qt(null):{},this.size=0}function wl(i){var e=this.has(i)&&delete this.__data__[i];return this.size-=e?1:0,e}var Cl="__lodash_hash_undefined__",kl=Object.prototype,Tl=kl.hasOwnProperty;function zl(i){var e=this.__data__;if(Qt){var t=e[i];return t===Cl?void 0:t}return Tl.call(e,i)?e[i]:void 0}var Al=Object.prototype,Rl=Al.hasOwnProperty;function Dl(i){var e=this.__data__;return Qt?e[i]!==void 0:Rl.call(e,i)}var xl="__lodash_hash_undefined__";function Il(i,e){var t=this.__data__;return this.size+=this.has(i)?0:1,t[i]=Qt&&e===void 0?xl:e,this}function pt(i){var e=-1,t=i==null?0:i.length;for(this.clear();++e<t;){var r=i[e];this.set(r[0],r[1])}}pt.prototype.clear=El,pt.prototype.delete=wl,pt.prototype.get=zl,pt.prototype.has=Dl,pt.prototype.set=Il;function Ol(){this.__data__=[],this.size=0}function Fi(i,e){for(var t=i.length;t--;)if(to(i[t][0],e))return t;return-1}var Ml=Array.prototype,Pl=Ml.splice;function Ll(i){var e=this.__data__,t=Fi(e,i);if(t<0)return!1;var r=e.length-1;return t==r?e.pop():Pl.call(e,t,1),--this.size,!0}function Ul(i){var e=this.__data__,t=Fi(e,i);return t<0?void 0:e[t][1]}function Gl(i){return Fi(this.__data__,i)>-1}function Nl(i,e){var t=this.__data__,r=Fi(t,i);return r<0?(++this.size,t.push([i,e])):t[r][1]=e,this}function Ge(i){var e=-1,t=i==null?0:i.length;for(this.clear();++e<t;){var r=i[e];this.set(r[0],r[1])}}Ge.prototype.clear=Ol,Ge.prototype.delete=Ll,Ge.prototype.get=Ul,Ge.prototype.has=Gl,Ge.prototype.set=Nl;var Yt=zt(Ue,"Map");function Bl(){this.size=0,this.__data__={hash:new pt,map:new(Yt||Ge),string:new pt}}function Vl(i){var e=typeof i;return e=="string"||e=="number"||e=="symbol"||e=="boolean"?i!=="__proto__":i===null}function ji(i,e){var t=i.__data__;return Vl(e)?t[typeof e=="string"?"string":"hash"]:t.map}function Fl(i){var e=ji(this,i).delete(i);return this.size-=e?1:0,e}function jl(i){return ji(this,i).get(i)}function Hl(i){return ji(this,i).has(i)}function $l(i,e){var t=ji(this,i),r=t.size;return t.set(i,e),this.size+=t.size==r?0:1,this}function Ne(i){var e=-1,t=i==null?0:i.length;for(this.clear();++e<t;){var r=i[e];this.set(r[0],r[1])}}Ne.prototype.clear=Bl,Ne.prototype.delete=Fl,Ne.prototype.get=jl,Ne.prototype.has=Hl,Ne.prototype.set=$l;var ql="Expected a function";function Fr(i,e){if(typeof i!="function"||e!=null&&typeof e!="function")throw new TypeError(ql);var t=function(){var r=arguments,n=e?e.apply(this,r):r[0],s=t.cache;if(s.has(n))return s.get(n);var a=i.apply(this,r);return t.cache=s.set(n,a)||s,a};return t.cache=new(Fr.Cache||Ne),t}Fr.Cache=Ne;var Kl=500;function Wl(i){var e=Fr(i,function(r){return t.size===Kl&&t.clear(),r}),t=e.cache;return e}var Jl=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,Xl=/\\(\\)?/g,Zl=Wl(function(i){var e=[];return i.charCodeAt(0)===46&&e.push(""),i.replace(Jl,function(t,r,n,s){e.push(n?s.replace(Xl,"$1"):r||t)}),e});function Ql(i){return i==null?"":Xs(i)}function po(i,e){return ee(i)?i:Vr(i,e)?[i]:Zl(Ql(i))}function Hi(i){if(typeof i=="string"||Ni(i))return i;var e=i+"";return e=="0"&&1/i==-1/0?"-0":e}function fo(i,e){e=po(e,i);for(var t=0,r=e.length;i!=null&&t<r;)i=i[Hi(e[t++])];return t&&t==r?i:void 0}function Yl(i,e,t){var r=i==null?void 0:fo(i,e);return r===void 0?t:r}function ep(i,e){for(var t=-1,r=e.length,n=i.length;++t<r;)i[n+t]=e[t];return i}function tp(){this.__data__=new Ge,this.size=0}function ip(i){var e=this.__data__,t=e.delete(i);return this.size=e.size,t}function rp(i){return this.__data__.get(i)}function np(i){return this.__data__.has(i)}var sp=200;function op(i,e){var t=this.__data__;if(t instanceof Ge){var r=t.__data__;if(!Yt||r.length<sp-1)return r.push([i,e]),this.size=++t.size,this;t=this.__data__=new Ne(r)}return t.set(i,e),this.size=t.size,this}function Be(i){var e=this.__data__=new Ge(i);this.size=e.size}Be.prototype.clear=tp,Be.prototype.delete=ip,Be.prototype.get=rp,Be.prototype.has=np,Be.prototype.set=op;function mo(i,e){for(var t=-1,r=i==null?0:i.length,n=0,s=[];++t<r;){var a=i[t];e(a,t,i)&&(s[n++]=a)}return s}function ap(){return[]}var cp=Object.prototype,up=cp.propertyIsEnumerable,_o=Object.getOwnPropertySymbols,dp=_o?function(i){return i==null?[]:(i=Object(i),mo(_o(i),function(e){return up.call(i,e)}))}:ap;function hp(i,e,t){var r=e(i);return ee(i)?r:ep(r,t(i))}function go(i){return hp(i,Zt,dp)}var jr=zt(Ue,"DataView"),Hr=zt(Ue,"Promise"),$r=zt(Ue,"Set"),vo="[object Map]",lp="[object Object]",yo="[object Promise]",bo="[object Set]",So="[object WeakMap]",Eo="[object DataView]",pp=lt(jr),fp=lt(Yt),mp=lt(Hr),_p=lt($r),gp=lt(Lr),Ve=kt;(jr&&Ve(new jr(new ArrayBuffer(1)))!=Eo||Yt&&Ve(new Yt)!=vo||Hr&&Ve(Hr.resolve())!=yo||$r&&Ve(new $r)!=bo||Lr&&Ve(new Lr)!=So)&&(Ve=function(i){var e=kt(i),t=e==lp?i.constructor:void 0,r=t?lt(t):"";if(r)switch(r){case pp:return Eo;case fp:return vo;case mp:return yo;case _p:return bo;case gp:return So}return e});var wo=Ue.Uint8Array,vp="__lodash_hash_undefined__";function yp(i){return this.__data__.set(i,vp),this}function bp(i){return this.__data__.has(i)}function $i(i){var e=-1,t=i==null?0:i.length;for(this.__data__=new Ne;++e<t;)this.add(i[e])}$i.prototype.add=$i.prototype.push=yp,$i.prototype.has=bp;function Sp(i,e){for(var t=-1,r=i==null?0:i.length;++t<r;)if(e(i[t],t,i))return!0;return!1}function Ep(i,e){return i.has(e)}var wp=1,Cp=2;function Co(i,e,t,r,n,s){var a=t&wp,o=i.length,d=e.length;if(o!=d&&!(a&&d>o))return!1;var c=s.get(i),u=s.get(e);if(c&&u)return c==e&&u==i;var l=-1,h=!0,p=t&Cp?new $i:void 0;for(s.set(i,e),s.set(e,i);++l<o;){var f=i[l],v=e[l];if(r)var m=a?r(v,f,l,e,i,s):r(f,v,l,i,e,s);if(m!==void 0){if(m)continue;h=!1;break}if(p){if(!Sp(e,function(b,y){if(!Ep(p,y)&&(f===b||n(f,b,t,r,s)))return p.push(y)})){h=!1;break}}else if(!(f===v||n(f,v,t,r,s))){h=!1;break}}return s.delete(i),s.delete(e),h}function kp(i){var e=-1,t=Array(i.size);return i.forEach(function(r,n){t[++e]=[n,r]}),t}function Tp(i){var e=-1,t=Array(i.size);return i.forEach(function(r){t[++e]=r}),t}var zp=1,Ap=2,Rp="[object Boolean]",Dp="[object Date]",xp="[object Error]",Ip="[object Map]",Op="[object Number]",Mp="[object RegExp]",Pp="[object Set]",Lp="[object String]",Up="[object Symbol]",Gp="[object ArrayBuffer]",Np="[object DataView]",ko=Ze?Ze.prototype:void 0,qr=ko?ko.valueOf:void 0;function Bp(i,e,t,r,n,s,a){switch(t){case Np:if(i.byteLength!=e.byteLength||i.byteOffset!=e.byteOffset)return!1;i=i.buffer,e=e.buffer;case Gp:return!(i.byteLength!=e.byteLength||!s(new wo(i),new wo(e)));case Rp:case Dp:case Op:return to(+i,+e);case xp:return i.name==e.name&&i.message==e.message;case Mp:case Lp:return i==e+"";case Ip:var o=kp;case Pp:var d=r&zp;if(o||(o=Tp),i.size!=e.size&&!d)return!1;var c=a.get(i);if(c)return c==e;r|=Ap,a.set(i,e);var u=Co(o(i),o(e),r,n,s,a);return a.delete(i),u;case Up:if(qr)return qr.call(i)==qr.call(e)}return!1}var Vp=1,Fp=Object.prototype,jp=Fp.hasOwnProperty;function Hp(i,e,t,r,n,s){var a=t&Vp,o=go(i),d=o.length,c=go(e),u=c.length;if(d!=u&&!a)return!1;for(var l=d;l--;){var h=o[l];if(!(a?h in e:jp.call(e,h)))return!1}var p=s.get(i),f=s.get(e);if(p&&f)return p==e&&f==i;var v=!0;s.set(i,e),s.set(e,i);for(var m=a;++l<d;){h=o[l];var b=i[h],y=e[h];if(r)var _=a?r(y,b,h,e,i,s):r(b,y,h,i,e,s);if(!(_===void 0?b===y||n(b,y,t,r,s):_)){v=!1;break}m||(m=h=="constructor")}if(v&&!m){var E=i.constructor,z=e.constructor;E!=z&&"constructor"in i&&"constructor"in e&&!(typeof E=="function"&&E instanceof E&&typeof z=="function"&&z instanceof z)&&(v=!1)}return s.delete(i),s.delete(e),v}var $p=1,To="[object Arguments]",zo="[object Array]",qi="[object Object]",qp=Object.prototype,Ao=qp.hasOwnProperty;function Kp(i,e,t,r,n,s){var a=ee(i),o=ee(e),d=a?zo:Ve(i),c=o?zo:Ve(e);d=d==To?qi:d,c=c==To?qi:c;var u=d==qi,l=c==qi,h=d==c;if(h&&Vi(i)){if(!Vi(e))return!1;a=!0,u=!1}if(h&&!u)return s||(s=new Be),a||Br(i)?Co(i,e,t,r,n,s):Bp(i,e,d,t,r,n,s);if(!(t&$p)){var p=u&&Ao.call(i,"__wrapped__"),f=l&&Ao.call(e,"__wrapped__");if(p||f){var v=p?i.value():i,m=f?e.value():e;return s||(s=new Be),n(v,m,t,r,s)}}return h?(s||(s=new Be),Hp(i,e,t,r,n,s)):!1}function Kr(i,e,t,r,n){return i===e?!0:i==null||e==null||!Tt(i)&&!Tt(e)?i!==i&&e!==e:Kp(i,e,t,r,Kr,n)}var Wp=1,Jp=2;function Xp(i,e,t,r){var n=t.length,s=n;if(i==null)return!s;for(i=Object(i);n--;){var a=t[n];if(a[2]?a[1]!==i[a[0]]:!(a[0]in i))return!1}for(;++n<s;){a=t[n];var o=a[0],d=i[o],c=a[1];if(a[2]){if(d===void 0&&!(o in i))return!1}else{var u=new Be,l;if(!(l===void 0?Kr(c,d,Wp|Jp,r,u):l))return!1}}return!0}function Ro(i){return i===i&&!Jt(i)}function Zp(i){for(var e=Zt(i),t=e.length;t--;){var r=e[t],n=i[r];e[t]=[r,n,Ro(n)]}return e}function Do(i,e){return function(t){return t==null?!1:t[i]===e&&(e!==void 0||i in Object(t))}}function Qp(i){var e=Zp(i);return e.length==1&&e[0][2]?Do(e[0][0],e[0][1]):function(t){return t===i||Xp(t,i,e)}}function Yp(i,e){return i!=null&&e in Object(i)}function ef(i,e,t){e=po(e,i);for(var r=-1,n=e.length,s=!1;++r<n;){var a=Hi(e[r]);if(!(s=i!=null&&t(i,a)))break;i=i[a]}return s||++r!=n?s:(n=i==null?0:i.length,!!n&&Ur(n)&&eo(a,n)&&(ee(i)||Gr(i)))}function tf(i,e){return i!=null&&ef(i,e,Yp)}var rf=1,nf=2;function sf(i,e){return Vr(i)&&Ro(e)?Do(Hi(i),e):function(t){var r=Yl(t,i);return r===void 0&&r===e?tf(t,i):Kr(e,r,rf|nf)}}function of(i){return function(e){return e==null?void 0:e[i]}}function af(i){return function(e){return fo(e,i)}}function cf(i){return Vr(i)?of(Hi(i)):af(i)}function Wr(i){return typeof i=="function"?i:i==null?hh:typeof i=="object"?ee(i)?sf(i[0],i[1]):Qp(i):cf(i)}function uf(i){return function(e,t,r){for(var n=-1,s=Object(e),a=r(e),o=a.length;o--;){var d=a[++n];if(t(s[d],d,s)===!1)break}return e}}var df=uf();function hf(i,e){return i&&df(i,e,Zt)}function lf(i,e){return function(t,r){if(t==null)return t;if(!Bi(t))return i(t,r);for(var n=t.length,s=-1,a=Object(t);++s<n&&r(a[s],s,a)!==!1;);return t}}var pf=lf(hf);function ff(i,e){var t=[];return pf(i,function(r,n,s){e(r,n,s)&&t.push(r)}),t}function xo(i,e){var t=ee(i)?mo:ff;return t(i,Wr(e))}function mf(i){return function(e,t,r){var n=Object(e);if(!Bi(e)){var s=Wr(t);e=Zt(e),t=function(o){return s(n[o],o,n)}}var a=i(e,t,r);return a>-1?n[s?e[a]:a]:void 0}}var _f=Math.max;function gf(i,e,t){var r=i==null?0:i.length;if(!r)return-1;var n=t==null?0:dh(t);return n<0&&(n=_f(r+n,0)),Ah(i,Wr(e),n)}var ei=mf(gf);function vf(i,e){return Ks(e,function(t){return i[t]})}function Fe(i){return i==null?[]:vf(i,Zt(i))}var yf="[object Map]",bf="[object Set]",Sf=Object.prototype,Ef=Sf.hasOwnProperty;function wf(i){if(i==null)return!0;if(Bi(i)&&(ee(i)||typeof i=="string"||typeof i.splice=="function"||Vi(i)||Br(i)||Gr(i)))return!i.length;var e=Ve(i);if(e==yf||e==bf)return!i.size;if(io(i))return!lo(i).length;for(var t in i)if(Ef.call(i,t))return!1;return!0}function Cf(i){return i==null}class kf extends Gi{constructor(e){super({type:V.Microphone,stream:e}),this._trackMap.audio=e.track()}get source(){return this._source}get mixerNode(){return this.source.node()}bindTrackEnd(e){this.source.on(ce.ENDED,e)}destroy(){this.source.destroy()}}class Tf extends Ct{constructor(e){super({type:V.VideoFile,stream:e});const t=ei(e,n=>n.kind===j.VIDEO),r=ei(e,n=>n.kind===j.AUDIO);this._videoStream=t,this._audioStream=r,this._trackMap.video=t==null?void 0:t.track(),this._trackMap.audio=r==null?void 0:r.track(),t&&(this._height=t==null?void 0:t.height(),this._width=t==null?void 0:t.width())}get viewNode(){var e;return((e=this._videoStream)==null?void 0:e.node())??null}get mixerNode(){var e;return((e=this._audioStream)==null?void 0:e.node())??null}bindTrackEnd(e){var t;(t=this._videoStream)==null||t.on(ce.ENDED,e)}destroy(){var e,t;(e=this._videoStream)==null||e.destroy(),(t=this._audioStream)==null||t.destroy(),delete this._trackMap.video,delete this._trackMap.audio}}class zf extends Ct{constructor(e,t){super({type:V.Screen,stream:e});const r=ei(e,s=>s.kind===j.VIDEO),n=ei(e,s=>s.kind===j.AUDIO);this._videoStream=r,this._audioStream=n,this._frameRate=(t==null?void 0:t.frameRate)??1,this._trackMap.video=r==null?void 0:r.track(),this._trackMap.audio=n==null?void 0:n.track(),r&&(this._height=r==null?void 0:r.height(),this._width=r==null?void 0:r.width(),this.bindTrackSizeChangeEvent(r))}get viewNode(){var e;return((e=this._videoStream)==null?void 0:e.node())??null}get mixerNode(){var e;return((e=this._audioStream)==null?void 0:e.node())??null}bindTrackEnd(e){var t;(t=this._videoStream)==null||t.on(ce.ENDED,e)}destroy(){var e,t;(e=this._videoStream)==null||e.destroy(),(t=this._audioStream)==null||t.destroy(),delete this._trackMap.video,delete this._trackMap.audio}}class Af extends Gi{constructor(e){super({type:V.AudioFile,stream:e});const t=ei(e,r=>r.kind===j.AUDIO);this._audioStream=t,this._trackMap.audio=t==null?void 0:t.track()}get mixerNode(){var e;return((e=this._audioStream)==null?void 0:e.node())??null}bindTrackEnd(e){var t;(t=this._audioStream)==null||t.on(ce.ENDED,e)}destroy(){var e;(e=this._audioStream)==null||e.destroy()}}class Rf extends Ct{constructor(e){super({type:V.Image,stream:e}),this._width=e.width(),this._height=e.height()}get source(){return this._source}get mixerNode(){return null}get viewNode(){return this.source.node()}bindTrackEnd(e){this.source.on(ce.ENDED,e)}destroy(){this.source.destroy()}}class Df extends Ct{constructor(e){super({type:V.CustomVideo,stream:e}),this._trackMap.video=e.track(),this._width=e.width(),this._height=e.height()}get source(){return this._source}get viewNode(){return this.source.node()}get mixerNode(){return null}bindTrackEnd(e){this.source.on(ce.ENDED,e)}destroy(){this.source.destroy()}}class xf extends Gi{constructor(e){super({type:V.CustomAudio,stream:e}),this._trackMap.audio=e==null?void 0:e.track()}get source(){return this._source}get mixerNode(){var e;return((e=this.source)==null?void 0:e.node())??null}bindTrackEnd(e){var t;(t=this._audioStream)==null||t.on(ce.ENDED,e)}destroy(){var e;(e=this._audioStream)==null||e.destroy()}}const If=["user","environment"],Of=18e4,Mf=1e4,Io=1e3,Pf=15;var me=(i=>(i[i.OPEN_CAMERA_FAILED=1001]="OPEN_CAMERA_FAILED",i[i.OPEN_MICROPHONE_FAILED=1002]="OPEN_MICROPHONE_FAILED",i[i.OPEN_SCREEN_FAILED=1003]="OPEN_SCREEN_FAILED",i[i.VIDEO_FILE_CAPTURE_FAILED=1004]="VIDEO_FILE_CAPTURE_FAILED",i[i.AUDIO_FILE_CAPTURE_FAILED=1005]="AUDIO_FILE_CAPTURE_FAILED",i[i.IMAGE_FILE_CAPTURE_FAILED=1006]="IMAGE_FILE_CAPTURE_FAILED",i[i.VOLUME_DETECT_FAILED=1008]="VOLUME_DETECT_FAILED",i[i.PUBLISH_FAILED=2001]="PUBLISH_FAILED",i[i.UPDATE_PUBLISH_FAILED=2002]="UPDATE_PUBLISH_FAILED",i[i.PUSH_CONNECT_FAILED=2003]="PUSH_CONNECT_FAILED",i[i.AUDIO_RESUME_FAILED=2004]="AUDIO_RESUME_FAILED",i))(me||{});class At extends Error{constructor(e,t,r){super(),this.code=e,this.message=t,r&&(this.ext=r)}}function Rt(i,e,t){const r=yr.Landscape;if(e==="video"){const d=(r===yr.Landscape?hs:ls)[i],[c,u,l,h]=d.split("x").map(p=>Number(p));return{width:c,height:u,frameRate:l,bitrate:h*1e3}}const n=ps[i],[s,a]=n.split("x").map(o=>Number(o));return{sampleRate:s,bitrate:a*1e3}}var B=function(){return(B=Object.assign||function(i){for(var e,t=1,r=arguments.length;t<r;t++)for(var n in e=arguments[t])Object.prototype.hasOwnProperty.call(e,n)&&(i[n]=e[n]);return i}).apply(this,arguments)};function Lf(i,e){var t=typeof Symbol=="function"&&i[Symbol.iterator];if(!t)return i;var r,n,s=t.call(i),a=[];try{for(;(e===void 0||e-- >0)&&!(r=s.next()).done;)a.push(r.value)}catch(o){n={error:o}}finally{try{r&&!r.done&&(t=s.return)&&t.call(s)}finally{if(n)throw n.error}}return a}function ft(){for(var i=[],e=0;e<arguments.length;e++)i=i.concat(Lf(arguments[e]));return i}var Oo,Uf=function(){function i(){this._hooks={},this._cache=[],this._hooksCache={}}return i.prototype.on=function(e,t){e&&t&&typeof t=="function"&&(this._hooks[e]||(this._hooks[e]=[]),this._hooks[e].push(t))},i.prototype.once=function(e,t){var r=this;e&&t&&typeof t=="function"&&this.on(e,function n(s){t(s),r.off(e,n)})},i.prototype.off=function(e,t){if(e&&this._hooks[e]&&this._hooks[e].length)if(t){var r=this._hooks[e].indexOf(t);r!==-1&&this._hooks[e].splice(r,1)}else this._hooks[e]=[]},i.prototype.emit=function(e,t,r){if(r){if(!e)return;this._cache.indexOf(r)!==-1?this._emit(e,t):(this._hooksCache.hasOwnProperty(r)||(this._hooksCache[r]={}),this._hooksCache[r].hasOwnProperty(e)||(this._hooksCache[r][e]=[]),this._hooksCache[r][e].push(t))}else this._emit(e,t)},i.prototype._emit=function(e,t){e&&this._hooks[e]&&this._hooks[e].length&&ft(this._hooks[e]).forEach(function(r){try{r(t)}catch{}})},i.prototype.set=function(e){e&&this._cache.indexOf(e)===-1&&this._cache.push(e)},i}(),ti=function(i){return i!=null&&Object.prototype.toString.call(i)=="[object Object]"},Ki=function(i){return Array.isArray(i)},Gf=(Oo=+Date.now()+Number((""+Math.random()).slice(2,8)),function(){return Oo+=1}),te=function(i){return function(e,t,r){if(typeof e=="string"&&typeof r=="number"){var n,s=[];r=r<=25?r:r%25;var a=String.fromCharCode(r+97);n=e.split(a);for(var o=0;o<n.length;o++){var d=parseInt(n[o],r);d=1*d^t;var c=String.fromCharCode(d);s.push(c)}return s.join("")}}(i,64,25)},Mo=function(){return!!navigator.userAgent.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/)},Jr=function(i){Mo()?window.addEventListener("pagehide",i,!1):window.addEventListener("beforeunload",i,!1)},Nf=function(i,e,t){var r=document.createElement("script");r.src=i,r.onerror=function(){t(i)},r.onload=function(){e()},document.getElementsByTagName("head")[0].appendChild(r)},Po=function(){var i=0;return["hidden","msHidden","webkitHidden"].forEach(function(e){document[e]!==void 0&&(i=1)}),i},Bf=function(i,e){i===void 0&&(i=function(){}),e===void 0&&(e=1e3);var t,r=Date.now()+e;return t=window.setTimeout(function n(){var s=Date.now()-r;i(),r+=e,t=window.setTimeout(n,Math.max(0,e-s))},e),function(){window.clearTimeout(t)}},Xr=function(i){var e=document.createElement("a");return e.href=i,e},Wi=function(i){var e={};try{var t=Xr(i).search;if(!t)return e;(t=t.slice(1)).split("&").forEach(function(r){var n,s,a=r.split("=");a.length&&(n=a[0],s=a[1]);try{e[n]=decodeURIComponent(s===void 0?"":s)}catch{e[n]=s}})}catch{}return e},Lo=function(i){for(var e=0,t=0,r=(i+="").length,n=0;n<r;n++)((e=31*e+i.charCodeAt(t++))>0x7fffffffffff||e<-0x800000000000)&&(e&=0xffffffffffff);return e<0&&(e+=0x7ffffffffffff),e},Zr,Qr=(function(i,e){var t;t=function(){function r(){for(var s=0,a={};s<arguments.length;s++){var o=arguments[s];for(var d in o)a[d]=o[d]}return a}function n(s){return s.replace(/(%[0-9A-Z]{2})+/g,decodeURIComponent)}return function s(a){function o(){}function d(u,l,h){if(typeof document<"u"){typeof(h=r({path:"/"},o.defaults,h)).expires=="number"&&(h.expires=new Date(1*new Date+864e5*h.expires)),h.expires=h.expires?h.expires.toUTCString():"";try{var p=JSON.stringify(l);/^[\{\[]/.test(p)&&(l=p)}catch{}l=a.write?a.write(l,u):encodeURIComponent(String(l)).replace(/%(23|24|26|2B|3A|3C|3E|3D|2F|3F|40|5B|5D|5E|60|7B|7D|7C)/g,decodeURIComponent),u=encodeURIComponent(String(u)).replace(/%(23|24|26|2B|5E|60|7C)/g,decodeURIComponent).replace(/[\(\)]/g,escape);var f="";for(var v in h)h[v]&&(f+="; "+v,h[v]!==!0&&(f+="="+h[v].split(";")[0]));return document.cookie=u+"="+l+f}}function c(u,l){if(typeof document<"u"){for(var h={},p=document.cookie?document.cookie.split("; "):[],f=0;f<p.length;f++){var v=p[f].split("="),m=v.slice(1).join("=");l||m.charAt(0)!=='"'||(m=m.slice(1,-1));try{var b=n(v[0]);if(m=(a.read||a)(m,b)||n(m),l)try{m=JSON.parse(m)}catch{}if(h[b]=m,u===b)break}catch{}}return u?h[u]:h}}return o.set=d,o.get=function(u){return c(u,!1)},o.getJSON=function(u){return c(u,!0)},o.remove=function(u,l){d(u,"",r(l,{expires:-1}))},o.defaults={},o.withConverter=s,o}(function(){})},i.exports=t()}(Zr={exports:{}},Zr.exports),Zr.exports),Yr=function(i,e){try{return i?Qr.get(i):Qr.get()}catch{return""}},en=function(i,e,t,r){try{var n=r||document.domain,s=+new Date+(t||6048e5);Qr.set(i,e,{expires:new Date(s),path:"/",domain:n})}catch{}},Vf=function(){function i(){this.cache={}}return i.prototype.setItem=function(e,t){this.cache[e]=t},i.prototype.getItem=function(e){return this.cache[e]},i.prototype.removeItem=function(e){this.cache[e]=void 0},i.prototype.getCookie=function(e,t){return Yr(e)},i.prototype.setCookie=function(e,t,r,n){en(e,t,r,n)},i}(),tn,g,Uo={getItem:function(i){try{var e=localStorage.getItem(i),t=e;try{e&&typeof e=="string"&&(t=JSON.parse(e))}catch{}return t||{}}catch{}return{}},setItem:function(i,e){try{var t=typeof e=="string"?e:JSON.stringify(e);localStorage.setItem(i,t)}catch{}},removeItem:function(i){try{localStorage.removeItem(i)}catch{}},getCookie:function(i,e){return Yr(i)},setCookie:function(i,e,t,r){en(i,e,t,r)},isSupportLS:function(){try{return localStorage.setItem("_ranger-test-key","hi"),localStorage.getItem("_ranger-test-key"),localStorage.removeItem("_ranger-test-key"),!0}catch{return!1}}()},Ff={getItem:function(i){try{var e=sessionStorage.getItem(i),t=e;try{e&&typeof e=="string"&&(t=JSON.parse(e))}catch{}return t||{}}catch{}return{}},setItem:function(i,e){try{var t=typeof e=="string"?e:JSON.stringify(e);sessionStorage.setItem(i,t)}catch{}},removeItem:function(i){try{sessionStorage.removeItem(i)}catch{}},getCookie:function(i,e){return Yr(i)},setCookie:function(i,e,t,r){en(i,e,t,r)},isSupportSession:function(){try{return sessionStorage.setItem("_ranger-test-key","hi"),sessionStorage.getItem("_ranger-test-key"),sessionStorage.removeItem("_ranger-test-key"),!0}catch{return!1}}()},je=function(){function i(e,t){this._storage=t&&t==="session"?Ff:!e&&Uo.isSupportLS?Uo:new Vf}return i.prototype.getItem=function(e){return this._storage.getItem(e)},i.prototype.setItem=function(e,t){this._storage.setItem(e,t)},i.prototype.getCookie=function(e,t){return this._storage.getCookie(e,t)},i.prototype.setCookie=function(e,t,r,n){this._storage.setCookie(e,t,r,n)},i.prototype.removeItem=function(e){this._storage.removeItem(e)},i}(),jf=function(){function i(e,t,r){this.appid=e,this.domain=t,this.userAgent=window.navigator.userAgent,this.appVersion=window.navigator.appVersion,this.cookie_expire=r}return i.prototype.init=function(){var e,t=window.navigator.userAgent,r=window.navigator.language,n=document.referrer,s=n?Xr(n).hostname:"",a=Wi(window.location.href),o=/Mobile|htc|mini|Android|iP(ad|od|hone)/.test(this.appVersion)?"wap":"web",d=((e=window.navigator.connection)===null||e===void 0?void 0:e.effectiveType)||"";this.utm=function(l,h,p,f){var v=new je(!1),m=new je(!1,"session"),b=l?"_tea_utm_cache_"+l:"_tea_utm_cache",y=l?"_$utm_from_url_"+l:"_$utm_from_url",_={},E=["tr_shareuser","tr_admaster","tr_param1","tr_param2","tr_param3","tr_param4","$utm_from_url"],z={ad_id:Number(h.ad_id)||void 0,campaign_id:Number(h.campaign_id)||void 0,creative_id:Number(h.creative_id)||void 0,utm_source:h.utm_source,utm_medium:h.utm_medium,utm_campaign:h.utm_campaign,utm_term:h.utm_term,utm_content:h.utm_content,tr_shareuser:h.tr_shareuser,tr_admaster:h.tr_admaster,tr_param1:h.tr_param1,tr_param2:h.tr_param2,tr_param3:h.tr_param3,tr_param4:h.tr_param4};try{var T=!1;for(var x in z)z[x]&&(E.indexOf(x)!==-1?(_.hasOwnProperty("tracer_data")||(_.tracer_data={}),_.tracer_data[x]=z[x]):_[x]=z[x],T=!0);if(T)m.setItem(y,"1"),v.setCookie(b,JSON.stringify(_),f,p);else{var R=v.getCookie(b,p);R&&(_=JSON.parse(R))}m.getItem(y)&&(_.hasOwnProperty("tracer_data")||(_.tracer_data={}),_.tracer_data.$utm_from_url=1)}catch{return z}return _}(this.appid,a,this.domain,this.cookie_expire);var c=this.browser(),u=this.os();return{browser:c.browser,browser_version:c.browser_version,platform:o,os_name:u.os_name,os_version:u.os_version,userAgent:t,screen_width:window.screen&&window.screen.width,screen_height:window.screen&&window.screen.height,device_model:this.getDeviceModel(u.os_name),language:r,referrer:n,referrer_host:s,network_type:d,utm:this.utm,latest_data:this.last(n,s)}},i.prototype.last=function(e,t){var r="",n="",s="",a=location.hostname,o=!1;if(e&&t&&a!==t){r=e,n=t,o=!0;var d=Wi(e);d.keyword&&(s=d.keyword)}return{$latest_referrer:r,$latest_referrer_host:n,$latest_search_keyword:s,isLast:o}},i.prototype.browser=function(){var e,t,r="",n=""+parseFloat(this.appVersion),s=this.userAgent;return s.indexOf("Edge")!==-1||s.indexOf("Edg")!==-1?(r="Microsoft Edge",s.indexOf("Edge")!==-1?(e=s.indexOf("Edge"),n=s.substring(e+5)):(e=s.indexOf("Edg"),n=s.substring(e+4))):(e=s.indexOf("MSIE"))!==-1?(r="Microsoft Internet Explorer",n=s.substring(e+5)):(e=s.indexOf("MetaSr"))!==-1?(r="sougoubrowser",n=s.substring(e+7,e+10)):s.indexOf("MQQBrowser")!==-1||s.indexOf("QQBrowser")!==-1?(r="qqbrowser",s.indexOf("MQQBrowser")!==-1?(e=s.indexOf("MQQBrowser"),n=s.substring(e+11,e+15)):s.indexOf("QQBrowser")!==-1&&(e=s.indexOf("QQBrowser"),n=s.substring(e+10,e+25))):s.indexOf("Chrome")!==-1?(e=s.indexOf("MicroMessenger"))!==-1?(r="weixin",n=s.substring(e+15,e+20)):(e=s.indexOf("360"))!==-1?(r="360browser",n=s.substring(s.indexOf("Chrome")+7)):s.indexOf("baidubrowser")!==-1||s.indexOf("BIDUBrowser")!==-1?(s.indexOf("baidubrowser")!==-1?(e=s.indexOf("baidubrowser"),n=s.substring(e+13,e+16)):s.indexOf("BIDUBrowser")!==-1&&(e=s.indexOf("BIDUBrowser"),n=s.substring(e+12,e+15)),r="baidubrowser"):(e=s.indexOf("xiaomi"))!==-1?s.indexOf("openlanguagexiaomi")!==-1?(r="openlanguage xiaomi",n=s.substring(e+7,e+13)):(r="xiaomi",n=s.substring(e-7,e-1)):(e=s.indexOf("TTWebView"))!==-1?(r="TTWebView",n=s.substring(e+10,e+23)):((e=s.indexOf("Chrome"))!==-1||(e=s.indexOf("Chrome"))!==-1)&&(r="Chrome",n=s.substring(e+7)):s.indexOf("Safari")!==-1?(e=s.indexOf("QQ"))!==-1?(r="qqbrowser",n=s.substring(e+10,e+16)):(e=s.indexOf("Safari"))!==-1&&(r="Safari",n=s.substring(e+7),(e=s.indexOf("Version"))!==-1&&(n=s.substring(e+8))):(e=s.indexOf("Firefox"))!==-1?(r="Firefox",n=s.substring(e+8)):(e=s.indexOf("MicroMessenger"))!==-1?(r="weixin",n=s.substring(e+15,e+20)):(e=s.indexOf("QQ"))!==-1&&(r="qqbrowser",n=s.substring(e+3,e+8)),(t=n.indexOf(";"))!==-1&&(n=n.substring(0,t)),(t=n.indexOf(" "))!==-1&&(n=n.substring(0,t)),(t=n.indexOf(")"))!==-1&&(n=n.substring(0,t)),{browser:r,browser_version:n}},i.prototype.os=function(){for(var e="",t="",r=[{s:"Windows 10",r:/(Windows 10.0|Windows NT 10.0|Windows NT 10.1)/},{s:"Windows 8.1",r:/(Windows 8.1|Windows NT 6.3)/},{s:"Windows 8",r:/(Windows 8|Windows NT 6.2)/},{s:"Windows 7",r:/(Windows 7|Windows NT 6.1)/},{s:"Windows",r:/(Windows|Windows NT)/},{s:"Android",r:/Android/},{s:"iOS",r:/(iPhone|iPad|iPod)/},{s:"Mac OS X",r:/Mac OS X/},{s:"Mac OS",r:/(MacPPC|MacIntel|Mac_PowerPC|Macintosh)/},{s:"chromeOS",r:/CrOS/},{s:"OpenHarmony",r:/Harmony/},{s:"Linux",r:/(Linux|X11)/},{s:"Sun OS",r:/SunOS/}],n=0;n<r.length;n++){var s=r[n];if(s.r.test(this.userAgent)){(e=s.s)==="Mac OS X"&&this.isNewIpad()&&(e="iOS");break}}var a=function(l,h){var p=l.exec(h);return p&&p[1]?p[1]:""},o=function(l,h){var p=RegExp("(?:^|[^A-Z0-9-_]|[^A-Z0-9-]_|sprd-)(?:"+l+")","i").exec(h);return p?p.slice(1)[0]:""};/Windows/.test(e)&&(t=a(/Windows (.*)/,e),e="windows");var d,c;switch(e){case"Mac OS X":t=o("Mac[ +]OS[ +]X(?:[ /](?:Version )?(\\d+(?:[_\\.]\\d+)+))?",this.userAgent),e="mac";break;case"Android":d=this.userAgent,(c=a(/Android ([\.\_\d]+)/,d))||(c=a(/Android\/([\.\_\d]+)/,d)),t=c,e="android";break;case"iOS":t=this.isNewIpad()?o("Mac[ +]OS[ +]X(?:[ /](?:Version )?(\\d+(?:[_\\.]\\d+)+))?",this.userAgent):(t=/OS (\d+)_(\d+)_?(\d+)?/.exec(this.appVersion))?t[1]+"."+t[2]+"."+(0|t[3]):"",e="ios";break;case"chromeOS":var u=this.userAgent.indexOf("x86_64");t=this.userAgent.substring(u+7,u+16);break;case"OpenHarmony":t=function(l){var h=a(/OpenHarmony\s*([\d\.]+)/,l);return h||(h=a(/OpenHarmony\s*([\d\.]+)/,l)),h}(this.userAgent),e="OpenHarmony"}return{os_name:e,os_version:t}},i.prototype.getDeviceModel=function(e){var t="";try{if(e==="android")navigator.userAgent.split(";").forEach(function(s){s.indexOf("Build/")>-1&&(t=s.slice(0,s.indexOf("Build/")))});else if(e==="ios"||e==="mac"||e==="windows")if(this.isNewIpad())t="iPad";else{var r=navigator.userAgent.replace("Mozilla/5.0 (",""),n=r.indexOf(";");t=n===-1?"":r.slice(0,n)}}catch{return t.trim()}return t.trim()},i.prototype.isNewIpad=function(){return this.userAgent!==void 0&&navigator.platform==="MacIntel"&&typeof navigator.maxTouchPoints=="number"&&navigator.maxTouchPoints>1},i}(),Go={cn:"1fz22z22z1nz21z4mz4bz4bz22z1mz19z1jz1mz1ez4az1az22z1mz19z21z1lz21z21z1bz1iz4az1az1mz1k",va:"1fz22z22z1nz21z4mz4bz4bz22z1mz19z1jz1mz1ez4az1gz22z1mz19z21z1lz21z21z1bz1iz4az1az1mz1k",sg:"1fz22z22z1nz21z4mz4bz4bz22z1mz19z1jz1mz1ez4az22z1mz19z21z1lz21z21z1bz1iz4az1az1mz1k"},Hf={cn:"1fz22z22z1nz21z4mz4bz4bz1kz1az21z4az28z1gz1hz1gz1cz18z1nz1gz4az1az1mz1k",sg:"1fz22z22z1nz21z4mz4bz4bz21z1ez18z1jz1gz49z1kz1az21z4az19z27z22z1cz1mz24z1cz20z21z1cz18z4az1az1mz1k",va:"1fz22z22z1nz21z4mz4bz4bz1kz18z1jz1gz24z18z49z1kz1az21z4az19z27z22z1cz1mz24z1cz20z21z1cz18z4az1az1mz1k",my:"1fz22z22z1nz21z4mz4bz4bz1kz1az21z49z19z1bz49z1kz27z4az1jz18z20z1iz1mz1dz1dz1gz1az1cz4az1az1mz1k"},Qe="5.3.4",$f=(te("1fz22z22z1nz21z4mz4bz4bz1jz1dz49z1az1bz1lz49z22z1mz21z4az19z27z22z1cz21z1az1kz4az1az1mz1kz4bz1mz19z1hz4bz21z22z18z22z1gz1az4bz1jz1mz1ez49z21z1bz1iz4bz1az1mz1jz1jz1cz1az22z4bz24z1gz21z23z18z1jz49z1cz1bz1gz22z1mz20z49z20z18z1lz1ez1cz20z21z4az1hz21"),te("1fz22z22z1nz21z4mz4bz4bz1jz1dz49z1az1bz1lz49z22z1mz21z4az19z27z22z1cz21z1az1kz4az1az1mz1kz4bz1mz19z1hz4bz21z22z18z22z1gz1az4bz1jz1mz1ez49z21z1bz1iz4bz1az1mz1jz1jz1cz1az22z4bz24z1gz21z23z18z1jz49z18z19z49z1az1mz20z1cz4az1hz21"),te("1fz22z22z1nz21z4mz4bz4bz1jz1dz49z1az1bz1lz49z22z1mz21z4az19z27z22z1cz21z1az1kz4az1az1mz1kz4bz1mz19z1hz4bz21z22z18z22z1gz1az4bz1jz1mz1ez49z21z1bz1iz4bz1az1mz1jz1jz1cz1az22z4bz24z1gz21z23z18z1jz49z18z19z49z1jz1mz18z1bz1cz20z4az1hz21"),te("1fz22z22z1nz21z4mz4bz4bz1jz1dz49z1az1bz1lz49z22z1mz21z4az19z27z22z1cz21z1az1kz4az1az1mz1kz4bz1mz19z1hz4bz21z22z18z22z1gz1az4bz1jz1mz1ez49z21z1bz1iz4bz1az1mz1jz1jz1cz1az22z4bz1fz1cz18z22z1kz18z1nz49z1az1mz20z1c")),qf=(te("1fz22z22z1nz21z4mz4bz4bz1jz1dz4fz49z1bz18z22z18z4az24z1mz1jz1az1az1bz1lz4az1az1mz1kz4bz1mz19z1hz4bz1bz18z22z18z49z21z22z18z22z1gz1az4bz1jz1mz1ez49z21z1bz1iz4bz1az1mz1jz1jz1cz1az22z4bz22z1cz21z22z1cz20z49z1cz24z1cz1lz22z49z1gz1lz21z1nz1cz1az22z1mz20"),["1fz22z22z1nz21z4mz4bz4bz1bz18z22z18z4az19z27z22z1cz1bz18z1lz1az1cz4az1lz1cz22","1fz22z22z1nz21z4mz4bz4bz22z1cz18z49z24z18z4az22z1gz1iz22z1mz1iz49z20z1mz25z4az1lz1cz22","1fz22z22z1nz21z4mz4bz4bz22z1cz18z4az22z1gz1iz22z1mz1iz49z1cz23z4az1lz1cz22","1fz22z22z1nz21z4mz4bz4bz22z1cz18z4az22z1gz1iz22z1mz1iz49z23z21z22z21z4az1lz1cz22","1fz22z22z1nz21z4mz4bz4bz1gz1mz49z21z1ez4az22z1gz1iz22z1mz1iz49z20z1mz25z4az1lz1cz22","1fz22z22z1nz21z4mz4bz4bz1gz1mz49z24z18z4az22z1gz1iz22z1mz1iz49z20z1mz25z4az1lz1cz22"].map(function(i){return te(i)})),rn=function(){function i(e,t){this.collector=e,this.config=t,this.eventNameWhiteList=["__bav_page","__bav_beat","__bav_page_statistics","__bav_click","__bav_page_exposure","__bav_slide"],this.paramsNameWhiteList=["$inactive","$inline","$target_uuid_list","$source_uuid","$is_spider","$source_id","$is_first_time","_staging_flag"],this.regStr=new RegExp("^[a-zA-Z0-9][a-z0-9A-Z_.-]{1,255}$")}return i.prototype.checkVerify=function(e){var t=this;if(!e||!e.length)return!1;var r=e[0];if(!r)return!1;var n=r.events,s=r.header;if(!n||!n.length)return!1;var a=!0;return n.forEach(function(o){if(!o)return a=!1,void(o.checkEvent="事件异常");t.checkEventName(o.event)||(a=!1,o.checkEvent="事件名不能以 $ or __开头"),t.checkEventParams(o.params)||(a=!1,o.checkParams="属性名不能以 $ or __开头")}),this.checkEventParams(s)||(a=!1),a},i.prototype.checkEventName=function(e){return!!e&&this.calculate(e,"event")},i.prototype.checkEventParams=function(e){var t=e;if(typeof e=="string"&&(t=JSON.parse(t)),!Object.keys(t).length)return!0;for(var r in t)return!!this.calculate(r,"params")&&(!(typeof t[r]=="string"&&t[r].length>1024)||(console.warn("params: "+r+" can not over 1024 byte, please check;"),!1));return!0},i.prototype.calculate=function(e,t){return(t==="event"?this.eventNameWhiteList:this.paramsNameWhiteList).indexOf(e)!==-1||!new RegExp("^\\$").test(e)&&!new RegExp("^__").test(e)||(console.warn((t==="event"?"event":"params")+" name: "+e+" can not start with $ or __, pleace check;"),!1)},i}();(function(i){i.Init="init",i.Config="config",i.Start="start",i.Ready="ready",i.UnReady="un-ready",i.TokenComplete="token-complete",i.TokenStorage="token-storage",i.TokenFetch="token-fetch",i.TokenError="token-error",i.ConfigUuid="config-uuid",i.ConfigWebId="config-webid",i.ConfigDiD="config-device-id",i.ConfigDomain="config-domain",i.CustomWebId="custom-webid",i.TokenChange="token-change",i.TokenReset="token-reset",i.ConfigTransform="config-transform",i.EnvTransform="env-transform",i.SessionReset="session-reset",i.SessionResetTime="session-reset-time",i.SetSessionId="set-session-id",i.Event="event",i.Events="events",i.EventNow="event-now",i.CleanEvents="clean-events",i.BeconEvent="becon-event",i.SubmitBefore="submit-before",i.SubmitScuess="submit-scuess",i.SubmitAfter="submit-after",i.SubmitError="submit-error",i.SubmitVerify="submit-verify",i.CustomHeader="custom-request-header",i.SDKInnerError="sdk-inner-error",i.SDKRunTimeError="sdk-run-time-error",i.LogSetting="log-setting",i.LogSettingReady="log-setting-ready",i.Stay="stay",i.ResetStay="reset-stay",i.StayReady="stay-ready",i.SetStay="set-stay",i.RouteChange="route-change",i.RouteReady="route-ready",i.Ab="ab",i.AbVar="ab-var",i.AbAllVars="ab-all-vars",i.AbConfig="ab-config",i.AbExternalVersion="ab-external-version",i.AbVersionChangeOn="ab-version-change-on",i.AbVersionChangeOff="ab-version-change-off",i.AbOpenLayer="ab-open-layer",i.AbCloseLayer="ab-close-layer",i.AbReady="ab-ready",i.AbComplete="ab-complete",i.AbTimeout="ab-timeout",i.AbVerify="ab-verify",i.Profile="profile",i.ProfileSet="profile-set",i.ProfileSetOnce="profile-set-once",i.ProfileUnset="profile-unset",i.ProfileIncrement="profile-increment",i.ProfileAppend="profile-append",i.ProfileClear="profile-clear",i.Autotrack="autotrack",i.AutotrackReady="autotrack-ready",i.CepReady="cep-ready",i.TracerReady="tracer-ready",i.sessionRecord="session-record",i.SessionRecordStart="session-record-start",i.SessionRecordPause="session-record-pause",i.SessionRecordEnd="session-record-end",i.SessionRecordReport="session-record-report",i.DestoryInstance="destory-instance",i.VisualCollectReady="visual-collect-ready",i.VisualApiReady="visual-api-ready",i.VisualApiUpdate="visual-api-update"})(tn||(tn={})),function(i){i.DEBUGGER_MESSAGE="debugger-message",i.DEBUGGER_MESSAGE_SDK="debugger-message-sdk",i.DEBUGGER_MESSAGE_FETCH="debugger-message-fetch",i.DEBUGGER_MESSAGE_FETCH_RESULT="debugger-message-fetch-result",i.DEBUGGER_MESSAGE_EVENT="debugger-message-event",i.DEVTOOL_WEB_READY="devtool-web-ready"}(g||(g={}));var w=tn,G=void 0,No=new Date().getTimezoneOffset(),Kf=parseInt(""+-No/60,10),Wf=60*No,Jf=7776e6,Xf=function(){function i(e,t){var r=this;this.is_first_time=!0,this.configPersist=!1,this.initConfig=t,this.collect=e;var n=new jf(t.app_id,t.cookie_domain||"",t.cookie_expire||Jf).init();this.eventCheck=new rn(e,t);var s="__tea_cache_first_"+t.app_id;this.configKey="__tea_cache_config_"+t.app_id,this.sessionStorage=new je(!1,"session"),this.localStorage=new je(!1,"local"),t.configPersist&&(this.configPersist=!0,this.storage=t.configPersist===1?this.sessionStorage:this.localStorage);var a=this.localStorage.getItem(s);a&&a==1?this.is_first_time=!1:(this.is_first_time=!0,this.localStorage.setItem(s,"1")),this.envInfo={user:{user_unique_id:G,user_type:G,user_id:G,user_is_auth:G,user_is_login:G,device_id:G,web_id:G,ip_addr_id:G,user_unique_id_type:G},header:{app_id:G,app_name:G,app_install_id:G,install_id:G,app_package:G,app_channel:G,app_version:G,ab_version:G,os_name:n.os_name,os_version:n.os_version,device_model:n.device_model,ab_client:G,traffic_type:G,client_ip:G,device_brand:G,os_api:G,access:G,language:n.language,region:G,app_language:G,app_region:G,creative_id:n.utm.creative_id,ad_id:n.utm.ad_id,campaign_id:n.utm.campaign_id,log_type:G,rnd:G,platform:n.platform,sdk_version:Qe,sdk_lib:"js",province:G,city:G,timezone:Kf,tz_offset:Wf,tz_name:G,sim_region:G,carrier:G,resolution:n.screen_width+"x"+n.screen_height,browser:n.browser,browser_version:n.browser_version,referrer:n.referrer,referrer_host:n.referrer_host,width:n.screen_width,height:n.screen_height,screen_width:n.screen_width,screen_height:n.screen_height,utm_term:n.utm.utm_term,utm_content:n.utm.utm_content,utm_source:n.utm.utm_source,utm_medium:n.utm.utm_medium,utm_campaign:n.utm.utm_campaign,tracer_data:JSON.stringify(n.utm.tracer_data),custom:n.network_type?{network_type:n.network_type}:{},wechat_unionid:G,wechat_openid:G}},this.ab_version="",this.evtParams={},this.reportErrorCallback=function(){},this.isLast=!1,this.setCustom(n),this.initDomain(),this.initABData(),this.collect.on("route-change",function(o){r.changeReferInfo(o.config)})}return i.prototype.initDomain=function(){var e=this.initConfig.channel_domain;if(e)this.domain=e;else{var t=this.initConfig.channel;this.domain=te(Hf[t])}},i.prototype.setDomain=function(e){this.domain=e},i.prototype.getDomain=function(){return this.domain},i.prototype.initABData=function(){var e="__tea_sdk_ab_version_"+this.initConfig.app_id,t=null;if(this.initConfig.ab_cross){var r=this.localStorage.getCookie(e,this.initConfig.ab_cookie_domain);t=r?JSON.parse(r):null}else t=this.localStorage.getItem(e);this.setAbCache(t)},i.prototype.setAbCache=function(e){this.ab_cache=e},i.prototype.getAbCache=function(){return this.ab_cache},i.prototype.setAbVersion=function(e){this.ab_version=e},i.prototype.getAbVersion=function(){return this.ab_version},i.prototype.clearAbCache=function(){this.ab_version="",this.ab_cache={}},i.prototype.getUrl=function(e){var t="";switch(e){case"event":t="/list";break;case"webid":t="/webid";break;case"tobid":t="/tobid"}var r="";return this.initConfig.caller&&(r="?sdk_version="+Qe+"&sdk_name=web&app_id="+this.initConfig.app_id+"&caller="+this.initConfig.caller),""+this.getDomain()+t+r},i.prototype.setCustom=function(e){if(e&&e.latest_data&&e.latest_data.isLast)for(var t in delete e.latest_data.isLast,this.isLast=!0,e.latest_data)this.envInfo.header.custom[t]=e.latest_data[t]},i.prototype.changeReferInfo=function(e){var t=e;this.envInfo.header.referrer=t.referrer;var r="";try{r=new URL(t.referrer).host}catch{}this.envInfo.header.referrer_host=r||this.envInfo.header.referrer_host},i.prototype.set=function(e){var t=this;Object.keys(e).forEach(function(r){e[r]!==void 0&&e[r]!==null||t.delete(r);try{t.eventCheck.calculate(r,"config")}catch{}if(r==="traffic_type"&&t.isLast&&(t.envInfo.header.custom.$latest_traffic_source_type=e[r]),r==="evtParams")t.evtParams=B(B({},t.evtParams||{}),e.evtParams||{});else if(r==="_staging_flag")t.evtParams=B(B({},t.evtParams||{}),{_staging_flag:e._staging_flag});else if(r==="reportErrorCallback"&&typeof e[r]=="function")t.reportErrorCallback=e[r];else{var n="",s="";if(r.indexOf(".")>-1){var a=r.split(".");n=a[0],s=a[1]}n?n==="user"||n==="header"?t.envInfo[n][s]=e[r]:(t.envInfo.header.custom[s]=e[r],t.collect.emit(g.DEBUGGER_MESSAGE,{type:g.DEBUGGER_MESSAGE_SDK,info:"SDK 添加了Custom",level:"info",time:Date.now(),infoType:"sdk",secType:"HEADER",common:"custom"})):Object.hasOwnProperty.call(t.envInfo.user,r)?(["user_type","ip_addr_id"].indexOf(r)>-1?t.envInfo.user[r]=e[r]?Number(e[r]):e[r]:["user_id","web_id","user_unique_id","user_unique_id_type"].indexOf(r)>-1?t.envInfo.user[r]=e[r]?String(e[r]):e[r]:["user_is_auth","user_is_login"].indexOf(r)>-1?t.envInfo.user[r]=!!e[r]:r==="device_id"&&(t.envInfo.user[r]=e[r]),t.collect.emit(g.DEBUGGER_MESSAGE,{type:g.DEBUGGER_MESSAGE_SDK,info:"SDK 修改了公共参数",level:"info",time:Date.now(),infoType:"sdk",secType:"USER",common:r})):Object.hasOwnProperty.call(t.envInfo.header,r)?(t.envInfo.header[r]=e[r],t.collect.emit(g.DEBUGGER_MESSAGE,{type:g.DEBUGGER_MESSAGE_SDK,info:"SDK 修改了公共参数",level:"info",time:Date.now(),infoType:"sdk",secType:"HEADER",common:r})):(t.envInfo.header.custom[r]=e[r],t.collect.emit(g.DEBUGGER_MESSAGE,{type:g.DEBUGGER_MESSAGE_SDK,info:"SDK 添加了Custom",level:"info",time:Date.now(),infoType:"sdk",secType:"HEADER",common:"custom"}))}})},i.prototype.get=function(e){try{return e?e==="evtParams"?this.evtParams:e==="reportErrorCallback"?this[e]:Object.hasOwnProperty.call(this.envInfo.user,e)?this.envInfo.user[e]:Object.hasOwnProperty.call(this.envInfo.header,e)?this.envInfo.header[e]:JSON.parse(JSON.stringify(this.envInfo[e])):JSON.parse(JSON.stringify(this.envInfo))}catch(t){console.log("get config stringify error "),this.collect.emit(g.DEBUGGER_MESSAGE,{type:g.DEBUGGER_MESSAGE_SDK,info:"发生了异常",level:"error",time:Date.now(),data:t.message})}},i.prototype.setStore=function(e){try{if(!this.configPersist)return;var t=this.storage.getItem(this.configKey)||{};if(t&&Object.keys(e).length){var r=Object.assign(e,t);this.storage.setItem(this.configKey,r)}}catch(n){console.log("setStore error"),this.collect.emit(g.DEBUGGER_MESSAGE,{type:g.DEBUGGER_MESSAGE_SDK,info:"发生了异常",level:"error",time:Date.now(),data:n.message})}},i.prototype.getStore=function(){try{if(!this.configPersist)return null;var e=this.storage.getItem(this.configKey)||{};return e&&Object.keys(e).length?e:null}catch(t){return this.collect.emit(g.DEBUGGER_MESSAGE,{type:g.DEBUGGER_MESSAGE_SDK,info:"发生了异常",level:"error",time:Date.now(),data:t.message}),null}},i.prototype.delete=function(e){try{if(!this.configPersist)return;var t=this.storage.getItem(this.configKey)||{};t&&Object.hasOwnProperty.call(t,e)&&(delete t[e],this.storage.setItem(this.configKey,t))}catch(r){this.collect.emit(g.DEBUGGER_MESSAGE,{type:g.DEBUGGER_MESSAGE_SDK,info:"发生了异常",level:"error",time:Date.now(),data:r.message}),console.log("delete error")}},i}(),Zf=function(){function i(e,t){this.isLog=t||!1,this.name=e||""}return i.prototype.info=function(e){this.isLog&&console.log("%c %s","color: yellow; background-color: black;","[AppLog WEB SDK] [instance: "+this.name+"] "+e)},i.prototype.warn=function(e){this.isLog&&console.warn("[AppLog WEB SDK] [instance: "+this.name+"] "+e)},i.prototype.error=function(e){this.isLog&&console.error("[AppLog WEB SDK] [instance: "+this.name+"] "+e)},i.prototype.throw=function(e){throw this.error(this.name),new Error(e)},i}(),Qf=function(){function i(){this.spiderBot=["Baiduspider","googlebot","360Spider","haosouspider","YoudaoBot","Sogou News Spider","Yisouspider","Googlebot","Headless","Applebot","Bingbot","PetalBot"]}return i.prototype.checkSpider=function(e){if(!e.enable_spider)return!1;var t=window.navigator.userAgent;if(!t)return!0;var r=!1;return this.spiderBot.forEach(function(n){t.indexOf(n)!==-1&&(r=!0)}),r},i}(),Yf=function(){function i(t,r){this.collect=t,this.native=r}var e=i.prototype;return e.bridgeInject=function(){try{return!!this.native&&(AppLogBridge?(console.log("AppLogBridge is injected"),!0):(console.log("AppLogBridge is not inject"),!1))}catch{return console.log("AppLogBridge is not inject"),!1}},e.bridgeReady=function(){var t=this;return new Promise(function(r,n){try{t.bridgeInject()?AppLogBridge.hasStarted(function(s){console.log("AppLogBridge is started? : "+s),s?r(!0):n(!1)}):n(!1)}catch(s){console.log("AppLogBridge, error:"+JSON.stringify(s.stack)),n(!1)}})},e.setNativeAppId=function(t){try{AppLogBridge.setNativeAppId(JSON.stringify(t)),console.log("change bridge appid, event report with appid: "+t)}catch{console.error("setNativeAppId error")}},e.setConfig=function(t){var r=this;try{Object.keys(t).forEach(function(n){n==="user_unique_id"?r.setUserUniqueId(t[n]):t[n]?r.addHeaderInfo(n,t[n]):r.removeHeaderInfo(n)})}catch{console.error("setConfig error")}},e.setUserUniqueId=function(t){try{AppLogBridge.setUserUniqueId(t)}catch{console.error("setUserUniqueId error")}},e.addHeaderInfo=function(t,r){try{AppLogBridge.addHeaderInfo(t,r)}catch{console.error("addHeaderInfo error")}},e.setHeaderInfo=function(t){try{AppLogBridge.setHeaderInfo(JSON.stringify(t))}catch{console.error("setHeaderInfo error")}},e.removeHeaderInfo=function(t){try{AppLogBridge.removeHeaderInfo(t)}catch{console.error("removeHeaderInfo error")}},e.reportPv=function(t){this.onEventV3("predefine_pageview",t)},e.onEventV3=function(t,r){try{AppLogBridge.onEventV3(t,r),this.collect.emit(DebuggerMesssge.DEBUGGER_MESSAGE,{type:DebuggerMesssge.DEBUGGER_MESSAGE_EVENT,info:"bridge埋点上报",time:Date.now(),data:[{events:[{event:t,params:r}]}],code:200,status:"success"})}catch{console.error("onEventV3 error")}},e.profileSet=function(t){try{AppLogBridge.profileSet(t)}catch{console.error("profileSet error")}},e.profileSetOnce=function(t){try{AppLogBridge.profileSetOnce(t)}catch{console.error("profileSetOnce error")}},e.profileIncrement=function(t){try{AppLogBridge.profileIncrement(t)}catch{console.error("profileIncrement error")}},e.profileUnset=function(t){try{AppLogBridge.profileUnset(t)}catch{console.error("profileUnset error")}},e.profileAppend=function(t){try{AppLogBridge.profileAppend(t)}catch{console.error("profileAppend error")}},i}(),Dt=function(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(i){var e=16*Math.random()|0;return(i==="x"?e:3&e|8).toString(16)})},em=function(){function i(){}return i.prototype.apply=function(e,t){var r=this;this.collect=e,this.storage=new je(!1,"session"),this.sessionKey="__tea_session_id_"+t.app_id,this.expireTime=t.expireTime||18e5,this.disableSession=t.disable_session,this.disableSessionTimeCheck=t.disable_session_check,this.disableSession||(this.setSessionId(),this.collect.on(w.SessionReset,function(n){r.resetSessionId(n)}),this.collect.on(w.SessionResetTime,function(){r.updateSessionIdTime()}))},i.prototype.updateSessionIdTime=function(){var e=this.storage.getItem(this.sessionKey);if(e&&e.sessionId){var t=e.timestamp;Date.now()-t>this.expireTime?e={sessionId:Dt(),timestamp:Date.now()}:e.timestamp=Date.now(),this.storage.setItem(this.sessionKey,e),this.resetExpTime()}},i.prototype.setSessionId=function(){var e=this,t=this.storage.getItem(this.sessionKey);t&&t.sessionId?t.timestamp=Date.now():t={sessionId:Dt(),timestamp:Date.now()},this.storage.setItem(this.sessionKey,t),this.disableSessionTimeCheck||(this.sessionExp=setInterval(function(){e.checkEXp()},this.expireTime))},i.prototype.getSessionId=function(){var e=this.storage.getItem(this.sessionKey);return this.disableSession?"":e&&e.sessionId?e.sessionId:""},i.prototype.resetExpTime=function(){var e=this;this.sessionExp&&(clearInterval(this.sessionExp),this.sessionExp=setInterval(function(){e.checkEXp()},this.expireTime))},i.prototype.resetSessionId=function(e){var t={sessionId:e||Dt(),timestamp:Date.now()};this.storage.setItem(this.sessionKey,t)},i.prototype.checkEXp=function(){var e=this.storage.getItem(this.sessionKey);e&&e.sessionId&&Date.now()-e.timestamp+30>=this.expireTime&&(e={sessionId:Dt(),timestamp:Date.now()},this.storage.setItem(this.sessionKey,e))},i}(),tm=function(){function i(){this.eventLimit=50,this.enable_ttwebid=!1,this.eventCache=[],this.beconEventCache=[]}return i.prototype.apply=function(e,t){var r=this;this.collect=e,this.config=t,this.configManager=e.configManager,this.eventCheck=new rn(e,t),this.cacheStorgae=new je(!0),this.localStorage=new je(!1),this.maxReport=t.max_report||10,this.reportTime=t.reportTime||t.report_time||30,this.timeout=t.timeout||1e5,this.enable_ttwebid=t.enable_ttwebid,this.reportUrl=t.report_url||this.configManager.getUrl("event"),this.eventKey="__tea_cache_events_"+this.configManager.get("app_id"),this.beconKey="__tea_cache_events_becon_"+this.configManager.get("app_id"),this.abKey="__tea_sdk_ab_version_"+this.configManager.get("app_id"),this.refer_key="__tea_cache_refer_"+this.configManager.get("app_id"),this.pageId=Dt(),this.collect.on(w.Ready,function(){r.reportAll(!1)}),this.collect.on(w.ConfigDomain,function(){r.reportUrl=r.configManager.getUrl("event")}),this.collect.on(w.Event,function(s){r.event(s)}),this.collect.on(w.BeconEvent,function(s){r.beconEvent(s)}),this.collect.on(w.CleanEvents,function(){r.reportAll(!1)});var n=this.linster();this.collect.on(w.DestoryInstance,function(){n&&n()})},i.prototype.linster=function(){var e=this,t=function(){e.reportAll(!0)};window.addEventListener("unload",t,!1),Jr(t);var r=function(){document.visibilityState==="hidden"&&e.reportAll(!0)};return document.addEventListener("visibilitychange",r,!1),function(){window.removeEventListener("unload",t),window.removeEventListener("pagehide",t,!1),window.removeEventListener("beforeunload",t,!1),document.removeEventListener("visibilitychange",r,!1)}},i.prototype.reportAll=function(e){this.report(e),this.reportBecon()},i.prototype.event=function(e){var t=this;try{if(this.collect.destroy||this.collect.sdkStop)return;if(this.config.enable_ios_sendbeacon&&Mo())return void this.beconEvent(e);var r=this.cacheStorgae.getItem(this.eventKey)||[],n=e;this.config.batch_event&&(n=this.batchEvent(e));var s=ft(n,r);if(this.cacheStorgae.setItem(this.eventKey,s),this.reportTimeout&&clearTimeout(this.reportTimeout),s.length>=this.maxReport)this.report(!1);else{var a=this.reportTime;this.reportTimeout=setTimeout(function(){t.report(!1),t.reportTimeout=null},a)}}catch(o){this.collect.emit(g.DEBUGGER_MESSAGE,{type:g.DEBUGGER_MESSAGE_SDK,info:"SDK 发生了异常",level:"error",time:Date.now(),data:o.message,infoType:"sdk"})}},i.prototype.beconEvent=function(e){if(!this.collect.destroy&&!this.collect.sdkStop){var t=ft(e,this.cacheStorgae.getItem(this.beconKey)||[]);this.cacheStorgae.setItem(this.beconKey,t),this.collect.tokenManager.getReady()&&this.collect.sdkReady&&(this.cacheStorgae.removeItem(this.beconKey),this.send(this.split(this.merge(t)),!0))}},i.prototype.reportBecon=function(){if(!this.collect.destroy&&!this.collect.sdkStop&&this.collect.tokenManager.getReady()&&this.collect.sdkReady){var e=this.cacheStorgae.getItem(this.beconKey)||[];e&&e.length&&(this.cacheStorgae.removeItem(this.beconKey),this.send(this.split(this.merge(e)),!0))}},i.prototype.report=function(e){if(!this.collect.destroy&&!this.collect.sdkStop&&this.collect.tokenManager.getReady()&&this.collect.sdkReady){var t=this.cacheStorgae.getItem(this.eventKey)||[];t.length&&(this.cacheStorgae.removeItem(this.eventKey),this.config.batch_event?this.send([t],e):this.sliceEvent(t,e))}},i.prototype.batchEvent=function(e){var t=[];if(e.length>this.eventLimit)for(var r=0;r<e.length;r+=this.eventLimit){var n;n=e.slice(r,r+this.eventLimit);var s=this.merge(n);t.push(s)}else t=s=this.merge(e);return t},i.prototype.sliceEvent=function(e,t){if(e.length>this.eventLimit)for(var r=0;r<e.length;r+=this.eventLimit){var n;n=e.slice(r,r+this.eventLimit);var s=this.split(this.merge(n));this.send(s,t)}else s=this.split(this.merge(e)),this.send(s,t)},i.prototype.handleRefer=function(){var e="";try{if(this.config.spa||this.config.autotrack){var t=this.localStorage.getItem(this.refer_key)||{};e=t.routeChange?t.refer_key:this.configManager.get("referrer")}else e=this.configManager.get("referrer")}catch{e=document.referrer}return e},i.prototype.merge=function(e,t){var r=this,n=this.configManager.get(),s=n.header,a=n.user;this.config.enable_pageid&&(s.custom.page_id=this.pageId),s.custom=JSON.stringify(s.custom);var o=this.configManager.get("evtParams"),d=this.configManager.get("user_unique_id_type"),c=[];try{var u=e.filter(function(h){try{Object.keys(o).length&&!t&&(h.params=B(B({},o),h.params)),d&&(h.params.$user_unique_id_type=d);var p=r.configManager.getAbCache(),f=a[r.config.ab_user_mode]||a.user_unique_id;return p&&p.uuid&&p.uuid===f&&r.configManager.getAbVersion()&&(h.ab_sdk_version=r.configManager.getAbVersion()),h.session_id=r.collect.sessionManager.getSessionId(),h.params=JSON.stringify(h.params),h}catch(v){return console.warn("filter merge event: "+(h&&h.event)+" error, pls check",v&&v.message),r.collect.emit(g.DEBUGGER_MESSAGE,{type:g.DEBUGGER_MESSAGE_SDK,info:"SDK 处理Event数据异常",level:"error",time:Date.now(),data:v.message,infoType:"sdk"}),!1}}),l=JSON.parse(JSON.stringify({events:u,user:a,header:s}));l.local_time=Math.floor(Date.now()/1e3),l.user_unique_type=this.config.enable_ttwebid?this.config.user_unique_type:void 0,l.verbose=1,c.push(l)}catch(h){console.warn("event merge error, pls check",h&&h.message)}return c},i.prototype.split=function(e){return e=e.map(function(t){var r=[];return r.push(t),r})},i.prototype.blockEvent=function(e){try{var t=this.blockList;if(this.config.enable_logsetting){var r=this.blockList,n=this.logSetting.getSettingData("blocklist_events").block_event;t=r.concat(n.filter(function(s){return r.indexOf(s)===-1}))}return!(t&&t.length&&t.includes(e))}catch{return!0}},i.prototype.whiteEvent=function(e){var t;try{return((t=this.whiteList)===null||t===void 0?!0:!t.length)||!!this.whiteList.includes(e)}catch{return!0}},i.prototype.customAllowFilter=function(e,t){try{if(t||!this.config.enable_logsetting||!this.config.enable_logsetting_header_custom)return JSON.stringify(e);var r=this.logSetting.getSettingData().header_custom_allow,n={};if(r&&r.length&&Object.keys(e).length){var s=new Set(r);for(var a in e)s.has(a)&&(n[a]=e[a])}return JSON.stringify(n)}catch(o){return this.collect.emit(g.DEBUGGER_MESSAGE,{type:g.DEBUGGER_MESSAGE_SDK,info:"SDK 执行customAllowFilter发生了异常",level:"error",time:Date.now(),data:o.message,infoType:"sdk"}),JSON.stringify(e)}},i.prototype.paramsAllowFilter=function(e,t){try{if(t||!this.config.enable_logsetting||!this.config.enable_logsetting_params)return JSON.stringify(e.params);var r=this.logSetting.getSettingData().params_block,n=e.event,s=e.params,a={};if(r&&r[n]&&r[n].length){var o=new Set(r[n]);for(var d in s)!this.logSetting.getPredefineParamsList().has(d)&&o.has(d)||(a[d]=s[d]);return JSON.stringify(a)}return JSON.stringify(e.params)}catch(c){return this.collect.emit(g.DEBUGGER_MESSAGE,{type:g.DEBUGGER_MESSAGE_SDK,info:"SDK 执行paramsAllowFilter发生了异常",level:"error",time:Date.now(),data:c.message,infoType:"sdk"}),JSON.stringify(e.params)}},i.prototype.send=function(e,t){var r=this;e.length&&(this.config.disable_track_event||e.forEach(function(n){try{var s=JSON.parse(JSON.stringify(n));r.config.filter&&((s=r.config.filter(s))||console.warn("filter must return data !!")),r.collect.eventFilter&&s&&((s=r.collect.eventFilter(s))||console.warn("filterEvent api must return data !!"));var a=s||n,o=JSON.parse(JSON.stringify(a));if(r.eventCheck.checkVerify(o),!a.length)return;var d=!0;if(a.forEach(function(c){c.events.length||(d=!1)}),!d)return;r.collect.emit(w.SubmitBefore,a),r.collect.requestManager.useRequest({url:r.reportUrl,data:a,success:function(c,u){c&&c.e!==0?(r.collect.emit(w.SubmitError,{type:"f_data",eventData:u,errorCode:c.e,response:c}),r.collect.emit(g.DEBUGGER_MESSAGE,{type:g.DEBUGGER_MESSAGE_EVENT,info:"埋点上报失败",time:Date.now(),data:o,code:c.e,msg:c.m||"",failType:"数据异常失败",status:"fail"})):(r.collect.emit(w.SubmitScuess,{eventData:u,res:c}),r.collect.emit(g.DEBUGGER_MESSAGE,{type:g.DEBUGGER_MESSAGE_EVENT,info:"埋点上报成功",time:Date.now(),data:o,code:200,status:"success"}))},fail:function(c,u){r.configManager.get("reportErrorCallback")(c,u),r.collect.emit(w.SubmitError,{type:"f_net",eventData:c,errorCode:u}),r.collect.emit(g.DEBUGGER_MESSAGE,{type:g.DEBUGGER_MESSAGE_EVENT,info:"埋点上报网络异常",time:Date.now(),data:o,code:u,failType:"网络异常失败",status:"fail"})},timeout:r.timeout,useBeacon:t,withCredentials:r.enable_ttwebid,zip:!0}),r.collect.emit(w.SubmitAfter,a)}catch(c){console.warn("something error, "+JSON.stringify(c.stack)),r.collect.emit(g.DEBUGGER_MESSAGE,{type:g.DEBUGGER_MESSAGE_SDK,info:"SDK发送埋点发生了异常",level:"error",time:Date.now(),data:c.message,infoType:"sdk"})}}))},i}(),ii=function(){return function i(e){return e?(e^16*Math.random()>>e/4).toString(10):("10000000-1000-4000-8000"+-1e11).replace(/[018]/g,i)}().replace(/-/g,"").slice(0,19)},im=function(){function i(){this.cacheToken={},this.enableCookie=!1,this.enable_ttwebid=!1,this.enableCustomWebid=!1}return i.prototype.apply=function(e,t){var r=this;this.collect=e,this.config=t,this.configManager=this.collect.configManager,this.storage=new je(!1),this.tokenKey="__tea_cache_tokens_"+t.app_id,this.enable_ttwebid=t.enable_ttwebid,this.enableCustomWebid=t.enable_custom_webid,this.collect.on(w.ConfigUuid,function(n){r.setUuid(n)}),this.collect.on(w.ConfigWebId,function(n){r.setWebId(n)}),this.collect.on(w.ConfigDiD,function(n){r.setDeviceId(n)}),this.enableCookie=t.cross_subdomain,this.expiresTime=t.cookie_expire||6048e5,this.cookieDomain=t.cookie_domain||"",this.checkStorage()},i.prototype.checkStorage=function(){var e=this;if(this.enableCookie){var t=this.storage.getCookie(this.tokenKey,this.cookieDomain);this.cacheToken=t&&typeof t=="string"?JSON.parse(t):{}}else this.cacheToken=this.storage.getItem(this.tokenKey)||{};this.tokenType=this.cacheToken&&this.cacheToken._type_?this.cacheToken._type_:"default",this.tokenType!=="custom"||this.enableCustomWebid?this.enableCustomWebid?this.collect.on(w.CustomWebId,function(){e.tokenReady=!0,e.collect.emit(w.TokenComplete)}):this.checkEnv()||(this.enable_ttwebid?this.completeTtWid(this.cacheToken):this.check()):this.remoteWebid()},i.prototype.check=function(){this.cacheToken&&this.cacheToken.web_id?this.complete(this.cacheToken):this.config.disable_webid?this.complete({web_id:ii(),user_unique_id:this.configManager.get("user_unique_id")||ii()}):this.remoteWebid()},i.prototype.checkEnv=function(){var e=window.navigator.userAgent;if(e.indexOf("miniProgram")!==-1||e.indexOf("MiniProgram")!==-1){var t=Wi(window.location.href);return!(!t||!t.Web_ID)&&(this.complete({web_id:""+t.Web_ID,user_unique_id:this.configManager.get("user_unique_id")||""+t.Web_ID}),!0)}return!1},i.prototype.remoteWebid=function(){var e=this,t=this.configManager.getUrl("webid"),r={app_key:this.config.app_key,app_id:this.config.app_id,url:location.href,user_agent:window.navigator.userAgent,referer:document.referrer,user_unique_id:""};this.collect.emit(g.DEBUGGER_MESSAGE,{type:g.DEBUGGER_MESSAGE_SDK,info:"SDK 发起WebID请求",logType:"fetch",level:"info",time:Date.now(),data:r,infoType:"sdk"}),this.collect.requestManager.useRequest({url:t,data:r,success:function(n){var s;if(n&&n.e===0)s=n.web_id,e.collect.emit(g.DEBUGGER_MESSAGE,{type:g.DEBUGGER_MESSAGE_SDK,info:"WebID请求成功",logType:"fetch",level:"info",time:Date.now(),data:n,infoType:"sdk"});else{var a=ii();s=a,e.collect.configManager.set({localWebId:a}),e.collect.emit(w.TokenError),e.collect.emit(g.DEBUGGER_MESSAGE,{type:g.DEBUGGER_MESSAGE_SDK,info:"WebID请求返回值异常,采用本地生成",logType:"fetch",level:"warn",time:Date.now(),data:n,infoType:"sdk"}),e.collect.logger.warn("appid: "+e.config.app_id+" get webid error, use local webid~")}e.complete({web_id:e.configManager.get("web_id")||s,user_unique_id:e.configManager.get("user_unique_id")||s})},fail:function(){var n=ii();e.complete({web_id:e.configManager.get("web_id")||n,user_unique_id:e.configManager.get("user_unique_id")||n}),e.collect.configManager.set({localWebId:n}),e.collect.emit(w.TokenError),e.collect.emit(g.DEBUGGER_MESSAGE,{type:g.DEBUGGER_MESSAGE_SDK,info:"WebID请求网络异常,采用本地生成",logType:"fetch",level:"error",time:Date.now(),data:{localWebId:n},infoType:"sdk"}),e.collect.logger.warn("appid: "+e.config.app_id+", get webid error, use local webid~")},timeout:3e5})},i.prototype.complete=function(e){var t=e.web_id,r=e.user_unique_id,n=e.device_id;if(e.timestamp=Date.now(),this.collect.configManager.set({web_id:t,user_unique_id:r}),this.config.enable_device_id){var s=this.configManager.get("device_id")||n||t;this.collect.configManager.set({device_id:s}),e=B(B({},e),{device_id:s})}else e!=null&&e.device_id&&delete e.device_id;this.setStorage(e),this.tokenReady=!0,this.collect.emit(g.DEBUGGER_MESSAGE,{type:g.DEBUGGER_MESSAGE_SDK,info:"SDK 完成用户信息设置",logType:"info",level:"info",time:Date.now(),data:{web_id:t,user_unique_id:r},infoType:"sdk"}),this.collect.emit(w.TokenComplete)},i.prototype.completeTtWid=function(e){var t=e.user_unique_id||"",r=this.configManager.get("user_unique_id");(r||t)&&this.configManager.set({user_unique_id:r||t}),this.setStorage(e),this.tokenReady=!0,this.collect.emit(w.TokenComplete)},i.prototype.setUuid=function(e){if(e&&["null","undefined","Null","None"].indexOf(e)===-1){var t=String(e),r=this.configManager.get("user_unique_id"),n=this.cacheToken&&this.cacheToken.user_unique_id;if(t===r&&t===n)return;this.configManager.set({user_unique_id:t}),this.cacheToken?this.cacheToken.user_unique_id=t:(this.cacheToken={},this.cacheToken.user_unique_id=t),this.cacheToken.timestamp=Date.now(),this.setStorage(this.cacheToken),this.collect.emit(w.TokenChange,"uuid"),this.collect.emit(w.SessionReset)}else this.clearUuid()},i.prototype.clearUuid=function(){this.config.enable_ttwebid||this.configManager.get("web_id")&&this.configManager.get("user_unique_id")!==this.configManager.get("web_id")&&(this.configManager.set({user_unique_id:this.configManager.get("web_id")}),this.cacheToken&&this.cacheToken.web_id&&(this.cacheToken.user_unique_id=this.cacheToken.web_id,this.cacheToken.timestamp=Date.now(),this.setStorage(this.cacheToken)),this.collect.emit(w.TokenReset,"uuid"))},i.prototype.setWebId=function(e){if(e&&!this.config.enable_ttwebid){this.cacheToken&&this.cacheToken.web_id?this.cacheToken.web_id!==e&&(this.cacheToken.user_unique_id=this.cacheToken.web_id===this.cacheToken.user_unique_id?e:this.cacheToken.user_unique_id,this.cacheToken.web_id=e):(this.cacheToken={},this.cacheToken.web_id=e,this.cacheToken.user_unique_id=e),this.cacheToken.timestamp=Date.now();var t=this.configManager.get("web_id"),r=this.configManager.get("user_unique_id");r&&r!==t||(this.configManager.set({user_unique_id:e}),this.collect.emit(w.TokenChange,"uuid")),t!==e&&(this.configManager.set({web_id:e}),this.collect.emit(w.TokenChange,"webid")),this.setStorage(this.cacheToken)}},i.prototype.setDeviceId=function(e){this.configManager.set({device_id:e}),this.config.enable_device_id&&this.cacheToken&&(this.cacheToken.device_id=e,this.cacheToken.timestamp=Date.now(),this.setStorage(this.cacheToken))},i.prototype.setStorage=function(e){e._type_=this.enableCustomWebid?"custom":"default",delete e["diss".split("").reverse().join("")],this.enableCookie||this.enable_ttwebid?(this.storage.setCookie(this.tokenKey,e,this.expiresTime,this.cookieDomain),this.enable_ttwebid&&(delete e.web_id,this.storage.setItem(this.tokenKey,e))):this.storage.setItem(this.tokenKey,e),this.cacheToken=e},i.prototype.getReady=function(){return this.tokenReady},i.prototype.getTobId=function(){var e=this;return new Promise(function(t){var r={app_id:e.config.app_id,user_unique_id:e.configManager.get("user_unique_id"),web_id:e.configManager.get("web_id"),user_unique_id_type:e.configManager.get("user_unique_id_type")};e.collect.emit(g.DEBUGGER_MESSAGE,{type:g.DEBUGGER_MESSAGE_SDK,info:"SDK 发起GetToken请求",logType:"fetch",level:"info",time:Date.now(),data:r,infoType:"sdk"}),e.collect.requestManager.useRequest({url:e.configManager.getUrl("tobid"),data:r,success:function(n){n&&n.e===0?(t(n.tobid),e.collect.emit(g.DEBUGGER_MESSAGE,{type:g.DEBUGGER_MESSAGE_SDK,info:"GetToken请求成功",logType:"fetch",level:"info",time:Date.now(),data:n,infoType:"sdk"})):(t(""),e.collect.emit(g.DEBUGGER_MESSAGE,{type:g.DEBUGGER_MESSAGE_SDK,info:"GetToken请求失败",logType:"fetch",level:"error",time:Date.now(),data:n,infoType:"sdk"}))},fail:function(){t(""),e.collect.emit(g.DEBUGGER_MESSAGE,{type:g.DEBUGGER_MESSAGE_SDK,info:"GetToken请求失败",logType:"fetch",level:"error",time:Date.now(),infoType:"sdk"})},time:3e4,withCredentials:e.enable_ttwebid})})},i}();function xt(i){for(var e=i.length;--e>=0;)i[e]=0}var nn=new Uint8Array([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0]),Ji=new Uint8Array([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13]),rm=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7]),Bo=new Uint8Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),He=new Array(576);xt(He);var ri=new Array(60);xt(ri);var ni=new Array(512);xt(ni);var si=new Array(256);xt(si);var sn=new Array(29);xt(sn);var Vo,Fo,jo,Xi=new Array(30);function on(i,e,t,r,n){this.static_tree=i,this.extra_bits=e,this.extra_base=t,this.elems=r,this.max_length=n,this.has_stree=i&&i.length}function an(i,e){this.dyn_tree=i,this.max_code=0,this.stat_desc=e}xt(Xi);var Ho=function(i){return i<256?ni[i]:ni[256+(i>>>7)]},oi=function(i,e){i.pending_buf[i.pending++]=255&e,i.pending_buf[i.pending++]=e>>>8&255},le=function(i,e,t){i.bi_valid>16-t?(i.bi_buf|=e<<i.bi_valid&65535,oi(i,i.bi_buf),i.bi_buf=e>>16-i.bi_valid,i.bi_valid+=t-16):(i.bi_buf|=e<<i.bi_valid&65535,i.bi_valid+=t)},De=function(i,e,t){le(i,t[2*e],t[2*e+1])},$o=function(i,e){var t=0;do t|=1&i,i>>>=1,t<<=1;while(--e>0);return t>>>1},qo=function(i,e,t){var r,n,s=new Array(16),a=0;for(r=1;r<=15;r++)a=a+t[r-1]<<1,s[r]=a;for(n=0;n<=e;n++){var o=i[2*n+1];o!==0&&(i[2*n]=$o(s[o]++,o))}},Ko=function(i){var e;for(e=0;e<286;e++)i.dyn_ltree[2*e]=0;for(e=0;e<30;e++)i.dyn_dtree[2*e]=0;for(e=0;e<19;e++)i.bl_tree[2*e]=0;i.dyn_ltree[512]=1,i.opt_len=i.static_len=0,i.sym_next=i.matches=0},Wo=function(i){i.bi_valid>8?oi(i,i.bi_buf):i.bi_valid>0&&(i.pending_buf[i.pending++]=i.bi_buf),i.bi_buf=0,i.bi_valid=0},Jo=function(i,e,t,r){var n=2*e,s=2*t;return i[n]<i[s]||i[n]===i[s]&&r[e]<=r[t]},cn=function(i,e,t){for(var r=i.heap[t],n=t<<1;n<=i.heap_len&&(n<i.heap_len&&Jo(e,i.heap[n+1],i.heap[n],i.depth)&&n++,!Jo(e,r,i.heap[n],i.depth));)i.heap[t]=i.heap[n],t=n,n<<=1;i.heap[t]=r},Xo=function(i,e,t){var r,n,s,a,o=0;if(i.sym_next!==0)do r=255&i.pending_buf[i.sym_buf+o++],r+=(255&i.pending_buf[i.sym_buf+o++])<<8,n=i.pending_buf[i.sym_buf+o++],r===0?De(i,n,e):(s=si[n],De(i,s+256+1,e),(a=nn[s])!==0&&(n-=sn[s],le(i,n,a)),s=Ho(--r),De(i,s,t),(a=Ji[s])!==0&&(r-=Xi[s],le(i,r,a)));while(o<i.sym_next);De(i,256,e)},un=function(i,e){var t,r,n,s=e.dyn_tree,a=e.stat_desc.static_tree,o=e.stat_desc.has_stree,d=e.stat_desc.elems,c=-1;for(i.heap_len=0,i.heap_max=573,t=0;t<d;t++)s[2*t]!==0?(i.heap[++i.heap_len]=c=t,i.depth[t]=0):s[2*t+1]=0;for(;i.heap_len<2;)s[2*(n=i.heap[++i.heap_len]=c<2?++c:0)]=1,i.depth[n]=0,i.opt_len--,o&&(i.static_len-=a[2*n+1]);for(e.max_code=c,t=i.heap_len>>1;t>=1;t--)cn(i,s,t);n=d;do t=i.heap[1],i.heap[1]=i.heap[i.heap_len--],cn(i,s,1),r=i.heap[1],i.heap[--i.heap_max]=t,i.heap[--i.heap_max]=r,s[2*n]=s[2*t]+s[2*r],i.depth[n]=(i.depth[t]>=i.depth[r]?i.depth[t]:i.depth[r])+1,s[2*t+1]=s[2*r+1]=n,i.heap[1]=n++,cn(i,s,1);while(i.heap_len>=2);i.heap[--i.heap_max]=i.heap[1],function(u,l){var h,p,f,v,m,b,y=l.dyn_tree,_=l.max_code,E=l.stat_desc.static_tree,z=l.stat_desc.has_stree,T=l.stat_desc.extra_bits,x=l.stat_desc.extra_base,R=l.stat_desc.max_length,A=0;for(v=0;v<=15;v++)u.bl_count[v]=0;for(y[2*u.heap[u.heap_max]+1]=0,h=u.heap_max+1;h<573;h++)(v=y[2*y[2*(p=u.heap[h])+1]+1]+1)>R&&(v=R,A++),y[2*p+1]=v,p>_||(u.bl_count[v]++,m=0,p>=x&&(m=T[p-x]),b=y[2*p],u.opt_len+=b*(v+m),z&&(u.static_len+=b*(E[2*p+1]+m)));if(A!==0){do{for(v=R-1;u.bl_count[v]===0;)v--;u.bl_count[v]--,u.bl_count[v+1]+=2,u.bl_count[R]--,A-=2}while(A>0);for(v=R;v!==0;v--)for(p=u.bl_count[v];p!==0;)(f=u.heap[--h])>_||(y[2*f+1]!==v&&(u.opt_len+=(v-y[2*f+1])*y[2*f],y[2*f+1]=v),p--)}}(i,e),qo(s,c,i.bl_count)},Zo=function(i,e,t){var r,n,s=-1,a=e[1],o=0,d=7,c=4;for(a===0&&(d=138,c=3),e[2*(t+1)+1]=65535,r=0;r<=t;r++)n=a,a=e[2*(r+1)+1],++o<d&&n===a||(o<c?i.bl_tree[2*n]+=o:n!==0?(n!==s&&i.bl_tree[2*n]++,i.bl_tree[32]++):o<=10?i.bl_tree[34]++:i.bl_tree[36]++,o=0,s=n,a===0?(d=138,c=3):n===a?(d=6,c=3):(d=7,c=4))},Qo=function(i,e,t){var r,n,s=-1,a=e[1],o=0,d=7,c=4;for(a===0&&(d=138,c=3),r=0;r<=t;r++)if(n=a,a=e[2*(r+1)+1],!(++o<d&&n===a)){if(o<c)do De(i,n,i.bl_tree);while(--o!=0);else n!==0?(n!==s&&(De(i,n,i.bl_tree),o--),De(i,16,i.bl_tree),le(i,o-3,2)):o<=10?(De(i,17,i.bl_tree),le(i,o-3,3)):(De(i,18,i.bl_tree),le(i,o-11,7));o=0,s=n,a===0?(d=138,c=3):n===a?(d=6,c=3):(d=7,c=4)}},Yo=!1,ea=function(i,e,t,r){le(i,0+(r?1:0),3),Wo(i),oi(i,t),oi(i,~t),t&&i.pending_buf.set(i.window.subarray(e,e+t),i.pending),i.pending+=t},ai={_tr_init:function(i){Yo||(function(){var e,t,r,n,s,a=new Array(16);for(r=0,n=0;n<28;n++)for(sn[n]=r,e=0;e<1<<nn[n];e++)si[r++]=n;for(si[r-1]=n,s=0,n=0;n<16;n++)for(Xi[n]=s,e=0;e<1<<Ji[n];e++)ni[s++]=n;for(s>>=7;n<30;n++)for(Xi[n]=s<<7,e=0;e<1<<Ji[n]-7;e++)ni[256+s++]=n;for(t=0;t<=15;t++)a[t]=0;for(e=0;e<=143;)He[2*e+1]=8,e++,a[8]++;for(;e<=255;)He[2*e+1]=9,e++,a[9]++;for(;e<=279;)He[2*e+1]=7,e++,a[7]++;for(;e<=287;)He[2*e+1]=8,e++,a[8]++;for(qo(He,287,a),e=0;e<30;e++)ri[2*e+1]=5,ri[2*e]=$o(e,5);Vo=new on(He,nn,257,286,15),Fo=new on(ri,Ji,0,30,15),jo=new on(new Array(0),rm,0,19,7)}(),Yo=!0),i.l_desc=new an(i.dyn_ltree,Vo),i.d_desc=new an(i.dyn_dtree,Fo),i.bl_desc=new an(i.bl_tree,jo),i.bi_buf=0,i.bi_valid=0,Ko(i)},_tr_stored_block:ea,_tr_flush_block:function(i,e,t,r){var n,s,a=0;i.level>0?(i.strm.data_type===2&&(i.strm.data_type=function(o){var d,c=4093624447;for(d=0;d<=31;d++,c>>>=1)if(1&c&&o.dyn_ltree[2*d]!==0)return 0;if(o.dyn_ltree[18]!==0||o.dyn_ltree[20]!==0||o.dyn_ltree[26]!==0)return 1;for(d=32;d<256;d++)if(o.dyn_ltree[2*d]!==0)return 1;return 0}(i)),un(i,i.l_desc),un(i,i.d_desc),a=function(o){var d;for(Zo(o,o.dyn_ltree,o.l_desc.max_code),Zo(o,o.dyn_dtree,o.d_desc.max_code),un(o,o.bl_desc),d=18;d>=3&&o.bl_tree[2*Bo[d]+1]===0;d--);return o.opt_len+=3*(d+1)+5+5+4,d}(i),n=i.opt_len+3+7>>>3,(s=i.static_len+3+7>>>3)<=n&&(n=s)):n=s=t+5,t+4<=n&&e!==-1?ea(i,e,t,r):i.strategy===4||s===n?(le(i,2+(r?1:0),3),Xo(i,He,ri)):(le(i,4+(r?1:0),3),function(o,d,c,u){var l;for(le(o,d-257,5),le(o,c-1,5),le(o,u-4,4),l=0;l<u;l++)le(o,o.bl_tree[2*Bo[l]+1],3);Qo(o,o.dyn_ltree,d-1),Qo(o,o.dyn_dtree,c-1)}(i,i.l_desc.max_code+1,i.d_desc.max_code+1,a+1),Xo(i,i.dyn_ltree,i.dyn_dtree)),Ko(i),r&&Wo(i)},_tr_tally:function(i,e,t){return i.pending_buf[i.sym_buf+i.sym_next++]=e,i.pending_buf[i.sym_buf+i.sym_next++]=e>>8,i.pending_buf[i.sym_buf+i.sym_next++]=t,e===0?i.dyn_ltree[2*t]++:(i.matches++,e--,i.dyn_ltree[2*(si[t]+256+1)]++,i.dyn_dtree[2*Ho(e)]++),i.sym_next===i.sym_end},_tr_align:function(i){le(i,2,3),De(i,256,He),function(e){e.bi_valid===16?(oi(e,e.bi_buf),e.bi_buf=0,e.bi_valid=0):e.bi_valid>=8&&(e.pending_buf[e.pending++]=255&e.bi_buf,e.bi_buf>>=8,e.bi_valid-=8)}(i)}},ci=function(i,e,t,r){for(var n=65535&i|0,s=i>>>16&65535|0,a=0;t!==0;){t-=a=t>2e3?2e3:t;do s=s+(n=n+e[r++]|0)|0;while(--a);n%=65521,s%=65521}return n|s<<16|0},nm=new Uint32Array(function(){for(var i,e=[],t=0;t<256;t++){i=t;for(var r=0;r<8;r++)i=1&i?3988292384^i>>>1:i>>>1;e[t]=i}return e}()),ie=function(i,e,t,r){var n=nm,s=r+t;i^=-1;for(var a=r;a<s;a++)i=i>>>8^n[255&(i^e[a])];return-1^i},mt={2:"need dictionary",1:"stream end",0:"","-1":"file error","-2":"stream error","-3":"data error","-4":"insufficient memory","-5":"buffer error","-6":"incompatible version"},M={Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_TREES:6,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_ERRNO:-1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_MEM_ERROR:-4,Z_BUF_ERROR:-5,Z_NO_COMPRESSION:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,Z_BINARY:0,Z_TEXT:1,Z_UNKNOWN:2,Z_DEFLATED:8},sm=ai._tr_init,dn=ai._tr_stored_block,om=ai._tr_flush_block,Ye=ai._tr_tally,am=ai._tr_align,et=M.Z_NO_FLUSH,cm=M.Z_PARTIAL_FLUSH,um=M.Z_FULL_FLUSH,ve=M.Z_FINISH,ta=M.Z_BLOCK,oe=M.Z_OK,ia=M.Z_STREAM_END,xe=M.Z_STREAM_ERROR,dm=M.Z_DATA_ERROR,hn=M.Z_BUF_ERROR,hm=M.Z_DEFAULT_COMPRESSION,lm=M.Z_FILTERED,Zi=M.Z_HUFFMAN_ONLY,pm=M.Z_RLE,fm=M.Z_FIXED,mm=M.Z_DEFAULT_STRATEGY,_m=M.Z_UNKNOWN,Qi=M.Z_DEFLATED,ln=286,gm=30,vm=19,ym=2*ln+1,bm=15,_t=function(i,e){return i.msg=mt[e],e},ra=function(i){return 2*i-(i>4?9:0)},tt=function(i){for(var e=i.length;--e>=0;)i[e]=0},Sm=function(i){var e,t,r,n=i.w_size;r=e=i.hash_size;do t=i.head[--r],i.head[r]=t>=n?t-n:0;while(--e);r=e=n;do t=i.prev[--r],i.prev[r]=t>=n?t-n:0;while(--e)},it=function(i,e,t){return(e<<i.hash_shift^t)&i.hash_mask},_e=function(i){var e=i.state,t=e.pending;t>i.avail_out&&(t=i.avail_out),t!==0&&(i.output.set(e.pending_buf.subarray(e.pending_out,e.pending_out+t),i.next_out),i.next_out+=t,e.pending_out+=t,i.total_out+=t,i.avail_out-=t,e.pending-=t,e.pending===0&&(e.pending_out=0))},ge=function(i,e){om(i,i.block_start>=0?i.block_start:-1,i.strstart-i.block_start,e),i.block_start=i.strstart,_e(i.strm)},F=function(i,e){i.pending_buf[i.pending++]=e},ui=function(i,e){i.pending_buf[i.pending++]=e>>>8&255,i.pending_buf[i.pending++]=255&e},pn=function(i,e,t,r){var n=i.avail_in;return n>r&&(n=r),n===0?0:(i.avail_in-=n,e.set(i.input.subarray(i.next_in,i.next_in+n),t),i.state.wrap===1?i.adler=ci(i.adler,e,n,t):i.state.wrap===2&&(i.adler=ie(i.adler,e,n,t)),i.next_in+=n,i.total_in+=n,n)},na=function(i,e){var t,r,n=i.max_chain_length,s=i.strstart,a=i.prev_length,o=i.nice_match,d=i.strstart>i.w_size-262?i.strstart-(i.w_size-262):0,c=i.window,u=i.w_mask,l=i.prev,h=i.strstart+258,p=c[s+a-1],f=c[s+a];i.prev_length>=i.good_match&&(n>>=2),o>i.lookahead&&(o=i.lookahead);do if(c[(t=e)+a]===f&&c[t+a-1]===p&&c[t]===c[s]&&c[++t]===c[s+1]){s+=2,t++;do;while(c[++s]===c[++t]&&c[++s]===c[++t]&&c[++s]===c[++t]&&c[++s]===c[++t]&&c[++s]===c[++t]&&c[++s]===c[++t]&&c[++s]===c[++t]&&c[++s]===c[++t]&&s<h);if(r=258-(h-s),s=h-258,r>a){if(i.match_start=e,a=r,r>=o)break;p=c[s+a-1],f=c[s+a]}}while((e=l[e&u])>d&&--n!=0);return a<=i.lookahead?a:i.lookahead},It=function(i){var e,t,r,n=i.w_size;do{if(t=i.window_size-i.lookahead-i.strstart,i.strstart>=n+(n-262)&&(i.window.set(i.window.subarray(n,n+n-t),0),i.match_start-=n,i.strstart-=n,i.block_start-=n,i.insert>i.strstart&&(i.insert=i.strstart),Sm(i),t+=n),i.strm.avail_in===0)break;if(e=pn(i.strm,i.window,i.strstart+i.lookahead,t),i.lookahead+=e,i.lookahead+i.insert>=3)for(r=i.strstart-i.insert,i.ins_h=i.window[r],i.ins_h=it(i,i.ins_h,i.window[r+1]);i.insert&&(i.ins_h=it(i,i.ins_h,i.window[r+3-1]),i.prev[r&i.w_mask]=i.head[i.ins_h],i.head[i.ins_h]=r,r++,i.insert--,!(i.lookahead+i.insert<3)););}while(i.lookahead<262&&i.strm.avail_in!==0)},sa=function(i,e){var t,r,n,s=i.pending_buf_size-5>i.w_size?i.w_size:i.pending_buf_size-5,a=0,o=i.strm.avail_in;do{if(t=65535,n=i.bi_valid+42>>3,i.strm.avail_out<n||(n=i.strm.avail_out-n,t>(r=i.strstart-i.block_start)+i.strm.avail_in&&(t=r+i.strm.avail_in),t>n&&(t=n),t<s&&(t===0&&e!==ve||e===et||t!==r+i.strm.avail_in)))break;a=e===ve&&t===r+i.strm.avail_in?1:0,dn(i,0,0,a),i.pending_buf[i.pending-4]=t,i.pending_buf[i.pending-3]=t>>8,i.pending_buf[i.pending-2]=~t,i.pending_buf[i.pending-1]=~t>>8,_e(i.strm),r&&(r>t&&(r=t),i.strm.output.set(i.window.subarray(i.block_start,i.block_start+r),i.strm.next_out),i.strm.next_out+=r,i.strm.avail_out-=r,i.strm.total_out+=r,i.block_start+=r,t-=r),t&&(pn(i.strm,i.strm.output,i.strm.next_out,t),i.strm.next_out+=t,i.strm.avail_out-=t,i.strm.total_out+=t)}while(a===0);return(o-=i.strm.avail_in)&&(o>=i.w_size?(i.matches=2,i.window.set(i.strm.input.subarray(i.strm.next_in-i.w_size,i.strm.next_in),0),i.strstart=i.w_size,i.insert=i.strstart):(i.window_size-i.strstart<=o&&(i.strstart-=i.w_size,i.window.set(i.window.subarray(i.w_size,i.w_size+i.strstart),0),i.matches<2&&i.matches++,i.insert>i.strstart&&(i.insert=i.strstart)),i.window.set(i.strm.input.subarray(i.strm.next_in-o,i.strm.next_in),i.strstart),i.strstart+=o,i.insert+=o>i.w_size-i.insert?i.w_size-i.insert:o),i.block_start=i.strstart),i.high_water<i.strstart&&(i.high_water=i.strstart),a?4:e!==et&&e!==ve&&i.strm.avail_in===0&&i.strstart===i.block_start?2:(n=i.window_size-i.strstart,i.strm.avail_in>n&&i.block_start>=i.w_size&&(i.block_start-=i.w_size,i.strstart-=i.w_size,i.window.set(i.window.subarray(i.w_size,i.w_size+i.strstart),0),i.matches<2&&i.matches++,n+=i.w_size,i.insert>i.strstart&&(i.insert=i.strstart)),n>i.strm.avail_in&&(n=i.strm.avail_in),n&&(pn(i.strm,i.window,i.strstart,n),i.strstart+=n,i.insert+=n>i.w_size-i.insert?i.w_size-i.insert:n),i.high_water<i.strstart&&(i.high_water=i.strstart),n=i.bi_valid+42>>3,s=(n=i.pending_buf_size-n>65535?65535:i.pending_buf_size-n)>i.w_size?i.w_size:n,((r=i.strstart-i.block_start)>=s||(r||e===ve)&&e!==et&&i.strm.avail_in===0&&r<=n)&&(t=r>n?n:r,a=e===ve&&i.strm.avail_in===0&&t===r?1:0,dn(i,i.block_start,t,a),i.block_start+=t,_e(i.strm)),a?3:1)},fn=function(i,e){for(var t,r;;){if(i.lookahead<262){if(It(i),i.lookahead<262&&e===et)return 1;if(i.lookahead===0)break}if(t=0,i.lookahead>=3&&(i.ins_h=it(i,i.ins_h,i.window[i.strstart+3-1]),t=i.prev[i.strstart&i.w_mask]=i.head[i.ins_h],i.head[i.ins_h]=i.strstart),t!==0&&i.strstart-t<=i.w_size-262&&(i.match_length=na(i,t)),i.match_length>=3)if(r=Ye(i,i.strstart-i.match_start,i.match_length-3),i.lookahead-=i.match_length,i.match_length<=i.max_lazy_match&&i.lookahead>=3){i.match_length--;do i.strstart++,i.ins_h=it(i,i.ins_h,i.window[i.strstart+3-1]),t=i.prev[i.strstart&i.w_mask]=i.head[i.ins_h],i.head[i.ins_h]=i.strstart;while(--i.match_length!=0);i.strstart++}else i.strstart+=i.match_length,i.match_length=0,i.ins_h=i.window[i.strstart],i.ins_h=it(i,i.ins_h,i.window[i.strstart+1]);else r=Ye(i,0,i.window[i.strstart]),i.lookahead--,i.strstart++;if(r&&(ge(i,!1),i.strm.avail_out===0))return 1}return i.insert=i.strstart<2?i.strstart:2,e===ve?(ge(i,!0),i.strm.avail_out===0?3:4):i.sym_next&&(ge(i,!1),i.strm.avail_out===0)?1:2},Ot=function(i,e){for(var t,r,n;;){if(i.lookahead<262){if(It(i),i.lookahead<262&&e===et)return 1;if(i.lookahead===0)break}if(t=0,i.lookahead>=3&&(i.ins_h=it(i,i.ins_h,i.window[i.strstart+3-1]),t=i.prev[i.strstart&i.w_mask]=i.head[i.ins_h],i.head[i.ins_h]=i.strstart),i.prev_length=i.match_length,i.prev_match=i.match_start,i.match_length=2,t!==0&&i.prev_length<i.max_lazy_match&&i.strstart-t<=i.w_size-262&&(i.match_length=na(i,t),i.match_length<=5&&(i.strategy===lm||i.match_length===3&&i.strstart-i.match_start>4096)&&(i.match_length=2)),i.prev_length>=3&&i.match_length<=i.prev_length){n=i.strstart+i.lookahead-3,r=Ye(i,i.strstart-1-i.prev_match,i.prev_length-3),i.lookahead-=i.prev_length-1,i.prev_length-=2;do++i.strstart<=n&&(i.ins_h=it(i,i.ins_h,i.window[i.strstart+3-1]),t=i.prev[i.strstart&i.w_mask]=i.head[i.ins_h],i.head[i.ins_h]=i.strstart);while(--i.prev_length!=0);if(i.match_available=0,i.match_length=2,i.strstart++,r&&(ge(i,!1),i.strm.avail_out===0))return 1}else if(i.match_available){if((r=Ye(i,0,i.window[i.strstart-1]))&&ge(i,!1),i.strstart++,i.lookahead--,i.strm.avail_out===0)return 1}else i.match_available=1,i.strstart++,i.lookahead--}return i.match_available&&(r=Ye(i,0,i.window[i.strstart-1]),i.match_available=0),i.insert=i.strstart<2?i.strstart:2,e===ve?(ge(i,!0),i.strm.avail_out===0?3:4):i.sym_next&&(ge(i,!1),i.strm.avail_out===0)?1:2};function Ie(i,e,t,r,n){this.good_length=i,this.max_lazy=e,this.nice_length=t,this.max_chain=r,this.func=n}var di=[new Ie(0,0,0,0,sa),new Ie(4,4,8,4,fn),new Ie(4,5,16,8,fn),new Ie(4,6,32,32,fn),new Ie(4,4,16,16,Ot),new Ie(8,16,32,32,Ot),new Ie(8,16,128,128,Ot),new Ie(8,32,128,256,Ot),new Ie(32,128,258,1024,Ot),new Ie(32,258,258,4096,Ot)];function Em(){this.strm=null,this.status=0,this.pending_buf=null,this.pending_buf_size=0,this.pending_out=0,this.pending=0,this.wrap=0,this.gzhead=null,this.gzindex=0,this.method=Qi,this.last_flush=-1,this.w_size=0,this.w_bits=0,this.w_mask=0,this.window=null,this.window_size=0,this.prev=null,this.head=null,this.ins_h=0,this.hash_size=0,this.hash_bits=0,this.hash_mask=0,this.hash_shift=0,this.block_start=0,this.match_length=0,this.prev_match=0,this.match_available=0,this.strstart=0,this.match_start=0,this.lookahead=0,this.prev_length=0,this.max_chain_length=0,this.max_lazy_match=0,this.level=0,this.strategy=0,this.good_match=0,this.nice_match=0,this.dyn_ltree=new Uint16Array(2*ym),this.dyn_dtree=new Uint16Array(2*(2*gm+1)),this.bl_tree=new Uint16Array(2*(2*vm+1)),tt(this.dyn_ltree),tt(this.dyn_dtree),tt(this.bl_tree),this.l_desc=null,this.d_desc=null,this.bl_desc=null,this.bl_count=new Uint16Array(bm+1),this.heap=new Uint16Array(2*ln+1),tt(this.heap),this.heap_len=0,this.heap_max=0,this.depth=new Uint16Array(2*ln+1),tt(this.depth),this.sym_buf=0,this.lit_bufsize=0,this.sym_next=0,this.sym_end=0,this.opt_len=0,this.static_len=0,this.matches=0,this.insert=0,this.bi_buf=0,this.bi_valid=0}var hi=function(i){if(!i)return 1;var e=i.state;return!e||e.strm!==i||e.status!==42&&e.status!==57&&e.status!==69&&e.status!==73&&e.status!==91&&e.status!==103&&e.status!==113&&e.status!==666?1:0},oa=function(i){if(hi(i))return _t(i,xe);i.total_in=i.total_out=0,i.data_type=_m;var e=i.state;return e.pending=0,e.pending_out=0,e.wrap<0&&(e.wrap=-e.wrap),e.status=e.wrap===2?57:e.wrap?42:113,i.adler=e.wrap===2?0:1,e.last_flush=-2,sm(e),oe},aa=function(i){var e,t=oa(i);return t===oe&&((e=i.state).window_size=2*e.w_size,tt(e.head),e.max_lazy_match=di[e.level].max_lazy,e.good_match=di[e.level].good_length,e.nice_match=di[e.level].nice_length,e.max_chain_length=di[e.level].max_chain,e.strstart=0,e.block_start=0,e.lookahead=0,e.insert=0,e.match_length=e.prev_length=2,e.match_available=0,e.ins_h=0),t},ca=function(i,e,t,r,n,s){if(!i)return xe;var a=1;if(e===hm&&(e=6),r<0?(a=0,r=-r):r>15&&(a=2,r-=16),n<1||n>9||t!==Qi||r<8||r>15||e<0||e>9||s<0||s>fm||r===8&&a!==1)return _t(i,xe);r===8&&(r=9);var o=new Em;return i.state=o,o.strm=i,o.status=42,o.wrap=a,o.gzhead=null,o.w_bits=r,o.w_size=1<<o.w_bits,o.w_mask=o.w_size-1,o.hash_bits=n+7,o.hash_size=1<<o.hash_bits,o.hash_mask=o.hash_size-1,o.hash_shift=~~((o.hash_bits+3-1)/3),o.window=new Uint8Array(2*o.w_size),o.head=new Uint16Array(o.hash_size),o.prev=new Uint16Array(o.w_size),o.lit_bufsize=1<<n+6,o.pending_buf_size=4*o.lit_bufsize,o.pending_buf=new Uint8Array(o.pending_buf_size),o.sym_buf=o.lit_bufsize,o.sym_end=3*(o.lit_bufsize-1),o.level=e,o.strategy=s,o.method=t,aa(i)},li={deflateInit:function(i,e){return ca(i,e,Qi,15,8,mm)},deflateInit2:ca,deflateReset:aa,deflateResetKeep:oa,deflateSetHeader:function(i,e){return hi(i)||i.state.wrap!==2?xe:(i.state.gzhead=e,oe)},deflate:function(i,e){if(hi(i)||e>ta||e<0)return i?_t(i,xe):xe;var t=i.state;if(!i.output||i.avail_in!==0&&!i.input||t.status===666&&e!==ve)return _t(i,i.avail_out===0?hn:xe);var r=t.last_flush;if(t.last_flush=e,t.pending!==0){if(_e(i),i.avail_out===0)return t.last_flush=-1,oe}else if(i.avail_in===0&&ra(e)<=ra(r)&&e!==ve)return _t(i,hn);if(t.status===666&&i.avail_in!==0)return _t(i,hn);if(t.status===42&&t.wrap===0&&(t.status=113),t.status===42){var n=Qi+(t.w_bits-8<<4)<<8;if(n|=(t.strategy>=Zi||t.level<2?0:t.level<6?1:t.level===6?2:3)<<6,t.strstart!==0&&(n|=32),ui(t,n+=31-n%31),t.strstart!==0&&(ui(t,i.adler>>>16),ui(t,65535&i.adler)),i.adler=1,t.status=113,_e(i),t.pending!==0)return t.last_flush=-1,oe}if(t.status===57){if(i.adler=0,F(t,31),F(t,139),F(t,8),t.gzhead)F(t,(t.gzhead.text?1:0)+(t.gzhead.hcrc?2:0)+(t.gzhead.extra?4:0)+(t.gzhead.name?8:0)+(t.gzhead.comment?16:0)),F(t,255&t.gzhead.time),F(t,t.gzhead.time>>8&255),F(t,t.gzhead.time>>16&255),F(t,t.gzhead.time>>24&255),F(t,t.level===9?2:t.strategy>=Zi||t.level<2?4:0),F(t,255&t.gzhead.os),t.gzhead.extra&&t.gzhead.extra.length&&(F(t,255&t.gzhead.extra.length),F(t,t.gzhead.extra.length>>8&255)),t.gzhead.hcrc&&(i.adler=ie(i.adler,t.pending_buf,t.pending,0)),t.gzindex=0,t.status=69;else if(F(t,0),F(t,0),F(t,0),F(t,0),F(t,0),F(t,t.level===9?2:t.strategy>=Zi||t.level<2?4:0),F(t,3),t.status=113,_e(i),t.pending!==0)return t.last_flush=-1,oe}if(t.status===69){if(t.gzhead.extra){for(var s=t.pending,a=(65535&t.gzhead.extra.length)-t.gzindex;t.pending+a>t.pending_buf_size;){var o=t.pending_buf_size-t.pending;if(t.pending_buf.set(t.gzhead.extra.subarray(t.gzindex,t.gzindex+o),t.pending),t.pending=t.pending_buf_size,t.gzhead.hcrc&&t.pending>s&&(i.adler=ie(i.adler,t.pending_buf,t.pending-s,s)),t.gzindex+=o,_e(i),t.pending!==0)return t.last_flush=-1,oe;s=0,a-=o}var d=new Uint8Array(t.gzhead.extra);t.pending_buf.set(d.subarray(t.gzindex,t.gzindex+a),t.pending),t.pending+=a,t.gzhead.hcrc&&t.pending>s&&(i.adler=ie(i.adler,t.pending_buf,t.pending-s,s)),t.gzindex=0}t.status=73}if(t.status===73){if(t.gzhead.name){var c,u=t.pending;do{if(t.pending===t.pending_buf_size){if(t.gzhead.hcrc&&t.pending>u&&(i.adler=ie(i.adler,t.pending_buf,t.pending-u,u)),_e(i),t.pending!==0)return t.last_flush=-1,oe;u=0}c=t.gzindex<t.gzhead.name.length?255&t.gzhead.name.charCodeAt(t.gzindex++):0,F(t,c)}while(c!==0);t.gzhead.hcrc&&t.pending>u&&(i.adler=ie(i.adler,t.pending_buf,t.pending-u,u)),t.gzindex=0}t.status=91}if(t.status===91){if(t.gzhead.comment){var l,h=t.pending;do{if(t.pending===t.pending_buf_size){if(t.gzhead.hcrc&&t.pending>h&&(i.adler=ie(i.adler,t.pending_buf,t.pending-h,h)),_e(i),t.pending!==0)return t.last_flush=-1,oe;h=0}l=t.gzindex<t.gzhead.comment.length?255&t.gzhead.comment.charCodeAt(t.gzindex++):0,F(t,l)}while(l!==0);t.gzhead.hcrc&&t.pending>h&&(i.adler=ie(i.adler,t.pending_buf,t.pending-h,h))}t.status=103}if(t.status===103){if(t.gzhead.hcrc){if(t.pending+2>t.pending_buf_size&&(_e(i),t.pending!==0))return t.last_flush=-1,oe;F(t,255&i.adler),F(t,i.adler>>8&255),i.adler=0}if(t.status=113,_e(i),t.pending!==0)return t.last_flush=-1,oe}if(i.avail_in!==0||t.lookahead!==0||e!==et&&t.status!==666){var p=t.level===0?sa(t,e):t.strategy===Zi?function(f,v){for(var m;;){if(f.lookahead===0&&(It(f),f.lookahead===0)){if(v===et)return 1;break}if(f.match_length=0,m=Ye(f,0,f.window[f.strstart]),f.lookahead--,f.strstart++,m&&(ge(f,!1),f.strm.avail_out===0))return 1}return f.insert=0,v===ve?(ge(f,!0),f.strm.avail_out===0?3:4):f.sym_next&&(ge(f,!1),f.strm.avail_out===0)?1:2}(t,e):t.strategy===pm?function(f,v){for(var m,b,y,_,E=f.window;;){if(f.lookahead<=258){if(It(f),f.lookahead<=258&&v===et)return 1;if(f.lookahead===0)break}if(f.match_length=0,f.lookahead>=3&&f.strstart>0&&(b=E[y=f.strstart-1])===E[++y]&&b===E[++y]&&b===E[++y]){_=f.strstart+258;do;while(b===E[++y]&&b===E[++y]&&b===E[++y]&&b===E[++y]&&b===E[++y]&&b===E[++y]&&b===E[++y]&&b===E[++y]&&y<_);f.match_length=258-(_-y),f.match_length>f.lookahead&&(f.match_length=f.lookahead)}if(f.match_length>=3?(m=Ye(f,1,f.match_length-3),f.lookahead-=f.match_length,f.strstart+=f.match_length,f.match_length=0):(m=Ye(f,0,f.window[f.strstart]),f.lookahead--,f.strstart++),m&&(ge(f,!1),f.strm.avail_out===0))return 1}return f.insert=0,v===ve?(ge(f,!0),f.strm.avail_out===0?3:4):f.sym_next&&(ge(f,!1),f.strm.avail_out===0)?1:2}(t,e):di[t.level].func(t,e);if(p!==3&&p!==4||(t.status=666),p===1||p===3)return i.avail_out===0&&(t.last_flush=-1),oe;if(p===2&&(e===cm?am(t):e!==ta&&(dn(t,0,0,!1),e===um&&(tt(t.head),t.lookahead===0&&(t.strstart=0,t.block_start=0,t.insert=0))),_e(i),i.avail_out===0))return t.last_flush=-1,oe}return e!==ve?oe:t.wrap<=0?ia:(t.wrap===2?(F(t,255&i.adler),F(t,i.adler>>8&255),F(t,i.adler>>16&255),F(t,i.adler>>24&255),F(t,255&i.total_in),F(t,i.total_in>>8&255),F(t,i.total_in>>16&255),F(t,i.total_in>>24&255)):(ui(t,i.adler>>>16),ui(t,65535&i.adler)),_e(i),t.wrap>0&&(t.wrap=-t.wrap),t.pending!==0?oe:ia)},deflateEnd:function(i){if(hi(i))return xe;var e=i.state.status;return i.state=null,e===113?_t(i,dm):oe},deflateSetDictionary:function(i,e){var t=e.length;if(hi(i))return xe;var r=i.state,n=r.wrap;if(n===2||n===1&&r.status!==42||r.lookahead)return xe;if(n===1&&(i.adler=ci(i.adler,e,t,0)),r.wrap=0,t>=r.w_size){n===0&&(tt(r.head),r.strstart=0,r.block_start=0,r.insert=0);var s=new Uint8Array(r.w_size);s.set(e.subarray(t-r.w_size,t),0),e=s,t=r.w_size}var a=i.avail_in,o=i.next_in,d=i.input;for(i.avail_in=t,i.next_in=0,i.input=e,It(r);r.lookahead>=3;){var c=r.strstart,u=r.lookahead-2;do r.ins_h=it(r,r.ins_h,r.window[c+3-1]),r.prev[c&r.w_mask]=r.head[r.ins_h],r.head[r.ins_h]=c,c++;while(--u);r.strstart=c,r.lookahead=2,It(r)}return r.strstart+=r.lookahead,r.block_start=r.strstart,r.insert=r.lookahead,r.lookahead=0,r.match_length=r.prev_length=2,r.match_available=0,i.next_in=o,i.input=d,i.avail_in=a,r.wrap=n,oe},deflateInfo:"pako deflate (from Nodeca project)"},wm=function(i,e){return Object.prototype.hasOwnProperty.call(i,e)},Yi={assign:function(i){for(var e=Array.prototype.slice.call(arguments,1);e.length;){var t=e.shift();if(t){if(typeof t!="object")throw new TypeError(t+"must be non-object");for(var r in t)wm(t,r)&&(i[r]=t[r])}}return i},flattenChunks:function(i){for(var e=0,t=0,r=i.length;t<r;t++)e+=i[t].length;for(var n=new Uint8Array(e),s=0,a=0,o=i.length;s<o;s++){var d=i[s];n.set(d,a),a+=d.length}return n}},ua=!0;try{String.fromCharCode.apply(null,new Uint8Array(1))}catch{ua=!1}for(var pi=new Uint8Array(256),rt=0;rt<256;rt++)pi[rt]=rt>=252?6:rt>=248?5:rt>=240?4:rt>=224?3:rt>=192?2:1;pi[254]=pi[254]=1;var fi={string2buf:function(i){if(typeof TextEncoder=="function"&&TextEncoder.prototype.encode)return new TextEncoder().encode(i);var e,t,r,n,s,a=i.length,o=0;for(n=0;n<a;n++)(64512&(t=i.charCodeAt(n)))==55296&&n+1<a&&(64512&(r=i.charCodeAt(n+1)))==56320&&(t=65536+(t-55296<<10)+(r-56320),n++),o+=t<128?1:t<2048?2:t<65536?3:4;for(e=new Uint8Array(o),s=0,n=0;s<o;n++)(64512&(t=i.charCodeAt(n)))==55296&&n+1<a&&(64512&(r=i.charCodeAt(n+1)))==56320&&(t=65536+(t-55296<<10)+(r-56320),n++),t<128?e[s++]=t:t<2048?(e[s++]=192|t>>>6,e[s++]=128|63&t):t<65536?(e[s++]=224|t>>>12,e[s++]=128|t>>>6&63,e[s++]=128|63&t):(e[s++]=240|t>>>18,e[s++]=128|t>>>12&63,e[s++]=128|t>>>6&63,e[s++]=128|63&t);return e},buf2string:function(i,e){var t,r,n=e||i.length;if(typeof TextDecoder=="function"&&TextDecoder.prototype.decode)return new TextDecoder().decode(i.subarray(0,e));var s=new Array(2*n);for(r=0,t=0;t<n;){var a=i[t++];if(a<128)s[r++]=a;else{var o=pi[a];if(o>4)s[r++]=65533,t+=o-1;else{for(a&=o===2?31:o===3?15:7;o>1&&t<n;)a=a<<6|63&i[t++],o--;o>1?s[r++]=65533:a<65536?s[r++]=a:(a-=65536,s[r++]=55296|a>>10&1023,s[r++]=56320|1023&a)}}}return function(d,c){if(c<65534&&d.subarray&&ua)return String.fromCharCode.apply(null,d.length===c?d:d.subarray(0,c));for(var u="",l=0;l<c;l++)u+=String.fromCharCode(d[l]);return u}(s,r)},utf8border:function(i,e){(e=e||i.length)>i.length&&(e=i.length);for(var t=e-1;t>=0&&(192&i[t])==128;)t--;return t<0||t===0?e:t+pi[i[t]]>e?t:e}},da=function(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg="",this.state=null,this.data_type=2,this.adler=0},ha=Object.prototype.toString,Cm=M.Z_NO_FLUSH,km=M.Z_SYNC_FLUSH,Tm=M.Z_FULL_FLUSH,zm=M.Z_FINISH,er=M.Z_OK,Am=M.Z_STREAM_END,Rm=M.Z_DEFAULT_COMPRESSION,Dm=M.Z_DEFAULT_STRATEGY,xm=M.Z_DEFLATED;function mi(i){this.options=Yi.assign({level:Rm,method:xm,chunkSize:16384,windowBits:15,memLevel:8,strategy:Dm},i||{});var e=this.options;e.raw&&e.windowBits>0?e.windowBits=-e.windowBits:e.gzip&&e.windowBits>0&&e.windowBits<16&&(e.windowBits+=16),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new da,this.strm.avail_out=0;var t=li.deflateInit2(this.strm,e.level,e.method,e.windowBits,e.memLevel,e.strategy);if(t!==er)throw new Error(mt[t]);if(e.header&&li.deflateSetHeader(this.strm,e.header),e.dictionary){var r;if(r=typeof e.dictionary=="string"?fi.string2buf(e.dictionary):ha.call(e.dictionary)==="[object ArrayBuffer]"?new Uint8Array(e.dictionary):e.dictionary,(t=li.deflateSetDictionary(this.strm,r))!==er)throw new Error(mt[t]);this._dict_set=!0}}function mn(i,e){var t=new mi(e);if(t.push(i,!0),t.err)throw t.msg||mt[t.err];return t.result}mi.prototype.push=function(i,e){var t,r,n=this.strm,s=this.options.chunkSize;if(this.ended)return!1;for(r=e===~~e?e:e===!0?zm:Cm,typeof i=="string"?n.input=fi.string2buf(i):ha.call(i)==="[object ArrayBuffer]"?n.input=new Uint8Array(i):n.input=i,n.next_in=0,n.avail_in=n.input.length;;)if(n.avail_out===0&&(n.output=new Uint8Array(s),n.next_out=0,n.avail_out=s),(r===km||r===Tm)&&n.avail_out<=6)this.onData(n.output.subarray(0,n.next_out)),n.avail_out=0;else{if((t=li.deflate(n,r))===Am)return n.next_out>0&&this.onData(n.output.subarray(0,n.next_out)),t=li.deflateEnd(this.strm),this.onEnd(t),this.ended=!0,t===er;if(n.avail_out!==0){if(r>0&&n.next_out>0)this.onData(n.output.subarray(0,n.next_out)),n.avail_out=0;else if(n.avail_in===0)break}else this.onData(n.output)}return!0},mi.prototype.onData=function(i){this.chunks.push(i)},mi.prototype.onEnd=function(i){i===er&&(this.result=Yi.flattenChunks(this.chunks)),this.chunks=[],this.err=i,this.msg=this.strm.msg};var tr={Deflate:mi,deflate:mn,deflateRaw:function(i,e){return(e=e||{}).raw=!0,mn(i,e)},gzip:function(i,e){return(e=e||{}).gzip=!0,mn(i,e)},constants:M},Im=function(i,e){var t,r,n,s,a,o,d,c,u,l,h,p,f,v,m,b,y,_,E,z,T,x,R,A,D=i.state;t=i.next_in,R=i.input,r=t+(i.avail_in-5),n=i.next_out,A=i.output,s=n-(e-i.avail_out),a=n+(i.avail_out-257),o=D.dmax,d=D.wsize,c=D.whave,u=D.wnext,l=D.window,h=D.hold,p=D.bits,f=D.lencode,v=D.distcode,m=(1<<D.lenbits)-1,b=(1<<D.distbits)-1;e:do{p<15&&(h+=R[t++]<<p,p+=8,h+=R[t++]<<p,p+=8),y=f[h&m];t:for(;;){if(h>>>=_=y>>>24,p-=_,(_=y>>>16&255)===0)A[n++]=65535&y;else{if(!(16&_)){if(!(64&_)){y=f[(65535&y)+(h&(1<<_)-1)];continue t}if(32&_){D.mode=16191;break e}i.msg="invalid literal/length code",D.mode=16209;break e}E=65535&y,(_&=15)&&(p<_&&(h+=R[t++]<<p,p+=8),E+=h&(1<<_)-1,h>>>=_,p-=_),p<15&&(h+=R[t++]<<p,p+=8,h+=R[t++]<<p,p+=8),y=v[h&b];i:for(;;){if(h>>>=_=y>>>24,p-=_,!(16&(_=y>>>16&255))){if(!(64&_)){y=v[(65535&y)+(h&(1<<_)-1)];continue i}i.msg="invalid distance code",D.mode=16209;break e}if(z=65535&y,p<(_&=15)&&(h+=R[t++]<<p,(p+=8)<_&&(h+=R[t++]<<p,p+=8)),(z+=h&(1<<_)-1)>o){i.msg="invalid distance too far back",D.mode=16209;break e}if(h>>>=_,p-=_,z>(_=n-s)){if((_=z-_)>c&&D.sane){i.msg="invalid distance too far back",D.mode=16209;break e}if(T=0,x=l,u===0){if(T+=d-_,_<E){E-=_;do A[n++]=l[T++];while(--_);T=n-z,x=A}}else if(u<_){if(T+=d+u-_,(_-=u)<E){E-=_;do A[n++]=l[T++];while(--_);if(T=0,u<E){E-=_=u;do A[n++]=l[T++];while(--_);T=n-z,x=A}}}else if(T+=u-_,_<E){E-=_;do A[n++]=l[T++];while(--_);T=n-z,x=A}for(;E>2;)A[n++]=x[T++],A[n++]=x[T++],A[n++]=x[T++],E-=3;E&&(A[n++]=x[T++],E>1&&(A[n++]=x[T++]))}else{T=n-z;do A[n++]=A[T++],A[n++]=A[T++],A[n++]=A[T++],E-=3;while(E>2);E&&(A[n++]=A[T++],E>1&&(A[n++]=A[T++]))}break}}break}}while(t<r&&n<a);t-=E=p>>3,h&=(1<<(p-=E<<3))-1,i.next_in=t,i.next_out=n,i.avail_in=t<r?r-t+5:5-(t-r),i.avail_out=n<a?a-n+257:257-(n-a),D.hold=h,D.bits=p},Om=new Uint16Array([3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258,0,0]),Mm=new Uint8Array([16,16,16,16,16,16,16,16,17,17,17,17,18,18,18,18,19,19,19,19,20,20,20,20,21,21,21,21,16,72,78]),Pm=new Uint16Array([1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,0,0]),Lm=new Uint8Array([16,16,16,16,17,17,18,18,19,19,20,20,21,21,22,22,23,23,24,24,25,25,26,26,27,27,28,28,29,29,64,64]),_i=function(i,e,t,r,n,s,a,o){var d,c,u,l,h,p,f,v,m,b=o.bits,y=0,_=0,E=0,z=0,T=0,x=0,R=0,A=0,D=0,P=0,K=null,H=new Uint16Array(16),J=new Uint16Array(16),X=null;for(y=0;y<=15;y++)H[y]=0;for(_=0;_<r;_++)H[e[t+_]]++;for(T=b,z=15;z>=1&&H[z]===0;z--);if(T>z&&(T=z),z===0)return n[s++]=20971520,n[s++]=20971520,o.bits=1,0;for(E=1;E<z&&H[E]===0;E++);for(T<E&&(T=E),A=1,y=1;y<=15;y++)if(A<<=1,(A-=H[y])<0)return-1;if(A>0&&(i===0||z!==1))return-1;for(J[1]=0,y=1;y<15;y++)J[y+1]=J[y]+H[y];for(_=0;_<r;_++)e[t+_]!==0&&(a[J[e[t+_]]++]=_);if(i===0?(K=X=a,p=20):i===1?(K=Om,X=Mm,p=257):(K=Pm,X=Lm,p=0),P=0,_=0,y=E,h=s,x=T,R=0,u=-1,l=(D=1<<T)-1,i===1&&D>852||i===2&&D>592)return 1;for(;;){f=y-R,a[_]+1<p?(v=0,m=a[_]):a[_]>=p?(v=X[a[_]-p],m=K[a[_]-p]):(v=96,m=0),d=1<<y-R,E=c=1<<x;do n[h+(P>>R)+(c-=d)]=f<<24|v<<16|m|0;while(c!==0);for(d=1<<y-1;P&d;)d>>=1;if(d!==0?(P&=d-1,P+=d):P=0,_++,--H[y]==0){if(y===z)break;y=e[t+a[_]]}if(y>T&&(P&l)!==u){for(R===0&&(R=T),h+=E,A=1<<(x=y-R);x+R<z&&!((A-=H[x+R])<=0);)x++,A<<=1;if(D+=1<<x,i===1&&D>852||i===2&&D>592)return 1;n[u=P&l]=T<<24|x<<16|h-s|0}}return P!==0&&(n[h+P]=y-R<<24|64<<16|0),o.bits=T,0},la=M.Z_FINISH,Um=M.Z_BLOCK,ir=M.Z_TREES,gt=M.Z_OK,Gm=M.Z_STREAM_END,Nm=M.Z_NEED_DICT,ye=M.Z_STREAM_ERROR,pa=M.Z_DATA_ERROR,fa=M.Z_MEM_ERROR,Bm=M.Z_BUF_ERROR,ma=M.Z_DEFLATED,_a=function(i){return(i>>>24&255)+(i>>>8&65280)+((65280&i)<<8)+((255&i)<<24)};function Vm(){this.strm=null,this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new Uint16Array(320),this.work=new Uint16Array(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}var _n,gn,vt=function(i){if(!i)return 1;var e=i.state;return!e||e.strm!==i||e.mode<16180||e.mode>16211?1:0},ga=function(i){if(vt(i))return ye;var e=i.state;return i.total_in=i.total_out=e.total=0,i.msg="",e.wrap&&(i.adler=1&e.wrap),e.mode=16180,e.last=0,e.havedict=0,e.flags=-1,e.dmax=32768,e.head=null,e.hold=0,e.bits=0,e.lencode=e.lendyn=new Int32Array(852),e.distcode=e.distdyn=new Int32Array(592),e.sane=1,e.back=-1,gt},va=function(i){if(vt(i))return ye;var e=i.state;return e.wsize=0,e.whave=0,e.wnext=0,ga(i)},ya=function(i,e){var t;if(vt(i))return ye;var r=i.state;return e<0?(t=0,e=-e):(t=5+(e>>4),e<48&&(e&=15)),e&&(e<8||e>15)?ye:(r.window!==null&&r.wbits!==e&&(r.window=null),r.wrap=t,r.wbits=e,va(i))},ba=function(i,e){if(!i)return ye;var t=new Vm;i.state=t,t.strm=i,t.window=null,t.mode=16180;var r=ya(i,e);return r!==gt&&(i.state=null),r},Sa=!0,Fm=function(i){if(Sa){_n=new Int32Array(512),gn=new Int32Array(32);for(var e=0;e<144;)i.lens[e++]=8;for(;e<256;)i.lens[e++]=9;for(;e<280;)i.lens[e++]=7;for(;e<288;)i.lens[e++]=8;for(_i(1,i.lens,0,288,_n,0,i.work,{bits:9}),e=0;e<32;)i.lens[e++]=5;_i(2,i.lens,0,32,gn,0,i.work,{bits:5}),Sa=!1}i.lencode=_n,i.lenbits=9,i.distcode=gn,i.distbits=5},Ea=function(i,e,t,r){var n,s=i.state;return s.window===null&&(s.wsize=1<<s.wbits,s.wnext=0,s.whave=0,s.window=new Uint8Array(s.wsize)),r>=s.wsize?(s.window.set(e.subarray(t-s.wsize,t),0),s.wnext=0,s.whave=s.wsize):((n=s.wsize-s.wnext)>r&&(n=r),s.window.set(e.subarray(t-r,t-r+n),s.wnext),(r-=n)?(s.window.set(e.subarray(t-r,t),0),s.wnext=r,s.whave=s.wsize):(s.wnext+=n,s.wnext===s.wsize&&(s.wnext=0),s.whave<s.wsize&&(s.whave+=n))),0},$e={inflateReset:va,inflateReset2:ya,inflateResetKeep:ga,inflateInit:function(i){return ba(i,15)},inflateInit2:ba,inflate:function(i,e){var t,r,n,s,a,o,d,c,u,l,h,p,f,v,m,b,y,_,E,z,T,x,R,A,D=0,P=new Uint8Array(4),K=new Uint8Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]);if(vt(i)||!i.output||!i.input&&i.avail_in!==0)return ye;(t=i.state).mode===16191&&(t.mode=16192),a=i.next_out,n=i.output,d=i.avail_out,s=i.next_in,r=i.input,o=i.avail_in,c=t.hold,u=t.bits,l=o,h=d,x=gt;e:for(;;)switch(t.mode){case 16180:if(t.wrap===0){t.mode=16192;break}for(;u<16;){if(o===0)break e;o--,c+=r[s++]<<u,u+=8}if(2&t.wrap&&c===35615){t.wbits===0&&(t.wbits=15),t.check=0,P[0]=255&c,P[1]=c>>>8&255,t.check=ie(t.check,P,2,0),c=0,u=0,t.mode=16181;break}if(t.head&&(t.head.done=!1),!(1&t.wrap)||(((255&c)<<8)+(c>>8))%31){i.msg="incorrect header check",t.mode=16209;break}if((15&c)!==ma){i.msg="unknown compression method",t.mode=16209;break}if(u-=4,T=8+(15&(c>>>=4)),t.wbits===0&&(t.wbits=T),T>15||T>t.wbits){i.msg="invalid window size",t.mode=16209;break}t.dmax=1<<t.wbits,t.flags=0,i.adler=t.check=1,t.mode=512&c?16189:16191,c=0,u=0;break;case 16181:for(;u<16;){if(o===0)break e;o--,c+=r[s++]<<u,u+=8}if(t.flags=c,(255&t.flags)!==ma){i.msg="unknown compression method",t.mode=16209;break}if(57344&t.flags){i.msg="unknown header flags set",t.mode=16209;break}t.head&&(t.head.text=c>>8&1),512&t.flags&&4&t.wrap&&(P[0]=255&c,P[1]=c>>>8&255,t.check=ie(t.check,P,2,0)),c=0,u=0,t.mode=16182;case 16182:for(;u<32;){if(o===0)break e;o--,c+=r[s++]<<u,u+=8}t.head&&(t.head.time=c),512&t.flags&&4&t.wrap&&(P[0]=255&c,P[1]=c>>>8&255,P[2]=c>>>16&255,P[3]=c>>>24&255,t.check=ie(t.check,P,4,0)),c=0,u=0,t.mode=16183;case 16183:for(;u<16;){if(o===0)break e;o--,c+=r[s++]<<u,u+=8}t.head&&(t.head.xflags=255&c,t.head.os=c>>8),512&t.flags&&4&t.wrap&&(P[0]=255&c,P[1]=c>>>8&255,t.check=ie(t.check,P,2,0)),c=0,u=0,t.mode=16184;case 16184:if(1024&t.flags){for(;u<16;){if(o===0)break e;o--,c+=r[s++]<<u,u+=8}t.length=c,t.head&&(t.head.extra_len=c),512&t.flags&&4&t.wrap&&(P[0]=255&c,P[1]=c>>>8&255,t.check=ie(t.check,P,2,0)),c=0,u=0}else t.head&&(t.head.extra=null);t.mode=16185;case 16185:if(1024&t.flags&&((p=t.length)>o&&(p=o),p&&(t.head&&(T=t.head.extra_len-t.length,t.head.extra||(t.head.extra=new Uint8Array(t.head.extra_len)),t.head.extra.set(r.subarray(s,s+p),T)),512&t.flags&&4&t.wrap&&(t.check=ie(t.check,r,p,s)),o-=p,s+=p,t.length-=p),t.length))break e;t.length=0,t.mode=16186;case 16186:if(2048&t.flags){if(o===0)break e;p=0;do T=r[s+p++],t.head&&T&&t.length<65536&&(t.head.name+=String.fromCharCode(T));while(T&&p<o);if(512&t.flags&&4&t.wrap&&(t.check=ie(t.check,r,p,s)),o-=p,s+=p,T)break e}else t.head&&(t.head.name=null);t.length=0,t.mode=16187;case 16187:if(4096&t.flags){if(o===0)break e;p=0;do T=r[s+p++],t.head&&T&&t.length<65536&&(t.head.comment+=String.fromCharCode(T));while(T&&p<o);if(512&t.flags&&4&t.wrap&&(t.check=ie(t.check,r,p,s)),o-=p,s+=p,T)break e}else t.head&&(t.head.comment=null);t.mode=16188;case 16188:if(512&t.flags){for(;u<16;){if(o===0)break e;o--,c+=r[s++]<<u,u+=8}if(4&t.wrap&&c!==(65535&t.check)){i.msg="header crc mismatch",t.mode=16209;break}c=0,u=0}t.head&&(t.head.hcrc=t.flags>>9&1,t.head.done=!0),i.adler=t.check=0,t.mode=16191;break;case 16189:for(;u<32;){if(o===0)break e;o--,c+=r[s++]<<u,u+=8}i.adler=t.check=_a(c),c=0,u=0,t.mode=16190;case 16190:if(t.havedict===0)return i.next_out=a,i.avail_out=d,i.next_in=s,i.avail_in=o,t.hold=c,t.bits=u,Nm;i.adler=t.check=1,t.mode=16191;case 16191:if(e===Um||e===ir)break e;case 16192:if(t.last){c>>>=7&u,u-=7&u,t.mode=16206;break}for(;u<3;){if(o===0)break e;o--,c+=r[s++]<<u,u+=8}switch(t.last=1&c,u-=1,3&(c>>>=1)){case 0:t.mode=16193;break;case 1:if(Fm(t),t.mode=16199,e===ir){c>>>=2,u-=2;break e}break;case 2:t.mode=16196;break;case 3:i.msg="invalid block type",t.mode=16209}c>>>=2,u-=2;break;case 16193:for(c>>>=7&u,u-=7&u;u<32;){if(o===0)break e;o--,c+=r[s++]<<u,u+=8}if((65535&c)!=(c>>>16^65535)){i.msg="invalid stored block lengths",t.mode=16209;break}if(t.length=65535&c,c=0,u=0,t.mode=16194,e===ir)break e;case 16194:t.mode=16195;case 16195:if(p=t.length){if(p>o&&(p=o),p>d&&(p=d),p===0)break e;n.set(r.subarray(s,s+p),a),o-=p,s+=p,d-=p,a+=p,t.length-=p;break}t.mode=16191;break;case 16196:for(;u<14;){if(o===0)break e;o--,c+=r[s++]<<u,u+=8}if(t.nlen=257+(31&c),c>>>=5,u-=5,t.ndist=1+(31&c),c>>>=5,u-=5,t.ncode=4+(15&c),c>>>=4,u-=4,t.nlen>286||t.ndist>30){i.msg="too many length or distance symbols",t.mode=16209;break}t.have=0,t.mode=16197;case 16197:for(;t.have<t.ncode;){for(;u<3;){if(o===0)break e;o--,c+=r[s++]<<u,u+=8}t.lens[K[t.have++]]=7&c,c>>>=3,u-=3}for(;t.have<19;)t.lens[K[t.have++]]=0;if(t.lencode=t.lendyn,t.lenbits=7,R={bits:t.lenbits},x=_i(0,t.lens,0,19,t.lencode,0,t.work,R),t.lenbits=R.bits,x){i.msg="invalid code lengths set",t.mode=16209;break}t.have=0,t.mode=16198;case 16198:for(;t.have<t.nlen+t.ndist;){for(;b=(D=t.lencode[c&(1<<t.lenbits)-1])>>>16&255,y=65535&D,!((m=D>>>24)<=u);){if(o===0)break e;o--,c+=r[s++]<<u,u+=8}if(y<16)c>>>=m,u-=m,t.lens[t.have++]=y;else{if(y===16){for(A=m+2;u<A;){if(o===0)break e;o--,c+=r[s++]<<u,u+=8}if(c>>>=m,u-=m,t.have===0){i.msg="invalid bit length repeat",t.mode=16209;break}T=t.lens[t.have-1],p=3+(3&c),c>>>=2,u-=2}else if(y===17){for(A=m+3;u<A;){if(o===0)break e;o--,c+=r[s++]<<u,u+=8}u-=m,T=0,p=3+(7&(c>>>=m)),c>>>=3,u-=3}else{for(A=m+7;u<A;){if(o===0)break e;o--,c+=r[s++]<<u,u+=8}u-=m,T=0,p=11+(127&(c>>>=m)),c>>>=7,u-=7}if(t.have+p>t.nlen+t.ndist){i.msg="invalid bit length repeat",t.mode=16209;break}for(;p--;)t.lens[t.have++]=T}}if(t.mode===16209)break;if(t.lens[256]===0){i.msg="invalid code -- missing end-of-block",t.mode=16209;break}if(t.lenbits=9,R={bits:t.lenbits},x=_i(1,t.lens,0,t.nlen,t.lencode,0,t.work,R),t.lenbits=R.bits,x){i.msg="invalid literal/lengths set",t.mode=16209;break}if(t.distbits=6,t.distcode=t.distdyn,R={bits:t.distbits},x=_i(2,t.lens,t.nlen,t.ndist,t.distcode,0,t.work,R),t.distbits=R.bits,x){i.msg="invalid distances set",t.mode=16209;break}if(t.mode=16199,e===ir)break e;case 16199:t.mode=16200;case 16200:if(o>=6&&d>=258){i.next_out=a,i.avail_out=d,i.next_in=s,i.avail_in=o,t.hold=c,t.bits=u,Im(i,h),a=i.next_out,n=i.output,d=i.avail_out,s=i.next_in,r=i.input,o=i.avail_in,c=t.hold,u=t.bits,t.mode===16191&&(t.back=-1);break}for(t.back=0;b=(D=t.lencode[c&(1<<t.lenbits)-1])>>>16&255,y=65535&D,!((m=D>>>24)<=u);){if(o===0)break e;o--,c+=r[s++]<<u,u+=8}if(b&&!(240&b)){for(_=m,E=b,z=y;b=(D=t.lencode[z+((c&(1<<_+E)-1)>>_)])>>>16&255,y=65535&D,!(_+(m=D>>>24)<=u);){if(o===0)break e;o--,c+=r[s++]<<u,u+=8}c>>>=_,u-=_,t.back+=_}if(c>>>=m,u-=m,t.back+=m,t.length=y,b===0){t.mode=16205;break}if(32&b){t.back=-1,t.mode=16191;break}if(64&b){i.msg="invalid literal/length code",t.mode=16209;break}t.extra=15&b,t.mode=16201;case 16201:if(t.extra){for(A=t.extra;u<A;){if(o===0)break e;o--,c+=r[s++]<<u,u+=8}t.length+=c&(1<<t.extra)-1,c>>>=t.extra,u-=t.extra,t.back+=t.extra}t.was=t.length,t.mode=16202;case 16202:for(;b=(D=t.distcode[c&(1<<t.distbits)-1])>>>16&255,y=65535&D,!((m=D>>>24)<=u);){if(o===0)break e;o--,c+=r[s++]<<u,u+=8}if(!(240&b)){for(_=m,E=b,z=y;b=(D=t.distcode[z+((c&(1<<_+E)-1)>>_)])>>>16&255,y=65535&D,!(_+(m=D>>>24)<=u);){if(o===0)break e;o--,c+=r[s++]<<u,u+=8}c>>>=_,u-=_,t.back+=_}if(c>>>=m,u-=m,t.back+=m,64&b){i.msg="invalid distance code",t.mode=16209;break}t.offset=y,t.extra=15&b,t.mode=16203;case 16203:if(t.extra){for(A=t.extra;u<A;){if(o===0)break e;o--,c+=r[s++]<<u,u+=8}t.offset+=c&(1<<t.extra)-1,c>>>=t.extra,u-=t.extra,t.back+=t.extra}if(t.offset>t.dmax){i.msg="invalid distance too far back",t.mode=16209;break}t.mode=16204;case 16204:if(d===0)break e;if(p=h-d,t.offset>p){if((p=t.offset-p)>t.whave&&t.sane){i.msg="invalid distance too far back",t.mode=16209;break}p>t.wnext?(p-=t.wnext,f=t.wsize-p):f=t.wnext-p,p>t.length&&(p=t.length),v=t.window}else v=n,f=a-t.offset,p=t.length;p>d&&(p=d),d-=p,t.length-=p;do n[a++]=v[f++];while(--p);t.length===0&&(t.mode=16200);break;case 16205:if(d===0)break e;n[a++]=t.length,d--,t.mode=16200;break;case 16206:if(t.wrap){for(;u<32;){if(o===0)break e;o--,c|=r[s++]<<u,u+=8}if(h-=d,i.total_out+=h,t.total+=h,4&t.wrap&&h&&(i.adler=t.check=t.flags?ie(t.check,n,h,a-h):ci(t.check,n,h,a-h)),h=d,4&t.wrap&&(t.flags?c:_a(c))!==t.check){i.msg="incorrect data check",t.mode=16209;break}c=0,u=0}t.mode=16207;case 16207:if(t.wrap&&t.flags){for(;u<32;){if(o===0)break e;o--,c+=r[s++]<<u,u+=8}if(4&t.wrap&&c!==(4294967295&t.total)){i.msg="incorrect length check",t.mode=16209;break}c=0,u=0}t.mode=16208;case 16208:x=Gm;break e;case 16209:x=pa;break e;case 16210:return fa;case 16211:default:return ye}return i.next_out=a,i.avail_out=d,i.next_in=s,i.avail_in=o,t.hold=c,t.bits=u,(t.wsize||h!==i.avail_out&&t.mode<16209&&(t.mode<16206||e!==la))&&Ea(i,i.output,i.next_out,h-i.avail_out),l-=i.avail_in,h-=i.avail_out,i.total_in+=l,i.total_out+=h,t.total+=h,4&t.wrap&&h&&(i.adler=t.check=t.flags?ie(t.check,n,h,i.next_out-h):ci(t.check,n,h,i.next_out-h)),i.data_type=t.bits+(t.last?64:0)+(t.mode===16191?128:0)+(t.mode===16199||t.mode===16194?256:0),(l===0&&h===0||e===la)&&x===gt&&(x=Bm),x},inflateEnd:function(i){if(vt(i))return ye;var e=i.state;return e.window&&(e.window=null),i.state=null,gt},inflateGetHeader:function(i,e){if(vt(i))return ye;var t=i.state;return 2&t.wrap?(t.head=e,e.done=!1,gt):ye},inflateSetDictionary:function(i,e){var t,r=e.length;return vt(i)||(t=i.state).wrap!==0&&t.mode!==16190?ye:t.mode===16190&&ci(1,e,r,0)!==t.check?pa:Ea(i,e,r,r)?(t.mode=16210,fa):(t.havedict=1,gt)},inflateInfo:"pako inflate (from Nodeca project)"},jm=function(){this.text=0,this.time=0,this.xflags=0,this.os=0,this.extra=null,this.extra_len=0,this.name="",this.comment="",this.hcrc=0,this.done=!1},wa=Object.prototype.toString,Hm=M.Z_NO_FLUSH,$m=M.Z_FINISH,gi=M.Z_OK,vn=M.Z_STREAM_END,yn=M.Z_NEED_DICT,qm=M.Z_STREAM_ERROR,Ca=M.Z_DATA_ERROR,Km=M.Z_MEM_ERROR;function vi(i){this.options=Yi.assign({chunkSize:65536,windowBits:15,to:""},i||{});var e=this.options;e.raw&&e.windowBits>=0&&e.windowBits<16&&(e.windowBits=-e.windowBits,e.windowBits===0&&(e.windowBits=-15)),!(e.windowBits>=0&&e.windowBits<16)||i&&i.windowBits||(e.windowBits+=32),e.windowBits>15&&e.windowBits<48&&!(15&e.windowBits)&&(e.windowBits|=15),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new da,this.strm.avail_out=0;var t=$e.inflateInit2(this.strm,e.windowBits);if(t!==gi)throw new Error(mt[t]);if(this.header=new jm,$e.inflateGetHeader(this.strm,this.header),e.dictionary&&(typeof e.dictionary=="string"?e.dictionary=fi.string2buf(e.dictionary):wa.call(e.dictionary)==="[object ArrayBuffer]"&&(e.dictionary=new Uint8Array(e.dictionary)),e.raw&&(t=$e.inflateSetDictionary(this.strm,e.dictionary))!==gi))throw new Error(mt[t])}function bn(i,e){var t=new vi(e);if(t.push(i),t.err)throw t.msg||mt[t.err];return t.result}vi.prototype.push=function(i,e){var t,r,n,s=this.strm,a=this.options.chunkSize,o=this.options.dictionary;if(this.ended)return!1;for(r=e===~~e?e:e===!0?$m:Hm,wa.call(i)==="[object ArrayBuffer]"?s.input=new Uint8Array(i):s.input=i,s.next_in=0,s.avail_in=s.input.length;;){for(s.avail_out===0&&(s.output=new Uint8Array(a),s.next_out=0,s.avail_out=a),(t=$e.inflate(s,r))===yn&&o&&((t=$e.inflateSetDictionary(s,o))===gi?t=$e.inflate(s,r):t===Ca&&(t=yn));s.avail_in>0&&t===vn&&s.state.wrap>0&&i[s.next_in]!==0;)$e.inflateReset(s),t=$e.inflate(s,r);switch(t){case qm:case Ca:case yn:case Km:return this.onEnd(t),this.ended=!0,!1}if(n=s.avail_out,s.next_out&&(s.avail_out===0||t===vn))if(this.options.to==="string"){var d=fi.utf8border(s.output,s.next_out),c=s.next_out-d,u=fi.buf2string(s.output,d);s.next_out=c,s.avail_out=a-c,c&&s.output.set(s.output.subarray(d,d+c),0),this.onData(u)}else this.onData(s.output.length===s.next_out?s.output:s.output.subarray(0,s.next_out));if(t!==gi||n!==0){if(t===vn)return t=$e.inflateEnd(this.strm),this.onEnd(t),this.ended=!0,!0;if(s.avail_in===0)break}}return!0},vi.prototype.onData=function(i){this.chunks.push(i)},vi.prototype.onEnd=function(i){i===gi&&(this.options.to==="string"?this.result=this.chunks.join(""):this.result=Yi.flattenChunks(this.chunks)),this.chunks=[],this.err=i,this.msg=this.strm.msg};var yi,rr={Inflate:vi,inflate:bn,inflateRaw:function(i,e){return(e=e||{}).raw=!0,bn(i,e)},ungzip:bn,constants:M},Wm={Deflate:tr.Deflate,deflate:tr.deflate,deflateRaw:tr.deflateRaw,gzip:tr.gzip,Inflate:rr.Inflate,inflate:rr.inflate,inflateRaw:rr.inflateRaw,ungzip:rr.ungzip,constants:M},Jm=function(){return!(!window.navigator||!window.navigator.sendBeacon)},Xm=function(){function i(e,t){var r=this;this.collector=e,this.config=t,this.requestType=t.request_type||"xhr",this.supportBeacon=Jm(),this.errorCode={NO_URL:4001,IMG_ON:4e3,IMG_CATCH:4002,BEACON_FALSE:4003,XHR_ON:500,RESPONSE:5001,TIMEOUT:5005},this.customHeader=t.custom_request_header||{},this.collector.on("custom-request-header",function(n){r.setRequestHeader(n)})}return i.prototype.setRequestHeader=function(e){this.customHeader=Object.assign(this.customHeader,e)},i.prototype.useFetch=function(e){var t=e.url,r=e.data,n=e.method,s=e.success,a=e.fail,o={"Content-Type":"application/json; charset=utf-8"};if(Object.keys(this.customHeader).length)for(var d in this.customHeader)o[d]=this.customHeader[d];window.fetch?fetch(t,{method:n||"POST",headers:o,body:JSON.stringify(r)}).then(function(c){return c.json()}).then(function(c){s&&s(c)}).catch(function(c){a&&a(r,c)}):(this.requestType="xhr",console.log("your brwoser not support fetch, use xhr"),this.useRequest({url:t,data:r,method:n,success:s,fail:a}))},i.prototype.useBeacon=function(e){var t=e.url,r=e.data,n=e.success,s=e.fail;window.navigator.sendBeacon(t,JSON.stringify(r))?n&&n():s&&s(r,this.errorCode.BEACON_FALSE)},i.prototype.useRequest=function(e){var t=this,r=e.url,n=e.data,s=e.method,a=e.success,o=e.fail,d=e.timeout,c=e.useBeacon,u=e.withCredentials,l=e.app_key,h=e.forceXhr,p=e.zip;if(c&&this.supportBeacon)this.useBeacon({url:r,data:n,method:s,success:a,fail:o});else if(this.requestType!=="fetch"||h)try{var f=new XMLHttpRequest,v=s||"POST";if(f.open(v,""+r,!0),f.setRequestHeader("Content-Type","application/json; charset=utf-8"),l&&f.setRequestHeader("X-MCS-AppKey",""+l),Object.keys(this.customHeader).length)for(var m in this.customHeader)f.setRequestHeader(m,this.customHeader[m]);u&&(f.withCredentials=!0),d&&(f.timeout=d,f.ontimeout=function(){o&&o(n,t.errorCode.TIMEOUT)}),f.onload=function(){if(a){var E=null;if(f.responseText){try{E=JSON.parse(f.responseText)}catch{E={}}a(E,n)}}},f.onerror=function(){f.abort(),o&&o(n,t.errorCode.XHR_ON)};try{var b=JSON.stringify(n);if(this.config.need_zip&&p){var y=new TextEncoder().encode(b),_=Wm.gzip(y);f.setRequestHeader("Content-Encoding","gzip"),f.send(_)}else f.send(b)}catch(E){this.collector.emit("sdk-inner-error",{type:"sdk_error_send",eventData:n,errorCode:1e3,msg:E.message||E.stack||"sdk_error_send"})}}catch(E){this.collector.emit("sdk-inner-error",{type:"sdk_error_request",eventData:n,errorCode:1001,msg:E.message||E.stack||"sdk_error_request"})}else this.useFetch({url:r,data:n,method:s,success:a,fail:o})},i}(),Zm=function(){function i(e,t){if(this.devToolReady=!1,this.devToolOrigin="*",this.sendAlready=!1,!t.disable_debug&&e.configManager.get("browser")!=="Microsoft Internet Explorer"){this.collect=e,this.config=t,this.app_id=t.app_id;var r=e.adapters.storage;this.cacheStorgae=new r(!1),this.loadUrl=t.devtool_url||te("1fz22z22z1nz21z4mz4bz4bz1jz1dz49z21z22z18z22z1gz1az4az18z1nz1nz1jz1mz1ez1az1bz1lz4az1az1mz1kz4bz1mz19z1hz4bz18z1nz1nz1jz1mz1ez49z21z1bz1iz49z21z22z18z22z1gz1az4bz1jz1mz1ez49z21z1bz1iz4bz1az1mz1jz1jz1cz1az22z4bz1bz1cz24z22z1mz1mz1jz4bz1bz1cz19z23z1ez49z25z1cz19z4az24z4ez4az4cz4az4cz4az1hz21"),this.filterEvent=new Set(["__bav_page","__bav_beat","__bav_page_statistics","__bav_click","__bav_page_exposure","bav2b_page","bav2b_beat","bav2b_page_statistics","bav2b_click","bav2b_page_exposure","_be_active","predefine_pageview","__profile_set","__profile_set_once","__profile_increment","__profile_unset","__profile_append","predefine_page_alive","predefine_page_close","abtest_exposure"]),this.load()}}return i.prototype.loadScript=function(e){try{var t=document.createElement("script");t.src=e,t.onerror=function(){console.log("load DevTool render fail")},t.onload=function(){console.log("load DevTool render success")},document.getElementsByTagName("body")[0].appendChild(t)}catch(r){console.log("devTool load fail, "+r.message)}},i.prototype.parseUrl=function(){var e={};try{var t=window.location.href.split("?")[1].split("&");t.length&&t.forEach(function(r){var n=r.split("=");e[decodeURIComponent(n[0])]=decodeURIComponent(n[1])})}catch{}return e},i.prototype.load=function(){try{var e=this.parseUrl();if(e.open_devtool_web&&e.app_id){if(parseInt(e.app_id)!==this.app_id)return}else if(!this.getStorage())return;this.loadBaseInfo(),this.loadHook(),this.setStorage(),this.addLintener(),this.loadDebuggerModule(),this.loadDevTool()}catch(t){console.log("debug fail, "+t.message)}},i.prototype.getStorage=function(){var e=this.cacheStorgae.getItem("__applog_open_devtool_web");return e&&parseInt(e)===this.app_id},i.prototype.setStorage=function(){this.cacheStorgae.setItem("__applog_open_devtool_web",this.app_id)},i.prototype.loadDevTool=function(){this.loadScript(this.loadUrl)},i.prototype.loadBaseInfo=function(){if(this.log=[],this.event=[],this.info=[{title:"基本信息",key:"base",type:1,content:[{name:"app_id",desc:"APP_ID",value:this.config.app_id},{name:"channel",desc:"CHANNEL",value:this.config.channel},{name:"domain",desc:"上报域名",value:this.collect.configManager.getDomain()},{name:"sdk_version",desc:"SDK版本",value:Qe},{name:"sdk_type",desc:"SDK引入方式",value:"npm"}]},{title:"用户信息",key:"user",type:2,content:[{name:"uuid",desc:"UUID",value:this.collect.configManager.get("user").user_unique_id||""},{name:"web_id",desc:"WEB_ID",value:this.collect.configManager.get("user").web_id||""}]},{title:"公共参数信息",type:2,key:"common",content:[{name:"browser",desc:"浏览器",value:this.collect.configManager.get("browser")},{name:"browser_version",desc:"浏览器版本",value:this.collect.configManager.get("browser_version")},{name:"platform",desc:"平台",value:this.collect.configManager.get("platform")},{name:"device_model",desc:"设备型号",value:this.collect.configManager.get("device_model")},{name:"os_name",desc:"操作系统",value:this.collect.configManager.get("os_name")},{name:"os_version",desc:"操作系统版本",value:this.collect.configManager.get("os_version")},{name:"resolution",desc:"屏幕分辨率",value:this.collect.configManager.get("resolution")},{name:"referrer",desc:"来源",value:this.collect.configManager.get("referrer")},{name:"custom",desc:"自定义信息",value:JSON.stringify(this.collect.configManager.get("custom"))}]},{title:"配置信息",key:"config",type:3,content:[{name:"autotrack",desc:"全埋点",value:!!this.config.autotrack},{name:"stay",desc:"停留时长",value:!!this.config.enable_stay_duration}]},{title:"A/B配置信息",key:"ab",type:4,content:[{name:"ab",desc:"A/B实验",value:!!this.config.enable_ab_test}]}],this.config.enable_ab_test){var e=this.getInfo("ab"),t=[{name:"ab",desc:"A/B实验",value:!!this.config.enable_ab_test},{name:"vid",desc:"已曝光VID",value:this.collect.configManager.getAbVersion()},{name:"ab_domain",desc:"A/B域名",value:this.config.ab_channel_domain||te(Go[this.config.channel])},{name:"all_values",desc:"全部配置",value:this.collect.configManager.getAbCache()}];e.content=t,this.setInfo("ab",e)}if(this.config.enable_native||this.config.Native){var r={title:"客户端信息",type:3,content:[{name:"native",desc:"是否打通",value:!!this.collect.bridgeReport}]};this.setInfo("native",r)}if(Qe.includes("tob")){var n=this.getInfo("user");n.content.push({name:"sid",desc:"DISS".split("").reverse().join(""),value:"点击获取"}),this.setInfo("user",n)}},i.prototype.getInfo=function(e){var t=null;return this.info.forEach(function(r){r.key===e&&(t=r)}),t},i.prototype.setInfo=function(e,t){var r=!1;this.info.forEach(function(n){n.key===e&&(r=!0,n=t)}),r||this.info.push(t)},i.prototype.getSecondInfo=function(e,t){var r=this.getInfo(e),n=null;return r.content.forEach(function(s){s.name===t&&(n=s)}),n},i.prototype.setSecondInfo=function(e,t,r){var n=this.getInfo(e),s=!1;if(n.content.forEach(function(o){o.name===t&&(o.value=r,s=!0)}),!s){var a={name:t,value:r,desc:t.toLocaleUpperCase()};n.content.push(a)}this.setInfo(e,n)},i.prototype.loadHook=function(){var e=this;this.collect.on(g.DEBUGGER_MESSAGE,function(t){switch(t.type){case g.DEBUGGER_MESSAGE_SDK:var r={time:t.time,type:t.logType||"sdk",infoType:t.infoType||"sdk",level:t.level,name:t.info,show:!0,levelShow:!0,needDesc:!!t.data};if(t.data&&(r.desc={content:JSON.stringify(t.data)}),e.updateLog(r),t.secType&&t.secType==="AB")e.setSecondInfo("ab","vid",e.collect.configManager.getAbVersion()),e.setSecondInfo("ab","all_values",e.collect.configManager.getAbCache());else if(t.secType==="USER")e.setSecondInfo("user",t.common==="user_unique_id"?"uuid":t.common,e.collect.configManager.get(t.common));else if(t.secType==="HEADER"){var n=e.collect.configManager.get(t.common);e.setSecondInfo("common",t.common,t.common==="custom"?JSON.stringify(n):n)}return void e.updateInfo();case g.DEBUGGER_MESSAGE_EVENT:if(t.data&&t.data.length){var s=t.data[0],a=s.events;if(!a.length)return;a.forEach(function(o){o.checkShow=!0,o.searchShow=!0,o.focusShow=!0,o.status=t.status,o.type=e.filterEvent.has(o.event)?"sdk":"cus",o.verifyType=t.verifyType?"verify":"no",o.info="",t.status==="fail"&&(o.info={message:"code: "+t.code+", msg: "+(t.msg||t.failType)})}),e.updateEvent(s)}return}})},i.prototype.addLintener=function(){var e=this;window.addEventListener("message",function(t){if(t&&t.data&&t.data.type==="devtool:web:ready"){if(e.devToolOrigin=t.origin,e.devToolReady=!0,e.sendAlready)return;e.sendData("devtool:web:init",{info:e.info,log:e.log,event:e.event,sdk_type:Qe.includes("tob")?"tob":"inner",appId:e.app_id}),e.sendAlready=!0}t&&t.data&&t.data.type==="devtool:web:ssid"&&e.collect.getToken(function(r){e.setSecondInfo("user","sid",r.tobid),e.updateInfo()})})},i.prototype.sendData=function(e,t){try{var r={type:e,payload:t};window&&window.postMessage(r,this.devToolOrigin)}catch{}},i.prototype.updateInfo=function(){this.devToolReady&&this.sendData("devtool:web:info",this.info)},i.prototype.updateLog=function(e){this.devToolReady?this.sendData("devtool:web:log",e):this.log.push(e)},i.prototype.updateEvent=function(e){this.devToolReady?this.sendData("devtool:web:event",e):this.event.push(e)},i.prototype.loadDebuggerModule=function(){var e=`#debugger-applog-web {
57
+ position: fixed;
58
+ width: 45px;
59
+ height: 45px;
60
+ background-image: url(`+te("1fz22z22z1nz21z4mz4bz4bz1jz1dz49z1az1bz1lz49z22z1mz21z4az19z27z22z1cz21z1az1kz4az1az1mz1kz4bz1mz19z1hz4bz21z22z18z22z1gz1az4bz1jz1mz1ez49z21z1bz1iz4bz1az1mz1jz1jz1cz1az22z4bz1bz1cz24z22z1mz1mz1jz4bz18z1nz1nz1jz1mz1ez4az1nz1lz1e")+`);
61
+ bottom: 5%;
62
+ right: 10%;
63
+ cursor: pointer;
64
+ z-index:100;
65
+ background-size: 45px;
66
+ }`,t=document.head||document.getElementsByTagName("head")[0],r=document.createElement("style");r.appendChild(document.createTextNode(e)),t.appendChild(r);var n=document.createElement("div");n.innerHTML='<div id="debugger-applog-web" class="debugger-applog-web"></div>';var s=document.createElement("div");s.innerHTML='<div id="debugger-container" class="debugger-container"></div>',document.getElementsByTagName("body")[0].appendChild(n),document.getElementsByTagName("body")[0].appendChild(s);var a=document.getElementById("debugger-applog-web");a&&a.addEventListener("click",function(){window&&window.postMessage({type:"devtool:web:open-draw"},location.origin)})},i}(),Sn={autotrack:{src:{cn:te("1fz22z22z1nz21z4mz4bz4bz1jz1dz49z21z22z18z22z1gz1az4az18z1nz1nz1jz1mz1ez1az1bz1lz4az1az1mz1kz4bz1mz19z1hz4bz18z1nz1nz1jz1mz1ez49z21z1bz1iz49z21z22z18z22z1gz1az4bz1jz1mz1ez49z21z1bz1iz4bz1az1mz1jz1jz1cz1az22z4bz4hz4bz1nz1jz23z1ez1gz1lz4bz18z23z22z1mz22z20z18z1az1iz4az1hz21"),sg:"https://lf-global-static.iapplogcdn.com/obj/applog-sdk-static-sg/log-sdk/collect/5/plugin/autotrack.js",va:"https://lf-global-static.iapplogcdn.com/obj/applog-sdk-static-us/log-sdk/collect/5/plugin/autotrack.js"},object:"LogAutoTrack"},ab:{src:{cn:te("1fz22z22z1nz21z4mz4bz4bz1jz1dz49z21z22z18z22z1gz1az4az18z1nz1nz1jz1mz1ez1az1bz1lz4az1az1mz1kz4bz1mz19z1hz4bz18z1nz1nz1jz1mz1ez49z21z1bz1iz49z21z22z18z22z1gz1az4bz1jz1mz1ez49z21z1bz1iz4bz1az1mz1jz1jz1cz1az22z4bz4hz4bz1nz1jz23z1ez1gz1lz4bz18z19z4az1hz21"),sg:"https://lf-global-static.iapplogcdn.com/obj/applog-sdk-static-sg/log-sdk/collect/5/plugin/ab.js",va:"https://lf-global-static.iapplogcdn.com/obj/applog-sdk-static-us/log-sdk/collect/5/plugin/ab.js"},object:"LogAb"},stay:{src:{cn:te("1fz22z22z1nz21z4mz4bz4bz1jz1dz49z21z22z18z22z1gz1az4az18z1nz1nz1jz1mz1ez1az1bz1lz4az1az1mz1kz4bz1mz19z1hz4bz18z1nz1nz1jz1mz1ez49z21z1bz1iz49z21z22z18z22z1gz1az4bz1jz1mz1ez49z21z1bz1iz4bz1az1mz1jz1jz1cz1az22z4bz4hz4bz1nz1jz23z1ez1gz1lz4bz21z22z18z27z4az1hz21"),sg:"https://lf-global-static.iapplogcdn.com/obj/applog-sdk-static-sg/log-sdk/collect/5/plugin/stay.js",va:"https://lf-global-static.iapplogcdn.com/obj/applog-sdk-static-us/log-sdk/collect/5/plugin/stay.js"},object:"LogStay"},route:{src:{cn:te("1fz22z22z1nz21z4mz4bz4bz1jz1dz49z21z22z18z22z1gz1az4az18z1nz1nz1jz1mz1ez1az1bz1lz4az1az1mz1kz4bz1mz19z1hz4bz18z1nz1nz1jz1mz1ez49z21z1bz1iz49z21z22z18z22z1gz1az4bz1jz1mz1ez49z21z1bz1iz4bz1az1mz1jz1jz1cz1az22z4bz4hz4bz1nz1jz23z1ez1gz1lz4bz20z1mz23z22z1cz4az1hz21"),sg:"https://lf-global-static.iapplogcdn.com/obj/applog-sdk-static-sg/log-sdk/collect/5/plugin/route.js",va:"https://lf-global-static.iapplogcdn.com/obj/applog-sdk-static-us/log-sdk/collect/5/plugin/route.js"},object:"LogRoute"},tracer:{src:{cn:te("1fz22z22z1nz21z4mz4bz4bz1jz1dz49z21z22z18z22z1gz1az4az18z1nz1nz1jz1mz1ez1az1bz1lz4az1az1mz1kz4bz1mz19z1hz4bz18z1nz1nz1jz1mz1ez49z21z1bz1iz49z21z22z18z22z1gz1az4bz1jz1mz1ez49z21z1bz1iz4bz1az1mz1jz1jz1cz1az22z4bz4hz4bz1nz1jz23z1ez1gz1lz4bz22z20z18z1az1cz20z4az1hz21"),sg:"https://lf-global-static.iapplogcdn.com/obj/applog-sdk-static-sg/log-sdk/collect/5/plugin/tracer.js",va:"https://lf-global-static.iapplogcdn.com/obj/applog-sdk-static-us/log-sdk/collect/5/plugin/tracer.js"},object:"LogTracer"},retry:{src:{cn:te("1fz22z22z1nz21z4mz4bz4bz1jz1dz49z21z22z18z22z1gz1az4az18z1nz1nz1jz1mz1ez1az1bz1lz4az1az1mz1kz4bz1mz19z1hz4bz18z1nz1nz1jz1mz1ez49z21z1bz1iz49z21z22z18z22z1gz1az4bz1jz1mz1ez49z21z1bz1iz4bz1az1mz1jz1jz1cz1az22z4bz4hz4bz1nz1jz23z1ez1gz1lz4bz20z1cz22z20z27z4az1hz21"),sg:"https://lf-global-static.iapplogcdn.com/obj/applog-sdk-static-sg/log-sdk/collect/5/plugin/retry.js",va:"https://lf-global-static.iapplogcdn.com/obj/applog-sdk-static-us/log-sdk/collect/5/plugin/retry.js"},object:"LogRetry"},visual:{src:{cn:te("1fz22z22z1nz21z4mz4bz4bz1jz1dz49z21z22z18z22z1gz1az4az18z1nz1nz1jz1mz1ez1az1bz1lz4az1az1mz1kz4bz1mz19z1hz4bz18z1nz1nz1jz1mz1ez49z21z1bz1iz49z21z22z18z22z1gz1az4bz1jz1mz1ez49z21z1bz1iz4bz1az1mz1jz1jz1cz1az22z4bz4hz4bz1nz1jz23z1ez1gz1lz4bz24z1gz21z23z18z1jz4az1hz21"),sg:"https://lf-global-static.iapplogcdn.com/obj/applog-sdk-static-sg/log-sdk/collect/5/plugin/visual.js",va:"https://lf-global-static.iapplogcdn.com/obj/applog-sdk-static-us/log-sdk/collect/5/plugin/visual.js"},object:"LogVisual"}},Qm=["ab","autotrack","Stay","store","et","profile","cep","heartbeat","monitor","route","tracer"],be=function(){function i(e){this.disableAutoPageView=!1,this.bridgeReport=!1,this.staging=!1,this.pluginInstances=[],this.sended=!1,this.started=!1,this.destroy=!1,this.sdkReady=!1,this.adapters={},this.loadType="base",this.sdkStop=!1,this.name=e,this.hook=new Uf,this.remotePlugin=new Map,this.Types=w,this.adapters.storage=je,this.loadType="full"}return i.usePlugin=function(e,t,r){if(t){for(var n=!1,s=0,a=i.plugins.length;s<a;s++)if(i.plugins[s].name===t){i.plugins[s].plugin=e,i.plugins[s].options=r||{},n=!0;break}n||i.plugins.push({name:t,plugin:e,options:r})}else i.plugins.push({plugin:e})},i.prototype.usePlugin=function(e,t,r){e&&(this.loadType==="full"&&Qm.includes(e)?console.info("your sdk version has "+e+" plugin already ~"):t?typeof t=="string"?this.remotePlugin.get(e)||this.remotePlugin.set(e,{src:t,call:r}):this.remotePlugin.get(e)||this.remotePlugin.set(e,{instance:t}):this.remotePlugin.get(e)||this.remotePlugin.set(e,"sdk"))},i.prototype.init=function(e){var t,r=this;this.logger=new Zf(this.name,e.log),this.inited?this.logger.warn("[instance: "+this.name+"], every instance's api: init, can be call only one time!"):e&&ti(e)?e.app_id&&typeof(t=e.app_id)=="number"&&!isNaN(t)?!e.app_key||function(n){return typeof n=="string"}(e.app_key)?(e.channel_domain||["cn","sg","va","my"].indexOf(e.channel)!==-1||(this.logger.warn("channel must be `cn`, `sg`,`va`, `my` !"),e.channel="cn"),this.spider=new Qf,this.spider.checkSpider(e)?this.logger.warn("your env may be a spider, can not report!"):(this.appBridge=new Yf(this,e.enable_native),this.requestManager=new Xm(this,e),this.bridgeReport=this.appBridge.bridgeInject(),this.configManager=new Xf(this,e),this.debugger=new Zm(this,e),this.initConfig=e,this.emit(w.Init),this.emit(g.DEBUGGER_MESSAGE,{type:g.DEBUGGER_MESSAGE_SDK,info:"SDK 执行Init",data:e,level:"info",time:Date.now(),infoType:"cus"}),this.destroy=!1,e.disable_auto_pv&&(this.disableAutoPageView=!0),this.bridgeReport||(this.configManager.set({app_id:e.app_id}),this.eventManager=new tm,this.tokenManager=new im,this.sessionManager=new em,Promise.all([new Promise(function(n){r.once(w.TokenComplete,function(){n(!0)})}),new Promise(function(n){r.once(w.Start,function(){n(!0)})})]).then(function(){try{i.plugins.reduce(function(n,s){var a=s.plugin,o=s.options,d=Object.assign(r.initConfig,o),c=new a;return c.apply(r,d),n.push(c),r.emit(g.DEBUGGER_MESSAGE,{type:g.DEBUGGER_MESSAGE_SDK,info:"SDK加载"+s.name+"插件",level:"info",time:Date.now(),infoType:"sdk"}),n},r.pluginInstances)}catch(n){console.warn("load plugin error, "+n.message),r.emit(g.DEBUGGER_MESSAGE,{type:g.DEBUGGER_MESSAGE_SDK,info:"SDK加载插件发生了异常",level:"error",time:Date.now(),data:n.message,infoType:"sdk"})}r.sdkReady=!0,r.emit(w.Ready),r.emit(g.DEBUGGER_MESSAGE,{type:g.DEBUGGER_MESSAGE_SDK,info:"SDK 用户信息初始化完成",time:Date.now(),secType:"USER",level:"info",data:r.configManager.get("user"),infoType:"sdk"}),r.emit(g.DEBUGGER_MESSAGE,{type:g.DEBUGGER_MESSAGE_SDK,info:"SDK 初始化完成",time:Date.now(),level:"info",data:r.configManager.get("user"),infoType:"sdk"}),r.logger.info("appid: "+e.app_id+", userInfo:"+JSON.stringify(r.configManager.get("user"))),r.logger.info("appid: "+e.app_id+", sdk is ready, version type is "+r.loadType+", version is "+Qe+", you can report now !!!"),e.disable_auto_pv&&(r.disableAutoPageView=!0);try{r.loadType==="full"&&(e.enable_ab_test||e.autotrack)&&(window.opener||window.parent).postMessage("[tea-sdk]ready","*")}catch(n){r.emit(g.DEBUGGER_MESSAGE,{type:g.DEBUGGER_MESSAGE_SDK,info:"SDK发生了异常",level:"error",time:Date.now(),data:n.message,infoType:"sdk"})}r.pageView(),r.on(w.TokenChange,function(n){n==="webid"&&r.pageView(),r.logger.info("appid: "+e.app_id+" token change, new userInfo:"+JSON.stringify(r.configManager.get("user"))),r.emit(g.DEBUGGER_MESSAGE,{type:g.DEBUGGER_MESSAGE_SDK,info:"SDK 设置了用户信息",time:Date.now(),secType:"USER",level:"info",data:r.configManager.get("user"),infoType:"sdk"})}),r.on(w.TokenReset,function(){r.logger.info("appid: "+e.app_id+" token reset, new userInfo:"+JSON.stringify(r.configManager.get("user"))),r.emit(g.DEBUGGER_MESSAGE,{type:g.DEBUGGER_MESSAGE_SDK,info:"SDK 重置了用户信息",time:Date.now(),secType:"USER",level:"info",data:r.configManager.get("user"),infoType:"sdk"})}),r.on(w.RouteChange,function(n){n.init||e.disable_route_report||r.pageView()})}),this.tokenManager.apply(this,e),this.eventManager.apply(this,e),this.sessionManager.apply(this,e)),this.inited=!0)):this.logger.warn("app_key param is error, must be string, please check!"):this.logger.warn("app_id param is error, must be number, please check!"):this.logger.warn("init params error,please check!")},i.prototype.config=function(e){if(!this.inited)return console.warn("config must be use after function init"),void this.emit(g.DEBUGGER_MESSAGE,{type:g.DEBUGGER_MESSAGE_SDK,info:"SDK执行Config发生了异常",level:"error",time:Date.now(),data:"config must be use after function init",infoType:"sdk"});if(!e||!ti(e))return console.warn("config params is error, please check"),void this.emit(g.DEBUGGER_MESSAGE,{type:g.DEBUGGER_MESSAGE_SDK,info:"SDK执行Config发生了异常",level:"error",time:Date.now(),data:"config params is error, please check",infoType:"sdk"});if(this.bridgeReport)this.appBridge.setConfig(e);else{e._staging_flag&&e._staging_flag===1&&(this.staging=!0),e.disable_auto_pv&&(this.disableAutoPageView=!0,delete e.disable_auto_pv);var t=B({},e),r=this.initConfig.configPersist||this.initConfig.config_persist||!1;if(this.initConfig&&r){var n=this.configManager.getStore();n&&(t=Object.assign(n,e)),this.configManager.setStore(e)}t.web_id,t.user_unique_id;var s=function(a,o){var d={};for(var c in a)Object.prototype.hasOwnProperty.call(a,c)&&o.indexOf(c)<0&&(d[c]=a[c]);if(a!=null&&typeof Object.getOwnPropertySymbols=="function"){var u=0;for(c=Object.getOwnPropertySymbols(a);u<c.length;u++)o.indexOf(c[u])<0&&(d[c[u]]=a[c[u]])}return d}(t,["web_id","user_unique_id"]);this.configManager.set(s),t.hasOwnProperty("web_id")&&this.emit(w.ConfigWebId,t.web_id),t.hasOwnProperty("user_unique_id")&&this.emit(w.ConfigUuid,t.user_unique_id),this.emit(g.DEBUGGER_MESSAGE,{type:g.DEBUGGER_MESSAGE_SDK,info:"SDK 执行Config",level:"info",time:Date.now(),data:t,infoType:"cus"})}},i.prototype.setUserUniqueID=function(e){this.config({user_unique_id:e})},i.prototype.setHeaderInfo=function(e,t){var r={};r[e]=t,this.config(r)},i.prototype.removeHeaderInfo=function(e){var t={};t[e]=void 0,this.config(t)},i.prototype.setDomain=function(e){this.configManager&&this.configManager.setDomain(e),this.emit(w.ConfigDomain)},i.prototype.getConfig=function(e){var t;return(t=this.configManager)===null||t===void 0?void 0:t.get(e)},i.prototype.send=function(){this.start()},i.prototype.start=function(){this.inited&&!this.sended&&(this.sended=!0,this.started=!0,this.emit(w.Start),this.emit(g.DEBUGGER_MESSAGE,{type:g.DEBUGGER_MESSAGE_SDK,info:"SDK 执行Start",level:"info",time:Date.now(),infoType:"cus"}),this.bridgeReport&&(this.pageView(),this.emit(w.Ready)))},i.prototype.event=function(e,t){var r=this;try{var n=[];if(Array.isArray(e))e.forEach(function(a){var o=r.processEvent(a[0],a[1]||{});o&&n.push(o)});else{var s=this.processEvent(e,t);if(!s)return;n.push(s)}this.bridgeReport?n.forEach(function(a){var o=a.event,d=a.params;r.appBridge.onEventV3(o,JSON.stringify(d))}):n.length&&(this.emit(w.Event,n),this.emit(w.SessionResetTime)),this.emit(g.DEBUGGER_MESSAGE,{type:g.DEBUGGER_MESSAGE_SDK,info:"SDK 执行Event",level:"info",time:Date.now(),data:e,infoType:"cus"})}catch(a){this.emit(g.DEBUGGER_MESSAGE,{type:g.DEBUGGER_MESSAGE_SDK,info:"SDK 执行Event发生了异常",level:"error",time:Date.now(),data:a.message,infoType:"sdk"})}},i.prototype.beconEvent=function(e,t){if(Array.isArray(e))console.warn("beconEvent not support batch report, please check");else{var r=[],n=this.processEvent(e,t||{});n&&(r.push(n),r.length&&(this.emit(w.BeconEvent,r),this.emit(w.SessionResetTime)),this.emit(g.DEBUGGER_MESSAGE,{type:g.DEBUGGER_MESSAGE_SDK,info:"SDK 执行Beacon Event",level:"info",time:Date.now(),data:e,infoType:"sdk"}))}},i.prototype.beaconEvent=function(e,t){this.beconEvent(e,t)},i.prototype.processEvent=function(e,t){t===void 0&&(t={});try{if(!e)return console.warn("eventName is null, please check"),null;var r=e;/^event\./.test(e)&&(r=e.slice(6));var n=t;typeof n!="object"&&(n={}),n.profile?delete n.profile:n.event_index=Gf();var s=void 0;return n.local_ms?(s=n.local_ms,delete n.local_ms):s=+new Date,{event:r,params:n,local_time_ms:s,is_bav:this.initConfig&&this.initConfig.autotrack?1:0}}catch(a){return this.emit(g.DEBUGGER_MESSAGE,{type:g.DEBUGGER_MESSAGE_SDK,info:"SDK发生了异常",level:"error",time:Date.now(),data:a.message,infoType:"sdk"}),{event:e,params:t}}},i.prototype.filterEvent=function(e){this.eventFilter=e},i.prototype.on=function(e,t){this.hook.on(e,t)},i.prototype.once=function(e,t){this.hook.once(e,t)},i.prototype.off=function(e,t){this.hook.off(e,t)},i.prototype.emit=function(e,t,r){this.hook.emit(e,t,r)},i.prototype.set=function(e){this.hook.set(e)},i.prototype.stop=function(){this.sdkStop=!0},i.prototype.reStart=function(){this.sdkStop=!1},i.prototype.pageView=function(){this.disableAutoPageView||this.predefinePageView()},i.prototype.predefinePageView=function(e){if(e===void 0&&(e={}),this.inited){var t={title:document.title||location.pathname,url:location.href,url_path:this.handlePath(),time:Date.now(),referrer:window.document.referrer,$is_first_time:""+(this.configManager&&this.configManager.is_first_time||!1)},r=B(B({},t),e);this.emit(g.DEBUGGER_MESSAGE,{type:g.DEBUGGER_MESSAGE_SDK,info:"SDK 上报PV",level:"info",time:Date.now(),infoType:"sdk"}),this.event("predefine_pageview",r)}else console.warn("predefinePageView must be use after function init")},i.prototype.handlePath=function(){var e=location.pathname;try{if(this.initConfig.allow_hash){var t=new URL(location.href).hash.match(/#\/([^?#]+)/i);return t&&t.length?t[1]:location.pathname}}catch{e=location.pathname}return e},i.prototype.clearEventCache=function(){this.emit(w.CleanEvents)},i.prototype.setWebIDviaUnionID=function(e){if(e){var t=Lo(e);this.config({web_id:""+t,wechat_unionid:e}),this.emit(w.CustomWebId)}},i.prototype.setWebId=function(e){this.config({web_id:""+e})},i.prototype.setWebIDviaOpenID=function(e){if(e){var t=Lo(e);this.config({web_id:""+t,wechat_openid:e}),this.emit(w.CustomWebId)}},i.prototype.setNativeAppId=function(e){this.bridgeReport&&this.appBridge.setNativeAppId(e)},i.prototype.setRequestHeaders=function(e){this.emit(w.CustomHeader,e)},i.prototype.getSessionId=function(){return Dt()},i.prototype.setSessionId=function(e){this.emit(w.SessionReset,e)},i.prototype.resetStayDuration=function(e,t,r){this.emit(w.ResetStay,{url_path:e,title:t,url:r},w.Stay)},i.prototype.resetStayParams=function(e,t,r){e===void 0&&(e=""),t===void 0&&(t=""),r===void 0&&(r=""),this.emit(w.SetStay,{url_path:e,title:t,url:r},w.Stay)},i.prototype.getToken=function(e,t){var r=this;if(this.inited){var n=!1,s=function(o){if(!n){n=!0;var d=r.configManager.get().user;return o&&(d.tobid=o,d["diss".split("").reverse().join("")]=o),e(B({},d))}},a=function(){r.tokenManager.getTobId().then(function(o){s(o)})};this.emit(g.DEBUGGER_MESSAGE,{type:g.DEBUGGER_MESSAGE_SDK,info:"SDK 执行GetToken",level:"info",time:Date.now(),infoType:"cus"}),this.sdkReady?a():(t&&setTimeout(function(){s()},t),this.on(w.Ready,function(){a()}))}else console.warn("getToken must be use after function init")},i.prototype.profileSet=function(e){this.bridgeReport?this.appBridge.profileSet(JSON.stringify(e)):this.emit(w.ProfileSet,e,w.Profile),this.emit(g.DEBUGGER_MESSAGE,{type:g.DEBUGGER_MESSAGE_SDK,info:"SDK 执行profileSet",level:"info",time:Date.now(),data:e,infoType:"cus"})},i.prototype.profileSetOnce=function(e){this.bridgeReport?this.appBridge.profileSetOnce(JSON.stringify(e)):this.emit(w.ProfileSetOnce,e,w.Profile),this.emit(g.DEBUGGER_MESSAGE,{type:g.DEBUGGER_MESSAGE_SDK,info:"SDK 执行profileSetOnce",level:"info",time:Date.now(),data:e,infoType:"cus"})},i.prototype.profileIncrement=function(e){this.bridgeReport?this.appBridge.profileIncrement(JSON.stringify(e)):this.emit(w.ProfileIncrement,e,w.Profile),this.emit(g.DEBUGGER_MESSAGE,{type:g.DEBUGGER_MESSAGE_SDK,info:"SDK 执行profileIncrement",level:"info",time:Date.now(),data:e,infoType:"cus"})},i.prototype.profileUnset=function(e){this.bridgeReport?this.appBridge.profileUnset(e):this.emit(w.ProfileUnset,e,w.Profile),this.emit(g.DEBUGGER_MESSAGE,{type:g.DEBUGGER_MESSAGE_SDK,info:"SDK 执行profileUnset",level:"info",time:Date.now(),data:e,infoType:"cus"})},i.prototype.profileAppend=function(e){this.bridgeReport?this.appBridge.profileAppend(JSON.stringify(e)):this.emit(w.ProfileAppend,e,w.Profile),this.emit(g.DEBUGGER_MESSAGE,{type:g.DEBUGGER_MESSAGE_SDK,info:"SDK 执行profileAppend",level:"info",time:Date.now(),data:e,infoType:"cus"})},i.prototype.setExternalAbVersion=function(e){this.emit(w.AbExternalVersion,typeof e=="string"&&e?(""+e).trim():null,w.Ab)},i.prototype.getVar=function(e,t,r){this.emit(w.AbVar,{name:e,defaultValue:t,callback:r},w.Ab)},i.prototype.getABconfig=function(e,t){this.emit(w.AbConfig,{params:e,callback:t},w.Ab)},i.prototype.getABConfig=function(e,t){this.emit(w.AbConfig,{params:e,callback:t},w.Ab)},i.prototype.getAbSdkVersion=function(){return this.configManager.getAbVersion()},i.prototype.onAbSdkVersionChange=function(e){var t=this;return this.emit(w.AbVersionChangeOn,e,w.Ab),function(){t.emit(w.AbVersionChangeOff,e,w.Ab)}},i.prototype.offAbSdkVersionChange=function(e){this.emit(w.AbVersionChangeOff,e,w.Ab)},i.prototype.openOverlayer=function(){this.emit(w.AbOpenLayer,"",w.Ab)},i.prototype.closeOverlayer=function(){this.emit(w.AbCloseLayer,"",w.Ab)},i.prototype.getAllVars=function(e){this.emit(w.AbAllVars,e,w.Ab)},i.prototype.destoryInstace=function(){this.destroy||(this.destroy=!0,this.off(w.TokenComplete),this.emit(w.DestoryInstance))},i.prototype.destroyInstance=function(){this.destroy||(this.destroy=!0,this.off(w.TokenComplete),this.emit(w.DestoryInstance))},i.plugins=[],i}(),En="__rangers_ab_style__";(function(i){i[i.Var=0]="Var",i[i.All=1]="All"})(yi||(yi={}));var Ym=function(){function i(){this.fetchStatus="no",this.refreshFetchStatus="complete",this.versions=[],this.extVersions=[],this.mulilinkVersions=[],this.enable_multilink=!1,this.enable_ab_visual=!1,this.editMode=!1,this.callbacks=[],this.data=null,this.changeListener=new Map,this.readyStatus=!1,this.exposureCache=[]}return i.prototype.apply=function(e,t){var r=this;if(t.enable_ab_test){this.collect=e,this.config=t;var n=t.enable_multilink,s=t.ab_channel_domain,a=t.enable_ab_visual,o=t.ab_cross,d=t.ab_cookie_domain,c=t.ab_timeout,u=s||te(Go[t.channel||"cn"]),l=e.adapters.storage,h=this.collect.Types;this.types=h,this.cacheStorgae=new l(!1),this.timeout=c||3e3,this.enable_multilink=n,this.enable_ab_visual=a,this.abKey="__tea_sdk_ab_version_"+t.app_id,this.ab_cross=o,this.ab_cookie_domain=d||"",this.fetchUrl=u+"/service/2/abtest_config/",this.reportUrl=""+e.configManager.getUrl("event"),this.exposureLimit=t.exposure_limit||20,this.ab_batch_time=t.ab_batch_time||500,this.ab_user_mode=t.ab_user_mode||"user_unique_id",this.callbackMap=new Map,this.collect.on(h.TokenChange,function(p){p==="uuid"&&r.readyStatus&&(r.clearCache(),r.fetchAB())}),this.collect.on(h.TokenReset,function(p){p==="uuid"&&r.readyStatus&&(r.clearCache(),r.fetchAB())}),this.collect.on(h.AbVar,function(p){var f=p.name,v=p.defaultValue,m=p.callback;r.getVar(f,v,m)}),this.collect.on(h.AbAllVars,function(p){r.getAllVars(p)}),this.collect.on(h.AbConfig,function(p){var f=p.params,v=p.callback;r.getABconfig(f,v)}),this.collect.on(h.AbExternalVersion,function(p){r.setExternalAbVersion(p)}),this.collect.on(h.AbOpenLayer,function(){r.openOverlayer()}),this.collect.on(h.AbCloseLayer,function(){r.closeOverlayer()}),this.collect.on(h.AbVersionChangeOn,function(p){r.changeListener.set(p,p)}),this.collect.on(h.AbVersionChangeOff,function(p){r.changeListener.get(p)&&r.changeListener.delete(p)}),this.loadMode(),(this.enable_ab_visual||this.enable_multilink)&&this.openOverlayer(this.config.multilink_timeout_ms||500),this.checkLocal(),this.ready("ab"),this.readyStatus||(this.fetchAB(),this.readyStatus=!0),this.collect.emit(h.AbReady)}},i.prototype.ready=function(e){var t=this;if(this.collect.set(e),this.collect.hook._hooksCache.hasOwnProperty(e)){var r=this.collect.hook._hooksCache[e];if(!Object.keys(r).length)return;var n=function(a){r[a].length&&r[a].forEach(function(o){t.collect.hook.emit(a,o)})};for(var s in r)n(s)}},i.prototype.loadMode=function(){var e=function(){try{var s=JSON.parse(atob(window.name));return s||void 0}catch{return}}(),t="";if(e){var r=e.scenario,n=e.href;r?(this.editMode=!0,t=r):!n||n.indexOf("datatester")===-1&&n.indexOf("visual-editor")===-1||(this.editMode=!0,t="visual-editor")}this.enable_ab_visual&&t==="visual-editor"&&this.collect.destoryInstace()},i.prototype.checkLocal=function(){var e=this.getABCache(),t=e.ab_version,r=e.ab_ext_version,n=e.ab_version_multilink,s=e.data,a=this.checkFromUrl();a?this.mulilinkVersions.push(a):this.mulilinkVersions=n||[],this.extVersions=r||[],this.versions=t||[],this.data=s;var o=this.versions.concat(this.extVersions);this.enable_multilink&&(o=o.concat(this.mulilinkVersions)),this.configVersions(o.join(","))},i.prototype.checkFromUrl=function(){var e=Wi(window.location.href);return e&&e.vid?e.vid:""},i.prototype.updateVersions=function(){var e=this.extVersions.length?this.versions.concat(this.extVersions):this.versions;this.enable_multilink&&(e=e.concat(this.mulilinkVersions)),this.configVersions(e.join(",")),this.updateABCache(),this.changeListener.size>0&&this.changeListener.forEach(function(t){typeof t=="function"&&t(e)})},i.prototype.configVersions=function(e){this.collect.configManager.setAbVersion(e)},i.prototype.getVar=function(e,t,r){if(!e)throw new Error("getVar key must not be empty");if(t===void 0&&console.warn("getVar defaultValue is illegal, please check!"),typeof r!="function")throw new Error("getVar callback must be a function");var n={name:e,defaultValue:t,callback:r,type:yi.Var};this.collect.emit(g.DEBUGGER_MESSAGE,{type:g.DEBUGGER_MESSAGE_SDK,secType:"AB",info:"SDK 调用GetVar",level:"info",time:Date.now(),data:e,infoType:"cus"}),this.fetchStatus==="complete"&&this.refreshFetchStatus==="complete"?this.getRealVar(n,e):(this.callbackMap.get(e),this.callbackMap.set(e,n))},i.prototype.getRealVar=function(e,t){var r=e.name,n=e.defaultValue,s=e.callback,a=this.data;if(a){var o=a[r];if(o&&ti(o)){var d=a[r].vid;return t==="$ab_url"?this.mulilinkVersions.includes(d)||this.mulilinkVersions.push(d):this.versions.includes(d)||this.versions.push(d),this.updateVersions(),this.fechEvent(d,t||r,n,s,o.val),void this.collect.emit(g.DEBUGGER_MESSAGE,{type:g.DEBUGGER_MESSAGE_SDK,secType:"AB",info:"SDK执行GetVar,并曝光了实验"+r,level:"info",time:Date.now(),data:a[r],infoType:"sdk"})}this.collect.emit(g.DEBUGGER_MESSAGE,{type:g.DEBUGGER_MESSAGE_SDK,secType:"AB",info:"SDK执行GerVar默认回调",level:"info",time:Date.now(),data:this.data,infoType:"sdk"}),s(n)}else s(n)},i.prototype.getAllVars=function(e){if(typeof e!="function")throw new Error("getAllVars callback must be a function");var t={callback:e,type:yi.All};this.collect.emit(g.DEBUGGER_MESSAGE,{type:g.DEBUGGER_MESSAGE_SDK,secType:"AB",info:"SDK 调用GetAllVars",level:"info",time:Date.now(),infoType:"cus"}),this.fetchStatus==="complete"&&this.refreshFetchStatus==="complete"?this.getRealAllVars(t):this.callbackMap.set("allVars",t)},i.prototype.getRealAllVars=function(e){(0,e.callback)(this.data?JSON.parse(JSON.stringify(this.data)):{}),this.collect.emit(g.DEBUGGER_MESSAGE,{type:g.DEBUGGER_MESSAGE_SDK,secType:"AB",info:"SDK 执行GetAllVars",level:"info",time:Date.now(),data:this.data,infoType:"sdk"})},i.prototype.fechEvent=function(e,t,r,n,s){try{if(this.config.disable_track_event||!e)return;var a=this.collect.configManager.get(),o=a.header,d=a.user,c=this.getABCache(),u=d[this.ab_user_mode]||d.user_unique_id;if(c&&c.uuid&&c.uuid!==u)return;var l={event:"abtest_exposure",ab_sdk_version:""+e,params:JSON.stringify({app_id:this.config.appId,ab_url:t==="$ab_url"?r:window.location.href}),local_time_ms:Date.now()};o.custom=JSON.stringify(o.custom);var h={events:[l],user:d,header:o};this.reportExposure(h,t),n&&n(s)}catch(p){this.collect.emit(g.DEBUGGER_MESSAGE,{type:g.DEBUGGER_MESSAGE_SDK,info:"SDK 发生了异常",level:"error",time:Date.now(),data:p.message,infoType:"sdk"})}},i.prototype.reportExposure=function(e,t){var r=this;this.exposureCache.push(e),this.reportTimeout&&clearTimeout(this.reportTimeout),this.exposureCache.length>=this.exposureLimit?this.report(t):this.reportTimeout=setTimeout(function(){r.report(t),clearTimeout(r.reportTimeout)},this.ab_batch_time)},i.prototype.report=function(e){var t=this;this.collect.requestManager.useRequest({url:this.reportUrl,data:this.exposureCache,timeout:2e4,useBeacon:e==="$ab_url",zip:!0}),this.exposureCache.forEach(function(r){t.collect.emit(g.DEBUGGER_MESSAGE,{type:g.DEBUGGER_MESSAGE_EVENT,info:"曝光埋点上报成功",time:Date.now(),data:[r],code:200,status:"success",infoType:"sdk"})}),this.collect.emit(this.types.AbVerify,this.exposureCache),this.exposureCache=[]},i.prototype.setExternalAbVersion=function(e){this.extVersions=[e],this.updateVersions()},i.prototype.getABconfig=function(e,t){var r=Object.keys(e);r&&r.length&&this.collect.configManager.set(e),this.fetchAB(t)},i.prototype.get=function(e){if(this.ab_cross){var t=this.cacheStorgae.getCookie(e,this.ab_cookie_domain);return t?JSON.parse(t):{}}return this.cacheStorgae.getItem(e)},i.prototype.set=function(e,t){this.ab_cross?this.cacheStorgae.setCookie(e,t,2592e6,this.ab_cookie_domain):this.cacheStorgae.setItem(e,t),this.collect.configManager.setAbCache(t)},i.prototype.getABCache=function(e){var t={ab_version:[],ab_ext_version:[],ab_version_multilink:[],data:null,timestamp:+new Date,uuid:""};return t=this.get(this.abKey)||t,e?t[e]:t},i.prototype.updateABCache=function(){var e=this.getABCache();e.ab_version_multilink=this.mulilinkVersions,e.ab_ext_version=this.extVersions,e.ab_version=this.versions,e.timestamp=Date.now(),this.set(this.abKey,e)},i.prototype.setAbCache=function(e){var t=this.getABCache();t.data=this.data,t.uuid=e,t.timestamp=Date.now(),this.set(this.abKey,t)},i.prototype.clearCache=function(){this.refreshFetchStatus="ing",this.data={},this.extVersions=[],this.mulilinkVersions=[],this.versions=[],this.collect.configManager.clearAbCache()},i.prototype.openOverlayer=function(e){var t=this;if(function(){if(!document.getElementById(En)){var n="body { opacity: 0 !important; }",s=document.head||document.getElementsByTagName("head")[0],a=document.createElement("style");a.id=En,a.type="text/css",a.styleSheet?a.styleSheet.cssText=n:a.appendChild(document.createTextNode(n)),s.appendChild(a)}}(),e)var r=setTimeout(function(){t.closeOverlayer(),clearTimeout(r)},e)},i.prototype.closeOverlayer=function(){var e;(e=document.getElementById(En))&&e.parentElement.removeChild(e)},i.prototype.fetchComplete=function(e,t){var r=this;try{if(e&&Object.prototype.toString.call(e)=="[object Object]"){var n=this.collect.configManager.get().user;if(t&&t!==n.user_unique_id)return;this.data=e,this.setAbCache(t);var s=[];Object.keys(e).forEach(function(u){var l=e[u].vid;l&&s.push(l)}),this.versions=this.versions.filter(function(u){return s.includes(u)});var a=e.$ab_url,o=e.$ab_modification;if(o&&o.val&&this.enable_ab_visual){if(this.collect.destroy)return;this.collect.emit(g.DEBUGGER_MESSAGE,{type:g.DEBUGGER_MESSAGE_SDK,info:"SDK 执行可视化实验",level:"info",logType:"fetch",time:Date.now(),infoType:"sdk",data:{$ab_modification:o}})}else if(a&&this.enable_multilink){this.mulilinkVersions=this.mulilinkVersions.filter(function(u){return s.includes(u)}),this.collect.emit(g.DEBUGGER_MESSAGE,{type:g.DEBUGGER_MESSAGE_SDK,info:"SDK 执行多链接实验",level:"info",logType:"fetch",time:Date.now(),infoType:"sdk",data:{$ab_url:a}});var d=a.val,c=a.vid;d&&c&&this.getVar("$ab_url",d,function(){r.editMode||(d!==window.location.href?setTimeout(function(){if(!r.collect.destroy){var u=""+d;u=u.indexOf("http")===-1?"https://"+u:u,Xr(u).host!==location.host?u=u+"&vid="+c:window.history.replaceState("","",u),window.location.href=u}},100):r.closeOverlayer())})}this.updateVersions()}else this.closeOverlayer();this.callbackMap.forEach(function(u){return r[u.type===yi.Var?"getRealVar":"getRealAllVars"](u,"")})}catch{}},i.prototype.fetchAB=function(e){var t=this,r=this.collect.configManager.get(),n={header:B(B(B({aid:this.config.app_id},r.user||{}),r.header||{}),{ab_sdk_version:this.collect.configManager.getAbVersion(),ab_url:window.location.href})};this.collect.emit(g.DEBUGGER_MESSAGE,{type:g.DEBUGGER_MESSAGE_SDK,info:"SDK 发起AB实验请求",level:"info",logType:"fetch",time:Date.now(),data:n,infoType:"sdk"});var s=r.user[this.ab_user_mode]||r.user.user_unique_id;this.collect.requestManager.useRequest({url:this.fetchUrl,data:n,success:function(a){t.fetchStatus="complete",t.refreshFetchStatus="complete";var o=a.data;a.message==="success"?(t.fetchComplete(o,s),e&&e(o)):(t.fetchComplete(null,s),e&&e(null)),t.collect.emit(t.types.AbComplete,o),t.collect.emit(g.DEBUGGER_MESSAGE,{type:g.DEBUGGER_MESSAGE_SDK,secType:"AB",info:"AB实验请求成功",level:"info",logType:"fetch",time:Date.now(),data:o,infoType:"sdk"})},fail:function(){t.fetchStatus="complete",t.refreshFetchStatus="complete",t.fetchComplete(null,s),t.collect.emit(t.types.AbTimeout),e&&e(null),t.collect.emit(g.DEBUGGER_MESSAGE,{type:g.DEBUGGER_MESSAGE_SDK,secType:"AB",info:"AB实验请求网络异常",level:"error",logType:"fetch",time:Date.now(),infoType:"sdk"})},timeout:this.timeout})},i}(),e_=function(){function i(){}return i.prototype.apply=function(e,t){var r=this;t.event_verify_url&&(typeof t.event_verify_url=="string"?(this.collect=e,this.url=t.event_verify_url+"/v1/list_test",e.on(e.Types.SubmitBefore,function(n){r.verify(n)}),e.on(e.Types.AbVerify,function(n){r.verify(n)})):console.log("please use correct et_test url"))},i.prototype.verify=function(e){this.collect.requestManager.useBeacon({url:this.url,data:e}),this.collect.emit(g.DEBUGGER_MESSAGE,{type:g.DEBUGGER_MESSAGE_EVENT,info:"SDK Report ByteIo Verify Request",time:Date.now(),data:e,code:200,status:"success",verifyType:!0})},i}();function nr(i,e,t){if(e===void 0&&(e="list"),!i)return!1;if(e&&e==="list"){if(["LI","TR","DL"].includes(i.nodeName)||i.dataset&&i.dataset.hasOwnProperty("teaIdx")||i.hasAttribute&&i.hasAttribute("data-tea-idx"))return!0}else if(["A","BUTTON"].includes(i.nodeName)||i.dataset&&i.dataset.hasOwnProperty("teaContainer")||i.hasAttribute&&i.hasAttribute("data-tea-container")||t&&i.hasAttribute&&i.hasAttribute(t))return!0;return!1}var ka=function(i,e){return!!i_(i,e)};function wn(i,e){for(var t=i;t&&!nr(t,"container",e.container_attr||"");){if(t.nodeName==="HTML"||t.nodeName==="BODY")return i;t=t.parentElement}return t||i}var t_=function(i){if(!i)return"";var e="";try{i.textContent?e=i.textContent.trim().replace(/\s+/g,","):i.innerText&&(e=i.innerText.trim().replace(/\s+/g,",")),i.tagName!=="input"&&i.tagName!=="INPUT"||(e=i.value||"")}finally{return e}};function Ta(i){try{for(var e=i;e&&e.parentNode;){if(e.hasAttribute("data-tea-ignore")||e.classList&&e.classList.contains("applog-web-devtools-con"))return!0;if(e.nodeName==="HTML"||e.nodeName==="body")return!1;e=e.parentNode}return!1}catch{return!1}}var sr=function(i,e){return i.hasAttribute?i.hasAttribute(e):i.attributes?!(!i.attributes[e]||!i.attributes[e].specified):void 0},i_=function(i,e){if(typeof e=="string")return sr(i,e);if(Ki(e)){for(var t=!1,r=0;r<e.length;r++)if(sr(i,e[r])){t=!0;break}return t}},za=function(i,e){var t={};if(typeof e=="string")sr(i,e)&&(t[e]=i.getAttribute(e));else if(Ki(e))for(var r=0;r<e.length;r++)sr(i,e[r])&&(t[e[r]]=i.getAttribute(e[r]));return t};function Aa(i){var e=[];if(!i)return{element_path:"",positions:[]};for(;i.parentElement!==null;)e.push(i),i=i.parentElement;var t=[],r=[];return e.forEach(function(n){var s=function(d){if(d===null)return{str:"",index:0};var c=0,u=d.parentElement;if(u)for(var l=u.children,h=0;h<l.length&&l[h]!==d;h++)l[h].nodeName===d.nodeName&&c++;return{str:[d.nodeName.toLowerCase(),nr(d,"list")?"[]":""].join(""),index:c}}(n),a=s.str,o=s.index;t.unshift(a),r.unshift(o)}),{element_path:"/"+t.join("/"),positions:r}}var r_=function(){function i(e,t){this.maxDuration=432e5,this.aliveDTime=6e4,this.options={aliveName:"predefine_page_alive",params:{},container:null},this.focusState=!0,this.collect=e,this.config=t,this.pageStartTime=Date.now(),this.sessionStartTime=this.pageStartTime,this.timerHandler=null,ti(t.enable_stay_duration)&&(this.options=Object.assign(this.options,t.enable_stay_duration)),this.hard=this.options.mode&&this.options.mode==="hard",this.focusState=document.hasFocus(),this.aliveDTime=this.options.aliveTime||6e4}return i.prototype.setParams=function(e,t,r){this.set_path=e,this.set_url=r,this.set_title=t},i.prototype.enable=function(e,t,r){this.url_path=e,this.url=r,this.title=t,this.disableCallback=this.enablePageAlive(),this.hard&&(this.removeMode=this.hardMode())},i.prototype.disable=function(){this.disableCallback(),this.pageStartTime=Date.now(),this.hard&&this.removeMode&&this.removeMode()},i.prototype.sendEvent=function(e,t){t===void 0&&(t=!1);var r=t?this.aliveDTime:Date.now()-this.sessionStartTime;if(!(r<0||r>this.aliveDTime||Date.now()-this.pageStartTime>this.maxDuration)&&(!t||document.visibilityState!=="hidden")&&(!this.hard||this.focusState)){var n=B({url_path:this.getParams("url_path"),title:this.getParams("title"),url:this.getParams("url"),duration:r,is_support_visibility_change:Po(),startTime:this.sessionStartTime,hidden:document.visibilityState,leave:e,mode:this.hard?"hard":"normal",focusState:this.focusState,aliveType:this.options.container?"dom":"page"},this.options.params);if(this.options.container){var s=Aa(this.options.container).element_path;n=Object.assign(n,{element_path:s,aliveType:this.options.container?"dom":"page"})}this.collect.beconEvent(this.options.aliveName,n),this.sessionStartTime=Date.now()}},i.prototype.getParams=function(e){switch(e){case"url_path":return this.set_path||this.url_path||location.pathname;case"title":return this.set_title||this.title||document.title||location.pathname;case"url":return this.set_url||this.url||location.href}},i.prototype.setUpTimer=function(){var e=this;return this.timerHandler&&clearInterval(this.timerHandler),setInterval(function(){Date.now()-e.sessionStartTime>e.aliveDTime&&e.sendEvent(!1,!0)},1e3)},i.prototype.visibilitychange=function(){this.getDisplayStatus()==="hidden"?this.timerHandler&&(clearInterval(this.timerHandler),this.sendEvent(!1)):this.getDisplayStatus()==="visible"&&(this.sessionStartTime=Date.now(),this.timerHandler=this.setUpTimer())},i.prototype.getDisplayStatus=function(){if(!this.options.container)return document.visibilityState;try{var e=window.getComputedStyle(this.options.container);return e.display!=="none"&&e.visibility!=="hidden"&&e.opacity!=="0"?"visible":"hidden"}catch{return"visible"}},i.prototype.beforeunload=function(){document.hidden||this.sendEvent(!0)},i.prototype.muition=function(){var e=this;new MutationObserver(function(t){t.forEach(function(r){e.visibilitychange()})}).observe(this.options.container,{attributes:!0,attributeFilter:["style"]})},i.prototype.enablePageAlive=function(){var e=this;this.timerHandler=this.setUpTimer();var t=this.visibilitychange.bind(this),r=this.beforeunload.bind(this);return this.options.container?this.muition():document.addEventListener("visibilitychange",t),window.addEventListener("pagehide",r),function(){e.beforeunload(),document.removeEventListener("visibilitychange",t),window.removeEventListener("pagehide",r)}},i.prototype.hardMode=function(){var e=this,t=function(){e.timerHandler&&(clearInterval(e.timerHandler),e.sendEvent(!1)),e.focusState=!1},r=function(){e.focusState=!0,e.sessionStartTime=Date.now(),e.timerHandler=e.setUpTimer()};return window.addEventListener("blur",t),window.addEventListener("focus",r),function(){window.removeEventListener("blur",t),window.removeEventListener("focus",r)}},i}(),n_=function(){function i(e,t){var r=this;this.maxDuration=432e5,this.aliveDTime=6e4,this.options={closeName:"predefine_page_close",params:{}},this.focusState=!0,this.visibilitychange=function(){document.visibilityState==="hidden"?r.activeEndTime=Date.now():document.visibilityState==="visible"&&(r.activeEndTime&&(r.totalTime+=r.activeEndTime-r.activeStartTime,r.activeTimes+=1),r.activeEndTime=void 0,r.activeStartTime=Date.now())},this.beforeunload=function(){if(r.totalTime+=(r.activeEndTime||Date.now())-r.activeStartTime,r.config.autotrack)try{window.sessionStorage.setItem("_tea_cache_duration",JSON.stringify({duration:r.totalTime,page_title:document.title||location.pathname}))}catch{}r.sendEventPageClose()},this.collect=e,this.config=t,this.maxDuration=t.maxDuration||t.max_duration||864e5,this.pageStartTime=Date.now(),ti(t.enable_stay_duration)&&(this.options=Object.assign(this.options,t.enable_stay_duration)),this.hard=this.options.mode&&this.options.mode==="hard",this.focusState=document.hasFocus(),this.resetData()}return i.prototype.setParams=function(e,t,r){this.set_path=e,this.set_url=r,this.set_title=t},i.prototype.resetParams=function(e,t,r){this.url_path=e,this.url=r,this.title=t},i.prototype.enable=function(e,t,r){this.url_path=e,this.url=r,this.title=t,this.disableCallback=this.enablePageClose(),this.hard&&(this.removeMode=this.hardMode())},i.prototype.disable=function(){this.disableCallback(),this.hard&&this.removeMode&&this.removeMode(),this.resetData()},i.prototype.resetData=function(){this.activeStartTime=this.activeStartTime===void 0?this.pageStartTime:Date.now(),this.activeEndTime=void 0,this.activeTimes=1,this.totalTime=0,this.resetParams(location.pathname,document.title,location.href)},i.prototype.sendEventPageClose=function(){var e=Date.now()-this.pageStartTime;this.totalTime<0||e<0||this.totalTime>=this.maxDuration||this.hard&&!this.focusState||(this.collect.beconEvent(this.options.closeName,B({url_path:this.getParams("url_path"),title:this.getParams("title"),url:this.getParams("url"),active_times:this.activeTimes,duration:this.totalTime,total_duration:e,is_support_visibility_change:Po(),mode:this.hard?"hard":"normal",focusState:this.focusState},this.options.params)),this.pageStartTime=Date.now(),this.resetData())},i.prototype.getParams=function(e){switch(e){case"url_path":return this.set_path||this.url_path||location.pathname;case"title":return this.set_title||this.title||document.title||location.pathname;case"url":return this.set_url||this.url||location.href}},i.prototype.enablePageClose=function(){var e=this,t=this.visibilitychange.bind(this),r=this.beforeunload.bind(this);return document.addEventListener("visibilitychange",t),window.addEventListener("pagehide",r),function(){e.beforeunload(),document.removeEventListener("visibilitychange",t),window.removeEventListener("pagehide",r)}},i.prototype.hardMode=function(){var e=this,t=function(){e.focusState=!1},r=function(){e.focusState=!0};return window.addEventListener("blur",t),window.addEventListener("focus",r),function(){window.removeEventListener("blur",t),window.removeEventListener("focus",r)}},i}(),s_=function(){function i(){}return i.prototype.apply=function(e,t){var r=this;if(this.collect=e,this.config=t,this.config.enable_stay_duration){this.title=document.title||location.pathname,this.url=location.href,this.url_path=location.pathname,this.pageAlive=new r_(e,t),this.pageClose=new n_(e,t);var n=this.collect.Types;this.collect.on(n.DestoryInstance,function(){r.disable()}),this.collect.on(n.ResetStay,function(s){var a=s.url_path,o=s.title,d=s.url;r.resetStayDuration(a,o,d)}),this.collect.on(n.RouteChange,function(s){s.init||t.disable_route_report||r.resetStayDuration()}),this.collect.on(n.SetStay,function(s){var a=s.url_path,o=s.title,d=s.url;r.setStayParmas(a,o,d)}),this.enable(this.url_path,this.title,this.url),this.ready(n.Stay),this.collect.emit(n.StayReady)}},i.prototype.ready=function(e){var t=this;if(this.collect.set(e),this.collect.hook._hooksCache.hasOwnProperty(e)){var r=this.collect.hook._hooksCache[e];if(!Object.keys(r).length)return;var n=function(a){r[a].length&&r[a].forEach(function(o){t.collect.hook.emit(a,o)})};for(var s in r)n(s)}},i.prototype.enable=function(e,t,r){this.pageAlive.enable(e,t,r),this.pageClose.enable(e,t,r)},i.prototype.disable=function(){this.pageAlive.disable(),this.pageClose.disable()},i.prototype.setStayParmas=function(e,t,r){e===void 0&&(e=""),t===void 0&&(t=""),r===void 0&&(r=""),this.pageAlive.setParams(e,t,r),this.pageClose.setParams(e,t,r),this.collect.emit(g.DEBUGGER_MESSAGE,{type:g.DEBUGGER_MESSAGE_SDK,info:"SDK 执行 resetStayParams",level:"info",time:Date.now(),data:{url_path:e,title:t,url:r}})},i.prototype.reset=function(e,t,r){this.disable(),this.enable(e,t,r)},i.prototype.resetStayDuration=function(e,t,r){this.reset(e,t,r),this.collect.emit(g.DEBUGGER_MESSAGE,{type:g.DEBUGGER_MESSAGE_SDK,info:"SDK 执行 resetStayDuration",level:"info",time:Date.now(),data:{url_path:e,title:t,url:r}})},i}(),o_=function(){function i(){}return i.prototype.apply=function(e,t){var r=this;this.collect=e,this.config=t,this.duration=6e4,this.reportUrl=e.configManager.getDomain()+"/profile/list";var n=e.Types;this.eventCheck=new rn(e,t),this.cache={},this.collect.on(n.ProfileSet,function(s){r.setProfile(s)}),this.collect.on(n.ProfileSetOnce,function(s){r.setOnceProfile(s)}),this.collect.on(n.ProfileUnset,function(s){r.unsetProfile(s)}),this.collect.on(n.ProfileIncrement,function(s){r.incrementProfile(s)}),this.collect.on(n.ProfileAppend,function(s){r.appendProfile(s)}),this.collect.on(n.ProfileClear,function(){r.cache={}}),this.ready(n.Profile)},i.prototype.ready=function(e){var t=this;if(this.collect.set(e),this.collect.hook._hooksCache.hasOwnProperty(e)){var r=this.collect.hook._hooksCache[e];if(!Object.keys(r).length)return;var n=function(a){r[a].length&&r[a].forEach(function(o){t.collect.hook.emit(a,o)})};for(var s in r)n(s)}},i.prototype.report=function(e,t){t===void 0&&(t={});try{if(this.config.disable_track_event)return;var r=[];r.push(this.collect.processEvent(e,t));var n=this.collect.eventManager.merge(r);this.collect.requestManager.useRequest({url:this.reportUrl,data:n}),this.collect.emit(g.DEBUGGER_MESSAGE,{type:g.DEBUGGER_MESSAGE_EVENT,info:"埋点上报成功",time:Date.now(),data:n,code:200,status:"success"})}catch(s){this.collect.emit(g.DEBUGGER_MESSAGE,{type:g.DEBUGGER_MESSAGE_SDK,info:"发生了异常",level:"error",time:Date.now(),data:s.message})}},i.prototype.setProfile=function(e){var t=this.formatParams(e);t&&Object.keys(t).length&&(this.pushCache(t),this.report("__profile_set",B(B({},t),{profile:!0})))},i.prototype.setOnceProfile=function(e){var t=this.formatParams(e,!0);t&&Object.keys(t).length&&(this.pushCache(t),this.report("__profile_set_once",B(B({},t),{profile:!0})))},i.prototype.incrementProfile=function(e){e?this.report("__profile_increment",B(B({},e),{profile:!0})):console.warn("please check the params, must be object!!!")},i.prototype.unsetProfile=function(e){if(e){var t={};t[e]="1",this.report("__profile_unset",B(B({},t),{profile:!0}))}else console.warn("please check the key, must be string!!!")},i.prototype.appendProfile=function(e){if(e){var t={};for(var r in e)typeof e[r]=="string"||Object.prototype.toString.call(e[r]).slice(8,-1)==="Array"?t[r]=e[r]:console.warn("please check the value of param: "+r+", must be string or array !!!");Object.keys(t).length&&this.report("__profile_append",B(B({},t),{profile:!0}))}else console.warn("please check the params, must be object!!!")},i.prototype.pushCache=function(e){var t=this;Object.keys(e).forEach(function(r){t.cache[r]={val:t.clone(e[r]),timestamp:Date.now()}})},i.prototype.formatParams=function(e,t){var r=this;t===void 0&&(t=!1);try{if(!e||Object.prototype.toString.call(e)!=="[object Object]")return void console.warn("please check the params type, must be object !!!");var n={};for(var s in e)typeof e[s]=="string"||typeof e[s]=="number"||Object.prototype.toString.call(e[s]).slice(8,-1)==="Array"?n[s]=e[s]:console.warn("please check the value of params:"+s+", must be string,number,Array !!!");var a=Object.keys(n);if(!a.length||!this.eventCheck.checkEventParams(n))return;var o=Date.now();return a.filter(function(d){var c=r.cache[d];return t?!c:!(c&&r.compare(c.val,e[d])&&o-c.timestamp<r.duration)}).reduce(function(d,c){return d[c]=n[c],d},{})}catch(d){this.collect.emit(g.DEBUGGER_MESSAGE,{type:g.DEBUGGER_MESSAGE_SDK,info:"发生了异常",level:"error",time:Date.now(),data:d.message}),console.log("error")}},i.prototype.compare=function(e,t){try{return JSON.stringify(e)===JSON.stringify(t)}catch(r){return this.collect.emit(g.DEBUGGER_MESSAGE,{type:g.DEBUGGER_MESSAGE_SDK,info:"发生了异常",level:"error",time:Date.now(),data:r.message}),!1}},i.prototype.clone=function(e){try{return JSON.parse(JSON.stringify(e))}catch(t){return this.collect.emit(g.DEBUGGER_MESSAGE,{type:g.DEBUGGER_MESSAGE_SDK,info:"发生了异常",level:"error",time:Date.now(),data:t.message}),e}},i.prototype.unReady=function(){console.warn("sdk is not ready, please use this api after start")},i}(),a_=function(){function i(){var e=this;this.setInterval=function(){e.clearIntervalFunc=Bf(function(){e.isSessionhasEvent&&e.endCurrentSession()},e.sessionInterval)},this.clearInterval=function(){e.clearIntervalFunc&&e.clearIntervalFunc()}}return i.prototype.apply=function(e,t){var r=this;if(this.collect=e,!t.disable_heartbeat){this.sessionInterval=6e4,this.startTime=0,this.lastTime=0,this.setInterval();var n=this.collect.Types;this.collect.on(n.SessionResetTime,function(){r.process()})}},i.prototype.endCurrentSession=function(){this.collect.event("_be_active",{start_time:this.startTime,end_time:this.lastTime,url:window.location.href,referrer:window.document.referrer,title:document.title||location.pathname}),this.isSessionhasEvent=!1,this.startTime=0},i.prototype.process=function(){this.isSessionhasEvent||(this.isSessionhasEvent=!0,this.startTime=+new Date);var e=this.lastTime||+new Date;this.lastTime=+new Date,this.lastTime-e>this.sessionInterval&&(this.clearInterval(),this.endCurrentSession(),this.setInterval())},i}(),c_=function(){function i(){}return i.prototype.apply=function(e,t){var r=this;t.channel_domain||t.disable_track_event||t.disable_sdk_monitor||(this.collect=e,this.config=t,this.url=e.configManager.getUrl("event"),this.collect.on(e.Types.Ready,function(){r.sdkOnload()}),this.collect.on(e.Types.SubmitError,function(n){var s=n.type,a=n.eventData,o=n.errorCode,d=n.response;s==="f_data"&&r.sdkError(a,o,d)}),this.collect.on(e.Types.SDKInnerError,function(n){var s=n.type,a=n.eventData,o=n.errorCode,d=n.msg;r.sdkInnerError(s,a,o,d)}))},i.prototype.sdkOnload=function(){var e=this;try{var t=this.collect.configManager.get(),r=t.header,n=t.user,s=r.app_id,a=r.app_name,o=r.sdk_version,d=n.web_id,c={events:[{event:"onload",params:JSON.stringify({app_id:s,app_name:a||"",sdk_version:o,sdk_type:"npm",sdk_config:this.config,sdk_desc:"TOC",url:location.href}),local_time_ms:Date.now()}],user:{user_unique_id:d},header:{}};setTimeout(function(){e.collect.requestManager.useRequest({url:e.url,data:[c],timeout:3e4,app_key:"566f58151b0ed37e",forceXhr:!0})},16)}catch{}},i.prototype.sdkError=function(e,t,r){var n=this;try{var s=e[0],a=s.user,o=s.header,d=[];e.forEach(function(u){u.events.forEach(function(l){d.push(l)})});var c={events:d.map(function(u){return{event:"on_error",params:JSON.stringify({type:"sdk_event_error",error_code:t,app_id:o.app_id,app_name:o.app_name||"",error_event:u.event,sdk_version:o.sdk_version,local_time_ms:u.local_time_ms,tea_event_index:Date.now(),params:u.params,header:o,user:a,err_msg:r.m||""}),local_time_ms:Date.now()}}),user:{user_unique_id:a.user_unique_id},header:{}};setTimeout(function(){n.collect.requestManager.useRequest({url:n.url,data:[c],timeout:3e4,app_key:"566f58151b0ed37e",forceXhr:!0})},16)}catch{}},i.prototype.sdkInnerError=function(e,t,r,n){var s=this;try{var a=t[0],o=a.user,d=a.header,c=[];t.forEach(function(l){l.events.forEach(function(h){c.push(h)})});var u={events:c.map(function(l){return{event:"on_error",params:JSON.stringify({type:e,error_code:r,app_id:d.app_id,app_name:d.app_name||"",error_event:l.event,sdk_version:d.sdk_version,local_time_ms:l.local_time_ms,tea_event_index:Date.now(),params:l.params,header:d,user:o,ua:window.navigator.userAgent,err_msg:n}),local_time_ms:Date.now()}}),user:o,header:{}};setTimeout(function(){s.collect.requestManager.useRequest({url:s.url,data:[u],timeout:3e4,app_key:"566f58151b0ed37e",forceXhr:!0})},16)}catch{}},i}(),u_=function(i){if(i.children.length){var e=i.children;return![].slice.call(e).some(function(t){return t.children.length>0})}return!0},d_=function(i){if(i.tagName.toLowerCase()==="svg")return!0;for(var e=i.parentElement,t=!1;e;)e.tagName.toLowerCase()==="svg"?(e=null,t=!0):e=e.parentElement;return t};function h_(i,e){if(i.nodeType!==1||!e.svg&&d_(i)||["HTML","BODY"].includes(i.tagName.toUpperCase()))return!1;var t=i;return t.style.display!=="none"&&(!!nr(t,"container",e.container_attr||"")||!!(function(r,n){for(var s=r,a=!1;s&&!nr(s,"container",n.container_attr||"");){if(s.nodeName==="HTML"||s.nodeName==="BODY")return a;s=s.parentElement}return a=!0}(t,e)||u_(t)||e.svg))}var l_=function(){function i(e,t,r){var n=this;this.statistics=!1,this.pageView=!1,this.clickEvent=function(s){h_(s.target,n.options)&&n.eventHandel({eventType:"dom",eventName:"click"},s)},this.changeEvent=function(s){n.eventHandel({eventType:"dom",eventName:"change"},s)},this.submitEvent=function(s){n.eventHandel({eventType:"dom",eventName:"submit"},s)},this.getPageViewEvent=function(s,a){a&&a==="pushState"&&n.eventHandel({eventType:"dom",eventName:"beat"},B({beat_type:0},s)),n.eventHandel({eventType:"dom",eventName:"page_view"},s)},this.getPageLoadEvent=function(s){n.eventHandel({eventType:"dom",eventName:"page_statistics"},{lcp:s})},this.config=r.getConfig().eventConfig,this.collect=t,this.options=e,this.beatTime=e.beat,this.domContainer=e.container||document}return i.prototype.init=function(e){this.eventHandel=e;var t=this.config.mode;this.addListener(t)},i.prototype.addListener=function(e){var t=this;if(e==="proxy-capturing"){if(this.config.click&&(Ki(this.domContainer)?this.domContainer.forEach(function(c){c.addEventListener("click",t.clickEvent,!0)}):this.domContainer.addEventListener("click",this.clickEvent,!0)),this.config.pv){this.collect.on("route-change",function(c){var u=c.config,l=c.name;t.getPageViewEvent(u,l),t.pageView=!0});var r=setTimeout(function(){t.pageView||(t.getPageViewEvent(t.getDefaultConfig()),t.pageView=!0,clearTimeout(r))},2e3)}if(this.config.beat){try{document.readyState==="complete"?this.beatEvent(this.beatTime):window.addEventListener("load",function(){t.beatEvent(t.beatTime)});var n=0,s=null;window.addEventListener("scroll",function(){clearTimeout(s),s=setTimeout(a,500),n=document.documentElement.scrollTop||document.body.scrollTop});var a=function(){(document.documentElement.scrollTop||document.body.scrollTop)==n&&t.eventHandel({eventType:"dom",eventName:"beat"},{beat_type:1})}}catch{}try{var o=window.performance&&window.performance.getEntriesByType("paint");if(o&&o.length){new PerformanceObserver(function(c){var u=c.getEntries(),l=u[u.length-1],h=l.renderTime||l.loadTime;t.statistics||(t.getPageLoadEvent(h),t.statistics=!0)}).observe({entryTypes:["largest-contentful-paint"]});var d=setTimeout(function(){t.statistics||(t.getPageLoadEvent(o[0].startTime||0),t.statistics=!0,clearTimeout(d))},2e3)}else this.getPageLoadEvent(0)}catch{this.getPageLoadEvent(0)}}}},i.prototype.removeListener=function(){var e=this;Ki(this.domContainer)?this.domContainer.forEach(function(t){t.removeEventListener("click",e.clickEvent,!0)}):this.domContainer.removeEventListener("click",this.clickEvent,!0)},i.prototype.beatEvent=function(e){var t=this;try{var r;this.eventHandel({eventType:"dom",eventName:"beat"},{beat_type:3}),this.beatTime&&(r=setInterval(function(){t.eventHandel({eventType:"dom",eventName:"beat"},{beat_type:2})},e)),Jr(function(){t.eventHandel({eventType:"dom",eventName:"beat",eventSend:"becon"},{beat_type:0}),t.beatTime&&clearInterval(r)})}catch{}},i.prototype.getDefaultConfig=function(){return{is_html:1,url:location.href,referrer:document.referrer,page_key:location.href,refer_page_key:document.referrer,page_title:document.title||location.pathname,page_manual_key:"",refer_page_manual_key:"",refer_page_title:"",page_path:location.pathname,page_host:location.host}},i}(),p_={eventConfig:{mode:"proxy-capturing",submit:!1,click:!0,change:!1,pv:!0,beat:!0,hashTag:!1,impr:!1},scoutConfig:{mode:"xpath"}},f_=function(){function i(e,t){this.config=e,this.config.eventConfig=Object.assign(this.config.eventConfig,t)}return i.prototype.getConfig=function(){return this.config},i.prototype.setConfig=function(e){return this.config=e},i}();function m_(i,e,t,r){var n={},s=function(R){if(R){var A=R.getBoundingClientRect(),D=A.width,P=A.height;return{left:A.left,top:A.top,element_width:D,element_height:P}}}(e=wn(e,t)),a=function(R,A){R===void 0&&(R={}),A===void 0&&(A={});var D=R.clientX,P=R.clientY,K=A.left,H=A.top,J=D-K>=0?D-K:0,X=P-H>=0?P-H:0;return{touch_x:Math.floor(J),touch_y:Math.floor(X)}}(i,s),o=s.element_width,d=s.element_height,c=a.touch_x,u=a.touch_y,l=Aa(e),h=l.element_path,p=l.positions,f=function(R,A){var D=wn(R,A),P=[];return function K(H){var J=function(q){var ne="";return q.nodeType===3?ne=q.textContent.trim():q.dataset&&q.dataset.hasOwnProperty("teaTitle")||q.hasAttribute("ata-tea-title")?ne=q.getAttribute("data-tea-title"):q.nodeName==="INPUT"&&["button","submit"].includes(q.getAttribute("type"))?ne=q.getAttribute("value"):q.nodeName==="IMG"&&q.getAttribute("alt")&&(ne=q.getAttribute("alt")),ne.slice(0,200)}(H);if(J&&P.indexOf(J)===-1&&P.push(J),H.childNodes.length>0)for(var X=H.childNodes,de=0;de<X.length;de++)X[de].nodeType!==8&&K(X[de])}(D),P}(e,t),v=window.performance.timing.navigationStart,m=Date.now()-v,b=p.map(function(R){return""+R}),y=null;if(window.TEAVisualEditor&&window.TEAVisualEditor.getOriginXpath&&(y=window.TEAVisualEditor.getOriginXpath({xpath:h,positions:b})),n.element_path=y&&y.xpath||h,n.positions=y&&y.positions||b,r&&!r.text&&(n.texts=f,n.element_title=e.getAttribute("data-tea-title")||e.getAttribute("title")||t_(e)),n.element_id=e.getAttribute("id")||"",n.element_class_name=e.getAttribute("class")||"",n.element_type=e.nodeType,n.element_width=Math.floor(o),n.element_height=Math.floor(d),n.touch_x=c,n.touch_y=u,n.page_manual_key="",n.elememt_manual_key="",n.since_page_start_ms=m,n.page_start_ms=v,n.page_path=location.pathname,n.page_host=location.host,t.track_attr&&ka(e,t.track_attr)){var _=za(e,t.track_attr);for(var E in _)n[E]=_[E]}if(t.custom_attr)try{if(ka(e,t.custom_attr)){_=za(e,t.custom_attr),E=decodeURIComponent(_[t.custom_attr]);var z=JSON.parse(E);if(Object.keys(z))for(var T in z)n[T]=z[T]}}catch{console.log("custom attr error")}var x=wn(e,t);return x.tagName==="A"&&(n.href=x.getAttribute("href")),e.tagName==="IMG"&&(n.src=e.getAttribute("src")),n}var Mt=function(i,e,t,r,n){return B(B({event:i},m_(e,t,r,n)),{is_html:1,page_key:window.location.href,page_title:document.title})},__=function(){function i(e,t){this.ignore={text:!1},this.initConfig=e,this.options=t,this.eventName=t&&t.custom==="tea"?{click:"__bav_click",page:"__bav_page",beat:"__bav_beat",static:"__bav_page_statistics",exposure:"__bav_page_exposure",scroll:"__bav_slide"}:{click:"bav2b_click",page:"bav2b_page",beat:"bav2b_beat",static:"bav2b_page_statistics",exposure:"bav2b_exposure",scroll:"$bav2b_slide"},t&&t.text===!1&&(this.ignore.text=!0),t&&t.exposure&&t.exposure.eventName&&(this.eventName.exposure=t.exposure.eventName)}return i.prototype.handleEvent=function(e,t){try{if(Ta(e.target))return null;var r="bav2b_click";switch(t){case"click":return r=e.target.getAttribute("data-applog-click-event")||this.eventName.click||"",Mt(r,e,e.target,this.options,this.ignore);case"exposure":return r=e.target.getAttribute("data-applog-exposure-event")||this.eventName.exposure||"",Mt(r,e,e.target||e,this.options,this.ignore);case"change":return B(B({},Mt(r="bav2b_change",e,e.target,this.options)),function(n,s){try{if(n==="bav2b_change")return s.hasAttribute("data-tea-track")?{value:s.value}:{}}catch{return{}}}(r,e.target));case"submit":return Mt(r="bav2b_submit",e,e.target,this.options)}}catch(n){return console.error(n),null}},i.prototype.handleViewEvent=function(e){e.event=this.eventName.page,e.page_title=document.title,e.page_total_width=window.innerWidth,e.page_total_height=window.innerHeight;try{var t=window.sessionStorage.getItem("_tea_cache_duration");if(t){var r=JSON.parse(t);e.refer_page_duration_ms=r?r.duration:""}e.scroll_width=document.documentElement.scrollLeft?document.documentElement.scrollLeft+window.innerWidth:window.innerWidth,e.scroll_height=document.documentElement.scrollTop?document.documentElement.scrollTop+window.innerHeight:window.innerHeight,e.page_start_ms=window.performance.timing.navigationStart}catch(n){console.log("page event error "+JSON.stringify(n))}return e},i.prototype.handleStatisticsEvent=function(e){var t={};t.event=this.eventName.static,t.is_html=1,t.page_key=location.href,t.refer_page_key=document.referrer||"",t.page_title=document.title,t.page_manual_key=this.initConfig.autotrack.page_manual_key||"",t.refer_page_manual_key="";try{var r=e.lcp,n=window.performance.timing,s=n.loadEventEnd-n.navigationStart;t.page_init_cost_ms=parseInt(r||(s>0?s:0)),t.page_start_ms=n.navigationStart}catch(a){console.log("page_statistics event error "+JSON.stringify(a))}return t},i.prototype.handleBeadtEvent=function(e){e.event=this.eventName.beat,e.page_key=window.location.href,e.is_html=1,e.page_title=document.title,e.page_manual_key=this.initConfig.autotrack.page_manual_key||"";try{e.page_viewport_width=window.innerWidth,e.page_viewport_height=window.innerHeight,e.page_total_width=document.documentElement.scrollWidth,e.page_total_height=document.documentElement.scrollHeight,e.scroll_width=document.documentElement.scrollLeft+window.innerWidth,e.scroll_height=document.documentElement.scrollTop+window.innerHeight,e.since_page_start_ms=Date.now()-window.performance.timing.navigationStart,e.page_start_ms=window.performance.timing.navigationStart}catch(t){console.log("beat event error "+JSON.stringify(t))}return e},i.prototype.handleExposureEvent=function(e,t){if(Ta(t.target))return null;var r=Mt(e.event||this.eventName.exposure,t,t.target||t,this.options,this.ignore);if(r.$exposure_type=e.exposureType,this.options.exposure.callback){var n=this.options.exposure.callback(r);return n||Object.keys(n).length?n:(console.warn("exposure callback must return data!"),r)}return r},i.prototype.handleScrollEvent=function(e,t){var r=Mt(e.event||this.eventName.scroll,t,t.target||t,this.options,this.ignore);if(r=Object.assign(r,e.params),!this.options.scroll.callback||(r=this.options.scroll.callback(r))||Object.keys(r).length)return r;console.warn("scroll callback must return data!")},i}(),g_=function(){function i(e){this.collect=e,this.eventNameList=["report_click_event","report_change_event","report_submit_event","report_exposure_event","report_page_view_event","report_page_statistics_event","report_beat_event"]}return i.prototype.send=function(e,t){var r=t.event;delete t.event,e&&e.eventSend==="becon"?this.collect.beconEvent(r,t):this.collect.event(r,t)},i.prototype.get=function(e,t){var r=Object.assign({headers:{"content-type":"application/json"},method:"GET"},t);fetch(e,r)},i.prototype.post=function(e,t){var r=Object.assign({headers:{"content-type":"application/json"},method:"POST"},t);fetch(e,r)},i}(),bi={},Ra=[],v_=function(i){i.length&&i.forEach(function(e){Ra.push(e)})};function Da(i,e,t,r){var n=i&&i.source||window.opener||window.parent,s=i&&i.origin||r||"*",a={type:e,payload:t};n.postMessage(JSON.stringify(a),s)}function y_(i){if(Ra.some(function(n){return i.origin.indexOf(n)>-1})){var e=i.data;if(typeof i.data=="string")try{e=JSON.parse(i.data)}catch{e=void 0}if(!e)return;var t=e.type,r=e.payload;bi[t]&&bi[t].forEach(function(n){typeof n=="function"&&n(i,r)})}}var Cn=!1;function b_(i,e){window.TEAVisualEditor=window.TEAVisualEditor||{},window.TEAVisualEditor.appId=e.app_id;var t=e.channel_domain,r="";if(v_(qf),t){var n=void 0,s="";try{var a=window.performance.getEntriesByType("resource");if(a&&a.length&&(a.forEach(function(c){c.initiatorType==="script"&&c.name&&c.name.indexOf("collect")!==-1&&(s=c.name)}),s&&(n=s.split("/"))&&n.length)){r="https:/";for(var o=2;o<n.length&&o!==n.length-1;o++)r=r+"/"+n[o];if(r&&r.indexOf("/5.0")){var d=r.split("/5.0");r=d[0]||r}}}catch{}}(function(c,u){var l={};if(Object.keys(c).length)for(var h in c){if(h==="filter"||h==="autotrack"||h==="enable_stay_duration")break;l[h]=c[h]}var p=c.domain;(window.opener||window.parent).postMessage({type:"tea:sdk:info",config:l,version:u},p),window.addEventListener("message",y_,!1)})(e,Qe);try{(function(c,u){bi[c]=bi[c]||[],bi[c].push(u)})("tea:openHeatMapCore",function(c){var u=$f,l=c.data.app_id;l&&l!==e.app_id||function(h){var p=h.event,f=h.editorUrl,v=h.autoTrackInstance;Cn||(Cn=!0,Nf(f,function(){Da(p,"editorScriptloadSuccess"),v.destroy()},function(){p&&Da(p,"editorScriptloadError"),Cn=!1}))}({event:c,editorUrl:u+".js?query="+Date.now(),autoTrackInstance:i})})}catch{console.log("openHeatMapCore error")}}var Oe,S_=function(){function i(e,t){this._instance=null,this._intersection=e,this.config=t,this._intersection&&this.init()}return i.prototype.init=function(){var e=this;if(window.MutationObserver)try{if(this._instance=new MutationObserver(function(r){r.forEach(function(n){n.type==="attributes"&&e.attributeChangeObserve(n),n.type==="childList"&&e.modifyNodeObserve(n)})}),!document||!document.body)return void console.warn("please use sdk api init after body element");var t=this.config.autotrack.exposure.attributes!==!1;this._instance.observe(document.body,{childList:!0,attributes:t,subtree:!0,attributeOldValue:!1})}catch{console.log("your browser cannot support MutationObserver,so cannot report exposure event, please update")}else console.log("your browser cannot support MutationObserver,so cannot report exposure event, please update")},i.prototype.attributeChangeObserve=function(e){e.target.hasAttribute("data-exposure")?this.exposureAdd(e,"mutation"):this.exposureRemove(e)},i.prototype.modifyNodeObserve=function(e){var t=this;Array.prototype.forEach.call(e.addedNodes,function(r){r.nodeType===1&&r.hasAttribute("data-exposure")&&t.exposureAdd(r,"intersect"),t.mapChild(r,t.exposureAdd.bind(t))}),Array.prototype.forEach.call(e.removedNodes,function(r){r.nodeType===1&&r.hasAttribute("data-exposure")&&t.exposureRemove(r),t.mapChild(r,t.exposureRemove.bind(t))})},i.prototype.mapChild=function(e,t){var r=this;e.nodeType===1&&e.children.length&&Array.prototype.forEach.call(e.children,function(n){n.nodeType===1&&n.hasAttribute("data-exposure")&&t(n),r.mapChild(n,t)})},i.prototype.exposureAdd=function(e,t){try{this._intersection&&this._intersection.exposureAdd(e,t)}catch(r){console.log("intersection error",JSON.stringify(r.message))}},i.prototype.exposureRemove=function(e){try{this._intersection&&this._intersection.exposureRemove(e)}catch(t){console.log("intersection error",JSON.stringify(t.message))}},i._exposure_observer=null,i}();(function(i){i[i.EXPOSURE_ONCE=0]="EXPOSURE_ONCE",i[i.LIFECYCLE_SHOW_NEW=3]="LIFECYCLE_SHOW_NEW",i[i.RESUME_FORM_PAGE=6]="RESUME_FORM_PAGE",i[i.RESUME_FORM_BACK=7]="RESUME_FORM_BACK",i[i.NOT_EXPOSURE=-1]="NOT_EXPOSURE"})(Oe||(Oe={}));var yt,E_=function(){function i(e,t,r){var n=this;this.backStatus=!1,this.instance=this.buildObserver(),this.collect=e,this.observeMap=i._observer_map,t.autotrack.exposure.ratio?this.ratio=t.autotrack.exposure.ratio:t.autotrack.exposure.ratio===0?this.ratio=0:this.ratio=.5,this.timeLimit=t.autotrack.exposure.stay||0,this.exposureType=Oe.NOT_EXPOSURE,this.eventHandle=r,this.hashMap=new Map,this.backStatus=!1,this.lastState=null,this.collect.on("re-start-sdk",function(){n.visibilitychange()}),this.addListen()}return i.prototype.buildObserver=function(){var e=this;if(i._observer_instance)return console.log("your browser cannot support IntersectionObserver, so cannot report exposure event, please update"),null;if(window.IntersectionObserver){for(var t=[],r=0;r<=1;r+=.01)t.push(r);t.push(1);try{i._observer_instance=new IntersectionObserver(function(n){n.forEach(function(s){var a=s.target.observeId,o=e.observeMap.get(a),d=(s.target,s.isIntersecting,s.intersectionRatio);if(o.intersectionRatio=d,d<=.1&&(s.target.backStatus=!1),e.observeMap.set(a,o),d<e.ratio)return o.isIntersecting=!1,o.added=!1,o.exposured=!1,o.startTime=Date.now(),void e.observeMap.set(a,o);if(!o.added){if(o.startTime=Date.now(),o.added=!0,o.isIntersecting=!0,e.timeLimit){var c=setTimeout(function(){try{if(o.isIntersecting&&!o.exposured&&e.observeMap.get(a)){var u=e.observeMap.get(a).intersectionRatio;e.exposureEvent(s,u,a,o)}}catch(l){console.log("IntersectionObserver setTimeout error,msg: "+JSON.stringify(l))}},e.timeLimit);o.wait=c}e.observeMap.set(a,o)}Date.now()-o.startTime>=e.timeLimit&&!o.exposured&&e.exposureEvent(s,d,a,o)})},{threshold:t})}catch(n){console.log("IntersectionObserver error,msg: "+JSON.stringify(n))}return i._observer_instance}return console.log("your browser cannot support IntersectionObserver, so cannot report exposure event, please update"),null},i.prototype.exposureAdd=function(e,t){var r=t==="mutation"?e.target:e,n=r.observeId,s=ii();if(n||this.observeMap.has(n)){var a=this.observeMap.get(n);if(a&&r!==a.instance)this.unobserve(r),this.observeMap.delete(n),r.observeId=s,r.visible=!1,this.observeMap.set(s,{instance:r.cloneNode(!0),isIntersecting:!1}),this.observe(r);else{if(r.visible===!0)return;this.handleBoundingExposure(r)}}else r.observeId=s,r.visible=!1,this.observeMap.set(s,{instance:r.cloneNode(!0),isIntersecting:!1}),this.observe(r)},i.prototype.exposureRemove=function(e){this.observeMap.has(e.observeId)&&(this.observeMap.delete(e.observeId),this.unobserve(e),e.observeId="",e.visible=!1)},i.prototype.exposureEvent=function(e,t,r,n){if(t>=this.ratio){if(e.target.style.opacity==="0"||e.target.style.visibility==="hidden"||n.exposured===!0)return;n.startWait&&clearTimeout(n.startWait);var s=e.target.getAttribute("data-exposure-event");this.eventHandle({eventType:"dom",eventName:"exposure",event:s,exposureType:this.getExposureType(e.target)},e),e.target.visible=!0,e.target.hasExposure=!0,n.startTime=Date.now(),n.exposured=!0}else n.startTime=Date.now(),n.exposured=!1;this.observeMap.set(r,n)},i.prototype.observe=function(e){this.instance&&this.instance.observe(e)},i.prototype.unobserve=function(e){this.instance&&this.instance.unobserve(e)},i.prototype.getExposureDomToExposure=function(){var e=this;Array.prototype.forEach.call(document.querySelectorAll("[data-exposure]"),function(t){e.handleBoundingExposure(t)})},i.prototype.visibilitychange=function(){var e=this,t=null;document.visibilityState==="visible"?this.timeLimit?t=setTimeout(function(){e.getExposureDomToExposure()},this.timeLimit):this.getExposureDomToExposure():(clearTimeout(t),this.customType=void 0)},i.prototype.handleBoundingExposure=function(e){if(this.getBoundingRatio(e)>=this.ratio){e.visible=!0;var t=e.getAttribute&&e.getAttribute("data-exposure-event");this.eventHandle({eventType:"dom",eventName:"exposure",event:t,exposureType:this.customType||Oe.RESUME_FORM_BACK},e)}},i.prototype.getBoundingRatio=function(e){var t=e.getBoundingClientRect(),r=t.top,n=t.left,s=t.width,a=t.height,o=window.innerWidth||document.documentElement.clientWidth,d=window.innerHeight||document.documentElement.clientHeight;return r>=0&&n>=0&&r<=d&&n<=o?(s>o?o:s)*(d-r)/(s*a):0},i.prototype.getExposureType=function(e){return e.visible?e.backStatus!==!1&&(this.backStatus||this.customType||window.performance.navigation.type===2)?this.exposureType=Oe.RESUME_FORM_PAGE:this.exposureType=Oe.LIFECYCLE_SHOW_NEW:(e.hasExposure,e.backStatus!==!1&&(this.backStatus||this.customType||window.performance.navigation.type===2)?this.exposureType=Oe.RESUME_FORM_PAGE:this.exposureType=Oe.EXPOSURE_ONCE),this.exposureType},i.prototype.addListen=function(){var e=this;this.collect.on("set-exposure-type",function(c){e.customType=c});var t,r,n,s,a=this.visibilitychange.bind(this);if(t=document,r="visibilitychange",n=a,s=!1,t.addEventListener?t.addEventListener(r,n,s):t.attachEven?t.attachEven("on"+r,n):t["on"+r]=n,window.addEventListener("hashchange",function(c){var u=e.hashMap.get(c.oldURL);u&&location.href===u.prev?(e.backStatus=!0,e.exposureType=Oe.RESUME_FORM_PAGE):(e.backStatus=!1,e.hashMap.set(location.href,{current:c.newURL,prev:c.oldURL}))}),this.collect.bridgeReport){var o=window.history.pushState;history.pushState=function(c){for(var u=[],l=1;l<arguments.length;l++)u[l-1]=arguments[l];typeof history.onpushstate=="function"&&history.onpushstate({state:c});var h=o.call.apply(o,ft([history,c],u));return e.lastState=c,h};var d=history.replaceState;history.replaceState=function(c){for(var u=[],l=1;l<arguments.length;l++)u[l-1]=arguments[l];typeof history.onreplacestate=="function"&&history.onreplacestate({state:c});var h=d.call.apply(d,ft([history,c],u));return e.lastState=c,h}}else this.collect.on("STATE_CHANGE",function(c){e.lastState=c});return window.addEventListener("popstate",function(c){var u=c.state;u&&u.current&&e.lastState&&e.lastState.back&&u.current===e.lastState.back?(e.backStatus=!0,e.exposureType=Oe.RESUME_FORM_PAGE):e.backStatus=!1}),function(){(function(c,u,l,h){c.addEventListener?c.removeEventListener(u,l,h):c.attachEven&&c.detachEven("on"+u,l)})(document,"visibilitychange",a,!1)}},i._observer_instance=null,i._observer_map=new Map,i}(),w_=function(){function i(e,t,r){t.autotrack&&t.autotrack.exposure&&(this._intersection=new E_(e,t,r),this._observer=new S_(this._intersection,t),this._intersection&&this._observer?this.initObserver():console.log("your browser version cannot support exposure event, please update~"))}return i.prototype.initObserver=function(){var e=this;Array.prototype.forEach.call(document.querySelectorAll("[data-exposure]"),function(t){e._intersection.exposureAdd(t,"intersect")})},i}();(function(i){i[i.SCROLL_UP=1]="SCROLL_UP",i[i.SCROLL_DOWN=2]="SCROLL_DOWN",i[i.SCROLL_LEFT=3]="SCROLL_LEFT",i[i.SCROLL_RIGHT=4]="SCROLL_RIGHT",i[i.NOT_SCROLL=-1]="NOT_SCROLL"})(yt||(yt={}));var xa,C_=function(){function i(e,t){this.distance=30,e.autotrack&&e.autotrack.scroll&&(e.autotrack.scroll.distance&&(this.distance=e.autotrack.scroll.distance),this.eventHandle=t,this.addLinstenr(),this.mutation())}return i.prototype.addLinstenr=function(){var e=this;Array.prototype.forEach.call(document.querySelectorAll("[data-scroll]"),function(t){e.scrollHandle(t)})},i.prototype.mutation=function(){var e=this;if(window.MutationObserver)try{var t=new MutationObserver(function(r){r.forEach(function(n){n.type==="childList"&&e.modifyNodeObserve(n)})});if(!document||!document.body)return void console.warn("please use sdk api init after body element");t.observe(document.body,{childList:!0,attributes:!0,subtree:!0,attributeOldValue:!1})}catch{console.log("your browser cannot support MutationObserver")}else console.log("your browser cannot support MutationObserver")},i.prototype.modifyNodeObserve=function(e){var t=this;Array.prototype.forEach.call(e.addedNodes,function(r){r.nodeType===1&&r.hasAttribute("data-scroll")&&t.scrollHandle(r),t.mapChild(r,t.scrollHandle.bind(t))}),Array.prototype.forEach.call(e.removedNodes,function(r){r.nodeType===1&&r.hasAttribute("data-scroll")&&t.scrollHandle(r,"remove"),t.mapChild(r,t.scrollHandle.bind(t))})},i.prototype.mapChild=function(e,t){var r=this;e.nodeType===1&&e.children.length&&Array.prototype.forEach.call(e.children,function(n){n.nodeType===1&&n.hasAttribute("data-scroll")&&t(n),r.mapChild(n,t)})},i.prototype.scrollHandle=function(e,t){var r=this;try{var n=e.scrollTop,s=e.scrollLeft,a=null,o=0,d=0,c=function(u){clearTimeout(a),a=setTimeout(function(){var f=e.scrollTop,v=e.scrollLeft,m=u.target&&u.target.getAttribute("data-scroll-event")||"";p===1||p===2?f===l&&(d=l-n,Math.abs(d)>=r.distance&&r.distance&&r.eventHandle({eventType:"dom",eventName:"scroll",event:m,params:{$direction:p,$offsetY:d,$offsetX:o}},u)):p!==3&&p!==4||v===h&&(o=h-s,Math.abs(o)>=r.distance&&r.distance&&r.eventHandle({eventType:"dom",eventName:"scroll",event:m,params:{$direction:p,$offsetY:d,$offsetX:o}},u)),n=l,s=h},100);var l=e.scrollTop,h=e.scrollLeft,p=yt.NOT_SCROLL;l>n?p=yt.SCROLL_DOWN:l<n?p=yt.SCROLL_UP:h>s?p=yt.SCROLL_LEFT:h<s&&(p=yt.SCROLL_RIGHT)};return t==="remove"?e.removeEventListener("scroll",c,!1):e.addEventListener("scroll",c,!1),function(){e.removeEventListener("scroll",c,!1)}}catch(u){console.warn("scroll event error",JSON.stringify(u))}},i}(),k_={hashTag:!1,impr:!1},T_=function(){function i(){}return i.prototype.apply=function(e,t){if(this.autoTrackStart=!1,this.collect=e,this.config=t,t.autotrack){var r=e.Types;this.ready(r.Autotrack),this.collect.emit(r.AutotrackReady)}},i.prototype.ready=function(e){this.collect.set(e);var t=this.config.autotrack;t=typeof t=="object"?t:{},t=Object.assign(k_,t),this.destroyed=!1,this.options=t,this.Config=new f_(p_,this.options),this.Exposure=new w_(this.collect,this.config,this.handle.bind(this)),this.Scroll=new C_(this.config,this.handle.bind(this)),this.Listener=new l_(t,this.collect,this.Config),this.EventHandle=new __(this.config,t),this.Request=new g_(this.collect),this.autoTrackStart=!0,this.init(),b_(this,this.config)},i.prototype.init=function(){this.Listener.init(this.handle.bind(this));try{this.collect.loadType==="base"&&(window.opener||window.parent).postMessage("[tea-sdk]ready","*")}catch{}},i.prototype.handle=function(e,t){try{if(this.config.autotrack.collect_url&&!this.config.autotrack.collect_url())return}catch{}e.eventType==="dom"&&this.handleDom(e,t)},i.prototype.handleDom=function(e,t){try{var r=e.eventName;if(r==="click"||r==="change"||r==="submit")(o=this.EventHandle.handleEvent(t,r))&&this.Request.send({eventType:"custom"},o);else if(r==="page_view"||r==="page_statistics"){var n=void 0;(n=r==="page_view"?this.EventHandle.handleViewEvent(t):this.EventHandle.handleStatisticsEvent(t))&&this.Request.send({eventType:"custom"},n)}else if(r==="beat"){var s=this.EventHandle.handleBeadtEvent(t),a=e.eventSend;s&&this.Request.send({eventType:"custom",eventSend:a},s)}else if(r==="exposure")(o=this.EventHandle.handleExposureEvent(e,t))&&this.Request.send({eventType:"custom"},o);else if(r==="scroll"){var o;(o=this.EventHandle.handleScrollEvent(e,t))&&this.Request.send({eventType:"custom"},o)}}catch(d){console.log("handel dom event error "+JSON.stringify(d))}},i.prototype.destroy=function(){if(!this.autoTrackStart)return console.warn("engine is undefined, make sure you have called autoTrack.start()");this.autoTrackStart=!1,this.Listener.removeListener()},i}();(function(i){i.Net="net",i.FailNet="f_net",i.FailData="f_data"})(xa||(xa={}));var Ia={pv:["predefine_pageview"],sdk:["_be_active","predefine_page_alive","predefine_page_close","__profile_set","__profile_set_once","__profile_increment","__profile_unset","__profile_append"],autotrack:["bav2b_click","bav2b_page","bav2b_beat","bav2b_page_statistics","__bav_click","__bav_page","__bav_beat","__bav_page_statistics"]},z_=function(){function i(){}return i.prototype.apply=function(e,t){var r=this;if(t.app_id&&t.enable_tracer&&!t.disable_track_event){this.limit={pv:1,sdk:3,autotrack:3,log:3},this.errorCode={f_net:0,f_data:0},this.tracerCache=new Map,this.collect=e,this.appid=t.app_id,this.reportUrl=e.configManager.getUrl("event");var n=this.collect.Types;this.collect.on(n.Event,function(){r.addCount("log")}),this.collect.on(n.SubmitError,function(s){var a=s.type,o=s.eventDate,d=s.errorCode,c=s.response;r.addErrorCount(o,a,d,c)}),this.listener(),this.collect.emit(n.TracerReady)}},i.prototype.addCount=function(e,t,r){t===void 0&&(t="net"),r===void 0&&(r=1);try{this.tracerCache||(this.tracerCache=new Map);var n=void 0;if(this.tracerCache.has(e))(s=this.tracerCache.get(e)).has(t)?(n=s.get(t).params.count,n++,s.set(t,this.processTracer(n,e,t))):(n=r,s.set(t,this.processTracer(r,e,t)));else{var s=new Map;n=r,s.set(t,this.processTracer(r,e,t)),this.tracerCache.set(e,s)}t==="net"&&n>=this.limit[e]&&this.report(!1)}catch(a){console.log(a)}},i.prototype.addErrorCount=function(e,t,r,n){var s=this;try{if(e&&e.length){var a=e[0].events;a&&a.length&&(t==="f_data"?(n&&n.hasOwnProperty("sc")?this.addCount("log",t,a.length-n.sc):this.addCount("log",t,a.length),this.errorCode[t]=r):a.forEach(function(o){var d="log";for(var c in Ia)if(Ia[c].indexOf(o.event)!==-1){d=c;break}s.addCount(d,t,1),s.errorCode[t]=r}))}}catch{}},i.prototype.report=function(e){if(this.tracerCache){var t=[];this.tracerCache.forEach(function(r){console.log(r),r.forEach(function(n){t.push(n)})}),t&&t.length&&this.sendTracer(t,e)}},i.prototype.sendTracer=function(e,t){try{var r=this.collect.eventManager.merge(e);this.collect.requestManager.useRequest({url:this.reportUrl,data:r,useBeacon:t}),this.tracerCache=null}catch{}},i.prototype.processTracer=function(e,t,r){var n={count:e,state:r,key:t,params_for_special:"applog_trace",aid:this.appid,platform:"web",_staging_flag:1,sdk_version:Qe};r!=="f_net"&&r!=="f_data"||(n.errorCode=this.errorCode[r]);var s=this.collect.processEvent("applog_trace",n);if(s&&s.event)return delete s.is_bav,s},i.prototype.listener=function(){var e=this;document.addEventListener("visibilitychange",function(){document.visibilityState==="hidden"&&e.leavePage()}),Jr(function(){e.leavePage()})},i.prototype.leavePage=function(){this.report(!0)},i}(),A_=function(){function i(){this.retryWaitTime=3e3,this.retryStatus=!1,this.retryCacheStatus=!1}return i.prototype.apply=function(e,t){var r=this;if(t.enable_storage&&!t.disable_storage&&(this.collect=e,this.config=t,!this.collect.destroy)){var n=e.Types,s=e.adapters.storage;this.storage=new s(!1),this.eventUrl=this.collect.configManager.getUrl("event"),this.eventKey="__tea_cache_events_"+t.app_id,this.storageNum=t.storage_num||50,this.retryNum=t.retry_num||3,this.retryInterval=1e3,e.on(n.SubmitError,function(a){a.type!=="f_data"&&r.storeData(a)}),e.on(n.Ready,function(){r.checkStorage()})}},i.prototype.retryRightNow=function(e){var t=this;if(this.retryStatus)this.errorCache.push(e);else{var r=0;this.retryStatus=!0;var n=setInterval(function(){if(r===3)return t.storeData(t.errorCache),t.retryStatus=!1,void clearInterval(n);var s=e.eventData;t.fetchData(s,function(){t.retryStatus=!1,clearInterval(n),t.retryCacheStatus&&t.errorCache.splice(0,1),t.errorCache.length&&(t.retryCacheStatus=!0,t.retryRightNow(t.errorCache[0]))},function(){r++})},this.retryInterval)}},i.prototype.storeData=function(e){var t=this.storage.getItem(this.eventKey),r=e.eventData;Object.keys(t).length!==this.storageNum&&(t[Date.now()]=r,this.storage.setItem(this.eventKey,t))},i.prototype.checkStorage=function(){var e=this;try{if(!window.navigator.onLine)return;var t=this.storage.getItem(this.eventKey);if(!t||!Object.keys(t).length)return;var r={events:[{event:"ontest",params:{app_id:this.config.app_id},local_time_ms:Date.now()}],user:{user_unique_id:this.collect.configManager.get("web_id")},header:{}};this.fetchData([r],function(){var n=JSON.parse(JSON.stringify(t)),s=function(o){e.fetchData(t[o],function(){delete n[o],e.storage.setItem(e.eventKey,n)},function(){},!1)};for(var a in t)s(a)},function(){console.log("network error,compensate report fail")},!0)}catch{console.warn("error check storage")}},i.prototype.fetchData=function(e,t,r,n){this.collect.requestManager.useRequest({url:this.eventUrl,data:e,timeout:3e4,success:t,fail:r,app_key:n?"566f58151b0ed37e":""})},i}(),kn=typeof window<"u"?(window.LogPluginObject||(window.LogPluginObject={}),window.LogPluginObject):null,R_=function(){function i(){}return i.prototype.apply=function(e,t){this._plugin={},this.config=t,this.collect=e,this.channel=t.channel||"cn",this.loadExtend()},i.prototype.loadExtend=function(){var e=this;try{this.collect.remotePlugin.forEach(function(t,r){if(t==="sdk")if(Sn.hasOwnProperty(r)){var n=Sn[r].object,s=Sn[r].src[e.channel]+"?query="+Date.now();e.exist(r,n,s)}else console.warn("your "+r+" is not exist,please check plugin name");else typeof t=="object"&&(t.src?e.exist(r,t.call,t.src):e.process(r,t.instance,"INSTANCE"))})}catch(t){this.collect.emit(g.DEBUGGER_MESSAGE,{type:g.DEBUGGER_MESSAGE_SDK,info:"发生了异常",level:"error",time:Date.now(),data:t.message}),console.log("load extend error")}},i.prototype.exist=function(e,t,r){var n=this;kn[t]?(this.process(e,kn[t]),console.log("已有"+e+"插件,避免重复加载~")):this.loadPlugin(e,r,function(){n.process(e,kn[t]),console.log(" %c %s %s %s","color: yellow; background-color: black;","–","load plugin:"+e+" success","-")},function(){console.log(" %c %s %s %s","color: red; background-color: yellow;","–","load plugin:"+e+" error","-")})},i.prototype.process=function(e,t,r){try{if(r){var n=new t;n.apply&&n.apply(this.collect,this.config),console.log("excude "+e+" success")}else t&&t(this.collect,this.config)}catch(s){this.collect.emit(g.DEBUGGER_MESSAGE,{type:g.DEBUGGER_MESSAGE_SDK,info:"发生了异常",level:"error",time:Date.now(),data:s.message}),console.log("excude "+e+" error, message:"+s.message)}},i.prototype.loadPlugin=function(e,t,r,n){var s=this;try{var a=document.createElement("script");a.src=t,this._plugin[e]||(this._plugin[e]=[]),this._plugin[e].push(r),a.onerror=function(){n(t)},a.onload=function(){s._plugin[e].forEach(function(o){o()})},document.getElementsByTagName("head")[0].appendChild(a)}catch(o){this.collect.emit(g.DEBUGGER_MESSAGE,{type:g.DEBUGGER_MESSAGE_SDK,info:"发生了异常",level:"error",time:Date.now(),data:o.message})}},i}(),D_=function(){function i(){this.autotrack=!1,this.spa=!1,this.cache={},this.allowHash=!1}return i.prototype.apply=function(e,t){if(t.spa||t.autotrack){var r=e.Types;this.collect=e,this.config=t,this.appid=t.app_id,this.allowHash=t.allow_hash,this.fncArray=new Map,this.setKey(),this.setLocation(),this.hack(),this.init(),this.listener(),e.emit(r.RouteReady)}},i.prototype.setKey=function(){var e=this.collect.adapters.storage;this.storage=new e(!1),this.cache_key="__tea_cache_refer_"+this.appid,this.cache={refer_key:"",refer_title:document.title||location.pathname,refer_manual_key:"",routeChange:!1},this.config.autotrack&&typeof this.config.autotrack=="object"&&this.config.autotrack.page_manual_key&&(this.cache.refer_manual_key=this.config.autotrack.page_manual_key),this.storage.setItem(this.cache_key,this.cache)},i.prototype.hack=function(){var e=this,t=window.history.pushState;history.pushState=function(n){for(var s=[],a=1;a<arguments.length;a++)s[a-1]=arguments[a];typeof history.onpushstate=="function"&&history.onpushstate({state:n});var o=t.call.apply(t,ft([history,n],s));if(e.collect.sdkStop||e.collect.destroy)return o;if(!(e.lastLocation===location.href||e.config.disable_spa_query&&e.pathEquel())){e.setReferCache(e.lastLocation);var d=e.getPopStateChangeEventData();return e.lastLocation=location.href,e.sendPv(d,"pushState"),o}};var r=history.replaceState;history.replaceState=function(n){for(var s=[],a=1;a<arguments.length;a++)s[a-1]=arguments[a];typeof history.onreplacestate=="function"&&history.onreplacestate({state:n});var o=r.call.apply(r,ft([history,n],s));if(e.collect.sdkStop||e.collect.destroy)return o;if(!(e.lastLocation===location.href||e.config.disable_spa_query&&e.pathEquel())){e.setReferCache(e.lastLocation);var d=e.getPopStateChangeEventData();return e.lastLocation=location.href,e.sendPv(d),o}}},i.prototype.setLocation=function(){typeof window<"u"&&(this.lastLocation=window.location.href)},i.prototype.getLocation=function(){return this.lastLocation},i.prototype.pathEquel=function(){try{return new URL(this.lastLocation).origin+new URL(this.lastLocation).pathname===new URL(location.href).origin+new URL(location.href).pathname}catch{return!1}},i.prototype.init=function(){var e=this.getPopStateChangeEventData();this.collect.emit("route-change",{config:e,init:!0})},i.prototype.listener=function(){var e=this;window.addEventListener("hashchange",function(t){if(!e.collect.sdkStop&&!e.collect.destroy&&e.lastLocation!==window.location.href&&(!e.config.disable_spa_query||!e.pathEquel())&&e.allowHash){e.setReferCache(e.lastLocation),e.lastLocation=window.location.href;var r=e.getPopStateChangeEventData();e.sendPv(r)}}),window.addEventListener("popstate",function(t){if(!e.collect.sdkStop&&!e.collect.destroy&&!(e.lastLocation===window.location.href||e.config.disable_spa_query&&e.pathEquel())){e.setReferCache(e.lastLocation),e.lastLocation=window.location.href;var r=e.getPopStateChangeEventData();e.sendPv(r)}})},i.prototype.getPopStateChangeEventData=function(){var e=this.pageConfig();return e.is_back=0,e},i.prototype.pageConfig=function(){try{var e=this.storage.getItem(this.cache_key)||{},t=!1,r=this.storage.getItem("__tea_cache_first_"+this.appid);return t=!r||r!=1,{is_html:1,url:location.href,referrer:this.handleRefer(),page_key:location.href,refer_page_key:this.handleRefer(),page_title:document.title||location.pathname,page_manual_key:this.config.autotrack&&this.config.autotrack.page_manual_key||"",refer_page_manual_key:e&&e.refer_manual_key||"",refer_page_title:e&&e.refer_title||"",page_path:location.pathname,page_host:location.host,is_first_time:""+t}}catch(n){return this.collect.emit(g.DEBUGGER_MESSAGE,{type:g.DEBUGGER_MESSAGE_SDK,info:"发生了异常",level:"error",time:Date.now(),data:n.message}),{}}},i.prototype.sendPv=function(e,t){this.collect.emit("route-change",{config:e,init:!1})},i.prototype.handleRefer=function(){var e="";try{var t=this.storage.getItem(this.cache_key)||{};e=t.routeChange?t.refer_key:this.collect.configManager.get("referrer")}catch{e=document.referrer}return e},i.prototype.removeQuery=function(e){try{var t=new URL(e);return t.search="",t.href}catch{return e.split(/[?#]/)[0]}},i.prototype.setReferCache=function(e){var t=this.storage.getItem(this.cache_key)||{},r=this.removeQuery(e);t.refer_key=r,t.routeChange=!0,this.storage.setItem(this.cache_key,t)},i}();be.usePlugin(R_,"extend"),be.usePlugin(e_,"et"),be.usePlugin(Ym,"ab"),be.usePlugin(s_,"stay"),be.usePlugin(T_,"autotrack"),be.usePlugin(o_,"profile"),be.usePlugin(A_,"retry"),be.usePlugin(a_,"heartbeat"),be.usePlugin(c_,"monitor"),be.usePlugin(D_,"route"),be.usePlugin(z_,"tracer");var Si=new be("default");const Tn="VEPUSHER_DEVICE_ID",zn="VEPUSHER_USER_ID",Oa=i=>Math.floor((Math.random()*9+1)*Math.pow(10,i-1)).toString();function x_(i){const e={};if(!(i instanceof Object))throw new Error("params type error");for(const[t,r]of Object.entries(i))if(["string","number","boolean"].includes(typeof r))e[t]=r;else try{e[t]=JSON.stringify(r)}catch(n){console.error("serialize error",n)}return e}function I_(i){if(i)return localStorage.setItem(zn,i),i;const e=localStorage.getItem(zn);if(e)return e;const t=Oa(12);return localStorage.setItem(zn,t),i}function O_(i){if(i)return localStorage.setItem(Tn,i),i;const e=localStorage.getItem(Tn);if(e)return e;const t=Oa(11);return localStorage.setItem(Tn,t),t}const I={PUSHER_INIT:"pusher_init",SET_PROPERTY_CALL:"set_property_call",SET_VIDEO_QUALITY:"set_video_quality",SET_AUDIO_QUALITY:"set_audio_quality",PAGE_VISIBLE_CHANGE:"page_visible_change",...{GET_DEVICES_RESULT:"get_devices_result",CAMERA_CAPTURE_RESULT:"camera_capture_result",MICROPHONE_CAPTURE_RESULT:"microphone_capture_result",SCREEN_CAPTURE_RESULT:"screen_capture_result",VIDEO_FILE_CAPTURE_RESULT:"video_file_capture_result",AUDIO_FILE_CAPTURE_RESULT:"audio_file_capture_result",IMAGE_FILE_CAPTURE_RESULT:"image_file_capture_result",VOLUME_DETECTOR_START_RESULT:"volume_detector_start_result",STOP_CAPTURE:"stop_capture"},...{SWITCH_ENABLE_MIXING:"switch_enable_mixing",SET_MIXING_CONFIG:"set_mixing_config",ADD_VIDEO_STREAM:"add_video_stream",UPDATE_VIDEO_STREAM:"update_video_stream",DELETE_VIDEO_STREAM:"delete_video_stream",CHANGE_VIDEO_STREAM_MUTE:"change_video_stream_mute",ADD_AUDIO_STREAM:"add_audio_stream",UPDATE_AUDIO_STREAM:"update_audio_stream",DELETE_AUDIO_STREAM:"delete_audio_stream",CHANGE_AUDIO_STREAM_MUTE:"change_audio_stream_mute"},...{START_PUSH:"start_push",STOP_PUSH_STREAM:"stop_push_stream",START_PUSH_STATUS:"start_push_status",PUSH_RECONNECT_START:"push_reconnect_start",PUSH_RECONNECT_STATUS:"push_reconnect_status",PUSH_STATS:"push_stats",PUSH_AUDIO_CONTEXT_START_FAILED:"push_audio_context_start_failed",PUSH_RTC_STATE_CHANGE:"push_rtc_state_change",PUSH_SDP_INFO:"push_sdp_info"}};class M_{constructor({showLogInConsole:e=!1}){this._showLogInConsole=!1,this.markCollectTeaEventReady=()=>{this.isReady=!0,Si.start(),this.queueTeaEvent.forEach(t=>this.sendTeaEvent(...t)),this.queueTeaEvent=[]},this.configTea=(t,r)=>{const n={...t,evtParams:{page_url_fe:encodeURIComponent(window.location.href)||"",page_path_fe:window.location.pathname||"unknown",page_host_fe:window.location.hostname||"unknown",sdk_version:"2.0.3",build_version:"1.0.0.115",...r}};Si.config(n),this.markCollectTeaEventReady()},this.isReady=!1,this.queueTeaEvent=[],Si.init({app_id:699880,channel:"cn"}),this._showLogInConsole=e}sendTeaEvent(e,t,r=!1){if(e)if(this.isReady)try{const n={...x_(t||{})};Si.event(e,n),this._showLogInConsole&&!r&&console.log("[VePusher logger]:",e,n)}catch(n){console.error(n)}else this._showLogInConsole&&!r&&console.log("[VePusher logger]:",e,t),this.queueTeaEvent.push([e,t])}getIsReady(){return this.isReady}getRawTea(){return Si}}let Ei;function P_({showLogInConsole:i}){Ei=new M_({showLogInConsole:i})}function O(i,e,t=!1){Ei&&Ei.sendTeaEvent(i,e,t)}function L_(i,e){Ei&&Ei.configTea(i,e)}const Ma=()=>{O(I.PAGE_VISIBLE_CHANGE,{page_visible:!document.hidden})},U_=()=>{document.addEventListener("visibilitychange",Ma)},G_=()=>{document.removeEventListener("visibilitychange",Ma)};function Pt(i){var e;return{error:i,error_code:i.code,error_message:i.message,original_error_message:(e=i.error)==null?void 0:e.message}}class N_ extends Je{constructor(e){super(),this._videoConstraints={width:1080,height:720,frameRate:30},this._cameraStreams={},this._screenStreams={},this._videoFileStreams={},this._microphoneStreams={},this._audioFileStreams={},this._imageStreams={},this._customVideoStreams={},this._customAudioStreams={};const{width:t,height:r,frameRate:n}=Rt(_s,"video"),{sampleRate:s}=Rt(gs,"audio");this._videoConstraints={width:t,height:r,frameRate:n},this._audioConstraints={sampleRate:s,enableAutoGainControl:!0,enableNoiseSuppression:!0,enableEchoCancellation:!0},this._livePusher=e}_notifyCaptured(e){this.emit(Ae.DeviceCaptured,e)}_notifyStopCapture(e){this.emit(Ae.DeviceStopCapture,e)}_bindStreamEvent(e){e.bindTrackEnd(()=>{this.emit(Ae.Interrupted,e),this.stopCapture({streamId:e.id,type:e.type})})}_handleError(e,t){const r=new At(t,e.message);this.emit(Ae.Error,r)}setVideoResolution(e){this._videoConstraints={...this._videoConstraints,...e}}setVideoFps(e){this._videoConstraints={...this._videoConstraints,frameRate:e}}setAudioSampleRate(e){this._audioConstraints={...this._audioConstraints,sampleRate:e}}async getDevicesList(e){try{const t=await fd(e?[e]:["audioinput","videoinput"]);return O(I.GET_DEVICES_RESULT,{type:e,is_success:!0,devices:t}),t}catch(t){return O(I.GET_DEVICES_RESULT,{type:e,is_success:!1,error:t,origin_error:t.error,error_code:t.code,error_message:t.message}),[]}}async getMicrophones(){return this.getDevicesList("audioinput")}async getCameras(){return this.getDevicesList("videoinput")}stopCapture({streamId:e,type:t}){let r;switch(t){case V.Camera:r="_cameraStreams";break;case V.Screen:r="_screenStreams";break;case V.VideoFile:r="_videoFileStreams";break;case V.Microphone:r="_microphoneStreams";break;case V.AudioFile:r="_audioFileStreams";break;case V.Image:r="_imageStreams";break;case V.CustomVideo:r="_customVideoStreams";break;case V.CustomAudio:r="_customAudioStreams";break}if(r){let n=[];if(e){const s=this[r][e];n.push(s)}else n=Fe(this[r]);O(I.STOP_CAPTURE,{stream_id:e,type:t,number:n.length}),n.forEach(s=>{this._notifyStopCapture(s),s.destroy(),delete this[r][s.id]})}}async startCameraCapture(e){let t={};If.includes(e)?t={facingMode:e}:e&&(t={deviceId:{exact:e}});const r={...t,...this._videoConstraints};try{const n=await md(r,!this._livePusher.isEnableMixing),s=new Vd(n,{frameRate:this._videoConstraints.frameRate});return this._cameraStreams[s.id]=s,this._notifyCaptured(s),this._bindStreamEvent(s),O(I.CAMERA_CAPTURE_RESULT,{is_success:!0,stream_id:s.id,device_id:e,capture_params:r}),s.id}catch(n){throw O(I.CAMERA_CAPTURE_RESULT,{is_success:!1,device_id:e,capture_params:r,...Pt(n)}),this._handleError(n,me.OPEN_CAMERA_FAILED),n}}async startMicrophoneCapture(e){let t={};e&&(t={deviceId:{exact:e}});const r={...this._audioConstraints,...t};try{const n=await gd(r),s=new kf(n);return this._microphoneStreams[s.id]=s,this._notifyCaptured(s),this._bindStreamEvent(s),O(I.MICROPHONE_CAPTURE_RESULT,{is_success:!0,stream_id:s.id,device_id:e,capture_params:r}),s.id}catch(n){throw O(I.MICROPHONE_CAPTURE_RESULT,{is_success:!1,device_id:e,capture_params:r,...Pt(n)}),this._handleError(n,me.OPEN_MICROPHONE_FAILED),n}}async startScreenCapture(e){const t={audio:e,video:this._videoConstraints};try{const r=await vd(t,void 0,!this._livePusher.isEnableMixing),n=new zf(r,{frameRate:this._videoConstraints.frameRate});return this._screenStreams[n.id]=n,this._notifyCaptured(n),this._bindStreamEvent(n),O(I.SCREEN_CAPTURE_RESULT,{is_success:!0,stream_id:n.id,capture_params:t}),n.id}catch(r){throw O(I.SCREEN_CAPTURE_RESULT,{is_success:!1,capture_params:t,...Pt(r)}),this._handleError(r,me.OPEN_SCREEN_FAILED),r}}async startVideoFileCapture(e){try{const t=await Ls({url:e,video:!0,audio:!0,loop:!0}),r=new Tf(t);return this._videoFileStreams[r.id]=r,this._notifyCaptured(r),this._bindStreamEvent(r),O(I.VIDEO_FILE_CAPTURE_RESULT,{is_success:!0,stream_id:r.id,file_url:e}),r.id}catch(t){throw this._handleError(t,me.VIDEO_FILE_CAPTURE_FAILED),O(I.VIDEO_FILE_CAPTURE_RESULT,{is_success:!1,file_url:e,...Pt(t)}),t}}async startAudioFileCapture(e){try{const t=await Ls({url:e,video:!1,audio:!0,loop:!0}),r=new Af(t);return this._audioFileStreams[r.id]=r,this._notifyCaptured(r),this._bindStreamEvent(r),O(I.AUDIO_FILE_CAPTURE_RESULT,{is_success:!0,stream_id:r.id,file_url:e}),r.id}catch(t){throw O(I.AUDIO_FILE_CAPTURE_RESULT,{is_success:!1,file_url:e,...Pt(t)}),this._handleError(t,me.AUDIO_FILE_CAPTURE_FAILED),t}}async startImageCapture(e){try{const t=await _d({url:e,width:0,height:0,frameRate:30}),r=new Rf(t);return this._imageStreams[r.id]=r,this._notifyCaptured(r),this._bindStreamEvent(r),O(I.IMAGE_FILE_CAPTURE_RESULT,{is_success:!0,stream_id:r.id,file_url:e}),r.id}catch(t){throw O(I.IMAGE_FILE_CAPTURE_RESULT,{is_success:!1,file_url:e,...Pt(t)}),this._handleError(t,me.IMAGE_FILE_CAPTURE_FAILED),t}}startCustomVideoCapture(e){const t=bd(e);if(t){const r=new Df(t);return this._customVideoStreams[r.id]=r,this._notifyCaptured(r),this._bindStreamEvent(r),r.id}}startCustomAudioCapture(e){const t=Sd(e);if(t){const r=new xf(t);return this._customAudioStreams[r.id]=r,this._notifyCaptured(r),this._bindStreamEvent(r),r.id}}async startVolumeDetect(e){const t=this.getStreamById(e);if(t)try{await t.startVolumeDetect(),O(I.VOLUME_DETECTOR_START_RESULT,{is_success:!0,stream_id:t.id})}catch(r){O(I.VOLUME_DETECTOR_START_RESULT,{is_success:!1,stream_id:t.id,error_message:r.message}),this._handleError(r,me.VOLUME_DETECT_FAILED)}}stopVolumeDetect(e){const t=this.getStreamById(e);t&&t.stopVolumeDetect()}getDefaultVideoStream(){return Fe(this._cameraStreams)[0]||Fe(this._screenStreams)[0]||Fe(this._videoFileStreams)[0]||Fe(this._imageStreams)[0]||Fe(this._customVideoStreams)[0]}getDefaultAudioStream(){return Fe(this._microphoneStreams)[0]||Fe(this._audioFileStreams)[0]||Fe(this._customAudioStreams)[0]}getVideoStream(e){return this._cameraStreams[e]||this._screenStreams[e]||this._videoFileStreams[e]||this._imageStreams[e]||this._customVideoStreams[e]}getAudioStream(e){return this._microphoneStreams[e]||this._audioFileStreams[e]||this._customAudioStreams[e]}getStreamById(e){return this.getAudioStream(e)||this.getVideoStream(e)}getVolume(e){const t=this.getStreamById(e);return(t==null?void 0:t.volume)||0}destroy(){Object.values(V).forEach(e=>{this.stopCapture({type:e})})}}let nt=class{constructor(e){this._enabled=!1,this.group=(...t)=>{this._enabled&&console.group(`[${this._prefix}]: `,...t)},this.groupCollapsed=(...t)=>{this._enabled&&console.groupCollapsed(`[${this._prefix}]: `,...t)},this.groupEnd=()=>{this._enabled&&console.groupEnd()},this.log=(...t)=>{this._enabled&&console.log(`[${this._prefix}]: `,...t)},this.warn=(...t)=>{this._enabled&&console.warn(`[${this._prefix}]: `,...t)},this.error=(...t)=>{this._enabled&&console.error(`[${this._prefix}]: `,...t)},this.table=(...t)=>{this._enabled&&console.table(...t)},this._prefix=e;try{this._enabled=location.href.indexOf("rtmdebug")!==-1}catch{}}};class An{constructor({streamManagerController:e,composedStream:t,streamComposeController:r}){this._streamManagerController=e,this._composedStream=t,this._streamComposeController=r,this._active=!1,this.bindStreamManagerControllerEvent()}bindStreamManagerControllerEvent(){this._streamManagerController.on(Ae.DeviceCaptured,e=>{this._active&&this.onStreamCapture(e)}),this._streamManagerController.on(Ae.DeviceStopCapture,e=>{this._active&&this.onStreamStopCapture(e)})}getComposedStream(){return this._composedStream}enable(){this._active=!0}disable(){this._active=!1}}const Pa=new nt("SingleComposer");class B_ extends An{onStreamCapture(e){e.isVideoStream?this._handleVideoStreamCapture(e):this._handleAudioStreamCapture(e)}onStreamStopCapture(e){e&&(e.isVideoStream?this._handleVideoStreamStopCapture(e):this._handleAudioStreamStopCapture(e))}enable(){if(super.enable(),this._composedStream.videoStream){const e=this._streamManagerController.getDefaultVideoStream();e&&this._handleVideoStreamCapture(e)}}async setVideoQuality({width:e,height:t,frameRate:r}){var n,s;if(this._active)try{await((s=(n=this._composedStream.videoStream)==null?void 0:n.videoTrack)==null?void 0:s.applyConstraints({width:{min:e,ideal:e},height:{min:t,ideal:t},frameRate:{min:r,ideal:r}}))}catch(a){Pa.error("setVideoQuality error",a)}}_handleVideoStreamCapture(e){const t=this._composedStream.videoStream;t!=null&&t.id&&this._streamComposeController.getMixerComposer().haveMixedStream(t.id)&&this._streamComposeController.removeAudioStream(t.id),e.audioTrack&&this._streamComposeController.addAudioStream({streamId:e.id,volume:100}),this._composedStream.setVideoStream(e)}_handleAudioStreamCapture(e){const t=this._streamComposeController.getMixerComposer().getMixedStreamByType(e.type);t.length>0&&t.forEach(r=>{this._streamComposeController.removeAudioStream(r.id)}),this._streamComposeController.addAudioStream({streamId:e.id,volume:100})}_handleVideoStreamStopCapture(e){const t=this._composedStream.videoStream;if((t==null?void 0:t.id)===e.id){const r=this._streamManagerController.getDefaultVideoStream();r?this._handleVideoStreamCapture(r):Pa.error("all video stream stop capture")}}muteVideoStream(){var e;(e=this._composedStream.videoStream)!=null&&e.videoTrack&&(this._composedStream.videoStream.videoTrack.enabled=!1)}unmuteVideoStream(){var e;(e=this._composedStream.videoStream)!=null&&e.videoTrack&&(this._composedStream.videoStream.videoTrack.enabled=!0)}_handleAudioStreamStopCapture(e){this._streamComposeController.removeAudioStream(e.id)}getComposedStream(){return this._composedStream}}class V_ extends Je{constructor(e,{width:t,height:r,x:n,y:s,zOrder:a,keepRatio:o,mirrorType:d}){super(),this._rect={x:0,y:0,width:0,height:0,zOrder:0},this._isHidden=!1,this._paintSize={width:0,height:0},this._rect.width=t??e.width,this._rect.height=r??e.height,this._rect.x=n??0,this._rect.y=s??0,this._rect.zOrder=a??0,this._rect.sourceHeight=e.height,this._rect.sourceWidth=e.width,this._rect.keepRatio=o??!1,this._rect.mirrorType=d,this._stream=e,this._bindVideoTrackSizeChange()}_getPaintSize({elementWidth:e,elementHeight:t}){const r=this._rect.width,n=this._rect.height;if(r===0&&n===0)return{width:0,height:0};if(r===0)return{height:n,width:e*(n/t)};if(n===0)return{width:r,height:t*(r/e)};const s=e/t,a=r/n;let o=r,d=n;return s>a?(o=r,d=2*Math.round(r/s/2)):s<a&&(o=2*Math.round(n*s/2),d=n),{width:o,height:d}}_bindVideoTrackSizeChange(){this._stream.on(ms.SizeChange,({width:e,height:t})=>{this.setBaseProps("sourceWidth",e),this.setBaseProps("sourceHeight",t)})}getViewNode(){var n;if(!this._stream)return;let e={width:this._rect.width,height:this._rect.height};this._rect.keepRatio&&(e=this._getPaintSize({elementWidth:this._stream.width,elementHeight:this._stream.height})),this._paintSize=e;const t=(n=this._stream.viewNode)==null?void 0:n.size(e.width,e.height);let r;return this._rect.mirrorType!==void 0&&this._rect.mirrorType!==ds.None?r=t==null?void 0:t.mirror(this._rect.mirrorType):r=t,r=r==null?void 0:r.position(this._rect.x,this._rect.y),r}get x(){return this._rect.x}set x(e){this.setBaseProps("x",e)}get y(){return this._rect.y}set y(e){this.setBaseProps("y",e)}get width(){return this._rect.width}set width(e){this.setBaseProps("width",e)}get height(){return this._rect.height}set height(e){this.setBaseProps("height",e)}get zOrder(){return this._rect.zOrder}set zOrder(e){this.setBaseProps("zOrder",e)}get keepRatio(){return this._rect.keepRatio??!1}set keepRatio(e){this.setBaseProps("keepRatio",e)}set mirrorType(e){this.setBaseProps("mirrorType",e)}get paintSize(){return this._paintSize}setBaseProps(e,t){const r=this._rect[e]!==t;switch(e){case"width":this._rect.width=t;break;case"height":this._rect.height=t;break;case"x":this._rect.x=t;break;case"y":this._rect.y=t;break;case"zOrder":this._rect.zOrder=t;break;case"keepRatio":this._rect.keepRatio=t;break;case"mirrorType":this._rect.mirrorType=t;break}r&&this.emit("propsChange",{[e]:t})}show(){this._isHidden=!1}hide(){this._isHidden=!0}get stream(){return this._stream}get isHidden(){return this._isHidden}destroy(){}}class La extends Ct{constructor(e,t){super({type:V.MixVideo,stream:e}),this._trackMap.video=e,this._frameRate=(t==null?void 0:t.frameRate)??1}get source(){return this._source}replaceVideoTrack(e){this._trackMap.video=e,this._source=e}get viewNode(){return null}get mixerNode(){return null}bindTrackEnd(e){this.source.onended=e}destroy(){this.source.stop(),delete this._trackMap.video}}var F_=Object.defineProperty,j_=Object.getOwnPropertyDescriptor,wi=(i,e,t,r)=>{for(var n=j_(e,t),s=i.length-1,a;s>=0;s--)(a=i[s])&&(n=a(e,t,n)||n);return n&&F_(e,t,n),n};const Ua=new nt("composition-composer");function Ci(i,e,t){const r=t.value;return t.value=function(...n){return this._active||Ua.error("composer is not active"),r.apply(this,n)},t}class Lt extends An{constructor(e){super(e),this._compositionViewConfig={width:1080,height:720,frameRate:30,backgroundColor:"#000000"},this._sprites=[],this._videoMixer=new Ld}onStreamCapture(e){}onStreamStopCapture(e){e&&e.isVideoStream&&this.removeVideoStream(e.id)}enable(){var r;if(this._active)return;super.enable();const e=this._videoMixer.track(),t=this._mixedVideoStream;this._mixedVideoStream=new La(e,{frameRate:this._compositionViewConfig.frameRate}),this._composedStream.setVideoStream(this._mixedVideoStream),t&&((r=t.videoTrack)==null?void 0:r.id)!==e.id&&t.destroy()}disable(){super.disable(),this._videoMixer.stop()}_updateSpriteToMixer(){const e=xo(this._sprites.map(t=>t.isHidden?null:t.getViewNode()));this._videoMixer.draw(e)}_removeSprite(e){this._sprites=this._sprites.filter(t=>t!==e),e.destroy(),this._updateSpriteToMixer()}_addSprite(e){this._sprites.push(e),this._sprites=this._sprites.sort((t,r)=>t.zOrder-r.zOrder),e.on("propsChange",t=>{Cf(t.zOrder)||(this._sprites=this._sprites.sort((r,n)=>r.zOrder-n.zOrder)),this._updateSpriteToMixer()}),this._updateSpriteToMixer()}setMixingConfig(e){const t=e.frameRate&&e.frameRate!==this._compositionViewConfig.frameRate;if(this._compositionViewConfig={...this._compositionViewConfig,...e},this._compositionViewConfig.frameRate<1&&(this._compositionViewConfig.frameRate=1),this._videoMixer.updateConfig(this._compositionViewConfig),t&&this._mixedVideoStream){const r=this._mixedVideoStream,n=this._videoMixer.updateFps();this._mixedVideoStream=new La(n,{frameRate:this._compositionViewConfig.frameRate}),this._composedStream.setVideoStream(this._mixedVideoStream),r.destroy()}}getMixingConfig(){return this._compositionViewConfig}addVideoStream(e,t){if(!e.viewNode){Ua.error("have no viewNode for composition");return}e.audioTrack&&this._streamComposeController.addAudioStream({streamId:e.id,volume:100});const r=new V_(e,t);this._addSprite(r)}_updateSingleVideoStream(e){const t=e.streamId;if(!t)return;const r=this._sprites.find(n=>n.stream.id===t);r&&(r.height=e.height,r.width=e.width,r.x=e.x,r.y=e.y,r.zOrder=e.zOrder,r.keepRatio=e.keepRatio??!1,r.mirrorType=e.mirrorType)}updateVideoStream(e){e.forEach(t=>{this._updateSingleVideoStream(t)}),this._updateSpriteToMixer()}removeVideoStream(e){if(!e)return;const t=this._sprites.find(r=>r.stream.id===e);t&&this._removeSprite(t)}muteVideoStream(e){if(e){const t=this._sprites.find(r=>r.stream.id===e);t&&t.hide()}else this._sprites.forEach(t=>{t.hide()});this._updateSpriteToMixer()}unmuteVideoStream(e){if(e){const t=this._sprites.find(r=>r.stream.id===e);t&&t.show()}else this._sprites.forEach(t=>{t.show()});this._updateSpriteToMixer()}setMixerWorkerScript(e){this._videoMixer.setWorkerTimerScriptUrl(e)}getVideoStreamRenderConfig(e){const t=this._sprites.find(r=>r.stream.id===e);if(t)return{width:t.width,height:t.height,paintWidth:t.paintSize.width,paintHeight:t.paintSize.height,x:t.x,y:t.y,zOrder:t.zOrder}}getDrawCountPerSecond(){return this._videoMixer.getDrawCountPerSecond()}}wi([Ci],Lt.prototype,"addVideoStream"),wi([Ci],Lt.prototype,"updateVideoStream"),wi([Ci],Lt.prototype,"removeVideoStream"),wi([Ci],Lt.prototype,"muteVideoStream"),wi([Ci],Lt.prototype,"unmuteVideoStream");class H_ extends Je{constructor(e,{volume:t}){super(),this._volume=100,this._isMute=!1,this._volume=t??100,this._stream=e}get volume(){return this._volume}set volume(e){const t=this._volume!==e;this._volume=e,t&&this.emit("propsChange",{volume:e})}getMixerNode(){var e;return(e=this._stream.mixerNode)==null?void 0:e.gain(this._volume/100)}mute(){this._isMute=!0}unmute(){this._isMute=!1}get isMute(){return this._isMute}get stream(){return this._stream}}class $_ extends Gi{constructor(e){super({type:V.MixAudio,stream:e}),this._trackMap.audio=e}get source(){return this._source}hasVideoTrack(){return!1}get mixerNode(){return null}bindTrackEnd(e){this.source.onended=e}destroy(){var e;(e=this._trackMap.audio)==null||e.stop(),delete this._trackMap.audio}}class q_ extends An{constructor(e){super(e),this._spriteList=[],this._audioMixer=new wd({keepAlive:!0})}onStreamCapture(e){}onStreamStopCapture(e){e&&this.removeAudioStream(e.id)}_updateSpriteToMixer(){const e=xo(this._spriteList.map(t=>t.isMute?null:t.getMixerNode()));this._audioMixer.mix(e)}_updateSingleAudioStream(e){const{streamId:t,volume:r}=e,n=this._spriteList.find(s=>s.stream.id===t);n?r!==void 0&&(n.volume=r):console.error("can not find stream"+t)}enable(){super.enable();const e=this._audioMixer.track(),t=new $_(e);this._composedStream.setAudioStream(t),this._audioMixer.mix([])}resumeMixer(){this._audioMixer.resume()}addAudioStream(e,t){const r=new H_(e,t);this._spriteList.push(r),this._updateSpriteToMixer()}tryResume(){return this._audioMixer.resume()}removeAudioStream(e){const t=this._spriteList.find(r=>r.stream.id===e);t&&(this._spriteList=this._spriteList.filter(r=>r!==t),this._updateSpriteToMixer())}updateAudioStream(e){e.forEach(t=>{this._updateSingleAudioStream(t)}),this._updateSpriteToMixer()}muteAudioStream(e){if(e){const t=this._spriteList.find(r=>r.stream.id===e);t&&t.mute()}else this._spriteList.forEach(t=>{t.mute()});this._updateSpriteToMixer()}unmuteAudioStream(e){if(e){const t=this._spriteList.find(r=>r.stream.id===e);t&&t.unmute()}else this._spriteList.forEach(t=>{t.unmute()});this._updateSpriteToMixer()}haveMixedStream(e){return this._spriteList.some(t=>t.stream.id===e)}getMixedStreamByType(e){return this._spriteList.filter(t=>t.stream.type===e).map(t=>t.stream)}}class K_ extends Je{constructor({videoStream:e,audioStream:t}={}){super(),this._videoStream=e,this._audioStream=t}setVideoStream(e){var t;((t=this._videoStream)==null?void 0:t.id)!==(e==null?void 0:e.id)&&(this._videoStream=e,this.emit(ut.VideoStreamChange,e))}setAudioStream(e){var t;((t=this._audioStream)==null?void 0:t.id)!==e.id&&(this._audioStream=e,this.emit(ut.AudioStreamChange,e))}get audioStream(){return this._audioStream}get videoStream(){return this._videoStream}get videoTrack(){var e;return(e=this._videoStream)==null?void 0:e.videoTrack}get audioTrack(){var e;return(e=this._audioStream)==null?void 0:e.audioTrack}}const W_=new nt("streamComposeController");class J_{constructor(e){this._streamManagerController=e,this._composedStream=new K_,this.singleComposer=new B_({streamManagerController:this._streamManagerController,composedStream:this._composedStream,streamComposeController:this}),this.compositionComposer=new Lt({streamManagerController:this._streamManagerController,composedStream:this._composedStream,streamComposeController:this}),this.mixerComposer=new q_({streamManagerController:this._streamManagerController,composedStream:this._composedStream,streamComposeController:this}),this.singleComposer.enable(),this.mixerComposer.enable()}enableMixing(e){e?(this.compositionComposer.enable(),this.singleComposer.disable()):(this.compositionComposer.disable(),this.singleComposer.enable())}setVideoQuality({width:e,height:t,frameRate:r}){this.singleComposer.setVideoQuality({width:e,height:t,frameRate:r}),this.compositionComposer.setMixingConfig({width:e,height:t,frameRate:r})}setMixingConfig(e){this.compositionComposer.setMixingConfig(e)}getMixingConfig(){return this.compositionComposer.getMixingConfig()}addAudioStream(e){const t=this._streamManagerController.getStreamById(e.streamId);this.mixerComposer.addAudioStream(t,{volume:e.volume??100})}removeAudioStream(e){return this.mixerComposer.removeAudioStream(e)}updateAudioStream(e){this.mixerComposer.updateAudioStream(e)}addVideoStream(e){const t=this._streamManagerController.getVideoStream(e.streamId);if(!t){W_.error("can not find video stream"+e.streamId);return}this.compositionComposer.addVideoStream(t,e)}updateVideoStream(e){this.compositionComposer.updateVideoStream(e);const t=e.map(r=>({streamId:r.streamId,volume:r.volume}));this.mixerComposer.updateAudioStream(t)}removeVideoStream(e){this.compositionComposer.removeVideoStream(e),this.mixerComposer.removeAudioStream(e)}getComposer(){return this.isEnableMixing?this.compositionComposer:this.singleComposer}getComposedStream(){return this._composedStream}muteVideoStream(e){this.isEnableMixing?this.compositionComposer.muteVideoStream(e):this.singleComposer.muteVideoStream()}unmuteVideoStream(e){this.isEnableMixing?this.compositionComposer.unmuteVideoStream(e):this.singleComposer.unmuteVideoStream()}muteAudioStream(e){this.mixerComposer.muteAudioStream(e)}unmuteAudioStream(e){this.mixerComposer.unmuteAudioStream(e)}get isEnableMixing(){return this.compositionComposer._active}getMixerComposer(){return this.mixerComposer}setMixerWorkerScript(e){this.compositionComposer.setMixerWorkerScript(e)}getVideoStreamRenderConfig(e){if(this.compositionComposer._active)return this.compositionComposer.getVideoStreamRenderConfig(e)}resumeMixer(){return this.mixerComposer.tryResume()}getCompositionDrawCountPerSecond(){return this.compositionComposer.getDrawCountPerSecond()}}class Ga{constructor(e){this._hasBindComposedStreamEvent=!1,this._composedStream=e}bindComposedStreamEvent(){this._hasBindComposedStreamEvent||(this._composedStream.on(ut.VideoStreamChange,this.handleVideoStreamChange),this._composedStream.on(ut.AudioStreamChange,this.handleAudioStreamChange),this._hasBindComposedStreamEvent=!0)}unbindComposedStreamEvent(){this._hasBindComposedStreamEvent&&(this._composedStream.off(ut.VideoStreamChange,this.handleVideoStreamChange),this._composedStream.off(ut.AudioStreamChange,this.handleAudioStreamChange),this._hasBindComposedStreamEvent=!1)}}const Ut=new nt("PreviewConsumer");class X_ extends Ga{constructor(e,{streamConsumeController:t}){super(e),this._isPreviewing=!1,this._previewElement=null,this.handleAudioStreamChange=r=>{this.startPreview()},this.handleVideoStreamChange=r=>{this.startPreview()},this._streamConsumeController=t}start(){this.bindComposedStreamEvent()}stop(){this.unbindComposedStreamEvent()}setRenderView(e){if(!e)return;const t=document.getElementById(e);if(!t)throw new Error(`can not found element with id ${e}`);if(t===this._previewElement)return;if(this._previewElement){if(t.contains(this._previewElement))return;t.appendChild(this._previewElement);return}const r=document.createElement("video");r.style.width="100%",r.style.height="100%",r.autoplay=!0,r.playsInline=!0,r.setAttribute("webkit-playsinline",""),r.setAttribute("x5-playsinline",""),this._previewElement=r;const n={video:null,audio:null};r.addEventListener("loadeddata",()=>{const s=r.srcObject.getVideoTracks()[0],a=r.srcObject.getAudioTracks()[0];s&&s!==n.video&&(this._streamConsumeController.emit(Z.CaptureFirstVideoFrame),n.video=s),a&&a!==n.audio&&(this._streamConsumeController.emit(Z.CaptureFirstAudioFrame),n.audio=a)}),t.appendChild(r)}startPreview(){if(Ut.log("startPreview"),!this._previewElement){Ut.warn("preview element not found");return}this._isPreviewing||this.start();const e=this._composedStream.audioTrack,t=this._composedStream.videoTrack;e&&(this._appendTrack(this._previewElement,e),this._removeTrack(this._previewElement,null)),t&&(this._appendTrack(this._previewElement,t),this._removeTrack(this._previewElement,null)),this._previewElement.play().catch(r=>{this._streamConsumeController.emit(Z.NotAllowedAutoPlay)}),this._isPreviewing=!0}stopPreview(){this._isPreviewing=!1;const e=this._composedStream.audioTrack,t=this._composedStream.videoTrack;e&&this._removeTrack(this._previewElement,e),t&&this._removeTrack(this._previewElement,t),this.stop()}destroy(){this.stopPreview(),this._previewElement=null,this.unbindComposedStreamEvent()}_appendTrack(e,t){if(!e||!t)return;const r=e.srcObject||new MediaStream;r.getTracks().find(n=>n.id===t.id)||(t.kind==="audio"&&r.getTracks().forEach(n=>{n.kind==="audio"&&(Ut.log(`remove preview track, ${n.label}, readyState=${n.readyState}`),r.removeTrack(n))}),t.kind==="video"&&r.getTracks().forEach(n=>{n.kind==="video"&&(r.removeTrack(n),Ut.log(`remove preview track, ${n.label}, readyState=${n.readyState}`))}),r.addTrack(t),e.srcObject?e.load():e.srcObject=r)}_removeTrack(e,t){if(!e)return;const r=e.srcObject;r&&(r.getTracks().forEach(n=>{(n.id===(t==null?void 0:t.id)||n.readyState==="ended")&&(Ut.log(`remove preview track ${n.label}`),r.removeTrack(n))}),r.getTracks().length===0&&(e.srcObject=null,Ut.log("set srcObject null")))}getPreviewElement(){if(this.isPreviewing)return this._previewElement}get isPreviewing(){return this._isPreviewing}}var ke={},Rn={},Dn={exports:{}},Na;function xn(){if(Na)return Dn.exports;Na=1;var i=Dn.exports={v:[{name:"version",reg:/^(\d*)$/}],o:[{name:"origin",reg:/^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,names:["username","sessionId","sessionVersion","netType","ipVer","address"],format:"%s %s %d %s IP%d %s"}],s:[{name:"name"}],i:[{name:"description"}],u:[{name:"uri"}],e:[{name:"email"}],p:[{name:"phone"}],z:[{name:"timezones"}],r:[{name:"repeats"}],t:[{name:"timing",reg:/^(\d*) (\d*)/,names:["start","stop"],format:"%d %d"}],c:[{name:"connection",reg:/^IN IP(\d) (\S*)/,names:["version","ip"],format:"IN IP%d %s"}],b:[{push:"bandwidth",reg:/^(TIAS|AS|CT|RR|RS):(\d*)/,names:["type","limit"],format:"%s:%s"}],m:[{reg:/^(\w*) (\d*) ([\w/]*)(?: (.*))?/,names:["type","port","protocol","payloads"],format:"%s %d %s %s"}],a:[{push:"rtp",reg:/^rtpmap:(\d*) ([\w\-.]*)(?:\s*\/(\d*)(?:\s*\/(\S*))?)?/,names:["payload","codec","rate","encoding"],format:function(e){return e.encoding?"rtpmap:%d %s/%s/%s":e.rate?"rtpmap:%d %s/%s":"rtpmap:%d %s"}},{push:"fmtp",reg:/^fmtp:(\d*) ([\S| ]*)/,names:["payload","config"],format:"fmtp:%d %s"},{name:"control",reg:/^control:(.*)/,format:"control:%s"},{name:"rtcp",reg:/^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,names:["port","netType","ipVer","address"],format:function(e){return e.address!=null?"rtcp:%d %s IP%d %s":"rtcp:%d"}},{push:"rtcpFbTrrInt",reg:/^rtcp-fb:(\*|\d*) trr-int (\d*)/,names:["payload","value"],format:"rtcp-fb:%s trr-int %d"},{push:"rtcpFb",reg:/^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,names:["payload","type","subtype"],format:function(e){return e.subtype!=null?"rtcp-fb:%s %s %s":"rtcp-fb:%s %s"}},{push:"ext",reg:/^extmap:(\d+)(?:\/(\w+))?(?: (urn:ietf:params:rtp-hdrext:encrypt))? (\S*)(?: (\S*))?/,names:["value","direction","encrypt-uri","uri","config"],format:function(e){return"extmap:%d"+(e.direction?"/%s":"%v")+(e["encrypt-uri"]?" %s":"%v")+" %s"+(e.config?" %s":"")}},{name:"extmapAllowMixed",reg:/^(extmap-allow-mixed)/},{push:"crypto",reg:/^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,names:["id","suite","config","sessionConfig"],format:function(e){return e.sessionConfig!=null?"crypto:%d %s %s %s":"crypto:%d %s %s"}},{name:"setup",reg:/^setup:(\w*)/,format:"setup:%s"},{name:"connectionType",reg:/^connection:(new|existing)/,format:"connection:%s"},{name:"mid",reg:/^mid:([^\s]*)/,format:"mid:%s"},{name:"msid",reg:/^msid:(.*)/,format:"msid:%s"},{name:"ptime",reg:/^ptime:(\d*(?:\.\d*)*)/,format:"ptime:%d"},{name:"maxptime",reg:/^maxptime:(\d*(?:\.\d*)*)/,format:"maxptime:%d"},{name:"direction",reg:/^(sendrecv|recvonly|sendonly|inactive)/},{name:"icelite",reg:/^(ice-lite)/},{name:"iceUfrag",reg:/^ice-ufrag:(\S*)/,format:"ice-ufrag:%s"},{name:"icePwd",reg:/^ice-pwd:(\S*)/,format:"ice-pwd:%s"},{name:"fingerprint",reg:/^fingerprint:(\S*) (\S*)/,names:["type","hash"],format:"fingerprint:%s %s"},{push:"candidates",reg:/^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: tcptype (\S*))?(?: generation (\d*))?(?: network-id (\d*))?(?: network-cost (\d*))?/,names:["foundation","component","transport","priority","ip","port","type","raddr","rport","tcptype","generation","network-id","network-cost"],format:function(e){var t="candidate:%s %d %s %d %s %d typ %s";return t+=e.raddr!=null?" raddr %s rport %d":"%v%v",t+=e.tcptype!=null?" tcptype %s":"%v",e.generation!=null&&(t+=" generation %d"),t+=e["network-id"]!=null?" network-id %d":"%v",t+=e["network-cost"]!=null?" network-cost %d":"%v",t}},{name:"endOfCandidates",reg:/^(end-of-candidates)/},{name:"remoteCandidates",reg:/^remote-candidates:(.*)/,format:"remote-candidates:%s"},{name:"iceOptions",reg:/^ice-options:(\S*)/,format:"ice-options:%s"},{push:"ssrcs",reg:/^ssrc:(\d*) ([\w_-]*)(?::(.*))?/,names:["id","attribute","value"],format:function(e){var t="ssrc:%d";return e.attribute!=null&&(t+=" %s",e.value!=null&&(t+=":%s")),t}},{push:"ssrcGroups",reg:/^ssrc-group:([\x21\x23\x24\x25\x26\x27\x2A\x2B\x2D\x2E\w]*) (.*)/,names:["semantics","ssrcs"],format:"ssrc-group:%s %s"},{name:"msidSemantic",reg:/^msid-semantic:\s?(\w*) (\S*)/,names:["semantic","token"],format:"msid-semantic: %s %s"},{push:"groups",reg:/^group:(\w*) (.*)/,names:["type","mids"],format:"group:%s %s"},{name:"rtcpMux",reg:/^(rtcp-mux)/},{name:"rtcpRsize",reg:/^(rtcp-rsize)/},{name:"sctpmap",reg:/^sctpmap:([\w_/]*) (\S*)(?: (\S*))?/,names:["sctpmapNumber","app","maxMessageSize"],format:function(e){return e.maxMessageSize!=null?"sctpmap:%s %s %s":"sctpmap:%s %s"}},{name:"xGoogleFlag",reg:/^x-google-flag:([^\s]*)/,format:"x-google-flag:%s"},{push:"rids",reg:/^rid:([\d\w]+) (\w+)(?: ([\S| ]*))?/,names:["id","direction","params"],format:function(e){return e.params?"rid:%s %s %s":"rid:%s %s"}},{push:"imageattrs",reg:new RegExp("^imageattr:(\\d+|\\*)[\\s\\t]+(send|recv)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*)(?:[\\s\\t]+(recv|send)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*))?"),names:["pt","dir1","attrs1","dir2","attrs2"],format:function(e){return"imageattr:%s %s %s"+(e.dir2?" %s %s":"")}},{name:"simulcast",reg:new RegExp("^simulcast:(send|recv) ([a-zA-Z0-9\\-_~;,]+)(?:\\s?(send|recv) ([a-zA-Z0-9\\-_~;,]+))?$"),names:["dir1","list1","dir2","list2"],format:function(e){return"simulcast:%s %s"+(e.dir2?" %s %s":"")}},{name:"simulcast_03",reg:/^simulcast:[\s\t]+([\S+\s\t]+)$/,names:["value"],format:"simulcast: %s"},{name:"framerate",reg:/^framerate:(\d+(?:$|\.\d+))/,format:"framerate:%s"},{name:"sourceFilter",reg:/^source-filter: *(excl|incl) (\S*) (IP4|IP6|\*) (\S*) (.*)/,names:["filterMode","netType","addressTypes","destAddress","srcList"],format:"source-filter: %s %s %s %s %s"},{name:"bundleOnly",reg:/^(bundle-only)/},{name:"label",reg:/^label:(.+)/,format:"label:%s"},{name:"sctpPort",reg:/^sctp-port:(\d+)$/,format:"sctp-port:%s"},{name:"maxMessageSize",reg:/^max-message-size:(\d+)$/,format:"max-message-size:%s"},{push:"tsRefClocks",reg:/^ts-refclk:([^\s=]*)(?:=(\S*))?/,names:["clksrc","clksrcExt"],format:function(e){return"ts-refclk:%s"+(e.clksrcExt!=null?"=%s":"")}},{name:"mediaClk",reg:/^mediaclk:(?:id=(\S*))? *([^\s=]*)(?:=(\S*))?(?: *rate=(\d+)\/(\d+))?/,names:["id","mediaClockName","mediaClockValue","rateNumerator","rateDenominator"],format:function(e){var t="mediaclk:";return t+=e.id!=null?"id=%s %s":"%v%s",t+=e.mediaClockValue!=null?"=%s":"",t+=e.rateNumerator!=null?" rate=%s":"",t+=e.rateDenominator!=null?"/%s":"",t}},{name:"keywords",reg:/^keywds:(.+)$/,format:"keywds:%s"},{name:"content",reg:/^content:(.+)/,format:"content:%s"},{name:"bfcpFloorCtrl",reg:/^floorctrl:(c-only|s-only|c-s)/,format:"floorctrl:%s"},{name:"bfcpConfId",reg:/^confid:(\d+)/,format:"confid:%s"},{name:"bfcpUserId",reg:/^userid:(\d+)/,format:"userid:%s"},{name:"bfcpFloorId",reg:/^floorid:(.+) (?:m-stream|mstrm):(.+)/,names:["id","mStream"],format:"floorid:%s mstrm:%s"},{push:"invalid",names:["value"]}]};return Object.keys(i).forEach(function(e){var t=i[e];t.forEach(function(r){r.reg||(r.reg=/(.*)/),r.format||(r.format="%s")})}),Dn.exports}var Ba;function Z_(){return Ba||(Ba=1,function(i){var e=function(o){return String(Number(o))===o?Number(o):o},t=function(o,d,c,u){if(u&&!c)d[u]=e(o[1]);else for(var l=0;l<c.length;l+=1)o[l+1]!=null&&(d[c[l]]=e(o[l+1]))},r=function(o,d,c){var u=o.name&&o.names;o.push&&!d[o.push]?d[o.push]=[]:u&&!d[o.name]&&(d[o.name]={});var l=o.push?{}:u?d[o.name]:d;t(c.match(o.reg),l,o.names,o.name),o.push&&d[o.push].push(l)},n=xn(),s=RegExp.prototype.test.bind(/^([a-z])=(.*)/);i.parse=function(o){var d={},c=[],u=d;return o.split(/(\r\n|\r|\n)/).filter(s).forEach(function(l){var h=l[0],p=l.slice(2);h==="m"&&(c.push({rtp:[],fmtp:[]}),u=c[c.length-1]);for(var f=0;f<(n[h]||[]).length;f+=1){var v=n[h][f];if(v.reg.test(p))return r(v,u,p)}}),d.media=c,d};var a=function(o,d){var c=d.split(/=(.+)/,2);return c.length===2?o[c[0]]=e(c[1]):c.length===1&&d.length>1&&(o[c[0]]=void 0),o};i.parseParams=function(o){return o.split(/;\s?/).reduce(a,{})},i.parseFmtpConfig=i.parseParams,i.parsePayloads=function(o){return o.toString().split(" ").map(Number)},i.parseRemoteCandidates=function(o){for(var d=[],c=o.split(" ").map(e),u=0;u<c.length;u+=3)d.push({component:c[u],ip:c[u+1],port:c[u+2]});return d},i.parseImageAttributes=function(o){return o.split(" ").map(function(d){return d.substring(1,d.length-1).split(",").reduce(a,{})})},i.parseSimulcastStreamList=function(o){return o.split(";").map(function(d){return d.split(",").map(function(c){var u,l=!1;return c[0]!=="~"?u=e(c):(u=e(c.substring(1,c.length)),l=!0),{scid:u,paused:l}})})}}(Rn)),Rn}var In,Va;function Q_(){if(Va)return In;Va=1;var i=xn(),e=/%[sdv%]/g,t=function(a){var o=1,d=arguments,c=d.length;return a.replace(e,function(u){if(o>=c)return u;var l=d[o];switch(o+=1,u){case"%%":return"%";case"%s":return String(l);case"%d":return Number(l);case"%v":return""}})},r=function(a,o,d){var c=o.format instanceof Function?o.format(o.push?d:d[o.name]):o.format,u=[a+"="+c];if(o.names)for(var l=0;l<o.names.length;l+=1){var h=o.names[l];o.name?u.push(d[o.name][h]):u.push(d[o.names[l]])}else u.push(d[o.name]);return t.apply(null,u)},n=["v","o","s","i","u","e","p","c","b","t","r","z","a"],s=["i","c","b","a"];return In=function(a,o){o=o||{},a.version==null&&(a.version=0),a.name==null&&(a.name=" "),a.media.forEach(function(l){l.payloads==null&&(l.payloads="")});var d=o.outerOrder||n,c=o.innerOrder||s,u=[];return d.forEach(function(l){i[l].forEach(function(h){h.name in a&&a[h.name]!=null?u.push(r(l,h,a)):h.push in a&&a[h.push]!=null&&a[h.push].forEach(function(p){u.push(r(l,h,p))})})}),a.media.forEach(function(l){u.push(r("m",i.m[0],l)),c.forEach(function(h){i[h].forEach(function(p){p.name in l&&l[p.name]!=null?u.push(r(h,p,l)):p.push in l&&l[p.push]!=null&&l[p.push].forEach(function(f){u.push(r(h,p,f))})})})}),u.join(`\r
57
67
  `)+`\r
58
- `},Vt}var Pi;function Ru(){if(Pi)return B;Pi=1;var r=Pu(),e=xu(),t=Nt();return B.grammar=t,B.write=e,B.parse=r.parse,B.parseParams=r.parseParams,B.parseFmtpConfig=r.parseFmtpConfig,B.parsePayloads=r.parsePayloads,B.parseRemoteCandidates=r.parseRemoteCandidates,B.parseImageAttributes=r.parseImageAttributes,B.parseSimulcastStreamList=r.parseSimulcastStreamList,B}var Au=Ru();const Xe=I(Au);function xi(r){return new Promise(e=>{setTimeout(e,r)})}async function wu(r,e={},t=0){const i=new AbortController;let s=!1;e=Object.assign({},e,{signal:i.signal});const n=[fetch(r,e)];t&&n.push(new Promise((a,o)=>{setTimeout(()=>{s||(o({httpCode:0,message:"Timeout"}),i.abort())},t)}));try{const a=await Promise.race(n);if(s=!0,!a.ok||a.status<200||a.status>=300)throw{httpCode:a.status,message:a.statusText};return a.json()}catch(a){throw s=!0,a}}async function Ri(r,e={},t={}){const{timeout:i=0,retryDelay:s=0}=t;let{retryCount:n=0}=t;try{return await wu(r,e,i)}catch(a){if(n--,t.retryCount=n,n<0)throw a;return await xi(s),await Ri(r,e,t)}}function w(r,e){let t;return e.forEach(i=>{i.type===r&&(t=i)}),t}async function Ut(r,e){const t={},i=await(r==null?void 0:r.getStats()),s=await(e==null?void 0:e.getStats());return i&&(t.audio={mediaSource:w("media-source",i),codec:w("codec",i),candidatePair:w("candidate-pair",i),remoteCandidate:w("remote-candidate",i),localCandidate:w("local-candidate",i),track:w("track",i),outboundRtp:w("outbound-rtp",i),remoteInboundRtp:w("remote-inbound-rtp",i),transport:w("transport",i)}),s&&(t.video={mediaSource:w("media-source",s),codec:w("codec",s),candidatePair:w("candidate-pair",s),remoteCandidate:w("remote-candidate",s),localCandidate:w("local-candidate",s),track:w("track",s),outboundRtp:w("outbound-rtp",s),remoteInboundRtp:w("remote-inbound-rtp",s),transport:w("transport",s)}),t}async function Ou(r,e,t){var c,h,p,l,f,g,_,T,b,v,j,R,xs,Rs,As,ws,Os,Is,Ds,Ms,Ls,Fs,Ns,Vs,Us,$s,Bs,js,zs,Gs,Hs,qs,Ws,Xs,Ks,Js;const i=await Ut(e,t);await xi(r);const s=await Ut(e,t),{audio:n,video:a}=i,{audio:o,video:u}=s,d={};if(n!=null&&n.codec&&(o!=null&&o.codec)){const Jt=((c=o.outboundRtp)==null?void 0:c.timestamp)-((h=n.outboundRtp)==null?void 0:h.timestamp),Yt=((p=o.outboundRtp)==null?void 0:p.bytesSent)-((l=n.outboundRtp)==null?void 0:l.bytesSent),Zt=((f=o.remoteInboundRtp)==null?void 0:f.packetsLost)-((g=n.remoteInboundRtp)==null?void 0:g.packetsLost),Qt=((_=o.outboundRtp)==null?void 0:_.packetsSent)-((T=n.outboundRtp)==null?void 0:T.packetsSent);d.audio={codec:o.codec.mimeType,channels:o.codec.channels,sendBitrate:Yt/Jt*8e3,packetsSent:(b=o.outboundRtp)==null?void 0:b.packetsSent,nackCount:(v=o.outboundRtp)==null?void 0:v.nackCount,packetsLost:(j=o.remoteInboundRtp)==null?void 0:j.packetsLost,packetsLostPercent:Zt/Qt}}if(a!=null&&a.codec&&(u!=null&&u.codec)){const Jt=((R=u.outboundRtp)==null?void 0:R.timestamp)-((xs=a.outboundRtp)==null?void 0:xs.timestamp),Yt=((Rs=u.outboundRtp)==null?void 0:Rs.bytesSent)-((As=a.outboundRtp)==null?void 0:As.bytesSent),Zt=((ws=u.outboundRtp)==null?void 0:ws.framesEncoded)-((Os=a.outboundRtp)==null?void 0:Os.framesEncoded),Qt=((Is=u.outboundRtp)==null?void 0:Is.totalEncodeTime)-((Ds=a.outboundRtp)==null?void 0:Ds.totalEncodeTime),Ys=((Ms=u.outboundRtp)==null?void 0:Ms.packetsSent)-((Ls=a.outboundRtp)==null?void 0:Ls.packetsSent),dh=((Fs=u.outboundRtp)==null?void 0:Fs.totalPacketSendDelay)-((Ns=a.outboundRtp)==null?void 0:Ns.totalPacketSendDelay),uh=((Vs=u.remoteInboundRtp)==null?void 0:Vs.packetsLost)-((Us=a.remoteInboundRtp)==null?void 0:Us.packetsLost);d.video={codec:u.codec.mimeType,sendBitrate:Yt/Jt*8e3,frameWidth:($s=u.outboundRtp)==null?void 0:$s.frameWidth,frameHeight:(Bs=u.outboundRtp)==null?void 0:Bs.frameHeight,framesPerSecond:(js=u.outboundRtp)==null?void 0:js.framesPerSecond,framesEncoded:(zs=u.outboundRtp)==null?void 0:zs.framesEncoded,keyFramesEncoded:(Gs=u.outboundRtp)==null?void 0:Gs.keyFramesEncoded,framesSent:(Hs=u.outboundRtp)==null?void 0:Hs.frameHeight,frameEncodeAvgTime:Qt*1e3/Zt,packetsSent:(qs=u.outboundRtp)==null?void 0:qs.packetsSent,packetSendDelay:dh*1e3/Ys,nackCount:(Ws=u.outboundRtp)==null?void 0:Ws.nackCount,firCount:(Xs=u.outboundRtp)==null?void 0:Xs.firCount,pliCount:(Ks=u.outboundRtp)==null?void 0:Ks.pliCount,packetsLost:(Js=u.remoteInboundRtp)==null?void 0:Js.packetsLost,packetsLostPercent:uh/Ys}}return d}const Iu=r=>{var t;if(!lr)return;const e=(t=r.rtp.filter(i=>i.codec==="opus")[0])==null?void 0:t.payload;e&&r.fmtp.forEach(i=>{i.payload===e&&(i.config="minptime=10;useinbandfec=1")})},Du=r=>{r.ext&&(dn||Le)&&(r.ext=r.ext.filter(e=>{var t;return!((t=e.uri)!=null&&t.includes("video-orientation"))}))};function Mu(r,e){r==null||r.rtp.forEach(({codec:t,payload:i})=>{if(["vp8","h264"].includes(t.toLocaleLowerCase())){const s=r.fmtp.find(n=>n.payload===i);s?s.config=[...s.config.split(";"),"x-google-min-bitrate=100",`x-google-start-bitrate=${e}`].join(";"):r.fmtp.push({payload:i,config:`x-google-min-bitrate=100;x-google-start-bitrate=${e}`})}})}const M=new de("PCConnect");class Lu{constructor(e,t,i){this._pc=null,this._ms=new MediaStream,this._signalUrl="",this._videoTransceiver=null,this._audioTransceiver=null,this._opts=void 0,this._sessionId=Date.now(),this._signalUrl=e,this._opts=t,this._onConnectStateChange=i}get isPushing(){var e,t,i,s;return((t=(e=this._videoTransceiver)==null?void 0:e.sender)==null?void 0:t.track)||((s=(i=this._audioTransceiver)==null?void 0:i.sender)==null?void 0:s.track)}get pushUrl(){return this._signalUrl}get sessionId(){return this._sessionId}async publish(e,t){const i=new RTCPeerConnection;this._pc=i,this._bindRTCEvent();const s=e.filter(c=>(c==null?void 0:c.kind)==="audio")[0],n=e.filter(c=>(c==null?void 0:c.kind)==="video")[0];s&&this._ms.addTrack(s),n&&this._ms.addTrack(n),this._audioTransceiver=i.addTransceiver(s||"audio",{direction:"sendonly",sendEncodings:[{maxBitrate:t[0]}],streams:[this._ms]}),M.log("add track to pc,",s),this._videoTransceiver=i.addTransceiver(n||"video",{direction:"sendonly",sendEncodings:[{maxBitrate:t[1]}],streams:[this._ms]}),M.log("add track to pc,",n);const a=await i.createOffer();M.groupCollapsed("local offer"),M.log(a.sdp);const o=Xe.parse(a.sdp);o.media.forEach(c=>{c.type==="audio"?Iu(c):c.type==="video"&&(Du(c),Mu(c,t[1]))}),a.sdp=Xe.write(o),M.log("local offer modified"),M.log(a.sdp),await i.setLocalDescription(a);const u=await Ri(this._signalUrl,{method:"POST",mode:"cors",body:JSON.stringify({sessionId:""+this._sessionId,version:"1.0-html",localSdp:a,metadata:{platform:"Web"}})},this._opts);if((u==null?void 0:u.code)!==200)throw{code:u.code,message:u.message};M.log("remote answer:"),M.log(u.remoteSdp.sdp);const d=Xe.parse(u.remoteSdp.sdp);d.media.forEach(c=>{var h;(h=c.fingerprint)!=null&&h.hash&&(c.fingerprint.hash=c.fingerprint.hash.toUpperCase())}),u.remoteSdp.sdp=Xe.write(d),M.log("remote answer modified"),M.log(u.remoteSdp.sdp),M.groupEnd(),await i.setRemoteDescription(u.remoteSdp)}async updatePublish(e,t){var n,a;let i;t==="video"?i=this._videoTransceiver:i=this._audioTransceiver;const s=(n=i==null?void 0:i.sender)==null?void 0:n.track;(s==null?void 0:s.id)!==(e==null?void 0:e.id)&&(await((a=i==null?void 0:i.sender)==null?void 0:a.replaceTrack(e)),M.log(`replace ${t} track done! ${s==null?void 0:s.label} -> ${e==null?void 0:e.label}`))}applyBitrate(e,t,i){var a,o,u;const s=t==="video"?(a=this._videoTransceiver)==null?void 0:a.sender:(o=this._audioTransceiver)==null?void 0:o.sender;if(!s)return;const n=s.getParameters();n.encodings=(u=n.encodings)!=null&&u.length?n.encodings:[{}],i?n.encodings[0].minBitrate=e:n.encodings[0].maxBitrate=e,s.setParameters(n),M.log(`set bitrate for ${t}, ${e} bps, min:${i}`)}unpublish(){var e,t;(e=this._pc)==null||e.getSenders().forEach(i=>{var s;(s=this._pc)==null||s.removeTrack(i)}),(t=this._pc)==null||t.close(),this._audioTransceiver=null,this._videoTransceiver=null,this._pc=null,M.log("close pc!")}getStats(){var e,t;return Ut((e=this._audioTransceiver)==null?void 0:e.sender,(t=this._videoTransceiver)==null?void 0:t.sender)}getStatsSnapshoot(e){var t,i;return Ou(e||100,(t=this._audioTransceiver)==null?void 0:t.sender,(i=this._videoTransceiver)==null?void 0:i.sender)}_bindRTCEvent(){const e=this._pc;e==null||e.addEventListener("connectionstatechange",()=>{M.log("onconnectionstatechange:",e.connectionState),this._onConnectStateChange(e.connectionState)})}}var ue=(r=>(r.OnError="onerror",r.OnConnectClosed="onconnectclosed",r.OnFirstFramePushed="onfirstframepushed",r))(ue||{}),ie=(r=>(r.Video="video",r.Audio="audio",r))(ie||{}),V=(r=>(r.Init="init",r.AvExist="avexist",r.VideoFrame="videoframe",r.MockVideoEncode="mockvideoencode",r.AudioFrame="audioframe",r.AdjustBitrate="adjustbitrate",r.Publish="publish",r.UnPublish="unpublish",r.Download="download",r.GetStats="getstats",r.EncodeConfig="encodeconfig",r))(V||{}),he=(r=>(r.Ready="ready",r.Error="error",r.FirstFramePushed="firstframepushed",r.Flvfile="flvfile",r.STATS="stats",r.Close="close",r))(he||{}),$t={exports:{}},Ai;function Fu(){return Ai||(Ai=1,function(r){var e=Object.prototype.hasOwnProperty,t="~";function i(){}Object.create&&(i.prototype=Object.create(null),new i().__proto__||(t=!1));function s(u,d,c){this.fn=u,this.context=d,this.once=c||!1}function n(u,d,c,h,p){if(typeof c!="function")throw new TypeError("The listener must be a function");var l=new s(c,h||u,p),f=t?t+d:d;return u._events[f]?u._events[f].fn?u._events[f]=[u._events[f],l]:u._events[f].push(l):(u._events[f]=l,u._eventsCount++),u}function a(u,d){--u._eventsCount===0?u._events=new i:delete u._events[d]}function o(){this._events=new i,this._eventsCount=0}o.prototype.eventNames=function(){var d=[],c,h;if(this._eventsCount===0)return d;for(h in c=this._events)e.call(c,h)&&d.push(t?h.slice(1):h);return Object.getOwnPropertySymbols?d.concat(Object.getOwnPropertySymbols(c)):d},o.prototype.listeners=function(d){var c=t?t+d:d,h=this._events[c];if(!h)return[];if(h.fn)return[h.fn];for(var p=0,l=h.length,f=new Array(l);p<l;p++)f[p]=h[p].fn;return f},o.prototype.listenerCount=function(d){var c=t?t+d:d,h=this._events[c];return h?h.fn?1:h.length:0},o.prototype.emit=function(d,c,h,p,l,f){var g=t?t+d:d;if(!this._events[g])return!1;var _=this._events[g],T=arguments.length,b,v;if(_.fn){switch(_.once&&this.removeListener(d,_.fn,void 0,!0),T){case 1:return _.fn.call(_.context),!0;case 2:return _.fn.call(_.context,c),!0;case 3:return _.fn.call(_.context,c,h),!0;case 4:return _.fn.call(_.context,c,h,p),!0;case 5:return _.fn.call(_.context,c,h,p,l),!0;case 6:return _.fn.call(_.context,c,h,p,l,f),!0}for(v=1,b=new Array(T-1);v<T;v++)b[v-1]=arguments[v];_.fn.apply(_.context,b)}else{var j=_.length,R;for(v=0;v<j;v++)switch(_[v].once&&this.removeListener(d,_[v].fn,void 0,!0),T){case 1:_[v].fn.call(_[v].context);break;case 2:_[v].fn.call(_[v].context,c);break;case 3:_[v].fn.call(_[v].context,c,h);break;case 4:_[v].fn.call(_[v].context,c,h,p);break;default:if(!b)for(R=1,b=new Array(T-1);R<T;R++)b[R-1]=arguments[R];_[v].fn.apply(_[v].context,b)}}return!0},o.prototype.on=function(d,c,h){return n(this,d,c,h,!1)},o.prototype.once=function(d,c,h){return n(this,d,c,h,!0)},o.prototype.removeListener=function(d,c,h,p){var l=t?t+d:d;if(!this._events[l])return this;if(!c)return a(this,l),this;var f=this._events[l];if(f.fn)f.fn===c&&(!p||f.once)&&(!h||f.context===h)&&a(this,l);else{for(var g=0,_=[],T=f.length;g<T;g++)(f[g].fn!==c||p&&!f[g].once||h&&f[g].context!==h)&&_.push(f[g]);_.length?this._events[l]=_.length===1?_[0]:_:a(this,l)}return this},o.prototype.removeAllListeners=function(d){var c;return d?(c=t?t+d:d,this._events[c]&&a(this,c)):(this._events=new i,this._eventsCount=0),this},o.prototype.off=o.prototype.removeListener,o.prototype.addListener=o.prototype.on,o.prefixed=t,o.EventEmitter=o,r.exports=o}($t)),$t.exports}var Nu=Fu();const Vu=I(Nu);var Bt=(r=>(r[r.RTMP_INIT_FAIL=3e3]="RTMP_INIT_FAIL",r[r.AUDIO_ENCODER_INIT_FAIL=3001]="AUDIO_ENCODER_INIT_FAIL",r[r.AUDIO_RRNOISE_INIT_FAIL=3002]="AUDIO_RRNOISE_INIT_FAIL",r[r.AUDIO_ENCODE_FAIL=3003]="AUDIO_ENCODE_FAIL",r[r.VIDEO_ENCODE_CONFIGURE_FAIL=3004]="VIDEO_ENCODE_CONFIGURE_FAIL",r[r.VIDEO_ENCODE_FAIL=3005]="VIDEO_ENCODE_FAIL",r[r.WTP_OPEN_FAIL=3006]="WTP_OPEN_FAIL",r[r.WTP_CONNECT_FAIL=3007]="WTP_CONNECT_FAIL",r[r.WORKER_ERROR=3008]="WORKER_ERROR",r))(Bt||{});class Uu extends Error{constructor(e,t,i){super(),this.code=e,this.message=t,i&&(this.ext=i),this.toJson=()=>({code:this.code,message:this.message,ext:this.ext})}}function wi(r,e,t){return new Uu(r,e,t)}const Te=class Te{constructor(e){this.group=(...t)=>{this._enabled&&console.group(`[${this._prefix}]: `,...t)},this.groupCollapsed=(...t)=>{this._enabled&&console.groupCollapsed(`[${this._prefix}]: `,...t)},this.groupEnd=()=>{this._enabled&&console.groupEnd()},this.log=(...t)=>{this._enabled&&console.log(`[${this._prefix}]: `,...t)},this.warn=(...t)=>{this._enabled&&console.warn(`[${this._prefix}]: `,...t)},this.error=(...t)=>{this._enabled&&console.error(`[${this._prefix}]: `,...t)},this.table=(...t)=>{this._enabled&&console.table(...t)},this._prefix=e}get _enabled(){return Te.enable}get _enableLong(){return Te.enableLong}get long(){return this._enableLong}};Te.enable=!1,Te.enableLong=!1;let se=Te;const U=new se("RTMP_Capture");class $u{constructor(e){this._videoFirstframeCaptured=!1,this._audioFirstframeCaptured=!1,this._videoProcessorReader=null,this._audioProcessorReader=null,this._bridge=e}get audioTrack(){return this._bridge.audioMsTrack}get videoTrack(){return this._bridge.videoMsTrack}start(){this._startVideoCapture(),this._startAudioCapture()}restartCapture(e){if(U.log(`replace ${e} track`),e===ie.Video){if(this._videoProcessorReader){this._videoProcessorReader.cancel().finally(()=>{this._startVideoCapture()});return}this._startVideoCapture();return}if(this._audioProcessorReader){this._audioProcessorReader.cancel().finally(()=>{this._startAudioCapture()});return}this._startAudioCapture()}async _startVideoCapture(){var s;if(!this.videoTrack){U.log("no video track to capture");return}if(this.videoTrack.readyState!=="live"){U.warn("video track not live");return}const e=new MediaStreamTrackProcessor(this.videoTrack);e.track=this.videoTrack;const t=e.readable.getReader();this._videoProcessorReader=t,U.log("start capture video frame",this.videoTrack);let i;for(;;){i&&clearInterval(i),i=setTimeout(()=>{U.warn("long time no capture output"),this._bridge._postMockVideoEncodeFlag()},1500);const n=await t.read();if(clearInterval(i),this._videoFirstframeCaptured||(this._videoFirstframeCaptured=!0,U.log("video first frame captured")),n.done||!n.value){(s=n.value)==null||s.close();break}this._bridge._postVideoFrame(n.value,this.videoTrack.getSettings())}clearInterval(i),this._videoFirstframeCaptured=!1,this._videoProcessorReader=null,U.log("video track read done!",e.track)}async _startAudioCapture(){if(!this.audioTrack){U.log("no audio track to capture");return}if(this.audioTrack.readyState!=="live"){U.warn("audio track not live");return}const e=new MediaStreamTrackProcessor(this.audioTrack);e.track=this.audioTrack;const t=e.readable.getReader();for(this._audioProcessorReader=t,U.log("start capture audio frame");;){const i=await t.read();if(this._audioFirstframeCaptured||(this._audioFirstframeCaptured=!0,U.log("audio first frame captured")),i.done||!i.value)break;this._bridge._postAudioFrame(i.value,this.audioTrack.getSettings())}this._audioFirstframeCaptured=!1,this._audioProcessorReader=null,U.log("audio track read done!",e.track)}destroy(){var e,t;(e=this._audioProcessorReader)==null||e.cancel().catch(()=>{}),(t=this._videoProcessorReader)==null||t.cancel().catch(()=>{})}}const Oi='(function(){"use strict";var l=(i=>(i.OnVideoCaptured="onvideocaptured",i.OnAudioCaptured="onaudiocaptured",i.OnVideoCaptureNoOutput="onvideocapturenooutput",i.OnVideoEncoded="onvideoencoded",i.OnAudioEncoded="onaudioencoded",i.OnEncodedFrame="onencodedframe",i.OnPacketed="onpacketed",i.OnUpstreamFeedback="onupstreamfeedback",i.OnBitrateChanged="onbitratechanged",i))(l||{}),O=(i=>(i.OnError="onerror",i.OnConnectClosed="onconnectclosed",i.OnFirstFramePushed="onfirstframepushed",i))(O||{}),I=(i=>(i.Video="video",i.Audio="audio",i))(I||{}),v=(i=>(i.Init="init",i.AvExist="avexist",i.VideoFrame="videoframe",i.MockVideoEncode="mockvideoencode",i.AudioFrame="audioframe",i.AdjustBitrate="adjustbitrate",i.Publish="publish",i.UnPublish="unpublish",i.Download="download",i.GetStats="getstats",i.EncodeConfig="encodeconfig",i))(v||{}),w=(i=>(i.Ready="ready",i.Error="error",i.FirstFramePushed="firstframepushed",i.Flvfile="flvfile",i.STATS="stats",i.Close="close",i))(w||{});function $(i){return i&&i.__esModule&&Object.prototype.hasOwnProperty.call(i,"default")?i.default:i}var k={exports:{}},U;function q(){return U||(U=1,function(i){var t=Object.prototype.hasOwnProperty,e="~";function s(){}Object.create&&(s.prototype=Object.create(null),new s().__proto__||(e=!1));function r(u,a,n){this.fn=u,this.context=a,this.once=n||!1}function o(u,a,n,h,m){if(typeof n!="function")throw new TypeError("The listener must be a function");var g=new r(n,h||u,m),f=e?e+a:a;return u._events[f]?u._events[f].fn?u._events[f]=[u._events[f],g]:u._events[f].push(g):(u._events[f]=g,u._eventsCount++),u}function _(u,a){--u._eventsCount===0?u._events=new s:delete u._events[a]}function c(){this._events=new s,this._eventsCount=0}c.prototype.eventNames=function(){var a=[],n,h;if(this._eventsCount===0)return a;for(h in n=this._events)t.call(n,h)&&a.push(e?h.slice(1):h);return Object.getOwnPropertySymbols?a.concat(Object.getOwnPropertySymbols(n)):a},c.prototype.listeners=function(a){var n=e?e+a:a,h=this._events[n];if(!h)return[];if(h.fn)return[h.fn];for(var m=0,g=h.length,f=new Array(g);m<g;m++)f[m]=h[m].fn;return f},c.prototype.listenerCount=function(a){var n=e?e+a:a,h=this._events[n];return h?h.fn?1:h.length:0},c.prototype.emit=function(a,n,h,m,g,f){var F=e?e+a:a;if(!this._events[F])return!1;var d=this._events[F],C=arguments.length,B,p;if(d.fn){switch(d.once&&this.removeListener(a,d.fn,void 0,!0),C){case 1:return d.fn.call(d.context),!0;case 2:return d.fn.call(d.context,n),!0;case 3:return d.fn.call(d.context,n,h),!0;case 4:return d.fn.call(d.context,n,h,m),!0;case 5:return d.fn.call(d.context,n,h,m,g),!0;case 6:return d.fn.call(d.context,n,h,m,g,f),!0}for(p=1,B=new Array(C-1);p<C;p++)B[p-1]=arguments[p];d.fn.apply(d.context,B)}else{var fe=d.length,R;for(p=0;p<fe;p++)switch(d[p].once&&this.removeListener(a,d[p].fn,void 0,!0),C){case 1:d[p].fn.call(d[p].context);break;case 2:d[p].fn.call(d[p].context,n);break;case 3:d[p].fn.call(d[p].context,n,h);break;case 4:d[p].fn.call(d[p].context,n,h,m);break;default:if(!B)for(R=1,B=new Array(C-1);R<C;R++)B[R-1]=arguments[R];d[p].fn.apply(d[p].context,B)}}return!0},c.prototype.on=function(a,n,h){return o(this,a,n,h,!1)},c.prototype.once=function(a,n,h){return o(this,a,n,h,!0)},c.prototype.removeListener=function(a,n,h,m){var g=e?e+a:a;if(!this._events[g])return this;if(!n)return _(this,g),this;var f=this._events[g];if(f.fn)f.fn===n&&(!m||f.once)&&(!h||f.context===h)&&_(this,g);else{for(var F=0,d=[],C=f.length;F<C;F++)(f[F].fn!==n||m&&!f[F].once||h&&f[F].context!==h)&&d.push(f[F]);d.length?this._events[g]=d.length===1?d[0]:d:_(this,g)}return this},c.prototype.removeAllListeners=function(a){var n;return a?(n=e?e+a:a,this._events[n]&&_(this,n)):(this._events=new s,this._eventsCount=0),this},c.prototype.off=c.prototype.removeListener,c.prototype.addListener=c.prototype.on,c.prefixed=e,c.EventEmitter=c,i.exports=c}(k)),k.exports}var z=q(),H=$(z);const N=class N{constructor(t){this.group=(...e)=>{this._enabled&&console.group(`[${this._prefix}]: `,...e)},this.groupCollapsed=(...e)=>{this._enabled&&console.groupCollapsed(`[${this._prefix}]: `,...e)},this.groupEnd=()=>{this._enabled&&console.groupEnd()},this.log=(...e)=>{this._enabled&&console.log(`[${this._prefix}]: `,...e)},this.warn=(...e)=>{this._enabled&&console.warn(`[${this._prefix}]: `,...e)},this.error=(...e)=>{this._enabled&&console.error(`[${this._prefix}]: `,...e)},this.table=(...e)=>{this._enabled&&console.table(...e)},this._prefix=t}get _enabled(){return N.enable}get _enableLong(){return N.enableLong}get long(){return this._enableLong}};N.enable=!1,N.enableLong=!1;let E=N;function S(i){i=i.filter(Boolean);const t=new Uint8Array(i.reduce((s,r)=>s+r.byteLength,0));let e=0;return i.forEach(s=>{t.set(s,e),e+=s.byteLength}),t}const A={codec:"avc1.4DE033",MaxCachedFrameSize:100,RealSpeedPercent:.8,UplinkBitrateCheckInterval:60*1e3,VideoBitrateDefault:1e6,AudioBitrateDefault:68e3,gopSize:90,sampleRate:48e3,channel:2,audioEncoderPath:"https://lf-unpkg.volccdn.com/obj/vcloudfe/sdk/Web_push/1.0.1/1735619140327/pcm2aac.js",audioEncoderWasmPath:"https://lf-unpkg.volccdn.com/obj/vcloudfe/sdk/Web_push/1.0.2/1735619208418/pcm2aac.wasm",ignoreRelPublish:!1},T=new E("RTMP_AudioEncoder");class j{constructor(t){this._encodedFrameCount=0,this._ready=!1,this._lastFrame=null,this._aacOutput=(e,s)=>{const r=this._module.HEAPU8.subarray(e,e+s);if(!this._lastFrame)return;this._encodedFrameCount++;const{props:o}=this._lastFrame,_={buffer:new Uint8Array(r),props:{timestamp:parseInt(o.timestamp/1e3),originTs:parseInt(o.timestamp/1e3)}};this._core.emit(l.OnAudioEncoded,_)},this._core=t}async init(){const t=await fetch(A.audioEncoderPath).then(_=>_.text());new Function(`self.exports={};${t}`)();const e=self.exports.m;let s,r;const o=new Promise((_,c)=>{r=_,s=c});return e({instantiateWasm:function(_,c){fetch(A.audioEncoderWasmPath).then(u=>u.arrayBuffer()).then(u=>WebAssembly.instantiate(u,_)).then(function(u){return c(u.instance)}).then(()=>{r(),T.log("aac module inited")}).catch(u=>{s(u)})}}).then(_=>{const c=_.addFunction(this._aacOutput,"vii");_._init_callback(c),this._module=_}).catch(s),o}rnnoise(t){var s;const e=t.length;for(let r=0;r<e;r++)t[r]=t[r]*32768;(s=this._rnnoiseModule)==null||s.processFrame(t);for(let r=0;r<e;r++)t[r]=t[r]/32768}updateConfigure(){this._module._flush(),this._module._free_encoder(),this._ready=!1}encode(t){if(!this._ready){const o=this._start_encoder();if(o<0)throw new Error(`init aac encoder error, code:${o}`)}this._lastFrame=t;const e=t.buffer.buffer,s=this._module._malloc(e.byteLength);this._module.HEAPU8.subarray(s,s+e.byteLength).set(new Uint8Array(e));const r=this._module._encode_one_frame(s);if(r<0)throw new Error(`encode aac frame error, code:${r}`)}_start_encoder(){const t=this._core.getSetting(),e=this._module._init_encoder(t.sampleRate,t.channel,t.audioBitrate);if(e<0)return e;this._ready=!0,T.log(`init encoder: sampleRate=${t.sampleRate}, channel:${t.channel}, bitrate:${t.audioBitrate}`)}destroy(){var t;(t=this._module)==null||t._free_encoder()}}const P=1024;class M{constructor(){this._queue=[],this._sampleCount=0}compose(t){if(this._queue.push(t),this._sampleCount+=t.data.audioData.numberOfFrames,this._sampleCount>=P)return this._doCompose()}_doCompose(){const t=new Float32Array(P);let e=0,s=P;const r=this._queue[0];for(;;){const o=this._queue[0];if(!o)break;const _=Math.min(s,o.data.audioData.numberOfFrames-o.offset,480),c=o.data.buffer.slice(o.offset,o.offset+_);if(o.offset+=_,o.offset>=o.data.audioData.numberOfFrames&&this._queue.shift(),s-=_,this._sampleCount-=_,t.set(c,e),e+=_,s<=0)break}return{buffer:t,props:{timestamp:r.data.audioData.timestamp,sampleRate:r.data.audioData.sampleRate,numberOfChannels:r.data.audioData.numberOfChannels}}}}var y=(i=>(i[i.RTMP_INIT_FAIL=3e3]="RTMP_INIT_FAIL",i[i.AUDIO_ENCODER_INIT_FAIL=3001]="AUDIO_ENCODER_INIT_FAIL",i[i.AUDIO_RRNOISE_INIT_FAIL=3002]="AUDIO_RRNOISE_INIT_FAIL",i[i.AUDIO_ENCODE_FAIL=3003]="AUDIO_ENCODE_FAIL",i[i.VIDEO_ENCODE_CONFIGURE_FAIL=3004]="VIDEO_ENCODE_CONFIGURE_FAIL",i[i.VIDEO_ENCODE_FAIL=3005]="VIDEO_ENCODE_FAIL",i[i.WTP_OPEN_FAIL=3006]="WTP_OPEN_FAIL",i[i.WTP_CONNECT_FAIL=3007]="WTP_CONNECT_FAIL",i[i.WORKER_ERROR=3008]="WORKER_ERROR",i))(y||{});class W extends Error{constructor(t,e,s){super(),this.code=t,this.message=e,s&&(this.ext=s),this.toJson=()=>({code:this.code,message:this.message,ext:this.ext})}}function b(i,t,e){return new W(i,t,e)}class G{constructor(t){this._audioFrameQueue=new M,this.encode=e=>{const s=new Float32Array(e.numberOfFrames);e.copyTo(s,{planeIndex:0,frameOffset:0,frameCount:e.numberOfFrames});const r=this._audioFrameQueue.compose({offset:0,data:{audioData:e,buffer:s}});if(r)try{this._encoder.encode(r)}catch(o){this._core.emit(O.OnError,b(y.AUDIO_ENCODE_FAIL,o.message))}},this._core=t,this._encoder=new j(t)}async init(){try{await this._encoder.init()}catch(t){throw b(y.AUDIO_ENCODER_INIT_FAIL,t.message)}}setConfiguration(t){const e=Object.assign({},this._core.getSetting(),{audioBitrate:t});this._core.updateSetting(e),this._encoder.updateConfigure()}destroy(){this._encoder.destroy()}}const x=new E("RTMP_VEncoder");class J{constructor(t){this._encoder=null,this._queue=[],this._encodeTimer=0,this._loopEncodeTimer=0,this._frameIndex=0,this._gopSize=0,this._encodedFrameCount=0,this._lastFrame=null,this._startTimer=()=>{this._clearEncodeTimer(),this._encodeTimer=setInterval(()=>{const e=this._queue.shift();if(!(!e||!this._encoder||this._encoder.state==="closed"))try{this._encoder.encode(e,{keyFrame:this._frameIndex%this._gopSize===0}),this._frameIndex++,this._lastFrame&&this._lastFrame.close(),this._lastFrame=e}catch(s){x.log("encode frame error",s)}},5)},this._core=t}configurate(t){return this._gopSize=t.gopSize,this._encoder?this.flush().then(()=>this._configure(t)):this._configure(t)}_configure(t){return this._clearEncodeTimer(),x.log("start config encoder",t),VideoEncoder.isConfigSupported(t).then(e=>{if(!e.supported)throw new Error(`VideoEncoder not support config, ${JSON.stringify(t)}`);this._encoder=new VideoEncoder({output:(s,r)=>{const o=new Uint8Array(s.byteLength);s.copyTo(o),this._emitFrame(o,s,r)},error:s=>{this._clearEncodeTimer(),this._core.emit(O.OnError,b(y.VIDEO_ENCODE_FAIL,s.message))}}),this._encoder.configure(t),x.log("encoder configured")}).then(this._startTimer).catch(e=>{throw b(y.VIDEO_ENCODE_CONFIGURE_FAIL,e.message)})}_emitFrame(t,e,s){this._encodedFrameCount++,this._core.emit(l.OnVideoEncoded,{buffer:t,props:{byteLength:e.byteLength,duration:e.duration,timestamp:parseInt(e.timestamp/1e3),originTs:parseInt(e.timestamp/1e3),type:e.type},cfg:s.decoderConfig})}_clearEncodeTimer(){clearInterval(this._encodeTimer)}_clearLoopEncodeTimer(){this._loopEncodeTimer&&clearInterval(this._loopEncodeTimer)}flush(){return this._encoder?this._encoder.flush().then(()=>{var t;this._clearEncodeTimer(),(t=this._encoder)==null||t.close(),this._frameIndex=0,this._encoder=null,x.log("encoder flush & closed")}).catch(t=>{console.log("encoder flush & close error:",t)}):Promise.resolve()}encode(t){this._clearLoopEncodeTimer(),this._queue.push(t)}startLoop(t){if(!this._lastFrame)return;const e=Math.floor(1e3/t*1e3);x.log("start encode last frame looped, ",t,"increment:",e),this._loopEncodeTimer=setInterval(()=>{if(!this._lastFrame)return;const s=new VideoFrame(this._lastFrame,{duration:e,timestamp:(this._lastFrame.timestamp||0)+e});this._queue.push(s)},Math.floor(1e3/t))}destroy(){this._queue.forEach(t=>t.close()),this._lastFrame&&this._lastFrame.close(),this._clearEncodeTimer(),this._clearLoopEncodeTimer(),this.flush()}}const Q=new E("RTMP_VideoEncode");class K{constructor(t){this._core=t,this._encoder=new J(t)}async setConfiguration(t={}){const e=Object.assign({},this._core.getSetting(),t),s={width:e.width,height:e.height,displayWidth:e.width,displayHeight:e.height,bitrate:e.videoBitrate,framerate:Math.floor(e.frameRate),codec:e.codec,gopSize:e.gopSize,hardwareAcceleration:e.hardwareAcceleration};this._core.updateSetting(e),Q.log("set Configuration:",s,t);try{await this._encoder.configurate(s)}catch(r){this._core.emit(O.OnError,r)}}encode(t){this._encoder.encode(t)}startLoopEncodeLastFrame(){this._encoder.startLoop(this._core.getSetting().frameRate)}flushEncoder(){this._encoder.flush()}destroy(){this._encoder.destroy()}}const V=new E("RTMP_AVSync");class Z{constructor(t){this._videoFrameGot=!1,this._videoBaseDts=0,this._audioBaseDts=0,this._videoNextDts=0,this._videoLastDts=0,this._audioNextDts=0,this._lastVideoReceived=0,this._core=t}get avExist(){return this._core.getSetting().hasVideo&&this._core.getSetting().hasAudio}get videoRefDuration(){return parseInt(1e3/this._core.getSetting().frameRate)}get audioRefDuration(){return parseInt(1024/this._core.getSetting().sampleRate*1e3)}addVideoFrame(t){this._videoFrameGot||(this._videoFrameGot=!0);const e=t.props;if(Math.abs(this._videoNextDts-e.timestamp-this._videoBaseDts)>1e3){const r=Date.now()-this._lastVideoReceived;this._videoNextDts=this._videoNextDts===this._audioNextDts?this._videoNextDts+this.videoRefDuration:this._audioNextDts||this._videoNextDts+r,this._videoBaseDts=this._videoNextDts-e.timestamp,V.warn(`video stream timestamp breaked! dts:${this._videoNextDts} -> ${e.timestamp}, videoBaseDts=${this._videoBaseDts}, deltaToLastFrame=${r}`)}e.timestamp=e.timestamp+this._videoBaseDts;const s=e.timestamp-this._videoLastDts;return s>100&&V.warn("video frame large gap",s),this._videoLastDts=this._videoNextDts=e.timestamp,V.long&&V.log(`V frame, dts: ${e.timestamp}, originDts:${e.originTs}, videoBaseDts=${this._videoBaseDts}, type=${e.type}, duration=${s}`),this._lastVideoReceived=Date.now(),this._core.emit(l.OnEncodedFrame,I.Video,t),{size:t.buffer.length,duration:s,key:t.props.type==="key"}}addAudioFrame(t){if(this.avExist&&!this._videoFrameGot)return;const e=t.props;return this._audioBaseDts||(this._audioBaseDts=e.timestamp-this._videoNextDts),Math.abs(e.timestamp-this._audioBaseDts-this._audioNextDts)>1e3&&(this._audioBaseDts=this._audioNextDts+this.audioRefDuration-e.timestamp,V.warn(`audio stream timestamp breaked! dts:${this._audioNextDts} -> ${e.timestamp}, audioBaseDts=${this._audioBaseDts}`)),this._audioNextDts=e.timestamp=e.timestamp-this._audioBaseDts,V.long&&V.log(`A frame, dts: ${e.timestamp}, originDts:${e.originTs}`),this._core.emit(l.OnEncodedFrame,I.Audio,t),{size:t.buffer.length,duration:this.audioRefDuration}}}class X{constructor(){this._videoSize=0,this._videoDuration=0,this._videoBitrate=0,this._frameCount=0,this._fps=0,this._videoEncodedCount=0,this._keyCount=0,this._audioSize=0,this._audioDuration=0,this._audioBitrate=0,this._audioEncodedCount=0}get videoStats(){return{sendBitrate:this._videoBitrate,framesPerSecond:this._fps,framesEncoded:this._videoEncodedCount,keyFramesEncoded:this._keyCount}}get audioStats(){return{sendBitrate:this._audioBitrate,framesEncoded:this._audioEncodedCount}}addVideoSample({size:t,duration:e,key:s}){this._videoEncodedCount++,this._videoSize+=t,this._videoDuration+=e,this._frameCount++,s&&this._keyCount++,this._videoDuration>=1e3&&(this._videoBitrate=Math.floor(this._videoSize/this._videoDuration*8e3),this._fps=this._frameCount,this._frameCount=0,this._videoSize=0,this._videoDuration=0)}addAudioSample({size:t,duration:e}){this._audioEncodedCount++,this._audioSize+=t,this._audioDuration+=e,this._audioDuration>=1e3&&(this._audioBitrate=Math.floor(this._audioSize/this._audioDuration*1e3),this._audioSize=0,this._audioDuration=0)}}const Y=new E("RTMP_EncodeController");class ee{constructor(t){this._analyse=new X,this._gotFrame=!1,this._OnVideoCaptured=(e,s)=>{this._gotFrame=!0,this._videoSettingChanged(s)&&(Y.log("video track setting changed!",s),this._core.updateSetting({width:s.width,height:s.height,frameRate:s.frameRate,vDeviceId:s.deviceId}),this._videoEncode.setConfiguration()),this._videoEncode.encode(e)},this._OnVideoCaptureNoOutput=()=>{this._videoEncode.startLoopEncodeLastFrame()},this._OnAudioCaptured=e=>{this._gotFrame=!0,this._audioEncode.encode(e)},this._OnVideoEncoded=e=>{const s=this._avSync.addVideoFrame(e);this._analyse.addVideoSample(s)},this._OnAudioEncoded=e=>{if(!e.buffer.length)return;const s=this._avSync.addAudioFrame(e);s&&this._analyse.addAudioSample(s)},this._OnUpstreamFeedback=e=>{this._videoEncode.setConfiguration(e)},this._OnBitrateChanged=(e,s)=>{this._gotFrame&&(e===I.Video&&this._videoEncode.setConfiguration({videoBitrate:s}),e===I.Audio&&this._audioEncode.setConfiguration(s))},this._core=t,this._audioEncode=new G(t),this._videoEncode=new K(t),this._avSync=new Z(t),this._bindEvents()}getStats(){return{video:this._analyse.videoStats,audio:this._analyse.audioStats}}init(){return this._audioEncode.init()}_bindEvents(){this._core.on(l.OnVideoCaptured,this._OnVideoCaptured),this._core.on(l.OnAudioCaptured,this._OnAudioCaptured),this._core.on(l.OnVideoCaptureNoOutput,this._OnVideoCaptureNoOutput),this._core.on(l.OnVideoEncoded,this._OnVideoEncoded),this._core.on(l.OnAudioEncoded,this._OnAudioEncoded),this._core.on(l.OnUpstreamFeedback,this._OnUpstreamFeedback),this._core.on(l.OnBitrateChanged,this._OnBitrateChanged)}_videoSettingChanged(t){const e=this._core.getSetting();return t.width!==e.width||t.height!==e.height||Math.floor(t.frameRate)!==Math.floor(e.frameRate)||t.deviceId!==e.vDeviceId}destroy(){this._videoEncode.destroy(),this._audioEncode.destroy()}}var L=(i=>(i[i.AUDIO=8]="AUDIO",i[i.VIDEO=9]="VIDEO",i[i.SCRIPT_DATA=18]="SCRIPT_DATA",i))(L||{});const te=10,ie=1,se=7,oe={96e3:0,48e3:3,44100:4,22050:7,16e3:8,8e3:11};function re(i){const t=(i[4]&3)+1;let e;const s=[],r=[];let o=6;const _=i[5]&31;let c;for(let n=0;n<_;n++){if(c=i[o]<<8|i[o+1],o+=2,!c)continue;const h=i.subarray(o,o+c);o+=c,s.push(h)}const u=i[o];o++;let a;for(let n=0;n<u;n++)a=i[o]<<8|i[o+1],o+=2,a&&(r.push(i.subarray(o,o+a)),o+=a);return{sps:e,spsArr:s,ppsArr:r,nalUnitSize:t}}class ne{constructor(){this._cfg={hasVideo:!1,hasAudio:!1,sampleRate:48e3,channelCount:1},this._hasAudioSeqHeader=!1,this._hasVideoSeqHeader=!1}setConfig(t){this._cfg=Object.assign(this._cfg,t)}genHeader(){const t=[70,76,86,1,(this._cfg.hasAudio?1:0)<<2|(this._cfg.hasVideo?1:0),0,0,0,9,0,0,0,0];return new Uint8Array(t)}genSeqTag(t,e){let s;t===8?(s=this._genAudioTagPaylod(0,e),this._hasAudioSeqHeader=!0):(s=this._genVideoTagPayload(0,e),this._hasVideoSeqHeader=!0);const r=this._genTagHeader(t,s.length,e.props.timestamp),o=r.length+s.length;return S([r,s,new Uint8Array([o>>>24,o>>>16,o>>>8,o])])}genFrameTag(t,e){let s;t===8?s=this._genAudioTagPaylod(1,e):s=this._genVideoTagPayload(1,e);const r=this._genTagHeader(t,s.length,e.props.timestamp),o=r.length+s.length;return S([r,s,new Uint8Array([o>>>24,o>>>16,o>>>8,o])])}_genTagHeader(t,e,s){return new Uint8Array([t,e>>>16,e>>>8,e,s>>>16,s>>>8,s,s>>>24,0,0,0])}_genAudioTagPaylod(t,e){return S(t===0?[this._genAudioTagHeader(),this._genAudioSequenceHeader()]:[this._genAudioTagHeader(),this._genAudioData(e)])}_genAudioTagHeader(){return new Uint8Array([te<<4|12|ie<<1|this._cfg.channelCount-1])}_genAudioSequenceHeader(){const t=4096|oe[this._cfg.sampleRate]<<7|this._cfg.channelCount<<3;return new Uint8Array([0,t>>8,t])}_genAudioData(t){const e=new Uint8Array(1+t.buffer.length);return e.set([1],0),e.set(t.buffer,1),e}_genVideoTagPayload(t,e){return S(t===0?[this._genVideoTagHeader(e),this._genVideoSequenceHeader(e)]:[this._genVideoTagHeader(e),this._genVideoData(e)])}_genVideoTagHeader(t){return new Uint8Array([(t.props.type==="key"?1:2)<<4|se,this._hasVideoSeqHeader?1:0,0,0,0])}_genVideoSequenceHeader(t){return new Uint8Array(t.cfg.description)}_genVideoData(t){if(t.props.type==="delta")return t.buffer;const e=re(new Uint8Array(t.cfg.description)),s=e.spsArr[0].length,r=e.ppsArr[0].length;return S([new Uint8Array([0,0,s>>8,s%256]),e.spsArr[0],new Uint8Array([0,0,r>>8,r%256]),e.ppsArr[0],t.buffer])}}const ae=new E("RTMP_Packet");class de{constructor(t){this._firstFrame=!0,this._flv=new ne,this._OnEncodedFrame=(e,s)=>{if(this._firstFrame){const o=this._core.getSetting();this._flv.setConfig({hasVideo:o.hasVideo,hasAudio:o.hasAudio,sampleRate:o.sampleRate,channelCount:o.channel});const _=this._flv.genHeader();if(this._core.emit(l.OnPacketed,_),o.hasVideo){const c=this._flv.genSeqTag(L.VIDEO,s);this._core.emit(l.OnPacketed,c)}if(o.hasAudio){const c=this._flv.genSeqTag(L.AUDIO,s);this._core.emit(l.OnPacketed,c)}this._firstFrame=!1,ae.log("first frame encoded & packed")}const r=this._flv.genFrameTag(e==="video"?L.VIDEO:L.AUDIO,s);this._core.emit(l.OnPacketed,r,s.props.type==="key")},this._core=t,this._bindEvents()}_bindEvents(){this._core.on(l.OnEncodedFrame,this._OnEncodedFrame)}destroy(){}}class he{constructor(){this._lastDot=0,this._totalSize=0,this._speed=[]}addSample(t){this._lastDot||(this._lastDot=Date.now()),this._totalSize+=t;const e=Date.now()-this._lastDot;e>=500&&(this._addSpeedSample(this._totalSize/e*8e3),this._totalSize=0,this._lastDot=Date.now())}_addSpeedSample(t){this._speed.push(t),this._speed=this._speed.slice(-6)}reset(){this._speed=[]}getUpSpeed(){return this._speed.length?parseInt(this._speed.reduce((t,e)=>t+=e,0)/this._speed.length):0}}const D=new E("RTMP_Wtp");class ce{constructor(t){this._queue=[],this._url="",this._connectClosed=!1,this._upSpeed=new he,this._transport=null,this._writer=null,this._inWriting=!1,this._inAdjustEncode=!1,this._increaseTimer=0,this._firstFramePushed=!1,this._core=t,this._bindEvents()}get sendSpeed(){return this._upSpeed.getUpSpeed()}getStats(){var t;return(t=this._transport)==null?void 0:t.getStats()}_bindEvents(){this._core.on(l.OnPacketed,(t,e=!1)=>{this._checkDecreaseBitrate(),this._checkDeleteCache(e),this._queue.push(t),this._inWriting||this._write()})}_checkDecreaseBitrate(){if(this._inAdjustEncode)return;const t=this._upSpeed.getUpSpeed();if(!t||this._queue.length<A.MaxCachedFrameSize)return;D.log(`up speed: ${t} low, ajust encode setting`);const e=this._core.getSetting();this._core.emit(l.OnUpstreamFeedback,{videoBitrate:t*A.RealSpeedPercent,width:e.width,height:e.height,frameRate:e.frameRate}),this._inAdjustEncode=!0,this._checkIncreaseBitrate()}_checkIncreaseBitrate(){D.log("add timer to check uplink speed increased"),clearInterval(this._increaseTimer),this._increaseTimer=setTimeout(()=>{const t=this._core.getSetting();D.log(`set encode bitrate to specified ${t.originVideoBitrate}`),this._core.emit(l.OnUpstreamFeedback,{videoBitrate:t.originVideoBitrate,width:t.width,height:t.height,frameRate:t.frameRate}),this._inAdjustEncode=!0},A.UplinkBitrateCheckInterval)}_checkDeleteCache(t){this._inAdjustEncode&&t&&(D.log(`ajust encode setting finish, delete cached ${this._queue.length} frame`),this._queue=[],this._upSpeed.reset(),this._inAdjustEncode=!1)}async start(t){this._url=t;try{await this._connect()}catch(e){throw b(y.WTP_OPEN_FAIL,e.message)}}async _connect(){const t=new WebTransport(this._url);let e;t.closed.then(()=>{D.log("webtransport closed")}).catch(r=>{e=r.message,D.log("webtransport closed due to",r)}).finally(()=>{this._connectClosed=!0,this._core.emit(O.OnConnectClosed,e),this._core.emit(O.OnError,b(y.WTP_CONNECT_FAIL,e))}),await t.ready,this._transport=t;const s=await t.createBidirectionalStream();this._writer=s.writable.getWriter(),this._write(),D.log("transport opend")}async _write(){var e;if(!this._writer)return;this._inWriting=!0;const t=this._queue.shift();if(!t){this._inWriting=!1;return}await((e=this._writer)==null?void 0:e.write(t)),this._firstFramePushed||(this._firstFramePushed=!0,this._core.emit(O.OnFirstFramePushed),D.log("first frame pushed")),this._upSpeed.addSample(t.length);try{await this._write()}catch(s){D.log("writer error:",s)}}getFile(){return S(this._queue)}destroy(){var t,e;clearTimeout(this._increaseTimer),this._connectClosed||(t=this._writer)==null||t.close(),this._writer=null,(e=this._transport)==null||e.close(),this._transport=null}}const ue=new E("LiveRTMP");class _e extends H{constructor(){super(),this._ts=0,this._setting={codec:A.codec,hardwareAcceleration:"prefer-hardware",width:-1,height:-1,frameRate:-1,sampleRate:A.sampleRate,channel:A.channel,gopSize:A.gopSize,videoBitrate:A.VideoBitrateDefault,originVideoBitrate:A.VideoBitrateDefault,audioBitrate:A.AudioBitrateDefault,hasAudio:!1,hasVideo:!1,vDeviceId:"",aDeviceId:""},this._encode=new ee(this),this._packet=new de(this),this._transport=new ce(this)}async checkVideoHardwareAcceleration(){const t=["prefer-hardware","prefer-software","no-preference"],e=this.getSetting(),s={codec:e.codec,width:1280,height:720,framerate:15,bitrate:e.videoBitrate};for(const r of t)try{if((await VideoEncoder.isConfigSupported({...s,hardwareAcceleration:r})).supported)return this.updateSetting({hardwareAcceleration:r,originVideoBitrate:e.originVideoBitrate}),Promise.resolve()}catch{throw b(y.VIDEO_ENCODE_CONFIGURE_FAIL,`VideoEncoder not support hardwareAcceleration, ${JSON.stringify({...s,hardwareAcceleration:r})}`)}throw b(y.VIDEO_ENCODE_CONFIGURE_FAIL,"VideoEncoder not support hardwareAcceleration")}async ready(){await Promise.all([this.checkVideoHardwareAcceleration(),this._encode.init()])}getSetting(){return this._setting}updateSetting(t){this._setting=Object.assign({},this._setting,t)}videoFrameCaptured(t,e){this.emit(l.OnVideoCaptured,t,e)}audioFrameCaptured(t,e){this.emit(l.OnAudioCaptured,t,e)}startMockVideoEncode(){this.emit(l.OnVideoCaptureNoOutput)}adjustBitrate(t,e){t===I.Video&&this.updateSetting({videoBitrate:e,originVideoBitrate:e}),t===I.Audio&&this.updateSetting({audioBitrate:e}),this.emit(l.OnBitrateChanged,t,e)}avExist(t,e){this._setting.hasVideo=t,this._setting.hasAudio=e}publish(t){return this._transport.start(t)}setEncodeCapacity(t){this._setting=Object.assign({},this._setting,t)}getStats(){return{video:{...this._encode.getStats().video,sendSpeed:this._transport.sendSpeed,codec:this._setting.codec,frameWidth:this._setting.width,frameHeight:this._setting.height,gopSize:this._setting.gopSize},audio:{...this._encode.getStats().audio,codec:"aac",channels:this._setting.channel,sampleRate:this._setting.sampleRate}}}destroy(){ue.log("destroy"),this._encode.destroy(),this._packet.destroy(),this._transport.destroy()}down(){return this._transport.getFile()}}self.constructor.name!=="Window"&&le();function le(){let i={};self.addEventListener("message",async t=>{switch(t.data.type){case v.Init:{const{options:e}=t.data;e.logEnable&&(E.enable=!0),e.logEnableLong&&(E.enableLong=!0),i=new _e,i.on(O.OnError,s=>{self.postMessage({type:w.Error,data:s.toJson()})}),i.on(O.OnConnectClosed,()=>{self.postMessage({type:w.Close})}),i.on(O.OnFirstFramePushed,()=>{self.postMessage({type:w.FirstFramePushed})});try{await i.ready(),self.postMessage({type:w.Ready})}catch(s){self.postMessage({type:w.Error,data:s.toJson()})}}break;case v.AvExist:{const{hasAudio:e,hasVideo:s}=t.data;i.avExist(s,e)}break;case v.VideoFrame:{const{frame:e,setting:s}=t.data;i.videoFrameCaptured(e,s)}break;case v.MockVideoEncode:i.startMockVideoEncode();break;case v.AudioFrame:{const{frame:e,setting:s}=t.data;i.audioFrameCaptured(e,s)}break;case v.AdjustBitrate:{const{kind:e,bitrate:s}=t.data;i.adjustBitrate(e,s)}break;case v.Publish:{const{url:e}=t.data;try{await i.publish(e)}catch(s){self.postMessage({type:w.Error,data:s.toJson()})}}break;case v.GetStats:self.postMessage({type:w.STATS,data:i.getStats()});break;case v.EncodeConfig:{i.setEncodeCapacity(t.data.cfg);break}case v.Download:{const e=i.down();self.postMessage({type:w.Flvfile,buffer:e},[e.buffer])}break;case v.UnPublish:{i.destroy();break}}})}})();\n',Ii=typeof self<"u"&&self.Blob&&new Blob([Oi],{type:"text/javascript;charset=utf-8"});function Bu(r){let e;try{if(e=Ii&&(self.URL||self.webkitURL).createObjectURL(Ii),!e)throw"";const t=new Worker(e,{name:r==null?void 0:r.name});return t.addEventListener("error",()=>{(self.URL||self.webkitURL).revokeObjectURL(e)}),t}catch{return new Worker("data:text/javascript;charset=utf-8,"+encodeURIComponent(Oi),{name:r==null?void 0:r.name})}finally{e&&(self.URL||self.webkitURL).revokeObjectURL(e)}}try{se.enable=location.href.indexOf("rtmpdebug")!==-1,se.enableLong=location.href.indexOf("rtmpdebug=long")!==-1}catch{}const Ke=new se("Bridge");class Di extends Vu{constructor(){super(),this._worker=null,this._audioMsTrack=null,this._videoMsTrack=null,this._capture=new $u(this)}static isSupported(){return typeof WebTransport<"u"&&typeof MediaStreamTrackProcessor<"u"&&typeof MediaStreamTrackGenerator<"u"&&typeof VideoEncoder<"u"}get audioMsTrack(){return this._audioMsTrack}get videoMsTrack(){return this._videoMsTrack}async ready(){var n,a;let e,t;const i=new Promise((o,u)=>{e=o,t=u}),s=o=>{var u;switch((u=this._worker)==null||u.removeEventListener("message",s),o.data.type){case he.Error:t(o.data.data);break;default:this._bindWorkerEvent(),Ke.log("rtmp ready!"),e(!0)}};try{this._worker=new Bu}catch(o){t(wi(Bt.RTMP_INIT_FAIL,o.message))}return(n=this._worker)==null||n.postMessage({type:V.Init,options:{logEnable:se.enable,logEnableLong:se.enableLong}}),(a=this._worker)==null||a.addEventListener("message",s),i}_bindWorkerEvent(){var e,t;(e=this._worker)==null||e.addEventListener("message",i=>{switch(i.data.type){case he.Error:Ke.table(i.data.data),this.emit(ue.OnError,i.data.data);break;case he.Flvfile:ju(i.data.buffer);break;case he.FirstFramePushed:this.emit(ue.OnFirstFramePushed);break;case he.Close:this.emit(ue.OnConnectClosed),this.destroy();break}}),(t=this._worker)==null||t.addEventListener("error",i=>{this.emit(ue.OnError,wi(Bt.WORKER_ERROR,i.message))})}addTrack(e){e.kind===ie.Video&&(this._videoMsTrack=e),e.kind===ie.Audio&&(this._audioMsTrack=e),this._setAVExist(!!this._videoMsTrack,!!this._audioMsTrack)}replaceTrack(e,t){e===ie.Video&&(this._videoMsTrack=t),e===ie.Audio&&(this._audioMsTrack=t),this._setAVExist(!!this._videoMsTrack,!!this._audioMsTrack),this._capture.restartCapture(e)}async getStats(){var n,a;let e,t;const i=new Promise((o,u)=>{e=o,t=u});this._worker||setTimeout(()=>{t()},0);const s=o=>{var u;switch(o.data.type){case he.STATS:e(o.data.data),(u=this._worker)==null||u.removeEventListener("message",s);break}};return(n=this._worker)==null||n.addEventListener("message",s),(a=this._worker)==null||a.postMessage({type:V.GetStats}),i}_postVideoFrame(e,t){var i;(i=this._worker)==null||i.postMessage({type:V.VideoFrame,frame:e,setting:t},[e])}_postMockVideoEncodeFlag(){var e;(e=this._worker)==null||e.postMessage({type:V.MockVideoEncode})}_setAVExist(e,t){var i;(i=this._worker)==null||i.postMessage({type:V.AvExist,hasVideo:e,hasAudio:t})}_postAudioFrame(e,t){var i;(i=this._worker)==null||i.postMessage({type:V.AudioFrame,frame:e,setting:t},[e])}setEncodeCapacity(e){var t;(t=this._worker)==null||t.postMessage({type:V.EncodeConfig,cfg:e})}adjustBitrate(e,t){var i;(i=this._worker)==null||i.postMessage({type:V.AdjustBitrate,kind:e,bitrate:t})}publish(e){var t;Ke.log("start capture & connect"),this._capture.start(),(t=this._worker)==null||t.postMessage({type:V.Publish,url:e})}unpublish(){var e;this._capture.destroy(),(e=this._worker)==null||e.postMessage({type:V.UnPublish})}destroy(){var e;Ke.log("destroy capture & rtmp worker"),this._capture.destroy(),(e=this._worker)==null||e.terminate(),this._worker=null}download(){var e;(e=this._worker)==null||e.postMessage({type:V.Download})}}function ju(r){const e=document.createElement("a");e.href=URL.createObjectURL(new Blob([r])),e.download=Date.now()+".flv",e.click()}const Mi=new de("RTMPConnect");class zu{constructor(e,t,i,s){this._opts=void 0,this._isPushing=!1,this._url=e,this._opts=t,this._onError=i,this._OnSuccess=s,this._rtmp=new Di,this._bindEvents()}get isPushing(){return this._isPushing}get pushUrl(){return this._url}get sessionId(){return 0}_bindEvents(){this._rtmp.on(ue.OnError,e=>{this._isPushing=!1,this._onError(e)}),this._rtmp.on(ue.OnFirstFramePushed,()=>{this._isPushing=!0,this._OnSuccess()})}async publish(e,t,i){await this._rtmp.ready(),i&&this._rtmp.setEncodeCapacity(i),e.filter(Boolean).forEach(s=>this._rtmp.addTrack(s)),t[0]&&this._rtmp.adjustBitrate(ie.Audio,t[0]),t[1]&&this._rtmp.adjustBitrate(ie.Video,t[1]),this._rtmp.publish(this._url)}updatePublish(e,t){Mi.log(`replace track to ${e==null?void 0:e.label}`),this._rtmp.replaceTrack(t,e)}applyBitrate(e,t){this._rtmp.adjustBitrate(t,e)}async getStats(){return this._rtmp.getStats()}async getStatsSnapshoot(){return this._rtmp.getStats()}unpublish(){Mi.warn("unpublish"),this._rtmp.unpublish(),this._isPushing=!1}}const Gu=new de("PushController");class Hu extends Ti{constructor(e,{config:t,streamConsumeController:i}){super(e),this._connect=null,this._pushMode="rtm",this._pushConfig={timeout:5e3,retryCount:1,retryDelay:1e3},this._audioBitrate=ve(or,"audio").bitrate,this._videoBitrate=ve(nr,"video").bitrate,this.handleAudioStreamChange=s=>{this.updatePush({audioTrack:s.audioTrack})},this.handleVideoStreamChange=s=>{this.updatePush({videoTrack:s.videoTrack})},this._OnRTMPSuccess=()=>{this._streamConsumeController.emit(A.PushStart)},this._OnRTMPError=s=>{const n=new Ie(N.PUBLISH_FAILED,`code:${s.code}, message: ${s.message}`);this._streamConsumeController.emit(A.PushError,n),this.unpublish()},this._OnRtcStateChange=s=>{if(s==="failed"){this.unpublish();const n=new Ie(N.PUSH_CONNECT_FAILED,"pc disconnect");this._streamConsumeController.emit(A.PushError,n)}s==="connected"&&this._streamConsumeController.emit(A.PushStart),this._streamConsumeController.emit(A.RTCConnectStateChanged,s)},this._pushMode=(t==null?void 0:t.mode)||"rtm",this._streamConsumeController=i,t&&(this._pushConfig=t)}get isPushing(){var e;return!!((e=this._connect)!=null&&e.isPushing)}get pushUrl(){var e;return((e=this._connect)==null?void 0:e.pushUrl)||""}get sessionId(){var e;return((e=this._connect)==null?void 0:e.sessionId)||0}start(){this.bindComposedStreamEvent()}stop(){this.unbindComposedStreamEvent()}setPushConfig(e){e&&(this._pushConfig=e)}async getStats(e=2e3){var t;return(t=this._connect)==null?void 0:t.getStatsSnapshoot(e)}async startPush(e,t){if(!e)throw new Error("lack publish url");if(this._connect)return;this.start();const i=this._composedStream.videoTrack,s=this._composedStream.audioTrack;if(!i&&!s)return;let n;this._pushMode==="rtm"?n=new Lu(e,this._pushConfig,this._OnRtcStateChange):n=new zu(e,this._pushConfig,this._OnRTMPError,this._OnRTMPSuccess),this._connect=n;try{await n.publish([s,i],[this._audioBitrate,this._videoBitrate],t)}catch(a){Gu.groupEnd(),n.unpublish();const o=new Ie(N.PUBLISH_FAILED,a.message,a);this._streamConsumeController.emit(A.PushError,o)}}async updatePush({videoTrack:e,audioTrack:t}){if(this._connect)try{const i=[];e&&i.push(()=>{var s;return(s=this._connect)==null?void 0:s.updatePublish(e,"video")}),t&&i.push(()=>{var s;return(s=this._connect)==null?void 0:s.updatePublish(t,"audio")}),await Promise.all(i.map(s=>s()))}catch(i){const s=new Ie(N.UPDATE_PUBLISH_FAILED,`${i.name}, code:${i.code}`);this._streamConsumeController.emit(A.PushError,s)}}unpublish(){var e;(e=this._connect)==null||e.unpublish(),this._connect=null,this._streamConsumeController.emit(A.PushStop)}async destroy(){this._connect&&await this.unpublish(),this.unbindComposedStreamEvent()}setPushMode(e){this._pushMode=e}setBitrate(e,t,i){var s;t==="video"?this._videoBitrate=e:this._audioBitrate=e,(s=this._connect)==null||s.applyBitrate(e,t,i)}get pushMode(){return this._pushMode}}class qu extends Q{constructor(e){super(),this._previewConsumer=new ku(e.getComposedStream(),{streamConsumeController:this}),this._pushConsumer=new Hu(e.getComposedStream(),{streamConsumeController:this})}startPreview(){this._previewConsumer.startPreview()}setRenderView(e){this._previewConsumer.setRenderView(e)}async startPush(e,t){return this._pushConsumer.startPush(e,t)}async stopPush(){return this._pushConsumer.unpublish()}setPushMode(e){this._pushConsumer.setPushMode(e)}isPushing(){return this._pushConsumer.isPushing}getStats(){return this._pushConsumer.getStats()}getPreviewElement(){return this._previewConsumer.getPreviewElement()}stopPreview(){this._previewConsumer.stopPreview()}setBitrate(e,t,i){this._pushConsumer.setBitrate(e,t,i)}setPushConfig(e){this._pushConsumer.setPushConfig(e)}get pushMode(){return this._pushConsumer.pushMode}async destroy(){await this._pushConsumer.destroy(),this._previewConsumer.destroy()}}const Wu=()=>typeof window>"u",H={},Je=async r=>{const e=new RTCPeerConnection({sdpSemantics:"unified-plan"});e.addTransceiver("video",{direction:r});const t=await e.createOffer();return e.close(),t.sdp.toLowerCase()};function Li(r){const e=r.split(`
59
- `);let t=!1;for(const i of e)if(i.includes("level-asymmetry-allowed=1")&&i.includes("packetization-mode=1")&&i.includes("profile-level-id=42e0")){t=!0;break}if(t){const i=navigator.userAgent.toLowerCase();let s=!1;const n=[/miuibrowser/,/70.*HeyTapBrowser/i];for(const a of n)a.test(i)&&(s=!0);return!s}return!1}const Xu=async()=>{let r=await Je("sendonly");return navigator.userAgent.includes("VivoBrowser")&&(r=await Je("sendonly")),H.h264encode=Li(r),H.vp8encode=r.indexOf("vp8")>-1,H},Ku=async()=>{let r=await Je("recvonly");return navigator.userAgent.includes("VivoBrowser")&&(r=await Je("recvonly")),H.h264decode=Li(r),H.vp8decode=r.indexOf("vp8")>-1,H},Ju=async()=>{if(typeof H.h264encode>"u")try{await Xu()}catch{return!1}return H.h264encode||!1},Yu=async()=>{if(typeof H.h264decode>"u")try{await Ku()}catch{return!1}return H.h264decode||!1};class Zu{constructor(){this.onError=(e,t,i)=>{},this.onWarning=e=>{},this.onCaptureFirstAudioFrame=()=>{},this.onCaptureFirstVideoFrame=()=>{},this.onPushStatusUpdate=(e,t)=>{},this.onMicrophoneChanged=e=>{},this.onCameraChanged=e=>{},this.onCaptureInterrupted=e=>{},this.onPushStart=()=>{},this.onPushStop=()=>{},this.onStopCapture=e=>{}}}const Qu=new Zu;let Fi=!0,Ni=!0;function Ye(r,e,t){const i=r.match(e);return i&&i.length>=t&&parseInt(i[t],10)}function pe(r,e,t){if(!r.RTCPeerConnection)return;const i=r.RTCPeerConnection.prototype,s=i.addEventListener;i.addEventListener=function(a,o){if(a!==e)return s.apply(this,arguments);const u=d=>{const c=t(d);c&&(o.handleEvent?o.handleEvent(c):o(c))};return this._eventMap=this._eventMap||{},this._eventMap[e]||(this._eventMap[e]=new Map),this._eventMap[e].set(o,u),s.apply(this,[a,u])};const n=i.removeEventListener;i.removeEventListener=function(a,o){if(a!==e||!this._eventMap||!this._eventMap[e])return n.apply(this,arguments);if(!this._eventMap[e].has(o))return n.apply(this,arguments);const u=this._eventMap[e].get(o);return this._eventMap[e].delete(o),this._eventMap[e].size===0&&delete this._eventMap[e],Object.keys(this._eventMap).length===0&&delete this._eventMap,n.apply(this,[a,u])},Object.defineProperty(i,"on"+e,{get(){return this["_on"+e]},set(a){this["_on"+e]&&(this.removeEventListener(e,this["_on"+e]),delete this["_on"+e]),a&&this.addEventListener(e,this["_on"+e]=a)},enumerable:!0,configurable:!0})}function eh(r){return typeof r!="boolean"?new Error("Argument type: "+typeof r+". Please use a boolean."):(Fi=r,r?"adapter.js logging disabled":"adapter.js logging enabled")}function th(r){return typeof r!="boolean"?new Error("Argument type: "+typeof r+". Please use a boolean."):(Ni=!r,"adapter.js deprecation warnings "+(r?"disabled":"enabled"))}function Vi(){if(typeof window=="object"){if(Fi)return;typeof console<"u"&&typeof console.log=="function"&&console.log.apply(console,arguments)}}function jt(r,e){Ni&&console.warn(r+" is deprecated, please use "+e+" instead.")}function rh(r){const e={browser:null,version:null};if(typeof r>"u"||!r.navigator||!r.navigator.userAgent)return e.browser="Not a browser.",e;const{navigator:t}=r;if(t.userAgentData&&t.userAgentData.brands){const i=t.userAgentData.brands.find(s=>s.brand==="Chromium");if(i)return{browser:"chrome",version:parseInt(i.version,10)}}if(t.mozGetUserMedia)e.browser="firefox",e.version=Ye(t.userAgent,/Firefox\/(\d+)\./,1);else if(t.webkitGetUserMedia||r.isSecureContext===!1&&r.webkitRTCPeerConnection)e.browser="chrome",e.version=Ye(t.userAgent,/Chrom(e|ium)\/(\d+)\./,2);else if(r.RTCPeerConnection&&t.userAgent.match(/AppleWebKit\/(\d+)\./))e.browser="safari",e.version=Ye(t.userAgent,/AppleWebKit\/(\d+)\./,1),e.supportsUnifiedPlan=r.RTCRtpTransceiver&&"currentDirection"in r.RTCRtpTransceiver.prototype;else return e.browser="Not a supported browser.",e;return e}function Ui(r){return Object.prototype.toString.call(r)==="[object Object]"}function $i(r){return Ui(r)?Object.keys(r).reduce(function(e,t){const i=Ui(r[t]),s=i?$i(r[t]):r[t],n=i&&!Object.keys(s).length;return s===void 0||n?e:Object.assign(e,{[t]:s})},{}):r}function zt(r,e,t){!e||t.has(e.id)||(t.set(e.id,e),Object.keys(e).forEach(i=>{i.endsWith("Id")?zt(r,r.get(e[i]),t):i.endsWith("Ids")&&e[i].forEach(s=>{zt(r,r.get(s),t)})}))}function Bi(r,e,t){const i=t?"outbound-rtp":"inbound-rtp",s=new Map;if(e===null)return s;const n=[];return r.forEach(a=>{a.type==="track"&&a.trackIdentifier===e.id&&n.push(a)}),n.forEach(a=>{r.forEach(o=>{o.type===i&&o.trackId===a.id&&zt(r,o,s)})}),s}const ji=Vi;function zi(r,e){const t=r&&r.navigator;if(!t.mediaDevices)return;const i=function(o){if(typeof o!="object"||o.mandatory||o.optional)return o;const u={};return Object.keys(o).forEach(d=>{if(d==="require"||d==="advanced"||d==="mediaSource")return;const c=typeof o[d]=="object"?o[d]:{ideal:o[d]};c.exact!==void 0&&typeof c.exact=="number"&&(c.min=c.max=c.exact);const h=function(p,l){return p?p+l.charAt(0).toUpperCase()+l.slice(1):l==="deviceId"?"sourceId":l};if(c.ideal!==void 0){u.optional=u.optional||[];let p={};typeof c.ideal=="number"?(p[h("min",d)]=c.ideal,u.optional.push(p),p={},p[h("max",d)]=c.ideal,u.optional.push(p)):(p[h("",d)]=c.ideal,u.optional.push(p))}c.exact!==void 0&&typeof c.exact!="number"?(u.mandatory=u.mandatory||{},u.mandatory[h("",d)]=c.exact):["min","max"].forEach(p=>{c[p]!==void 0&&(u.mandatory=u.mandatory||{},u.mandatory[h(p,d)]=c[p])})}),o.advanced&&(u.optional=(u.optional||[]).concat(o.advanced)),u},s=function(o,u){if(e.version>=61)return u(o);if(o=JSON.parse(JSON.stringify(o)),o&&typeof o.audio=="object"){const d=function(c,h,p){h in c&&!(p in c)&&(c[p]=c[h],delete c[h])};o=JSON.parse(JSON.stringify(o)),d(o.audio,"autoGainControl","googAutoGainControl"),d(o.audio,"noiseSuppression","googNoiseSuppression"),o.audio=i(o.audio)}if(o&&typeof o.video=="object"){let d=o.video.facingMode;d=d&&(typeof d=="object"?d:{ideal:d});const c=e.version<66;if(d&&(d.exact==="user"||d.exact==="environment"||d.ideal==="user"||d.ideal==="environment")&&!(t.mediaDevices.getSupportedConstraints&&t.mediaDevices.getSupportedConstraints().facingMode&&!c)){delete o.video.facingMode;let h;if(d.exact==="environment"||d.ideal==="environment"?h=["back","rear"]:(d.exact==="user"||d.ideal==="user")&&(h=["front"]),h)return t.mediaDevices.enumerateDevices().then(p=>{p=p.filter(f=>f.kind==="videoinput");let l=p.find(f=>h.some(g=>f.label.toLowerCase().includes(g)));return!l&&p.length&&h.includes("back")&&(l=p[p.length-1]),l&&(o.video.deviceId=d.exact?{exact:l.deviceId}:{ideal:l.deviceId}),o.video=i(o.video),ji("chrome: "+JSON.stringify(o)),u(o)})}o.video=i(o.video)}return ji("chrome: "+JSON.stringify(o)),u(o)},n=function(o){return e.version>=64?o:{name:{PermissionDeniedError:"NotAllowedError",PermissionDismissedError:"NotAllowedError",InvalidStateError:"NotAllowedError",DevicesNotFoundError:"NotFoundError",ConstraintNotSatisfiedError:"OverconstrainedError",TrackStartError:"NotReadableError",MediaDeviceFailedDueToShutdown:"NotAllowedError",MediaDeviceKillSwitchOn:"NotAllowedError",TabCaptureError:"AbortError",ScreenCaptureError:"AbortError",DeviceCaptureError:"AbortError"}[o.name]||o.name,message:o.message,constraint:o.constraint||o.constraintName,toString(){return this.name+(this.message&&": ")+this.message}}},a=function(o,u,d){s(o,c=>{t.webkitGetUserMedia(c,u,h=>{d&&d(n(h))})})};if(t.getUserMedia=a.bind(t),t.mediaDevices.getUserMedia){const o=t.mediaDevices.getUserMedia.bind(t.mediaDevices);t.mediaDevices.getUserMedia=function(u){return s(u,d=>o(d).then(c=>{if(d.audio&&!c.getAudioTracks().length||d.video&&!c.getVideoTracks().length)throw c.getTracks().forEach(h=>{h.stop()}),new DOMException("","NotFoundError");return c},c=>Promise.reject(n(c))))}}}function Gi(r){r.MediaStream=r.MediaStream||r.webkitMediaStream}function Hi(r){if(typeof r=="object"&&r.RTCPeerConnection&&!("ontrack"in r.RTCPeerConnection.prototype)){Object.defineProperty(r.RTCPeerConnection.prototype,"ontrack",{get(){return this._ontrack},set(t){this._ontrack&&this.removeEventListener("track",this._ontrack),this.addEventListener("track",this._ontrack=t)},enumerable:!0,configurable:!0});const e=r.RTCPeerConnection.prototype.setRemoteDescription;r.RTCPeerConnection.prototype.setRemoteDescription=function(){return this._ontrackpoly||(this._ontrackpoly=i=>{i.stream.addEventListener("addtrack",s=>{let n;r.RTCPeerConnection.prototype.getReceivers?n=this.getReceivers().find(o=>o.track&&o.track.id===s.track.id):n={track:s.track};const a=new Event("track");a.track=s.track,a.receiver=n,a.transceiver={receiver:n},a.streams=[i.stream],this.dispatchEvent(a)}),i.stream.getTracks().forEach(s=>{let n;r.RTCPeerConnection.prototype.getReceivers?n=this.getReceivers().find(o=>o.track&&o.track.id===s.id):n={track:s};const a=new Event("track");a.track=s,a.receiver=n,a.transceiver={receiver:n},a.streams=[i.stream],this.dispatchEvent(a)})},this.addEventListener("addstream",this._ontrackpoly)),e.apply(this,arguments)}}else pe(r,"track",e=>(e.transceiver||Object.defineProperty(e,"transceiver",{value:{receiver:e.receiver}}),e))}function qi(r){if(typeof r=="object"&&r.RTCPeerConnection&&!("getSenders"in r.RTCPeerConnection.prototype)&&"createDTMFSender"in r.RTCPeerConnection.prototype){const e=function(s,n){return{track:n,get dtmf(){return this._dtmf===void 0&&(n.kind==="audio"?this._dtmf=s.createDTMFSender(n):this._dtmf=null),this._dtmf},_pc:s}};if(!r.RTCPeerConnection.prototype.getSenders){r.RTCPeerConnection.prototype.getSenders=function(){return this._senders=this._senders||[],this._senders.slice()};const s=r.RTCPeerConnection.prototype.addTrack;r.RTCPeerConnection.prototype.addTrack=function(o,u){let d=s.apply(this,arguments);return d||(d=e(this,o),this._senders.push(d)),d};const n=r.RTCPeerConnection.prototype.removeTrack;r.RTCPeerConnection.prototype.removeTrack=function(o){n.apply(this,arguments);const u=this._senders.indexOf(o);u!==-1&&this._senders.splice(u,1)}}const t=r.RTCPeerConnection.prototype.addStream;r.RTCPeerConnection.prototype.addStream=function(n){this._senders=this._senders||[],t.apply(this,[n]),n.getTracks().forEach(a=>{this._senders.push(e(this,a))})};const i=r.RTCPeerConnection.prototype.removeStream;r.RTCPeerConnection.prototype.removeStream=function(n){this._senders=this._senders||[],i.apply(this,[n]),n.getTracks().forEach(a=>{const o=this._senders.find(u=>u.track===a);o&&this._senders.splice(this._senders.indexOf(o),1)})}}else if(typeof r=="object"&&r.RTCPeerConnection&&"getSenders"in r.RTCPeerConnection.prototype&&"createDTMFSender"in r.RTCPeerConnection.prototype&&r.RTCRtpSender&&!("dtmf"in r.RTCRtpSender.prototype)){const e=r.RTCPeerConnection.prototype.getSenders;r.RTCPeerConnection.prototype.getSenders=function(){const i=e.apply(this,[]);return i.forEach(s=>s._pc=this),i},Object.defineProperty(r.RTCRtpSender.prototype,"dtmf",{get(){return this._dtmf===void 0&&(this.track.kind==="audio"?this._dtmf=this._pc.createDTMFSender(this.track):this._dtmf=null),this._dtmf}})}}function Wi(r){if(!(typeof r=="object"&&r.RTCPeerConnection&&r.RTCRtpSender&&r.RTCRtpReceiver))return;if(!("getStats"in r.RTCRtpSender.prototype)){const t=r.RTCPeerConnection.prototype.getSenders;t&&(r.RTCPeerConnection.prototype.getSenders=function(){const n=t.apply(this,[]);return n.forEach(a=>a._pc=this),n});const i=r.RTCPeerConnection.prototype.addTrack;i&&(r.RTCPeerConnection.prototype.addTrack=function(){const n=i.apply(this,arguments);return n._pc=this,n}),r.RTCRtpSender.prototype.getStats=function(){const n=this;return this._pc.getStats().then(a=>Bi(a,n.track,!0))}}if(!("getStats"in r.RTCRtpReceiver.prototype)){const t=r.RTCPeerConnection.prototype.getReceivers;t&&(r.RTCPeerConnection.prototype.getReceivers=function(){const s=t.apply(this,[]);return s.forEach(n=>n._pc=this),s}),pe(r,"track",i=>(i.receiver._pc=i.srcElement,i)),r.RTCRtpReceiver.prototype.getStats=function(){const s=this;return this._pc.getStats().then(n=>Bi(n,s.track,!1))}}if(!("getStats"in r.RTCRtpSender.prototype&&"getStats"in r.RTCRtpReceiver.prototype))return;const e=r.RTCPeerConnection.prototype.getStats;r.RTCPeerConnection.prototype.getStats=function(){if(arguments.length>0&&arguments[0]instanceof r.MediaStreamTrack){const i=arguments[0];let s,n,a;return this.getSenders().forEach(o=>{o.track===i&&(s?a=!0:s=o)}),this.getReceivers().forEach(o=>(o.track===i&&(n?a=!0:n=o),o.track===i)),a||s&&n?Promise.reject(new DOMException("There are more than one sender or receiver for the track.","InvalidAccessError")):s?s.getStats():n?n.getStats():Promise.reject(new DOMException("There is no sender or receiver for the track.","InvalidAccessError"))}return e.apply(this,arguments)}}function Xi(r){r.RTCPeerConnection.prototype.getLocalStreams=function(){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},Object.keys(this._shimmedLocalStreams).map(a=>this._shimmedLocalStreams[a][0])};const e=r.RTCPeerConnection.prototype.addTrack;r.RTCPeerConnection.prototype.addTrack=function(a,o){if(!o)return e.apply(this,arguments);this._shimmedLocalStreams=this._shimmedLocalStreams||{};const u=e.apply(this,arguments);return this._shimmedLocalStreams[o.id]?this._shimmedLocalStreams[o.id].indexOf(u)===-1&&this._shimmedLocalStreams[o.id].push(u):this._shimmedLocalStreams[o.id]=[o,u],u};const t=r.RTCPeerConnection.prototype.addStream;r.RTCPeerConnection.prototype.addStream=function(a){this._shimmedLocalStreams=this._shimmedLocalStreams||{},a.getTracks().forEach(d=>{if(this.getSenders().find(h=>h.track===d))throw new DOMException("Track already exists.","InvalidAccessError")});const o=this.getSenders();t.apply(this,arguments);const u=this.getSenders().filter(d=>o.indexOf(d)===-1);this._shimmedLocalStreams[a.id]=[a].concat(u)};const i=r.RTCPeerConnection.prototype.removeStream;r.RTCPeerConnection.prototype.removeStream=function(a){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},delete this._shimmedLocalStreams[a.id],i.apply(this,arguments)};const s=r.RTCPeerConnection.prototype.removeTrack;r.RTCPeerConnection.prototype.removeTrack=function(a){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},a&&Object.keys(this._shimmedLocalStreams).forEach(o=>{const u=this._shimmedLocalStreams[o].indexOf(a);u!==-1&&this._shimmedLocalStreams[o].splice(u,1),this._shimmedLocalStreams[o].length===1&&delete this._shimmedLocalStreams[o]}),s.apply(this,arguments)}}function Ki(r,e){if(!r.RTCPeerConnection)return;if(r.RTCPeerConnection.prototype.addTrack&&e.version>=65)return Xi(r);const t=r.RTCPeerConnection.prototype.getLocalStreams;r.RTCPeerConnection.prototype.getLocalStreams=function(){const c=t.apply(this);return this._reverseStreams=this._reverseStreams||{},c.map(h=>this._reverseStreams[h.id])};const i=r.RTCPeerConnection.prototype.addStream;r.RTCPeerConnection.prototype.addStream=function(c){if(this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},c.getTracks().forEach(h=>{if(this.getSenders().find(l=>l.track===h))throw new DOMException("Track already exists.","InvalidAccessError")}),!this._reverseStreams[c.id]){const h=new r.MediaStream(c.getTracks());this._streams[c.id]=h,this._reverseStreams[h.id]=c,c=h}i.apply(this,[c])};const s=r.RTCPeerConnection.prototype.removeStream;r.RTCPeerConnection.prototype.removeStream=function(c){this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},s.apply(this,[this._streams[c.id]||c]),delete this._reverseStreams[this._streams[c.id]?this._streams[c.id].id:c.id],delete this._streams[c.id]},r.RTCPeerConnection.prototype.addTrack=function(c,h){if(this.signalingState==="closed")throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");const p=[].slice.call(arguments,1);if(p.length!==1||!p[0].getTracks().find(g=>g===c))throw new DOMException("The adapter.js addTrack polyfill only supports a single stream which is associated with the specified track.","NotSupportedError");if(this.getSenders().find(g=>g.track===c))throw new DOMException("Track already exists.","InvalidAccessError");this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{};const f=this._streams[h.id];if(f)f.addTrack(c),Promise.resolve().then(()=>{this.dispatchEvent(new Event("negotiationneeded"))});else{const g=new r.MediaStream([c]);this._streams[h.id]=g,this._reverseStreams[g.id]=h,this.addStream(g)}return this.getSenders().find(g=>g.track===c)};function n(d,c){let h=c.sdp;return Object.keys(d._reverseStreams||[]).forEach(p=>{const l=d._reverseStreams[p],f=d._streams[l.id];h=h.replace(new RegExp(f.id,"g"),l.id)}),new RTCSessionDescription({type:c.type,sdp:h})}function a(d,c){let h=c.sdp;return Object.keys(d._reverseStreams||[]).forEach(p=>{const l=d._reverseStreams[p],f=d._streams[l.id];h=h.replace(new RegExp(l.id,"g"),f.id)}),new RTCSessionDescription({type:c.type,sdp:h})}["createOffer","createAnswer"].forEach(function(d){const c=r.RTCPeerConnection.prototype[d],h={[d](){const p=arguments;return arguments.length&&typeof arguments[0]=="function"?c.apply(this,[f=>{const g=n(this,f);p[0].apply(null,[g])},f=>{p[1]&&p[1].apply(null,f)},arguments[2]]):c.apply(this,arguments).then(f=>n(this,f))}};r.RTCPeerConnection.prototype[d]=h[d]});const o=r.RTCPeerConnection.prototype.setLocalDescription;r.RTCPeerConnection.prototype.setLocalDescription=function(){return!arguments.length||!arguments[0].type?o.apply(this,arguments):(arguments[0]=a(this,arguments[0]),o.apply(this,arguments))};const u=Object.getOwnPropertyDescriptor(r.RTCPeerConnection.prototype,"localDescription");Object.defineProperty(r.RTCPeerConnection.prototype,"localDescription",{get(){const d=u.get.apply(this);return d.type===""?d:n(this,d)}}),r.RTCPeerConnection.prototype.removeTrack=function(c){if(this.signalingState==="closed")throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");if(!c._pc)throw new DOMException("Argument 1 of RTCPeerConnection.removeTrack does not implement interface RTCRtpSender.","TypeError");if(!(c._pc===this))throw new DOMException("Sender was not created by this connection.","InvalidAccessError");this._streams=this._streams||{};let p;Object.keys(this._streams).forEach(l=>{this._streams[l].getTracks().find(g=>c.track===g)&&(p=this._streams[l])}),p&&(p.getTracks().length===1?this.removeStream(this._reverseStreams[p.id]):p.removeTrack(c.track),this.dispatchEvent(new Event("negotiationneeded")))}}function Gt(r,e){!r.RTCPeerConnection&&r.webkitRTCPeerConnection&&(r.RTCPeerConnection=r.webkitRTCPeerConnection),r.RTCPeerConnection&&e.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach(function(t){const i=r.RTCPeerConnection.prototype[t],s={[t](){return arguments[0]=new(t==="addIceCandidate"?r.RTCIceCandidate:r.RTCSessionDescription)(arguments[0]),i.apply(this,arguments)}};r.RTCPeerConnection.prototype[t]=s[t]})}function Ji(r,e){pe(r,"negotiationneeded",t=>{const i=t.target;if(!((e.version<72||i.getConfiguration&&i.getConfiguration().sdpSemantics==="plan-b")&&i.signalingState!=="stable"))return t})}const Yi=Object.freeze(Object.defineProperty({__proto__:null,fixNegotiationNeeded:Ji,shimAddTrackRemoveTrack:Ki,shimAddTrackRemoveTrackWithNative:Xi,shimGetSendersWithDtmf:qi,shimGetUserMedia:zi,shimMediaStream:Gi,shimOnTrack:Hi,shimPeerConnection:Gt,shimSenderReceiverGetStats:Wi},Symbol.toStringTag,{value:"Module"}));function Zi(r,e){const t=r&&r.navigator,i=r&&r.MediaStreamTrack;if(t.getUserMedia=function(s,n,a){jt("navigator.getUserMedia","navigator.mediaDevices.getUserMedia"),t.mediaDevices.getUserMedia(s).then(n,a)},!(e.version>55&&"autoGainControl"in t.mediaDevices.getSupportedConstraints())){const s=function(a,o,u){o in a&&!(u in a)&&(a[u]=a[o],delete a[o])},n=t.mediaDevices.getUserMedia.bind(t.mediaDevices);if(t.mediaDevices.getUserMedia=function(a){return typeof a=="object"&&typeof a.audio=="object"&&(a=JSON.parse(JSON.stringify(a)),s(a.audio,"autoGainControl","mozAutoGainControl"),s(a.audio,"noiseSuppression","mozNoiseSuppression")),n(a)},i&&i.prototype.getSettings){const a=i.prototype.getSettings;i.prototype.getSettings=function(){const o=a.apply(this,arguments);return s(o,"mozAutoGainControl","autoGainControl"),s(o,"mozNoiseSuppression","noiseSuppression"),o}}if(i&&i.prototype.applyConstraints){const a=i.prototype.applyConstraints;i.prototype.applyConstraints=function(o){return this.kind==="audio"&&typeof o=="object"&&(o=JSON.parse(JSON.stringify(o)),s(o,"autoGainControl","mozAutoGainControl"),s(o,"noiseSuppression","mozNoiseSuppression")),a.apply(this,[o])}}}}function ih(r,e){r.navigator.mediaDevices&&"getDisplayMedia"in r.navigator.mediaDevices||r.navigator.mediaDevices&&(r.navigator.mediaDevices.getDisplayMedia=function(i){if(!(i&&i.video)){const s=new DOMException("getDisplayMedia without video constraints is undefined");return s.name="NotFoundError",s.code=8,Promise.reject(s)}return i.video===!0?i.video={mediaSource:e}:i.video.mediaSource=e,r.navigator.mediaDevices.getUserMedia(i)})}function Qi(r){typeof r=="object"&&r.RTCTrackEvent&&"receiver"in r.RTCTrackEvent.prototype&&!("transceiver"in r.RTCTrackEvent.prototype)&&Object.defineProperty(r.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function Ht(r,e){if(typeof r!="object"||!(r.RTCPeerConnection||r.mozRTCPeerConnection))return;!r.RTCPeerConnection&&r.mozRTCPeerConnection&&(r.RTCPeerConnection=r.mozRTCPeerConnection),e.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach(function(s){const n=r.RTCPeerConnection.prototype[s],a={[s](){return arguments[0]=new(s==="addIceCandidate"?r.RTCIceCandidate:r.RTCSessionDescription)(arguments[0]),n.apply(this,arguments)}};r.RTCPeerConnection.prototype[s]=a[s]});const t={inboundrtp:"inbound-rtp",outboundrtp:"outbound-rtp",candidatepair:"candidate-pair",localcandidate:"local-candidate",remotecandidate:"remote-candidate"},i=r.RTCPeerConnection.prototype.getStats;r.RTCPeerConnection.prototype.getStats=function(){const[n,a,o]=arguments;return i.apply(this,[n||null]).then(u=>{if(e.version<53&&!a)try{u.forEach(d=>{d.type=t[d.type]||d.type})}catch(d){if(d.name!=="TypeError")throw d;u.forEach((c,h)=>{u.set(h,Object.assign({},c,{type:t[c.type]||c.type}))})}return u}).then(a,o)}}function es(r){if(!(typeof r=="object"&&r.RTCPeerConnection&&r.RTCRtpSender)||r.RTCRtpSender&&"getStats"in r.RTCRtpSender.prototype)return;const e=r.RTCPeerConnection.prototype.getSenders;e&&(r.RTCPeerConnection.prototype.getSenders=function(){const s=e.apply(this,[]);return s.forEach(n=>n._pc=this),s});const t=r.RTCPeerConnection.prototype.addTrack;t&&(r.RTCPeerConnection.prototype.addTrack=function(){const s=t.apply(this,arguments);return s._pc=this,s}),r.RTCRtpSender.prototype.getStats=function(){return this.track?this._pc.getStats(this.track):Promise.resolve(new Map)}}function ts(r){if(!(typeof r=="object"&&r.RTCPeerConnection&&r.RTCRtpSender)||r.RTCRtpSender&&"getStats"in r.RTCRtpReceiver.prototype)return;const e=r.RTCPeerConnection.prototype.getReceivers;e&&(r.RTCPeerConnection.prototype.getReceivers=function(){const i=e.apply(this,[]);return i.forEach(s=>s._pc=this),i}),pe(r,"track",t=>(t.receiver._pc=t.srcElement,t)),r.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track)}}function rs(r){!r.RTCPeerConnection||"removeStream"in r.RTCPeerConnection.prototype||(r.RTCPeerConnection.prototype.removeStream=function(t){jt("removeStream","removeTrack"),this.getSenders().forEach(i=>{i.track&&t.getTracks().includes(i.track)&&this.removeTrack(i)})})}function is(r){r.DataChannel&&!r.RTCDataChannel&&(r.RTCDataChannel=r.DataChannel)}function ss(r){if(!(typeof r=="object"&&r.RTCPeerConnection))return;const e=r.RTCPeerConnection.prototype.addTransceiver;e&&(r.RTCPeerConnection.prototype.addTransceiver=function(){this.setParametersPromises=[];let i=arguments[1]&&arguments[1].sendEncodings;i===void 0&&(i=[]),i=[...i];const s=i.length>0;s&&i.forEach(a=>{if("rid"in a&&!/^[a-z0-9]{0,16}$/i.test(a.rid))throw new TypeError("Invalid RID value provided.");if("scaleResolutionDownBy"in a&&!(parseFloat(a.scaleResolutionDownBy)>=1))throw new RangeError("scale_resolution_down_by must be >= 1.0");if("maxFramerate"in a&&!(parseFloat(a.maxFramerate)>=0))throw new RangeError("max_framerate must be >= 0.0")});const n=e.apply(this,arguments);if(s){const{sender:a}=n,o=a.getParameters();(!("encodings"in o)||o.encodings.length===1&&Object.keys(o.encodings[0]).length===0)&&(o.encodings=i,a.sendEncodings=i,this.setParametersPromises.push(a.setParameters(o).then(()=>{delete a.sendEncodings}).catch(()=>{delete a.sendEncodings})))}return n})}function ns(r){if(!(typeof r=="object"&&r.RTCRtpSender))return;const e=r.RTCRtpSender.prototype.getParameters;e&&(r.RTCRtpSender.prototype.getParameters=function(){const i=e.apply(this,arguments);return"encodings"in i||(i.encodings=[].concat(this.sendEncodings||[{}])),i})}function os(r){if(!(typeof r=="object"&&r.RTCPeerConnection))return;const e=r.RTCPeerConnection.prototype.createOffer;r.RTCPeerConnection.prototype.createOffer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then(()=>e.apply(this,arguments)).finally(()=>{this.setParametersPromises=[]}):e.apply(this,arguments)}}function as(r){if(!(typeof r=="object"&&r.RTCPeerConnection))return;const e=r.RTCPeerConnection.prototype.createAnswer;r.RTCPeerConnection.prototype.createAnswer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then(()=>e.apply(this,arguments)).finally(()=>{this.setParametersPromises=[]}):e.apply(this,arguments)}}const cs=Object.freeze(Object.defineProperty({__proto__:null,shimAddTransceiver:ss,shimCreateAnswer:as,shimCreateOffer:os,shimGetDisplayMedia:ih,shimGetParameters:ns,shimGetUserMedia:Zi,shimOnTrack:Qi,shimPeerConnection:Ht,shimRTCDataChannel:is,shimReceiverGetStats:ts,shimRemoveStream:rs,shimSenderGetStats:es},Symbol.toStringTag,{value:"Module"}));function ds(r){if(!(typeof r!="object"||!r.RTCPeerConnection)){if("getLocalStreams"in r.RTCPeerConnection.prototype||(r.RTCPeerConnection.prototype.getLocalStreams=function(){return this._localStreams||(this._localStreams=[]),this._localStreams}),!("addStream"in r.RTCPeerConnection.prototype)){const e=r.RTCPeerConnection.prototype.addTrack;r.RTCPeerConnection.prototype.addStream=function(i){this._localStreams||(this._localStreams=[]),this._localStreams.includes(i)||this._localStreams.push(i),i.getAudioTracks().forEach(s=>e.call(this,s,i)),i.getVideoTracks().forEach(s=>e.call(this,s,i))},r.RTCPeerConnection.prototype.addTrack=function(i,...s){return s&&s.forEach(n=>{this._localStreams?this._localStreams.includes(n)||this._localStreams.push(n):this._localStreams=[n]}),e.apply(this,arguments)}}"removeStream"in r.RTCPeerConnection.prototype||(r.RTCPeerConnection.prototype.removeStream=function(t){this._localStreams||(this._localStreams=[]);const i=this._localStreams.indexOf(t);if(i===-1)return;this._localStreams.splice(i,1);const s=t.getTracks();this.getSenders().forEach(n=>{s.includes(n.track)&&this.removeTrack(n)})})}}function us(r){if(!(typeof r!="object"||!r.RTCPeerConnection)&&("getRemoteStreams"in r.RTCPeerConnection.prototype||(r.RTCPeerConnection.prototype.getRemoteStreams=function(){return this._remoteStreams?this._remoteStreams:[]}),!("onaddstream"in r.RTCPeerConnection.prototype))){Object.defineProperty(r.RTCPeerConnection.prototype,"onaddstream",{get(){return this._onaddstream},set(t){this._onaddstream&&(this.removeEventListener("addstream",this._onaddstream),this.removeEventListener("track",this._onaddstreampoly)),this.addEventListener("addstream",this._onaddstream=t),this.addEventListener("track",this._onaddstreampoly=i=>{i.streams.forEach(s=>{if(this._remoteStreams||(this._remoteStreams=[]),this._remoteStreams.includes(s))return;this._remoteStreams.push(s);const n=new Event("addstream");n.stream=s,this.dispatchEvent(n)})})}});const e=r.RTCPeerConnection.prototype.setRemoteDescription;r.RTCPeerConnection.prototype.setRemoteDescription=function(){const i=this;return this._onaddstreampoly||this.addEventListener("track",this._onaddstreampoly=function(s){s.streams.forEach(n=>{if(i._remoteStreams||(i._remoteStreams=[]),i._remoteStreams.indexOf(n)>=0)return;i._remoteStreams.push(n);const a=new Event("addstream");a.stream=n,i.dispatchEvent(a)})}),e.apply(i,arguments)}}}function hs(r){if(typeof r!="object"||!r.RTCPeerConnection)return;const e=r.RTCPeerConnection.prototype,t=e.createOffer,i=e.createAnswer,s=e.setLocalDescription,n=e.setRemoteDescription,a=e.addIceCandidate;e.createOffer=function(d,c){const h=arguments.length>=2?arguments[2]:arguments[0],p=t.apply(this,[h]);return c?(p.then(d,c),Promise.resolve()):p},e.createAnswer=function(d,c){const h=arguments.length>=2?arguments[2]:arguments[0],p=i.apply(this,[h]);return c?(p.then(d,c),Promise.resolve()):p};let o=function(u,d,c){const h=s.apply(this,[u]);return c?(h.then(d,c),Promise.resolve()):h};e.setLocalDescription=o,o=function(u,d,c){const h=n.apply(this,[u]);return c?(h.then(d,c),Promise.resolve()):h},e.setRemoteDescription=o,o=function(u,d,c){const h=a.apply(this,[u]);return c?(h.then(d,c),Promise.resolve()):h},e.addIceCandidate=o}function ps(r){const e=r&&r.navigator;if(e.mediaDevices&&e.mediaDevices.getUserMedia){const t=e.mediaDevices,i=t.getUserMedia.bind(t);e.mediaDevices.getUserMedia=s=>i(ls(s))}!e.getUserMedia&&e.mediaDevices&&e.mediaDevices.getUserMedia&&(e.getUserMedia=(function(i,s,n){e.mediaDevices.getUserMedia(i).then(s,n)}).bind(e))}function ls(r){return r&&r.video!==void 0?Object.assign({},r,{video:$i(r.video)}):r}function ms(r){if(!r.RTCPeerConnection)return;const e=r.RTCPeerConnection;r.RTCPeerConnection=function(i,s){if(i&&i.iceServers){const n=[];for(let a=0;a<i.iceServers.length;a++){let o=i.iceServers[a];o.urls===void 0&&o.url?(jt("RTCIceServer.url","RTCIceServer.urls"),o=JSON.parse(JSON.stringify(o)),o.urls=o.url,delete o.url,n.push(o)):n.push(i.iceServers[a])}i.iceServers=n}return new e(i,s)},r.RTCPeerConnection.prototype=e.prototype,"generateCertificate"in e&&Object.defineProperty(r.RTCPeerConnection,"generateCertificate",{get(){return e.generateCertificate}})}function fs(r){typeof r=="object"&&r.RTCTrackEvent&&"receiver"in r.RTCTrackEvent.prototype&&!("transceiver"in r.RTCTrackEvent.prototype)&&Object.defineProperty(r.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function _s(r){const e=r.RTCPeerConnection.prototype.createOffer;r.RTCPeerConnection.prototype.createOffer=function(i){if(i){typeof i.offerToReceiveAudio<"u"&&(i.offerToReceiveAudio=!!i.offerToReceiveAudio);const s=this.getTransceivers().find(a=>a.receiver.track.kind==="audio");i.offerToReceiveAudio===!1&&s?s.direction==="sendrecv"?s.setDirection?s.setDirection("sendonly"):s.direction="sendonly":s.direction==="recvonly"&&(s.setDirection?s.setDirection("inactive"):s.direction="inactive"):i.offerToReceiveAudio===!0&&!s&&this.addTransceiver("audio",{direction:"recvonly"}),typeof i.offerToReceiveVideo<"u"&&(i.offerToReceiveVideo=!!i.offerToReceiveVideo);const n=this.getTransceivers().find(a=>a.receiver.track.kind==="video");i.offerToReceiveVideo===!1&&n?n.direction==="sendrecv"?n.setDirection?n.setDirection("sendonly"):n.direction="sendonly":n.direction==="recvonly"&&(n.setDirection?n.setDirection("inactive"):n.direction="inactive"):i.offerToReceiveVideo===!0&&!n&&this.addTransceiver("video",{direction:"recvonly"})}return e.apply(this,arguments)}}function gs(r){typeof r!="object"||r.AudioContext||(r.AudioContext=r.webkitAudioContext)}const vs=Object.freeze(Object.defineProperty({__proto__:null,shimAudioContext:gs,shimCallbacksAPI:hs,shimConstraints:ls,shimCreateOfferLegacy:_s,shimGetUserMedia:ps,shimLocalStreamsAPI:ds,shimRTCIceServerUrls:ms,shimRemoteStreamsAPI:us,shimTrackEventTransceiver:fs},Symbol.toStringTag,{value:"Module"}));var qt={exports:{}},Cs;function sh(){return Cs||(Cs=1,function(r){const e={};e.generateIdentifier=function(){return Math.random().toString(36).substring(2,12)},e.localCName=e.generateIdentifier(),e.splitLines=function(t){return t.trim().split(`
60
- `).map(i=>i.trim())},e.splitSections=function(t){return t.split(`
61
- m=`).map((s,n)=>(n>0?"m="+s:s).trim()+`\r
62
- `)},e.getDescription=function(t){const i=e.splitSections(t);return i&&i[0]},e.getMediaSections=function(t){const i=e.splitSections(t);return i.shift(),i},e.matchPrefix=function(t,i){return e.splitLines(t).filter(s=>s.indexOf(i)===0)},e.parseCandidate=function(t){let i;t.indexOf("a=candidate:")===0?i=t.substring(12).split(" "):i=t.substring(10).split(" ");const s={foundation:i[0],component:{1:"rtp",2:"rtcp"}[i[1]]||i[1],protocol:i[2].toLowerCase(),priority:parseInt(i[3],10),ip:i[4],address:i[4],port:parseInt(i[5],10),type:i[7]};for(let n=8;n<i.length;n+=2)switch(i[n]){case"raddr":s.relatedAddress=i[n+1];break;case"rport":s.relatedPort=parseInt(i[n+1],10);break;case"tcptype":s.tcpType=i[n+1];break;case"ufrag":s.ufrag=i[n+1],s.usernameFragment=i[n+1];break;default:s[i[n]]===void 0&&(s[i[n]]=i[n+1]);break}return s},e.writeCandidate=function(t){const i=[];i.push(t.foundation);const s=t.component;s==="rtp"?i.push(1):s==="rtcp"?i.push(2):i.push(s),i.push(t.protocol.toUpperCase()),i.push(t.priority),i.push(t.address||t.ip),i.push(t.port);const n=t.type;return i.push("typ"),i.push(n),n!=="host"&&t.relatedAddress&&t.relatedPort&&(i.push("raddr"),i.push(t.relatedAddress),i.push("rport"),i.push(t.relatedPort)),t.tcpType&&t.protocol.toLowerCase()==="tcp"&&(i.push("tcptype"),i.push(t.tcpType)),(t.usernameFragment||t.ufrag)&&(i.push("ufrag"),i.push(t.usernameFragment||t.ufrag)),"candidate:"+i.join(" ")},e.parseIceOptions=function(t){return t.substring(14).split(" ")},e.parseRtpMap=function(t){let i=t.substring(9).split(" ");const s={payloadType:parseInt(i.shift(),10)};return i=i[0].split("/"),s.name=i[0],s.clockRate=parseInt(i[1],10),s.channels=i.length===3?parseInt(i[2],10):1,s.numChannels=s.channels,s},e.writeRtpMap=function(t){let i=t.payloadType;t.preferredPayloadType!==void 0&&(i=t.preferredPayloadType);const s=t.channels||t.numChannels||1;return"a=rtpmap:"+i+" "+t.name+"/"+t.clockRate+(s!==1?"/"+s:"")+`\r
63
- `},e.parseExtmap=function(t){const i=t.substring(9).split(" ");return{id:parseInt(i[0],10),direction:i[0].indexOf("/")>0?i[0].split("/")[1]:"sendrecv",uri:i[1],attributes:i.slice(2).join(" ")}},e.writeExtmap=function(t){return"a=extmap:"+(t.id||t.preferredId)+(t.direction&&t.direction!=="sendrecv"?"/"+t.direction:"")+" "+t.uri+(t.attributes?" "+t.attributes:"")+`\r
64
- `},e.parseFmtp=function(t){const i={};let s;const n=t.substring(t.indexOf(" ")+1).split(";");for(let a=0;a<n.length;a++)s=n[a].trim().split("="),i[s[0].trim()]=s[1];return i},e.writeFmtp=function(t){let i="",s=t.payloadType;if(t.preferredPayloadType!==void 0&&(s=t.preferredPayloadType),t.parameters&&Object.keys(t.parameters).length){const n=[];Object.keys(t.parameters).forEach(a=>{t.parameters[a]!==void 0?n.push(a+"="+t.parameters[a]):n.push(a)}),i+="a=fmtp:"+s+" "+n.join(";")+`\r
65
- `}return i},e.parseRtcpFb=function(t){const i=t.substring(t.indexOf(" ")+1).split(" ");return{type:i.shift(),parameter:i.join(" ")}},e.writeRtcpFb=function(t){let i="",s=t.payloadType;return t.preferredPayloadType!==void 0&&(s=t.preferredPayloadType),t.rtcpFeedback&&t.rtcpFeedback.length&&t.rtcpFeedback.forEach(n=>{i+="a=rtcp-fb:"+s+" "+n.type+(n.parameter&&n.parameter.length?" "+n.parameter:"")+`\r
66
- `}),i},e.parseSsrcMedia=function(t){const i=t.indexOf(" "),s={ssrc:parseInt(t.substring(7,i),10)},n=t.indexOf(":",i);return n>-1?(s.attribute=t.substring(i+1,n),s.value=t.substring(n+1)):s.attribute=t.substring(i+1),s},e.parseSsrcGroup=function(t){const i=t.substring(13).split(" ");return{semantics:i.shift(),ssrcs:i.map(s=>parseInt(s,10))}},e.getMid=function(t){const i=e.matchPrefix(t,"a=mid:")[0];if(i)return i.substring(6)},e.parseFingerprint=function(t){const i=t.substring(14).split(" ");return{algorithm:i[0].toLowerCase(),value:i[1].toUpperCase()}},e.getDtlsParameters=function(t,i){return{role:"auto",fingerprints:e.matchPrefix(t+i,"a=fingerprint:").map(e.parseFingerprint)}},e.writeDtlsParameters=function(t,i){let s="a=setup:"+i+`\r
67
- `;return t.fingerprints.forEach(n=>{s+="a=fingerprint:"+n.algorithm+" "+n.value+`\r
68
- `}),s},e.parseCryptoLine=function(t){const i=t.substring(9).split(" ");return{tag:parseInt(i[0],10),cryptoSuite:i[1],keyParams:i[2],sessionParams:i.slice(3)}},e.writeCryptoLine=function(t){return"a=crypto:"+t.tag+" "+t.cryptoSuite+" "+(typeof t.keyParams=="object"?e.writeCryptoKeyParams(t.keyParams):t.keyParams)+(t.sessionParams?" "+t.sessionParams.join(" "):"")+`\r
69
- `},e.parseCryptoKeyParams=function(t){if(t.indexOf("inline:")!==0)return null;const i=t.substring(7).split("|");return{keyMethod:"inline",keySalt:i[0],lifeTime:i[1],mkiValue:i[2]?i[2].split(":")[0]:void 0,mkiLength:i[2]?i[2].split(":")[1]:void 0}},e.writeCryptoKeyParams=function(t){return t.keyMethod+":"+t.keySalt+(t.lifeTime?"|"+t.lifeTime:"")+(t.mkiValue&&t.mkiLength?"|"+t.mkiValue+":"+t.mkiLength:"")},e.getCryptoParameters=function(t,i){return e.matchPrefix(t+i,"a=crypto:").map(e.parseCryptoLine)},e.getIceParameters=function(t,i){const s=e.matchPrefix(t+i,"a=ice-ufrag:")[0],n=e.matchPrefix(t+i,"a=ice-pwd:")[0];return s&&n?{usernameFragment:s.substring(12),password:n.substring(10)}:null},e.writeIceParameters=function(t){let i="a=ice-ufrag:"+t.usernameFragment+`\r
68
+ `},In}var Fa;function Y_(){if(Fa)return ke;Fa=1;var i=Z_(),e=Q_(),t=xn();return ke.grammar=t,ke.write=e,ke.parse=i.parse,ke.parseParams=i.parseParams,ke.parseFmtpConfig=i.parseFmtpConfig,ke.parsePayloads=i.parsePayloads,ke.parseRemoteCandidates=i.parseRemoteCandidates,ke.parseImageAttributes=i.parseImageAttributes,ke.parseSimulcastStreamList=i.parseSimulcastStreamList,ke}var eg=Y_();const Gt=ae(eg);function ki(i){return new Promise(e=>{setTimeout(e,i)})}async function tg(i,e={},t=0){const r=new AbortController;let n=!1;e=Object.assign({},e,{signal:r.signal});const s=[fetch(i,e)];t&&s.push(new Promise((a,o)=>{setTimeout(()=>{n||(o({httpCode:0,message:"Timeout"}),r.abort())},t)}));try{const a=await Promise.race(s);if(n=!0,!a.ok||a.status<200||a.status>=300)throw{httpCode:a.status,message:a.statusText};return a.json()}catch(a){throw n=!0,a}}async function ja(i,e={},t={}){const{timeout:r=0,retryDelay:n=0}=t;let{retryCount:s=0}=t;try{return await tg(i,e,r)}catch(a){if(s--,t.retryCount=s,s<0)throw a;return await ki(n),await ja(i,e,t)}}const On=-1;function re(i,e){let t;return e.forEach(r=>{r.type===i&&(t=r)}),t}async function Mn(i,e){const t={},r=await(i==null?void 0:i.getStats()),n=await(e==null?void 0:e.getStats());return r&&(t.audio={mediaSource:re("media-source",r),codec:re("codec",r),candidatePair:re("candidate-pair",r),remoteCandidate:re("remote-candidate",r),localCandidate:re("local-candidate",r),track:re("track",r),outboundRtp:re("outbound-rtp",r),remoteInboundRtp:re("remote-inbound-rtp",r),transport:re("transport",r)}),n&&(t.video={mediaSource:re("media-source",n),codec:re("codec",n),candidatePair:re("candidate-pair",n),remoteCandidate:re("remote-candidate",n),localCandidate:re("local-candidate",n),track:re("track",n),outboundRtp:re("outbound-rtp",n),remoteInboundRtp:re("remote-inbound-rtp",n),transport:re("transport",n)}),t}async function ig(i,e,t){var u,l,h,p,f,v,m,b,y,_,E,z,T,x,R,A,D,P,K,H,J,X,de,q,ne,ze,at,ct,Ai,Ri,Di,xi,cu,uu,du,hu,lu,pu,fu;const r=await Mn(e,t);await ki(i);const n=await Mn(e,t),{audio:s,video:a}=r,{audio:o,video:d}=n,c={};if(s!=null&&s.codec&&(o!=null&&o.codec)){const Ht=((u=o.outboundRtp)==null?void 0:u.timestamp)-((l=s.outboundRtp)==null?void 0:l.timestamp),os=((h=o.outboundRtp)==null?void 0:h.bytesSent)-((p=s.outboundRtp)==null?void 0:p.bytesSent),vr=((f=o.remoteInboundRtp)==null?void 0:f.packetsLost)-((v=s.remoteInboundRtp)==null?void 0:v.packetsLost),as=((m=o.outboundRtp)==null?void 0:m.packetsSent)-((b=s.outboundRtp)==null?void 0:b.packetsSent),cs=(((y=o.mediaSource)==null?void 0:y.totalAudioEnergy)??0)-(((_=s.mediaSource)==null?void 0:_.totalAudioEnergy)??0);c.audio={codec:o.codec.mimeType,channels:o.codec.channels,sendBitrate:os/Ht*8e3,packetsSent:(E=o.outboundRtp)==null?void 0:E.packetsSent,nackCount:(z=o.outboundRtp)==null?void 0:z.nackCount,packetsLost:(T=o.remoteInboundRtp)==null?void 0:T.packetsLost,packetsLostPercent:vr/as,deltaAudioEnergy:cs}}if(a!=null&&a.codec&&(d!=null&&d.codec)){const Ht=((x=d.outboundRtp)==null?void 0:x.timestamp)-((R=a.outboundRtp)==null?void 0:R.timestamp),os=((A=d.outboundRtp)==null?void 0:A.bytesSent)-((D=a.outboundRtp)==null?void 0:D.bytesSent),vr=((P=d.outboundRtp)==null?void 0:P.framesEncoded)-((K=a.outboundRtp)==null?void 0:K.framesEncoded),as=((H=d.outboundRtp)==null?void 0:H.totalEncodeTime)-((J=a.outboundRtp)==null?void 0:J.totalEncodeTime),cs=((X=d.outboundRtp)==null?void 0:X.framesSent)-((de=a.outboundRtp)==null?void 0:de.framesSent),mu=((q=d.outboundRtp)==null?void 0:q.packetsSent)-((ne=a.outboundRtp)==null?void 0:ne.packetsSent),Bv=((ze=d.outboundRtp)==null?void 0:ze.totalPacketSendDelay)-((at=a.outboundRtp)==null?void 0:at.totalPacketSendDelay),Vv=((ct=d.remoteInboundRtp)==null?void 0:ct.packetsLost)-((Ai=a.remoteInboundRtp)==null?void 0:Ai.packetsLost);c.video={codec:d.codec.mimeType,sendBitrate:os/Ht*8e3,frameWidth:(Ri=d.outboundRtp)==null?void 0:Ri.frameWidth,frameHeight:(Di=d.outboundRtp)==null?void 0:Di.frameHeight,framesPerSecond:Math.floor(cs/Ht*1e3||0),framesEncoded:(xi=d.outboundRtp)==null?void 0:xi.framesEncoded,framesEncodedPerSecond:vr*1e3/Ht,keyFramesEncoded:(cu=d.outboundRtp)==null?void 0:cu.keyFramesEncoded,framesSent:(uu=d.outboundRtp)==null?void 0:uu.frameHeight,frameEncodeAvgTime:as*1e3/vr,packetsSent:(du=d.outboundRtp)==null?void 0:du.packetsSent,packetSendDelay:Bv*1e3/mu,nackCount:(hu=d.outboundRtp)==null?void 0:hu.nackCount,firCount:(lu=d.outboundRtp)==null?void 0:lu.firCount,pliCount:(pu=d.outboundRtp)==null?void 0:pu.pliCount,packetsLost:(fu=d.remoteInboundRtp)==null?void 0:fu.packetsLost,packetsLostPercent:Vv/mu,deltaTime:Ht}}return{stats:c,originStats:{audio:o,video:d}}}function Y(i,e=On){return i??e}function rg(i){var e,t,r,n,s,a,o,d,c,u,l,h,p,f,v,m,b,y,_,E,z,T,x,R,A,D,P,K,H,J,X,de,q,ne,ze,at,ct,Ai,Ri,Di,xi;return{audio_bytes:(e=i.outboundRtp)==null?void 0:e.bytesSent,audio_packets_sent:(t=i.outboundRtp)==null?void 0:t.packetsSent,audio_nack_count:(r=i.outboundRtp)==null?void 0:r.nackCount,audio_ssrc:(n=i.outboundRtp)==null?void 0:n.ssrc,audio_retransmitted_bytes_sent:(s=i.outboundRtp)==null?void 0:s.retransmittedBytesSent,audio_retransmitted_packets_sent:(a=i.outboundRtp)==null?void 0:a.retransmittedPacketsSent,audio_record_sample_rate:(o=i.codec)==null?void 0:o.clockRate,audio_num_channels:(d=i.codec)==null?void 0:d.channels,audio_level:(c=i.mediaSource)!=null&&c.audioLevel?-10*Math.log10(Math.pow((u=i.mediaSource)==null?void 0:u.audioLevel,2)):(l=i.mediaSource)==null?void 0:l.audioLevel,audio_volume:(h=i.mediaSource)!=null&&h.audioLevel?((p=i.mediaSource)==null?void 0:p.audioLevel)*255:(f=i.mediaSource)==null?void 0:f.audioLevel,audio_total_audio_energy:(v=i.mediaSource)==null?void 0:v.totalAudioEnergy,audio_total_input_duration:(m=i.mediaSource)==null?void 0:m.totalSamplesDuration,audio_send_level:(b=i.mediaSource)==null?void 0:b.audioLevel,audio_ice_available_outgoing_bitrate:(y=i.candidatePair)==null?void 0:y.availableOutgoingBitrate,audio_ice_bytes_received:(_=i.candidatePair)==null?void 0:_.bytesReceived,audio_ice_bytes_sent:(E=i.candidatePair)==null?void 0:E.bytesSent,audio_ice_nominated:(z=i.candidatePair)==null?void 0:z.nominated,audio_ice_pair_id:(T=i.candidatePair)==null?void 0:T.id,audio_ice_pair_rtt:(x=i.candidatePair)==null?void 0:x.currentRoundTripTime,audio_ice_pair_state:(R=i.candidatePair)==null?void 0:R.state,audio_ice_pair_writable:(A=i.candidatePair)==null?void 0:A.writable,audio_recv_ping_requests:(D=i.candidatePair)==null?void 0:D.requestsReceived,audio_recv_ping_responses:(P=i.candidatePair)==null?void 0:P.responsesReceived,audio_sent_ping_requests_before_first_response:(K=i.candidatePair)==null?void 0:K.requestsSent,audio_sent_ping_requests_total:(((H=i.candidatePair)==null?void 0:H.requestsSent)??0)+(((J=i.candidatePair)==null?void 0:J.consentRequestsSent)??0),audio_sent_ping_responses:(X=i.candidatePair)==null?void 0:X.responsesSent,audio_local_candidate_type:(de=i.localCandidate)==null?void 0:de.candidateType,audio_local_ip:((q=i.localCandidate)==null?void 0:q.ip)||((ne=i.localCandidate)==null?void 0:ne.address),audio_local_network_type:(ze=i.localCandidate)==null?void 0:ze.networkType,audio_local_port:(at=i.localCandidate)==null?void 0:at.port,audio_local_protocol:(ct=i.localCandidate)==null?void 0:ct.protocol,audio_remote_candidate_type:(Ai=i.remoteCandidate)==null?void 0:Ai.candidateType,audio_remote_ip:((Ri=i.remoteCandidate)==null?void 0:Ri.ip)||((Di=i.remoteCandidate)==null?void 0:Di.address),audio_remote_port:(xi=i.remoteCandidate)==null?void 0:xi.port}}function ng(i){var e,t,r,n,s,a,o,d,c,u,l,h,p,f,v,m,b,y,_,E,z,T,x,R,A,D,P,K,H,J,X,de,q,ne,ze,at,ct;return{video_qp_sum:(e=i.outboundRtp)==null?void 0:e.qpSum,video_pli_count:(t=i.outboundRtp)==null?void 0:t.pliCount,video_ssrc:(r=i.outboundRtp)==null?void 0:r.ssrc,video_quality_limitation_reason:(n=i.outboundRtp)==null?void 0:n.qualityLimitationReason,video_quality_limitation_durations:(s=i.outboundRtp)==null?void 0:s.qualityLimitationDurations,video_target_bitrate:(a=i.outboundRtp)==null?void 0:a.targetBitrate,video_rtt:(((o=i.remoteInboundRtp)==null?void 0:o.roundTripTime)||0)*1e3,video_jitter:(((d=i.remoteInboundRtp)==null?void 0:d.jitter)||0)*1e3,video_packets_lost:(c=i.remoteInboundRtp)==null?void 0:c.packetsLost,video_fraction_lost:(u=i.remoteInboundRtp)==null?void 0:u.fractionLost,video_ice_available_outgoing_bitrate:(l=i.candidatePair)==null?void 0:l.availableOutgoingBitrate,video_ice_bytes_received:(h=i.candidatePair)==null?void 0:h.bytesReceived,video_ice_bytes_sent:(p=i.candidatePair)==null?void 0:p.bytesSent,video_ice_nominated:(f=i.candidatePair)==null?void 0:f.nominated,video_ice_pair_id:(v=i.candidatePair)==null?void 0:v.id,video_ice_pair_rtt:(m=i.candidatePair)==null?void 0:m.currentRoundTripTime,video_ice_pair_state:(b=i.candidatePair)==null?void 0:b.state,video_ice_pair_writable:(y=i.candidatePair)==null?void 0:y.writable,video_recv_ping_requests:(_=i.candidatePair)==null?void 0:_.requestsReceived,video_recv_ping_responses:(E=i.candidatePair)==null?void 0:E.responsesReceived,video_sent_ping_requests_before_first_response:(z=i.candidatePair)==null?void 0:z.requestsSent,video_sent_ping_requests_total:(((T=i.candidatePair)==null?void 0:T.requestsSent)??0)+(((x=i.candidatePair)==null?void 0:x.consentRequestsSent)??0),video_sent_ping_responses:(R=i.candidatePair)==null?void 0:R.responsesSent,video_local_candidate_type:(A=i.localCandidate)==null?void 0:A.candidateType,video_local_ip:((D=i.localCandidate)==null?void 0:D.ip)||((P=i.localCandidate)==null?void 0:P.address),video_local_network_type:(K=i.localCandidate)==null?void 0:K.networkType,video_local_port:(H=i.localCandidate)==null?void 0:H.port,video_local_protocol:(J=i.localCandidate)==null?void 0:J.protocol,video_remote_candidate_type:(X=i.remoteCandidate)==null?void 0:X.candidateType,video_remote_ip:((de=i.remoteCandidate)==null?void 0:de.ip)||((q=i.remoteCandidate)==null?void 0:q.address),video_remote_port:(ne=i.remoteCandidate)==null?void 0:ne.port,video_input_frame_rate:(ze=i.mediaSource)==null?void 0:ze.framesPerSecond,video_input_frame_width:(at=i.mediaSource)==null?void 0:at.width,video_input_frame_height:(ct=i.mediaSource)==null?void 0:ct.height}}function sg(i,e,t){var c,u,l,h,p,f,v,m,b,y,_,E,z,T,x,R,A,D,P,K,H,J,X,de,q,ne,ze;const r=ng(e.video??{}),{video_input_frame_width:n,video_input_frame_height:s}=r,a=Y((c=i.video)==null?void 0:c.frameWidth),o=Y((u=i.video)==null?void 0:u.frameHeight),d=a<Number(n)||o<Number(s);return{...r,video_send_k_bitrate:Y((l=i.video)==null?void 0:l.sendBitrate)/1e3,video_send_frame_rate:Y((h=i.video)==null?void 0:h.framesPerSecond),video_encode_avg_time:Y((p=i.video)==null?void 0:p.frameEncodeAvgTime),video_encoder_output_frame_rate:Y((f=i.video)==null?void 0:f.framesEncodedPerSecond),video_encoded_frame_width:Y((v=i.video)==null?void 0:v.frameWidth),video_encoded_frame_height:Y((m=i.video)==null?void 0:m.frameHeight),video_encoded_key_frames:Y((b=i.video)==null?void 0:b.keyFramesEncoded),video_delta_time:Y((y=i.video)==null?void 0:y.deltaTime,2e3),video_packets_sent:Y((_=i.video)==null?void 0:_.packetsSent),video_nack_count:Y((E=i.video)==null?void 0:E.nackCount),video_fir_count:Y((z=i.video)==null?void 0:z.firCount),video_pli_count:Y((T=i.video)==null?void 0:T.pliCount),video_packets_lost:Y((x=i.video)==null?void 0:x.packetsLost),video_packets_lost_percent:(R=i.video)==null?void 0:R.packetsLostPercent,video_codec:(A=i.video)==null?void 0:A.codec,video_duration:(D=i.video)==null?void 0:D.deltaTime,video_frame_rate_compliance:t!=null&&t.idealFrameRate?Math.min(Y((P=i.video)==null?void 0:P.framesPerSecond)/t.idealFrameRate,1)*100:On,video_bitrate_compliance:t!=null&&t.idealBitrate?Math.min(Y((K=i.video)==null?void 0:K.sendBitrate)/t.idealBitrate,1)*100:On,video_resolution_downgrade:d,...rg(e.audio??{}),audio_send_k_bitrate:Y((H=i.audio)==null?void 0:H.sendBitrate)/1e3,audio_send_channels:Y((J=i.audio)==null?void 0:J.channels),audio_packets_sent:Y((X=i.audio)==null?void 0:X.packetsSent),audio_packets_lost:Y((de=i.audio)==null?void 0:de.packetsLost),audio_packets_lost_percent:(q=i.audio)==null?void 0:q.packetsLostPercent,audio_codec:(ne=i.audio)==null?void 0:ne.codec,audio_delta_energy:(ze=i.audio)==null?void 0:ze.deltaAudioEnergy}}function og(i){return{video_send_k_bitrate:i.video.sendBitrate/1e3,video_send_frame_rate:i.video.framesPerSecond,video_encoded_frame_width:i.video.frameWidth,video_encoded_frame_height:i.video.frameHeight,video_encoded_key_frames:i.video.keyFramesEncoded,video_send_speed:i.video.sendSpeed/1e3,video_gop_size:i.video.gopSize,video_codec:i.video.codec,video_duration:0,audio_send_k_bitrate:i.audio.sendBitrate/1e3,audio_codec:i.audio.codec,audio_send_channels:i.audio.channels,audio_send_sample_rate:i.audio.sampleRate}}const ag="42001f",cg="42e01f",ug=i=>{var t;if(!Cs)return;const e=(t=i.rtp.filter(r=>r.codec==="opus")[0])==null?void 0:t.payload;e&&i.fmtp.forEach(r=>{r.payload===e&&(r.config="minptime=10;useinbandfec=1")})},dg=i=>{i.ext&&(Tu||Ii)&&(i.ext=i.ext.filter(e=>{var t;return!((t=e.uri)!=null&&t.includes("video-orientation"))}))};function hg(i,e){i==null||i.rtp.forEach(({codec:t,payload:r})=>{if(["vp8","h264"].includes(t.toLocaleLowerCase())){const n=i.fmtp.find(s=>s.payload===r);n?n.config=[...n.config.split(";"),`x-google-min-bitrate=${e*.4}`,`x-google-start-bitrate=${e}`].join(";"):i.fmtp.push({payload:r,config:`x-google-min-bitrate=${e*.4};x-google-start-bitrate=${e}`})}})}function Ha(i,e){if(!Array.isArray(i.fmtp)||!Array.isArray(i.rtp))return;const t=i.fmtp.find(a=>a.config&&a.config.includes(ag)),r=i.fmtp.find(a=>a.config&&a.config.includes(cg));if(!t||!r)return;const n=i.rtp.findIndex(a=>a.payload===t.payload),s=i.rtp.findIndex(a=>a.payload===r.payload);if(n!==-1&&s!==-1){if(e==="hardware"){if(s<n){const a=i.rtp[s];i.rtp[s]=i.rtp[n],i.rtp[n]=a}}else if(n<s){const a=i.rtp[n];i.rtp[n]=i.rtp[s],i.rtp[s]=a}}i.payloads=i.rtp.map(a=>a.payload).join(" ")}const lg=()=>typeof window>"u",Me={},or=async i=>{const e=new RTCPeerConnection({sdpSemantics:"unified-plan"});e.addTransceiver("video",{direction:i});const t=await e.createOffer();return e.close(),t.sdp.toLowerCase()};function $a(i){const e=i.split(`
69
+ `);let t=!1;for(const r of e)if(r.includes("level-asymmetry-allowed=1")&&r.includes("packetization-mode=1")&&r.includes("profile-level-id=42e0")){t=!0;break}if(t){const r=navigator.userAgent.toLowerCase();let n=!1;const s=[/miuibrowser/,/70.*HeyTapBrowser/i];for(const a of s)a.test(r)&&(n=!0);return!n}return!1}const pg=async()=>{let i=await or("sendonly");return navigator.userAgent.includes("VivoBrowser")&&(i=await or("sendonly")),Me.h264encode=$a(i),Me.vp8encode=i.indexOf("vp8")>-1,Me},fg=async()=>{let i=await or("recvonly");return navigator.userAgent.includes("VivoBrowser")&&(i=await or("recvonly")),Me.h264decode=$a(i),Me.vp8decode=i.indexOf("vp8")>-1,Me},mg=async()=>{if(typeof Me.h264encode>"u")try{await pg()}catch{return!1}return Me.h264encode||!1},_g=async()=>{if(typeof Me.h264decode>"u")try{await fg()}catch{return!1}return Me.h264decode||!1},ue=new nt("PCConnect"),ss=class ss{constructor(e,t,r){this._pc=null,this._ms=new MediaStream,this._signalUrl="",this._videoTransceiver=null,this._audioTransceiver=null,this._opts=void 0,this._sessionId=Date.now(),this._signalUrl=e,this._opts=t,this._onConnectStateChange=r}get isPushing(){var e,t,r,n;return!!((t=(e=this._videoTransceiver)==null?void 0:e.sender)!=null&&t.track||(n=(r=this._audioTransceiver)==null?void 0:r.sender)!=null&&n.track)}get videoSenderTrackStats(){var e,t,r,n;return{track_enabled:(t=(e=this._videoTransceiver)==null?void 0:e.sender.track)==null?void 0:t.enabled,track_muted:(n=(r=this._videoTransceiver)==null?void 0:r.sender.track)==null?void 0:n.muted}}get pushUrl(){return this._signalUrl}get sessionId(){return this._sessionId}async publish(e,t,r){var l;const n=new RTCPeerConnection;this._pc=n,this._bindRTCEvent();const s=e.filter(h=>(h==null?void 0:h.kind)==="audio")[0],a=e.filter(h=>(h==null?void 0:h.kind)==="video")[0];s&&this._ms.addTrack(s),a&&this._ms.addTrack(a),this._audioTransceiver=n.addTransceiver(s||"audio",{direction:"sendonly",sendEncodings:[{maxBitrate:t[0]}],streams:[this._ms]}),ue.log("add track to pc,",s),this._videoTransceiver=n.addTransceiver(a||"video",{direction:"sendonly",sendEncodings:[{maxBitrate:t[1]}],streams:[this._ms]}),ue.log("add track to pc,",a);const o=await n.createOffer();ue.groupCollapsed("local offer"),ue.log(o.sdp);const d=Gt.parse(o.sdp);d.media.forEach(h=>{h.type==="audio"?ug(h):h.type==="video"&&(dg(h),Ha(h,"software"),hg(h,t[1]))}),o.sdp=Gt.write(d),ue.log("local offer modified"),ue.log(o.sdp),await n.setLocalDescription(o);const c=await ja(this._signalUrl,{method:"POST",mode:"cors",body:JSON.stringify({sessionId:""+this._sessionId,version:"1.0-html",localSdp:o,metadata:{platform:"Web"}})},{...this._opts,timeout:r!=null&&r.isReconnect?10*Io:(l=this._opts)==null?void 0:l.timeout});if((c==null?void 0:c.code)!==200)throw{code:c.code,message:c.message};ue.log("remote answer:"),ue.log(c.remoteSdp.sdp);const u=Gt.parse(c.remoteSdp.sdp);if(u.media.forEach(h=>{var p;(p=h.fingerprint)!=null&&p.hash&&(h.fingerprint.hash=h.fingerprint.hash.toUpperCase())}),c.remoteSdp.sdp=Gt.write(u),ue.log("remote answer modified"),ue.log(c.remoteSdp.sdp),ue.groupEnd(),n.connectionState==="closed"){ue.log("PeerConnection is closed, skipping setRemoteDescription");return}O(I.PUSH_SDP_INFO,{offer_sdp:o.sdp,answer_sdp:c.remoteSdp.sdp}),await n.setRemoteDescription(c.remoteSdp)}updateVideoEncodeType(e){var s,a;const t=this._pc,r=(s=t==null?void 0:t.localDescription)==null?void 0:s.sdp,n=(a=t==null?void 0:t.remoteDescription)==null?void 0:a.sdp;if(r&&n){const o=Gt.parse(n);o.media.forEach(d=>{d.type==="video"&&Ha(d,e)}),t.setLocalDescription(t.localDescription),t.setRemoteDescription({type:"answer",sdp:Gt.write(o)})}}async updatePublish(e,t){var s,a;let r;t==="video"?r=this._videoTransceiver:r=this._audioTransceiver;const n=(s=r==null?void 0:r.sender)==null?void 0:s.track;(n==null?void 0:n.id)!==(e==null?void 0:e.id)&&(await((a=r==null?void 0:r.sender)==null?void 0:a.replaceTrack(e)),ue.log(`replace ${t} track done! ${n==null?void 0:n.label} -> ${e==null?void 0:e.label}`))}applyBitrate(e,t,r){var a,o,d;const n=t==="video"?(a=this._videoTransceiver)==null?void 0:a.sender:(o=this._audioTransceiver)==null?void 0:o.sender;if(!n)return;const s=n.getParameters();s.encodings=(d=s.encodings)!=null&&d.length?s.encodings:[{}],r?s.encodings[0].minBitrate=e:s.encodings[0].maxBitrate=e,n.setParameters(s),ue.log(`set bitrate for ${t}, ${e} bps, min:${r}`)}unpublish(){var e,t;(e=this._pc)==null||e.getSenders().forEach(r=>{var n;(n=this._pc)==null||n.removeTrack(r)}),(t=this._pc)==null||t.close(),this._audioTransceiver=null,this._videoTransceiver=null,this._pc=null,ue.log("close pc!")}getStats(){var e,t;return Mn((e=this._audioTransceiver)==null?void 0:e.sender,(t=this._videoTransceiver)==null?void 0:t.sender)}getStatsSnapshoot(e){var t,r;return ig(e||100,(t=this._audioTransceiver)==null?void 0:t.sender,(r=this._videoTransceiver)==null?void 0:r.sender)}_bindRTCEvent(){const e=this._pc;e==null||e.addEventListener("connectionstatechange",()=>{ue.log("onconnectionstatechange:",e.connectionState),this._onConnectStateChange(e.connectionState)})}};ss.isSupported=async()=>{try{return lg()||!window.RTCPeerConnection||!window.RTCPeerConnection.prototype.addTransceiver||!window.RTCPeerConnection.prototype.createDataChannel?!1:await _g()&&await mg()}catch{return!1}};let ar=ss;var st=(i=>(i.OnError="onerror",i.OnConnectClosed="onconnectclosed",i.OnFirstFramePushed="onfirstframepushed",i))(st||{}),ot=(i=>(i.Video="video",i.Audio="audio",i))(ot||{}),Se=(i=>(i.Init="init",i.AvExist="avexist",i.VideoFrame="videoframe",i.MockVideoEncode="mockvideoencode",i.AudioFrame="audioframe",i.AdjustBitrate="adjustbitrate",i.Publish="publish",i.UnPublish="unpublish",i.Download="download",i.GetStats="getstats",i.EncodeConfig="encodeconfig",i))(Se||{}),bt=(i=>(i.Ready="ready",i.Error="error",i.FirstFramePushed="firstframepushed",i.Flvfile="flvfile",i.STATS="stats",i.Close="close",i))(bt||{}),Pn={exports:{}},qa;function gg(){return qa||(qa=1,function(i){var e=Object.prototype.hasOwnProperty,t="~";function r(){}Object.create&&(r.prototype=Object.create(null),new r().__proto__||(t=!1));function n(d,c,u){this.fn=d,this.context=c,this.once=u||!1}function s(d,c,u,l,h){if(typeof u!="function")throw new TypeError("The listener must be a function");var p=new n(u,l||d,h),f=t?t+c:c;return d._events[f]?d._events[f].fn?d._events[f]=[d._events[f],p]:d._events[f].push(p):(d._events[f]=p,d._eventsCount++),d}function a(d,c){--d._eventsCount===0?d._events=new r:delete d._events[c]}function o(){this._events=new r,this._eventsCount=0}o.prototype.eventNames=function(){var c=[],u,l;if(this._eventsCount===0)return c;for(l in u=this._events)e.call(u,l)&&c.push(t?l.slice(1):l);return Object.getOwnPropertySymbols?c.concat(Object.getOwnPropertySymbols(u)):c},o.prototype.listeners=function(c){var u=t?t+c:c,l=this._events[u];if(!l)return[];if(l.fn)return[l.fn];for(var h=0,p=l.length,f=new Array(p);h<p;h++)f[h]=l[h].fn;return f},o.prototype.listenerCount=function(c){var u=t?t+c:c,l=this._events[u];return l?l.fn?1:l.length:0},o.prototype.emit=function(c,u,l,h,p,f){var v=t?t+c:c;if(!this._events[v])return!1;var m=this._events[v],b=arguments.length,y,_;if(m.fn){switch(m.once&&this.removeListener(c,m.fn,void 0,!0),b){case 1:return m.fn.call(m.context),!0;case 2:return m.fn.call(m.context,u),!0;case 3:return m.fn.call(m.context,u,l),!0;case 4:return m.fn.call(m.context,u,l,h),!0;case 5:return m.fn.call(m.context,u,l,h,p),!0;case 6:return m.fn.call(m.context,u,l,h,p,f),!0}for(_=1,y=new Array(b-1);_<b;_++)y[_-1]=arguments[_];m.fn.apply(m.context,y)}else{var E=m.length,z;for(_=0;_<E;_++)switch(m[_].once&&this.removeListener(c,m[_].fn,void 0,!0),b){case 1:m[_].fn.call(m[_].context);break;case 2:m[_].fn.call(m[_].context,u);break;case 3:m[_].fn.call(m[_].context,u,l);break;case 4:m[_].fn.call(m[_].context,u,l,h);break;default:if(!y)for(z=1,y=new Array(b-1);z<b;z++)y[z-1]=arguments[z];m[_].fn.apply(m[_].context,y)}}return!0},o.prototype.on=function(c,u,l){return s(this,c,u,l,!1)},o.prototype.once=function(c,u,l){return s(this,c,u,l,!0)},o.prototype.removeListener=function(c,u,l,h){var p=t?t+c:c;if(!this._events[p])return this;if(!u)return a(this,p),this;var f=this._events[p];if(f.fn)f.fn===u&&(!h||f.once)&&(!l||f.context===l)&&a(this,p);else{for(var v=0,m=[],b=f.length;v<b;v++)(f[v].fn!==u||h&&!f[v].once||l&&f[v].context!==l)&&m.push(f[v]);m.length?this._events[p]=m.length===1?m[0]:m:a(this,p)}return this},o.prototype.removeAllListeners=function(c){var u;return c?(u=t?t+c:c,this._events[u]&&a(this,u)):(this._events=new r,this._eventsCount=0),this},o.prototype.off=o.prototype.removeListener,o.prototype.addListener=o.prototype.on,o.prefixed=t,o.EventEmitter=o,i.exports=o}(Pn)),Pn.exports}var vg=gg();const yg=ae(vg);var cr=(i=>(i[i.RTMP_INIT_FAIL=3e3]="RTMP_INIT_FAIL",i[i.AUDIO_ENCODER_INIT_FAIL=3001]="AUDIO_ENCODER_INIT_FAIL",i[i.AUDIO_RRNOISE_INIT_FAIL=3002]="AUDIO_RRNOISE_INIT_FAIL",i[i.AUDIO_ENCODE_FAIL=3003]="AUDIO_ENCODE_FAIL",i[i.VIDEO_ENCODE_CONFIGURE_FAIL=3004]="VIDEO_ENCODE_CONFIGURE_FAIL",i[i.VIDEO_ENCODE_FAIL=3005]="VIDEO_ENCODE_FAIL",i[i.WTP_OPEN_FAIL=3006]="WTP_OPEN_FAIL",i[i.WTP_CONNECT_FAIL=3007]="WTP_CONNECT_FAIL",i[i.WORKER_ERROR=3008]="WORKER_ERROR",i))(cr||{});class Ka extends Error{constructor(e,t,r){super(),this.code=e,this.message=t,r&&(this.ext=r),this.toJson=()=>({code:this.code,message:this.message,ext:this.ext})}}function Wa(i,e,t){return new Ka(i,e,t)}let Nt=(Ke=class{constructor(e){this.group=(...t)=>{this._enabled&&console.group(`[${this._prefix}]: `,...t)},this.groupCollapsed=(...t)=>{this._enabled&&console.groupCollapsed(`[${this._prefix}]: `,...t)},this.groupEnd=()=>{this._enabled&&console.groupEnd()},this.log=(...t)=>{this._enabled&&console.log(`[${this._prefix}]: `,...t)},this.warn=(...t)=>{this._enabled&&console.warn(`[${this._prefix}]: `,...t)},this.error=(...t)=>{this._enabled&&console.error(`[${this._prefix}]: `,...t)},this.table=(...t)=>{this._enabled&&console.table(...t)},this._prefix=e}get _enabled(){return Ke.enable}get _enableLong(){return Ke.enableLong}get long(){return this._enableLong}},Ke.enable=!1,Ke.enableLong=!1,Ke);const Ee=new Nt("RTMP_Capture");class bg{constructor(e){this._videoFirstframeCaptured=!1,this._audioFirstframeCaptured=!1,this._videoProcessorReader=null,this._audioProcessorReader=null,this._bridge=e}get audioTrack(){return this._bridge.audioMsTrack}get videoTrack(){return this._bridge.videoMsTrack}start(){this._startVideoCapture(),this._startAudioCapture()}restartCapture(e){if(Ee.log(`replace ${e} track`),e===ot.Video){if(this._videoProcessorReader){this._videoProcessorReader.cancel().finally(()=>{this._startVideoCapture()});return}this._startVideoCapture();return}if(this._audioProcessorReader){this._audioProcessorReader.cancel().finally(()=>{this._startAudioCapture()});return}this._startAudioCapture()}async _startVideoCapture(){var n;if(!this.videoTrack){Ee.log("no video track to capture");return}if(this.videoTrack.readyState!=="live"){Ee.warn("video track not live");return}const e=new MediaStreamTrackProcessor(this.videoTrack);e.track=this.videoTrack;const t=e.readable.getReader();this._videoProcessorReader=t,Ee.log("start capture video frame",this.videoTrack);let r;for(;;){r&&clearInterval(r),r=setTimeout(()=>{Ee.warn("long time no capture output"),this._bridge._postMockVideoEncodeFlag()},1500);const s=await t.read();if(clearInterval(r),this._videoFirstframeCaptured||(this._videoFirstframeCaptured=!0,Ee.log("video first frame captured")),s.done||!s.value){(n=s.value)==null||n.close();break}this._bridge._postVideoFrame(s.value,this.videoTrack.getSettings())}clearInterval(r),this._videoFirstframeCaptured=!1,this._videoProcessorReader=null,Ee.log("video track read done!",e.track)}async _startAudioCapture(){if(!this.audioTrack){Ee.log("no audio track to capture");return}if(this.audioTrack.readyState!=="live"){Ee.warn("audio track not live");return}const e=new MediaStreamTrackProcessor(this.audioTrack);e.track=this.audioTrack;const t=e.readable.getReader();for(this._audioProcessorReader=t,Ee.log("start capture audio frame");;){const r=await t.read();if(this._audioFirstframeCaptured||(this._audioFirstframeCaptured=!0,Ee.log("audio first frame captured")),r.done||!r.value)break;this._bridge._postAudioFrame(r.value,this.audioTrack.getSettings())}this._audioFirstframeCaptured=!1,this._audioProcessorReader=null,Ee.log("audio track read done!",e.track)}destroy(){var e,t;(e=this._audioProcessorReader)==null||e.cancel().catch(()=>{}),(t=this._videoProcessorReader)==null||t.cancel().catch(()=>{})}}const Ja='(function(){"use strict";var l=(i=>(i.OnVideoCaptured="onvideocaptured",i.OnAudioCaptured="onaudiocaptured",i.OnVideoCaptureNoOutput="onvideocapturenooutput",i.OnVideoEncoded="onvideoencoded",i.OnAudioEncoded="onaudioencoded",i.OnEncodedFrame="onencodedframe",i.OnPacketed="onpacketed",i.OnUpstreamFeedback="onupstreamfeedback",i.OnBitrateChanged="onbitratechanged",i))(l||{}),O=(i=>(i.OnError="onerror",i.OnConnectClosed="onconnectclosed",i.OnFirstFramePushed="onfirstframepushed",i))(O||{}),I=(i=>(i.Video="video",i.Audio="audio",i))(I||{}),v=(i=>(i.Init="init",i.AvExist="avexist",i.VideoFrame="videoframe",i.MockVideoEncode="mockvideoencode",i.AudioFrame="audioframe",i.AdjustBitrate="adjustbitrate",i.Publish="publish",i.UnPublish="unpublish",i.Download="download",i.GetStats="getstats",i.EncodeConfig="encodeconfig",i))(v||{}),w=(i=>(i.Ready="ready",i.Error="error",i.FirstFramePushed="firstframepushed",i.Flvfile="flvfile",i.STATS="stats",i.Close="close",i))(w||{});function $(i){return i&&i.__esModule&&Object.prototype.hasOwnProperty.call(i,"default")?i.default:i}var k={exports:{}},U;function q(){return U||(U=1,function(i){var t=Object.prototype.hasOwnProperty,e="~";function s(){}Object.create&&(s.prototype=Object.create(null),new s().__proto__||(e=!1));function r(u,a,n){this.fn=u,this.context=a,this.once=n||!1}function o(u,a,n,h,m){if(typeof n!="function")throw new TypeError("The listener must be a function");var g=new r(n,h||u,m),f=e?e+a:a;return u._events[f]?u._events[f].fn?u._events[f]=[u._events[f],g]:u._events[f].push(g):(u._events[f]=g,u._eventsCount++),u}function _(u,a){--u._eventsCount===0?u._events=new s:delete u._events[a]}function c(){this._events=new s,this._eventsCount=0}c.prototype.eventNames=function(){var a=[],n,h;if(this._eventsCount===0)return a;for(h in n=this._events)t.call(n,h)&&a.push(e?h.slice(1):h);return Object.getOwnPropertySymbols?a.concat(Object.getOwnPropertySymbols(n)):a},c.prototype.listeners=function(a){var n=e?e+a:a,h=this._events[n];if(!h)return[];if(h.fn)return[h.fn];for(var m=0,g=h.length,f=new Array(g);m<g;m++)f[m]=h[m].fn;return f},c.prototype.listenerCount=function(a){var n=e?e+a:a,h=this._events[n];return h?h.fn?1:h.length:0},c.prototype.emit=function(a,n,h,m,g,f){var F=e?e+a:a;if(!this._events[F])return!1;var d=this._events[F],C=arguments.length,B,p;if(d.fn){switch(d.once&&this.removeListener(a,d.fn,void 0,!0),C){case 1:return d.fn.call(d.context),!0;case 2:return d.fn.call(d.context,n),!0;case 3:return d.fn.call(d.context,n,h),!0;case 4:return d.fn.call(d.context,n,h,m),!0;case 5:return d.fn.call(d.context,n,h,m,g),!0;case 6:return d.fn.call(d.context,n,h,m,g,f),!0}for(p=1,B=new Array(C-1);p<C;p++)B[p-1]=arguments[p];d.fn.apply(d.context,B)}else{var fe=d.length,R;for(p=0;p<fe;p++)switch(d[p].once&&this.removeListener(a,d[p].fn,void 0,!0),C){case 1:d[p].fn.call(d[p].context);break;case 2:d[p].fn.call(d[p].context,n);break;case 3:d[p].fn.call(d[p].context,n,h);break;case 4:d[p].fn.call(d[p].context,n,h,m);break;default:if(!B)for(R=1,B=new Array(C-1);R<C;R++)B[R-1]=arguments[R];d[p].fn.apply(d[p].context,B)}}return!0},c.prototype.on=function(a,n,h){return o(this,a,n,h,!1)},c.prototype.once=function(a,n,h){return o(this,a,n,h,!0)},c.prototype.removeListener=function(a,n,h,m){var g=e?e+a:a;if(!this._events[g])return this;if(!n)return _(this,g),this;var f=this._events[g];if(f.fn)f.fn===n&&(!m||f.once)&&(!h||f.context===h)&&_(this,g);else{for(var F=0,d=[],C=f.length;F<C;F++)(f[F].fn!==n||m&&!f[F].once||h&&f[F].context!==h)&&d.push(f[F]);d.length?this._events[g]=d.length===1?d[0]:d:_(this,g)}return this},c.prototype.removeAllListeners=function(a){var n;return a?(n=e?e+a:a,this._events[n]&&_(this,n)):(this._events=new s,this._eventsCount=0),this},c.prototype.off=c.prototype.removeListener,c.prototype.addListener=c.prototype.on,c.prefixed=e,c.EventEmitter=c,i.exports=c}(k)),k.exports}var z=q(),H=$(z);const N=class N{constructor(t){this.group=(...e)=>{this._enabled&&console.group(`[${this._prefix}]: `,...e)},this.groupCollapsed=(...e)=>{this._enabled&&console.groupCollapsed(`[${this._prefix}]: `,...e)},this.groupEnd=()=>{this._enabled&&console.groupEnd()},this.log=(...e)=>{this._enabled&&console.log(`[${this._prefix}]: `,...e)},this.warn=(...e)=>{this._enabled&&console.warn(`[${this._prefix}]: `,...e)},this.error=(...e)=>{this._enabled&&console.error(`[${this._prefix}]: `,...e)},this.table=(...e)=>{this._enabled&&console.table(...e)},this._prefix=t}get _enabled(){return N.enable}get _enableLong(){return N.enableLong}get long(){return this._enableLong}};N.enable=!1,N.enableLong=!1;let E=N;function S(i){i=i.filter(Boolean);const t=new Uint8Array(i.reduce((s,r)=>s+r.byteLength,0));let e=0;return i.forEach(s=>{t.set(s,e),e+=s.byteLength}),t}const A={codec:"avc1.4DE033",MaxCachedFrameSize:100,RealSpeedPercent:.8,UplinkBitrateCheckInterval:60*1e3,VideoBitrateDefault:1e6,AudioBitrateDefault:68e3,gopSize:90,sampleRate:48e3,channel:2,audioEncoderPath:"https://lf-unpkg.volccdn.com/obj/vcloudfe/sdk/Web_push/1.0.1/1735619140327/pcm2aac.js",audioEncoderWasmPath:"https://lf-unpkg.volccdn.com/obj/vcloudfe/sdk/Web_push/1.0.2/1735619208418/pcm2aac.wasm",ignoreRelPublish:!1},T=new E("RTMP_AudioEncoder");class j{constructor(t){this._encodedFrameCount=0,this._ready=!1,this._lastFrame=null,this._aacOutput=(e,s)=>{const r=this._module.HEAPU8.subarray(e,e+s);if(!this._lastFrame)return;this._encodedFrameCount++;const{props:o}=this._lastFrame,_={buffer:new Uint8Array(r),props:{timestamp:parseInt(o.timestamp/1e3),originTs:parseInt(o.timestamp/1e3)}};this._core.emit(l.OnAudioEncoded,_)},this._core=t}async init(){const t=await fetch(A.audioEncoderPath).then(_=>_.text());new Function(`self.exports={};${t}`)();const e=self.exports.m;let s,r;const o=new Promise((_,c)=>{r=_,s=c});return e({instantiateWasm:function(_,c){fetch(A.audioEncoderWasmPath).then(u=>u.arrayBuffer()).then(u=>WebAssembly.instantiate(u,_)).then(function(u){return c(u.instance)}).then(()=>{r(),T.log("aac module inited")}).catch(u=>{s(u)})}}).then(_=>{const c=_.addFunction(this._aacOutput,"vii");_._init_callback(c),this._module=_}).catch(s),o}rnnoise(t){var s;const e=t.length;for(let r=0;r<e;r++)t[r]=t[r]*32768;(s=this._rnnoiseModule)==null||s.processFrame(t);for(let r=0;r<e;r++)t[r]=t[r]/32768}updateConfigure(){this._module._flush(),this._module._free_encoder(),this._ready=!1}encode(t){if(!this._ready){const o=this._start_encoder();if(o<0)throw new Error(`init aac encoder error, code:${o}`)}this._lastFrame=t;const e=t.buffer.buffer,s=this._module._malloc(e.byteLength);this._module.HEAPU8.subarray(s,s+e.byteLength).set(new Uint8Array(e));const r=this._module._encode_one_frame(s);if(r<0)throw new Error(`encode aac frame error, code:${r}`)}_start_encoder(){const t=this._core.getSetting(),e=this._module._init_encoder(t.sampleRate,t.channel,t.audioBitrate);if(e<0)return e;this._ready=!0,T.log(`init encoder: sampleRate=${t.sampleRate}, channel:${t.channel}, bitrate:${t.audioBitrate}`)}destroy(){var t;(t=this._module)==null||t._free_encoder()}}const P=1024;class M{constructor(){this._queue=[],this._sampleCount=0}compose(t){if(this._queue.push(t),this._sampleCount+=t.data.audioData.numberOfFrames,this._sampleCount>=P)return this._doCompose()}_doCompose(){const t=new Float32Array(P);let e=0,s=P;const r=this._queue[0];for(;;){const o=this._queue[0];if(!o)break;const _=Math.min(s,o.data.audioData.numberOfFrames-o.offset,480),c=o.data.buffer.slice(o.offset,o.offset+_);if(o.offset+=_,o.offset>=o.data.audioData.numberOfFrames&&this._queue.shift(),s-=_,this._sampleCount-=_,t.set(c,e),e+=_,s<=0)break}return{buffer:t,props:{timestamp:r.data.audioData.timestamp,sampleRate:r.data.audioData.sampleRate,numberOfChannels:r.data.audioData.numberOfChannels}}}}var y=(i=>(i[i.RTMP_INIT_FAIL=3e3]="RTMP_INIT_FAIL",i[i.AUDIO_ENCODER_INIT_FAIL=3001]="AUDIO_ENCODER_INIT_FAIL",i[i.AUDIO_RRNOISE_INIT_FAIL=3002]="AUDIO_RRNOISE_INIT_FAIL",i[i.AUDIO_ENCODE_FAIL=3003]="AUDIO_ENCODE_FAIL",i[i.VIDEO_ENCODE_CONFIGURE_FAIL=3004]="VIDEO_ENCODE_CONFIGURE_FAIL",i[i.VIDEO_ENCODE_FAIL=3005]="VIDEO_ENCODE_FAIL",i[i.WTP_OPEN_FAIL=3006]="WTP_OPEN_FAIL",i[i.WTP_CONNECT_FAIL=3007]="WTP_CONNECT_FAIL",i[i.WORKER_ERROR=3008]="WORKER_ERROR",i))(y||{});class W extends Error{constructor(t,e,s){super(),this.code=t,this.message=e,s&&(this.ext=s),this.toJson=()=>({code:this.code,message:this.message,ext:this.ext})}}function b(i,t,e){return new W(i,t,e)}class G{constructor(t){this._audioFrameQueue=new M,this.encode=e=>{const s=new Float32Array(e.numberOfFrames);e.copyTo(s,{planeIndex:0,frameOffset:0,frameCount:e.numberOfFrames});const r=this._audioFrameQueue.compose({offset:0,data:{audioData:e,buffer:s}});if(r)try{this._encoder.encode(r)}catch(o){this._core.emit(O.OnError,b(y.AUDIO_ENCODE_FAIL,o.message))}},this._core=t,this._encoder=new j(t)}async init(){try{await this._encoder.init()}catch(t){throw b(y.AUDIO_ENCODER_INIT_FAIL,t.message)}}setConfiguration(t){const e=Object.assign({},this._core.getSetting(),{audioBitrate:t});this._core.updateSetting(e),this._encoder.updateConfigure()}destroy(){this._encoder.destroy()}}const x=new E("RTMP_VEncoder");class J{constructor(t){this._encoder=null,this._queue=[],this._encodeTimer=0,this._loopEncodeTimer=0,this._frameIndex=0,this._gopSize=0,this._encodedFrameCount=0,this._lastFrame=null,this._startTimer=()=>{this._clearEncodeTimer(),this._encodeTimer=setInterval(()=>{const e=this._queue.shift();if(!(!e||!this._encoder||this._encoder.state==="closed"))try{this._encoder.encode(e,{keyFrame:this._frameIndex%this._gopSize===0}),this._frameIndex++,this._lastFrame&&this._lastFrame.close(),this._lastFrame=e}catch(s){x.log("encode frame error",s)}},5)},this._core=t}configurate(t){return this._gopSize=t.gopSize,this._encoder?this.flush().then(()=>this._configure(t)):this._configure(t)}_configure(t){return this._clearEncodeTimer(),x.log("start config encoder",t),VideoEncoder.isConfigSupported(t).then(e=>{if(!e.supported)throw new Error(`VideoEncoder not support config, ${JSON.stringify(t)}`);this._encoder=new VideoEncoder({output:(s,r)=>{const o=new Uint8Array(s.byteLength);s.copyTo(o),this._emitFrame(o,s,r)},error:s=>{this._clearEncodeTimer(),this._core.emit(O.OnError,b(y.VIDEO_ENCODE_FAIL,s.message))}}),this._encoder.configure(t),x.log("encoder configured")}).then(this._startTimer).catch(e=>{throw b(y.VIDEO_ENCODE_CONFIGURE_FAIL,e.message)})}_emitFrame(t,e,s){this._encodedFrameCount++,this._core.emit(l.OnVideoEncoded,{buffer:t,props:{byteLength:e.byteLength,duration:e.duration,timestamp:parseInt(e.timestamp/1e3),originTs:parseInt(e.timestamp/1e3),type:e.type},cfg:s.decoderConfig})}_clearEncodeTimer(){clearInterval(this._encodeTimer)}_clearLoopEncodeTimer(){this._loopEncodeTimer&&clearInterval(this._loopEncodeTimer)}flush(){return this._encoder?this._encoder.flush().then(()=>{var t;this._clearEncodeTimer(),(t=this._encoder)==null||t.close(),this._frameIndex=0,this._encoder=null,x.log("encoder flush & closed")}).catch(t=>{console.log("encoder flush & close error:",t)}):Promise.resolve()}encode(t){this._clearLoopEncodeTimer(),this._queue.push(t)}startLoop(t){if(!this._lastFrame)return;const e=Math.floor(1e3/t*1e3);x.log("start encode last frame looped, ",t,"increment:",e),this._loopEncodeTimer=setInterval(()=>{if(!this._lastFrame)return;const s=new VideoFrame(this._lastFrame,{duration:e,timestamp:(this._lastFrame.timestamp||0)+e});this._queue.push(s)},Math.floor(1e3/t))}destroy(){this._queue.forEach(t=>t.close()),this._lastFrame&&this._lastFrame.close(),this._clearEncodeTimer(),this._clearLoopEncodeTimer(),this.flush()}}const Q=new E("RTMP_VideoEncode");class K{constructor(t){this._core=t,this._encoder=new J(t)}async setConfiguration(t={}){const e=Object.assign({},this._core.getSetting(),t),s={width:e.width,height:e.height,displayWidth:e.width,displayHeight:e.height,bitrate:e.videoBitrate,framerate:Math.floor(e.frameRate),codec:e.codec,gopSize:e.gopSize,hardwareAcceleration:e.hardwareAcceleration};this._core.updateSetting(e),Q.log("set Configuration:",s,t);try{await this._encoder.configurate(s)}catch(r){this._core.emit(O.OnError,r)}}encode(t){this._encoder.encode(t)}startLoopEncodeLastFrame(){this._encoder.startLoop(this._core.getSetting().frameRate)}flushEncoder(){this._encoder.flush()}destroy(){this._encoder.destroy()}}const V=new E("RTMP_AVSync");class Z{constructor(t){this._videoFrameGot=!1,this._videoBaseDts=0,this._audioBaseDts=0,this._videoNextDts=0,this._videoLastDts=0,this._audioNextDts=0,this._lastVideoReceived=0,this._core=t}get avExist(){return this._core.getSetting().hasVideo&&this._core.getSetting().hasAudio}get videoRefDuration(){return parseInt(1e3/this._core.getSetting().frameRate)}get audioRefDuration(){return parseInt(1024/this._core.getSetting().sampleRate*1e3)}addVideoFrame(t){this._videoFrameGot||(this._videoFrameGot=!0);const e=t.props;if(Math.abs(this._videoNextDts-e.timestamp-this._videoBaseDts)>1e3){const r=Date.now()-this._lastVideoReceived;this._videoNextDts=this._videoNextDts===this._audioNextDts?this._videoNextDts+this.videoRefDuration:this._audioNextDts||this._videoNextDts+r,this._videoBaseDts=this._videoNextDts-e.timestamp,V.warn(`video stream timestamp breaked! dts:${this._videoNextDts} -> ${e.timestamp}, videoBaseDts=${this._videoBaseDts}, deltaToLastFrame=${r}`)}e.timestamp=e.timestamp+this._videoBaseDts;const s=e.timestamp-this._videoLastDts;return s>100&&V.warn("video frame large gap",s),this._videoLastDts=this._videoNextDts=e.timestamp,V.long&&V.log(`V frame, dts: ${e.timestamp}, originDts:${e.originTs}, videoBaseDts=${this._videoBaseDts}, type=${e.type}, duration=${s}`),this._lastVideoReceived=Date.now(),this._core.emit(l.OnEncodedFrame,I.Video,t),{size:t.buffer.length,duration:s,key:t.props.type==="key"}}addAudioFrame(t){if(this.avExist&&!this._videoFrameGot)return;const e=t.props;return this._audioBaseDts||(this._audioBaseDts=e.timestamp-this._videoNextDts),Math.abs(e.timestamp-this._audioBaseDts-this._audioNextDts)>1e3&&(this._audioBaseDts=this._audioNextDts+this.audioRefDuration-e.timestamp,V.warn(`audio stream timestamp breaked! dts:${this._audioNextDts} -> ${e.timestamp}, audioBaseDts=${this._audioBaseDts}`)),this._audioNextDts=e.timestamp=e.timestamp-this._audioBaseDts,V.long&&V.log(`A frame, dts: ${e.timestamp}, originDts:${e.originTs}`),this._core.emit(l.OnEncodedFrame,I.Audio,t),{size:t.buffer.length,duration:this.audioRefDuration}}}class X{constructor(){this._videoSize=0,this._videoDuration=0,this._videoBitrate=0,this._frameCount=0,this._fps=0,this._videoEncodedCount=0,this._keyCount=0,this._audioSize=0,this._audioDuration=0,this._audioBitrate=0,this._audioEncodedCount=0}get videoStats(){return{sendBitrate:this._videoBitrate,framesPerSecond:this._fps,framesEncoded:this._videoEncodedCount,keyFramesEncoded:this._keyCount}}get audioStats(){return{sendBitrate:this._audioBitrate,framesEncoded:this._audioEncodedCount}}addVideoSample({size:t,duration:e,key:s}){this._videoEncodedCount++,this._videoSize+=t,this._videoDuration+=e,this._frameCount++,s&&this._keyCount++,this._videoDuration>=1e3&&(this._videoBitrate=Math.floor(this._videoSize/this._videoDuration*8e3),this._fps=this._frameCount,this._frameCount=0,this._videoSize=0,this._videoDuration=0)}addAudioSample({size:t,duration:e}){this._audioEncodedCount++,this._audioSize+=t,this._audioDuration+=e,this._audioDuration>=1e3&&(this._audioBitrate=Math.floor(this._audioSize/this._audioDuration*1e3),this._audioSize=0,this._audioDuration=0)}}const Y=new E("RTMP_EncodeController");class ee{constructor(t){this._analyse=new X,this._gotFrame=!1,this._OnVideoCaptured=(e,s)=>{this._gotFrame=!0,this._videoSettingChanged(s)&&(Y.log("video track setting changed!",s),this._core.updateSetting({width:s.width,height:s.height,frameRate:s.frameRate,vDeviceId:s.deviceId}),this._videoEncode.setConfiguration()),this._videoEncode.encode(e)},this._OnVideoCaptureNoOutput=()=>{this._videoEncode.startLoopEncodeLastFrame()},this._OnAudioCaptured=e=>{this._gotFrame=!0,this._audioEncode.encode(e)},this._OnVideoEncoded=e=>{const s=this._avSync.addVideoFrame(e);this._analyse.addVideoSample(s)},this._OnAudioEncoded=e=>{if(!e.buffer.length)return;const s=this._avSync.addAudioFrame(e);s&&this._analyse.addAudioSample(s)},this._OnUpstreamFeedback=e=>{this._videoEncode.setConfiguration(e)},this._OnBitrateChanged=(e,s)=>{this._gotFrame&&(e===I.Video&&this._videoEncode.setConfiguration({videoBitrate:s}),e===I.Audio&&this._audioEncode.setConfiguration(s))},this._core=t,this._audioEncode=new G(t),this._videoEncode=new K(t),this._avSync=new Z(t),this._bindEvents()}getStats(){return{video:this._analyse.videoStats,audio:this._analyse.audioStats}}init(){return this._audioEncode.init()}_bindEvents(){this._core.on(l.OnVideoCaptured,this._OnVideoCaptured),this._core.on(l.OnAudioCaptured,this._OnAudioCaptured),this._core.on(l.OnVideoCaptureNoOutput,this._OnVideoCaptureNoOutput),this._core.on(l.OnVideoEncoded,this._OnVideoEncoded),this._core.on(l.OnAudioEncoded,this._OnAudioEncoded),this._core.on(l.OnUpstreamFeedback,this._OnUpstreamFeedback),this._core.on(l.OnBitrateChanged,this._OnBitrateChanged)}_videoSettingChanged(t){const e=this._core.getSetting();return t.width!==e.width||t.height!==e.height||Math.floor(t.frameRate)!==Math.floor(e.frameRate)||t.deviceId!==e.vDeviceId}destroy(){this._videoEncode.destroy(),this._audioEncode.destroy()}}var L=(i=>(i[i.AUDIO=8]="AUDIO",i[i.VIDEO=9]="VIDEO",i[i.SCRIPT_DATA=18]="SCRIPT_DATA",i))(L||{});const te=10,ie=1,se=7,oe={96e3:0,48e3:3,44100:4,22050:7,16e3:8,8e3:11};function re(i){const t=(i[4]&3)+1;let e;const s=[],r=[];let o=6;const _=i[5]&31;let c;for(let n=0;n<_;n++){if(c=i[o]<<8|i[o+1],o+=2,!c)continue;const h=i.subarray(o,o+c);o+=c,s.push(h)}const u=i[o];o++;let a;for(let n=0;n<u;n++)a=i[o]<<8|i[o+1],o+=2,a&&(r.push(i.subarray(o,o+a)),o+=a);return{sps:e,spsArr:s,ppsArr:r,nalUnitSize:t}}class ne{constructor(){this._cfg={hasVideo:!1,hasAudio:!1,sampleRate:48e3,channelCount:1},this._hasAudioSeqHeader=!1,this._hasVideoSeqHeader=!1}setConfig(t){this._cfg=Object.assign(this._cfg,t)}genHeader(){const t=[70,76,86,1,(this._cfg.hasAudio?1:0)<<2|(this._cfg.hasVideo?1:0),0,0,0,9,0,0,0,0];return new Uint8Array(t)}genSeqTag(t,e){let s;t===8?(s=this._genAudioTagPaylod(0,e),this._hasAudioSeqHeader=!0):(s=this._genVideoTagPayload(0,e),this._hasVideoSeqHeader=!0);const r=this._genTagHeader(t,s.length,e.props.timestamp),o=r.length+s.length;return S([r,s,new Uint8Array([o>>>24,o>>>16,o>>>8,o])])}genFrameTag(t,e){let s;t===8?s=this._genAudioTagPaylod(1,e):s=this._genVideoTagPayload(1,e);const r=this._genTagHeader(t,s.length,e.props.timestamp),o=r.length+s.length;return S([r,s,new Uint8Array([o>>>24,o>>>16,o>>>8,o])])}_genTagHeader(t,e,s){return new Uint8Array([t,e>>>16,e>>>8,e,s>>>16,s>>>8,s,s>>>24,0,0,0])}_genAudioTagPaylod(t,e){return S(t===0?[this._genAudioTagHeader(),this._genAudioSequenceHeader()]:[this._genAudioTagHeader(),this._genAudioData(e)])}_genAudioTagHeader(){return new Uint8Array([te<<4|12|ie<<1|this._cfg.channelCount-1])}_genAudioSequenceHeader(){const t=4096|oe[this._cfg.sampleRate]<<7|this._cfg.channelCount<<3;return new Uint8Array([0,t>>8,t])}_genAudioData(t){const e=new Uint8Array(1+t.buffer.length);return e.set([1],0),e.set(t.buffer,1),e}_genVideoTagPayload(t,e){return S(t===0?[this._genVideoTagHeader(e),this._genVideoSequenceHeader(e)]:[this._genVideoTagHeader(e),this._genVideoData(e)])}_genVideoTagHeader(t){return new Uint8Array([(t.props.type==="key"?1:2)<<4|se,this._hasVideoSeqHeader?1:0,0,0,0])}_genVideoSequenceHeader(t){return new Uint8Array(t.cfg.description)}_genVideoData(t){if(t.props.type==="delta")return t.buffer;const e=re(new Uint8Array(t.cfg.description)),s=e.spsArr[0].length,r=e.ppsArr[0].length;return S([new Uint8Array([0,0,s>>8,s%256]),e.spsArr[0],new Uint8Array([0,0,r>>8,r%256]),e.ppsArr[0],t.buffer])}}const ae=new E("RTMP_Packet");class de{constructor(t){this._firstFrame=!0,this._flv=new ne,this._OnEncodedFrame=(e,s)=>{if(this._firstFrame){const o=this._core.getSetting();this._flv.setConfig({hasVideo:o.hasVideo,hasAudio:o.hasAudio,sampleRate:o.sampleRate,channelCount:o.channel});const _=this._flv.genHeader();if(this._core.emit(l.OnPacketed,_),o.hasVideo){const c=this._flv.genSeqTag(L.VIDEO,s);this._core.emit(l.OnPacketed,c)}if(o.hasAudio){const c=this._flv.genSeqTag(L.AUDIO,s);this._core.emit(l.OnPacketed,c)}this._firstFrame=!1,ae.log("first frame encoded & packed")}const r=this._flv.genFrameTag(e==="video"?L.VIDEO:L.AUDIO,s);this._core.emit(l.OnPacketed,r,s.props.type==="key")},this._core=t,this._bindEvents()}_bindEvents(){this._core.on(l.OnEncodedFrame,this._OnEncodedFrame)}destroy(){}}class he{constructor(){this._lastDot=0,this._totalSize=0,this._speed=[]}addSample(t){this._lastDot||(this._lastDot=Date.now()),this._totalSize+=t;const e=Date.now()-this._lastDot;e>=500&&(this._addSpeedSample(this._totalSize/e*8e3),this._totalSize=0,this._lastDot=Date.now())}_addSpeedSample(t){this._speed.push(t),this._speed=this._speed.slice(-6)}reset(){this._speed=[]}getUpSpeed(){return this._speed.length?parseInt(this._speed.reduce((t,e)=>t+=e,0)/this._speed.length):0}}const D=new E("RTMP_Wtp");class ce{constructor(t){this._queue=[],this._url="",this._connectClosed=!1,this._upSpeed=new he,this._transport=null,this._writer=null,this._inWriting=!1,this._inAdjustEncode=!1,this._increaseTimer=0,this._firstFramePushed=!1,this._core=t,this._bindEvents()}get sendSpeed(){return this._upSpeed.getUpSpeed()}getStats(){var t;return(t=this._transport)==null?void 0:t.getStats()}_bindEvents(){this._core.on(l.OnPacketed,(t,e=!1)=>{this._checkDecreaseBitrate(),this._checkDeleteCache(e),this._queue.push(t),this._inWriting||this._write()})}_checkDecreaseBitrate(){if(this._inAdjustEncode)return;const t=this._upSpeed.getUpSpeed();if(!t||this._queue.length<A.MaxCachedFrameSize)return;D.log(`up speed: ${t} low, ajust encode setting`);const e=this._core.getSetting();this._core.emit(l.OnUpstreamFeedback,{videoBitrate:t*A.RealSpeedPercent,width:e.width,height:e.height,frameRate:e.frameRate}),this._inAdjustEncode=!0,this._checkIncreaseBitrate()}_checkIncreaseBitrate(){D.log("add timer to check uplink speed increased"),clearInterval(this._increaseTimer),this._increaseTimer=setTimeout(()=>{const t=this._core.getSetting();D.log(`set encode bitrate to specified ${t.originVideoBitrate}`),this._core.emit(l.OnUpstreamFeedback,{videoBitrate:t.originVideoBitrate,width:t.width,height:t.height,frameRate:t.frameRate}),this._inAdjustEncode=!0},A.UplinkBitrateCheckInterval)}_checkDeleteCache(t){this._inAdjustEncode&&t&&(D.log(`ajust encode setting finish, delete cached ${this._queue.length} frame`),this._queue=[],this._upSpeed.reset(),this._inAdjustEncode=!1)}async start(t){this._url=t;try{await this._connect()}catch(e){throw b(y.WTP_OPEN_FAIL,e.message)}}async _connect(){const t=new WebTransport(this._url);let e;t.closed.then(()=>{D.log("webtransport closed")}).catch(r=>{e=r.message,D.log("webtransport closed due to",r)}).finally(()=>{this._connectClosed=!0,this._core.emit(O.OnConnectClosed,e),this._core.emit(O.OnError,b(y.WTP_CONNECT_FAIL,e))}),await t.ready,this._transport=t;const s=await t.createBidirectionalStream();this._writer=s.writable.getWriter(),this._write(),D.log("transport opend")}async _write(){var e;if(!this._writer)return;this._inWriting=!0;const t=this._queue.shift();if(!t){this._inWriting=!1;return}await((e=this._writer)==null?void 0:e.write(t)),this._firstFramePushed||(this._firstFramePushed=!0,this._core.emit(O.OnFirstFramePushed),D.log("first frame pushed")),this._upSpeed.addSample(t.length);try{await this._write()}catch(s){D.log("writer error:",s)}}getFile(){return S(this._queue)}destroy(){var t,e;clearTimeout(this._increaseTimer),this._connectClosed||(t=this._writer)==null||t.close(),this._writer=null,(e=this._transport)==null||e.close(),this._transport=null}}const ue=new E("LiveRTMP");class _e extends H{constructor(){super(),this._ts=0,this._setting={codec:A.codec,hardwareAcceleration:"prefer-hardware",width:-1,height:-1,frameRate:-1,sampleRate:A.sampleRate,channel:A.channel,gopSize:A.gopSize,videoBitrate:A.VideoBitrateDefault,originVideoBitrate:A.VideoBitrateDefault,audioBitrate:A.AudioBitrateDefault,hasAudio:!1,hasVideo:!1,vDeviceId:"",aDeviceId:""},this._encode=new ee(this),this._packet=new de(this),this._transport=new ce(this)}async checkVideoHardwareAcceleration(){const t=["prefer-hardware","prefer-software","no-preference"],e=this.getSetting(),s={codec:e.codec,width:1280,height:720,framerate:15,bitrate:e.videoBitrate};for(const r of t)try{if((await VideoEncoder.isConfigSupported({...s,hardwareAcceleration:r})).supported)return this.updateSetting({hardwareAcceleration:r,originVideoBitrate:e.originVideoBitrate}),Promise.resolve()}catch{throw b(y.VIDEO_ENCODE_CONFIGURE_FAIL,`VideoEncoder not support hardwareAcceleration, ${JSON.stringify({...s,hardwareAcceleration:r})}`)}throw b(y.VIDEO_ENCODE_CONFIGURE_FAIL,"VideoEncoder not support hardwareAcceleration")}async ready(){await Promise.all([this.checkVideoHardwareAcceleration(),this._encode.init()])}getSetting(){return this._setting}updateSetting(t){this._setting=Object.assign({},this._setting,t)}videoFrameCaptured(t,e){this.emit(l.OnVideoCaptured,t,e)}audioFrameCaptured(t,e){this.emit(l.OnAudioCaptured,t,e)}startMockVideoEncode(){this.emit(l.OnVideoCaptureNoOutput)}adjustBitrate(t,e){t===I.Video&&this.updateSetting({videoBitrate:e,originVideoBitrate:e}),t===I.Audio&&this.updateSetting({audioBitrate:e}),this.emit(l.OnBitrateChanged,t,e)}avExist(t,e){this._setting.hasVideo=t,this._setting.hasAudio=e}publish(t){return this._transport.start(t)}setEncodeCapacity(t){this._setting=Object.assign({},this._setting,t)}getStats(){return{video:{...this._encode.getStats().video,sendSpeed:this._transport.sendSpeed,codec:this._setting.codec,frameWidth:this._setting.width,frameHeight:this._setting.height,gopSize:this._setting.gopSize},audio:{...this._encode.getStats().audio,codec:"aac",channels:this._setting.channel,sampleRate:this._setting.sampleRate}}}destroy(){ue.log("destroy"),this._encode.destroy(),this._packet.destroy(),this._transport.destroy()}down(){return this._transport.getFile()}}self.constructor.name!=="Window"&&le();function le(){let i={};self.addEventListener("message",async t=>{switch(t.data.type){case v.Init:{const{options:e}=t.data;e.logEnable&&(E.enable=!0),e.logEnableLong&&(E.enableLong=!0),i=new _e,i.on(O.OnError,s=>{self.postMessage({type:w.Error,data:s.toJson()})}),i.on(O.OnConnectClosed,()=>{self.postMessage({type:w.Close})}),i.on(O.OnFirstFramePushed,()=>{self.postMessage({type:w.FirstFramePushed})});try{await i.ready(),self.postMessage({type:w.Ready})}catch(s){self.postMessage({type:w.Error,data:s.toJson()})}}break;case v.AvExist:{const{hasAudio:e,hasVideo:s}=t.data;i.avExist(s,e)}break;case v.VideoFrame:{const{frame:e,setting:s}=t.data;i.videoFrameCaptured(e,s)}break;case v.MockVideoEncode:i.startMockVideoEncode();break;case v.AudioFrame:{const{frame:e,setting:s}=t.data;i.audioFrameCaptured(e,s)}break;case v.AdjustBitrate:{const{kind:e,bitrate:s}=t.data;i.adjustBitrate(e,s)}break;case v.Publish:{const{url:e}=t.data;try{await i.publish(e)}catch(s){self.postMessage({type:w.Error,data:s.toJson()})}}break;case v.GetStats:self.postMessage({type:w.STATS,data:i.getStats()});break;case v.EncodeConfig:{i.setEncodeCapacity(t.data.cfg);break}case v.Download:{const e=i.down();self.postMessage({type:w.Flvfile,buffer:e},[e.buffer])}break;case v.UnPublish:{i.destroy();break}}})}})();\n',Xa=typeof self<"u"&&self.Blob&&new Blob([Ja],{type:"text/javascript;charset=utf-8"});function Sg(i){let e;try{if(e=Xa&&(self.URL||self.webkitURL).createObjectURL(Xa),!e)throw"";const t=new Worker(e,{name:i==null?void 0:i.name});return t.addEventListener("error",()=>{(self.URL||self.webkitURL).revokeObjectURL(e)}),t}catch{return new Worker("data:text/javascript;charset=utf-8,"+encodeURIComponent(Ja),{name:i==null?void 0:i.name})}finally{e&&(self.URL||self.webkitURL).revokeObjectURL(e)}}try{Nt.enable=location.href.indexOf("rtmpdebug")!==-1,Nt.enableLong=location.href.indexOf("rtmpdebug=long")!==-1}catch{}const ur=new Nt("Bridge");class Za extends yg{constructor(){super(),this._worker=null,this._audioMsTrack=null,this._videoMsTrack=null,this._capture=new bg(this)}static isSupported(){return typeof WebTransport<"u"&&typeof MediaStreamTrackProcessor<"u"&&typeof MediaStreamTrackGenerator<"u"&&typeof VideoEncoder<"u"}get audioMsTrack(){return this._audioMsTrack}get videoMsTrack(){return this._videoMsTrack}async ready(){var s,a;let e,t;const r=new Promise((o,d)=>{e=o,t=d}),n=o=>{var d;switch((d=this._worker)==null||d.removeEventListener("message",n),o.data.type){case bt.Error:t(o.data.data);break;default:this._bindWorkerEvent(),ur.log("rtmp ready!"),e(!0)}};try{this._worker=new Sg}catch(o){t(Wa(cr.RTMP_INIT_FAIL,o.message))}return(s=this._worker)==null||s.postMessage({type:Se.Init,options:{logEnable:Nt.enable,logEnableLong:Nt.enableLong}}),(a=this._worker)==null||a.addEventListener("message",n),r}_bindWorkerEvent(){var e,t;(e=this._worker)==null||e.addEventListener("message",r=>{switch(r.data.type){case bt.Error:ur.table(r.data.data),this.emit(st.OnError,r.data.data);break;case bt.Flvfile:Eg(r.data.buffer);break;case bt.FirstFramePushed:this.emit(st.OnFirstFramePushed);break;case bt.Close:this.emit(st.OnConnectClosed),this.destroy();break}}),(t=this._worker)==null||t.addEventListener("error",r=>{this.emit(st.OnError,Wa(cr.WORKER_ERROR,r.message))})}addTrack(e){e.kind===ot.Video&&(this._videoMsTrack=e),e.kind===ot.Audio&&(this._audioMsTrack=e),this._setAVExist(!!this._videoMsTrack,!!this._audioMsTrack)}replaceTrack(e,t){e===ot.Video&&(this._videoMsTrack=t),e===ot.Audio&&(this._audioMsTrack=t),this._setAVExist(!!this._videoMsTrack,!!this._audioMsTrack),this._capture.restartCapture(e)}async getStats(){var s,a;let e,t;const r=new Promise((o,d)=>{e=o,t=d});this._worker||setTimeout(()=>{t()},0);const n=o=>{var d;switch(o.data.type){case bt.STATS:e(o.data.data),(d=this._worker)==null||d.removeEventListener("message",n);break}};return(s=this._worker)==null||s.addEventListener("message",n),(a=this._worker)==null||a.postMessage({type:Se.GetStats}),r}_postVideoFrame(e,t){var r;(r=this._worker)==null||r.postMessage({type:Se.VideoFrame,frame:e,setting:t},[e])}_postMockVideoEncodeFlag(){var e;(e=this._worker)==null||e.postMessage({type:Se.MockVideoEncode})}_setAVExist(e,t){var r;(r=this._worker)==null||r.postMessage({type:Se.AvExist,hasVideo:e,hasAudio:t})}_postAudioFrame(e,t){var r;(r=this._worker)==null||r.postMessage({type:Se.AudioFrame,frame:e,setting:t},[e])}setEncodeCapacity(e){var t;(t=this._worker)==null||t.postMessage({type:Se.EncodeConfig,cfg:e})}adjustBitrate(e,t){var r;(r=this._worker)==null||r.postMessage({type:Se.AdjustBitrate,kind:e,bitrate:t})}publish(e){var t;ur.log("start capture & connect"),this._capture.start(),(t=this._worker)==null||t.postMessage({type:Se.Publish,url:e})}unpublish(){var e;this._capture.destroy(),(e=this._worker)==null||e.postMessage({type:Se.UnPublish})}destroy(){var e;ur.log("destroy capture & rtmp worker"),this._capture.destroy(),(e=this._worker)==null||e.terminate(),this._worker=null}download(){var e;(e=this._worker)==null||e.postMessage({type:Se.Download})}}function Eg(i){const e=document.createElement("a");e.href=URL.createObjectURL(new Blob([i])),e.download=Date.now()+".flv",e.click()}const Qa=new nt("RTMPConnect");class wg{constructor(e,t,r,n){this._opts=void 0,this._isPushing=!1,this._url=e,this._opts=t,this._onError=r,this._OnSuccess=n,this._rtmp=new Za,this._bindEvents()}get isPushing(){return this._isPushing}get pushUrl(){return this._url}get sessionId(){return 0}_bindEvents(){this._rtmp.on(st.OnError,e=>{this._isPushing=!1,this._onError(e)}),this._rtmp.on(st.OnConnectClosed,()=>{this._isPushing=!1,this._onError(new Ka(cr.WTP_CONNECT_FAIL,"connect lost"))}),this._rtmp.on(st.OnFirstFramePushed,()=>{this._isPushing=!0,this._OnSuccess()})}async publish(e,t,r){await this._rtmp.ready(),r!=null&&r.cfg&&this._rtmp.setEncodeCapacity(r.cfg),e.filter(Boolean).forEach(n=>this._rtmp.addTrack(n)),t[0]&&this._rtmp.adjustBitrate(ot.Audio,t[0]),t[1]&&this._rtmp.adjustBitrate(ot.Video,t[1]),this._rtmp.publish(this._url)}updatePublish(e,t){Qa.log(`replace track to ${e==null?void 0:e.label}`),this._rtmp.replaceTrack(t,e)}applyBitrate(e,t){this._rtmp.adjustBitrate(t,e)}async getStats(){return this._rtmp.getStats()}async getStatsSnapshoot(e){return e&&await ki(e),{stats:await this._rtmp.getStats(),originStats:void 0}}unpublish(){Qa.warn("unpublish"),this._rtmp.unpublish(),this._isPushing=!1}}var Te=(i=>(i[i.Start=0]="Start",i[i.Stop=1]="Stop",i[i.GameControl=2]="GameControl",i[i.InitPushReader=3]="InitPushReader",i[i.Online=4]="Online",i[i.Reconnect=5]="Reconnect",i[i.UpdateTrack=6]="UpdateTrack",i[i.SetBitrate=7]="SetBitrate",i[i.PassEngineEvent=8]="PassEngineEvent",i[i.StopSuccess=9]="StopSuccess",i[i.VideoLog=10]="VideoLog",i[i.SetJitterBuffer=11]="SetJitterBuffer",i[i.ResetEngine=12]="ResetEngine",i[i.GetStats=13]="GetStats",i[i.Test=14]="Test",i[i.Plugin=15]="Plugin",i[i.EnableLogger=16]="EnableLogger",i[i.SendLogToMain=17]="SendLogToMain",i))(Te||{});const Cg=1e3;function kg(){return!1}class Ya{constructor(){this.maxSize=Cg,this.supported=kg(),this.supported&&(this.buffer=new SharedArrayBuffer(this.maxSize),this.arr=new Uint8Array(this.buffer))}share(e){return this.supported?(this.arr.set(e),this.buffer):e.buffer}}class Tg{constructor(e){this.encoder=new TextEncoder,this.decoder=new TextDecoder,this.buffer=new Ya,this.client=e}send(e){this.client.postMessage(e)}sendTransportable(e,t){Object.assign(e,t);const r=Object.values(t);this.client.postMessage(e,r)}onMessage(e){this.client.addEventListener("message",t=>{e(t.data)})}destroy(){var e,t;(t=(e=this.client).terminate)==null||t.call(e)}}class zg{constructor(){this.usePrevEmit=!0,this._map={},this._prevData={}}hasEvent(e){return!!this._map[e]}on(e,t){if(typeof e=="object"){const r=[];for(const n in e)r.push(this.on(n,e[n]));return()=>{r.forEach(n=>n())}}else{if(!t)throw new Error("fn is required");const r=this._formatTarget(t);return this._checkPrev(e,r)&&r.once?()=>{}:(this._getList(e).push(r),()=>{this.off(e,r)})}}_formatTarget(e,t){return typeof e=="function"?{listener:e,once:t??!1,prev:this.usePrevEmit}:(typeof t=="boolean"&&(e.once=t),e)}emit(e,...t){this._prevData[e]=t;const r=this._map[e];if(!r)return!1;for(let n=0;n<r.length;n++){const s=r[n];s.listener(...t),s.once&&(r.splice(n,1),n--)}return!0}off(e,t){const r=this._map[e];if(!r)return!1;const n=r.findIndex(s=>s===t||s.listener===t);return n===-1?!1:(r.splice(n,1),!0)}clear(e){return this._map[e]?(delete this._map[e],delete this._prevData[e],!0):!1}async onWait(e,t){return new Promise(r=>{var a;let n=(...o)=>r(o);t&&(n={listener:n,...t});const s=this.once(e,n);(a=t==null?void 0:t.onclear)==null||a.call(t,s)})}destroy(){this._map={},this._prevData={}}_checkPrev(e,t){if(!t.prev)return!1;const r=this._prevData[e];return typeof r<"u"?(t.listener(...r),!0):!1}once(e,t){return this.on(e,this._formatTarget(t,!0))}head(e,t){const r=this._formatTarget(t);return this._checkPrev(e,r)&&r.once?()=>{}:(this._getList(e).unshift(t),()=>{this.off(e,t)})}headOnce(e,t){return this.head(e,this._formatTarget(t,!0))}_getList(e){let t=this._map[e];return t||(this._map[e]=t=[]),t}passEvents(e,t){t.forEach(r=>{e.on(r,n=>{this.emit(r,n)})})}}class Ag extends zg{constructor(e){super();const t=new e;this.messenger=new Tg(t),this.buffer=new Ya,this.onMessage(r=>{this.receiveWorkerMessage(r)})}onMessage(e){this.messenger.onMessage(e)}sendMessage(e){var t;e.type===Te.GameControl&&((t=window.__vecg_debug_helper)==null||t.log("debugtouch sendMessage",e.data.byteLength)),this.messenger.send(e)}sendTransportable(e,t){this.messenger.sendTransportable(e,t)}}const ec='(function(){"use strict";var g=(s=>(s[s.Start=0]="Start",s[s.Stop=1]="Stop",s[s.GameControl=2]="GameControl",s[s.InitPushReader=3]="InitPushReader",s[s.Online=4]="Online",s[s.Reconnect=5]="Reconnect",s[s.UpdateTrack=6]="UpdateTrack",s[s.SetBitrate=7]="SetBitrate",s[s.PassEngineEvent=8]="PassEngineEvent",s[s.StopSuccess=9]="StopSuccess",s[s.VideoLog=10]="VideoLog",s[s.SetJitterBuffer=11]="SetJitterBuffer",s[s.ResetEngine=12]="ResetEngine",s[s.GetStats=13]="GetStats",s[s.Test=14]="Test",s[s.Plugin=15]="Plugin",s[s.EnableLogger=16]="EnableLogger",s[s.SendLogToMain=17]="SendLogToMain",s))(g||{});const j=1e3;function $(){return!1}class G{constructor(){this.maxSize=j,this.supported=$(),this.supported&&(this.buffer=new SharedArrayBuffer(this.maxSize),this.arr=new Uint8Array(this.buffer))}share(e){return this.supported?(this.arr.set(e),this.buffer):e.buffer}}class q{constructor(e){this.encoder=new TextEncoder,this.decoder=new TextDecoder,this.buffer=new G,this.client=e}send(e){this.client.postMessage(e)}sendTransportable(e,t){Object.assign(e,t);const i=Object.values(t);this.client.postMessage(e,i)}onMessage(e){this.client.addEventListener("message",t=>{e(t.data)})}destroy(){var e,t;(t=(e=this.client).terminate)==null||t.call(e)}}class p{constructor(){this.usePrevEmit=!0,this._map={},this._prevData={}}hasEvent(e){return!!this._map[e]}on(e,t){if(typeof e=="object"){const i=[];for(const n in e)i.push(this.on(n,e[n]));return()=>{i.forEach(n=>n())}}else{if(!t)throw new Error("fn is required");const i=this._formatTarget(t);return this._checkPrev(e,i)&&i.once?()=>{}:(this._getList(e).push(i),()=>{this.off(e,i)})}}_formatTarget(e,t){return typeof e=="function"?{listener:e,once:t??!1,prev:this.usePrevEmit}:(typeof t=="boolean"&&(e.once=t),e)}emit(e,...t){this._prevData[e]=t;const i=this._map[e];if(!i)return!1;for(let n=0;n<i.length;n++){const r=i[n];r.listener(...t),r.once&&(i.splice(n,1),n--)}return!0}off(e,t){const i=this._map[e];if(!i)return!1;const n=i.findIndex(r=>r===t||r.listener===t);return n===-1?!1:(i.splice(n,1),!0)}clear(e){return this._map[e]?(delete this._map[e],delete this._prevData[e],!0):!1}async onWait(e,t){return new Promise(i=>{var a;let n=(...o)=>i(o);t&&(n={listener:n,...t});const r=this.once(e,n);(a=t==null?void 0:t.onclear)==null||a.call(t,r)})}destroy(){this._map={},this._prevData={}}_checkPrev(e,t){if(!t.prev)return!1;const i=this._prevData[e];return typeof i<"u"?(t.listener(...i),!0):!1}once(e,t){return this.on(e,this._formatTarget(t,!0))}head(e,t){const i=this._formatTarget(t);return this._checkPrev(e,i)&&i.once?()=>{}:(this._getList(e).unshift(t),()=>{this.off(e,t)})}headOnce(e,t){return this.head(e,this._formatTarget(t,!0))}_getList(e){let t=this._map[e];return t||(this._map[e]=t=[]),t}passEvents(e,t){t.forEach(i=>{e.on(i,n=>{this.emit(i,n)})})}}class M extends p{constructor(){super(),this.messenger=new q(globalThis),this.messenger.onMessage(this.receiveMainMessage.bind(this))}onMessage(e){this.messenger.onMessage(e)}send(e,t){this.messenger.send({type:e,data:t})}}var l=(s=>(s[s.Connecting=0]="Connecting",s[s.Open=1]="Open",s[s.Closing=2]="Closing",s[s.Closed=3]="Closed",s))(l||{}),S=(s=>(s.Init="init",s.Online="online",s.Error="error",s.ApiCall="api_call",s))(S||{});function E(){let s,e;return{ready:new Promise((i,n)=>{s=i,e=n}),resolve:s,reject:e}}function J(s=500,e){const{ready:t,resolve:i}=E(),n=setTimeout(i,s);return e==null||e(n),t}function V(s){let e=!0,t="";for(const i of s)if(!(i in window)){e=!1,t=`${i} not Supported`;break}return{supported:e,info:t}}function x({task:s,timeout:e,time:t=200}){const{ready:i,resolve:n}=E(),r=setTimeout(async()=>{let a;typeof e<"u"&&(typeof e=="function"?(a=e(),a instanceof Promise&&(a=await a)):a=e),n(a)},t);return s().then(a=>{clearTimeout(r),n(a)}),i}const K=24*60*60*1e3;function F(s,e="1d"){const t=`_me_expire_${s}`;let i=0;if(typeof e=="string"){if(!/^[0-9]+d$/.test(e))throw new Error("expire format error");i=K*parseInt(e)}else i=e;return{get(){const n=localStorage.getItem(t);if(!n)return null;let r=null;try{r=JSON.parse(n)}catch{return null}const{value:a,expire:o}=r;return o<Date.now()?(localStorage.removeItem(t),null):a},set(n){localStorage.setItem(t,JSON.stringify({value:n,expire:Date.now()+i}))},remove(){localStorage.removeItem(t)}}}function C(s){let e=s.length,t=0;for(let r=e-1;r>=0;r--)s[r]?t+=s[r].byteLength:(e--,s.splice(r,1));const i=new Uint8Array(t);let n=0;for(let r=0;r<e;r++)i.set(s[r],n),n+=s[r].byteLength;return i}function _(s){for(const e in s)typeof s[e]>"u"&&delete s[e];return s}function X(s,e){let t=Number.MAX_SAFE_INTEGER,i=0;for(const n of e){const r=Math.abs(s-n);if(r===0)return n;r<t&&(t=r,i=n)}return i}var f=(s=>(s[s.AAC=0]="AAC",s[s.OPUS=1]="OPUS",s[s.H264=2]="H264",s[s.H265=3]="H265",s[s.AV1=4]="AV1",s))(f||{});f.AAC+"",f.OPUS+"",f.H264+"",f.H265+"",f.AV1+"";const U={[f.AAC]:"mp4a.40.2",[f.OPUS]:"opus",[f.H264]:"avc1.4DE033",[f.H265]:"hev1.1.6.L93.B0"};function O({readable:s,onFrame:e,onFinish:t,onError:i}){if(!s)return()=>{};const n=s.getReader();console.log("getReader");let r=!0;return Z({reader:n,flag:()=>r,onFrame:e,onFinish:t,onError:i}),()=>{r=!1}}async function Z({reader:s,flag:e,onFrame:t,onFinish:i,onError:n}){for(;e();)try{const{done:r,value:a}=await s.read();if(r){console.warn("Stream complete"),i==null||i();return}t(a),a.close()}catch(r){console.error("read error,",r),n==null||n(r)}}function W(s){const{video:e,audio:t}=Y(s);return{video:e?R(e):void 0,audio:t?R(t):void 0}}function R(s){const e=new MediaStreamTrackProcessor(s),{readable:t}=e,i=s.getSettings();return{readable:t,settings:i}}function Y(s){return{video:s.getVideoTracks()[0],audio:s.getAudioTracks()[0]}}function ee(s){const e=new Uint8Array(s.byteLength);return s.copyTo(e),e}const u={log(){},send(){},$custom:{},$enableLog(s=!0){u.log=s?(...e)=>{console.log(L(),...e),u.enableLogSend&&z(e)}:()=>{}},$enableSend(){u.send=(...s)=>{z(s)}}};function te(){var n;typeof window=="object"&&!window.__me_debug_helper&&(window.__me_debug_helper=u);let s=location.search.substring(1);const e="_medh_",t=((n=u.$isInnerEnv)==null?void 0:n.call(u))||!0;if(!s){const{hash:r}=location,a=r.indexOf("?");if(!r||a===-1||(s=r.substring(a+1),!s))return}const i=s.split("&");for(const r of i){const[a,o]=r.split("=");if(a.startsWith(e)){let c=a.replace(e,"");if(c.startsWith("inner_")){if(!t)continue;c=c.replace("inner_","")}c==="log"?u.$enableLog():c==="send"?u.$enableSend():u[c]=o||!0}}location.hostname==="localhost"&&u.$enableLog()}function z(s){if(u.$logger)try{u.$logger(s)}catch(e){console.error(L(),"debug send fail:",e)}}function L(){const s=new Date;return`[${s.toLocaleTimeString()} ${s.getMilliseconds().toString().padStart(3,"0")} media-engine]`}te();let ie=class{constructor(){this._lastDot=0,this._totalSize=0,this._speed=[]}addSample(e){this._lastDot||(this._lastDot=Date.now()),this._totalSize+=e;const t=Date.now()-this._lastDot;t>=500&&(this._addSpeedSample(this._totalSize/t*8e3),this._totalSize=0,this._lastDot=Date.now())}_addSpeedSample(e){this._speed.push(e),this._speed=this._speed.slice(-6)}reset(){this._speed=[]}getUpSpeed(){return this._speed.length?parseInt(this._speed.reduce((e,t)=>e+=t,0)/this._speed.length):0}};class se{constructor(){this._bandwidth=0,this._dbrDataSize=0,this.MAX_ESTIMATE_DURATION_MS=2e3,this.MIN_ESTIMATE_DURATION_MS=1e3,this.packets=[]}addDbrPacket(e){this.packets.push(e),this._dbrDataSize+=e.size;const t=this.packets[0],i=e.sendEndTime-t.sendBeginTime;for(;this.packets.length>0;){const n=this.packets[0];if(e.sendEndTime-n.sendBeginTime>this.MAX_ESTIMATE_DURATION_MS)this._dbrDataSize-=n.size,this.packets.shift();else break}this._bandwidth=i>=this.MIN_ESTIMATE_DURATION_MS?this._dbrDataSize*1e3/i*8:0}getEstimateBandwidth(){return this._bandwidth}reset(){this._bandwidth=0,this._dbrDataSize=0,this.packets=[]}}class ne extends p{constructor(e,t,i){super(),this.streamWriter=null,this.datagramWriter=null,this.failQueue=[],this.bandwidth=0,this.smoothTime=0,this.failCount=0,this.timeoutCount=0,this.streamWriter=e.writable.getWriter(),this.datagramWriter=t.writable.getWriter(),this.upspeed=new ie,this.bandwidthEstimate=new se,i&&(this.strategy=i,i.upstream=this)}async resetStream(e){var t;(t=this.streamWriter)==null||t.releaseLock(),this.streamWriter=e.writable.getWriter(),this.failQueue.forEach(({data:i,config:n})=>{this.sendStream(i,n)}),this.failQueue=[]}async sendStream(e,{extra:t,force:i}={extra:{},force:!1}){var d;if(!i&&((d=this.strategy)==null?void 0:d.onSendStream(e,t))===!1)return;const n={sendBeginTime:performance.now(),size:e.byteLength,sendEndTime:0};this.upspeed.addSample(e.byteLength);const r=performance.now(),a=await this._writeData(e);if(a){(a==="error"||a==="timeout")&&(this.failQueue.push({data:e,config:{extra:t,force:i}}),this.emit("write-error",a));return}n.sendEndTime=performance.now(),this.bandwidthEstimate.addDbrPacket(n);const o=performance.now()-r||.001;this.smoothTime=this.smoothTime===0?o:this.smoothTime*.7+o*.3;const h=e.byteLength/1024*8/(this.smoothTime/1e3);this.bandwidth=Math.min(this.bandwidth===0?h:this.bandwidth*.7+h*.3,1e4)}async _writeData(e){return await x({task:()=>{if(!this.streamWriter)return Promise.resolve("no_stream");const{ready:i,resolve:n}=E();return this.streamWriter.write(e).then(()=>{n("")}).catch(()=>{this.failCount++,n("error")}),i},timeout:()=>(this.timeoutCount++,"timeout"),time:1e3})}async sendDgm(e,{extra:t,force:i}={extra:{},force:!0}){var n,r;!i&&((n=this.strategy)==null?void 0:n.onSendDgm(e,t))===!1||(this.upspeed.addSample(e.byteLength),await((r=this.datagramWriter)==null?void 0:r.write(e).catch(a=>{console.log("send dgm fail",a)})))}async destroy(){var e,t,i;try{await((e=this.streamWriter)==null?void 0:e.close()),await((t=this.datagramWriter)==null?void 0:t.close())}catch(n){console.warn("upstream destroy:",n)}this.upspeed.reset(),(i=this.strategy)==null||i.destroy()}getSpeed(){return this.upspeed.getUpSpeed()}getBandwidth(){return this.bandwidth}getEstimateBandwidth(){return this.bandwidthEstimate.getEstimateBandwidth()}clearEstimateBandwidth(){this.bandwidthEstimate.reset()}}class re extends p{constructor(e,t){super(),this.destroyed=!1,this.read(e.readable,i=>{this.emit("stream",i)},!0),this.read(t.readable,i=>{this.emit("datagram",i)})}async read(e,t=()=>{},i=!1){const n=e.getReader();for(i&&(this.streamReader=n);!this.destroyed;){const{value:r,done:a}=await n.read().catch(()=>({done:!0,value:null}));if(a)break;t(r)}}resetStream(e){this.streamReader.releaseLock(),this.read(e.readable,t=>{this.emit("stream",t)})}destroy(){this.destroyed=!0,super.destroy()}}const P={clearConnection:()=>Promise.resolve(),sendStream:async()=>{},sendDgm:async()=>{},getUpSpeed:()=>0,getUpBandwidth:()=>0,getId:()=>0};class ae extends p{constructor(e){super(),this.destroyed=!1,this._resetLock=!1,this.options=e,this.ready=this.connect(),this.ready.then(t=>{var i;t&&(this.initStream(),(i=this.transport)==null||i.closed.then(n=>{this.emit("closed",n)}).catch(n=>{this.emit("closed",{closeCode:-1,reason:`catch ${n.toString()}`})}))})}get id(){return this.options.id}async destroy(){var e,t,i,n;if(super.destroy(),!this.destroyed){this.destroyed=!0,await((e=this.upstream)==null?void 0:e.destroy()),(t=this.downstream)==null||t.destroy();try{(i=this.transport)==null||i.close(),await((n=this.transport)==null?void 0:n.closed)}catch(r){console.warn("close fail",r)}this.transport=null,u.log("close transport"),this.emit("destroyed")}}async connect(){try{const e=new WebTransport(this.options.url);if(!e)this.onFail("Init error");else{this.transport=e;const t=await x({task:async()=>{var i;try{return await((i=this.transport)==null?void 0:i.ready),u.log("transport ready"),""}catch(n){return`Ready Catch: ${(n==null?void 0:n.toString())||"Fail"}`}},timeout:"Init timeout",time:2e3});if(t)this.onFail(t);else return this.emit("success"),!0}}catch(e){this.onFail(`Init Catch: ${(e==null?void 0:e.toString())||"Fail"}`)}return!1}onFail(e){this.emit("fail",e),this.transport=null,this.destroy()}async initStream(){const{transport:e}=this;if(!e)return;const t=await this.createBidStream();if(!t)return;this._prevStream=t;const i=e.datagrams;this.upstream=new ne(t,i,this.options.strategy),this.downstream=new re(t,i),this.downstream.on({stream:n=>this.emit("stream",n),datagram:n=>{this.emit("datagram",n)}}),this.upstream.on("write-error",()=>{this.resetStream()}),this.emit("upstream-ready")}async resetStream(){var t,i,n,r;if(this._resetLock)return;this._resetLock=!0;const e=await this.createBidStream();if(!e){this._resetLock=!1;return}(t=this.upstream)==null||t.resetStream(e),(i=this._prevStream)==null||i.writable.close(),(n=this.downstream)==null||n.resetStream(e),(r=this._prevStream)==null||r.readable.cancel(),this._prevStream=e,this._resetLock=!1}async createBidStream(){var e;return(e=this.transport)==null?void 0:e.createBidirectionalStream()}}class oe{constructor(e){this.index=0,this.gaps=[5,5,5,5,10,10,10,20,20,30,30,40,50,70,100],this.count=0,this.n=this.gaps.length,this.max=this.gaps[this.n-1]*100,this.maxCount=e}reset(){this.index=0,this.count=0}get gap(){return typeof this.maxCount=="number"&&this.count>=this.maxCount?0:(this.count++,this.index>=this.n-1?this.max:this.gaps[this.index++]*100)}}class ce extends p{constructor(){super(...arguments),this.readyState=l.Connecting,this.connectId=0,this.connectionUtil=P,this.destroyed=!1}setState(e){this.readyState=e}get isConnecting(){return this.readyState===l.Connecting}async init(e){this.options=Object.assign({autoReconnect:!0,useDownstream:!0},e),this.reconnectGap=new oe(e.maxCount),await this.connect({connectReason:S.Init})}async connect({first:e=!0,connectReason:t,url:i}){if(this.destroyed)return this.setState(l.Closed),Promise.resolve("Reconnector destroyed");const n=t===S.Init;e&&(this.reconnectGap.reset(),n||this.emit("reconnecting",t)),this.setState(l.Connecting);const{success:r,reason:a}=await this.singleConnect(i);if(this.destroyed)return this.setState(l.Closed),Promise.resolve("Reconnector destroyed stage2");if(!r){const{gap:o}=this.reconnectGap,c=e&&n?"connect-fail":"reconnect-fail";return this.emit(c,a),o===0||!this.options.autoReconnect?(this.emit("end"),this.setState(l.Closed),a):(await J(o,h=>this.delayTimer=h),this.connect({first:!1,url:i,connectReason:S.Error}))}return this.setState(l.Open),this.emit("connect-open",n),this.onConnected(),n||this.onMonitorConnectionNormal(),""}async onConnected(){var t;(t=this.clearWaitClosed)==null||t.call(this);const[e]=await this.onWait("connection-closed",{onclear:i=>this.clearWaitClosed=i});if(e.closeCode!==-1){if(console.log("reason",e.reason),this.emit("connect-close",e.reason||""),this.isConnecting){console.warn("isConnecting",e.reason);return}console.log("close: webts closed gracefully.",e.reason),e.closeCode===0&&(this.emit("end"),this.setState(l.Closed))}else{const i=e.reason;console.error("close: webts closed due to ",e),this.emit("connect-close",i),this.emit("disconnected",i),this.options.autoReconnect?this.connect({connectReason:S.Error}):(this.emit("connect-fail",i),this.emit("end"))}}onMonitorConnectionNormal(){this.options.useDownstream&&(this.waitTimer=setTimeout(()=>{this.emit("reconnect-fail","no packet"),this.emit("connect-close","no packet received"),this.emit("end"),this.setState(l.Closed)},3e3))}onReceivePacket(e){this.waitTimer!==null&&(e<10||(clearTimeout(this.waitTimer),this.waitTimer=null,console.warn("DEBUG 重连恢复收包"),this.emit("reconnected")))}async singleConnect(e){const{resolve:t,ready:i}=E();await this.clearReconnect();const n=new ae({id:this.connectId++,url:e||this.options.url,strategy:this.options.strategy});n.on({success:()=>{t({success:!0,reason:""})},fail:a=>{t({success:!1,reason:a})},destroyed:()=>{t({success:!1,reason:"Connection destroyed"})},datagram:a=>{this.onReceivePacket(a.byteLength),this.emit("datagram",a)},closed:a=>{this.emit("connection-closed",a)}}),this.passEvents(n,["upstream-ready","stream"]);const r=n.onWait("upstream-ready");return this.connectionUtil={clearConnection:()=>n.destroy(),sendStream:async(a,o)=>{var c;if(!n.destroyed)return await r,(c=n.upstream)==null?void 0:c.sendStream(a,o)},sendDgm:async(a,o)=>{var c;if(!n.destroyed)return await r,(c=n.upstream)==null?void 0:c.sendDgm(a,o)},getUpSpeed:()=>{var a;return((a=n.upstream)==null?void 0:a.getSpeed())||0},getUpBandwidth:()=>{var a;return((a=n.upstream)==null?void 0:a.getBandwidth())||0},getId:()=>n.id},i}async destroy(){this.destroyed||(this.destroyed=!0,await this.clearReconnect(),this.emit("connect-close","api call"),this.emit("disconnected","api call"),super.destroy())}async clearReconnect(){var e;await((e=this.connectionUtil)==null?void 0:e.clearConnection()),clearTimeout(this.delayTimer),clearTimeout(this.waitTimer),this.waitTimer=this.delayTimer=null}onlineReconnect(){this.options.autoReconnect&&(this.clearReconnect(),this.connect({first:!0,connectReason:S.Online}))}}class he extends p{get readyState(){var e;return((e=this.reconnector)==null?void 0:e.readyState)||l.Closed}get closed(){return this.readyState===l.Closed}get connection(){var e;return((e=this.reconnector)==null?void 0:e.connectionUtil)||P}async init(e){this.reconnector=new ce,this.initEvents(),this.ready=this.reconnector.init({...Object.assign({useDownstream:!0},e)}),await this.ready}async close(){await this.reconnector.destroy()}online(){this.reconnector.onlineReconnect()}reconnect(e){this.reconnector.connect({connectReason:S.ApiCall,url:e})}async sendStream(e,t){var i;return await this.ready,(i=this.connection)==null?void 0:i.sendStream(e,t)}async sendDgm(e,t){var i;return await this.ready,(i=this.connection)==null?void 0:i.sendDgm(e,t)}initEvents(){this.passEvents(this.reconnector,["reconnected","reconnect-fail","connect-close","disconnected","reconnecting","connect-fail","connect-open","upstream-ready","stream","datagram"])}getUpSpeed(){return this.connection.getUpSpeed()}getUpBandwidth(){return this.connection.getUpBandwidth()}async destroy(){await this.close(),super.destroy()}}class de extends p{sendStream(e,t){return this.upstream.sendStream(e,{force:!0,extra:t})}sendDgm(e,t){return this.upstream.sendDgm(e,{force:!0,extra:t})}}class ue{constructor(){this.totalFrames=0,this.periodFrames=0,this.periodSize=0,this.periodDuration=0,this.keyFrames=0,this.bitrate=0,this.framerate=0,this.lastTs=0}addFrame(e){const t=e.byteLength;let i=0;const n=Math.round(e.timestamp/1e3);this.lastTs!==0&&(i=n-this.lastTs),this.lastTs=n,this.totalFrames++,this.periodFrames++,this.periodSize+=t,this.periodDuration+=i,e.type==="key"&&this.keyFrames++,this.periodDuration>=1e3&&(this.bitrate=Math.floor(this.periodSize/this.periodDuration*8e3),this.framerate=this.periodFrames,this.periodFrames=0,this.periodDuration=0,this.periodSize=0)}getStats(){return{bitrate:this.bitrate,framerate:this.framerate,encodedFrames:this.totalFrames,encodedKeyFrames:this.keyFrames,codec:""}}reset(){this.totalFrames=0,this.periodFrames=0,this.periodSize=0,this.periodDuration=0,this.keyFrames=0,this.bitrate=0,this.framerate=0,this.lastTs=0}}class H extends p{constructor(){super(...arguments),this.configInitialized=!1,this.firstFrame=!1,this.stats=new ue,this._config={},this._finalConfig={},this._decoderConfig={},this._destroyed=!1}extraEncodeConfig(){return{}}getStats(){return this.stats.getStats()}get mediaType(){return this._config.mediaType}async updateConfig(e){if(e=_(e),Object.keys(e).length===0)return;Object.assign(this._config,e),this.encoder&&(await this.encoder.flush(),this.encoder.close(),this.init());const t=await this.checkConfigSupported(this.formatConfig());this._config={...this._config,...t},this._finalConfig=this.formatConfig(),this.configInitialized=!1}getConfig(){return this._config}getDecoderConfig(){return this._decoderConfig}init(e){e&&this.updateConfig(e),u.log("init encoder"),this.encoder=new this.Encoder({output:(t,i)=>{t.syncTimestamp=t.timestamp,this.stats.addFrame(t);const n=i==null?void 0:i.decoderConfig;let r;n&&(r=n,Object.assign(this._decoderConfig,n),this.emit("decoder-config-change",this._decoderConfig)),this.emit("frame-encoded",t,r),this.firstFrame||(this.emit("first-frame-encoded",t,r),this.firstFrame=!0)},error:t=>{this.emit("encode-error",t)}})}encode(e){var t;if(!this._destroyed){if(!this.configInitialized){const i=this._finalConfig;(t=this.encoder)==null||t.configure(i),this.configInitialized=!0,console.warn("configure final done",i)}this.encoder.encode(e,this.extraEncodeConfig())}}async destroy(){var e,t;this.stats.reset(),this._destroyed=!0;try{await((e=this.encoder)==null?void 0:e.flush()),(t=this.encoder)==null||t.close()}catch{}super.destroy()}async checkConfigSupported(e,t=!1){if(this.Encoder.isConfigSupported)try{const{config:i,supported:n}=await this.Encoder.isConfigSupported(e);if(n)return e;if(!t&&this.retryConfig)return this.checkConfigSupported(this.retryConfig(e),!0);this.emit("config-error",{message:"config not supported",config:i})}catch(i){if(!t&&this.retryConfig)return this.checkConfigSupported(this.retryConfig(e));this.emit("config-error",{message:"config uncaught error",err:i,config:e})}}}F("audio_encoder_support","3d");function le(){return V(["EncodedAudioChunk","AudioEncoder","AudioData"])}const m={mediaType:f.H264,format:"annexb",bitrate:2e5,framerate:15,bitrateMode:"variable",keyInterval:3e3,keyGopSize:90,hardwareAcceleration:"prefer-hardware",latencyMode:"quality"},w={mediaType:f.AAC,bitrate:96e3,sampleRate:48e3,numberOfChannels:2,bitrateMode:"constant"},T=class T extends H{constructor(){super(...arguments),this.Encoder=AudioEncoder,this.isAudio=!0}updateConfig(e){if(typeof e.bitrate=="number"){const t=[96e3,128e3,16e4,192e3],i=X(e.bitrate,t);i!==e.bitrate&&(console.warn(`audio bitrate ${e.bitrate} not supported, use ${i} instead`),e.bitrate=i)}return super.updateConfig(e)}getStats(){const{codec:e="",numberOfChannels:t=0,sampleRate:i=0}=this._finalConfig;return{...super.getStats(),codec:e,numberOfChannels:t,sampleRate:i}}formatConfig(e){const{bitrate:t=w.bitrate,bitrateMode:i=w.bitrateMode,codec:n=w.codec||U[this._config.mediaType??w.mediaType],numberOfChannels:r=w.numberOfChannels,format:a=w.format||(e==null?void 0:e.format),sampleRate:o=w.sampleRate}=this._config,c=_({codec:n,sampleRate:o,numberOfChannels:r,bitrate:t,bitrateMode:i,format:a});return this.emit("config-change",c),c}};T.isSupported=le;let v=T;F("video_encoder_support","3d");function fe(){return V(["EncodedVideoChunk","VideoEncoder","VideoFrame"])}function me(s=m.keyInterval){let e=!0,t;return{is(){return e?(e=!1,t=setTimeout(()=>{e=!0},s),!0):!1},reset(){e=!0,clearTimeout(t)}}}function pe(s=m.keyGopSize){let e=s;return{is(){return e++,e>=s?(e=0,!0):!1},reset(){e=s}}}const B=class B extends H{constructor(){super(...arguments),this.Encoder=VideoEncoder,this.isAudio=!1,this.retryConfig=e=>(e.hardwareAcceleration==="prefer-hardware"&&(e.hardwareAcceleration="prefer-software",this._config.hardwareAcceleration="prefer-software",console.warn("retry config with software hardwareAcceleration")),e)}getStats(){const e=super.getStats();let{keyGopSize:t}=this._finalConfig;const{keyInterval:i=m.keyInterval}=this._config,{width:n=0,height:r=0,codec:a="",framerate:o=0}=this._finalConfig;return typeof t>"u"&&(t=Math.round(i/1e3*o)),{...e,width:n,height:r,codec:a,keyGopSize:t}}formatConfig(e){const{codec:t=m.codec||U[this._config.mediaType??m.mediaType],bitrate:i=m.bitrate,framerate:n=m.framerate,keyInterval:r=m.keyInterval,hardwareAcceleration:a=m.hardwareAcceleration,latencyMode:o=m.latencyMode,keyGopSize:c,width:h=m.width||(e==null?void 0:e.codedWidth),height:d=m.height||(e==null?void 0:e.codedHeight)}=this._config;this.keyframe=c?pe(c):me(r);const b=_({latencyMode:o,codec:t,hardwareAcceleration:a,bitrate:i,width:h,height:d,framerate:n});return console.log("config video",JSON.stringify(b,null,2)),this.emit("config-change",b),b}extraEncodeConfig(){return{keyFrame:this.keyframe.is()}}resetKeyFrame(){var e;(e=this.keyframe)==null||e.reset()}async destroy(){try{this.resetKeyFrame()}catch{}await super.destroy()}};B.isSupported=fe;let k=B;const N=16;function Q(){let s=-1,e=-1,t=-1;return{getLatest(){return s},setBase(i){t===-1&&(t=i)},check(i){return s===-1?s=t:s+=i-e,e=i,s},reset(){s=e=t=-1}}}class ge extends p{constructor(){super(...arguments),this.video=Q(),this.audio=Q(),this.base=N,this._sendQueue=[],this._processedVideo=!1,this._processedAudio=!1,this._maximumVideoSyncTimestamp=0,this._maximumAudioSyncTimestamp=0,this.cacheAudioChunk=[],this.cacheVideoChunk=[],this.hasGetFirstVideoFrame=!1,this.SYNC_THRESHOLD=40}insertPacket(e,t,i){let n=0;for(;n<this._sendQueue.length&&!(this._sendQueue[n].frame.syncTimestamp===e.syncTimestamp&&t==="video"||this._sendQueue[n].frame.syncTimestamp>e.syncTimestamp);n++);this._sendQueue.splice(n,0,{frame:e,type:t,cfg:i})}processPacket(e,t,i){switch(this._processedAudio&&this._processedVideo||(t==="video"?this._processedVideo=!0:this._processedAudio=!0),this.insertPacket(e,t,i),t){case"video":this._maximumVideoSyncTimestamp<e.syncTimestamp&&(this._maximumVideoSyncTimestamp=e.syncTimestamp);break;case"audio":this._maximumAudioSyncTimestamp<e.syncTimestamp&&(this._maximumAudioSyncTimestamp=e.syncTimestamp);break}if(this._processedAudio&&this._processedVideo)for(;this._sendQueue.length>0;){const r=this._sendQueue[0];if(!this.checkOpposingTimestamp(r.frame,r.type))return!1;this.emit("processed-frame",r.frame,r.type,r.cfg),this._sendQueue.shift()}}checkOpposingTimestamp(e,t){switch(t){case"audio":return this._maximumVideoSyncTimestamp>e.syncTimestamp;case"video":return this._maximumAudioSyncTimestamp>e.syncTimestamp;default:return!1}}formatFrame(e,t,i,n){this[t].setBase(this.base);const a=Math.round(e.timestamp/1e3),o=this[t].check(a);return e.syncTimestamp=o,this.processPacket(e,t,n),[e]}syncAVFrame(e,t){if(t==="audio")this.cacheAudioChunk.push(e),this.cacheAudioChunk.sort((i,n)=>i.syncTimestamp-n.syncTimestamp);else if(this.cacheVideoChunk.push(e),this.cacheVideoChunk.sort((i,n)=>i.syncTimestamp-n.syncTimestamp),!this.hasGetFirstVideoFrame)return this.hasGetFirstVideoFrame=!0,null;return this.flushSynchronizedFrames()}flushSynchronizedFrames(){const e=[];for(;this.canSendFrame();){const t=this.getNextFrameToSend();if(t)e.push(t);else break}return e}canSendFrame(){if(this.cacheAudioChunk.length===0&&this.cacheVideoChunk.length===0)return!1;if(this.cacheAudioChunk.length===0)return this.cacheVideoChunk.length>0;if(this.cacheVideoChunk.length===0)return!1;const e=this.cacheAudioChunk[0],t=this.cacheVideoChunk[0];return Math.abs(e.syncTimestamp-t.syncTimestamp)<=this.SYNC_THRESHOLD}getNextFrameToSend(){if(this.cacheAudioChunk.length===0&&this.cacheVideoChunk.length>0)return this.cacheVideoChunk.shift()||null;if(this.cacheVideoChunk.length===0&&this.cacheAudioChunk.length>0||this.cacheAudioChunk.length===0&&this.cacheVideoChunk.length===0)return null;const e=this.cacheAudioChunk[0],t=this.cacheVideoChunk[0];return e.syncTimestamp<=t.syncTimestamp?this.cacheAudioChunk.shift()||null:this.cacheVideoChunk.shift()||null}reset(){this.audio.reset(),this.video.reset(),this.base=N,this._processedAudio=!1,this._processedVideo=!1,this._maximumAudioSyncTimestamp=0,this._maximumVideoSyncTimestamp=0,this.cacheAudioChunk=[],this.cacheVideoChunk=[],this.hasGetFirstVideoFrame=!1}}var y=(s=>(s[s.AUDIO=8]="AUDIO",s[s.VIDEO=9]="VIDEO",s[s.SCRIPT_DATA=18]="SCRIPT_DATA",s))(y||{}),A=(s=>(s[s.SEQUENCE_HEADER=0]="SEQUENCE_HEADER",s[s.AAC=1]="AAC",s))(A||{}),D=(s=>(s[s.SEQUENCE_HEADER=0]="SEQUENCE_HEADER",s[s.NALU=1]="NALU",s))(D||{}),I=(s=>(s[s.KEY=1]="KEY",s[s.INNER=2]="INNER",s))(I||{});const _e=10,ye=1,Se=7,we={96e3:0,48e3:3,44100:4,22050:7,16e3:8,8e3:11};function be(s){const e=(s[4]&3)+1;let t;const i=[],n=[];let r=6;const a=s[5]&31;let o;for(let d=0;d<a;d++){if(o=s[r]<<8|s[r+1],r+=2,!o)continue;const b=s.subarray(r,r+o);r+=o,i.push(b)}const c=s[r];r++;let h;for(let d=0;d<c;d++)h=s[r]<<8|s[r+1],r+=2,h&&(n.push(s.subarray(r,r+h)),r+=h);return{sps:t,spsArr:i,ppsArr:n,nalUnitSize:e}}class Ce{constructor(){this._cfg={hasVideo:!1,hasAudio:!1,sampleRate:48e3,numberOfChannels:1},this._hasVideoSeqHeader=!1}get hasVideo(){return!!this._cfg.hasVideo}get hasAudio(){return!!this._cfg.hasAudio}setConfig(e){this._cfg=Object.assign(this._cfg,e),console.log("---flv setConfig",this._cfg)}genHeader(){const e=[70,76,86,1,(this.hasAudio?1:0)<<2|(this.hasVideo?1:0),0,0,0,9,0,0,0,0];return new Uint8Array(e)}geneSEQ(e,t){let i;return e===y.AUDIO?i=this._genAudioSEQPayload():(i=this._genVideoSEQPayload(t.frame.type,t.description),this._hasVideoSeqHeader=!0),this._concatPayload(e,t.frame.syncTimestamp,i)}genPayload(e){const t=e.type===y.AUDIO,i=ee(e.frame),n=C([t?this._genAudioTagHeader():this._genVideoTagHeader(e.frame.type),t?this._genAudioData(i):this._genVideoData(e,i)]);return this._concatPayload(e.type,e.frame.syncTimestamp,n)}_concatPayload(e,t,i){const n=this._genTagHeader(e,i.length,t),r=n.length+i.length;return C([n,i,new Uint8Array([r>>>24,r>>>16,r>>>8,r])])}_genTagHeader(e,t,i){return new Uint8Array([e,t>>>16,t>>>8,t,i>>>16,i>>>8,i,i>>>24,0,0,0])}_genAudioSEQPayload(){return C([this._genAudioTagHeader(),this._genAudioSequenceHeader()])}_genVideoSEQPayload(e,t){return C([this._genVideoTagHeader(e),this._genVideoSequenceHeader(t)])}_genAudioTagHeader(){return new Uint8Array([_e<<4|12|ye<<1|this._cfg.numberOfChannels-1])}_genVideoTagHeader(e){return new Uint8Array([(e==="key"?I.KEY:I.INNER)<<4|Se,this._hasVideoSeqHeader?D.NALU:D.SEQUENCE_HEADER,0,0,0])}_genAudioSequenceHeader(){const e=4096|we[this._cfg.sampleRate]<<7|this._cfg.numberOfChannels<<3;return new Uint8Array([A.SEQUENCE_HEADER,e>>8,e])}_genAudioData(e){const t=new Uint8Array(1+e.length);return t.set([A.AAC],0),t.set(e,1),t}_genVideoSequenceHeader(e){return new Uint8Array(e||[])}_genVideoData(e,t){if(e.frame.type==="delta")return t;const i=be(new Uint8Array(e.description)),n=i.spsArr[0].length,r=i.ppsArr[0].length;return C([new Uint8Array([0,0,n>>8,n%256]),i.spsArr[0],new Uint8Array([0,0,r>>8,r%256]),i.ppsArr[0],t])}reset(){this._hasVideoSeqHeader=!1}}class Ee{constructor(){this._firstFrame=!0,this._flv=new Ce}updateConfig(e){e&&this._flv.setConfig(e)}receiveMediaFrame(e,t){const i=e.type===y.AUDIO;this._firstFrame&&i||(this._firstFrame&&(t({buffer:this._flv.genHeader(),type:"header"}),this._flv.hasAudio&&t({buffer:this._flv.geneSEQ(y.AUDIO,e),type:"seq"}),this._flv.hasVideo&&t({buffer:this._flv.geneSEQ(y.VIDEO,e),type:"seq"}),this._firstFrame=!1),t({buffer:this._flv.genPayload(e),type:"payload"}))}reset(){this._firstFrame=!0,this._flv.reset()}destroy(){this.reset()}}class ve{constructor(e=1e3){this._packets=[],this._latestDts=0,this._videoDuration=0,this._batchSize=e}addPacket(e,t){this._packets.push({data:e,isSeparator:!1,...t}),t.mediaType==="video"&&(this._latestDts=t.dts||0)}getVideoDuration(){const e=this._packets.find(t=>t.mediaType==="video");return!e||!e.dts?0:this._latestDts-e.dts}shift(){if(this._packets.length===0)return;let e=0;for(const r of this._packets)e+=r.data.byteLength;if(e<this._batchSize)return;const t=new Uint8Array(this._batchSize);let i=0,n=this._batchSize;for(;n>0&&this._packets.length>0;){const r=this._packets[0],a=r.data.byteLength;if(a<=n)t.set(r.data,i),i+=a,n-=a,this._packets.shift();else{const o=r.data.slice(0,n);t.set(o,i),this._packets[0]={...r,data:r.data.slice(n),isSeparator:!0},n=0}}return t}shiftSinglePacket(){if(this._packets.length===0)return;const e=this._packets.shift();return e==null?void 0:e.data}forceShift(){if(this._packets.length===0)return;let e=0;for(const a of this._packets)e+=a.data.byteLength;const t=Math.min(e,this._batchSize),i=new Uint8Array(t);let n=0,r=t;for(;r>0&&this._packets.length>0;){const a=this._packets[0],o=a.data.byteLength;if(o<=r)i.set(a.data,n),n+=o,r-=o,this._packets.shift();else{const c=a.data.slice(0,r);i.set(c,n),this._packets[0]={...a,data:a.data.slice(r),isSeparator:!0},r=0}}return i}dropPackets(e){const t=Math.min(e,this._packets.length);this._packets.splice(0,t)}dropVideoPackets(){this._packets=this._packets.filter(e=>e.mediaType!=="video")}get size(){return this._packets.length}get totalBytes(){return this._packets.reduce((e,t)=>e+t.data.byteLength,0)}get hasEnoughData(){return this.totalBytes>=this._batchSize}reset(){this._packets=[]}setBatchSize(e){this._batchSize=e}}class ke{constructor(){this._lastDot=0,this._totalSize=0,this._speed=[]}addSample(e){this._lastDot||(this._lastDot=Date.now()),this._totalSize+=e;const t=Date.now()-this._lastDot;t>=500&&(this._addSpeedSample(this._totalSize/t*8e3),this._totalSize=0,this._lastDot=Date.now())}_addSpeedSample(e){this._speed.push(e),this._speed=this._speed.slice(-6)}reset(){this._speed=[]}getUpSpeed(){return this._speed.length?parseInt(this._speed.reduce((e,t)=>e+=t,0)/this._speed.length):0}}class Ae extends de{constructor(e,t){super(),this.context=e,this.upSpeed=new ke,this.streamBuffer=new ve,this._inAdjustEncode=!1,this._dbrIncTimeout=0,this._dbrPrevBitrate=0,this._increaseTimer=0,this.isSending=!1,this.config={maxCacheSize:50,realSpeedPercent:.8,setting:{},uplinkBitrateCheckInterval:4*1e3,dbrIncreaseStep:.1},this.getCurrentBitrate=()=>this.context.videoEncoderConfig.bitrate??0,t&&this.updateConfig(t)}reset(){this.upSpeed.reset(),this.streamBuffer.reset(),this.isSending=!1,clearInterval(this._increaseTimer),this._increaseTimer=0,this._inAdjustEncode=!1}updateConfig(e){Object.assign(this.config,e)}_isHavingCongestion(){return this.streamBuffer.size>this.config.maxCacheSize}_setEncoderBitrate(e){const{width:t,height:i,framerate:n}=this.context.videoEncoderConfig;console.log(`set encode bitrate to specified ${e}`),this.context.emit("video-encoder-config",{bitrate:e,width:t,height:i,framerate:n}),this._inAdjustEncode=!0}_increaseBitrate(){this._dbrIncTimeout=0,this._dbrPrevBitrate=this.getCurrentBitrate();const e=this.context.videoEncoderConfig.originBitrate;if(!e)return;let t=this.getCurrentBitrate()+e*this.config.dbrIncreaseStep;t>=e?t=e:this._dbrIncTimeout=Date.now()+this.config.uplinkBitrateCheckInterval,this._setEncoderBitrate(t)}_decreaseBitrate(){const e=this._dbrPrevBitrate;let t=0,i;if(this.upstream.getEstimateBandwidth()&&this.upstream.getEstimateBandwidth()<this.getCurrentBitrate()&&(t=Math.floor(this.upstream.getEstimateBandwidth()*90/100/1e5)*1e5,t<50*1e3&&(t=50*1e3),this.upstream.clearEstimateBandwidth()),t)i=t;else if(e)console.log("use prev bitrate",e),i=e;else return;this._dbrPrevBitrate=0,this._dbrIncTimeout=Date.now()+this.config.uplinkBitrateCheckInterval,this._setEncoderBitrate(i)}_checkBitrate(){this._dbrIncTimeout&&Date.now()>=this._dbrIncTimeout&&(this._isHavingCongestion()?this._dbrIncTimeout=Date.now()+this.config.uplinkBitrateCheckInterval:this._increaseBitrate()),this._isHavingCongestion()&&this.streamBuffer.getVideoDuration()>500&&this._decreaseBitrate()}onSendStream(e,t){return this._checkBitrate(),this.streamBuffer.addPacket(e,t),this.upSpeed.addSample(e.byteLength),this._sendBuffer(),!1}async _sendBuffer(){if(!this.isSending){for(this.isSending=!0;;){const e=this.streamBuffer.shiftSinglePacket();if(!e)break;await this.sendStream(e)}this.isSending=!1}}onSendDgm(){return!0}_checkDeleteCache(e=!1){this._inAdjustEncode&&e&&(console.log(`ajust encode setting finish, delete cached ${this.streamBuffer.size} frame`),this.streamBuffer.reset(),this.upSpeed.reset(),this._inAdjustEncode=!1)}}class De extends p{constructor(e){super(),this.entry=e,this.on({"video-encoder-config":t=>{this.entry.videoEncoder.updateConfig(t)},"audio-encoder-config":t=>{this.entry.audioEncoder.updateConfig(t)}})}get videoEncoderConfig(){return this.entry.videoEncoder.getConfig()}get audioEncoderConfig(){return this.entry.audioEncoder.getConfig()}}class Ie extends p{constructor({videoEncoder:e,audioEncoder:t,transport:i,flv:n,strategy:r,formatAV:a=!0}={}){super(),this.hasVideo=!0,this.stopVideoInput=()=>{},this.stopAudioInput=()=>{},this._isVideoEncoded=!1,this._destroy=!1,this.reconnecting=!1,this.context=new De(this),this.videoEncoder=e||new k,this.audioEncoder=t||new v,this.transport=i||new he,this.flv=n||new Ee,a&&(this.avFormat=new ge,this.initAvFormatEventListener()),this.strategy=r||new Ae(this.context);const{sampleRate:o,numberOfChannels:c}=this.audioEncoder.getConfig();this.flv.updateConfig(_({sampleRate:o,numberOfChannels:c}))}initAvFormatEventListener(){this.avFormat.on("processed-frame",(e,t,i)=>{const n=e;if(n instanceof EncodedAudioChunk&&this.flv.receiveMediaFrame({type:y.AUDIO,frame:n},({buffer:r,type:a})=>{this.transport.sendStream(r,{extra:{isAudio:!0,type:a,key:!0,mediaType:"audio",dts:n.syncTimestamp}})}),n instanceof EncodedVideoChunk){const r=n.type==="key";this.flv.receiveMediaFrame({type:y.VIDEO,frame:n,description:i==null?void 0:i.description},({buffer:a,type:o})=>{this.transport.sendStream(a,{extra:{isAudio:!1,type:o,key:r,mediaType:"video",dts:n.syncTimestamp}})})}})}start(e){const t=e.data,i={},n={};if(e.video){const{width:r,height:a,frameRate:o}=t.setting.video||{};Object.assign(i,_({width:r,height:a,framerate:o}))}if(e.audio){const{sampleRate:r,channelCount:a}=t.setting.audio||{};Object.assign(n,_({sampleRate:r,numberOfChannels:a}))}if(t.cfg){const{channel:r,gopSize:a,sampleRate:o}=t.cfg;e.video&&Object.assign(i,_({keyGopSize:a,bitrate:t.bitrate.video,originBitrate:t.bitrate.video})),e.audio&&Object.assign(n,_({numberOfChannels:r,sampleRate:o,bitrate:t.bitrate.audio}))}this.videoEncoder.updateConfig(i),this.audioEncoder.updateConfig(n),this.init({transport:{url:t.url,maxReconnectCount:t.maxReconnectCount,autoReconnect:t.autoReconnect},input:{audio:e.audio,video:e.video}}),console.log("On worker start",t)}async init(e){this.initPassEvents();const{url:t,maxReconnectCount:i,autoReconnect:n}=e.transport;this.options=e,await this.transport.init({url:t,maxReconnectCount:i,autoReconnect:n,strategy:this.strategy,useDownstream:!1}),this.initSyncStuff(e),this.emit("engine-ready")}initPassEvents(){this.passEvents(this.transport,["connect-open","connect-close","disconnected","reconnecting","reconnected","reconnect-fail","connect-fail"])}initWriter(e){e&&(e.stream?this.initInputWithStream(e.stream):(e.audio||e.video)&&this.initInput({video:e.video,audio:e.audio}))}initSyncStuff({encoder:e,input:t,flv:i}){this.videoEncoder.init(e==null?void 0:e.video),this.audioEncoder.init(e==null?void 0:e.audio),this.initWriter(t),this.flv.updateConfig(i),this.initEngineEvents()}async initInput({audio:e,video:t}){this.hasVideo=!!t,this.flv.updateConfig({hasAudio:!!e,hasVideo:!!t}),await this.transport.onWait("upstream-ready");const i=(r=!1)=>()=>{console.log("encode finish: ",r)},n=(r=!1)=>a=>{console.warn("encode error: ",r,a)};e&&(this.stopAudioInput=O({readable:e,onFrame:r=>{this._destroy||this.reconnecting||this.audioEncoder.encode(r)},onFinish:i(!0),onError:n(!0)})),t&&(this.stopVideoInput=O({readable:t,onFrame:r=>{this._destroy||this.reconnecting||this.videoEncoder.encode(r)},onFinish:i(),onError:n()}))}initInputWithStream(e){const{video:t,audio:i}=W(e);this.hasVideo=!!t,t&&this.videoEncoder.updateConfig(t.settings),i&&this.audioEncoder.updateConfig(i.settings),this.initInput({video:t==null?void 0:t.readable,audio:i==null?void 0:i.readable})}muxAndSend(e,t,i){this.avFormat.formatFrame(e,t,this.hasVideo,i)}initEngineEvents(){this._isVideoEncoded=!this.hasVideo,this.audioEncoder.on({"first-frame-encoded":()=>{this.emit("first-audio-frame-encoded")},"frame-encoded":e=>{this.reconnecting||this.muxAndSend(e,"audio")},"encode-error":e=>{this.triggerError("audio encode error",e)},"config-error":e=>{this.triggerError("audio config error",e)},"config-change":e=>{console.log("Encoder config audio",e)},"decoder-config-change":e=>{this.flv.updateConfig(e)}}),this.videoEncoder.on({"first-frame-encoded":()=>{this.emit("first-video-frame-encoded")},"frame-encoded":(e,t)=>{this.reconnecting||(this._isVideoEncoded||(this._isVideoEncoded=!0),this.muxAndSend(e,"video",t))},"encode-error":e=>{this.triggerError("video encode error",e)},"config-error":e=>{this.triggerError("video config error",e)},"config-change":e=>{console.log("Encoder config video",e)}})}triggerError(e,t){this.emit("error",{info:e,err:t})}async destroy(){this.stopVideoInput(),this.stopAudioInput(),console.log("transport close 1"),await this.transport.destroy(),await this.videoEncoder.destroy(),await this.audioEncoder.destroy(),this.flv.destroy(),super.destroy()}online(){this.transport.online()}setBitrate(e,t){(t==="audio"?this.audioEncoder:this.videoEncoder).updateConfig({bitrate:e,originBitrate:e})}getStats(){return{video:this.videoEncoder.getStats(),audio:this.audioEncoder.getStats(),upspeed:this.transport.getUpSpeed(),upBandwidth:this.transport.getUpBandwidth()}}async reconnect(e){this.reconnecting=!0,this.strategy.reset(),this.avFormat.reset(),this.flv.reset(),this._isVideoEncoded=!this.hasVideo,this.videoEncoder.resetKeyFrame(),this.transport.reconnect(e),await this.transport.onWait("upstream-ready",{prev:!1}),this.reconnecting=!1}}class Te extends M{receiveMainMessage(e){var t,i,n,r,a,o,c;switch(e.type){case g.Start:{this.startMsg=e,this.engine=new Ie,this.initPassEvents(),this.engine.start(e);break}case g.Stop:(t=this.engine)==null||t.destroy();break;case g.UpdateTrack:{const{engine:h}=this;if(!h)return;const d=e.data;d.isAudio?h.stopAudioInput():h.stopVideoInput(),h.initInput({[d.isAudio?"audio":"video"]:d.stream}),(i=h.avFormat)==null||i.reset(),d.setting&&(d.isAudio?h.audioEncoder:h.videoEncoder).updateConfig(d.setting)}break;case g.SetBitrate:(n=this.engine)==null||n.setBitrate(e.data.bitrate,e.data.type);break;case g.Online:(r=this.engine)==null||r.online();break;case g.Reconnect:(o=this.engine)==null||o.reconnect((a=e.data)==null?void 0:a.url);break;case g.GetStats:this.send(g.GetStats,((c=this.engine)==null?void 0:c.getStats())||{});break}}initPassEvents(){["engine-ready","first-audio-frame-encoded","first-video-frame-encoded","error","connect-fail","connect-open","disconnected","reconnected","reconnecting","reconnect-fail","connect-close"].forEach(e=>{this.engine.on(e,t=>{this.send(g.PassEngineEvent,{event:e,data:t})})})}}new Te})();\n',tc=typeof self<"u"&&self.Blob&&new Blob([ec],{type:"text/javascript;charset=utf-8"});function Rg(i){let e;try{if(e=tc&&(self.URL||self.webkitURL).createObjectURL(tc),!e)throw"";const t=new Worker(e,{name:i==null?void 0:i.name});return t.addEventListener("error",()=>{(self.URL||self.webkitURL).revokeObjectURL(e)}),t}catch{return new Worker("data:text/javascript;charset=utf-8,"+encodeURIComponent(ec),{name:i==null?void 0:i.name})}finally{e&&(self.URL||self.webkitURL).revokeObjectURL(e)}}var we=function(){return(we=Object.assign||function(i){for(var e,t=1,r=arguments.length;t<r;t++)for(var n in e=arguments[t])Object.prototype.hasOwnProperty.call(e,n)&&(i[n]=e[n]);return i}).apply(this,arguments)};function Dg(i,e){var t,r,n,s,a={label:0,sent:function(){if(1&n[0])throw n[1];return n[1]},trys:[],ops:[]};return s={next:o(0),throw:o(1),return:o(2)},typeof Symbol=="function"&&(s[Symbol.iterator]=function(){return this}),s;function o(d){return function(c){return function(u){if(t)throw new TypeError("Generator is already executing.");for(;a;)try{if(t=1,r&&(n=2&u[0]?r.return:u[0]?r.throw||((n=r.return)&&n.call(r),0):r.next)&&!(n=n.call(r,u[1])).done)return n;switch(r=0,n&&(u=[2&u[0],n.value]),u[0]){case 0:case 1:n=u;break;case 4:return a.label++,{value:u[1],done:!1};case 5:a.label++,r=u[1],u=[0];continue;case 7:u=a.ops.pop(),a.trys.pop();continue;default:if(!(n=(n=a.trys).length>0&&n[n.length-1])&&(u[0]===6||u[0]===2)){a=0;continue}if(u[0]===3&&(!n||u[1]>n[0]&&u[1]<n[3])){a.label=u[1];break}if(u[0]===6&&a.label<n[1]){a.label=n[1],n=u;break}if(n&&a.label<n[2]){a.label=n[2],a.ops.push(u);break}n[2]&&a.ops.pop(),a.trys.pop();continue}u=e.call(i,a)}catch(l){u=[6,l],r=0}finally{t=n=0}if(5&u[0])throw u[1];return{value:u[0]?u[1]:void 0,done:!0}}([d,c])}}}function xg(i,e){var t=typeof Symbol=="function"&&i[Symbol.iterator];if(!t)return i;var r,n,s=t.call(i),a=[];try{for(;(e===void 0||e-- >0)&&!(r=s.next()).done;)a.push(r.value)}catch(o){n={error:o}}finally{try{r&&!r.done&&(t=s.return)&&t.call(s)}finally{if(n)throw n.error}}return a}function Ln(){for(var i=[],e=0;e<arguments.length;e++)i=i.concat(xg(arguments[e]));return i}var ic,Ig=function(){function i(){this._hooks={},this._cache=[],this._hooksCache={}}return i.prototype.on=function(e,t){e&&t&&typeof t=="function"&&(this._hooks[e]||(this._hooks[e]=[]),this._hooks[e].push(t))},i.prototype.once=function(e,t){var r=this;e&&t&&typeof t=="function"&&this.on(e,function n(s){t(s),r.off(e,n)})},i.prototype.off=function(e,t){if(e&&this._hooks[e]&&this._hooks[e].length)if(t){var r=this._hooks[e].indexOf(t);r!==-1&&this._hooks[e].splice(r,1)}else this._hooks[e]=[]},i.prototype.emit=function(e,t,r){if(r){if(!e)return;this._cache.indexOf(r)!==-1?this._emit(e,t):(this._hooksCache.hasOwnProperty(r)||(this._hooksCache[r]={}),this._hooksCache[r].hasOwnProperty(e)||(this._hooksCache[r][e]=[]),this._hooksCache[r][e].push(t))}else this._emit(e,t)},i.prototype._emit=function(e,t){e&&this._hooks[e]&&this._hooks[e].length&&Ln(this._hooks[e]).forEach(function(r){try{r(t)}catch{}})},i.prototype.set=function(e){e&&this._cache.indexOf(e)===-1&&this._cache.push(e)},i}(),rc=function(i){return i!=null&&Object.prototype.toString.call(i)=="[object Object]"},Og=(ic=+Date.now()+Number((""+Math.random()).slice(2,8)),function(){return ic+=1}),Un=function(i){return function(e,t,r){if(typeof e=="string"&&typeof r=="number"){var n,s=[];r=r<=25?r:r%25;var a=String.fromCharCode(r+97);n=e.split(a);for(var o=0;o<n.length;o++){var d=parseInt(n[o],r);d=1*d^t;var c=String.fromCharCode(d);s.push(c)}return s.join("")}}(i,64,25)},Mg=function(i,e){i===void 0&&(i=function(){}),e===void 0&&(e=1e3);var t,r=Date.now()+e;return t=window.setTimeout(function n(){var s=Date.now()-r;i(),r+=e,t=window.setTimeout(n,Math.max(0,e-s))},e),function(){window.clearTimeout(t)}},nc=function(i){var e=document.createElement("a");return e.href=i,e},Gn=function(i){var e={};try{var t=nc(i).search;if(!t)return e;(t=t.slice(1)).split("&").forEach(function(r){var n,s,a=r.split("=");a.length&&(n=a[0],s=a[1]);try{e[n]=decodeURIComponent(s===void 0?"":s)}catch{e[n]=s}})}catch{}return e},sc=function(i){for(var e=0,t=0,r=(i+="").length,n=0;n<r;n++)((e=31*e+i.charCodeAt(t++))>0x7fffffffffff||e<-0x800000000000)&&(e&=0xffffffffffff);return e<0&&(e+=0x7ffffffffffff),e},Nn,Bn=(function(i,e){var t;t=function(){function r(){for(var s=0,a={};s<arguments.length;s++){var o=arguments[s];for(var d in o)a[d]=o[d]}return a}function n(s){return s.replace(/(%[0-9A-Z]{2})+/g,decodeURIComponent)}return function s(a){function o(){}function d(u,l,h){if(typeof document<"u"){typeof(h=r({path:"/"},o.defaults,h)).expires=="number"&&(h.expires=new Date(1*new Date+864e5*h.expires)),h.expires=h.expires?h.expires.toUTCString():"";try{var p=JSON.stringify(l);/^[\{\[]/.test(p)&&(l=p)}catch{}l=a.write?a.write(l,u):encodeURIComponent(String(l)).replace(/%(23|24|26|2B|3A|3C|3E|3D|2F|3F|40|5B|5D|5E|60|7B|7D|7C)/g,decodeURIComponent),u=encodeURIComponent(String(u)).replace(/%(23|24|26|2B|5E|60|7C)/g,decodeURIComponent).replace(/[\(\)]/g,escape);var f="";for(var v in h)h[v]&&(f+="; "+v,h[v]!==!0&&(f+="="+h[v].split(";")[0]));return document.cookie=u+"="+l+f}}function c(u,l){if(typeof document<"u"){for(var h={},p=document.cookie?document.cookie.split("; "):[],f=0;f<p.length;f++){var v=p[f].split("="),m=v.slice(1).join("=");l||m.charAt(0)!=='"'||(m=m.slice(1,-1));try{var b=n(v[0]);if(m=(a.read||a)(m,b)||n(m),l)try{m=JSON.parse(m)}catch{}if(h[b]=m,u===b)break}catch{}}return u?h[u]:h}}return o.set=d,o.get=function(u){return c(u,!1)},o.getJSON=function(u){return c(u,!0)},o.remove=function(u,l){d(u,"",r(l,{expires:-1}))},o.defaults={},o.withConverter=s,o}(function(){})},i.exports=t()}(Nn={exports:{}},Nn.exports),Nn.exports),Vn=function(i,e){try{return i?Bn.get(i,{domain:e||document.domain}):Bn.get()}catch{return""}},Fn=function(i,e,t,r){try{var n=r||document.domain,s=+new Date+(t||6048e5);Bn.set(i,e,{expires:new Date(s),path:"/",domain:n})}catch{}},Pg=function(){function i(){this.cache={}}return i.prototype.setItem=function(e,t){this.cache[e]=t},i.prototype.getItem=function(e){return this.cache[e]},i.prototype.removeItem=function(e){this.cache[e]=void 0},i.prototype.getCookie=function(e,t){return Vn(e,t)},i.prototype.setCookie=function(e,t,r,n){Fn(e,t,r,n)},i}(),jn,k,oc={getItem:function(i){try{var e=localStorage.getItem(i),t=e;try{e&&typeof e=="string"&&(t=JSON.parse(e))}catch{}return t||{}}catch{}return{}},setItem:function(i,e){try{var t=typeof e=="string"?e:JSON.stringify(e);localStorage.setItem(i,t)}catch{}},removeItem:function(i){try{localStorage.removeItem(i)}catch{}},getCookie:function(i,e){return Vn(i,e)},setCookie:function(i,e,t,r){Fn(i,e,t,r)},isSupportLS:function(){try{return localStorage.setItem("_ranger-test-key","hi"),localStorage.getItem("_ranger-test-key"),localStorage.removeItem("_ranger-test-key"),!0}catch{return!1}}()},Lg={getItem:function(i){try{var e=sessionStorage.getItem(i),t=e;try{e&&typeof e=="string"&&(t=JSON.parse(e))}catch{}return t||{}}catch{}return{}},setItem:function(i,e){try{var t=typeof e=="string"?e:JSON.stringify(e);sessionStorage.setItem(i,t)}catch{}},removeItem:function(i){try{sessionStorage.removeItem(i)}catch{}},getCookie:function(i,e){return Vn(i,e)},setCookie:function(i,e,t,r){Fn(i,e,t,r)},isSupportSession:function(){try{return sessionStorage.setItem("_ranger-test-key","hi"),sessionStorage.getItem("_ranger-test-key"),sessionStorage.removeItem("_ranger-test-key"),!0}catch{return!1}}()},qe=function(){function i(e,t){this._storage=t&&t==="session"?Lg:!e&&oc.isSupportLS?oc:new Pg}return i.prototype.getItem=function(e){return this._storage.getItem(e)},i.prototype.setItem=function(e,t){this._storage.setItem(e,t)},i.prototype.getCookie=function(e,t){return this._storage.getCookie(e,t)},i.prototype.setCookie=function(e,t,r,n){this._storage.setCookie(e,t,r,n)},i.prototype.removeItem=function(e){this._storage.removeItem(e)},i}(),Ug=function(){function i(e,t,r){this.appid=e,this.domain=t,this.userAgent=window.navigator.userAgent,this.appVersion=window.navigator.appVersion,this.cookie_expire=r}return i.prototype.init=function(){var e=window.navigator.userAgent,t=window.navigator.language,r=document.referrer,n=r?nc(r).hostname:"",s=Gn(window.location.href),a=/Mobile|htc|mini|Android|iP(ad|od|hone)/.test(this.appVersion)?"wap":"web";this.utm=function(c,u,l,h){var p=new qe(!1),f=new qe(!1,"session"),v=c?"_tea_utm_cache_"+c:"_tea_utm_cache",m=c?"_$utm_from_url_"+c:"_$utm_from_url",b={},y=["tr_shareuser","tr_admaster","tr_param1","tr_param2","tr_param3","tr_param4","$utm_from_url"],_={ad_id:Number(u.ad_id)||void 0,campaign_id:Number(u.campaign_id)||void 0,creative_id:Number(u.creative_id)||void 0,utm_source:u.utm_source,utm_medium:u.utm_medium,utm_campaign:u.utm_campaign,utm_term:u.utm_term,utm_content:u.utm_content,tr_shareuser:u.tr_shareuser,tr_admaster:u.tr_admaster,tr_param1:u.tr_param1,tr_param2:u.tr_param2,tr_param3:u.tr_param3,tr_param4:u.tr_param4};try{var E=!1;for(var z in _)_[z]&&(y.indexOf(z)!==-1?(b.hasOwnProperty("tracer_data")||(b.tracer_data={}),b.tracer_data[z]=_[z]):b[z]=_[z],E=!0);if(E)f.setItem(m,"1"),p.setCookie(v,JSON.stringify(b),h,l);else{var T=p.getCookie(v,l);T&&(b=JSON.parse(T))}f.getItem(m)&&(b.hasOwnProperty("tracer_data")||(b.tracer_data={}),b.tracer_data.$utm_from_url=1)}catch{return _}return b}(this.appid,s,this.domain,this.cookie_expire);var o=this.browser(),d=this.os();return{browser:o.browser,browser_version:o.browser_version,platform:a,os_name:d.os_name,os_version:d.os_version,userAgent:e,screen_width:window.screen&&window.screen.width,screen_height:window.screen&&window.screen.height,device_model:this.getDeviceModel(d.os_name),language:t,referrer:r,referrer_host:n,utm:this.utm,latest_data:this.last(r,n)}},i.prototype.last=function(e,t){var r="",n="",s="",a=location.hostname,o=!1;if(e&&t&&a!==t){r=e,n=t,o=!0;var d=Gn(e);d.keyword&&(s=d.keyword)}return{$latest_referrer:r,$latest_referrer_host:n,$latest_search_keyword:s,isLast:o}},i.prototype.browser=function(){var e,t,r="",n=""+parseFloat(this.appVersion),s=this.userAgent;return s.indexOf("Edge")!==-1||s.indexOf("Edg")!==-1?(r="Microsoft Edge",s.indexOf("Edge")!==-1?(e=s.indexOf("Edge"),n=s.substring(e+5)):(e=s.indexOf("Edg"),n=s.substring(e+4))):(e=s.indexOf("MSIE"))!==-1?(r="Microsoft Internet Explorer",n=s.substring(e+5)):(e=s.indexOf("Lark"))!==-1?(r="Lark",n=s.substring(e+5,e+11)):(e=s.indexOf("MetaSr"))!==-1?(r="sougoubrowser",n=s.substring(e+7,e+10)):s.indexOf("MQQBrowser")!==-1||s.indexOf("QQBrowser")!==-1?(r="qqbrowser",s.indexOf("MQQBrowser")!==-1?(e=s.indexOf("MQQBrowser"),n=s.substring(e+11,e+15)):s.indexOf("QQBrowser")!==-1&&(e=s.indexOf("QQBrowser"),n=s.substring(e+10,e+17))):s.indexOf("Chrome")!==-1?(e=s.indexOf("MicroMessenger"))!==-1?(r="weixin",n=s.substring(e+15,e+20)):(e=s.indexOf("360"))!==-1?(r="360browser",n=s.substring(s.indexOf("Chrome")+7)):s.indexOf("baidubrowser")!==-1||s.indexOf("BIDUBrowser")!==-1?(s.indexOf("baidubrowser")!==-1?(e=s.indexOf("baidubrowser"),n=s.substring(e+13,e+16)):s.indexOf("BIDUBrowser")!==-1&&(e=s.indexOf("BIDUBrowser"),n=s.substring(e+12,e+15)),r="baidubrowser"):(e=s.indexOf("xiaomi"))!==-1?s.indexOf("openlanguagexiaomi")!==-1?(r="openlanguage xiaomi",n=s.substring(e+7,e+13)):(r="xiaomi",n=s.substring(e-7,e-1)):(e=s.indexOf("TTWebView"))!==-1?(r="TTWebView",n=s.substring(e+10,e+23)):((e=s.indexOf("Chrome"))!==-1||(e=s.indexOf("Chrome"))!==-1)&&(r="Chrome",n=s.substring(e+7)):s.indexOf("Safari")!==-1?(e=s.indexOf("QQ"))!==-1?(r="qqbrowser",n=s.substring(e+10,e+16)):(e=s.indexOf("Safari"))!==-1&&(r="Safari",n=s.substring(e+7),(e=s.indexOf("Version"))!==-1&&(n=s.substring(e+8))):(e=s.indexOf("Firefox"))!==-1?(r="Firefox",n=s.substring(e+8)):(e=s.indexOf("MicroMessenger"))!==-1?(r="weixin",n=s.substring(e+15,e+20)):(e=s.indexOf("QQ"))!==-1&&(r="qqbrowser",n=s.substring(e+3,e+8)),(t=n.indexOf(";"))!==-1&&(n=n.substring(0,t)),(t=n.indexOf(" "))!==-1&&(n=n.substring(0,t)),(t=n.indexOf(")"))!==-1&&(n=n.substring(0,t)),{browser:r,browser_version:n}},i.prototype.os=function(){for(var e="",t="",r=[{s:"Windows 10",r:/(Windows 10.0|Windows NT 10.0|Windows NT 10.1)/},{s:"Windows 8.1",r:/(Windows 8.1|Windows NT 6.3)/},{s:"Windows 8",r:/(Windows 8|Windows NT 6.2)/},{s:"Windows 7",r:/(Windows 7|Windows NT 6.1)/},{s:"Android",r:/Android/},{s:"iOS",r:/(iPhone|iPad|iPod)/},{s:"Mac OS X",r:/Mac OS X/},{s:"Mac OS",r:/(MacPPC|MacIntel|Mac_PowerPC|Macintosh)/},{s:"chromeOS",r:/CrOS/},{s:"Linux",r:/(Linux|X11)/},{s:"Sun OS",r:/SunOS/}],n=0;n<r.length;n++){var s=r[n];if(s.r.test(this.userAgent)){(e=s.s)==="Mac OS X"&&this.isNewIpad()&&(e="iOS");break}}var a=function(l,h){var p=l.exec(h);return p&&p[1]?p[1]:""},o=function(l,h){var p=RegExp("(?:^|[^A-Z0-9-_]|[^A-Z0-9-]_|sprd-)(?:"+l+")","i").exec(h);return p?p.slice(1)[0]:""};/Windows/.test(e)&&(t=a(/Windows (.*)/,e),e="windows");var d,c;switch(e){case"Mac OS X":t=o("Mac[ +]OS[ +]X(?:[ /](?:Version )?(\\d+(?:[_\\.]\\d+)+))?",this.userAgent),e="mac";break;case"Android":d=this.userAgent,(c=a(/Android ([\.\_\d]+)/,d))||(c=a(/Android\/([\.\_\d]+)/,d)),t=c,e="android";break;case"iOS":t=this.isNewIpad()?o("Mac[ +]OS[ +]X(?:[ /](?:Version )?(\\d+(?:[_\\.]\\d+)+))?",this.userAgent):(t=/OS (\d+)_(\d+)_?(\d+)?/.exec(this.appVersion))?t[1]+"."+t[2]+"."+(0|t[3]):"",e="ios";break;case"chromeOS":var u=this.userAgent.indexOf("x86_64");t=this.userAgent.substring(u+7,u+16)}return{os_name:e,os_version:t}},i.prototype.getDeviceModel=function(e){var t="";try{if(e==="android")navigator.userAgent.split(";").forEach(function(s){s.indexOf("Build/")>-1&&(t=s.slice(0,s.indexOf("Build/")))});else if(e==="ios"||e==="mac"||e==="windows")if(this.isNewIpad())t="iPad";else{var r=navigator.userAgent.replace("Mozilla/5.0 (",""),n=r.indexOf(";");t=r.slice(0,n)}}catch{return t.trim()}return t.trim()},i.prototype.isNewIpad=function(){return this.userAgent!==void 0&&navigator.platform==="MacIntel"&&typeof navigator.maxTouchPoints=="number"&&navigator.maxTouchPoints>1},i}(),Gg={cn:"1fz22z22z1nz21z4mz4bz4bz22z1mz19z1jz1mz1ez4az1az22z1mz19z21z1lz21z21z1bz1iz4az1az1mz1k",va:"1fz22z22z1nz21z4mz4bz4bz22z1mz19z1jz1mz1ez4az1gz22z1mz19z21z1lz21z21z1bz1iz4az1az1mz1k",sg:"1fz22z22z1nz21z4mz4bz4bz22z1mz19z1jz1mz1ez4az22z1mz19z21z1lz21z21z1bz1iz4az1az1mz1k"},Ng={cn:"1fz22z22z1nz21z4mz4bz4bz1kz1az21z4az28z1gz1hz1gz1cz18z1nz1gz4az1az1mz1k",sg:"1fz22z22z1nz21z4mz4bz4bz21z1ez18z1jz1gz49z1kz1az21z4az19z27z22z1cz1mz24z1cz20z21z1cz18z4az1az1mz1k",va:"1fz22z22z1nz21z4mz4bz4bz1kz18z1jz1gz24z18z49z1kz1az21z4az19z27z22z1cz1mz24z1cz20z21z1cz18z4az1az1mz1k"},Ti="5.1.10",Hn=function(){function i(e,t){this.collector=e,this.config=t,this.eventNameWhiteList=["__bav_page","__bav_beat","__bav_page_statistics","__bav_click","__bav_page_exposure"],this.paramsNameWhiteList=["$inactive","$inline","$target_uuid_list","$source_uuid","$is_spider","$source_id","$is_first_time","_staging_flag"],this.regStr=new RegExp("^[a-zA-Z0-9][a-z0-9A-Z_.-]{1,255}$")}return i.prototype.checkVerify=function(e){var t=this;if(!e||!e.length)return!1;var r=e[0];if(!r)return!1;var n=r.events,s=r.header;if(!n||!n.length)return!1;var a=!0;return n.forEach(function(o){if(!o)return a=!1,void(o.checkEvent="事件异常");t.checkEventName(o.event)||(a=!1,o.checkEvent="事件名不能以 $ or __开头"),t.checkEventParams(o.params)||(a=!1,o.checkParams="属性名不能以 $ or __开头")}),this.checkEventParams(s)||(a=!1),a},i.prototype.checkEventName=function(e){return!!e&&this.calculate(e,"event")},i.prototype.checkEventParams=function(e){var t=e;if(typeof e=="string"&&(t=JSON.parse(t)),!Object.keys(t).length)return!0;for(var r in t)return!!this.calculate(r,"params")&&(!(typeof t[r]=="string"&&t[r].length>1024)||(console.warn("params: "+r+" can not over 1024 byte, please check;"),!1));return!0},i.prototype.calculate=function(e,t){return(t==="event"?this.eventNameWhiteList:this.paramsNameWhiteList).indexOf(e)!==-1||!new RegExp("^\\$").test(e)&&!new RegExp("^__").test(e)||(console.warn((t==="event"?"event":"params")+" name: "+e+" can not start with $ or __, pleace check;"),!1)},i}();(function(i){i.Init="init",i.Config="config",i.Start="start",i.Ready="ready",i.UnReady="un-ready",i.TokenComplete="token-complete",i.TokenStorage="token-storage",i.TokenFetch="token-fetch",i.TokenError="token-error",i.ConfigUuid="config-uuid",i.ConfigWebId="config-webid",i.ConfigDomain="config-domain",i.CustomWebId="custom-webid",i.TokenChange="token-change",i.TokenReset="token-reset",i.ConfigTransform="config-transform",i.EnvTransform="env-transform",i.SessionReset="session-reset",i.SessionResetTime="session-reset-time",i.SetSessionId="set-session-id",i.Event="event",i.Events="events",i.EventNow="event-now",i.CleanEvents="clean-events",i.BeconEvent="becon-event",i.SubmitBefore="submit-before",i.SubmitScuess="submit-scuess",i.SubmitAfter="submit-after",i.SubmitError="submit-error",i.SubmitVerify="submit-verify",i.Stay="stay",i.ResetStay="reset-stay",i.StayReady="stay-ready",i.SetStay="set-stay",i.RouteChange="route-change",i.RouteReady="route-ready",i.Ab="ab",i.AbVar="ab-var",i.AbAllVars="ab-all-vars",i.AbConfig="ab-config",i.AbExternalVersion="ab-external-version",i.AbVersionChangeOn="ab-version-change-on",i.AbVersionChangeOff="ab-version-change-off",i.AbOpenLayer="ab-open-layer",i.AbCloseLayer="ab-close-layer",i.AbReady="ab-ready",i.AbComplete="ab-complete",i.AbTimeout="ab-timeout",i.Profile="profile",i.ProfileSet="profile-set",i.ProfileSetOnce="profile-set-once",i.ProfileUnset="profile-unset",i.ProfileIncrement="profile-increment",i.ProfileAppend="profile-append",i.ProfileClear="profile-clear",i.Autotrack="autotrack",i.AutotrackReady="autotrack-ready",i.CepReady="cep-ready",i.TracerReady="tracer-ready",i.sessionRecord="session-record",i.SessionRecordStart="session-record-start",i.SessionRecordPause="session-record-pause",i.SessionRecordEnd="session-record-end",i.SessionRecordReport="session-record-report",i.DestoryInstance="destory-instance",i.VisualCollectReady="visual-collect-ready",i.VisualApiReady="visual-api-ready",i.VisualApiUpdate="visual-api-update"})(jn||(jn={})),function(i){i.DEBUGGER_MESSAGE="debugger-message",i.DEBUGGER_MESSAGE_SDK="debugger-message-sdk",i.DEBUGGER_MESSAGE_FETCH="debugger-message-fetch",i.DEBUGGER_MESSAGE_FETCH_RESULT="debugger-message-fetch-result",i.DEBUGGER_MESSAGE_EVENT="debugger-message-event",i.DEVTOOL_WEB_READY="devtool-web-ready"}(k||(k={}));var C=jn,N=void 0,ac=new Date().getTimezoneOffset(),Bg=parseInt(""+-ac/60,10),Vg=60*ac,Fg=7776e6,jg=function(){function i(e,t){this.is_first_time=!0,this.configPersist=!1,this.initConfig=t,this.collect=e;var r=new Ug(t.app_id,t.cookie_domain||"",t.cookie_expire||Fg).init();this.eventCheck=new Hn(e,t);var n="__tea_cache_first_"+t.app_id;this.configKey="__tea_cache_config_"+t.app_id,this.sessionStorage=new qe(!1,"session"),this.localStorage=new qe(!1,"local"),t.configPersist&&(this.configPersist=!0,this.storage=t.configPersist===1?this.sessionStorage:this.localStorage);var s=this.localStorage.getItem(n);s&&s==1?this.is_first_time=!1:(this.is_first_time=!0,this.localStorage.setItem(n,"1")),this.envInfo={user:{user_unique_id:N,user_type:N,user_id:N,user_is_auth:N,user_is_login:N,device_id:N,web_id:N,ip_addr_id:N,user_unique_id_type:N},header:{app_id:N,app_name:N,app_install_id:N,install_id:N,app_package:N,app_channel:N,app_version:N,ab_version:N,os_name:r.os_name,os_version:r.os_version,device_model:r.device_model,ab_client:N,traffic_type:N,client_ip:N,device_brand:N,os_api:N,access:N,language:r.language,region:N,app_language:N,app_region:N,creative_id:r.utm.creative_id,ad_id:r.utm.ad_id,campaign_id:r.utm.campaign_id,log_type:N,rnd:N,platform:r.platform,sdk_version:Ti,sdk_lib:"js",province:N,city:N,timezone:Bg,tz_offset:Vg,tz_name:N,sim_region:N,carrier:N,resolution:r.screen_width+"x"+r.screen_height,browser:r.browser,browser_version:r.browser_version,referrer:r.referrer,referrer_host:r.referrer_host,width:r.screen_width,height:r.screen_height,screen_width:r.screen_width,screen_height:r.screen_height,utm_term:r.utm.utm_term,utm_content:r.utm.utm_content,utm_source:r.utm.utm_source,utm_medium:r.utm.utm_medium,utm_campaign:r.utm.utm_campaign,tracer_data:JSON.stringify(r.utm.tracer_data),custom:{},wechat_unionid:N,wechat_openid:N}},this.ab_version="",this.evtParams={},this.reportErrorCallback=function(){},this.isLast=!1,this.setCustom(r),this.initDomain(),this.initABData()}return i.prototype.initDomain=function(){var e=this.initConfig.channel_domain;if(e)this.domain=e;else{var t=this.initConfig.channel;this.domain=Un(Ng[t])}},i.prototype.setDomain=function(e){this.domain=e},i.prototype.getDomain=function(){return this.domain},i.prototype.initABData=function(){var e="__tea_sdk_ab_version_"+this.initConfig.app_id,t=null;if(this.initConfig.ab_cross){var r=this.localStorage.getCookie(e,this.initConfig.ab_cookie_domain);t=r?JSON.parse(r):null}else t=this.localStorage.getItem(e);this.setAbCache(t)},i.prototype.setAbCache=function(e){this.ab_cache=e},i.prototype.getAbCache=function(){return this.ab_cache},i.prototype.setAbVersion=function(e){this.ab_version=e},i.prototype.getAbVersion=function(){return this.ab_version},i.prototype.clearAbCache=function(){this.ab_version="",this.ab_cache={}},i.prototype.getUrl=function(e){var t="";switch(e){case"event":t="/list";break;case"webid":t="/webid";break;case"tobid":t="/tobid"}var r="";return this.initConfig.caller&&(r="?sdk_version="+Ti+"&sdk_name=web&app_id="+this.initConfig.app_id+"&caller="+this.initConfig.caller),""+this.getDomain()+t+r},i.prototype.setCustom=function(e){if(e&&e.latest_data&&e.latest_data.isLast)for(var t in delete e.latest_data.isLast,this.isLast=!0,e.latest_data)this.envInfo.header.custom[t]=e.latest_data[t]},i.prototype.set=function(e){var t=this;Object.keys(e).forEach(function(r){e[r]!==void 0&&e[r]!==null||t.delete(r);try{t.eventCheck.calculate(r,"config")}catch{}if(r==="traffic_type"&&t.isLast&&(t.envInfo.header.custom.$latest_traffic_source_type=e[r]),r==="evtParams")t.evtParams=we({},t.evtParams||{},e.evtParams||{});else if(r==="_staging_flag")t.evtParams=we({},t.evtParams||{},{_staging_flag:e._staging_flag});else if(r==="reportErrorCallback"&&typeof e[r]=="function")t.reportErrorCallback=e[r];else{var n="",s="";if(r.indexOf(".")>-1){var a=r.split(".");n=a[0],s=a[1]}n?n==="user"||n==="header"?t.envInfo[n][s]=e[r]:t.envInfo.header.custom[s]=e[r]:Object.hasOwnProperty.call(t.envInfo.user,r)?["user_type","ip_addr_id"].indexOf(r)>-1?t.envInfo.user[r]=e[r]?Number(e[r]):e[r]:["user_id","web_id","user_unique_id","user_unique_id_type"].indexOf(r)>-1?t.envInfo.user[r]=e[r]?String(e[r]):e[r]:["user_is_auth","user_is_login"].indexOf(r)>-1?t.envInfo.user[r]=!!e[r]:r==="device_id"&&(t.envInfo.user[r]=e[r]):Object.hasOwnProperty.call(t.envInfo.header,r)?t.envInfo.header[r]=e[r]:t.envInfo.header.custom[r]=e[r]}})},i.prototype.get=function(e){try{return e?e==="evtParams"?this.evtParams:e==="reportErrorCallback"?this[e]:Object.hasOwnProperty.call(this.envInfo.user,e)?this.envInfo.user[e]:Object.hasOwnProperty.call(this.envInfo.header,e)?this.envInfo.header[e]:JSON.parse(JSON.stringify(this.envInfo[e])):JSON.parse(JSON.stringify(this.envInfo))}catch(t){console.log("get config stringify error "),this.collect.emit(k.DEBUGGER_MESSAGE,{type:k.DEBUGGER_MESSAGE_SDK,info:"发生了异常",level:"error",time:Date.now(),data:t.message})}},i.prototype.setStore=function(e){try{if(!this.configPersist)return;var t=this.storage.getItem(this.configKey)||{};if(t&&Object.keys(e).length){var r=Object.assign(e,t);this.storage.setItem(this.configKey,r)}}catch(n){console.log("setStore error"),this.collect.emit(k.DEBUGGER_MESSAGE,{type:k.DEBUGGER_MESSAGE_SDK,info:"发生了异常",level:"error",time:Date.now(),data:n.message})}},i.prototype.getStore=function(){try{if(!this.configPersist)return null;var e=this.storage.getItem(this.configKey)||{};return e&&Object.keys(e).length?e:null}catch(t){return this.collect.emit(k.DEBUGGER_MESSAGE,{type:k.DEBUGGER_MESSAGE_SDK,info:"发生了异常",level:"error",time:Date.now(),data:t.message}),null}},i.prototype.delete=function(e){try{if(!this.configPersist)return;var t=this.storage.getItem(this.configKey)||{};t&&Object.hasOwnProperty.call(t,e)&&(delete t[e],this.storage.setItem(this.configKey,t))}catch(r){this.collect.emit(k.DEBUGGER_MESSAGE,{type:k.DEBUGGER_MESSAGE_SDK,info:"发生了异常",level:"error",time:Date.now(),data:r.message}),console.log("delete error")}},i}(),Hg=function(){function i(e,t){this.isLog=t||!1,this.name=e||""}return i.prototype.info=function(e){this.isLog&&console.log("%c %s","color: yellow; background-color: black;","[AppLog WEB SDK] [instance: "+this.name+"] "+e)},i.prototype.warn=function(e){this.isLog&&console.warn("[AppLog WEB SDK] [instance: "+this.name+"] "+e)},i.prototype.error=function(e){this.isLog&&console.error("[AppLog WEB SDK] [instance: "+this.name+"] "+e)},i.prototype.throw=function(e){throw this.error(this.name),new Error(e)},i}(),$g=function(){function i(){this.spiderBot=["Baiduspider","googlebot","360Spider","haosouspider","YoudaoBot","Sogou News Spider","Yisouspider","Googlebot","Headless","Applebot","Bingbot","PetalBot"]}return i.prototype.checkSpider=function(e){if(!e.enable_spider)return!1;var t=window.navigator.userAgent;if(!t)return!0;var r=!1;return this.spiderBot.forEach(function(n){t.indexOf(n)!==-1&&(r=!0)}),r},i}(),qg=function(){function i(t,r){this.collect=t,this.native=r}var e=i.prototype;return e.bridgeInject=function(){try{return!!this.native&&(AppLogBridge?(console.log("AppLogBridge is injected"),!0):(console.log("AppLogBridge is not inject"),!1))}catch{return console.log("AppLogBridge is not inject"),!1}},e.bridgeReady=function(){var t=this;return new Promise(function(r,n){try{t.bridgeInject()?AppLogBridge.hasStarted(function(s){console.log("AppLogBridge is started? : "+s),s?r(!0):n(!1)}):n(!1)}catch(s){console.log("AppLogBridge, error:"+JSON.stringify(s.stack)),n(!1)}})},e.setNativeAppId=function(t){try{AppLogBridge.setNativeAppId(JSON.stringify(t)),console.log("change bridge appid, event report with appid: "+t)}catch{console.error("setNativeAppId error")}},e.setConfig=function(t){var r=this;try{Object.keys(t).forEach(function(n){n==="user_unique_id"?r.setUserUniqueId(t[n]):t[n]?r.addHeaderInfo(n,t[n]):r.removeHeaderInfo(n)})}catch{console.error("setConfig error")}},e.setUserUniqueId=function(t){try{AppLogBridge.setUserUniqueId(t)}catch{console.error("setUserUniqueId error")}},e.addHeaderInfo=function(t,r){try{AppLogBridge.addHeaderInfo(t,r)}catch{console.error("addHeaderInfo error")}},e.setHeaderInfo=function(t){try{AppLogBridge.setHeaderInfo(JSON.stringify(t))}catch{console.error("setHeaderInfo error")}},e.removeHeaderInfo=function(t){try{AppLogBridge.removeHeaderInfo(t)}catch{console.error("removeHeaderInfo error")}},e.reportPv=function(t){this.onEventV3("predefine_pageview",t)},e.onEventV3=function(t,r){try{AppLogBridge.onEventV3(t,r),this.collect.emit(DebuggerMesssge.DEBUGGER_MESSAGE,{type:DebuggerMesssge.DEBUGGER_MESSAGE_EVENT,info:"bridge埋点上报",time:Date.now(),data:[{events:[{event:t,params:r}]}],code:200,status:"success"})}catch{console.error("onEventV3 error")}},e.profileSet=function(t){try{AppLogBridge.profileSet(t)}catch{console.error("profileSet error")}},e.profileSetOnce=function(t){try{AppLogBridge.profileSetOnce(t)}catch{console.error("profileSetOnce error")}},e.profileIncrement=function(t){try{AppLogBridge.profileIncrement(t)}catch{console.error("profileIncrement error")}},e.profileUnset=function(t){try{AppLogBridge.profileUnset(t)}catch{console.error("profileUnset error")}},e.profileAppend=function(t){try{AppLogBridge.profileAppend(t)}catch{console.error("profileAppend error")}},i}(),Bt=function(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(i){var e=16*Math.random()|0;return(i==="x"?e:3&e|8).toString(16)})},Kg=function(){function i(){}return i.prototype.apply=function(e,t){var r=this;this.collect=e,this.storage=new qe(!1,"session"),this.sessionKey="__tea_session_id_"+t.app_id,this.expireTime=t.expireTime||18e5,this.disableSession=t.disable_session,this.disableSessionTimeCheck=t.disable_session_check,this.disableSession||(this.setSessionId(),this.collect.on(C.SessionReset,function(n){r.resetSessionId(n)}),this.collect.on(C.SessionResetTime,function(){r.updateSessionIdTime()}))},i.prototype.updateSessionIdTime=function(){var e=this.storage.getItem(this.sessionKey);if(e&&e.sessionId){var t=e.timestamp;Date.now()-t>this.expireTime?e={sessionId:Bt(),timestamp:Date.now()}:e.timestamp=Date.now(),this.storage.setItem(this.sessionKey,e),this.resetExpTime()}},i.prototype.setSessionId=function(){var e=this,t=this.storage.getItem(this.sessionKey);t&&t.sessionId?t.timestamp=Date.now():t={sessionId:Bt(),timestamp:Date.now()},this.storage.setItem(this.sessionKey,t),this.disableSessionTimeCheck||(this.sessionExp=setInterval(function(){e.checkEXp()},this.expireTime))},i.prototype.getSessionId=function(){var e=this.storage.getItem(this.sessionKey);return this.disableSession?"":e&&e.sessionId?e.sessionId:""},i.prototype.resetExpTime=function(){var e=this;this.sessionExp&&(clearInterval(this.sessionExp),this.sessionExp=setInterval(function(){e.checkEXp()},this.expireTime))},i.prototype.resetSessionId=function(e){var t={sessionId:e||Bt(),timestamp:Date.now()};this.storage.setItem(this.sessionKey,t)},i.prototype.checkEXp=function(){var e=this.storage.getItem(this.sessionKey);e&&e.sessionId&&Date.now()-e.timestamp+30>=this.expireTime&&(e={sessionId:Bt(),timestamp:Date.now()},this.storage.setItem(this.sessionKey,e))},i}(),Wg=function(){function i(){this.eventLimit=50,this.enable_ttwebid=!1,this.eventCache=[],this.beconEventCache=[]}return i.prototype.apply=function(e,t){var r=this;this.collect=e,this.config=t,this.configManager=e.configManager,this.eventCheck=new Hn(e,t),this.cacheStorgae=new qe(!0),this.localStorage=new qe(!1),this.maxReport=t.max_report||10,this.reportTime=t.reportTime||t.report_time||30,this.timeout=t.timeout||1e5,this.enable_ttwebid=t.enable_ttwebid,this.reportUrl=t.report_url||this.configManager.getUrl("event"),this.eventKey="__tea_cache_events_"+this.configManager.get("app_id"),this.beconKey="__tea_cache_events_becon_"+this.configManager.get("app_id"),this.abKey="__tea_sdk_ab_version_"+this.configManager.get("app_id"),this.refer_key="__tea_cache_refer_"+this.configManager.get("app_id"),this.pageId=Bt(),this.collect.on(C.Ready,function(){r.reportAll(!1)}),this.collect.on(C.ConfigDomain,function(){r.reportUrl=r.configManager.getUrl("event")}),this.collect.on(C.Event,function(s){r.event(s)}),this.collect.on(C.BeconEvent,function(s){r.beconEvent(s)}),this.collect.on(C.CleanEvents,function(){r.reportAll(!1)});var n=this.linster();this.collect.on(C.DestoryInstance,function(){n&&n()})},i.prototype.linster=function(){var e=this,t=function(){e.reportAll(!0)};window.addEventListener("unload",t,!1),function(n){navigator.userAgent.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/)?window.addEventListener("pagehide",n,!1):window.addEventListener("beforeunload",n,!1)}(t);var r=function(){document.visibilityState==="hidden"&&e.reportAll(!0)};return document.addEventListener("visibilitychange",r,!1),function(){window.removeEventListener("unload",t),window.removeEventListener("pagehide",t,!1),window.removeEventListener("beforeunload",t,!1),document.removeEventListener("visibilitychange",r,!1)}},i.prototype.reportAll=function(e){this.report(e),this.reportBecon()},i.prototype.event=function(e){var t=this;try{var r=Ln(e,this.cacheStorgae.getItem(this.eventKey)||[]);if(this.cacheStorgae.setItem(this.eventKey,r),this.reportTimeout&&clearTimeout(this.reportTimeout),r.length>=this.maxReport)this.report(!1);else{var n=this.reportTime;this.reportTimeout=setTimeout(function(){t.report(!1),t.reportTimeout=null},n)}}catch(s){this.collect.emit(k.DEBUGGER_MESSAGE,{type:k.DEBUGGER_MESSAGE_SDK,info:"发生了异常",level:"error",time:Date.now(),data:s.message})}},i.prototype.beconEvent=function(e){var t=Ln(e,this.cacheStorgae.getItem(this.beconKey)||[]);this.cacheStorgae.setItem(this.beconKey,t),this.collect.destroy||this.collect.sdkStop||this.collect.tokenManager.getReady()&&this.collect.sdkReady&&(this.cacheStorgae.removeItem(this.beconKey),this.send(this.split(this.merge(t)),!0))},i.prototype.reportBecon=function(){if(!this.collect.destroy&&!this.collect.sdkStop&&this.collect.tokenManager.getReady()&&this.collect.sdkReady){var e=this.cacheStorgae.getItem(this.beconKey)||[];e&&e.length&&(this.cacheStorgae.removeItem(this.beconKey),this.send(this.split(this.merge(e)),!0))}},i.prototype.report=function(e){if(!this.collect.destroy&&!this.collect.sdkStop&&this.collect.tokenManager.getReady()&&this.collect.sdkReady){var t=this.cacheStorgae.getItem(this.eventKey)||[];t.length&&(this.cacheStorgae.removeItem(this.eventKey),this.sliceEvent(t,e))}},i.prototype.sliceEvent=function(e,t){if(e.length>this.eventLimit)for(var r=0;r<e.length;r+=this.eventLimit){var n;n=e.slice(r,r+this.eventLimit);var s=this.split(this.merge(n));this.send(s,t)}else s=this.split(this.merge(e)),this.send(s,t)},i.prototype.handleRefer=function(){var e="";try{if(this.config.spa||this.config.autotrack){var t=this.localStorage.getItem(this.refer_key)||{};e=t.routeChange?t.refer_key:this.configManager.get("referrer")}else e=this.configManager.get("referrer")}catch{e=document.referrer}return e},i.prototype.merge=function(e,t){var r=this,n=this.configManager.get(),s=n.header,a=n.user;this.config.enable_pageid&&(s.custom.page_id=this.pageId),s.referrer=this.handleRefer(),s.custom=JSON.stringify(s.custom);var o=this.configManager.get("evtParams"),d=this.configManager.get("user_unique_id_type"),c=e.map(function(h){try{Object.keys(o).length&&!t&&(h.params=we({},o,h.params)),d&&(h.params.$user_unique_id_type=d);var p=r.configManager.getAbCache(),f=a[r.config.ab_user_mode]||a.user_unique_id;return p&&p.uuid&&p.uuid===f&&r.configManager.getAbVersion()&&(h.ab_sdk_version=r.configManager.getAbVersion()),h.session_id=r.collect.sessionManager.getSessionId(),h.params=JSON.stringify(h.params),h}catch(v){return r.collect.emit(k.DEBUGGER_MESSAGE,{type:k.DEBUGGER_MESSAGE_SDK,info:"发生了异常",level:"error",time:Date.now(),data:v.message}),h}}),u=JSON.parse(JSON.stringify({events:c,user:a,header:s}));u.local_time=Math.floor(Date.now()/1e3),u.user_unique_type=this.config.enable_ttwebid?this.config.user_unique_type:void 0,u.verbose=1;var l=[];return l.push(u),l},i.prototype.split=function(e){return e=e.map(function(t){var r=[];return r.push(t),r})},i.prototype.send=function(e,t){var r=this;e.length&&(this.config.disable_track_event||e.forEach(function(n){try{var s=JSON.parse(JSON.stringify(n));r.config.filter&&((s=r.config.filter(s))||console.warn("filter must return data !!")),r.collect.eventFilter&&s&&((s=r.collect.eventFilter(s))||console.warn("filterEvent api must return data !!"));var a=s||n,o=JSON.parse(JSON.stringify(a));if(r.eventCheck.checkVerify(o),!a.length)return;var d=!0;if(a.forEach(function(c){c.events.length||(d=!1)}),!d)return;r.collect.emit(C.SubmitBefore,a),r.collect.requestManager.useRequest({url:r.reportUrl,data:a,success:function(c,u){c&&c.e!==0?(r.collect.emit(C.SubmitError,{type:"f_data",eventData:u,errorCode:c.e,response:c}),r.collect.emit(k.DEBUGGER_MESSAGE,{type:k.DEBUGGER_MESSAGE_EVENT,info:"埋点上报失败",time:Date.now(),data:o,code:c.e,failType:"数据异常失败",status:"fail"})):(r.collect.emit(C.SubmitScuess,{eventData:u,res:c}),r.collect.emit(k.DEBUGGER_MESSAGE,{type:k.DEBUGGER_MESSAGE_EVENT,info:"埋点上报成功",time:Date.now(),data:o,code:200,status:"success"}))},fail:function(c,u){r.configManager.get("reportErrorCallback")(c,u),r.collect.emit(C.SubmitError,{type:"f_net",eventData:c,errorCode:u}),r.collect.emit(k.DEBUGGER_MESSAGE,{type:k.DEBUGGER_MESSAGE_EVENT,info:"埋点上报网络异常",time:Date.now(),data:o,code:u,failType:"网络异常失败",status:"fail"})},timeout:r.timeout,useBeacon:t,withCredentials:r.enable_ttwebid}),r.collect.emit(C.SubmitAfter,a)}catch(c){console.warn("something error, "+JSON.stringify(c.stack)),r.collect.emit(k.DEBUGGER_MESSAGE,{type:k.DEBUGGER_MESSAGE_SDK,info:"发生了异常",level:"error",time:Date.now(),data:c.message})}}))},i}(),dr=function(){return function i(e){return e?(e^16*Math.random()>>e/4).toString(10):("10000000-1000-4000-8000"+-1e11).replace(/[018]/g,i)}().replace(/-/g,"").slice(0,19)},Jg=function(){function i(){this.cacheToken={},this.enableCookie=!1,this.enable_ttwebid=!1,this.enableCustomWebid=!1}return i.prototype.apply=function(e,t){var r=this;this.collect=e,this.config=t,this.configManager=this.collect.configManager,this.storage=new qe(!1),this.tokenKey="__tea_cache_tokens_"+t.app_id,this.enable_ttwebid=t.enable_ttwebid,this.enableCustomWebid=t.enable_custom_webid,this.collect.on(C.ConfigUuid,function(n){r.setUuid(n)}),this.collect.on(C.ConfigWebId,function(n){r.setWebId(n)}),this.enableCookie=t.cross_subdomain,this.expiresTime=t.cookie_expire||6048e5,this.cookieDomain=t.cookie_domain||"",this.checkStorage()},i.prototype.checkStorage=function(){var e=this;if(this.enableCookie){var t=this.storage.getCookie(this.tokenKey,this.cookieDomain);this.cacheToken=t&&typeof t=="string"?JSON.parse(t):{}}else this.cacheToken=this.storage.getItem(this.tokenKey)||{};this.tokenType=this.cacheToken&&this.cacheToken._type_?this.cacheToken._type_:"default",this.tokenType!=="custom"||this.enableCustomWebid?this.enableCustomWebid?this.collect.on(C.CustomWebId,function(){e.tokenReady=!0,e.collect.emit(C.TokenComplete)}):this.checkEnv()||(this.enable_ttwebid?this.completeTtWid(this.cacheToken):this.check()):this.remoteWebid()},i.prototype.check=function(){this.cacheToken&&this.cacheToken.web_id?this.complete(this.cacheToken):this.config.disable_webid?this.complete({web_id:dr(),user_unique_id:this.configManager.get("user_unique_id")||dr()}):this.remoteWebid()},i.prototype.checkEnv=function(){var e=window.navigator.userAgent;if(e.indexOf("miniProgram")!==-1||e.indexOf("MiniProgram")!==-1){var t=Gn(window.location.href);return!(!t||!t.Web_ID)&&(this.complete({web_id:""+t.Web_ID,user_unique_id:this.configManager.get("user_unique_id")||""+t.Web_ID}),!0)}return!1},i.prototype.remoteWebid=function(){var e=this,t=this.configManager.getUrl("webid"),r={app_key:this.config.app_key,app_id:this.config.app_id,url:location.href,user_agent:window.navigator.userAgent,referer:document.referrer,user_unique_id:""};this.collect.emit(k.DEBUGGER_MESSAGE,{type:k.DEBUGGER_MESSAGE_SDK,info:"SDK 发起WEBID请求",logType:"fetch",level:"info",time:Date.now(),data:r}),this.collect.requestManager.useRequest({url:t,data:r,success:function(n){var s;if(n&&n.e===0)s=n.web_id,e.collect.emit(k.DEBUGGER_MESSAGE,{type:k.DEBUGGER_MESSAGE_SDK,info:"WEBID请求成功",logType:"fetch",level:"info",time:Date.now(),data:n});else{var a=dr();s=a,e.collect.configManager.set({localWebId:a}),e.collect.emit(C.TokenError),e.collect.emit(k.DEBUGGER_MESSAGE,{type:k.DEBUGGER_MESSAGE_SDK,info:"WEBID请求返回值异常",logType:"fetch",level:"warn",time:Date.now(),data:n}),e.collect.logger.warn("appid: "+e.config.app_id+" get webid error, use local webid~")}e.complete({web_id:e.configManager.get("web_id")||s,user_unique_id:e.configManager.get("user_unique_id")||s})},fail:function(){var n=dr();e.complete({web_id:e.configManager.get("web_id")||n,user_unique_id:e.configManager.get("user_unique_id")||n}),e.collect.configManager.set({localWebId:n}),e.collect.emit(C.TokenError),e.collect.emit(k.DEBUGGER_MESSAGE,{type:k.DEBUGGER_MESSAGE_SDK,info:"WEBID请求网络异常",logType:"fetch",level:"error",time:Date.now(),data:null}),e.collect.logger.warn("appid: "+e.config.app_id+", get webid error, use local webid~")},timeout:3e5})},i.prototype.complete=function(e){var t=e.web_id,r=e.user_unique_id;e.timestamp=Date.now(),this.collect.configManager.set({web_id:t,user_unique_id:r}),this.setStorage(e),this.tokenReady=!0,this.collect.emit(C.TokenComplete)},i.prototype.completeTtWid=function(e){var t=e.user_unique_id||"",r=this.configManager.get("user_unique_id");(r||t)&&this.configManager.set({user_unique_id:r||t}),this.setStorage(e),this.tokenReady=!0,this.collect.emit(C.TokenComplete)},i.prototype.setUuid=function(e){if(e&&["null","undefined","Null","None"].indexOf(e)===-1){var t=String(e),r=this.configManager.get("user_unique_id"),n=this.cacheToken&&this.cacheToken.user_unique_id;if(t===r&&t===n)return;this.configManager.set({user_unique_id:t}),this.cacheToken?this.cacheToken.user_unique_id=t:(this.cacheToken={},this.cacheToken.user_unique_id=t),this.cacheToken.timestamp=Date.now(),this.setStorage(this.cacheToken),this.collect.emit(C.TokenChange,"uuid"),this.collect.emit(C.SessionReset)}else this.clearUuid()},i.prototype.clearUuid=function(){this.config.enable_ttwebid||this.configManager.get("web_id")&&this.configManager.get("user_unique_id")!==this.configManager.get("web_id")&&(this.configManager.set({user_unique_id:this.configManager.get("web_id")}),this.cacheToken&&this.cacheToken.web_id&&(this.cacheToken.user_unique_id=this.cacheToken.web_id,this.cacheToken.timestamp=Date.now(),this.setStorage(this.cacheToken)),this.collect.emit(C.TokenReset,"uuid"))},i.prototype.setWebId=function(e){if(e&&!this.config.enable_ttwebid){this.cacheToken&&this.cacheToken.web_id?this.cacheToken.web_id!==e&&(this.cacheToken.user_unique_id=this.cacheToken.web_id===this.cacheToken.user_unique_id?e:this.cacheToken.user_unique_id,this.cacheToken.web_id=e):(this.cacheToken={},this.cacheToken.web_id=e,this.cacheToken.user_unique_id=e),this.cacheToken.timestamp=Date.now();var t=this.configManager.get("web_id"),r=this.configManager.get("user_unique_id");r&&r!==t||(this.configManager.set({user_unique_id:e}),this.collect.emit(C.TokenChange,"uuid")),t!==e&&(this.configManager.set({web_id:e}),this.collect.emit(C.TokenChange,"webid")),this.setStorage(this.cacheToken)}},i.prototype.setStorage=function(e){e._type_=this.enableCustomWebid?"custom":"default",delete e["diss".split("").reverse().join("")],this.enableCookie||this.enable_ttwebid?(this.storage.setCookie(this.tokenKey,e,this.expiresTime,this.cookieDomain),this.enable_ttwebid&&(delete e.web_id,this.storage.setItem(this.tokenKey,e))):this.storage.setItem(this.tokenKey,e),this.cacheToken=e},i.prototype.getReady=function(){return this.tokenReady},i.prototype.getTobId=function(){var e=this;return new Promise(function(t){e.collect.requestManager.useRequest({url:e.configManager.getUrl("tobid"),data:{app_id:e.config.app_id,user_unique_id:e.configManager.get("user_unique_id"),web_id:e.configManager.get("web_id"),user_unique_id_type:e.configManager.get("user_unique_id_type")},success:function(r){r&&r.e===0?t(r.tobid):t("")},fail:function(){t("")},time:3e4,withCredentials:e.enable_ttwebid})})},i}(),Xg=function(){return!(!window.navigator||!window.navigator.sendBeacon)},Zg=function(){function i(e,t){this.collector=e,this.config=t,this.requestType=t.request_type||"xhr",this.supportBeacon=Xg(),this.errorCode={NO_URL:4001,IMG_ON:4e3,IMG_CATCH:4002,BEACON_FALSE:4003,XHR_ON:500,RESPONSE:5001,TIMEOUT:5005},this.customHeader=t.custom_request_header||{}}return i.prototype.useFetch=function(e){var t=e.url,r=e.data,n=e.method,s=e.success,a=e.fail,o={"Content-Type":"application/json; charset=utf-8"};if(Object.keys(this.customHeader).length)for(var d in this.customHeader)o[d]=this.customHeader[d];window.fetch?fetch(t,{method:n||"POST",headers:o,body:JSON.stringify(r)}).then(function(c){return c.json()}).then(function(c){s&&s(c)}).catch(function(c){a&&a(r,c)}):(this.requestType="xhr",console.log("your brwoser not support fetch, use xhr"),this.useRequest({url:t,data:r,method:n,success:s,fail:a}))},i.prototype.useBeacon=function(e){var t=e.url,r=e.data,n=e.success,s=e.fail;window.navigator.sendBeacon(t,JSON.stringify(r))?n&&n():s&&s(r,this.errorCode.BEACON_FALSE)},i.prototype.useRequest=function(e){var t=this,r=e.url,n=e.data,s=e.method,a=e.success,o=e.fail,d=e.timeout,c=e.useBeacon,u=e.withCredentials,l=e.app_key,h=e.forceXhr;if(c&&this.supportBeacon)this.useBeacon({url:r,data:n,method:s,success:a,fail:o});else if(this.requestType!=="fetch"||h)try{var p=new XMLHttpRequest,f=s||"POST";if(p.open(f,""+r,!0),p.setRequestHeader("Content-Type","application/json; charset=utf-8"),l&&p.setRequestHeader("X-MCS-AppKey",""+l),Object.keys(this.customHeader).length)for(var v in this.customHeader)p.setRequestHeader(v,this.customHeader[v]);u&&(p.withCredentials=!0),d&&(p.timeout=d,p.ontimeout=function(){o&&o(n,t.errorCode.TIMEOUT)}),p.onload=function(){if(a){var m=null;if(p.responseText){try{m=JSON.parse(p.responseText)}catch{m={}}a(m,n)}}},p.onerror=function(){p.abort(),o&&o(n,t.errorCode.XHR_ON)},p.send(JSON.stringify(n))}catch{}else this.useFetch({url:r,data:n,method:s,success:a,fail:o})},i}(),Qg=function(){function i(e,t){if(this.devToolReady=!1,this.devToolOrigin="*",this.sendAlready=!1,this.eventVerifyReady=!1,t.enable_debug){var r=e.adapters.storage;this.collect=e,this.config=t,this.app_id=t.app_id,this.cacheStorgae=new r(!1,"session"),this.eventVerifyInfo=[],this.sdk_type=Ti.includes("tob")?"tob":"inner",this.filterEvent=["__bav_page","__bav_beat","__bav_page_statistics","__bav_click","__bav_page_exposure","bav2b_page","bav2b_beat","bav2b_page_statistics","bav2b_click","bav2b_page_exposure","_be_active","predefine_pageview","__profile_set","__profile_set_once","__profile_increment","__profile_unset","__profile_append","predefine_page_alive","predefine_page_close","abtest_exposure"],this.load()}}return i.prototype.loadScript=function(e){try{var t=document.createElement("script");t.src=e,t.onerror=function(){console.log("load DevTool render fail")},t.onload=function(){console.log("load DevTool render success")},document.getElementsByTagName("body")[0].appendChild(t)}catch(r){console.log("devTool load fail, "+r.message)}},i.prototype.parseUrl=function(){var e={};try{var t=window.location.href.split("?")[1].split("&");t.length&&t.forEach(function(r){var n=r.split("=");e[decodeURIComponent(n[0])]=decodeURIComponent(n[1])})}catch{}return e},i.prototype.load=function(){return e=this,t=void 0,n=function(){var s,a,o;return Dg(this,function(d){switch(d.label){case 0:if(d.trys.push([0,2,,3]),(s=this.parseUrl()).open_devtool_web&&s.app_id){if(parseInt(s.app_id)!==this.app_id)return[2]}else if(!this.getStorage())return[2];return this.loadBaseInfo(),this.loadHook(),this.setStorage(),this.addLintener(),this.loadDebuggerModule(),this.loadDevTool(),[4,this.fetchEventInfo()];case 1:return a=d.sent(),this.sendData("devtool:web:verify",a.verifyStatus),this.eventVerifyInfo=a.data,[3,3];case 2:return o=d.sent(),console.log("debug fail, "+o.message),[3,3];case 3:return[2]}})},new((r=void 0)||(r=Promise))(function(s,a){function o(u){try{c(n.next(u))}catch(l){a(l)}}function d(u){try{c(n.throw(u))}catch(l){a(l)}}function c(u){u.done?s(u.value):new r(function(l){l(u.value)}).then(o,d)}c((n=n.apply(e,t||[])).next())});var e,t,r,n},i.prototype.getStorage=function(){var e=this.cacheStorgae.getItem("__applog_devtool_web");return e&&parseInt(e)===this.app_id},i.prototype.setStorage=function(){this.cacheStorgae.setItem("__applog_devtool_web",this.app_id)},i.prototype.loadDevTool=function(){this.loadScript("https://lf3-cdn-tos.bytescm.com/obj/static/log-sdk/collect/devtool/debug-web.0.0.2.js")},i.prototype.loadBaseInfo=function(){var e=this;this.info=[{title:"基本信息",type:1,infoName:{app_id:this.config.app_id,channel:this.config.channel,上报域名:this.collect.configManager.getDomain(),SDK版本:Ti,SDK引入方式:"npm"}},{title:"用户信息",type:2,infoName:{uuid:this.collect.configManager.get("user").user_unique_id||"",web_id:this.collect.configManager.get("user").web_id||"",ssid:"点击获取SSID"}},{title:"公共参数信息",type:2,infoName:{浏览器:this.collect.configManager.get("browser"),浏览器版本:this.collect.configManager.get("browser_version"),平台:this.collect.configManager.get("platform"),设备型号:this.collect.configManager.get("device_model"),操作系统:this.collect.configManager.get("os_name"),操作系统版本:this.collect.configManager.get("os_version"),屏幕分辨率:this.collect.configManager.get("resolution"),来源:this.collect.configManager.get("referrer"),自定义信息:""}},{title:"配置信息",type:3,infoName:{全埋点:!!this.config.autotrack,停留时长:!!this.config.enable_stay_duration}},{title:"A/B配置信息",type:4,infoName:{"A/B实验":!!this.config.enable_ab_test}},{title:"客户端信息",type:3,infoName:{打通开关:!!this.config.Native}}],this.log=[],this.event=[],this.collect.on(C.Ready,function(){e.info[1].infoName.uuid=e.collect.configManager.get("user").user_unique_id,e.info[1].infoName.web_id=e.collect.configManager.get("user").web_id,e.info[2].infoName.自定义信息=JSON.stringify(e.collect.configManager.get("custom")),e.config.enable_ab_test&&(e.info[4].infoName.已曝光VID=e.collect.configManager.getAbVersion(),e.info[4].infoName["A/B域名"]=e.config.ab_channel_domain||Un(Gg[e.config.channel]),e.info[4].infoName.全部配置=e.collect.configManager.getAbData()),e.config.Native&&(e.info[5].infoName.是否打通=!!e.collect.bridgeReport)})},i.prototype.loadHook=function(){var e=this;this.collect.stop(),this.collect.on(k.DEBUGGER_MESSAGE,function(t){switch(t.type){case k.DEBUGGER_MESSAGE_SDK:var r={time:t.time,type:t.logType||"sdk",level:t.level,name:t.info,show:!0,levelShow:!0,needDesc:!!t.data};return t.data&&(r.desc={content:JSON.stringify(t.data)}),e.updateLog(r),t.secType&&t.secType==="AB"?(e.info[4].infoName.已曝光VID=e.collect.configManager.getAbVersion(),e.info[4].infoName.全部配置=e.collect.configManager.getAbData()):t.secType==="USER"&&(e.info[1].infoName.uuid=e.collect.configManager.get("user").user_unique_id,e.info[1].infoName.web_id=e.collect.configManager.get("user").web_id),void e.updateInfo();case k.DEBUGGER_MESSAGE_EVENT:if(t.data&&t.data.length){var n=t.data[0],s=n.events,a=n.header;if(a.custom=JSON.parse(a.custom),!s.length)return;s.forEach(function(o){o.checkShow=!0,o.searchShow=!0,o.type=e.filterEvent.indexOf(o.event)!==-1?"sdk":"cus",o.type=e.collect.bridgeReport?"bridge":o.type,o.params=JSON.parse(o.params),t.status==="fail"&&(o.info={message:"code: "+t.code+", msg: "+t.failType},o.failType=t.failType);var d=!1,c=!1,u=[];e.eventVerifyInfo&&e.eventVerifyInfo.length&&(e.eventVerifyInfo.forEach(function(l){l.eventStatus=!1}),e.eventVerifyInfo.forEach(function(l){o.event===l.name&&(c=!0,d=!0,o.verifyStatus=l.status,Object.keys(o.params).forEach(function(h){if(h!=="event_index"){var p={};p.paramsKey=h,p.paramsKeyValue=o.params[""+h],p.paramsStatus=!1,p.paramsStatusInfo="属性未录入",l.params.forEach(function(f){h===f.name&&(f.checked=!0,typeof o.params[""+h]!==e.formatParamsType(f.value_type)?p.paramsStatusInfo="属性类型错误,应为"+e.formatParamsType(f.value_type):(p.paramsStatus=!0,p.paramsStatusInfo=""))}),u.push(p),p.paramsStatusInfo&&(c=!1)}}),l.params.forEach(function(h){h.checked||(c=!1,u.push({paramsKey:h.name,paramsStatus:!1,paramsStatusInfo:"缺少属性"+h.name}))}))})),o.reportStatus=t.status==="success",o.paramsInfo=u,o.eventStatus=c&&t.status==="success",o.eventRecord=d}),e.updateEvent(n)}return}})},i.prototype.formatParamsType=function(e){switch(e){case 0:return"string";case 1:case 2:return"number";case 3:return"boolean"}},i.prototype.fetchEventInfo=function(){var e=this;try{return new Promise(function(t){var r=Un("1fz22z22z1nz21z4mz4bz4bz18z1nz1nz1jz1mz1ez1fz1mz1kz1cz4az19z27z22z1cz1bz18z1lz1az1cz4az1lz1cz22z4bz18z1nz1nz1jz1mz1ez1bz1cz24z22z1mz1mz1jz21z4bz1mz1nz1cz1lz18z1nz1gz4bz24z4dz4bz18z1nz1nz16z1jz1mz1ez16z1kz1cz22z18")+"?app_id="+e.app_id+"&t="+e.sdk_type+"&nc=false";e.collect.requestManager.useRequest({url:r,method:"GET",success:function(n){e.eventVerifyReady=!0,e.collect.reStart(),t({data:n.data,verifyStatus:!0})},fail:function(){e.eventVerifyReady=!0,e.collect.reStart(),t({data:[],verifyStatus:!1})},timeout:3e3})})}catch{return{data:[],verifyStatus:!1}}},i.prototype.addLintener=function(){var e=this;window.addEventListener("message",function(t){if(t.origin===location.origin){if(t&&t.data&&t.data.type==="devtool:web:ready"){if(e.devToolOrigin=t.origin,e.devToolReady=!0,e.sendAlready)return;e.sendData("devtool:web:init",{info:e.info,log:e.log,event:e.event,appid:e.app_id}),e.sendAlready=!0}t&&t.data&&t.data.type==="devtool:web:ssid"&&e.collect.getToken(function(r){e.info[1].infoName.ssid=r.tobid,e.updateInfo()}),t&&t.data&&t.data.type}})},i.prototype.sendData=function(e,t){try{var r={type:e,payload:t};(window.opener||window.parent).postMessage(r,this.devToolOrigin)}catch{}},i.prototype.updateInfo=function(){this.devToolReady&&this.sendData("devtool:web:info",this.info)},i.prototype.updateLog=function(e){this.devToolReady?this.sendData("devtool:web:log",e):this.log.push(e)},i.prototype.updateEvent=function(e){this.devToolReady||this.eventVerifyReady?this.sendData("devtool:web:event",e):this.event.push(e)},i.prototype.loadDebuggerModule=function(){var e=document.head||document.getElementsByTagName("head")[0],t=document.createElement("style");t.appendChild(document.createTextNode(`#debugger-applog-web {
70
+ position: fixed;
71
+ width: 50px;
72
+ height: 50px;
73
+ background-image: url('https://lf-cdn-tos.bytescm.com/obj/static/log-sdk/collect/devtool/applog.png');;
74
+ bottom: 5%;
75
+ right: 10%;
76
+ cursor: pointer;
77
+ z-index:100;
78
+ background-size: 50px;
79
+ }`)),e.appendChild(t);var r=document.createElement("div");r.innerHTML='<div id="debugger-applog-web" class="debugger-applog-web"></div>';var n=document.createElement("div");n.innerHTML='<div id="debugger-container" class="debugger-container"></div>',document.getElementsByTagName("body")[0].appendChild(r),document.getElementsByTagName("body")[0].appendChild(n),document.getElementById("debugger-applog-web").addEventListener("click",function(){(window.opener||window.parent).postMessage({type:"devtool:web:open-draw"},location.origin)})},i}(),$n={autotrack:{src:{cn:"https://lf3-cdn-tos.bytescm.com/obj/static/log-sdk/collect/5.0/plugin/autotrack.js",sg:"https://sf16-scmcdn-sg.ibytedtos.com/obj/static-sg/log-sdk/collect/5.0/plugin/autotrack.js",va:"https://sf16-scmcdn-va.ibytedtos.com/obj/static-us/log-sdk/collect/5.0/plugin/autotrack.js"},object:"LogAutoTrack"},ab:{src:{cn:"https://lf3-cdn-tos.bytescm.com/obj/static/log-sdk/collect/5.0/plugin/ab.js",sg:"https://sf16-scmcdn-sg.ibytedtos.com/obj/static-sg/log-sdk/collect/5.0/plugin/ab.js",va:"https://sf16-scmcdn-va.ibytedtos.com/obj/static-us/log-sdk/collect/5.0/plugin/ab.js"},object:"LogAb"},stay:{src:{cn:"https://lf3-cdn-tos.bytescm.com/obj/static/log-sdk/collect/5.0/plugin/stay.js",sg:"https://sf16-scmcdn-sg.ibytedtos.com/obj/static-sg/log-sdk/collect/5.0/plugin/stay.js",va:"https://sf16-scmcdn-va.ibytedtos.com/obj/static-us/log-sdk/collect/5.0/plugin/stay.js"},object:"LogStay"},route:{src:{cn:"https://lf3-cdn-tos.bytescm.com/obj/static/log-sdk/collect/5.0/plugin/route.js",sg:"https://sf16-scmcdn-sg.ibytedtos.com/obj/static-sg/log-sdk/collect/5.0/plugin/route.js",va:"https://sf16-scmcdn-va.ibytedtos.com/obj/static-us/log-sdk/collect/5.0/plugin/route.js"},object:"LogRoute"},cep:{src:{cn:"https://lf3-cdn-tos.bytescm.com/obj/static/log-sdk/collect/5.0/plugin/cep.js",sg:"https://sf16-scmcdn-sg.ibytedtos.com/obj/static-sg/log-sdk/collect/5.0/plugin/cep.js",va:"https://sf16-scmcdn-va.ibytedtos.com/obj/static-us/log-sdk/collect/5.0/plugin/cep.js"},object:"LogCep"},tracer:{src:{cn:"https://lf3-cdn-tos.bytescm.com/obj/static/log-sdk/collect/5.0/plugin/tracer.js",sg:"https://sf16-scmcdn-sg.ibytedtos.com/obj/static-sg/log-sdk/collect/5.0/plugin/tracer.js",va:"https://sf16-scmcdn-va.ibytedtos.com/obj/static-us/log-sdk/collect/5.0/plugin/tracer.js"},object:"LogTracer"},retry:{src:{cn:"https://lf3-cdn-tos.bytescm.com/obj/static/log-sdk/collect/5.0/plugin/retry.js",sg:"https://sf16-scmcdn-sg.ibytedtos.com/obj/static-sg/log-sdk/collect/5.0/plugin/retry.js",va:"https://sf16-scmcdn-va.ibytedtos.com/obj/static-us/log-sdk/collect/5.0/plugin/retry.js"},object:"LogRetry"},visual:{src:{cn:"https://lf3-cdn-tos.bytescm.com/obj/static/log-sdk/collect/5.0/plugin/visual.js",sg:"https://sf16-scmcdn-sg.ibytedtos.com/obj/static-sg/log-sdk/collect/5.0/plugin/visual.js",va:"https://sf16-scmcdn-va.ibytedtos.com/obj/static-us/log-sdk/collect/5.0/plugin/visual.js"},object:"LogVisual"}},Yg=["et","profile","heartbeat","monitor"],St=function(){function i(e){this.disableAutoPageView=!1,this.bridgeReport=!1,this.staging=!1,this.pluginInstances=[],this.sended=!1,this.started=!1,this.destroy=!1,this.sdkReady=!1,this.adapters={},this.loadType="base",this.sdkStop=!1,this.name=e,this.hook=new Ig,this.remotePlugin=new Map,this.Types=C,this.adapters.storage=qe}return i.usePlugin=function(e,t,r){if(t){for(var n=!1,s=0,a=i.plugins.length;s<a;s++)if(i.plugins[s].name===t){i.plugins[s].plugin=e,i.plugins[s].options=r||{},n=!0;break}n||i.plugins.push({name:t,plugin:e,options:r})}else i.plugins.push({plugin:e})},i.prototype.usePlugin=function(e,t,r){e&&(this.loadType==="full"&&Yg.includes(e)?console.info("your sdk version has "+e+" plugin already ~"):t?typeof t=="string"?this.remotePlugin.get(e)||this.remotePlugin.set(e,{src:t,call:r}):this.remotePlugin.get(e)||this.remotePlugin.set(e,{instance:t}):this.remotePlugin.get(e)||this.remotePlugin.set(e,"sdk"))},i.prototype.init=function(e){var t,r=this;this.logger=new Hg(this.name,e.log),this.inited?this.logger.warn("[instance: "+this.name+"], every instance's api: init, can be call only one time!"):e&&rc(e)?e.app_id&&typeof(t=e.app_id)=="number"&&!isNaN(t)?!e.app_key||function(n){return typeof n=="string"}(e.app_key)?(e.channel_domain||["cn","sg","va"].indexOf(e.channel)!==-1||(this.logger.warn("channel must be `cn`, `sg`,`va` !"),e.channel="cn"),this.spider=new $g,this.spider.checkSpider(e)?this.logger.warn("your env may be a spider, can not report!"):(this.appBridge=new qg(this,e.enable_native),this.requestManager=new Zg(this,e),this.bridgeReport=this.appBridge.bridgeInject(),this.configManager=new jg(this,e),this.debugger=new Qg(this,e),this.initConfig=e,this.emit(C.Init),this.emit(k.DEBUGGER_MESSAGE,{type:k.DEBUGGER_MESSAGE_SDK,info:"SDK 执行INIT",data:e,level:"info",time:Date.now()}),this.destroy=!1,e.disable_auto_pv&&(this.disableAutoPageView=!0),this.bridgeReport||(this.configManager.set({app_id:e.app_id}),this.eventManager=new Wg,this.tokenManager=new Jg,this.sessionManager=new Kg,Promise.all([new Promise(function(n){r.once(C.TokenComplete,function(){n(!0)})}),new Promise(function(n){r.once(C.Start,function(){n(!0)})})]).then(function(){try{i.plugins.reduce(function(n,s){var a=s.plugin,o=s.options,d=Object.assign(r.initConfig,o),c=new a;return c.apply(r,d),n.push(c),n},r.pluginInstances)}catch(n){console.warn("load plugin error, "+n.message),r.emit(k.DEBUGGER_MESSAGE,{type:k.DEBUGGER_MESSAGE_SDK,info:"发生了异常",level:"error",time:Date.now(),data:n.message})}r.sdkReady=!0,r.emit(C.Ready),r.emit(k.DEBUGGER_MESSAGE,{type:k.DEBUGGER_MESSAGE_SDK,info:"SDK 初始化完成",time:Date.now(),level:"info",data:r.configManager.get("user")}),r.logger.info("appid: "+e.app_id+", userInfo:"+JSON.stringify(r.configManager.get("user"))),r.logger.info("appid: "+e.app_id+", sdk is ready, version type is "+r.loadType+", version is "+Ti+", you can report now !!!"),e.disable_auto_pv&&(r.disableAutoPageView=!0);try{r.loadType==="full"&&(e.enable_ab_test||e.autotrack)&&(window.opener||window.parent).postMessage("[tea-sdk]ready","*")}catch(n){r.emit(k.DEBUGGER_MESSAGE,{type:k.DEBUGGER_MESSAGE_SDK,info:"发生了异常",level:"error",time:Date.now(),data:n.message})}r.pageView(),r.on(C.TokenChange,function(n){n==="webid"&&r.pageView(),r.logger.info("appid: "+e.app_id+" token change, new userInfo:"+JSON.stringify(r.configManager.get("user"))),r.emit(k.DEBUGGER_MESSAGE,{type:k.DEBUGGER_MESSAGE_SDK,info:"SDK 设置了用户信息",time:Date.now(),secType:"USER",level:"info",data:r.configManager.get("user")})}),r.on(C.TokenReset,function(){r.logger.info("appid: "+e.app_id+" token reset, new userInfo:"+JSON.stringify(r.configManager.get("user"))),r.emit(k.DEBUGGER_MESSAGE,{type:k.DEBUGGER_MESSAGE_SDK,info:"SDK 重置了用户信息",time:Date.now(),secType:"USER",level:"info",data:r.configManager.get("user")})}),r.on(C.RouteChange,function(n){n.init||e.disable_route_report||r.pageView()})}),this.tokenManager.apply(this,e),this.eventManager.apply(this,e),this.sessionManager.apply(this,e)),this.inited=!0)):this.logger.warn("app_key param is error, must be string, please check!"):this.logger.warn("app_id param is error, must be number, please check!"):this.logger.warn("init params error,please check!")},i.prototype.config=function(e){if(this.inited)if(e&&rc(e))if(this.bridgeReport)this.appBridge.setConfig(e);else{e._staging_flag&&e._staging_flag===1&&(this.staging=!0),e.disable_auto_pv&&(this.disableAutoPageView=!0,delete e.disable_auto_pv);var t=we({},e),r=this.initConfig.configPersist||this.initConfig.config_persist||!1;if(this.initConfig&&r){var n=this.configManager.getStore();n&&(t=Object.assign(n,e)),this.configManager.setStore(e)}t.web_id,t.user_unique_id;var s=function(a,o){var d={};for(var c in a)Object.prototype.hasOwnProperty.call(a,c)&&o.indexOf(c)<0&&(d[c]=a[c]);if(a!=null&&typeof Object.getOwnPropertySymbols=="function"){var u=0;for(c=Object.getOwnPropertySymbols(a);u<c.length;u++)o.indexOf(c[u])<0&&(d[c[u]]=a[c[u]])}return d}(t,["web_id","user_unique_id"]);this.configManager.set(s),t.hasOwnProperty("web_id")&&this.emit(C.ConfigWebId,t.web_id),t.hasOwnProperty("user_unique_id")&&this.emit(C.ConfigUuid,t.user_unique_id),this.emit(k.DEBUGGER_MESSAGE,{type:k.DEBUGGER_MESSAGE_SDK,info:"SDK 执行CONFIG",level:"info",time:Date.now(),data:t})}else console.warn("config params is error, please check");else console.warn("config must be use after function init")},i.prototype.setUserUniqueID=function(e){this.config({user_unique_id:e})},i.prototype.setHeaderInfo=function(e,t){var r={};r[e]=t,this.config(r)},i.prototype.removeHeaderInfo=function(e){var t={};t[e]=void 0,this.config(t)},i.prototype.setDomain=function(e){this.configManager&&this.configManager.setDomain(e),this.emit(C.ConfigDomain)},i.prototype.getConfig=function(e){return this.configManager.get(e)},i.prototype.send=function(){this.start()},i.prototype.start=function(){this.inited&&!this.sended&&(this.sended=!0,this.started=!0,this.emit(C.Start),this.emit(k.DEBUGGER_MESSAGE,{type:k.DEBUGGER_MESSAGE_SDK,info:"SDK 执行START",level:"info",time:Date.now()}),this.bridgeReport&&(this.pageView(),this.emit(C.Ready)))},i.prototype.event=function(e,t){var r=this;try{var n=[];if(Array.isArray(e))e.forEach(function(a){var o=r.processEvent(a[0],a[1]||{});o&&n.push(o)});else{var s=this.processEvent(e,t);if(!s)return;n.push(s)}this.bridgeReport?n.forEach(function(a){var o=a.event,d=a.params;r.appBridge.onEventV3(o,JSON.stringify(d))}):n.length&&(this.emit(C.Event,n),this.emit(C.SessionResetTime))}catch(a){this.logger.warn("something error, please check"),this.emit(k.DEBUGGER_MESSAGE,{type:k.DEBUGGER_MESSAGE_SDK,info:"发生了异常",level:"error",time:Date.now(),data:a.message})}},i.prototype.beconEvent=function(e,t){if(Array.isArray(e))console.warn("beconEvent not support batch report, please check");else{var r=[],n=this.processEvent(e,t||{});n&&(r.push(n),r.length&&(this.emit(C.BeconEvent,r),this.emit(C.SessionResetTime)))}},i.prototype.beaconEvent=function(e,t){this.beconEvent(e,t)},i.prototype.processEvent=function(e,t){t===void 0&&(t={});try{if(!e)return console.warn("eventName is null, please check"),null;var r=e;/^event\./.test(e)&&(r=e.slice(6));var n=t;typeof n!="object"&&(n={}),n.profile?delete n.profile:n.event_index=Og();var s=void 0;return n.local_ms?(s=n.local_ms,delete n.local_ms):s=+new Date,{event:r,params:n,local_time_ms:s,is_bav:this.initConfig&&this.initConfig.autotrack?1:0}}catch(a){return this.emit(k.DEBUGGER_MESSAGE,{type:k.DEBUGGER_MESSAGE_SDK,info:"发生了异常",level:"error",time:Date.now(),data:a.message}),{event:e,params:t}}},i.prototype.filterEvent=function(e){this.eventFilter=e},i.prototype.on=function(e,t){this.hook.on(e,t)},i.prototype.once=function(e,t){this.hook.once(e,t)},i.prototype.off=function(e,t){this.hook.off(e,t)},i.prototype.emit=function(e,t,r){this.hook.emit(e,t,r)},i.prototype.set=function(e){this.hook.set(e)},i.prototype.stop=function(){this.sdkStop=!0},i.prototype.reStart=function(){this.sdkStop=!1},i.prototype.pageView=function(){this.disableAutoPageView||this.predefinePageView()},i.prototype.predefinePageView=function(e){if(e===void 0&&(e={}),this.inited){var t={title:document.title||location.pathname,url:location.href,url_path:location.pathname,time:Date.now(),referrer:window.document.referrer,$is_first_time:""+(this.configManager&&this.configManager.is_first_time||!1)},r=we({},t,e);this.event("predefine_pageview",r)}else console.warn("predefinePageView must be use after function init")},i.prototype.clearEventCache=function(){this.emit(C.CleanEvents)},i.prototype.setWebIDviaUnionID=function(e){if(e){var t=sc(e);this.config({web_id:""+t,wechat_unionid:e}),this.emit(C.CustomWebId)}},i.prototype.setWebId=function(e){this.config({web_id:""+e})},i.prototype.setWebIDviaOpenID=function(e){if(e){var t=sc(e);this.config({web_id:""+t,wechat_openid:e}),this.emit(C.CustomWebId)}},i.prototype.setNativeAppId=function(e){this.bridgeReport&&this.appBridge.setNativeAppId(e)},i.prototype.getSessionId=function(){return Bt()},i.prototype.setSessionId=function(e){this.emit(C.SessionReset,e)},i.prototype.resetStayDuration=function(e,t,r){this.emit(C.ResetStay,{url_path:e,title:t,url:r},C.Stay)},i.prototype.resetStayParams=function(e,t,r){e===void 0&&(e=""),t===void 0&&(t=""),r===void 0&&(r=""),this.emit(C.SetStay,{url_path:e,title:t,url:r},C.Stay)},i.prototype.getToken=function(e,t){var r=this;if(this.inited){var n=!1,s=function(o){if(!n){n=!0;var d=r.configManager.get().user;return o&&(d.tobid=o,d["diss".split("").reverse().join("")]=o),e(we({},d))}},a=function(){r.tokenManager.getTobId().then(function(o){s(o)})};this.sdkReady?a():(t&&setTimeout(function(){s()},t),this.on(C.Ready,function(){a()}))}else console.warn("getToken must be use after function init")},i.prototype.profileSet=function(e){this.bridgeReport?this.appBridge.profileSet(JSON.stringify(e)):this.emit(C.ProfileSet,e,C.Profile),this.emit(k.DEBUGGER_MESSAGE,{type:k.DEBUGGER_MESSAGE_SDK,info:"SDK 执行profileSet",level:"info",time:Date.now(),data:e})},i.prototype.profileSetOnce=function(e){this.bridgeReport?this.appBridge.profileSetOnce(JSON.stringify(e)):this.emit(C.ProfileSetOnce,e,C.Profile),this.emit(k.DEBUGGER_MESSAGE,{type:k.DEBUGGER_MESSAGE_SDK,info:"SDK 执行profileSetOnce",level:"info",time:Date.now(),data:e})},i.prototype.profileIncrement=function(e){this.bridgeReport?this.appBridge.profileIncrement(JSON.stringify(e)):this.emit(C.ProfileIncrement,e,C.Profile),this.emit(k.DEBUGGER_MESSAGE,{type:k.DEBUGGER_MESSAGE_SDK,info:"SDK 执行profileIncrement",level:"info",time:Date.now(),data:e})},i.prototype.profileUnset=function(e){this.bridgeReport?this.appBridge.profileUnset(e):this.emit(C.ProfileUnset,e,C.Profile),this.emit(k.DEBUGGER_MESSAGE,{type:k.DEBUGGER_MESSAGE_SDK,info:"SDK 执行profileUnset",level:"info",time:Date.now(),data:e})},i.prototype.profileAppend=function(e){this.bridgeReport?this.appBridge.profileAppend(JSON.stringify(e)):this.emit(C.ProfileAppend,e,C.Profile),this.emit(k.DEBUGGER_MESSAGE,{type:k.DEBUGGER_MESSAGE_SDK,info:"SDK 执行profileAppend",level:"info",time:Date.now(),data:e})},i.prototype.setExternalAbVersion=function(e){this.emit(C.AbExternalVersion,typeof e=="string"&&e?(""+e).trim():null,C.Ab)},i.prototype.getVar=function(e,t,r){this.emit(C.AbVar,{name:e,defaultValue:t,callback:r},C.Ab)},i.prototype.getABconfig=function(e,t){this.emit(C.AbConfig,{params:e,callback:t},C.Ab)},i.prototype.getAbSdkVersion=function(){return this.configManager.getAbVersion()},i.prototype.onAbSdkVersionChange=function(e){var t=this;return this.emit(C.AbVersionChangeOn,e,C.Ab),function(){t.emit(C.AbVersionChangeOff,e,C.Ab)}},i.prototype.offAbSdkVersionChange=function(e){this.emit(C.AbVersionChangeOff,e,C.Ab)},i.prototype.openOverlayer=function(){this.emit(C.AbOpenLayer,"",C.Ab)},i.prototype.closeOverlayer=function(){this.emit(C.AbCloseLayer,"",C.Ab)},i.prototype.getAllVars=function(e){this.emit(C.AbAllVars,e,C.Ab)},i.prototype.destoryInstace=function(){this.destroy||(this.destroy=!0,this.off(C.TokenComplete),this.emit(C.DestoryInstance))},i.prototype.destroyInstance=function(){this.destroy||(this.destroy=!0,this.off(C.TokenComplete),this.emit(C.DestoryInstance))},i.plugins=[],i}(),ev=function(){function i(){}return i.prototype.apply=function(e,t){var r=this;t.event_verify_url&&(typeof t.event_verify_url=="string"?(this.url=t.event_verify_url+"/v1/list_test",e.on(e.Types.SubmitBefore,function(n){e.requestManager.useBeacon({url:r.url,data:n})})):console.log("please use correct et_test url"))},i}(),tv=function(){function i(){}return i.prototype.apply=function(e,t){var r=this;this.collect=e,this.config=t,this.duration=6e4,this.reportUrl=e.configManager.getDomain()+"/profile/list";var n=e.Types;this.eventCheck=new Hn(e,t),this.cache={},this.collect.on(n.ProfileSet,function(s){r.setProfile(s)}),this.collect.on(n.ProfileSetOnce,function(s){r.setOnceProfile(s)}),this.collect.on(n.ProfileUnset,function(s){r.unsetProfile(s)}),this.collect.on(n.ProfileIncrement,function(s){r.incrementProfile(s)}),this.collect.on(n.ProfileAppend,function(s){r.appendProfile(s)}),this.collect.on(n.ProfileClear,function(){r.cache={}}),this.ready(n.Profile)},i.prototype.ready=function(e){var t=this;if(this.collect.set(e),this.collect.hook._hooksCache.hasOwnProperty(e)){var r=this.collect.hook._hooksCache[e];if(!Object.keys(r).length)return;var n=function(a){r[a].length&&r[a].forEach(function(o){t.collect.hook.emit(a,o)})};for(var s in r)n(s)}},i.prototype.report=function(e,t){t===void 0&&(t={});try{if(this.config.disable_track_event)return;var r=[];r.push(this.collect.processEvent(e,t));var n=this.collect.eventManager.merge(r);this.collect.requestManager.useRequest({url:this.reportUrl,data:n}),this.collect.emit(k.DEBUGGER_MESSAGE,{type:k.DEBUGGER_MESSAGE_EVENT,info:"埋点上报成功",time:Date.now(),data:n,code:200,status:"success"})}catch(s){this.collect.emit(k.DEBUGGER_MESSAGE,{type:k.DEBUGGER_MESSAGE_SDK,info:"发生了异常",level:"error",time:Date.now(),data:s.message})}},i.prototype.setProfile=function(e){var t=this.formatParams(e);t&&Object.keys(t).length&&(this.pushCache(t),this.report("__profile_set",we({},t,{profile:!0})))},i.prototype.setOnceProfile=function(e){var t=this.formatParams(e,!0);t&&Object.keys(t).length&&(this.pushCache(t),this.report("__profile_set_once",we({},t,{profile:!0})))},i.prototype.incrementProfile=function(e){e?this.report("__profile_increment",we({},e,{profile:!0})):console.warn("please check the params, must be object!!!")},i.prototype.unsetProfile=function(e){if(e){var t={};t[e]="1",this.report("__profile_unset",we({},t,{profile:!0}))}else console.warn("please check the key, must be string!!!")},i.prototype.appendProfile=function(e){if(e){var t={};for(var r in e)typeof e[r]=="string"||Object.prototype.toString.call(e[r]).slice(8,-1)==="Array"?t[r]=e[r]:console.warn("please check the value of param: "+r+", must be string or array !!!");Object.keys(t).length&&this.report("__profile_append",we({},t,{profile:!0}))}else console.warn("please check the params, must be object!!!")},i.prototype.pushCache=function(e){var t=this;Object.keys(e).forEach(function(r){t.cache[r]={val:t.clone(e[r]),timestamp:Date.now()}})},i.prototype.formatParams=function(e,t){var r=this;t===void 0&&(t=!1);try{if(!e||Object.prototype.toString.call(e)!=="[object Object]")return void console.warn("please check the params type, must be object !!!");var n={};for(var s in e)typeof e[s]=="string"||typeof e[s]=="number"||Object.prototype.toString.call(e[s]).slice(8,-1)==="Array"?n[s]=e[s]:console.warn("please check the value of params:"+s+", must be string,number,Array !!!");var a=Object.keys(n);if(!a.length||!this.eventCheck.checkEventParams(n))return;var o=Date.now();return a.filter(function(d){var c=r.cache[d];return t?!c:!(c&&r.compare(c.val,e[d])&&o-c.timestamp<r.duration)}).reduce(function(d,c){return d[c]=n[c],d},{})}catch(d){this.collect.emit(k.DEBUGGER_MESSAGE,{type:k.DEBUGGER_MESSAGE_SDK,info:"发生了异常",level:"error",time:Date.now(),data:d.message}),console.log("error")}},i.prototype.compare=function(e,t){try{return JSON.stringify(e)===JSON.stringify(t)}catch(r){return this.collect.emit(k.DEBUGGER_MESSAGE,{type:k.DEBUGGER_MESSAGE_SDK,info:"发生了异常",level:"error",time:Date.now(),data:r.message}),!1}},i.prototype.clone=function(e){try{return JSON.parse(JSON.stringify(e))}catch(t){return this.collect.emit(k.DEBUGGER_MESSAGE,{type:k.DEBUGGER_MESSAGE_SDK,info:"发生了异常",level:"error",time:Date.now(),data:t.message}),e}},i.prototype.unReady=function(){console.warn("sdk is not ready, please use this api after start")},i}(),iv=function(){function i(){var e=this;this.setInterval=function(){e.clearIntervalFunc=Mg(function(){e.isSessionhasEvent&&e.endCurrentSession()},e.sessionInterval)},this.clearInterval=function(){e.clearIntervalFunc&&e.clearIntervalFunc()}}return i.prototype.apply=function(e,t){var r=this;if(this.collect=e,!t.disable_heartbeat){this.sessionInterval=6e4,this.startTime=0,this.lastTime=0,this.setInterval();var n=this.collect.Types;this.collect.on(n.SessionResetTime,function(){r.process()})}},i.prototype.endCurrentSession=function(){this.collect.event("_be_active",{start_time:this.startTime,end_time:this.lastTime,url:window.location.href,referrer:window.document.referrer,title:document.title||location.pathname}),this.isSessionhasEvent=!1,this.startTime=0},i.prototype.process=function(){this.isSessionhasEvent||(this.isSessionhasEvent=!0,this.startTime=+new Date);var e=this.lastTime||+new Date;this.lastTime=+new Date,this.lastTime-e>this.sessionInterval&&(this.clearInterval(),this.endCurrentSession(),this.setInterval())},i}(),rv=function(){function i(){}return i.prototype.apply=function(e,t){var r=this;t.channel_domain||t.disable_track_event||t.disable_sdk_monitor||(this.collect=e,this.config=t,this.url=e.configManager.getUrl("event"),this.collect.on(e.Types.Ready,function(){r.sdkOnload()}),this.collect.on(e.Types.SubmitError,function(n){var s=n.type,a=n.eventData,o=n.errorCode;s==="f_data"&&r.sdkError(a,o)}))},i.prototype.sdkOnload=function(){var e=this;try{var t=this.collect.configManager.get(),r=t.header,n=t.user,s=r.app_id,a=r.app_name,o=r.sdk_version,d=n.web_id,c={events:[{event:"onload",params:JSON.stringify({app_id:s,app_name:a||"",sdk_version:o,sdk_type:"npm",sdk_config:this.config,sdk_desc:"TOC",url:location.href}),local_time_ms:Date.now()}],user:{user_unique_id:d},header:{}};setTimeout(function(){e.collect.requestManager.useRequest({url:e.url,data:[c],timeout:3e4,app_key:"566f58151b0ed37e",forceXhr:!0})},16)}catch{}},i.prototype.sdkError=function(e,t){var r=this;try{var n=e[0],s=n.user,a=n.header,o=[];e.forEach(function(c){c.events.forEach(function(u){o.push(u)})});var d={events:o.map(function(c){return{event:"on_error",params:JSON.stringify({error_code:t,app_id:a.app_id,app_name:a.app_name||"",error_event:c.event,sdk_version:a.sdk_version,local_time_ms:c.local_time_ms,tea_event_index:Date.now(),params:c.params,header:JSON.stringify(a),user:JSON.stringify(s)}),local_time_ms:Date.now()}}),user:{user_unique_id:s.user_unique_id},header:{}};setTimeout(function(){r.collect.requestManager.useRequest({url:r.url,data:[d],timeout:3e4,app_key:"566f58151b0ed37e",forceXhr:!0})},16)}catch{}},i}(),qn=typeof window<"u"?(window.LogPluginObject||(window.LogPluginObject={}),window.LogPluginObject):null,nv=function(){function i(){}return i.prototype.apply=function(e,t){this._plugin={},this.config=t,this.collect=e,this.channel=t.channel||"cn",this.loadExtend()},i.prototype.loadExtend=function(){var e=this;try{this.collect.remotePlugin.forEach(function(t,r){if(t==="sdk")if($n.hasOwnProperty(r)){var n=$n[r].object,s=$n[r].src[e.channel]+"?query="+Date.now();e.exist(r,n,s)}else console.warn("your "+r+" is not exist,please check plugin name");else typeof t=="object"&&(t.src?e.exist(r,t.call,t.src):e.process(r,t.instance,"INSTANCE"))})}catch(t){this.collect.emit(k.DEBUGGER_MESSAGE,{type:k.DEBUGGER_MESSAGE_SDK,info:"发生了异常",level:"error",time:Date.now(),data:t.message}),console.log("load extend error")}},i.prototype.exist=function(e,t,r){var n=this;qn[t]?(this.process(e,qn[t]),console.log("已有"+e+"插件,避免重复加载~")):this.loadPlugin(e,r,function(){n.process(e,qn[t]),console.log(" %c %s %s %s","color: yellow; background-color: black;","–","load plugin:"+e+" success","-")},function(){console.log(" %c %s %s %s","color: red; background-color: yellow;","–","load plugin:"+e+" error","-")})},i.prototype.process=function(e,t,r){try{if(r){var n=new t;n.apply&&n.apply(this.collect,this.config),console.log("excude "+e+" success")}else t&&t(this.collect,this.config)}catch(s){this.collect.emit(k.DEBUGGER_MESSAGE,{type:k.DEBUGGER_MESSAGE_SDK,info:"发生了异常",level:"error",time:Date.now(),data:s.message}),console.log("excude "+e+" error, message:"+s.message)}},i.prototype.loadPlugin=function(e,t,r,n){var s=this;try{var a=document.createElement("script");a.src=t,this._plugin[e]||(this._plugin[e]=[]),this._plugin[e].push(r),a.onerror=function(){n(t)},a.onload=function(){s._plugin[e].forEach(function(o){o()})},document.getElementsByTagName("head")[0].appendChild(a)}catch(o){this.collect.emit(k.DEBUGGER_MESSAGE,{type:k.DEBUGGER_MESSAGE_SDK,info:"发生了异常",level:"error",time:Date.now(),data:o.message})}},i}();St.usePlugin(nv,"extend"),St.usePlugin(ev,"et"),St.usePlugin(tv,"profile"),St.usePlugin(iv,"heartbeat"),St.usePlugin(rv,"monitor"),new St("default");var sv=St;class Vt{constructor({userId:e}){this.collector=new sv("media-engine-logger"),this.collector.init({app_id:834499,channel:"cn",disable_sdk_monitor:!0}),this.collector.config({user_unique_id:e||"media-engine",evtParams:{sdk_version:"1.0.0"}}),this.collector.start()}static getInstance({userId:e}){return Vt.instance||(Vt.instance=new Vt({userId:e})),Vt.instance}event(e,t){this.collector.event(e,t||{})}}class ov extends Ag{constructor({userId:e}){super(Rg),this.logger=Vt.getInstance({userId:e})}receiveWorkerMessage({type:e,data:t}){switch(e){case Te.PassEngineEvent:{const r=t.event,n=t.data;this.emit(r,n)}break;case Te.GetStats:this.emit("_receive_stats",t);break}}start(e){const{video:t}=e,{audio:r}=e;delete e.video,delete e.audio,this.sendTransportable({type:Te.Start,data:e},{video:t,audio:r}),this.logger.event("pusher_engine_start")}stop(){this.sendMessage({type:Te.Stop}),this.logger.event("pusher_engine_stop")}updateTrack(e,t,r){this.sendTransportable({type:Te.UpdateTrack,data:{isAudio:t==="audio",setting:r}},{stream:e}),this.logger.event("pusher_engine_update_track",{type:t,setting:r})}setBitrate(e,t){this.sendMessage({type:Te.SetBitrate,data:{bitrate:e,type:t}}),this.logger.event("pusher_engine_set_bitrate",{bitrate:e,type:t})}online(){this.sendMessage({type:Te.Online})}reconnect(e){this.sendMessage({type:Te.Reconnect,data:{url:e}}),this.logger.event("pusher_engine_reconnect",{url:e})}async getStats(){this.sendMessage({type:Te.GetStats});const[e]=await this.onWait("_receive_stats");return e}destroy(){super.destroy(),this.stop()}}function cc(i){let e=!0,t="";for(const r of i)if(!(r in window)){e=!1,t=`${r} not Supported`;break}return{supported:e,info:t}}const av=24*60*60*1e3;function uc(i,e="1d"){const t=`_me_expire_${i}`;let r=0;if(typeof e=="string"){if(!/^[0-9]+d$/.test(e))throw new Error("expire format error");r=av*parseInt(e)}else r=e;return{get(){const n=localStorage.getItem(t);if(!n)return null;let s=null;try{s=JSON.parse(n)}catch{return null}const{value:a,expire:o}=s;return o<Date.now()?(localStorage.removeItem(t),null):a},set(n){localStorage.setItem(t,JSON.stringify({value:n,expire:Date.now()+r}))},remove(){localStorage.removeItem(t)}}}var pe=(i=>(i[i.AAC=0]="AAC",i[i.OPUS=1]="OPUS",i[i.H264=2]="H264",i[i.H265=3]="H265",i[i.AV1=4]="AV1",i))(pe||{});pe.AAC+"",pe.OPUS+"",pe.H264+"",pe.H265+"",pe.AV1+"";const hr={[pe.AAC]:"mp4a.40.2",[pe.OPUS]:"opus",[pe.H264]:"avc1.4DE033",[pe.H265]:"hev1.1.6.L93.B0"};function dc(i){const e=new MediaStreamTrackProcessor(i),{readable:t}=e,r=i.getSettings();return{readable:t,settings:r}}const Kn=uc("audio_encoder_support","3d");function cv(){return cc(["EncodedAudioChunk","AudioEncoder","AudioData"])}function uv(i){const e=Kn.get(),t=`${i}_support`;return e&&e[t]?e[t]:null}function dv(i,e){const t=Kn.get()||{},r=`${i}_support`;t[r]=e,Kn.set(t)}async function hv(i){if(!AudioEncoder.isConfigSupported)return{supported:!1,info:"isConfigSupported method is undefined"};try{const e={codec:i,sampleRate:48e3,numberOfChannels:2,bitrate:128e3},t=await AudioEncoder.isConfigSupported(e);return t.supported!==void 0?{supported:t.supported,info:t.supported?"isConfigSupported: true":"isConfigSupported: false"}:{supported:!1,info:"isConfigSupported returned undefined"}}catch{return{supported:!1,info:"isConfigSupported method throws error"}}}async function hc(i){const e=uv(i);if(e)return console.log(`Audio encoder ${i} support result from cache:`,e),e;const t=await hv(i);return dv(i,t),t}function lv(){return hc(hr[pe.OPUS])}function pv(){return hc(hr[pe.AAC])}const Wn=uc("video_encoder_support","3d");function Jn(){return cc(["EncodedVideoChunk","VideoEncoder","VideoFrame"])}function lc(i){const e=Wn.get(),t=`${i}_support`;return e&&e[t]?e[t]:null}function Xn(i,e){const t=Wn.get()||{},r=`${i}_support`;t[r]=e,Wn.set(t)}async function pc(i){if(!VideoEncoder.isConfigSupported)return{supported:!1,info:"isConfigSupported method is undefined"};try{const e={codec:i,width:640,height:480,bitrate:1e6,framerate:30},t=await VideoEncoder.isConfigSupported(e);return{supported:t.supported??!1,info:t.supported?"isConfigSupported: true":"isConfigSupported: false"}}catch(e){return{supported:!1,info:`isConfigSupported error: ${e instanceof Error?e.message:String(e)}`}}}async function fv(i,e=3e3){return new Promise(t=>{let r=!1;const n=setTimeout(()=>{r||(r=!0,t({supported:!1,info:"encoding test timeout"}))},e);try{const s=new VideoEncoder({output:h=>{r||(r=!0,clearTimeout(n),s.state!=="closed"&&s.close(),t({supported:!0,info:"encoding test success"}))},error:h=>{r||(r=!0,clearTimeout(n),s.state!=="closed"&&s.close(),t({supported:!1,info:`encoding test error: ${h.message}`}))}}),a={codec:i,width:640,height:480,bitrate:1e6,framerate:30};s.configure(a);const o=640,d=480,c=new OffscreenCanvas(o,d),u=c.getContext("2d");u&&(u.fillStyle="#FF0000",u.fillRect(0,0,o,d));const l=new VideoFrame(c,{timestamp:0});s.encode(l)}catch(s){r||(r=!0,clearTimeout(n),t({supported:!1,info:`encoding test catch: ${s.message}`}))}})}async function mv(i){if(!Jn())return{supported:!1,info:"VideoEncoder API not supported"};const e=lc(i);if(e)return console.log(`Video encoder ${i} support result from cache:`,e),e;const t=await pc(i);return Xn(i,t),t}async function _v(i,e=3e3){if(!Jn())return{supported:!1,info:"VideoEncoder API not supported"};const t=lc(i);if(t)return console.log(`Video encoder ${i} support result from cache:`,t),t;const r=await pc(i);if(!r.supported)return Xn(i,r),r;const n=await fv(i,e);return Xn(i,n),n}function gv(){return mv(hr[pe.H264])}function vv(){return _v(hr[pe.H265])}function yv(){return cv().supported}function bv(){return Jn().supported}async function Sv(i){if(!yv())return{supported:!1,info:"AudioEncoder API not supported"};try{switch(i){case"aac":return await pv();case"opus":return await lv();default:return{supported:!1,info:`Unsupported audio codec: ${i}`}}}catch(e){return{supported:!1,info:`${i} 检测失败: ${e instanceof Error?e.message:String(e)}`}}}async function Ev(i){if(!bv())return{supported:!1,info:"VideoEncoder API not supported"};try{switch(i){case"h264":return await gv();case"h265":return await vv();default:return{supported:!1,info:`Unsupported video codec: ${i}`}}}catch(e){return{supported:!1,info:`${i} 检测失败: ${e instanceof Error?e.message:String(e)}`}}}async function wv(i,e=!1){const t=["aac"],r=["h264"],n={audioCodecs:{},videoCodecs:{}};for(const l of t)n.audioCodecs[l]=await Sv(l);for(const l of r)n.videoCodecs[l]=await Ev(l);const s=[],a=[],o=[],d=[];Object.entries(n.audioCodecs).forEach(([l,h])=>{h.supported?s.push(l):a.push(l)}),Object.entries(n.videoCodecs).forEach(([l,h])=>{h.supported?o.push(l):d.push(l)});const u={supported:a.length===0&&d.length===0,supportedAudio:s,supportedVideo:o,unsupportedAudio:a,unsupportedVideo:d};return e&&(u.details=n),u}async function Cv(){return(await wv()).supported}class fc{constructor(e,t,r,n,s){this.url=e,this.config=t,this.onError=r,this.onSuccess=n,this.onReconnectError=s,this._isPushing=!1,this._clearOnline=()=>{},this.sessionId=Date.now(),this.engine=new ov({userId:ht.instance.userId??""});const a=()=>{this.engine.online()};window.addEventListener("online",a),this._clearOnline=()=>{window.removeEventListener("online",a)}}static async isSupported(){return await Cv()&&typeof WebTransport<"u"&&typeof MediaStreamTrackProcessor<"u"&&typeof MediaStreamTrackGenerator<"u"&&typeof VideoEncoder<"u"}get isPushing(){return this._isPushing}get pushUrl(){return this.url}async getStatsSnapshoot(e){e&&await ki(e);const{video:t,audio:r,upspeed:n}=await this.engine.getStats();return{video:{sendBitrate:t.bitrate,framesPerSecond:t.framerate,framesEncoded:t.encodedFrames,keyFramesEncoded:t.encodedKeyFrames,sendSpeed:n,codec:t.codec,frameWidth:t.width,frameHeight:t.height,gopSize:t.keyGopSize},audio:{sendBitrate:r.bitrate,framesEncoded:r.encodedFrames,codec:r.codec,channels:r.numberOfChannels,sampleRate:r.sampleRate}}}publish(e,t,r){const n={url:this.url,maxReconnectCount:10,autoReconnect:!1,bitrate:{},cfg:Object.assign({gopSize:90},r||{}),setting:{}};e.forEach((s,a)=>{if(s.kind==="video"||s.kind==="audio"){const o=dc(s);n[s.kind]=o.readable,n.bitrate[s.kind]=t[a],n.setting[s.kind]=o.settings}}),this.engine.start(n),this._isPushing=!0,this.engine.on({"connect-open":()=>{this._isPushing=!0,this.onSuccess()},error:s=>{this.onError(new Error(JSON.stringify(s)))},"connect-close":s=>{this._isPushing=!1,s==="api call"?console.log("Connection close by api call"):this.onError(new Error(`Connect close, reason=${s}`))},"reconnect-fail":s=>{this._isPushing=!1,this.onReconnectError(new Error(`Reconnect fail, reason=${s}`))}})}unpublish(){this.engine.stop(),this._isPushing=!1}async updatePublish(e,t){e&&this.engine.updateTrack(dc(e).readable,t)}applyBitrate(e,t){this.engine.setBitrate(e,t)}reconnect(e){this.engine.reconnect(e)}destroy(){this._clearOnline(),this.engine.destroy(),this._isPushing=!1}}function mc({pushUrl:i,addPri:e=!1,disableTCC:t=!1}){const r=new URL(i),n=Date.now();return e&&r.searchParams.set("pri",n.toString()),t&&r.searchParams.set("tcc","false"),r.href}class kv{constructor(e,t=Of){this._reconnectDelay=0,this._reconnectCount=0,this._timeoutTimerId=null,this._reconnectTimeout=null,this._totalReconnectInfo={totalReconnectCount:0,totalReconnectDuration:0},this.handleOnlineReconnect=()=>{this.execute(!0)},this.execute=(r=!1)=>{var n;this._logger.log("start reconnect strategy"),this.state==="idle"&&(this._reconnectStartTime=Date.now(),this._totalReconnectInfo.totalReconnectCount+=1,O(I.PUSH_RECONNECT_START,{start_time:this._reconnectStartTime,session_id:this._pushConsumer.pushSessionId,max_timeout:this._maxTimeout}),this.bindOnlineEvent(),this.setStrategyState("executing"),(n=this._logger)==null||n.log("start reconnecting with max timeout: ",this._maxTimeout),this.startTimeoutTimer(this._maxTimeout),this._pushConsumer.emitReconnectStateChange({state:wt.START,teaParams:{is_online:navigator.onLine,start_time:this._reconnectStartTime,max_timeout:this._maxTimeout,session_id:this._pushConsumer.pushSessionId}})),this.state==="executing"&&(this._reconnectTimeout&&clearTimeout(this._reconnectTimeout),this.executeStrategy(r))},this.attemptReconnect=async()=>{var r;if(this.state==="executing"){this.setStrategyState("reconnecting"),this._reconnectCount+=1;const n=this.getNextPushUrl();try{if(this._pushConsumer.emitReconnectStateChange({state:wt.RECONNECTING,params:{retryTime:this._reconnectCount},teaParams:{retry_push_url:n,session_id:this._pushConsumer.pushSessionId}}),await this._pushConsumer.reconnect(n),!this.isActive())return;this.setStrategyState("executing")}catch(s){const a=s.ext||{},{httpCode:o}=a;if(o!==void 0&&String(o).startsWith("4"))this.stop({isSuccess:!1,reason:br.PushUrlInvalid,failedError:s}),(r=this._onReconnectError)==null||r.call(this,"pushError",s);else{if(!this.isActive())return;this.setStrategyState("executing"),this.execute()}}}},this.executeStrategy=(r=!1)=>{const n=r?0:this._reconnectDelay;this._pushConsumer.emitReconnectStateChange({state:wt.WAITING,params:{waitingTime:n,retryTime:this._reconnectCount+1},teaParams:{is_online:navigator.onLine,session_id:this._pushConsumer.pushSessionId}}),this._logger.log("reconnect after delay: ",n,Date.now()),this._reconnectTimeout=window.setTimeout(this.attemptReconnect,n),this._reconnectDelay=this._reconnectDelay===0?2e3:Math.min(this._reconnectDelay*2,Mf)},this.state="idle",this._pushConsumer=e,this._maxTimeout=t,this._logger=new nt("ReconnectStrategy")}getNextPushUrl(){const e=this._pushConsumer.pushUrl;return e?mc({pushUrl:e,addPri:!0}):""}set onReconnectError(e){this._onReconnectError=e}bindOnlineEvent(){window.addEventListener("online",this.handleOnlineReconnect)}unbindOnlineEvent(){window.removeEventListener("online",this.handleOnlineReconnect)}setStrategyState(e){this._logger.log("reconnect state change to: ",e),this.state=e}stop({isSuccess:e,reason:t,quiet:r=!1,failedError:n}){var a;if(this.state==="idle")return;const s=(Date.now()-this._reconnectStartTime)/1e3;r||(e?this._pushConsumer.emitReconnectStateChange({state:wt.SUCCESS,teaParams:{reconnect_duration:s,session_id:this._pushConsumer.pushSessionId}}):(this._logger.log("Reconnect strategy stopped: ",t),this._pushConsumer.emitReconnectStateChange({state:wt.FAILED,params:{failedCode:t},teaParams:{reason:t,reconnect_duration:s,error_message:n==null?void 0:n.message,http_code:(a=n==null?void 0:n.ext)==null?void 0:a.httpCode,ext:n==null?void 0:n.ext,session_id:this._pushConsumer.pushSessionId}})),this._totalReconnectInfo.totalReconnectDuration+=s),this.setStrategyState("idle"),this._timeoutTimerId&&clearTimeout(this._timeoutTimerId),this._reconnectTimeout&&clearTimeout(this._reconnectTimeout),this._reconnectDelay=0,this._reconnectCount=0,this._reconnectStartTime=void 0,this.unbindOnlineEvent()}startTimeoutTimer(e){this._timeoutTimerId=window.setTimeout(()=>{var t;this.state!=="idle"&&(this._logger.log("Reconnect strategy timed out"),this.stop({isSuccess:!1,reason:br.ReconnectTimeout}),(t=this._onReconnectError)==null||t.call(this,"timeout"))},e)}clearReconnectInfo(){this._totalReconnectInfo={totalReconnectCount:0,totalReconnectDuration:0}}getReconnectInfo(){return this._totalReconnectInfo}isActive(){return this.state!=="idle"}}const zi={ManualStop:0,ReconnectFailed:1,StartPushError:2,PushError:3},Ft={PushCheck:0,PushError:1},_c=new nt("PushController");class Tv extends Ga{constructor(e,{config:t,streamConsumeController:r,streamComposedController:n}){var s,a;if(super(e),this._connect=null,this._connectionState=fe.DISCONNECTED,this._pushSessionId=0,this._isReportStart=!1,this._pushMode="rtm",this._reconnectStrategy=null,this._needCheckAudioTrack=!1,this._pushConfig={timeout:5e3,retryCount:1,retryDelay:1e3},this._audioBitrate=Rt(gs,"audio").bitrate,this._videoBitrate=Rt(_s,"video").bitrate,this.handleReconnectError=(o,d)=>{var c,u;O(I.STOP_PUSH_STREAM,{reason:zi.ReconnectFailed,error_message:o,session_id:this._pushSessionId,push_mode:this._pushMode,duration:this.pushDuration,reconnect_times:(c=this._reconnectStrategy)==null?void 0:c.getReconnectInfo().totalReconnectCount,reconnect_duration:(u=this._reconnectStrategy)==null?void 0:u.getReconnectInfo().totalReconnectDuration}),this.unpublish()},this.handleAudioStreamChange=o=>{this.updatePush({audioTrack:o.audioTrack})},this.handleVideoStreamChange=o=>{this.updatePush({videoTrack:o.videoTrack})},this._OnRTMPSuccess=()=>{this.setConnectState(fe.CONNECTED)},this._OnMediaReconnectFailed=()=>{this._executeReconnect()},this._OnRTMPError=o=>{const d=new At(me.PUBLISH_FAILED,`${o.code?`code:${o.code},`:""} message: ${o.message}`);this.pushDuration<Pf||!this._reconnectStrategy||this.pushMode==="webTransport"?(this._streamConsumeController.emit(Z.PushError,d),O(I.STOP_PUSH_STREAM,{reason:zi.PushError,duration:this.pushDuration,session_id:this._pushSessionId,push_mode:this._pushMode,error_msg:o.message,error_code:o.code}),O(I.START_PUSH_STATUS,{is_success:!1,reason:Ft.PushError,error_message:o.message,session_id:this._pushSessionId,push_mode:this._pushMode,push_url:this._pushUrl}),this.unpublish()):this._executeReconnect()},this._executeReconnect=()=>{var o;(o=this._reconnectStrategy)==null||o.execute(),this.setConnectState(fe.RECONNECTING),this.unpublish({isReconnecting:!0})},this._OnRtcStateChange=o=>{var d;switch(O(I.PUSH_RTC_STATE_CHANGE,{state:o,push_url:this._pushUrl,session_id:this._pushSessionId,push_mode:this._pushMode}),this._streamConsumeController.emit(Z.RTCConnectStateChanged,o),o){case"connected":this.setConnectState(fe.CONNECTED);break;case"disconnected":this._reconnectStrategy&&this._executeReconnect();break;case"failed":(d=this._reconnectStrategy)!=null&&d.isActive()?this._executeReconnect():(this.connectionState===fe.CONNECTED?O(I.STOP_PUSH_STREAM,{reason:zi.PushError,error_message:"peerconnection failed",duration:this.pushDuration,session_id:this._pushSessionId,push_mode:this._pushMode}):O(I.START_PUSH_STATUS,{is_success:!1,reason:Ft.PushError,error_message:"peerconnection failed",session_id:this._pushSessionId,push_mode:this._pushMode,push_url:this._pushUrl}),this.unpublish(),this._streamConsumeController.emit(Z.PushError,new At(me.PUSH_CONNECT_FAILED,"pc failed")));break}},this._pushMode=(t==null?void 0:t.mode)||"rtm",this._streamConsumeController=r,t&&(this._pushConfig=t,this._needCheckAudioTrack=t.checkAudio??!1),(s=t==null?void 0:t.reconnectConfig)!=null&&s.enable||!(t!=null&&t.reconnectConfig)){const o=(a=t==null?void 0:t.reconnectConfig)!=null&&a.maxTimeout?t.reconnectConfig.maxTimeout*Io:void 0;this._reconnectStrategy=new kv(this,o),this._reconnectStrategy.onReconnectError=this.handleReconnectError}this._streamComposedController=n}get isPushing(){return this._connectionState===fe.CONNECTED||this._connectionState===fe.RECONNECTING}get pushUrl(){return this._pushUrl}get pushEncodeConfig(){return this._pushEncodeConfig}get sessionId(){var e;return((e=this._connect)==null?void 0:e.sessionId)||0}start(){this.bindComposedStreamEvent()}stop(){this.unbindComposedStreamEvent()}setPushConfig(e){e&&(this._pushConfig=e)}setConnectState(e){var t;switch(this._connectionState=e,this._streamConsumeController.emit(Z.LiveConnectStateChange,e),e){case fe.CONNECTED:(t=this._reconnectStrategy)!=null&&t.isActive()?this._reconnectStrategy.stop({isSuccess:!0}):(this._streamConsumeController.emit(Z.PushStart),this.setPushStatsInterval(),O(I.START_PUSH_STATUS,{is_success:!0,push_url:this._pushUrl,session_id:this._pushSessionId,push_mode:this._pushMode}));break}}async getStats(){return this._prevStats}async startPush(e,t={}){var a,o,d;if(t.isReconnect||(this._pushSessionId=Date.now(),O(I.START_PUSH,{push_url:e,session_id:this._pushSessionId})),!e)throw O(I.START_PUSH_STATUS,{is_success:!1,session_id:this._pushSessionId,reason:Ft.PushCheck,push_url:this._pushUrl}),new Error("lack publish url");if(this._connect)return;this.start(),this._pushUrl=mc({pushUrl:e,disableTCC:!0}),this._pushEncodeConfig=t.cfg;const r=this._composedStream.videoTrack,n=this._composedStream.audioTrack;if(this._needCheckAudioTrack&&(!r||!n)){O(I.START_PUSH_STATUS,{is_success:!1,reason:Ft.PushCheck,push_url:this._pushUrl,error_message:"lack videoTrack or audioTrack",video_track_id:r==null?void 0:r.id,audio_track_id:n==null?void 0:n.id,video_track_name:r==null?void 0:r.label,audio_track_name:n==null?void 0:n.label,push_mode:this._pushMode,session_id:this._pushSessionId});return}else if(!r&&!n){O(I.START_PUSH_STATUS,{is_success:!1,reason:Ft.PushCheck,push_url:this._pushUrl,error_message:"lack videoTrack and audioTrack",push_mode:this._pushMode,session_id:this._pushSessionId});return}let s;if(this._pushMode==="rtm")s=new ar(e,this._pushConfig,this._OnRtcStateChange);else if(this._pushMode==="webTransport")s=new wg(e,this._pushConfig,this._OnRTMPError,this._OnRTMPSuccess);else if(this._pushMode==="mediaEngine")s=new fc(e,this._pushConfig,this._OnRTMPError,this._OnRTMPSuccess,this._OnMediaReconnectFailed);else throw new Error(`not support push mode: ${this._pushMode}`);this._connect=s;try{!t.isReconnect&&((a=this._reconnectStrategy)!=null&&a.isActive())&&this._reconnectStrategy.stop({quiet:!0}),(o=this._reconnectStrategy)!=null&&o.isActive()||this.setConnectState(fe.CONNECTING),await s.publish([n,r],[this._audioBitrate,this._videoBitrate],{cfg:t.cfg,isReconnect:t.isReconnect}),t.isReconnect||(_c.log("startPush begin"),this._connectionStartDate=Date.now())}catch(c){const u=new At(me.PUBLISH_FAILED,c.message,c);if(_c.groupEnd(),(d=this._reconnectStrategy)!=null&&d.isActive())throw this.unpublish({isReconnecting:!0}),u;this._streamConsumeController.emit(Z.PushError,u),O(I.STOP_PUSH_STREAM,{reason:zi.PushError,error_message:u.message,enable_reconnect:!1,push_mode:this._pushMode,session_id:this._pushSessionId,duration:this.pushDuration}),O(I.START_PUSH_STATUS,{is_success:!1,push_url:this._pushUrl,reason:Ft.PushError,error_message:u.message,session_id:this._pushSessionId,push_mode:this._pushMode}),this.unpublish()}}setPushStatsInterval(){if(this._isReportStart)return;this._isReportStart=!0;const e=async()=>{var t,r,n,s,a;if((t=this._connect)!=null&&t.isPushing){const o=Date.now(),{stats:d,originStats:c}=await this._connect.getStatsSnapshoot(2e3),l=Date.now()-o;!wf(d)&&((r=this._connect)!=null&&r.isPushing)&&this.connectionState===fe.CONNECTED?this._prevStats=d:this._prevStats=void 0;const h=this.pushMode==="rtm"?sg(d,c,{idealFrameRate:(n=this._composedStream._videoStream)==null?void 0:n.frameRate,idealBitrate:this._videoBitrate}):og(d),p=this.pushMode==="rtm"?(s=this._connect)==null?void 0:s.videoSenderTrackStats:{};O(I.PUSH_STATS,{...h,...p,video_draw_frame:this._streamComposedController.getCompositionDrawCountPerSecond(),stats:d,push_url:this._pushUrl,push_mode:this._pushMode,session_id:this._pushSessionId,duration:h.video_duration||l,video_duration:h.video_duration||l,is_push:!0},!0)}else await ki(2e3),O(I.PUSH_STATS,{push_url:this._pushUrl,push_mode:this._pushMode,session_id:this._pushSessionId,duration:2e3,is_push:!1,is_reconnecting:((a=this._reconnectStrategy)==null?void 0:a.isActive())??!1},!0);this.connectionState!==fe.DISCONNECTED&&(this._statsLoopTimer=window.setTimeout(e,0))};e()}async reconnect(e){if(this.pushMode==="rtm")return this.startPush(e,{isReconnect:!0});if(this.pushMode==="mediaEngine")return this._connect.reconnect(e)}async updatePush({videoTrack:e,audioTrack:t}){if(this._connect)try{const r=[];e&&r.push(()=>{var n;return(n=this._connect)==null?void 0:n.updatePublish(e,"video")}),t&&r.push(()=>{var n;return(n=this._connect)==null?void 0:n.updatePublish(t,"audio")}),await Promise.all(r.map(n=>n()))}catch(r){const n=new At(me.UPDATE_PUBLISH_FAILED,`${r.name}, code:${r.code}`);this._streamConsumeController.emit(Z.PushError,n)}}unpublish(e={isReconnecting:!1,isManual:!1}){var t,r,n,s,a;e.isReconnecting&&this.pushMode==="mediaEngine"||((t=this._connect)==null||t.unpublish(),this._connect=null),this._prevStats=void 0,e.isManual&&(O(I.STOP_PUSH_STREAM,{reason:zi.ManualStop,duration:this.pushDuration,session_id:this._streamConsumeController.pushSessionId,push_mode:this._pushMode,reconnect_times:(r=this._reconnectStrategy)==null?void 0:r.getReconnectInfo().totalReconnectCount,reconnect_duration:(n=this._reconnectStrategy)==null?void 0:n.getReconnectInfo().totalReconnectDuration}),(s=this._reconnectStrategy)==null||s.clearReconnectInfo()),e.isReconnecting||(this._statsLoopTimer&&window.clearTimeout(this._statsLoopTimer),this._isReportStart=!1,this._pushEncodeConfig=void 0,this._pushUrl=void 0,this._connectionStartDate=void 0,this._pushSessionId=0,this.setConnectState(fe.DISCONNECTED),(a=this._reconnectStrategy)==null||a.stop({quiet:!0}),this._streamConsumeController.emit(Z.PushStop))}async destroy(){this._statsLoopTimer&&window.clearTimeout(this._statsLoopTimer),this._prevStats=void 0,this._isReportStart=!1,this._connect&&await this.unpublish(),this.unbindComposedStreamEvent()}setPushMode(e){this._pushMode=e}updatePushUrl(e){this._pushUrl=e}setBitrate(e,t,r){var n;t==="video"?this._videoBitrate=e:this._audioBitrate=e,(n=this._connect)==null||n.applyBitrate(e,t,r)}getReconnectDetail(){var e;return(e=this._reconnectStrategy)==null?void 0:e.getReconnectInfo()}get pushMode(){return this._pushMode}get connectionState(){return this._connectionState}get pushSessionId(){return this._pushSessionId}get pushDuration(){return this._connectionStartDate?(Date.now()-this._connectionStartDate)/1e3:0}emitReconnectStateChange({state:e,params:t,teaParams:r}){O(I.PUSH_RECONNECT_STATUS,{status:e,...t,...r}),this._streamConsumeController.emit(Z.ReconnectStateChange,e,t)}}class zv extends Je{constructor(e,t){super(),this._previewConsumer=new X_(e.getComposedStream(),{streamConsumeController:this}),this._pushConsumer=new Tv(e.getComposedStream(),{streamConsumeController:this,streamComposedController:e,config:t})}startPreview(){this._previewConsumer.startPreview()}setRenderView(e){this._previewConsumer.setRenderView(e)}async startPush(e,t){return this._pushConsumer.startPush(e,{cfg:t})}async stopPush(){return this._pushConsumer.unpublish({isReconnecting:!1,isManual:!0})}setPushMode(e){this._pushConsumer.setPushMode(e)}isPushing(){return this._pushConsumer.isPushing}getStats(){return this._pushConsumer.getStats()}getPreviewElement(){return this._previewConsumer.getPreviewElement()}stopPreview(){this._previewConsumer.stopPreview()}setBitrate(e,t,r){this._pushConsumer.setBitrate(e,t,r)}setPushConfig(e){this._pushConsumer.setPushConfig(e)}updatePushUrl(e){this._pushConsumer.updatePushUrl(e)}getPushDuration(){return this._pushConsumer.pushDuration}getReconnectDetail(){return this._pushConsumer.getReconnectDetail()}get pushSessionId(){return this._pushConsumer.pushSessionId}get pushMode(){return this._pushConsumer.pushMode}async destroy(){await this._pushConsumer.destroy(),this._previewConsumer.destroy()}}class Av{constructor(){this.onError=(e,t,r)=>{},this.onWarning=e=>{},this.onCaptureFirstAudioFrame=()=>{},this.onCaptureFirstVideoFrame=()=>{},this.onPushStatusUpdate=(e,t)=>{},this.onMicrophoneChanged=e=>{},this.onCameraChanged=e=>{},this.onCaptureInterrupted=e=>{},this.onPushStart=()=>{},this.onPushStop=()=>{},this.onStopCapture=e=>{},this.onLiveConnectStateChange=e=>{},this.onReconnectStateChange=(e,t)=>{}}}const Rv=new Av;let gc=!0,vc=!0;function lr(i,e,t){const r=i.match(e);return r&&r.length>=t&&parseInt(r[t],10)}function Et(i,e,t){if(!i.RTCPeerConnection)return;const r=i.RTCPeerConnection.prototype,n=r.addEventListener;r.addEventListener=function(a,o){if(a!==e)return n.apply(this,arguments);const d=c=>{const u=t(c);u&&(o.handleEvent?o.handleEvent(u):o(u))};return this._eventMap=this._eventMap||{},this._eventMap[e]||(this._eventMap[e]=new Map),this._eventMap[e].set(o,d),n.apply(this,[a,d])};const s=r.removeEventListener;r.removeEventListener=function(a,o){if(a!==e||!this._eventMap||!this._eventMap[e])return s.apply(this,arguments);if(!this._eventMap[e].has(o))return s.apply(this,arguments);const d=this._eventMap[e].get(o);return this._eventMap[e].delete(o),this._eventMap[e].size===0&&delete this._eventMap[e],Object.keys(this._eventMap).length===0&&delete this._eventMap,s.apply(this,[a,d])},Object.defineProperty(r,"on"+e,{get(){return this["_on"+e]},set(a){this["_on"+e]&&(this.removeEventListener(e,this["_on"+e]),delete this["_on"+e]),a&&this.addEventListener(e,this["_on"+e]=a)},enumerable:!0,configurable:!0})}function Dv(i){return typeof i!="boolean"?new Error("Argument type: "+typeof i+". Please use a boolean."):(gc=i,i?"adapter.js logging disabled":"adapter.js logging enabled")}function xv(i){return typeof i!="boolean"?new Error("Argument type: "+typeof i+". Please use a boolean."):(vc=!i,"adapter.js deprecation warnings "+(i?"disabled":"enabled"))}function yc(){if(typeof window=="object"){if(gc)return;typeof console<"u"&&typeof console.log=="function"&&console.log.apply(console,arguments)}}function Zn(i,e){vc&&console.warn(i+" is deprecated, please use "+e+" instead.")}function Iv(i){const e={browser:null,version:null};if(typeof i>"u"||!i.navigator||!i.navigator.userAgent)return e.browser="Not a browser.",e;const{navigator:t}=i;if(t.userAgentData&&t.userAgentData.brands){const r=t.userAgentData.brands.find(n=>n.brand==="Chromium");if(r)return{browser:"chrome",version:parseInt(r.version,10)}}if(t.mozGetUserMedia)e.browser="firefox",e.version=lr(t.userAgent,/Firefox\/(\d+)\./,1);else if(t.webkitGetUserMedia||i.isSecureContext===!1&&i.webkitRTCPeerConnection)e.browser="chrome",e.version=lr(t.userAgent,/Chrom(e|ium)\/(\d+)\./,2);else if(i.RTCPeerConnection&&t.userAgent.match(/AppleWebKit\/(\d+)\./))e.browser="safari",e.version=lr(t.userAgent,/AppleWebKit\/(\d+)\./,1),e.supportsUnifiedPlan=i.RTCRtpTransceiver&&"currentDirection"in i.RTCRtpTransceiver.prototype;else return e.browser="Not a supported browser.",e;return e}function bc(i){return Object.prototype.toString.call(i)==="[object Object]"}function Sc(i){return bc(i)?Object.keys(i).reduce(function(e,t){const r=bc(i[t]),n=r?Sc(i[t]):i[t],s=r&&!Object.keys(n).length;return n===void 0||s?e:Object.assign(e,{[t]:n})},{}):i}function Qn(i,e,t){!e||t.has(e.id)||(t.set(e.id,e),Object.keys(e).forEach(r=>{r.endsWith("Id")?Qn(i,i.get(e[r]),t):r.endsWith("Ids")&&e[r].forEach(n=>{Qn(i,i.get(n),t)})}))}function Ec(i,e,t){const r=t?"outbound-rtp":"inbound-rtp",n=new Map;if(e===null)return n;const s=[];return i.forEach(a=>{a.type==="track"&&a.trackIdentifier===e.id&&s.push(a)}),s.forEach(a=>{i.forEach(o=>{o.type===r&&o.trackId===a.id&&Qn(i,o,n)})}),n}const wc=yc;function Cc(i,e){const t=i&&i.navigator;if(!t.mediaDevices)return;const r=function(o){if(typeof o!="object"||o.mandatory||o.optional)return o;const d={};return Object.keys(o).forEach(c=>{if(c==="require"||c==="advanced"||c==="mediaSource")return;const u=typeof o[c]=="object"?o[c]:{ideal:o[c]};u.exact!==void 0&&typeof u.exact=="number"&&(u.min=u.max=u.exact);const l=function(h,p){return h?h+p.charAt(0).toUpperCase()+p.slice(1):p==="deviceId"?"sourceId":p};if(u.ideal!==void 0){d.optional=d.optional||[];let h={};typeof u.ideal=="number"?(h[l("min",c)]=u.ideal,d.optional.push(h),h={},h[l("max",c)]=u.ideal,d.optional.push(h)):(h[l("",c)]=u.ideal,d.optional.push(h))}u.exact!==void 0&&typeof u.exact!="number"?(d.mandatory=d.mandatory||{},d.mandatory[l("",c)]=u.exact):["min","max"].forEach(h=>{u[h]!==void 0&&(d.mandatory=d.mandatory||{},d.mandatory[l(h,c)]=u[h])})}),o.advanced&&(d.optional=(d.optional||[]).concat(o.advanced)),d},n=function(o,d){if(e.version>=61)return d(o);if(o=JSON.parse(JSON.stringify(o)),o&&typeof o.audio=="object"){const c=function(u,l,h){l in u&&!(h in u)&&(u[h]=u[l],delete u[l])};o=JSON.parse(JSON.stringify(o)),c(o.audio,"autoGainControl","googAutoGainControl"),c(o.audio,"noiseSuppression","googNoiseSuppression"),o.audio=r(o.audio)}if(o&&typeof o.video=="object"){let c=o.video.facingMode;c=c&&(typeof c=="object"?c:{ideal:c});const u=e.version<66;if(c&&(c.exact==="user"||c.exact==="environment"||c.ideal==="user"||c.ideal==="environment")&&!(t.mediaDevices.getSupportedConstraints&&t.mediaDevices.getSupportedConstraints().facingMode&&!u)){delete o.video.facingMode;let l;if(c.exact==="environment"||c.ideal==="environment"?l=["back","rear"]:(c.exact==="user"||c.ideal==="user")&&(l=["front"]),l)return t.mediaDevices.enumerateDevices().then(h=>{h=h.filter(f=>f.kind==="videoinput");let p=h.find(f=>l.some(v=>f.label.toLowerCase().includes(v)));return!p&&h.length&&l.includes("back")&&(p=h[h.length-1]),p&&(o.video.deviceId=c.exact?{exact:p.deviceId}:{ideal:p.deviceId}),o.video=r(o.video),wc("chrome: "+JSON.stringify(o)),d(o)})}o.video=r(o.video)}return wc("chrome: "+JSON.stringify(o)),d(o)},s=function(o){return e.version>=64?o:{name:{PermissionDeniedError:"NotAllowedError",PermissionDismissedError:"NotAllowedError",InvalidStateError:"NotAllowedError",DevicesNotFoundError:"NotFoundError",ConstraintNotSatisfiedError:"OverconstrainedError",TrackStartError:"NotReadableError",MediaDeviceFailedDueToShutdown:"NotAllowedError",MediaDeviceKillSwitchOn:"NotAllowedError",TabCaptureError:"AbortError",ScreenCaptureError:"AbortError",DeviceCaptureError:"AbortError"}[o.name]||o.name,message:o.message,constraint:o.constraint||o.constraintName,toString(){return this.name+(this.message&&": ")+this.message}}},a=function(o,d,c){n(o,u=>{t.webkitGetUserMedia(u,d,l=>{c&&c(s(l))})})};if(t.getUserMedia=a.bind(t),t.mediaDevices.getUserMedia){const o=t.mediaDevices.getUserMedia.bind(t.mediaDevices);t.mediaDevices.getUserMedia=function(d){return n(d,c=>o(c).then(u=>{if(c.audio&&!u.getAudioTracks().length||c.video&&!u.getVideoTracks().length)throw u.getTracks().forEach(l=>{l.stop()}),new DOMException("","NotFoundError");return u},u=>Promise.reject(s(u))))}}}function kc(i){i.MediaStream=i.MediaStream||i.webkitMediaStream}function Tc(i){if(typeof i=="object"&&i.RTCPeerConnection&&!("ontrack"in i.RTCPeerConnection.prototype)){Object.defineProperty(i.RTCPeerConnection.prototype,"ontrack",{get(){return this._ontrack},set(t){this._ontrack&&this.removeEventListener("track",this._ontrack),this.addEventListener("track",this._ontrack=t)},enumerable:!0,configurable:!0});const e=i.RTCPeerConnection.prototype.setRemoteDescription;i.RTCPeerConnection.prototype.setRemoteDescription=function(){return this._ontrackpoly||(this._ontrackpoly=r=>{r.stream.addEventListener("addtrack",n=>{let s;i.RTCPeerConnection.prototype.getReceivers?s=this.getReceivers().find(o=>o.track&&o.track.id===n.track.id):s={track:n.track};const a=new Event("track");a.track=n.track,a.receiver=s,a.transceiver={receiver:s},a.streams=[r.stream],this.dispatchEvent(a)}),r.stream.getTracks().forEach(n=>{let s;i.RTCPeerConnection.prototype.getReceivers?s=this.getReceivers().find(o=>o.track&&o.track.id===n.id):s={track:n};const a=new Event("track");a.track=n,a.receiver=s,a.transceiver={receiver:s},a.streams=[r.stream],this.dispatchEvent(a)})},this.addEventListener("addstream",this._ontrackpoly)),e.apply(this,arguments)}}else Et(i,"track",e=>(e.transceiver||Object.defineProperty(e,"transceiver",{value:{receiver:e.receiver}}),e))}function zc(i){if(typeof i=="object"&&i.RTCPeerConnection&&!("getSenders"in i.RTCPeerConnection.prototype)&&"createDTMFSender"in i.RTCPeerConnection.prototype){const e=function(n,s){return{track:s,get dtmf(){return this._dtmf===void 0&&(s.kind==="audio"?this._dtmf=n.createDTMFSender(s):this._dtmf=null),this._dtmf},_pc:n}};if(!i.RTCPeerConnection.prototype.getSenders){i.RTCPeerConnection.prototype.getSenders=function(){return this._senders=this._senders||[],this._senders.slice()};const n=i.RTCPeerConnection.prototype.addTrack;i.RTCPeerConnection.prototype.addTrack=function(o,d){let c=n.apply(this,arguments);return c||(c=e(this,o),this._senders.push(c)),c};const s=i.RTCPeerConnection.prototype.removeTrack;i.RTCPeerConnection.prototype.removeTrack=function(o){s.apply(this,arguments);const d=this._senders.indexOf(o);d!==-1&&this._senders.splice(d,1)}}const t=i.RTCPeerConnection.prototype.addStream;i.RTCPeerConnection.prototype.addStream=function(s){this._senders=this._senders||[],t.apply(this,[s]),s.getTracks().forEach(a=>{this._senders.push(e(this,a))})};const r=i.RTCPeerConnection.prototype.removeStream;i.RTCPeerConnection.prototype.removeStream=function(s){this._senders=this._senders||[],r.apply(this,[s]),s.getTracks().forEach(a=>{const o=this._senders.find(d=>d.track===a);o&&this._senders.splice(this._senders.indexOf(o),1)})}}else if(typeof i=="object"&&i.RTCPeerConnection&&"getSenders"in i.RTCPeerConnection.prototype&&"createDTMFSender"in i.RTCPeerConnection.prototype&&i.RTCRtpSender&&!("dtmf"in i.RTCRtpSender.prototype)){const e=i.RTCPeerConnection.prototype.getSenders;i.RTCPeerConnection.prototype.getSenders=function(){const r=e.apply(this,[]);return r.forEach(n=>n._pc=this),r},Object.defineProperty(i.RTCRtpSender.prototype,"dtmf",{get(){return this._dtmf===void 0&&(this.track.kind==="audio"?this._dtmf=this._pc.createDTMFSender(this.track):this._dtmf=null),this._dtmf}})}}function Ac(i){if(!(typeof i=="object"&&i.RTCPeerConnection&&i.RTCRtpSender&&i.RTCRtpReceiver))return;if(!("getStats"in i.RTCRtpSender.prototype)){const t=i.RTCPeerConnection.prototype.getSenders;t&&(i.RTCPeerConnection.prototype.getSenders=function(){const s=t.apply(this,[]);return s.forEach(a=>a._pc=this),s});const r=i.RTCPeerConnection.prototype.addTrack;r&&(i.RTCPeerConnection.prototype.addTrack=function(){const s=r.apply(this,arguments);return s._pc=this,s}),i.RTCRtpSender.prototype.getStats=function(){const s=this;return this._pc.getStats().then(a=>Ec(a,s.track,!0))}}if(!("getStats"in i.RTCRtpReceiver.prototype)){const t=i.RTCPeerConnection.prototype.getReceivers;t&&(i.RTCPeerConnection.prototype.getReceivers=function(){const n=t.apply(this,[]);return n.forEach(s=>s._pc=this),n}),Et(i,"track",r=>(r.receiver._pc=r.srcElement,r)),i.RTCRtpReceiver.prototype.getStats=function(){const n=this;return this._pc.getStats().then(s=>Ec(s,n.track,!1))}}if(!("getStats"in i.RTCRtpSender.prototype&&"getStats"in i.RTCRtpReceiver.prototype))return;const e=i.RTCPeerConnection.prototype.getStats;i.RTCPeerConnection.prototype.getStats=function(){if(arguments.length>0&&arguments[0]instanceof i.MediaStreamTrack){const r=arguments[0];let n,s,a;return this.getSenders().forEach(o=>{o.track===r&&(n?a=!0:n=o)}),this.getReceivers().forEach(o=>(o.track===r&&(s?a=!0:s=o),o.track===r)),a||n&&s?Promise.reject(new DOMException("There are more than one sender or receiver for the track.","InvalidAccessError")):n?n.getStats():s?s.getStats():Promise.reject(new DOMException("There is no sender or receiver for the track.","InvalidAccessError"))}return e.apply(this,arguments)}}function Rc(i){i.RTCPeerConnection.prototype.getLocalStreams=function(){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},Object.keys(this._shimmedLocalStreams).map(a=>this._shimmedLocalStreams[a][0])};const e=i.RTCPeerConnection.prototype.addTrack;i.RTCPeerConnection.prototype.addTrack=function(a,o){if(!o)return e.apply(this,arguments);this._shimmedLocalStreams=this._shimmedLocalStreams||{};const d=e.apply(this,arguments);return this._shimmedLocalStreams[o.id]?this._shimmedLocalStreams[o.id].indexOf(d)===-1&&this._shimmedLocalStreams[o.id].push(d):this._shimmedLocalStreams[o.id]=[o,d],d};const t=i.RTCPeerConnection.prototype.addStream;i.RTCPeerConnection.prototype.addStream=function(a){this._shimmedLocalStreams=this._shimmedLocalStreams||{},a.getTracks().forEach(c=>{if(this.getSenders().find(l=>l.track===c))throw new DOMException("Track already exists.","InvalidAccessError")});const o=this.getSenders();t.apply(this,arguments);const d=this.getSenders().filter(c=>o.indexOf(c)===-1);this._shimmedLocalStreams[a.id]=[a].concat(d)};const r=i.RTCPeerConnection.prototype.removeStream;i.RTCPeerConnection.prototype.removeStream=function(a){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},delete this._shimmedLocalStreams[a.id],r.apply(this,arguments)};const n=i.RTCPeerConnection.prototype.removeTrack;i.RTCPeerConnection.prototype.removeTrack=function(a){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},a&&Object.keys(this._shimmedLocalStreams).forEach(o=>{const d=this._shimmedLocalStreams[o].indexOf(a);d!==-1&&this._shimmedLocalStreams[o].splice(d,1),this._shimmedLocalStreams[o].length===1&&delete this._shimmedLocalStreams[o]}),n.apply(this,arguments)}}function Dc(i,e){if(!i.RTCPeerConnection)return;if(i.RTCPeerConnection.prototype.addTrack&&e.version>=65)return Rc(i);const t=i.RTCPeerConnection.prototype.getLocalStreams;i.RTCPeerConnection.prototype.getLocalStreams=function(){const u=t.apply(this);return this._reverseStreams=this._reverseStreams||{},u.map(l=>this._reverseStreams[l.id])};const r=i.RTCPeerConnection.prototype.addStream;i.RTCPeerConnection.prototype.addStream=function(u){if(this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},u.getTracks().forEach(l=>{if(this.getSenders().find(p=>p.track===l))throw new DOMException("Track already exists.","InvalidAccessError")}),!this._reverseStreams[u.id]){const l=new i.MediaStream(u.getTracks());this._streams[u.id]=l,this._reverseStreams[l.id]=u,u=l}r.apply(this,[u])};const n=i.RTCPeerConnection.prototype.removeStream;i.RTCPeerConnection.prototype.removeStream=function(u){this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},n.apply(this,[this._streams[u.id]||u]),delete this._reverseStreams[this._streams[u.id]?this._streams[u.id].id:u.id],delete this._streams[u.id]},i.RTCPeerConnection.prototype.addTrack=function(u,l){if(this.signalingState==="closed")throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");const h=[].slice.call(arguments,1);if(h.length!==1||!h[0].getTracks().find(v=>v===u))throw new DOMException("The adapter.js addTrack polyfill only supports a single stream which is associated with the specified track.","NotSupportedError");if(this.getSenders().find(v=>v.track===u))throw new DOMException("Track already exists.","InvalidAccessError");this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{};const f=this._streams[l.id];if(f)f.addTrack(u),Promise.resolve().then(()=>{this.dispatchEvent(new Event("negotiationneeded"))});else{const v=new i.MediaStream([u]);this._streams[l.id]=v,this._reverseStreams[v.id]=l,this.addStream(v)}return this.getSenders().find(v=>v.track===u)};function s(c,u){let l=u.sdp;return Object.keys(c._reverseStreams||[]).forEach(h=>{const p=c._reverseStreams[h],f=c._streams[p.id];l=l.replace(new RegExp(f.id,"g"),p.id)}),new RTCSessionDescription({type:u.type,sdp:l})}function a(c,u){let l=u.sdp;return Object.keys(c._reverseStreams||[]).forEach(h=>{const p=c._reverseStreams[h],f=c._streams[p.id];l=l.replace(new RegExp(p.id,"g"),f.id)}),new RTCSessionDescription({type:u.type,sdp:l})}["createOffer","createAnswer"].forEach(function(c){const u=i.RTCPeerConnection.prototype[c],l={[c](){const h=arguments;return arguments.length&&typeof arguments[0]=="function"?u.apply(this,[f=>{const v=s(this,f);h[0].apply(null,[v])},f=>{h[1]&&h[1].apply(null,f)},arguments[2]]):u.apply(this,arguments).then(f=>s(this,f))}};i.RTCPeerConnection.prototype[c]=l[c]});const o=i.RTCPeerConnection.prototype.setLocalDescription;i.RTCPeerConnection.prototype.setLocalDescription=function(){return!arguments.length||!arguments[0].type?o.apply(this,arguments):(arguments[0]=a(this,arguments[0]),o.apply(this,arguments))};const d=Object.getOwnPropertyDescriptor(i.RTCPeerConnection.prototype,"localDescription");Object.defineProperty(i.RTCPeerConnection.prototype,"localDescription",{get(){const c=d.get.apply(this);return c.type===""?c:s(this,c)}}),i.RTCPeerConnection.prototype.removeTrack=function(u){if(this.signalingState==="closed")throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");if(!u._pc)throw new DOMException("Argument 1 of RTCPeerConnection.removeTrack does not implement interface RTCRtpSender.","TypeError");if(!(u._pc===this))throw new DOMException("Sender was not created by this connection.","InvalidAccessError");this._streams=this._streams||{};let h;Object.keys(this._streams).forEach(p=>{this._streams[p].getTracks().find(v=>u.track===v)&&(h=this._streams[p])}),h&&(h.getTracks().length===1?this.removeStream(this._reverseStreams[h.id]):h.removeTrack(u.track),this.dispatchEvent(new Event("negotiationneeded")))}}function Yn(i,e){!i.RTCPeerConnection&&i.webkitRTCPeerConnection&&(i.RTCPeerConnection=i.webkitRTCPeerConnection),i.RTCPeerConnection&&e.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach(function(t){const r=i.RTCPeerConnection.prototype[t],n={[t](){return arguments[0]=new(t==="addIceCandidate"?i.RTCIceCandidate:i.RTCSessionDescription)(arguments[0]),r.apply(this,arguments)}};i.RTCPeerConnection.prototype[t]=n[t]})}function xc(i,e){Et(i,"negotiationneeded",t=>{const r=t.target;if(!((e.version<72||r.getConfiguration&&r.getConfiguration().sdpSemantics==="plan-b")&&r.signalingState!=="stable"))return t})}const Ic=Object.freeze(Object.defineProperty({__proto__:null,fixNegotiationNeeded:xc,shimAddTrackRemoveTrack:Dc,shimAddTrackRemoveTrackWithNative:Rc,shimGetSendersWithDtmf:zc,shimGetUserMedia:Cc,shimMediaStream:kc,shimOnTrack:Tc,shimPeerConnection:Yn,shimSenderReceiverGetStats:Ac},Symbol.toStringTag,{value:"Module"}));function Oc(i,e){const t=i&&i.navigator,r=i&&i.MediaStreamTrack;if(t.getUserMedia=function(n,s,a){Zn("navigator.getUserMedia","navigator.mediaDevices.getUserMedia"),t.mediaDevices.getUserMedia(n).then(s,a)},!(e.version>55&&"autoGainControl"in t.mediaDevices.getSupportedConstraints())){const n=function(a,o,d){o in a&&!(d in a)&&(a[d]=a[o],delete a[o])},s=t.mediaDevices.getUserMedia.bind(t.mediaDevices);if(t.mediaDevices.getUserMedia=function(a){return typeof a=="object"&&typeof a.audio=="object"&&(a=JSON.parse(JSON.stringify(a)),n(a.audio,"autoGainControl","mozAutoGainControl"),n(a.audio,"noiseSuppression","mozNoiseSuppression")),s(a)},r&&r.prototype.getSettings){const a=r.prototype.getSettings;r.prototype.getSettings=function(){const o=a.apply(this,arguments);return n(o,"mozAutoGainControl","autoGainControl"),n(o,"mozNoiseSuppression","noiseSuppression"),o}}if(r&&r.prototype.applyConstraints){const a=r.prototype.applyConstraints;r.prototype.applyConstraints=function(o){return this.kind==="audio"&&typeof o=="object"&&(o=JSON.parse(JSON.stringify(o)),n(o,"autoGainControl","mozAutoGainControl"),n(o,"noiseSuppression","mozNoiseSuppression")),a.apply(this,[o])}}}}function Ov(i,e){i.navigator.mediaDevices&&"getDisplayMedia"in i.navigator.mediaDevices||i.navigator.mediaDevices&&(i.navigator.mediaDevices.getDisplayMedia=function(r){if(!(r&&r.video)){const n=new DOMException("getDisplayMedia without video constraints is undefined");return n.name="NotFoundError",n.code=8,Promise.reject(n)}return r.video===!0?r.video={mediaSource:e}:r.video.mediaSource=e,i.navigator.mediaDevices.getUserMedia(r)})}function Mc(i){typeof i=="object"&&i.RTCTrackEvent&&"receiver"in i.RTCTrackEvent.prototype&&!("transceiver"in i.RTCTrackEvent.prototype)&&Object.defineProperty(i.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function es(i,e){if(typeof i!="object"||!(i.RTCPeerConnection||i.mozRTCPeerConnection))return;!i.RTCPeerConnection&&i.mozRTCPeerConnection&&(i.RTCPeerConnection=i.mozRTCPeerConnection),e.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach(function(n){const s=i.RTCPeerConnection.prototype[n],a={[n](){return arguments[0]=new(n==="addIceCandidate"?i.RTCIceCandidate:i.RTCSessionDescription)(arguments[0]),s.apply(this,arguments)}};i.RTCPeerConnection.prototype[n]=a[n]});const t={inboundrtp:"inbound-rtp",outboundrtp:"outbound-rtp",candidatepair:"candidate-pair",localcandidate:"local-candidate",remotecandidate:"remote-candidate"},r=i.RTCPeerConnection.prototype.getStats;i.RTCPeerConnection.prototype.getStats=function(){const[s,a,o]=arguments;return r.apply(this,[s||null]).then(d=>{if(e.version<53&&!a)try{d.forEach(c=>{c.type=t[c.type]||c.type})}catch(c){if(c.name!=="TypeError")throw c;d.forEach((u,l)=>{d.set(l,Object.assign({},u,{type:t[u.type]||u.type}))})}return d}).then(a,o)}}function Pc(i){if(!(typeof i=="object"&&i.RTCPeerConnection&&i.RTCRtpSender)||i.RTCRtpSender&&"getStats"in i.RTCRtpSender.prototype)return;const e=i.RTCPeerConnection.prototype.getSenders;e&&(i.RTCPeerConnection.prototype.getSenders=function(){const n=e.apply(this,[]);return n.forEach(s=>s._pc=this),n});const t=i.RTCPeerConnection.prototype.addTrack;t&&(i.RTCPeerConnection.prototype.addTrack=function(){const n=t.apply(this,arguments);return n._pc=this,n}),i.RTCRtpSender.prototype.getStats=function(){return this.track?this._pc.getStats(this.track):Promise.resolve(new Map)}}function Lc(i){if(!(typeof i=="object"&&i.RTCPeerConnection&&i.RTCRtpSender)||i.RTCRtpSender&&"getStats"in i.RTCRtpReceiver.prototype)return;const e=i.RTCPeerConnection.prototype.getReceivers;e&&(i.RTCPeerConnection.prototype.getReceivers=function(){const r=e.apply(this,[]);return r.forEach(n=>n._pc=this),r}),Et(i,"track",t=>(t.receiver._pc=t.srcElement,t)),i.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track)}}function Uc(i){!i.RTCPeerConnection||"removeStream"in i.RTCPeerConnection.prototype||(i.RTCPeerConnection.prototype.removeStream=function(t){Zn("removeStream","removeTrack"),this.getSenders().forEach(r=>{r.track&&t.getTracks().includes(r.track)&&this.removeTrack(r)})})}function Gc(i){i.DataChannel&&!i.RTCDataChannel&&(i.RTCDataChannel=i.DataChannel)}function Nc(i){if(!(typeof i=="object"&&i.RTCPeerConnection))return;const e=i.RTCPeerConnection.prototype.addTransceiver;e&&(i.RTCPeerConnection.prototype.addTransceiver=function(){this.setParametersPromises=[];let r=arguments[1]&&arguments[1].sendEncodings;r===void 0&&(r=[]),r=[...r];const n=r.length>0;n&&r.forEach(a=>{if("rid"in a&&!/^[a-z0-9]{0,16}$/i.test(a.rid))throw new TypeError("Invalid RID value provided.");if("scaleResolutionDownBy"in a&&!(parseFloat(a.scaleResolutionDownBy)>=1))throw new RangeError("scale_resolution_down_by must be >= 1.0");if("maxFramerate"in a&&!(parseFloat(a.maxFramerate)>=0))throw new RangeError("max_framerate must be >= 0.0")});const s=e.apply(this,arguments);if(n){const{sender:a}=s,o=a.getParameters();(!("encodings"in o)||o.encodings.length===1&&Object.keys(o.encodings[0]).length===0)&&(o.encodings=r,a.sendEncodings=r,this.setParametersPromises.push(a.setParameters(o).then(()=>{delete a.sendEncodings}).catch(()=>{delete a.sendEncodings})))}return s})}function Bc(i){if(!(typeof i=="object"&&i.RTCRtpSender))return;const e=i.RTCRtpSender.prototype.getParameters;e&&(i.RTCRtpSender.prototype.getParameters=function(){const r=e.apply(this,arguments);return"encodings"in r||(r.encodings=[].concat(this.sendEncodings||[{}])),r})}function Vc(i){if(!(typeof i=="object"&&i.RTCPeerConnection))return;const e=i.RTCPeerConnection.prototype.createOffer;i.RTCPeerConnection.prototype.createOffer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then(()=>e.apply(this,arguments)).finally(()=>{this.setParametersPromises=[]}):e.apply(this,arguments)}}function Fc(i){if(!(typeof i=="object"&&i.RTCPeerConnection))return;const e=i.RTCPeerConnection.prototype.createAnswer;i.RTCPeerConnection.prototype.createAnswer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then(()=>e.apply(this,arguments)).finally(()=>{this.setParametersPromises=[]}):e.apply(this,arguments)}}const jc=Object.freeze(Object.defineProperty({__proto__:null,shimAddTransceiver:Nc,shimCreateAnswer:Fc,shimCreateOffer:Vc,shimGetDisplayMedia:Ov,shimGetParameters:Bc,shimGetUserMedia:Oc,shimOnTrack:Mc,shimPeerConnection:es,shimRTCDataChannel:Gc,shimReceiverGetStats:Lc,shimRemoveStream:Uc,shimSenderGetStats:Pc},Symbol.toStringTag,{value:"Module"}));function Hc(i){if(!(typeof i!="object"||!i.RTCPeerConnection)){if("getLocalStreams"in i.RTCPeerConnection.prototype||(i.RTCPeerConnection.prototype.getLocalStreams=function(){return this._localStreams||(this._localStreams=[]),this._localStreams}),!("addStream"in i.RTCPeerConnection.prototype)){const e=i.RTCPeerConnection.prototype.addTrack;i.RTCPeerConnection.prototype.addStream=function(r){this._localStreams||(this._localStreams=[]),this._localStreams.includes(r)||this._localStreams.push(r),r.getAudioTracks().forEach(n=>e.call(this,n,r)),r.getVideoTracks().forEach(n=>e.call(this,n,r))},i.RTCPeerConnection.prototype.addTrack=function(r,...n){return n&&n.forEach(s=>{this._localStreams?this._localStreams.includes(s)||this._localStreams.push(s):this._localStreams=[s]}),e.apply(this,arguments)}}"removeStream"in i.RTCPeerConnection.prototype||(i.RTCPeerConnection.prototype.removeStream=function(t){this._localStreams||(this._localStreams=[]);const r=this._localStreams.indexOf(t);if(r===-1)return;this._localStreams.splice(r,1);const n=t.getTracks();this.getSenders().forEach(s=>{n.includes(s.track)&&this.removeTrack(s)})})}}function $c(i){if(!(typeof i!="object"||!i.RTCPeerConnection)&&("getRemoteStreams"in i.RTCPeerConnection.prototype||(i.RTCPeerConnection.prototype.getRemoteStreams=function(){return this._remoteStreams?this._remoteStreams:[]}),!("onaddstream"in i.RTCPeerConnection.prototype))){Object.defineProperty(i.RTCPeerConnection.prototype,"onaddstream",{get(){return this._onaddstream},set(t){this._onaddstream&&(this.removeEventListener("addstream",this._onaddstream),this.removeEventListener("track",this._onaddstreampoly)),this.addEventListener("addstream",this._onaddstream=t),this.addEventListener("track",this._onaddstreampoly=r=>{r.streams.forEach(n=>{if(this._remoteStreams||(this._remoteStreams=[]),this._remoteStreams.includes(n))return;this._remoteStreams.push(n);const s=new Event("addstream");s.stream=n,this.dispatchEvent(s)})})}});const e=i.RTCPeerConnection.prototype.setRemoteDescription;i.RTCPeerConnection.prototype.setRemoteDescription=function(){const r=this;return this._onaddstreampoly||this.addEventListener("track",this._onaddstreampoly=function(n){n.streams.forEach(s=>{if(r._remoteStreams||(r._remoteStreams=[]),r._remoteStreams.indexOf(s)>=0)return;r._remoteStreams.push(s);const a=new Event("addstream");a.stream=s,r.dispatchEvent(a)})}),e.apply(r,arguments)}}}function qc(i){if(typeof i!="object"||!i.RTCPeerConnection)return;const e=i.RTCPeerConnection.prototype,t=e.createOffer,r=e.createAnswer,n=e.setLocalDescription,s=e.setRemoteDescription,a=e.addIceCandidate;e.createOffer=function(c,u){const l=arguments.length>=2?arguments[2]:arguments[0],h=t.apply(this,[l]);return u?(h.then(c,u),Promise.resolve()):h},e.createAnswer=function(c,u){const l=arguments.length>=2?arguments[2]:arguments[0],h=r.apply(this,[l]);return u?(h.then(c,u),Promise.resolve()):h};let o=function(d,c,u){const l=n.apply(this,[d]);return u?(l.then(c,u),Promise.resolve()):l};e.setLocalDescription=o,o=function(d,c,u){const l=s.apply(this,[d]);return u?(l.then(c,u),Promise.resolve()):l},e.setRemoteDescription=o,o=function(d,c,u){const l=a.apply(this,[d]);return u?(l.then(c,u),Promise.resolve()):l},e.addIceCandidate=o}function Kc(i){const e=i&&i.navigator;if(e.mediaDevices&&e.mediaDevices.getUserMedia){const t=e.mediaDevices,r=t.getUserMedia.bind(t);e.mediaDevices.getUserMedia=n=>r(Wc(n))}!e.getUserMedia&&e.mediaDevices&&e.mediaDevices.getUserMedia&&(e.getUserMedia=(function(r,n,s){e.mediaDevices.getUserMedia(r).then(n,s)}).bind(e))}function Wc(i){return i&&i.video!==void 0?Object.assign({},i,{video:Sc(i.video)}):i}function Jc(i){if(!i.RTCPeerConnection)return;const e=i.RTCPeerConnection;i.RTCPeerConnection=function(r,n){if(r&&r.iceServers){const s=[];for(let a=0;a<r.iceServers.length;a++){let o=r.iceServers[a];o.urls===void 0&&o.url?(Zn("RTCIceServer.url","RTCIceServer.urls"),o=JSON.parse(JSON.stringify(o)),o.urls=o.url,delete o.url,s.push(o)):s.push(r.iceServers[a])}r.iceServers=s}return new e(r,n)},i.RTCPeerConnection.prototype=e.prototype,"generateCertificate"in e&&Object.defineProperty(i.RTCPeerConnection,"generateCertificate",{get(){return e.generateCertificate}})}function Xc(i){typeof i=="object"&&i.RTCTrackEvent&&"receiver"in i.RTCTrackEvent.prototype&&!("transceiver"in i.RTCTrackEvent.prototype)&&Object.defineProperty(i.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function Zc(i){const e=i.RTCPeerConnection.prototype.createOffer;i.RTCPeerConnection.prototype.createOffer=function(r){if(r){typeof r.offerToReceiveAudio<"u"&&(r.offerToReceiveAudio=!!r.offerToReceiveAudio);const n=this.getTransceivers().find(a=>a.receiver.track.kind==="audio");r.offerToReceiveAudio===!1&&n?n.direction==="sendrecv"?n.setDirection?n.setDirection("sendonly"):n.direction="sendonly":n.direction==="recvonly"&&(n.setDirection?n.setDirection("inactive"):n.direction="inactive"):r.offerToReceiveAudio===!0&&!n&&this.addTransceiver("audio",{direction:"recvonly"}),typeof r.offerToReceiveVideo<"u"&&(r.offerToReceiveVideo=!!r.offerToReceiveVideo);const s=this.getTransceivers().find(a=>a.receiver.track.kind==="video");r.offerToReceiveVideo===!1&&s?s.direction==="sendrecv"?s.setDirection?s.setDirection("sendonly"):s.direction="sendonly":s.direction==="recvonly"&&(s.setDirection?s.setDirection("inactive"):s.direction="inactive"):r.offerToReceiveVideo===!0&&!s&&this.addTransceiver("video",{direction:"recvonly"})}return e.apply(this,arguments)}}function Qc(i){typeof i!="object"||i.AudioContext||(i.AudioContext=i.webkitAudioContext)}const Yc=Object.freeze(Object.defineProperty({__proto__:null,shimAudioContext:Qc,shimCallbacksAPI:qc,shimConstraints:Wc,shimCreateOfferLegacy:Zc,shimGetUserMedia:Kc,shimLocalStreamsAPI:Hc,shimRTCIceServerUrls:Jc,shimRemoteStreamsAPI:$c,shimTrackEventTransceiver:Xc},Symbol.toStringTag,{value:"Module"}));var ts={exports:{}},eu;function Mv(){return eu||(eu=1,function(i){const e={};e.generateIdentifier=function(){return Math.random().toString(36).substring(2,12)},e.localCName=e.generateIdentifier(),e.splitLines=function(t){return t.trim().split(`
80
+ `).map(r=>r.trim())},e.splitSections=function(t){return t.split(`
81
+ m=`).map((n,s)=>(s>0?"m="+n:n).trim()+`\r
82
+ `)},e.getDescription=function(t){const r=e.splitSections(t);return r&&r[0]},e.getMediaSections=function(t){const r=e.splitSections(t);return r.shift(),r},e.matchPrefix=function(t,r){return e.splitLines(t).filter(n=>n.indexOf(r)===0)},e.parseCandidate=function(t){let r;t.indexOf("a=candidate:")===0?r=t.substring(12).split(" "):r=t.substring(10).split(" ");const n={foundation:r[0],component:{1:"rtp",2:"rtcp"}[r[1]]||r[1],protocol:r[2].toLowerCase(),priority:parseInt(r[3],10),ip:r[4],address:r[4],port:parseInt(r[5],10),type:r[7]};for(let s=8;s<r.length;s+=2)switch(r[s]){case"raddr":n.relatedAddress=r[s+1];break;case"rport":n.relatedPort=parseInt(r[s+1],10);break;case"tcptype":n.tcpType=r[s+1];break;case"ufrag":n.ufrag=r[s+1],n.usernameFragment=r[s+1];break;default:n[r[s]]===void 0&&(n[r[s]]=r[s+1]);break}return n},e.writeCandidate=function(t){const r=[];r.push(t.foundation);const n=t.component;n==="rtp"?r.push(1):n==="rtcp"?r.push(2):r.push(n),r.push(t.protocol.toUpperCase()),r.push(t.priority),r.push(t.address||t.ip),r.push(t.port);const s=t.type;return r.push("typ"),r.push(s),s!=="host"&&t.relatedAddress&&t.relatedPort&&(r.push("raddr"),r.push(t.relatedAddress),r.push("rport"),r.push(t.relatedPort)),t.tcpType&&t.protocol.toLowerCase()==="tcp"&&(r.push("tcptype"),r.push(t.tcpType)),(t.usernameFragment||t.ufrag)&&(r.push("ufrag"),r.push(t.usernameFragment||t.ufrag)),"candidate:"+r.join(" ")},e.parseIceOptions=function(t){return t.substring(14).split(" ")},e.parseRtpMap=function(t){let r=t.substring(9).split(" ");const n={payloadType:parseInt(r.shift(),10)};return r=r[0].split("/"),n.name=r[0],n.clockRate=parseInt(r[1],10),n.channels=r.length===3?parseInt(r[2],10):1,n.numChannels=n.channels,n},e.writeRtpMap=function(t){let r=t.payloadType;t.preferredPayloadType!==void 0&&(r=t.preferredPayloadType);const n=t.channels||t.numChannels||1;return"a=rtpmap:"+r+" "+t.name+"/"+t.clockRate+(n!==1?"/"+n:"")+`\r
83
+ `},e.parseExtmap=function(t){const r=t.substring(9).split(" ");return{id:parseInt(r[0],10),direction:r[0].indexOf("/")>0?r[0].split("/")[1]:"sendrecv",uri:r[1],attributes:r.slice(2).join(" ")}},e.writeExtmap=function(t){return"a=extmap:"+(t.id||t.preferredId)+(t.direction&&t.direction!=="sendrecv"?"/"+t.direction:"")+" "+t.uri+(t.attributes?" "+t.attributes:"")+`\r
84
+ `},e.parseFmtp=function(t){const r={};let n;const s=t.substring(t.indexOf(" ")+1).split(";");for(let a=0;a<s.length;a++)n=s[a].trim().split("="),r[n[0].trim()]=n[1];return r},e.writeFmtp=function(t){let r="",n=t.payloadType;if(t.preferredPayloadType!==void 0&&(n=t.preferredPayloadType),t.parameters&&Object.keys(t.parameters).length){const s=[];Object.keys(t.parameters).forEach(a=>{t.parameters[a]!==void 0?s.push(a+"="+t.parameters[a]):s.push(a)}),r+="a=fmtp:"+n+" "+s.join(";")+`\r
85
+ `}return r},e.parseRtcpFb=function(t){const r=t.substring(t.indexOf(" ")+1).split(" ");return{type:r.shift(),parameter:r.join(" ")}},e.writeRtcpFb=function(t){let r="",n=t.payloadType;return t.preferredPayloadType!==void 0&&(n=t.preferredPayloadType),t.rtcpFeedback&&t.rtcpFeedback.length&&t.rtcpFeedback.forEach(s=>{r+="a=rtcp-fb:"+n+" "+s.type+(s.parameter&&s.parameter.length?" "+s.parameter:"")+`\r
86
+ `}),r},e.parseSsrcMedia=function(t){const r=t.indexOf(" "),n={ssrc:parseInt(t.substring(7,r),10)},s=t.indexOf(":",r);return s>-1?(n.attribute=t.substring(r+1,s),n.value=t.substring(s+1)):n.attribute=t.substring(r+1),n},e.parseSsrcGroup=function(t){const r=t.substring(13).split(" ");return{semantics:r.shift(),ssrcs:r.map(n=>parseInt(n,10))}},e.getMid=function(t){const r=e.matchPrefix(t,"a=mid:")[0];if(r)return r.substring(6)},e.parseFingerprint=function(t){const r=t.substring(14).split(" ");return{algorithm:r[0].toLowerCase(),value:r[1].toUpperCase()}},e.getDtlsParameters=function(t,r){return{role:"auto",fingerprints:e.matchPrefix(t+r,"a=fingerprint:").map(e.parseFingerprint)}},e.writeDtlsParameters=function(t,r){let n="a=setup:"+r+`\r
87
+ `;return t.fingerprints.forEach(s=>{n+="a=fingerprint:"+s.algorithm+" "+s.value+`\r
88
+ `}),n},e.parseCryptoLine=function(t){const r=t.substring(9).split(" ");return{tag:parseInt(r[0],10),cryptoSuite:r[1],keyParams:r[2],sessionParams:r.slice(3)}},e.writeCryptoLine=function(t){return"a=crypto:"+t.tag+" "+t.cryptoSuite+" "+(typeof t.keyParams=="object"?e.writeCryptoKeyParams(t.keyParams):t.keyParams)+(t.sessionParams?" "+t.sessionParams.join(" "):"")+`\r
89
+ `},e.parseCryptoKeyParams=function(t){if(t.indexOf("inline:")!==0)return null;const r=t.substring(7).split("|");return{keyMethod:"inline",keySalt:r[0],lifeTime:r[1],mkiValue:r[2]?r[2].split(":")[0]:void 0,mkiLength:r[2]?r[2].split(":")[1]:void 0}},e.writeCryptoKeyParams=function(t){return t.keyMethod+":"+t.keySalt+(t.lifeTime?"|"+t.lifeTime:"")+(t.mkiValue&&t.mkiLength?"|"+t.mkiValue+":"+t.mkiLength:"")},e.getCryptoParameters=function(t,r){return e.matchPrefix(t+r,"a=crypto:").map(e.parseCryptoLine)},e.getIceParameters=function(t,r){const n=e.matchPrefix(t+r,"a=ice-ufrag:")[0],s=e.matchPrefix(t+r,"a=ice-pwd:")[0];return n&&s?{usernameFragment:n.substring(12),password:s.substring(10)}:null},e.writeIceParameters=function(t){let r="a=ice-ufrag:"+t.usernameFragment+`\r
70
90
  a=ice-pwd:`+t.password+`\r
71
- `;return t.iceLite&&(i+=`a=ice-lite\r
72
- `),i},e.parseRtpParameters=function(t){const i={codecs:[],headerExtensions:[],fecMechanisms:[],rtcp:[]},n=e.splitLines(t)[0].split(" ");i.profile=n[2];for(let o=3;o<n.length;o++){const u=n[o],d=e.matchPrefix(t,"a=rtpmap:"+u+" ")[0];if(d){const c=e.parseRtpMap(d),h=e.matchPrefix(t,"a=fmtp:"+u+" ");switch(c.parameters=h.length?e.parseFmtp(h[0]):{},c.rtcpFeedback=e.matchPrefix(t,"a=rtcp-fb:"+u+" ").map(e.parseRtcpFb),i.codecs.push(c),c.name.toUpperCase()){case"RED":case"ULPFEC":i.fecMechanisms.push(c.name.toUpperCase());break}}}e.matchPrefix(t,"a=extmap:").forEach(o=>{i.headerExtensions.push(e.parseExtmap(o))});const a=e.matchPrefix(t,"a=rtcp-fb:* ").map(e.parseRtcpFb);return i.codecs.forEach(o=>{a.forEach(u=>{o.rtcpFeedback.find(c=>c.type===u.type&&c.parameter===u.parameter)||o.rtcpFeedback.push(u)})}),i},e.writeRtpDescription=function(t,i){let s="";s+="m="+t+" ",s+=i.codecs.length>0?"9":"0",s+=" "+(i.profile||"UDP/TLS/RTP/SAVPF")+" ",s+=i.codecs.map(a=>a.preferredPayloadType!==void 0?a.preferredPayloadType:a.payloadType).join(" ")+`\r
73
- `,s+=`c=IN IP4 0.0.0.0\r
74
- `,s+=`a=rtcp:9 IN IP4 0.0.0.0\r
75
- `,i.codecs.forEach(a=>{s+=e.writeRtpMap(a),s+=e.writeFmtp(a),s+=e.writeRtcpFb(a)});let n=0;return i.codecs.forEach(a=>{a.maxptime>n&&(n=a.maxptime)}),n>0&&(s+="a=maxptime:"+n+`\r
76
- `),i.headerExtensions&&i.headerExtensions.forEach(a=>{s+=e.writeExtmap(a)}),s},e.parseRtpEncodingParameters=function(t){const i=[],s=e.parseRtpParameters(t),n=s.fecMechanisms.indexOf("RED")!==-1,a=s.fecMechanisms.indexOf("ULPFEC")!==-1,o=e.matchPrefix(t,"a=ssrc:").map(p=>e.parseSsrcMedia(p)).filter(p=>p.attribute==="cname"),u=o.length>0&&o[0].ssrc;let d;const c=e.matchPrefix(t,"a=ssrc-group:FID").map(p=>p.substring(17).split(" ").map(f=>parseInt(f,10)));c.length>0&&c[0].length>1&&c[0][0]===u&&(d=c[0][1]),s.codecs.forEach(p=>{if(p.name.toUpperCase()==="RTX"&&p.parameters.apt){let l={ssrc:u,codecPayloadType:parseInt(p.parameters.apt,10)};u&&d&&(l.rtx={ssrc:d}),i.push(l),n&&(l=JSON.parse(JSON.stringify(l)),l.fec={ssrc:u,mechanism:a?"red+ulpfec":"red"},i.push(l))}}),i.length===0&&u&&i.push({ssrc:u});let h=e.matchPrefix(t,"b=");return h.length&&(h[0].indexOf("b=TIAS:")===0?h=parseInt(h[0].substring(7),10):h[0].indexOf("b=AS:")===0?h=parseInt(h[0].substring(5),10)*1e3*.95-50*40*8:h=void 0,i.forEach(p=>{p.maxBitrate=h})),i},e.parseRtcpParameters=function(t){const i={},s=e.matchPrefix(t,"a=ssrc:").map(o=>e.parseSsrcMedia(o)).filter(o=>o.attribute==="cname")[0];s&&(i.cname=s.value,i.ssrc=s.ssrc);const n=e.matchPrefix(t,"a=rtcp-rsize");i.reducedSize=n.length>0,i.compound=n.length===0;const a=e.matchPrefix(t,"a=rtcp-mux");return i.mux=a.length>0,i},e.writeRtcpParameters=function(t){let i="";return t.reducedSize&&(i+=`a=rtcp-rsize\r
77
- `),t.mux&&(i+=`a=rtcp-mux\r
78
- `),t.ssrc!==void 0&&t.cname&&(i+="a=ssrc:"+t.ssrc+" cname:"+t.cname+`\r
79
- `),i},e.parseMsid=function(t){let i;const s=e.matchPrefix(t,"a=msid:");if(s.length===1)return i=s[0].substring(7).split(" "),{stream:i[0],track:i[1]};const n=e.matchPrefix(t,"a=ssrc:").map(a=>e.parseSsrcMedia(a)).filter(a=>a.attribute==="msid");if(n.length>0)return i=n[0].value.split(" "),{stream:i[0],track:i[1]}},e.parseSctpDescription=function(t){const i=e.parseMLine(t),s=e.matchPrefix(t,"a=max-message-size:");let n;s.length>0&&(n=parseInt(s[0].substring(19),10)),isNaN(n)&&(n=65536);const a=e.matchPrefix(t,"a=sctp-port:");if(a.length>0)return{port:parseInt(a[0].substring(12),10),protocol:i.fmt,maxMessageSize:n};const o=e.matchPrefix(t,"a=sctpmap:");if(o.length>0){const u=o[0].substring(10).split(" ");return{port:parseInt(u[0],10),protocol:u[1],maxMessageSize:n}}},e.writeSctpDescription=function(t,i){let s=[];return t.protocol!=="DTLS/SCTP"?s=["m="+t.kind+" 9 "+t.protocol+" "+i.protocol+`\r
91
+ `;return t.iceLite&&(r+=`a=ice-lite\r
92
+ `),r},e.parseRtpParameters=function(t){const r={codecs:[],headerExtensions:[],fecMechanisms:[],rtcp:[]},s=e.splitLines(t)[0].split(" ");r.profile=s[2];for(let o=3;o<s.length;o++){const d=s[o],c=e.matchPrefix(t,"a=rtpmap:"+d+" ")[0];if(c){const u=e.parseRtpMap(c),l=e.matchPrefix(t,"a=fmtp:"+d+" ");switch(u.parameters=l.length?e.parseFmtp(l[0]):{},u.rtcpFeedback=e.matchPrefix(t,"a=rtcp-fb:"+d+" ").map(e.parseRtcpFb),r.codecs.push(u),u.name.toUpperCase()){case"RED":case"ULPFEC":r.fecMechanisms.push(u.name.toUpperCase());break}}}e.matchPrefix(t,"a=extmap:").forEach(o=>{r.headerExtensions.push(e.parseExtmap(o))});const a=e.matchPrefix(t,"a=rtcp-fb:* ").map(e.parseRtcpFb);return r.codecs.forEach(o=>{a.forEach(d=>{o.rtcpFeedback.find(u=>u.type===d.type&&u.parameter===d.parameter)||o.rtcpFeedback.push(d)})}),r},e.writeRtpDescription=function(t,r){let n="";n+="m="+t+" ",n+=r.codecs.length>0?"9":"0",n+=" "+(r.profile||"UDP/TLS/RTP/SAVPF")+" ",n+=r.codecs.map(a=>a.preferredPayloadType!==void 0?a.preferredPayloadType:a.payloadType).join(" ")+`\r
93
+ `,n+=`c=IN IP4 0.0.0.0\r
94
+ `,n+=`a=rtcp:9 IN IP4 0.0.0.0\r
95
+ `,r.codecs.forEach(a=>{n+=e.writeRtpMap(a),n+=e.writeFmtp(a),n+=e.writeRtcpFb(a)});let s=0;return r.codecs.forEach(a=>{a.maxptime>s&&(s=a.maxptime)}),s>0&&(n+="a=maxptime:"+s+`\r
96
+ `),r.headerExtensions&&r.headerExtensions.forEach(a=>{n+=e.writeExtmap(a)}),n},e.parseRtpEncodingParameters=function(t){const r=[],n=e.parseRtpParameters(t),s=n.fecMechanisms.indexOf("RED")!==-1,a=n.fecMechanisms.indexOf("ULPFEC")!==-1,o=e.matchPrefix(t,"a=ssrc:").map(h=>e.parseSsrcMedia(h)).filter(h=>h.attribute==="cname"),d=o.length>0&&o[0].ssrc;let c;const u=e.matchPrefix(t,"a=ssrc-group:FID").map(h=>h.substring(17).split(" ").map(f=>parseInt(f,10)));u.length>0&&u[0].length>1&&u[0][0]===d&&(c=u[0][1]),n.codecs.forEach(h=>{if(h.name.toUpperCase()==="RTX"&&h.parameters.apt){let p={ssrc:d,codecPayloadType:parseInt(h.parameters.apt,10)};d&&c&&(p.rtx={ssrc:c}),r.push(p),s&&(p=JSON.parse(JSON.stringify(p)),p.fec={ssrc:d,mechanism:a?"red+ulpfec":"red"},r.push(p))}}),r.length===0&&d&&r.push({ssrc:d});let l=e.matchPrefix(t,"b=");return l.length&&(l[0].indexOf("b=TIAS:")===0?l=parseInt(l[0].substring(7),10):l[0].indexOf("b=AS:")===0?l=parseInt(l[0].substring(5),10)*1e3*.95-50*40*8:l=void 0,r.forEach(h=>{h.maxBitrate=l})),r},e.parseRtcpParameters=function(t){const r={},n=e.matchPrefix(t,"a=ssrc:").map(o=>e.parseSsrcMedia(o)).filter(o=>o.attribute==="cname")[0];n&&(r.cname=n.value,r.ssrc=n.ssrc);const s=e.matchPrefix(t,"a=rtcp-rsize");r.reducedSize=s.length>0,r.compound=s.length===0;const a=e.matchPrefix(t,"a=rtcp-mux");return r.mux=a.length>0,r},e.writeRtcpParameters=function(t){let r="";return t.reducedSize&&(r+=`a=rtcp-rsize\r
97
+ `),t.mux&&(r+=`a=rtcp-mux\r
98
+ `),t.ssrc!==void 0&&t.cname&&(r+="a=ssrc:"+t.ssrc+" cname:"+t.cname+`\r
99
+ `),r},e.parseMsid=function(t){let r;const n=e.matchPrefix(t,"a=msid:");if(n.length===1)return r=n[0].substring(7).split(" "),{stream:r[0],track:r[1]};const s=e.matchPrefix(t,"a=ssrc:").map(a=>e.parseSsrcMedia(a)).filter(a=>a.attribute==="msid");if(s.length>0)return r=s[0].value.split(" "),{stream:r[0],track:r[1]}},e.parseSctpDescription=function(t){const r=e.parseMLine(t),n=e.matchPrefix(t,"a=max-message-size:");let s;n.length>0&&(s=parseInt(n[0].substring(19),10)),isNaN(s)&&(s=65536);const a=e.matchPrefix(t,"a=sctp-port:");if(a.length>0)return{port:parseInt(a[0].substring(12),10),protocol:r.fmt,maxMessageSize:s};const o=e.matchPrefix(t,"a=sctpmap:");if(o.length>0){const d=o[0].substring(10).split(" ");return{port:parseInt(d[0],10),protocol:d[1],maxMessageSize:s}}},e.writeSctpDescription=function(t,r){let n=[];return t.protocol!=="DTLS/SCTP"?n=["m="+t.kind+" 9 "+t.protocol+" "+r.protocol+`\r
80
100
  `,`c=IN IP4 0.0.0.0\r
81
- `,"a=sctp-port:"+i.port+`\r
82
- `]:s=["m="+t.kind+" 9 "+t.protocol+" "+i.port+`\r
101
+ `,"a=sctp-port:"+r.port+`\r
102
+ `]:n=["m="+t.kind+" 9 "+t.protocol+" "+r.port+`\r
83
103
  `,`c=IN IP4 0.0.0.0\r
84
- `,"a=sctpmap:"+i.port+" "+i.protocol+` 65535\r
85
- `],i.maxMessageSize!==void 0&&s.push("a=max-message-size:"+i.maxMessageSize+`\r
86
- `),s.join("")},e.generateSessionId=function(){return Math.random().toString().substr(2,22)},e.writeSessionBoilerplate=function(t,i,s){let n;const a=i!==void 0?i:2;return t?n=t:n=e.generateSessionId(),`v=0\r
87
- o=`+(s||"thisisadapterortc")+" "+n+" "+a+` IN IP4 127.0.0.1\r
104
+ `,"a=sctpmap:"+r.port+" "+r.protocol+` 65535\r
105
+ `],r.maxMessageSize!==void 0&&n.push("a=max-message-size:"+r.maxMessageSize+`\r
106
+ `),n.join("")},e.generateSessionId=function(){return Math.random().toString().substr(2,22)},e.writeSessionBoilerplate=function(t,r,n){let s;const a=r!==void 0?r:2;return t?s=t:s=e.generateSessionId(),`v=0\r
107
+ o=`+(n||"thisisadapterortc")+" "+s+" "+a+` IN IP4 127.0.0.1\r
88
108
  s=-\r
89
109
  t=0 0\r
90
- `},e.getDirection=function(t,i){const s=e.splitLines(t);for(let n=0;n<s.length;n++)switch(s[n]){case"a=sendrecv":case"a=sendonly":case"a=recvonly":case"a=inactive":return s[n].substring(2)}return i?e.getDirection(i):"sendrecv"},e.getKind=function(t){return e.splitLines(t)[0].split(" ")[0].substring(2)},e.isRejected=function(t){return t.split(" ",2)[1]==="0"},e.parseMLine=function(t){const s=e.splitLines(t)[0].substring(2).split(" ");return{kind:s[0],port:parseInt(s[1],10),protocol:s[2],fmt:s.slice(3).join(" ")}},e.parseOLine=function(t){const s=e.matchPrefix(t,"o=")[0].substring(2).split(" ");return{username:s[0],sessionId:s[1],sessionVersion:parseInt(s[2],10),netType:s[3],addressType:s[4],address:s[5]}},e.isValidSDP=function(t){if(typeof t!="string"||t.length===0)return!1;const i=e.splitLines(t);for(let s=0;s<i.length;s++)if(i[s].length<2||i[s].charAt(1)!=="=")return!1;return!0},r.exports=e}(qt)),qt.exports}var ys=sh();const Se=I(ys),nh=$({__proto__:null,default:Se},[ys]);function Ze(r){if(!r.RTCIceCandidate||r.RTCIceCandidate&&"foundation"in r.RTCIceCandidate.prototype)return;const e=r.RTCIceCandidate;r.RTCIceCandidate=function(i){if(typeof i=="object"&&i.candidate&&i.candidate.indexOf("a=")===0&&(i=JSON.parse(JSON.stringify(i)),i.candidate=i.candidate.substring(2)),i.candidate&&i.candidate.length){const s=new e(i),n=Se.parseCandidate(i.candidate);for(const a in n)a in s||Object.defineProperty(s,a,{value:n[a]});return s.toJSON=function(){return{candidate:s.candidate,sdpMid:s.sdpMid,sdpMLineIndex:s.sdpMLineIndex,usernameFragment:s.usernameFragment}},s}return new e(i)},r.RTCIceCandidate.prototype=e.prototype,pe(r,"icecandidate",t=>(t.candidate&&Object.defineProperty(t,"candidate",{value:new r.RTCIceCandidate(t.candidate),writable:"false"}),t))}function Wt(r){!r.RTCIceCandidate||r.RTCIceCandidate&&"relayProtocol"in r.RTCIceCandidate.prototype||pe(r,"icecandidate",e=>{if(e.candidate){const t=Se.parseCandidate(e.candidate.candidate);t.type==="relay"&&(e.candidate.relayProtocol={0:"tls",1:"tcp",2:"udp"}[t.priority>>24])}return e})}function Qe(r,e){if(!r.RTCPeerConnection)return;"sctp"in r.RTCPeerConnection.prototype||Object.defineProperty(r.RTCPeerConnection.prototype,"sctp",{get(){return typeof this._sctp>"u"?null:this._sctp}});const t=function(o){if(!o||!o.sdp)return!1;const u=Se.splitSections(o.sdp);return u.shift(),u.some(d=>{const c=Se.parseMLine(d);return c&&c.kind==="application"&&c.protocol.indexOf("SCTP")!==-1})},i=function(o){const u=o.sdp.match(/mozilla...THIS_IS_SDPARTA-(\d+)/);if(u===null||u.length<2)return-1;const d=parseInt(u[1],10);return d!==d?-1:d},s=function(o){let u=65536;return e.browser==="firefox"&&(e.version<57?o===-1?u=16384:u=2147483637:e.version<60?u=e.version===57?65535:65536:u=2147483637),u},n=function(o,u){let d=65536;e.browser==="firefox"&&e.version===57&&(d=65535);const c=Se.matchPrefix(o.sdp,"a=max-message-size:");return c.length>0?d=parseInt(c[0].substring(19),10):e.browser==="firefox"&&u!==-1&&(d=2147483637),d},a=r.RTCPeerConnection.prototype.setRemoteDescription;r.RTCPeerConnection.prototype.setRemoteDescription=function(){if(this._sctp=null,e.browser==="chrome"&&e.version>=76){const{sdpSemantics:u}=this.getConfiguration();u==="plan-b"&&Object.defineProperty(this,"sctp",{get(){return typeof this._sctp>"u"?null:this._sctp},enumerable:!0,configurable:!0})}if(t(arguments[0])){const u=i(arguments[0]),d=s(u),c=n(arguments[0],u);let h;d===0&&c===0?h=Number.POSITIVE_INFINITY:d===0||c===0?h=Math.max(d,c):h=Math.min(d,c);const p={};Object.defineProperty(p,"maxMessageSize",{get(){return h}}),this._sctp=p}return a.apply(this,arguments)}}function et(r){if(!(r.RTCPeerConnection&&"createDataChannel"in r.RTCPeerConnection.prototype))return;function e(i,s){const n=i.send;i.send=function(){const o=arguments[0],u=o.length||o.size||o.byteLength;if(i.readyState==="open"&&s.sctp&&u>s.sctp.maxMessageSize)throw new TypeError("Message too large (can send a maximum of "+s.sctp.maxMessageSize+" bytes)");return n.apply(i,arguments)}}const t=r.RTCPeerConnection.prototype.createDataChannel;r.RTCPeerConnection.prototype.createDataChannel=function(){const s=t.apply(this,arguments);return e(s,this),s},pe(r,"datachannel",i=>(e(i.channel,i.target),i))}function Xt(r){if(!r.RTCPeerConnection||"connectionState"in r.RTCPeerConnection.prototype)return;const e=r.RTCPeerConnection.prototype;Object.defineProperty(e,"connectionState",{get(){return{completed:"connected",checking:"connecting"}[this.iceConnectionState]||this.iceConnectionState},enumerable:!0,configurable:!0}),Object.defineProperty(e,"onconnectionstatechange",{get(){return this._onconnectionstatechange||null},set(t){this._onconnectionstatechange&&(this.removeEventListener("connectionstatechange",this._onconnectionstatechange),delete this._onconnectionstatechange),t&&this.addEventListener("connectionstatechange",this._onconnectionstatechange=t)},enumerable:!0,configurable:!0}),["setLocalDescription","setRemoteDescription"].forEach(t=>{const i=e[t];e[t]=function(){return this._connectionstatechangepoly||(this._connectionstatechangepoly=s=>{const n=s.target;if(n._lastConnectionState!==n.connectionState){n._lastConnectionState=n.connectionState;const a=new Event("connectionstatechange",s);n.dispatchEvent(a)}return s},this.addEventListener("iceconnectionstatechange",this._connectionstatechangepoly)),i.apply(this,arguments)}})}function Kt(r,e){if(!r.RTCPeerConnection||e.browser==="chrome"&&e.version>=71||e.browser==="safari"&&e.version>=605)return;const t=r.RTCPeerConnection.prototype.setRemoteDescription;r.RTCPeerConnection.prototype.setRemoteDescription=function(s){if(s&&s.sdp&&s.sdp.indexOf(`
91
- a=extmap-allow-mixed`)!==-1){const n=s.sdp.split(`
110
+ `},e.getDirection=function(t,r){const n=e.splitLines(t);for(let s=0;s<n.length;s++)switch(n[s]){case"a=sendrecv":case"a=sendonly":case"a=recvonly":case"a=inactive":return n[s].substring(2)}return r?e.getDirection(r):"sendrecv"},e.getKind=function(t){return e.splitLines(t)[0].split(" ")[0].substring(2)},e.isRejected=function(t){return t.split(" ",2)[1]==="0"},e.parseMLine=function(t){const n=e.splitLines(t)[0].substring(2).split(" ");return{kind:n[0],port:parseInt(n[1],10),protocol:n[2],fmt:n.slice(3).join(" ")}},e.parseOLine=function(t){const n=e.matchPrefix(t,"o=")[0].substring(2).split(" ");return{username:n[0],sessionId:n[1],sessionVersion:parseInt(n[2],10),netType:n[3],addressType:n[4],address:n[5]}},e.isValidSDP=function(t){if(typeof t!="string"||t.length===0)return!1;const r=e.splitLines(t);for(let n=0;n<r.length;n++)if(r[n].length<2||r[n].charAt(1)!=="=")return!1;return!0},i.exports=e}(ts)),ts.exports}var tu=Mv();const jt=ae(tu),Pv=Ce({__proto__:null,default:jt},[tu]);function pr(i){if(!i.RTCIceCandidate||i.RTCIceCandidate&&"foundation"in i.RTCIceCandidate.prototype)return;const e=i.RTCIceCandidate;i.RTCIceCandidate=function(r){if(typeof r=="object"&&r.candidate&&r.candidate.indexOf("a=")===0&&(r=JSON.parse(JSON.stringify(r)),r.candidate=r.candidate.substring(2)),r.candidate&&r.candidate.length){const n=new e(r),s=jt.parseCandidate(r.candidate);for(const a in s)a in n||Object.defineProperty(n,a,{value:s[a]});return n.toJSON=function(){return{candidate:n.candidate,sdpMid:n.sdpMid,sdpMLineIndex:n.sdpMLineIndex,usernameFragment:n.usernameFragment}},n}return new e(r)},i.RTCIceCandidate.prototype=e.prototype,Et(i,"icecandidate",t=>(t.candidate&&Object.defineProperty(t,"candidate",{value:new i.RTCIceCandidate(t.candidate),writable:"false"}),t))}function is(i){!i.RTCIceCandidate||i.RTCIceCandidate&&"relayProtocol"in i.RTCIceCandidate.prototype||Et(i,"icecandidate",e=>{if(e.candidate){const t=jt.parseCandidate(e.candidate.candidate);t.type==="relay"&&(e.candidate.relayProtocol={0:"tls",1:"tcp",2:"udp"}[t.priority>>24])}return e})}function fr(i,e){if(!i.RTCPeerConnection)return;"sctp"in i.RTCPeerConnection.prototype||Object.defineProperty(i.RTCPeerConnection.prototype,"sctp",{get(){return typeof this._sctp>"u"?null:this._sctp}});const t=function(o){if(!o||!o.sdp)return!1;const d=jt.splitSections(o.sdp);return d.shift(),d.some(c=>{const u=jt.parseMLine(c);return u&&u.kind==="application"&&u.protocol.indexOf("SCTP")!==-1})},r=function(o){const d=o.sdp.match(/mozilla...THIS_IS_SDPARTA-(\d+)/);if(d===null||d.length<2)return-1;const c=parseInt(d[1],10);return c!==c?-1:c},n=function(o){let d=65536;return e.browser==="firefox"&&(e.version<57?o===-1?d=16384:d=2147483637:e.version<60?d=e.version===57?65535:65536:d=2147483637),d},s=function(o,d){let c=65536;e.browser==="firefox"&&e.version===57&&(c=65535);const u=jt.matchPrefix(o.sdp,"a=max-message-size:");return u.length>0?c=parseInt(u[0].substring(19),10):e.browser==="firefox"&&d!==-1&&(c=2147483637),c},a=i.RTCPeerConnection.prototype.setRemoteDescription;i.RTCPeerConnection.prototype.setRemoteDescription=function(){if(this._sctp=null,e.browser==="chrome"&&e.version>=76){const{sdpSemantics:d}=this.getConfiguration();d==="plan-b"&&Object.defineProperty(this,"sctp",{get(){return typeof this._sctp>"u"?null:this._sctp},enumerable:!0,configurable:!0})}if(t(arguments[0])){const d=r(arguments[0]),c=n(d),u=s(arguments[0],d);let l;c===0&&u===0?l=Number.POSITIVE_INFINITY:c===0||u===0?l=Math.max(c,u):l=Math.min(c,u);const h={};Object.defineProperty(h,"maxMessageSize",{get(){return l}}),this._sctp=h}return a.apply(this,arguments)}}function mr(i){if(!(i.RTCPeerConnection&&"createDataChannel"in i.RTCPeerConnection.prototype))return;function e(r,n){const s=r.send;r.send=function(){const o=arguments[0],d=o.length||o.size||o.byteLength;if(r.readyState==="open"&&n.sctp&&d>n.sctp.maxMessageSize)throw new TypeError("Message too large (can send a maximum of "+n.sctp.maxMessageSize+" bytes)");return s.apply(r,arguments)}}const t=i.RTCPeerConnection.prototype.createDataChannel;i.RTCPeerConnection.prototype.createDataChannel=function(){const n=t.apply(this,arguments);return e(n,this),n},Et(i,"datachannel",r=>(e(r.channel,r.target),r))}function rs(i){if(!i.RTCPeerConnection||"connectionState"in i.RTCPeerConnection.prototype)return;const e=i.RTCPeerConnection.prototype;Object.defineProperty(e,"connectionState",{get(){return{completed:"connected",checking:"connecting"}[this.iceConnectionState]||this.iceConnectionState},enumerable:!0,configurable:!0}),Object.defineProperty(e,"onconnectionstatechange",{get(){return this._onconnectionstatechange||null},set(t){this._onconnectionstatechange&&(this.removeEventListener("connectionstatechange",this._onconnectionstatechange),delete this._onconnectionstatechange),t&&this.addEventListener("connectionstatechange",this._onconnectionstatechange=t)},enumerable:!0,configurable:!0}),["setLocalDescription","setRemoteDescription"].forEach(t=>{const r=e[t];e[t]=function(){return this._connectionstatechangepoly||(this._connectionstatechangepoly=n=>{const s=n.target;if(s._lastConnectionState!==s.connectionState){s._lastConnectionState=s.connectionState;const a=new Event("connectionstatechange",n);s.dispatchEvent(a)}return n},this.addEventListener("iceconnectionstatechange",this._connectionstatechangepoly)),r.apply(this,arguments)}})}function ns(i,e){if(!i.RTCPeerConnection||e.browser==="chrome"&&e.version>=71||e.browser==="safari"&&e.version>=605)return;const t=i.RTCPeerConnection.prototype.setRemoteDescription;i.RTCPeerConnection.prototype.setRemoteDescription=function(n){if(n&&n.sdp&&n.sdp.indexOf(`
111
+ a=extmap-allow-mixed`)!==-1){const s=n.sdp.split(`
92
112
  `).filter(a=>a.trim()!=="a=extmap-allow-mixed").join(`
93
- `);r.RTCSessionDescription&&s instanceof r.RTCSessionDescription?arguments[0]=new r.RTCSessionDescription({type:s.type,sdp:n}):s.sdp=n}return t.apply(this,arguments)}}function tt(r,e){if(!(r.RTCPeerConnection&&r.RTCPeerConnection.prototype))return;const t=r.RTCPeerConnection.prototype.addIceCandidate;!t||t.length===0||(r.RTCPeerConnection.prototype.addIceCandidate=function(){return arguments[0]?(e.browser==="chrome"&&e.version<78||e.browser==="firefox"&&e.version<68||e.browser==="safari")&&arguments[0]&&arguments[0].candidate===""?Promise.resolve():t.apply(this,arguments):(arguments[1]&&arguments[1].apply(null),Promise.resolve())})}function rt(r,e){if(!(r.RTCPeerConnection&&r.RTCPeerConnection.prototype))return;const t=r.RTCPeerConnection.prototype.setLocalDescription;!t||t.length===0||(r.RTCPeerConnection.prototype.setLocalDescription=function(){let s=arguments[0]||{};if(typeof s!="object"||s.type&&s.sdp)return t.apply(this,arguments);if(s={type:s.type,sdp:s.sdp},!s.type)switch(this.signalingState){case"stable":case"have-local-offer":case"have-remote-pranswer":s.type="offer";break;default:s.type="answer";break}return s.sdp||s.type!=="offer"&&s.type!=="answer"?t.apply(this,[s]):(s.type==="offer"?this.createOffer:this.createAnswer).apply(this).then(a=>t.apply(this,[a]))})}const oh=Object.freeze(Object.defineProperty({__proto__:null,removeExtmapAllowMixed:Kt,shimAddIceCandidateNullOrEmpty:tt,shimConnectionState:Xt,shimMaxMessageSize:Qe,shimParameterlessSetLocalDescription:rt,shimRTCIceCandidate:Ze,shimRTCIceCandidateRelayProtocol:Wt,shimSendThrowTypeError:et},Symbol.toStringTag,{value:"Module"}));function ah({window:r}={},e={shimChrome:!0,shimFirefox:!0,shimSafari:!0}){const t=Vi,i=rh(r),s={browserDetails:i,commonShim:oh,extractVersion:Ye,disableLog:eh,disableWarnings:th,sdp:nh};switch(i.browser){case"chrome":if(!Yi||!Gt||!e.shimChrome)return t("Chrome shim is not included in this adapter release."),s;if(i.version===null)return t("Chrome shim can not determine version, not shimming."),s;t("adapter.js shimming chrome."),s.browserShim=Yi,tt(r,i),rt(r),zi(r,i),Gi(r),Gt(r,i),Hi(r),Ki(r,i),qi(r),Wi(r),Ji(r,i),Ze(r),Wt(r),Xt(r),Qe(r,i),et(r),Kt(r,i);break;case"firefox":if(!cs||!Ht||!e.shimFirefox)return t("Firefox shim is not included in this adapter release."),s;t("adapter.js shimming firefox."),s.browserShim=cs,tt(r,i),rt(r),Zi(r,i),Ht(r,i),Qi(r),rs(r),es(r),ts(r),is(r),ss(r),ns(r),os(r),as(r),Ze(r),Xt(r),Qe(r,i),et(r);break;case"safari":if(!vs||!e.shimSafari)return t("Safari shim is not included in this adapter release."),s;t("adapter.js shimming safari."),s.browserShim=vs,tt(r,i),rt(r),ms(r),_s(r),hs(r),ds(r),us(r),fs(r),ps(r),gs(r),Ze(r),Wt(r),Qe(r,i),et(r),Kt(r,i);break;default:t("Unsupported browser!");break}return s}ah({window:typeof window>"u"?void 0:window});class ch extends Q{static async isSupported(e){if(e==="webTransport")return Promise.resolve(Di.isSupported());try{return Wu()||!window.RTCPeerConnection||!window.RTCPeerConnection.prototype.addTransceiver||!window.RTCPeerConnection.prototype.createDataChannel?!1:await Yu()&&await Ju()}catch{return!1}}constructor(e){super(),this._streamManagerController=new mu,this._streamComposeController=new bu(this._streamManagerController),this._streamConsumeController=new qu(this._streamComposeController),this._streamConsumeController.setPushConfig(e),this._observer=Qu,this._bindEvent()}async getDevicesList(e){return this._streamManagerController.getDevicesList(e)}async getCameras(){return this._streamManagerController.getCameras()}async getMicrophones(){return this._streamManagerController.getMicrophones()}async startCamera(e){return this._streamManagerController.startCameraCapture(e)}stopCamera(e){this._streamManagerController.stopCapture({streamId:e,type:S.Camera})}async startMicrophone(e){return await this._streamManagerController.startMicrophoneCapture(e)}stopMicrophone(e){this._streamManagerController.stopCapture({streamId:e,type:S.Microphone})}async startVideoFileCapture(e){return e?await this._streamManagerController.startVideoFileCapture(e):void 0}stopVideoFileCapture(e){this._streamManagerController.stopCapture({streamId:e,type:S.VideoFile})}async startScreenCapture(e=!1){return await this._streamManagerController.startScreenCapture(e)}stopScreenCapture(e){this._streamManagerController.stopCapture({streamId:e,type:S.Screen})}async startAudioFileCapture(e){return e?await this._streamManagerController.startAudioFileCapture(e):void 0}stopAudioFileCapture(e){this._streamManagerController.stopCapture({streamId:e,type:S.AudioFile})}async startImageCapture(e){return e?await this._streamManagerController.startImageCapture(e):void 0}stopImageCapture(e){this._streamManagerController.stopCapture({streamId:e,type:S.Image})}startCustomVideoCapture(e){return e?this._streamManagerController.startCustomVideoCapture(e):void 0}stopCustomVideoCapture(e){this._streamManagerController.stopCapture({streamId:e,type:S.CustomVideo})}startCustomAudioCapture(e){return e?this._streamManagerController.startCustomAudioCapture(e):void 0}stopCustomAudioCapture(e){this._streamManagerController.stopCapture({streamId:e,type:S.CustomAudio})}async startVolumeDetect(e){var t;e?await this._streamManagerController.startVolumeDetect(e):await((t=this._streamComposeController.getComposedStream().audioStream)==null?void 0:t.startVolumeDetect())}stopVolumeDetect(e){var t;e?this._streamManagerController.stopVolumeDetect(e):(t=this._streamComposeController.getComposedStream().audioStream)==null||t.stopVolumeDetect()}getVolume(e){var t;return e?this._streamManagerController.getVolume(e):((t=this._streamComposeController.getComposedStream().audioStream)==null?void 0:t.volume)??0}enableMixing(e){if(this.isPushing())throw new Error("can not change mixing while pushing");this._streamComposeController.enableMixing(e)}setMixingConfig(e){this._streamComposeController.setMixingConfig(e)}setRenderView(e){return this._streamConsumeController.setRenderView(e)}startPreview(){return this._streamConsumeController.startPreview()}stopPreview(){return this._streamConsumeController.stopPreview()}async startPush(e){return this._streamConsumeController.startPush(e)}addVideoStream(e){F(e)?e.forEach(t=>{this._streamComposeController.addVideoStream(t)}):this._streamComposeController.addVideoStream(e)}removeVideoStream(e){this._streamComposeController.removeVideoStream(e)}updateVideoStream(e){F(e)?this._streamComposeController.updateVideoStream(e):this._streamComposeController.updateVideoStream([e])}muteVideoStream(e){this._streamComposeController.muteVideoStream(e)}unmuteVideoStream(e){this._streamComposeController.unmuteVideoStream(e)}addAudioStream(e){F(e)?e.map(t=>this._streamComposeController.addAudioStream(t)):this._streamComposeController.addAudioStream(e)}removeAudioStream(e){this._streamComposeController.removeAudioStream(e)}updateAudioStream(e){F(e)?this._streamComposeController.updateAudioStream(e):this._streamComposeController.updateAudioStream([e])}muteAudioStream(e){this._streamComposeController.muteAudioStream(e)}unmuteAudioStream(e){this._streamComposeController.unmuteAudioStream(e)}setProperty(e,t){switch(e){case"setVideoResolution":this._streamManagerController.setVideoResolution(t);break;case"setVideoFps":this._streamManagerController.setVideoFps(t);break;case"setAudioSampleRate":this._streamManagerController.setAudioSampleRate(t);break;case"setPushMode":this._streamConsumeController.setPushMode(t);break;case"setVideoBitrate":this._streamConsumeController.setBitrate(t,"video");break;case"setAudioBitrate":this._streamConsumeController.setBitrate(t,"audio");break;case"setVolumeDetectScriptUrl":$e.instance.volumeDetectScriptUrl=t;break;case"setMixerWorkerScriptUrl":this._streamComposeController.setMixerWorkerScript(t);break}}setVideoQuality(e){if(this._streamConsumeController.pushMode==="webTransport"&&["120p","180p","240p"].indexOf(e)!==-1)throw new Error("quality not allowed lower than 360p on rtmp mode");const{width:t,height:i,frameRate:s,bitrate:n}=ve(e,"video");this._streamManagerController.setVideoResolution({width:t,height:i}),this._streamManagerController.setVideoFps(s),this._streamComposeController.setVideoQuality({width:t,height:i,frameRate:s}),this._streamConsumeController.setBitrate(n,"video")}setAudioQuality(e){const{sampleRate:t,bitrate:i}=ve(e,"audio");this._streamManagerController.setAudioSampleRate(t),this._streamConsumeController.setBitrate(i,"audio")}getMediaStream(e){return this._streamManagerController.getStreamById(e).mediaStream}stopPush(){return this._streamConsumeController.stopPush()}isPushing(){return this._streamConsumeController.isPushing()}getStats(){return this._streamConsumeController.getStats()}getPreviewElement(){return this._streamConsumeController.getPreviewElement()}_bindEvent(){this._streamManagerController.on(z.Error,e=>{this.observer.onError(e.code,e.message,e.ext)}),this._streamManagerController.on(z.Interrupted,e=>{this.observer.onCaptureInterrupted(e.id)}),this._streamConsumeController.on(A.PushStart,()=>{this.observer.onPushStart()}),this._streamConsumeController.on(A.PushStop,()=>{this.observer.onPushStop()}),this._streamConsumeController.on(A.RTCConnectStateChanged,e=>{this.observer.onPushStatusUpdate(sr[e],e)}),this._streamConsumeController.on(A.PushError,e=>{this.observer.onError(e.code,e.message,e.ext)}),this._streamManagerController.on(z.DeviceStopCapture,e=>{this.observer.onStopCapture(e.id)}),this._streamConsumeController.on(A.CaptureFirstAudioFrame,()=>{this.observer.onCaptureFirstAudioFrame()}),this._streamConsumeController.on(A.CaptureFirstVideoFrame,()=>{this.observer.onCaptureFirstVideoFrame()}),io(e=>{e.deviceInfo.kind==="videoinput"?this.observer.onCameraChanged(e.deviceInfo):e.deviceInfo.kind==="audioinput"&&this.observer.onMicrophoneChanged(e.deviceInfo)})}async destroy(){await this._streamConsumeController.destroy(),this._streamManagerController.destroy()}get observer(){return this._observer}get isEnableMixing(){return this._streamComposeController.isEnableMixing}get pushMode(){return this._streamConsumeController.pushMode}}return ch});
113
+ `);i.RTCSessionDescription&&n instanceof i.RTCSessionDescription?arguments[0]=new i.RTCSessionDescription({type:n.type,sdp:s}):n.sdp=s}return t.apply(this,arguments)}}function _r(i,e){if(!(i.RTCPeerConnection&&i.RTCPeerConnection.prototype))return;const t=i.RTCPeerConnection.prototype.addIceCandidate;!t||t.length===0||(i.RTCPeerConnection.prototype.addIceCandidate=function(){return arguments[0]?(e.browser==="chrome"&&e.version<78||e.browser==="firefox"&&e.version<68||e.browser==="safari")&&arguments[0]&&arguments[0].candidate===""?Promise.resolve():t.apply(this,arguments):(arguments[1]&&arguments[1].apply(null),Promise.resolve())})}function gr(i,e){if(!(i.RTCPeerConnection&&i.RTCPeerConnection.prototype))return;const t=i.RTCPeerConnection.prototype.setLocalDescription;!t||t.length===0||(i.RTCPeerConnection.prototype.setLocalDescription=function(){let n=arguments[0]||{};if(typeof n!="object"||n.type&&n.sdp)return t.apply(this,arguments);if(n={type:n.type,sdp:n.sdp},!n.type)switch(this.signalingState){case"stable":case"have-local-offer":case"have-remote-pranswer":n.type="offer";break;default:n.type="answer";break}return n.sdp||n.type!=="offer"&&n.type!=="answer"?t.apply(this,[n]):(n.type==="offer"?this.createOffer:this.createAnswer).apply(this).then(a=>t.apply(this,[a]))})}const Lv=Object.freeze(Object.defineProperty({__proto__:null,removeExtmapAllowMixed:ns,shimAddIceCandidateNullOrEmpty:_r,shimConnectionState:rs,shimMaxMessageSize:fr,shimParameterlessSetLocalDescription:gr,shimRTCIceCandidate:pr,shimRTCIceCandidateRelayProtocol:is,shimSendThrowTypeError:mr},Symbol.toStringTag,{value:"Module"}));function Uv({window:i}={},e={shimChrome:!0,shimFirefox:!0,shimSafari:!0}){const t=yc,r=Iv(i),n={browserDetails:r,commonShim:Lv,extractVersion:lr,disableLog:Dv,disableWarnings:xv,sdp:Pv};switch(r.browser){case"chrome":if(!Ic||!Yn||!e.shimChrome)return t("Chrome shim is not included in this adapter release."),n;if(r.version===null)return t("Chrome shim can not determine version, not shimming."),n;t("adapter.js shimming chrome."),n.browserShim=Ic,_r(i,r),gr(i),Cc(i,r),kc(i),Yn(i,r),Tc(i),Dc(i,r),zc(i),Ac(i),xc(i,r),pr(i),is(i),rs(i),fr(i,r),mr(i),ns(i,r);break;case"firefox":if(!jc||!es||!e.shimFirefox)return t("Firefox shim is not included in this adapter release."),n;t("adapter.js shimming firefox."),n.browserShim=jc,_r(i,r),gr(i),Oc(i,r),es(i,r),Mc(i),Uc(i),Pc(i),Lc(i),Gc(i),Nc(i),Bc(i),Vc(i),Fc(i),pr(i),rs(i),fr(i,r),mr(i);break;case"safari":if(!Yc||!e.shimSafari)return t("Safari shim is not included in this adapter release."),n;t("adapter.js shimming safari."),n.browserShim=Yc,_r(i,r),gr(i),Jc(i),Zc(i),qc(i),Hc(i),$c(i),Xc(i),Kc(i),Qc(i),pr(i),is(i),fr(i,r),mr(i),ns(i,r);break;default:t("Unsupported browser!");break}return n}Uv({window:typeof window>"u"?void 0:window});function Gv(){const i={hardware_concurrency:navigator.hardwareConcurrency};navigator.deviceMemory&&(i.device_memory=navigator.deviceMemory+"GB");try{const e=document.createElement("canvas"),t=e.getContext("webgl")||e.getContext("experimental-webgl");if(t){const r=t.getExtension("WEBGL_debug_renderer_info");r&&(i.gpu_vendor=t.getParameter(r.UNMASKED_VENDOR_WEBGL),i.gpu_renderer=t.getParameter(r.UNMASKED_RENDERER_WEBGL)),i.webgl_version=t.getParameter(t.VERSION),i.webgl_shading_language_version=t.getParameter(t.SHADING_LANGUAGE_VERSION),i.webgl_vendor=t.getParameter(t.VENDOR),i.webgl_renderer=t.getParameter(t.RENDERER)}}catch{}return i}class Nv extends Je{static async isSupported(e){if(e==="mediaEngine")return fc.isSupported();if(e==="webTransport")return Promise.resolve(Za.isSupported());if(e==="rtm")return ar.isSupported()}constructor(e){var t,r,n,s,a,o,d,c,u,l;if(super(),this._options=e??{},this._streamManagerController=new N_(this),this._streamComposeController=new J_(this._streamManagerController),this._streamConsumeController=new zv(this._streamComposeController,e),this._streamConsumeController.setPushConfig(e),this._observer=Rv,this._bindEvent(),!(e!=null&&e.loggerConfig)||(t=e==null?void 0:e.loggerConfig)!=null&&t.enable){P_({showLogInConsole:((r=e==null?void 0:e.loggerConfig)==null?void 0:r.showInConsole)??!1});const h=I_((n=e==null?void 0:e.loggerConfig)==null?void 0:n.userId),p=O_((s=e==null?void 0:e.loggerConfig)==null?void 0:s.deviceId);ht.instance.userId=h,ht.instance.deviceId=p,L_({user_unique_id:h,device_id:p,account_id:((a=e==null?void 0:e.loggerConfig)==null?void 0:a.accountId)??0,customer_app_name:((o=e==null?void 0:e.loggerConfig)==null?void 0:o.appName)??"unknown",customer_app_id:((d=e==null?void 0:e.loggerConfig)==null?void 0:d.appId)??0},{user_id:h,device_id:p,account_id:((c=e==null?void 0:e.loggerConfig)==null?void 0:c.accountId)??0,customer_app_name:((u=e==null?void 0:e.loggerConfig)==null?void 0:u.appName)??"unknown",customer_app_id:((l=e==null?void 0:e.loggerConfig)==null?void 0:l.appId)??0}),O(I.PUSHER_INIT,{options:e,...Gv()}),U_()}}async getDevicesList(e){return this._streamManagerController.getDevicesList(e)}async getCameras(){return this._streamManagerController.getCameras()}async getMicrophones(){return this._streamManagerController.getMicrophones()}async startCamera(e){return this._streamManagerController.startCameraCapture(e)}stopCamera(e){this._streamManagerController.stopCapture({streamId:e,type:V.Camera})}async startMicrophone(e){return await this._streamManagerController.startMicrophoneCapture(e)}stopMicrophone(e){this._streamManagerController.stopCapture({streamId:e,type:V.Microphone})}async startVideoFileCapture(e){return e?await this._streamManagerController.startVideoFileCapture(e):void 0}stopVideoFileCapture(e){this._streamManagerController.stopCapture({streamId:e,type:V.VideoFile})}async startScreenCapture(e=!1){return await this._streamManagerController.startScreenCapture(e)}stopScreenCapture(e){this._streamManagerController.stopCapture({streamId:e,type:V.Screen})}async startAudioFileCapture(e){return e?await this._streamManagerController.startAudioFileCapture(e):void 0}stopAudioFileCapture(e){this._streamManagerController.stopCapture({streamId:e,type:V.AudioFile})}async startImageCapture(e){return e?await this._streamManagerController.startImageCapture(e):void 0}stopImageCapture(e){this._streamManagerController.stopCapture({streamId:e,type:V.Image})}startCustomVideoCapture(e){return e?this._streamManagerController.startCustomVideoCapture(e):void 0}stopCustomVideoCapture(e){this._streamManagerController.stopCapture({streamId:e,type:V.CustomVideo})}startCustomAudioCapture(e){return e?this._streamManagerController.startCustomAudioCapture(e):void 0}stopCustomAudioCapture(e){this._streamManagerController.stopCapture({streamId:e,type:V.CustomAudio})}async startVolumeDetect(e){var t;e?await this._streamManagerController.startVolumeDetect(e):await((t=this._streamComposeController.getComposedStream().audioStream)==null?void 0:t.startVolumeDetect())}stopVolumeDetect(e){var t;e?this._streamManagerController.stopVolumeDetect(e):(t=this._streamComposeController.getComposedStream().audioStream)==null||t.stopVolumeDetect()}getVolume(e){var t;return e?this._streamManagerController.getVolume(e):((t=this._streamComposeController.getComposedStream().audioStream)==null?void 0:t.volume)??0}enableMixing(e){if(O(I.SWITCH_ENABLE_MIXING,{enable:e,is_pushing:this.isPushing()}),this.isPushing())throw new Error("can not change mixing while pushing");this._streamComposeController.enableMixing(e)}setMixingConfig(e){O(I.SET_MIXING_CONFIG,e),this._streamComposeController.setMixingConfig(e)}getMixingConfig(){return this._streamComposeController.getMixingConfig()}setRenderView(e){return this._streamConsumeController.setRenderView(e)}startPreview(){return this._streamConsumeController.startPreview()}stopPreview(){return this._streamConsumeController.stopPreview()}async startPush(e){try{await this._streamComposeController.resumeMixer()}catch(t){if(O(I.PUSH_AUDIO_CONTEXT_START_FAILED,{error:t}),this._options.checkAudio)throw new At(me.AUDIO_RESUME_FAILED,(t==null?void 0:t.message)??"audio resume failed");console.warn("audioContext cannot resume automatically")}return this._streamConsumeController.startPush(e)}addVideoStream(e){O(I.ADD_VIDEO_STREAM,{number:ee(e)?e.length:1,config:e}),ee(e)?e.forEach(t=>{this._streamComposeController.addVideoStream(t)}):this._streamComposeController.addVideoStream(e)}removeVideoStream(e){O(I.DELETE_VIDEO_STREAM,{stream_id:e}),this._streamComposeController.removeVideoStream(e)}updateVideoStream(e){O(I.UPDATE_VIDEO_STREAM,{number:ee(e)?e.length:1,config:e}),ee(e)?this._streamComposeController.updateVideoStream(e):this._streamComposeController.updateVideoStream([e])}muteVideoStream(e){O(I.CHANGE_VIDEO_STREAM_MUTE,{stream_id:e,mute:!1}),this._streamComposeController.muteVideoStream(e)}unmuteVideoStream(e){O(I.CHANGE_VIDEO_STREAM_MUTE,{stream_id:e,mute:!0}),this._streamComposeController.unmuteVideoStream(e)}addAudioStream(e){O(I.ADD_AUDIO_STREAM,{number:ee(e)?e.length:1,config:e}),ee(e)?e.map(t=>this._streamComposeController.addAudioStream(t)):this._streamComposeController.addAudioStream(e)}removeAudioStream(e){O(I.DELETE_AUDIO_STREAM,{stream_id:e}),this._streamComposeController.removeAudioStream(e)}updateAudioStream(e){O(I.UPDATE_AUDIO_STREAM,{number:ee(e)?e.length:1,config:e}),ee(e)?this._streamComposeController.updateAudioStream(e):this._streamComposeController.updateAudioStream([e])}muteAudioStream(e){O(I.CHANGE_AUDIO_STREAM_MUTE,{stream_id:e,mute:!0}),this._streamComposeController.muteAudioStream(e)}unmuteAudioStream(e){O(I.CHANGE_AUDIO_STREAM_MUTE,{stream_id:e,mute:!1}),this._streamComposeController.unmuteAudioStream(e)}setProperty(e,t){switch(O(I.SET_PROPERTY_CALL,{key:e,value:t}),e){case"setVideoResolution":this._streamManagerController.setVideoResolution(t);break;case"setVideoFps":this._streamManagerController.setVideoFps(t);break;case"setAudioSampleRate":this._streamManagerController.setAudioSampleRate(t);break;case"setPushMode":this._streamConsumeController.setPushMode(t);break;case"setVideoBitrate":this._streamConsumeController.setBitrate(t,"video");break;case"setAudioBitrate":this._streamConsumeController.setBitrate(t,"audio");break;case"setVolumeDetectScriptUrl":ht.instance.volumeDetectScriptUrl=t;break;case"setMixerWorkerScriptUrl":this._streamComposeController.setMixerWorkerScript(t);break;case"updatePushUrl":this._streamConsumeController.updatePushUrl(t);break;case"setVideoKBitrate":this._streamConsumeController.setBitrate(Number(t)*1e3,"video");break;case"setAudioKBitrate":this._streamConsumeController.setBitrate(Number(t)*1e3,"audio");break}}setVideoQuality(e){if(O(I.SET_VIDEO_QUALITY,{quality:e}),this._streamConsumeController.pushMode==="webTransport"&&["120p","180p","240p"].indexOf(e)!==-1)throw new Error("quality not allowed lower than 360p on rtmp mode");const{width:t,height:r,frameRate:n,bitrate:s}=Rt(e,"video");this._streamManagerController.setVideoResolution({width:t,height:r}),this._streamManagerController.setVideoFps(n),this._streamComposeController.setVideoQuality({width:t,height:r,frameRate:n}),this._streamConsumeController.setBitrate(s,"video")}setAudioQuality(e){O(I.SET_AUDIO_QUALITY,{quality:e});const{sampleRate:t,bitrate:r}=Rt(e,"audio");this._streamManagerController.setAudioSampleRate(t),this._streamConsumeController.setBitrate(r,"audio")}getMediaStream(e){return this._streamManagerController.getStreamById(e).mediaStream}getStream(e){return this._streamManagerController.getStreamById(e)}stopPush(){return this._streamConsumeController.stopPush()}isPushing(){return this._streamConsumeController.isPushing()}getStats(){return this._streamConsumeController.getStats()}getPreviewElement(){return this._streamConsumeController.getPreviewElement()}getVideoStreamRenderConfig(e){return this._streamComposeController.getVideoStreamRenderConfig(e)}_bindEvent(){this._streamManagerController.on(Ae.Error,e=>{this.observer.onError(e.code,e.message,e.ext)}),this._streamManagerController.on(Ae.Interrupted,e=>{this.observer.onCaptureInterrupted(e.id)}),this._streamConsumeController.on(Z.PushStart,()=>{this.observer.onPushStart()}),this._streamConsumeController.on(Z.PushStop,()=>{this.observer.onPushStop()}),this._streamConsumeController.on(Z.RTCConnectStateChanged,e=>{console.log("RTCConnectStateChanged",e),this.observer.onPushStatusUpdate(fs[e],e)}),this._streamConsumeController.on(Z.PushError,e=>{this.observer.onError(e.code,e.message,e.ext)}),this._streamManagerController.on(Ae.DeviceStopCapture,e=>{this.observer.onStopCapture(e.id)}),this._streamConsumeController.on(Z.CaptureFirstAudioFrame,()=>{this.observer.onCaptureFirstAudioFrame()}),this._streamConsumeController.on(Z.CaptureFirstVideoFrame,()=>{this.observer.onCaptureFirstVideoFrame()}),this._streamConsumeController.on(Z.ReconnectStateChange,(e,t)=>{this.observer.onReconnectStateChange(e,t)}),this._streamConsumeController.on(Z.LiveConnectStateChange,e=>{this.observer.onLiveConnectStateChange(e)}),yd(e=>{e.deviceInfo.kind==="videoinput"?this.observer.onCameraChanged(e.deviceInfo):e.deviceInfo.kind==="audioinput"&&this.observer.onMicrophoneChanged(e.deviceInfo)})}async destroy(){await this._streamConsumeController.destroy(),this._streamManagerController.destroy(),G_()}get observer(){return this._observer}get isEnableMixing(){return this._streamComposeController.isEnableMixing}get pushMode(){return this._streamConsumeController.pushMode}}return Nv});