@volcengine/vepusher 2.0.4-rc.6 → 2.0.4-rc.7

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(ye,ne){typeof exports=="object"&&typeof module<"u"?module.exports=ne():typeof define=="function"&&define.amd?define(ne):(ye=typeof globalThis<"u"?globalThis:ye||self,ye.vePusher=ne())})(this,function(){"use strict";var q_=Object.defineProperty;var K_=(ye,ne,Be)=>ne in ye?q_(ye,ne,{enumerable:!0,configurable:!0,writable:!0,value:Be}):ye[ne]=Be;var b=(ye,ne,Be)=>K_(ye,typeof ne!="symbol"?ne+"":ne,Be);var uc,dc,hc,lc,pc,fc;function ye(r,e){for(var t=0;t<e.length;t++){const i=e[t];if(typeof i!="string"&&!Array.isArray(i)){for(const n in i)if(n!=="default"&&!(n in r)){const s=Object.getOwnPropertyDescriptor(i,n);s&&Object.defineProperty(r,n,s.get?s:{enumerable:!0,get:()=>i[n]})}}}return Object.freeze(Object.defineProperty(r,Symbol.toStringTag,{value:"Module"}))}function ne(r){return r&&r.__esModule&&Object.prototype.hasOwnProperty.call(r,"default")?r.default:r}var Be={exports:{}},In;function Cc(){return In||(In=1,function(r){var e=Object.prototype.hasOwnProperty,t="~";function i(){}Object.create&&(i.prototype=Object.create(null),new i().__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 i:delete d._events[c]}function o(){this._events=new i,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],E=arguments.length,y,_;if(m.fn){switch(m.once&&this.removeListener(c,m.fn,void 0,!0),E){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(E-1);_<E;_++)y[_-1]=arguments[_];m.fn.apply(m.context,y)}else{var C=m.length,z;for(_=0;_<C;_++)switch(m[_].once&&this.removeListener(c,m[_].fn,void 0,!0),E){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(E-1);z<E;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=[],E=f.length;v<E;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 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}(Be)),Be.exports}var wc=Cc();const Ve=ne(wc);var On=(r=>(r.LeftToRight="LeftToRight",r.UpToDown="UpToDown",r.All="All",r.None="None",r))(On||{}),N=(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))(N||{}),Ee=(r=>(r.DeviceCaptured="deviceCaptured",r.DeviceStopCapture="deviceStopCapture",r.Error="error",r.Interrupted="interrupted",r))(Ee||{}),W=(r=>(r.PushStart="pushStart",r.PushStop="pushStop",r.PushError="pushError",r.RTCConnectStateChanged="rtcConnectStateChanged",r.CaptureFirstVideoFrame="capturefirstvideoframe",r.CaptureFirstAudioFrame="capturefirstaudioframe",r.NotAllowedAutoPlay="notallowedautoplay",r.ReconnectStateChange="reconnectStateChange",r.LiveConnectStateChange="liveConnectStateChange",r))(W||{}),Mn=(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))(Mn||{}),Ln=(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))(Ln||{}),Un=(r=>(r.STANDARD="48000x40",r.HIGH="48000x128",r))(Un||{}),rt=(r=>(r.VideoStreamChange="videoStreamChange",r.AudioStreamChange="audioStreamChange",r))(rt||{}),Nn=(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))(Nn||{});const Gn={SizeChange:"sizeChange"};var si=(r=>(r.Portrait="portrait",r.Landscape="landscape",r))(si||{});const Bn="720p-1",Vn="STANDARD";var pe=(r=>(r[r.DISCONNECTED=0]="DISCONNECTED",r[r.CONNECTING=1]="CONNECTING",r[r.CONNECTED=2]="CONNECTED",r[r.RECONNECTING=3]="RECONNECTING",r))(pe||{}),ft=(r=>(r[r.START=1]="START",r[r.WAITING=2]="WAITING",r[r.RECONNECTING=3]="RECONNECTING",r[r.SUCCESS=4]="SUCCESS",r[r.FAILED=5]="FAILED",r))(ft||{}),oi=(r=>(r[r.PushUrlInvalid=1001]="PushUrlInvalid",r[r.ReconnectTimeout=1002]="ReconnectTimeout",r))(oi||{}),M=(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))(M||{}),B=(r=>(r.AUDIO="audio",r.VIDEO="video",r))(B||{}),se=(r=>(r.ENDED="ended",r.MUTE="mute",r.UNMUTE="unmute",r.PLAY_FAILED="play-failed",r.SIZE_CHANGE="size-change",r))(se||{});const re=[];for(let r=0;r<256;++r)re.push((r+256).toString(16).slice(1));function Tc(r,e=0){return(re[r[e+0]]+re[r[e+1]]+re[r[e+2]]+re[r[e+3]]+"-"+re[r[e+4]]+re[r[e+5]]+"-"+re[r[e+6]]+re[r[e+7]]+"-"+re[r[e+8]]+re[r[e+9]]+"-"+re[r[e+10]]+re[r[e+11]]+re[r[e+12]]+re[r[e+13]]+re[r[e+14]]+re[r[e+15]]).toLowerCase()}let ai;const zc=new Uint8Array(16);function kc(){if(!ai){if(typeof crypto>"u"||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");ai=crypto.getRandomValues.bind(crypto)}return ai(zc)}const Fn={randomUUID:typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};function it(r,e,t){var n;if(Fn.randomUUID&&!r)return Fn.randomUUID();r=r||{};const i=r.random??((n=r.rng)==null?void 0:n.call(r))??kc();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,Tc(i)}class jn{constructor(){b(this,"id",it());b(this,"_nextNode");b(this,"_track");b(this,"_destNode")}gain(e){if(this._nextNode instanceof Hn)return this._nextNode.g=e,this._nextNode;const t=new Hn(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 Hn extends jn{constructor(t,i){super();b(this,"previousNode");b(this,"_node");b(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 Rc extends jn{constructor(t){super();b(this,"previousNode",null);b(this,"source");this.source=t}available(){return this.source.available()}destroy(){super.destroy()}}class Ac extends Rc{constructor(){super(...arguments);b(this,"_node")}createNode(t){if(this._node)return this._node;let i;if(this.source instanceof Qn){const n=this.source.element();i=new MediaElementAudioSourceNode(t,{mediaElement:n}),n.muted=!1}else{const n=this.source.track();i=new MediaStreamAudioSourceNode(t,{mediaStream:new MediaStream([n])})}return i}}class O extends Error{constructor(t,i,n){super(i);b(this,"code");b(this,"message");b(this,"error");this.code=t,this.message=i,this.error=n,Object.setPrototypeOf(this,O.prototype)}toString(){return`VeCapture Error: ${this.code} ${this.message}`}}const $n={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"}},qn="__debug__",Dc="[VE-CAPTURE]";function xc(){if(typeof location>"u"||typeof localStorage>"u")return!1;let r=!1;return location.href.includes(qn)&&(r=!0),localStorage.getItem(qn)&&(r=!0),r}let ce=class{constructor(e){b(this,"moduleName");this.moduleName=e}print(e,t,...i){const n=Pc();xc()&&console.log(`${n}-${Dc}%c[${$n[e].text}]%c[${this.moduleName}][${t}]`,`background-color:${$n[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(...s){i.info(`${t}-invoke`,...s);try{const a=e(...s);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 Pc(){const r=new Date;return`${r.toTimeString().split(" ")[0]}:${r.getMilliseconds().toString().padStart(3,"0")}`}function ci(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,n])=>{i==="muted"&&(t instanceof HTMLVideoElement||t instanceof HTMLAudioElement)?t.muted=!0:t.setAttribute(i,n)}),t}function Kn({width:r,height:e}){const t=document.createElement("canvas"),i=t.getContext("2d");if(!i)throw new O(M.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 ui{constructor(e){b(this,"target");b(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(n=>n!==t),this._eventDict.set(e,i),this.target.removeEventListener(e,t))}once(e,t){const i=n=>{t(n),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 J=()=>typeof window>"u";function $(){return navigator.userAgent.toLowerCase()}function di(r=$()){let e="none";return J()||(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 Wn=di()==="firefox",yr=di()==="safari";di(),!J()&&/crios/i.test($()),!J()&&/edg\//i.test($()),!J()&&/edgA/i.test($()),!J()&&/edgios/i.test($()),!J()&&/dingtalk/i.test($()),!J()&&/opr\//.test($()),!J()&&/(iphone|ipod)/i.exec($()),!J()&&(/(ipad)/i.exec($())||/macintosh/i.test($())&&"ontouchend"in document),!J()&&/macintosh/i.test($()),!J()&&/micromessenger/i.test($()),!J()&&$().includes("mobile"),!J()&&/sm-\w+/i.test($());const Ic=!J()&&!!/(iphone|ipad|ipod)/i.exec($());!J()&&/android/i.test($()),!J()&&/windows/i.test($()),!J()&&/openharmony/i.test($());let Jn="0";const Oc=!J()&&((uc=$().match(/version\/(\d+)/i))==null?void 0:uc[1]);yr&&Oc&&(Jn=(dc=navigator.userAgent.match(/version\/(\d+\.\d+)/i))==null?void 0:dc[1]),!J()&&((hc=$().match(/firefox\/(\d+)/i))==null||hc[1]);const hi=Jn;!J()&&((pc=(lc=$().match(/ ([\d_]+) like mac os x/i))==null?void 0:lc[1])==null||pc.split("_").map(r=>parseInt(r))),!J()&&((fc=$().match(/chrome\/(\d+)/i))==null||fc[1]);function Mc(){var r;return!!((r=navigator==null?void 0:navigator.permissions)!=null&&r.query)}function li(){return!!(navigator!=null&&navigator.mediaDevices)}function Lc(){var r;return li()&&!!((r=navigator==null?void 0:navigator.mediaDevices)!=null&&r.getUserMedia)}function Uc(){return!!Promise.withResolvers}function Nc(){return!(yr&&hi==="16.1")}function Gc(){return!(yr&&hi&&["16.1","16.2","16.3"].includes(hi))}function Bc(){return!Wn}function Vc(){return typeof CanvasCaptureMediaStreamTrack<"u"}function Fc(r){return typeof r.requestFrame=="function"}function jc(){return!!li()&&typeof navigator.mediaDevices.ondevicechange<"u"&&typeof navigator.mediaDevices.addEventListener=="function"}const Ae={permissionQuery:Mc,mediaDevices:li,settingResolutionInGetDisplayMedia:Nc,promiseWithResolvers:Uc,getUserMedia:Lc,isolateEnumerateDevices:Bc,supportIdealParamsInGetDisplayMedia:Gc,canvasCaptureMediaStreamTrack:Vc,requestFrameOnMediaStream:Fc,ondevicechange:jc};function Hc(){if(Ae.promiseWithResolvers())return Promise.withResolvers();let r,e;const t=new Promise((i,n)=>{r=i,e=n});if(!r||!e)throw Error("resolver and rejector working unexpected");return{promise:t,resolve:r,reject:e}}function Zn(r={}){const{timeout:e,message:t}={timeout:0,message:new O(M.UNEXPECTED_ERROR,"unexpected timeout"),...r},{promise:i,resolve:n,reject:s}=Hc();if(e<=0)return{promise:i,resolve:n,reject:s};const a=setTimeout(()=>{s(t)},e);return{promise:i,resolve:d=>{clearTimeout(a),n(d)},reject:s}}const $c={playsinline:"","webkit-playsinline":"","x5-playsinline":"","x5-video-player-type":"h5","x-webkit-airplay":"allow",preload:"metadata",muted:"",crossOrigin:"anonymous"},qc={playsinline:"","webkit-playsinline":"",preload:"metadata",muted:"",crossOrigin:"anonymous"};class Ot{constructor(e,t=[]){b(this,"id",it());b(this,"_referenceTracks",[]);b(this,"_element");b(this,"_volumeMode",0);b(this,"_readyLock");b(this,"_releaseReadyLock");b(this,"_throwReadyLock");b(this,"_stream");let i;if(e instanceof MediaStreamTrack){const o=new MediaStream([e]);i=Kc(o),this._stream=o}else if(e.url)i=Wc(e);else throw new O(M.UNEXPECTED_TYPE,`got ${typeof e}, expected: MediaStreamTrack or constraints for creating element`);const{promise:n,resolve:s,reject:a}=Zn({timeout:2e3,message:new O(M.PLAY_FAILED,"load media timeout")});this._readyLock=n,this._releaseReadyLock=s,this._throwReadyLock=a,this._element=new ui(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===B.AUDIO){this._upgradeVolumeMode(1e-4);const i=t.getAudioTracks();if(i.length<1)throw new O(M.UNEXPECTED_TYPE,"got empty list of audio tracks");return i[0]}if(e===B.VIDEO){const i=t.getVideoTracks();if(i.length<1)throw new O(M.UNEXPECTED_TYPE,"got empty list of video tracks");return i[0]}throw new O(M.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 O(M.PLAY_FAILED,"play element failed",e)}}_bindPlayerEvent(e){e.on("loadedmetadata",()=>{this._releaseReadyLock()}),e.on("error",()=>{this._throwReadyLock(new O(M.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 Kc(r){let e="audio";r.getVideoTracks().length>0&&(e="video");const t=Xn(e==="video"?B.VIDEO:B.AUDIO);return t.srcObject=r,t}function Wc(r){const{url:e,kind:t,loop:i}=r,n=Xn(t);return n.src=e,n.loop=i,n}function Xn(r){if(r===B.VIDEO)return ci(B.VIDEO,{style:{width:"100%",height:"100%"},attributes:$c});if(r===B.AUDIO)return ci(B.AUDIO,{style:{display:"none"},attributes:qc});throw new O(M.UNEXPECTED_TYPE,`got ${r}, expected: audio, video`)}class pi extends Ve{emit(e,...t){const i=this.listenerCount(e);return Promise.resolve().then(()=>{super.emit(e,...t)}),!!i}on(e,t,i){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,i)}once(e,t,i){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,i)}}function fi(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 O(M.UNEXPECTED_TYPE,"unexpected constraints type")}const br=1e3;class Yn{constructor(e){b(this,"id",it());b(this,"_context");b(this,"_canvas");b(this,"_image");b(this,"_config");b(this,"_readyLock");b(this,"_releaseReadyLock");b(this,"_throwReadyLock");b(this,"_loopTimer");b(this,"_referenceTracks",[]);b(this,"_stream");const t=fi(e.width),i=fi(e.height),n=fi(e.frameRate);this._config={width:t,height:i,frameRate:n};const{context:s,canvas:a}=Kn({width:t,height:i});this._context=s,this._canvas=a;const o=Jc({url:e.url,width:t,height:i});this._image=new ui(o);const{promise:d,resolve:c,reject:u}=Zn({timeout:2e3,message:new O(M.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 i=t.getVideoTracks();if(i.length<1)throw new O(M.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 O(M.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),br/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 Jc({url:r,height:e,width:t}){const i=ci("img",{style:{width:`${t}px`,height:`${e}px`},attributes:{crossOrigin:"anonymous"}});return i.src=r,i}class mi extends pi{constructor(t){super();b(this,"id",it());b(this,"_track");b(this,"_element");t instanceof MediaStreamTrack?(this._track=new ui(t),this._bindTrackEvent(this._track)):t instanceof Ot?(this._element=t,t.addReferenceTrack(this)):t instanceof Yn&&(this._element=t)}_bindTrackEvent(t){t.on("ended",this._handleTrackEnded.bind(this)),t.on("mute",()=>{this.emit(se.MUTE)}),t.on("unmute",()=>{this.emit(se.UNMUTE)})}_handleTrackEnded(){this.emit(se.ENDED),this.destroy()}handlePlayFailed(){this.emit(se.PLAY_FAILED)}track(){if(this.logger.info("track"),!this.available())throw new O(M.TRACK_NOT_AVAILABLE,"track is not available when creating MediaStreamTrack");if(this._track)return this._track.target;if(!this._element)throw new O(M.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 O(M.TRACK_NOT_AVAILABLE,"track is not available when creating HTMLMediaElement");if(this._element)return this._element.element();if(!this._track)throw new O(M.UNEXPECTED_TYPE,"got this._track falsy");const t=new Ot(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,n;(t=this._track)==null||t.clearAll(),(i=this._track)==null||i.target.stop(),this._track&&delete this._track,(n=this._element)==null||n.removeReference(this),delete this._element}}class Sr extends mi{constructor(){super(...arguments);b(this,"kind",B.AUDIO);b(this,"_node")}node(){if(this.logger.info("node",this.id),!this.available())throw new O(M.TRACK_NOT_AVAILABLE,"track is not avaiable when creating node");if(this._node)return this._node;const t=new Ac(this);return this._node=t,t}element(){if(this.logger.info("element",this.id),!this.available())throw new O(M.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 O(M.UNEXPECTED_TYPE,"source should be HTMLMediaElement");return i}if(!this._track)throw new O(M.UNEXPECTED_TYPE,"got this._track falsy");const t=new Ot(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 Zc extends Sr{constructor(){super(...arguments);b(this,"logger",new ce("MicrophoneAudioTrack"))}}class Xc extends Sr{constructor(){super(...arguments);b(this,"logger",new ce("ScreenAudioTrack"))}}class Qn extends Sr{constructor(){super(...arguments);b(this,"logger",new ce("MediaAudioTrack"))}handlePlayFailed(){this.emit(se.PLAY_FAILED)}async play(){if(this._element){if(!(this._element instanceof Ot))throw new O(M.UNEXPECTED_TYPE,"element is not TrackMediaElement");return this._element._playElement()}}}class Yc extends Sr{constructor(){super(...arguments);b(this,"logger",new ce("CustomAudioTrack"))}}let Qc=1;const _i=new ce("PromiseQueue");class eu{constructor(e){b(this,"lockingPromise",Promise.resolve());b(this,"locks",0);b(this,"name","");b(this,"lockId");b(this,"closeReason");this.lockId=Qc++,e&&(this.name=e),_i.info(`lock-${this.name}-${this.lockId}`,"is created.")}get isLocked(){return this.locks>0}lock(){this.locks+=1,_i.info(`lock-${this.name}-${this.lockId}`,`locked, current queue ${this.locks}.`);let e;const t=new Promise(n=>{e=()=>{this.locks-=1,_i.info(`lock-${this.name}-${this.lockId}`,`unlocked, current queue ${this.locks}.`),n()}}),i=this.lockingPromise.then(()=>e);return this.lockingPromise=this.lockingPromise.then(()=>t),i}}const tu=300,ru=3e3,Ce=new ce("Devices");class iu extends pi{constructor(){super();b(this,"_deviceMap",{audioinput:[],audiooutput:[],videoinput:[]});b(this,"_permissions",{[B.AUDIO]:!1,[B.VIDEO]:!1});b(this,"_changedQueue",new eu("device changed queue"));this._init()}async _init(){this._initDeviceChanged(),await this._initPermissionChanged();const t=is(this._permissions);t.length>0&&this._refreshDevices(t)}_initDeviceChanged(){if(Ce.info("_initDeviceChanged","invoked"),!Ae.ondevicechange()){Ce.error("_initDeviceChanged","no supported, use timer instead"),setInterval(()=>{this._handleDeviceChanged()},ru);return}Ae.ondevicechange()&&navigator.mediaDevices.addEventListener("devicechange",()=>{Ce.info("devicechange"),setTimeout(()=>{this._handleDeviceChanged()},tu)})}async _initPermissionChanged(){if(!Ae.permissionQuery()){Ce.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",()=>{Ce.info("_initPermissionChanged","update permission for audio"),this._permissions.audio=t.state==="granted"})}catch(t){Ce.error("_initPermissionChanged",t)}try{const t=await navigator.permissions.query({name:"camera"});this._permissions.video=t.state==="granted",t.addEventListener("change",()=>{Ce.info("_initPermissionChanged","update permission for video"),this._permissions.video=t.state==="granted"})}catch(t){Ce.error("_initPermissionChanged",t)}}async _refreshDevices(t){if(!Ae.mediaDevices())throw new O(M.NOT_SUPPORTED,"mediaDevices is not supported");if(t.length===0)throw new O(M.UNEXPECTED_TYPE,"kinds expect to containt values");let i;if(!Ae.isolateEnumerateDevices()){const a={};t.forEach(o=>{a[o]=!0}),i=await navigator.mediaDevices.getUserMedia(a)}let n=await navigator.mediaDevices.enumerateDevices();i&&es(i),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 i=!1;if(t.forEach(n=>{i=i||!this._permissions[n]}),!i)return{grant:!0};if(!Ae.getUserMedia())return{grant:!1,reason:new O(M.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[B.AUDIO]=!0),n.video&&(this._permissions[B.VIDEO]=!0),es(s),{grant:!0}):{grant:!1,reason:new O(M.UNEXPECTED_TYPE,"get stream falsy")}}catch(n){return{grant:!1,reason:new O(M.CAPTURE_FAILED,"acquire user permission failed",n)}}}async _handleDeviceChanged(){Ce.info("_handleDeviceChanged",this._deviceMap,this._permissions);const t=await this._changedQueue.lock();try{const i=rs(this._deviceMap);let n=[];const s=is(this._permissions);s.length===0?Ce.warn("_handleDeviceChanged","no permission, use empty list"):(await this._refreshDevices(s),n=rs(this._deviceMap)),n.forEach(a=>{i.findIndex(d=>ts(d,a))!==-1||this.emit("onDeviceStateChanged",{deviceInfo:a,deviceState:"active"})}),i.forEach(a=>{n.findIndex(d=>ts(d,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(B.AUDIO);else if(o==="videoinput")i.push(B.VIDEO);else throw new O(M.UNEXPECTED_TYPE,"kind in kinds should be enum MediaDeviceKind")});const{grant:n,reason:s}=await this._acquireUserPermission(i);if(!n)throw s;await this._refreshDevices(i);const a=[];return t.forEach(o=>{a.push(...this._deviceMap[o])}),a}async enableDevices(t){return this._acquireUserPermission(t)}}function es(r){r.getTracks().forEach(e=>e.stop())}function ts(r,e){return r.deviceId===e.deviceId}function rs(r){return Array.from([...r.audioinput.values(),...r.videoinput.values(),...r.audiooutput.values()])}function is(r){const e=[];return r.audio&&e.push(B.AUDIO),r.video&&e.push(B.VIDEO),e}const gi=new iu,vi={LeftToRight:"LeftToRight",UpToDown:"UpToDown",All:"All"};class yi{constructor(){b(this,"id",it())}position(e,t){return new nu(this,{x:e,y:t})}scale(e){return new ns(this,{s:e})}mirror(e){return new ns(this,{mirrorType:e})}available(){var e;return((e=this.previousNode)==null?void 0:e.available())??!1}}class nu extends yi{constructor(t,i){super();b(this,"previousNode");b(this,"_x");b(this,"_y");this.previousNode=t,this._x=i.x,this._y=i.y}paint(t){t.translate(this._x,this._y)}}class ns extends yi{constructor(t,i){super();b(this,"previousNode");b(this,"_scaleParams",[1,1]);if(this.previousNode=t,i.mirrorType)switch(i.mirrorType){case vi.LeftToRight:this._scaleParams=[-1,1];break;case vi.UpToDown:this._scaleParams=[1,-1];break;case vi.All:this._scaleParams=[-1,-1];break;default:this._scaleParams=[1,1];break}else i.s&&(this._scaleParams=[i.s,i.s])}paint(t){t.scale(this._scaleParams[0],this._scaleParams[1])}}class su extends yi{constructor(t){super();b(this,"previousNode",null);b(this,"_source");this._source=t}available(){return this._source.available()}}class Er extends su{constructor(t,i){super(t);b(this,"_targetWidth");b(this,"_targetHeight");const{width:n,height:s}=i??{};this._targetWidth=n??this._source.width(),this._targetHeight=s??this._source.height()}size(t,i){return new Er(this._source,{width:t,height:i})}paint(t){const i=this._targetWidth,n=this._targetHeight;t.drawImage(this._source.element(),-i/2,-n/2,i,n)}}class ou extends mi{constructor(){super(...arguments);b(this,"logger",new ce("PictureTrack"));b(this,"kind",B.VIDEO)}element(){const t=super.element();if(!(t instanceof HTMLImageElement))throw new O(M.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 O(M.TRACK_NOT_AVAILABLE,"track is not avaiable when creating node");const t=new Er(this);return this.logger.info("node",t),t}destroy(){this.logger.warn("destroy"),super.destroy()}}const au=500;class Cr extends mi{constructor(){super(...arguments);b(this,"kind",B.VIDEO);b(this,"sizeChangeTimer");b(this,"watchSizeChangeOnce",()=>{const t=this.width(),i=this.height();this.sizeChangeTimer=setTimeout(()=>{const n=this.width(),s=this.height();(i!==s||t!==n)&&this.emit(se.SIZE_CHANGE,{width:n,height:s})},au)})}element(){const t=super.element();if(!(t instanceof HTMLVideoElement))throw new O(M.UNEXPECTED_TYPE,"source should be HTMLVideoElement");return t}node(){if(!this.available())throw new O(M.TRACK_NOT_AVAILABLE,"track is not avaiable when creating node");return new Er(this)}destroy(){clearTimeout(this.sizeChangeTimer),super.destroy()}}class cu extends Cr{constructor(t){super(t);b(this,"logger",new ce("CameraVideoTrack"));this.watchSizeChangeOnce()}height(){const{height:t}=this.track().getSettings();return t??0}width(){const{width:t}=this.track().getSettings();return t??0}}class uu extends Cr{constructor(t){super(t);b(this,"logger",new ce("ScreenVideoTrack"));this.watchSizeChangeOnce()}height(){const{height:t}=this.track().getSettings();return t??0}width(){const{width:t}=this.track().getSettings();return t??0}}class du extends Cr{constructor(){super(...arguments);b(this,"logger",new ce("MediaVideoTrack"))}height(){const{videoHeight:t}=this.element();return t??0}width(){const{videoWidth:t}=this.element();return t??0}}class hu extends Cr{constructor(){super(...arguments);b(this,"logger",new ce("CustomVideoTrack"))}height(){const{height:t}=this.track().getSettings();return t??0}width(){const{width:t}=this.track().getSettings();return t??0}}async function ss(r,e){let t;if(e!=null&&e.frameRate&&typeof e.frameRate=="number"&&(t=e.frameRate),t)try{await r.applyConstraints({...e,frameRate:{min:t,ideal:t}})}catch(i){console.warn("[VePusher Error]: frameRate limit failed",i)}}const De=new ce("Capture");async function lu(r){return gi.enumerateDevices(r)}async function pu(r){gi.removeAllListeners("onDeviceStateChanged"),gi.on("onDeviceStateChanged",r)}async function fu(r,e){let t;try{const n={video:r??!0};typeof n.video=="object"&&n.video.facingMode&&delete n.video.deviceId,t=await navigator.mediaDevices.getUserMedia(n)}catch(n){throw new O(M.CAPTURE_FAILED,"got error when capturing camera",n)}const i=t.getVideoTracks()[0];if(r!=null&&r.frameRate&&e&&ss(i,r),!i)throw new O(M.UNEXPECTED_TYPE,"got falsy in track");return new cu(i)}async function mu(r,e,t){const{video:i,audio:n}=r;let s=i===!0?{}:i;e!=null&&e.displaySurface&&(s.displaySurface=e.displaySurface,delete e.displaySurface),Ae.settingResolutionInGetDisplayMedia()||(s=!0),!Ae.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 O(M.CAPTURE_FAILED,"got error when capture screen",u)}const o=a.getVideoTracks()[0],d=a.getAudioTracks()[0];if(!o)throw new O(M.UNEXPECTED_TYPE,"got falsy in videoTrack");typeof s!="boolean"&&typeof s.frameRate=="number"&&t&&ss(o,s);const c=[];return c.push(new uu(o)),d&&c.push(new Xc(d)),c}async function _u(r){const{url:e,audio:t,video:i,loop:n}=r,s=new Ot({url:e,kind:i?B.VIDEO:B.AUDIO,loop:n}),a=[];return t&&a.push(new Qn(s)),i&&a.push(new du(s)),await s.isReady(),a}async function gu(r){const e=new Yn(r);return await e.isReady(),new ou(e)}async function vu(r){let e;try{const i={audio:r??!0};e=await navigator.mediaDevices.getUserMedia(i)}catch(i){throw new O(M.CAPTURE_FAILED,"got error when capturing microphone",i)}const t=e.getAudioTracks()[0];if(!t)throw new O(M.UNEXPECTED_TYPE,"got falsy in track");return new Zc(t)}function yu(r){if(!r||r.kind!=="video")throw new O(M.UNEXPECTED_TYPE,"error custom video track type");return new hu(r)}function bu(r){if(!r||r.kind!=="audio")throw new O(M.UNEXPECTED_TYPE,"error custom audio track type");return new Yc(r)}const Su=De.invoke(lu,"enumerateInputDevices"),Eu=De.invoke(fu,"createCameraTrack"),Cu=De.invoke(gu,"createPictureTrack"),os=De.invoke(_u,"createMediaTracks"),wu=De.invoke(vu,"createMicrophoneTrack"),Tu=De.invoke(mu,"createScreenTracks"),zu=De.invoke(pu,"onDeviceChanged"),ku=De.invoke(yu,"createCustomVideoTrack"),Ru=De.invoke(bu,"createCustomAudioTrack");var bi=(r=>(r.PAUSING="pausing",r))(bi||{});const Au={sampleRate:48e3,keepAlive:!0},as=new Map,Mt=new ce("Mixer");class Du extends pi{constructor(t){super();b(this,"id",it());b(this,"_context");b(this,"_config");b(this,"_nodeList",[]);b(this,"_destNode");b(this,"_bufferNode");b(this,"_track");b(this,"unlockAudioContext",()=>{if(this._context.state!=="suspended")return;const t=document.body,i=["touchstart","touchend","mousedown","keydown"],n=()=>{i.forEach(a=>{t.removeEventListener(a,s)})},s=()=>{Lt(this._context).then(n)};i.forEach(a=>{t.addEventListener(a,s,!1)})});Mt.info("ctor",t),this._config={...Au,...t},this._context=xu(this._config),this._bindContextEvent(this._context)}mix(t){Mt.info("mix",t),Lt(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 Mt.info("resume"),Lt(this._context)}_connect(t,i){for(const n of t)n.connect(this._context,i)}_appendSlience(t,i){if(!i||this._bufferNode)return;const{sampleRate:n}=t,s=new AudioBuffer({length:100,sampleRate:n}),a=new AudioBufferSourceNode(t,{buffer:s,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")&&(Mt.info("_emit_",bi.PAUSING),this.emit(bi.PAUSING))}track(){if(Mt.info("track"),Lt(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 i=t.stream.getAudioTracks()[0];return this._destNode=t,this._track=i,i}}function xu(r){const{sampleRate:e,keepAlive:t}=r;let i=as.get(e);return(!i||i.state==="closed")&&(i=new AudioContext({sampleRate:e}),as.set(e,i)),t&&(i.onstatechange=()=>{Lt(i)}),i}function Lt(r){return r.state==="suspended"||r.state==="interrupted"?r.resume():Promise.resolve()}const Pu=r=>(e,t)=>(r.set(e,t),t),cs=Number.MAX_SAFE_INTEGER===void 0?9007199254740991:Number.MAX_SAFE_INTEGER,us=536870912,ds=us*2,Iu=(r,e)=>t=>{const i=e.get(t);let n=i===void 0?t.size:i<ds?i+1:0;if(!t.has(n))return r(t,n);if(t.size<us){for(;t.has(n);)n=Math.floor(Math.random()*ds);return r(t,n)}if(t.size>cs)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()*cs);return r(t,n)},hs=new WeakMap,Ou=Pu(hs),Fe=Iu(Ou,hs),Mu=r=>r.method!==void 0&&r.method==="call",Lu=r=>typeof r.id=="number"&&typeof r.result=="boolean",ls=((r,e)=>{let t=null;return()=>{if(t!==null)return t;const i=new Blob([e],{type:"application/javascript; charset=utf-8"}),n=URL.createObjectURL(i);return t=r(n),setTimeout(()=>URL.revokeObjectURL(n)),t}})(r=>{const e=new Map([[0,()=>{}]]),t=new Map([[0,()=>{}]]),i=new Map,n=new Worker(r);return n.addEventListener("message",({data:c})=>{if(Mu(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=i.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=i.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(Lu(c)){const{id:u}=c,l=i.get(u);if(l===void 0)throw new Error("The timer is in an undefined state.");const{timerId:h,timerType:p}=l;i.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=Fe(i);i.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=Fe(i);i.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=Fe(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=Fe(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})}}))})();`),Uu=r=>ls().clearTimeout(r),Nu=(...r)=>ls().setTimeout(...r),Gu=r=>r.method!==void 0&&r.method==="call",Bu=r=>typeof r.id=="number"&&typeof r.result=="boolean",Vu=r=>{const e=new Map([[0,()=>{}]]),t=new Map([[0,()=>{}]]),i=new Map,n=new Worker(r,{credentials:"omit"});return n.addEventListener("message",({data:c})=>{if(Gu(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=i.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=i.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(Bu(c)){const{id:u}=c,l=i.get(u);if(l===void 0)throw new Error("The timer is in an undefined state.");const{timerId:h,timerType:p}=l;i.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=Fe(i);i.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=Fe(i);i.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=Fe(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=Fe(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}}},Fu={width:640,height:480,frameRate:30,backgroundColor:"#000000"},wr=new ce("View");class ju{constructor(e){b(this,"id",it());b(this,"_context");b(this,"_canvas");b(this,"_config");b(this,"_nodeList",[]);b(this,"_track");b(this,"_stopped",!0);b(this,"_nextTime",Date.now());b(this,"_workerTimeoutId");b(this,"_raqId");b(this,"_workerTimerScriptUrl");b(this,"_customSetTimeout");b(this,"_customClearTimeout");b(this,"_drawCount",0);b(this,"_lastSecondDrawCount",0);b(this,"_lastCountResetTime",Date.now());b(this,"_loopTimer");b(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)},br/this._config.frameRate),this._raqId=requestAnimationFrame(this._paintLoop)});wr.info("ctor",e),this._config={...Fu,...e};const{context:t,canvas:i}=Kn(this._config);this._context=t,this._canvas=i,this._customSetTimeout=Nu,this._customClearTimeout=Uu}setWorkerTimerScriptUrl(e){if(this._workerTimerScriptUrl=e,this._workerTimerScriptUrl){const t=Vu(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+=br/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=[]){wr.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>=br&&(this._lastSecondDrawCount=this._drawCount,this._drawCount=0,this._lastCountResetTime=e)}getDrawCountPerSecond(){return this._updateDrawCountPerSecond(),this._lastSecondDrawCount}_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(wr.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,i=this._canvas.captureStream(t);return this._track=i.getVideoTracks()[0],e.stop(),this._track}else return this.track()}element(){return wr.info("element"),this._paintLoop(),this._canvas}stop(){this._stopped=!0}}function Hu(){return Math.random().toString(36).slice(-8)}const $u=`
1
+ (function(ye,ne){typeof exports=="object"&&typeof module<"u"?module.exports=ne():typeof define=="function"&&define.amd?define(ne):(ye=typeof globalThis<"u"?globalThis:ye||self,ye.vePusher=ne())})(this,function(){"use strict";var J_=Object.defineProperty;var Z_=(ye,ne,Be)=>ne in ye?J_(ye,ne,{enumerable:!0,configurable:!0,writable:!0,value:Be}):ye[ne]=Be;var b=(ye,ne,Be)=>Z_(ye,typeof ne!="symbol"?ne+"":ne,Be);var dc,hc,lc,pc,fc,mc;function ye(r,e){for(var t=0;t<e.length;t++){const i=e[t];if(typeof i!="string"&&!Array.isArray(i)){for(const n in i)if(n!=="default"&&!(n in r)){const s=Object.getOwnPropertyDescriptor(i,n);s&&Object.defineProperty(r,n,s.get?s:{enumerable:!0,get:()=>i[n]})}}}return Object.freeze(Object.defineProperty(r,Symbol.toStringTag,{value:"Module"}))}function ne(r){return r&&r.__esModule&&Object.prototype.hasOwnProperty.call(r,"default")?r.default:r}var Be={exports:{}},In;function wc(){return In||(In=1,function(r){var e=Object.prototype.hasOwnProperty,t="~";function i(){}Object.create&&(i.prototype=Object.create(null),new i().__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 i:delete d._events[c]}function o(){this._events=new i,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],E=arguments.length,y,_;if(m.fn){switch(m.once&&this.removeListener(c,m.fn,void 0,!0),E){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(E-1);_<E;_++)y[_-1]=arguments[_];m.fn.apply(m.context,y)}else{var C=m.length,z;for(_=0;_<C;_++)switch(m[_].once&&this.removeListener(c,m[_].fn,void 0,!0),E){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(E-1);z<E;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=[],E=f.length;v<E;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 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}(Be)),Be.exports}var Tc=wc();const Ve=ne(Tc);var On=(r=>(r.LeftToRight="LeftToRight",r.UpToDown="UpToDown",r.All="All",r.None="None",r))(On||{}),N=(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))(N||{}),Ee=(r=>(r.DeviceCaptured="deviceCaptured",r.DeviceStopCapture="deviceStopCapture",r.Error="error",r.Interrupted="interrupted",r))(Ee||{}),W=(r=>(r.PushStart="pushStart",r.PushStop="pushStop",r.PushError="pushError",r.RTCConnectStateChanged="rtcConnectStateChanged",r.CaptureFirstVideoFrame="capturefirstvideoframe",r.CaptureFirstAudioFrame="capturefirstaudioframe",r.NotAllowedAutoPlay="notallowedautoplay",r.ReconnectStateChange="reconnectStateChange",r.LiveConnectStateChange="liveConnectStateChange",r))(W||{}),Mn=(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))(Mn||{}),Ln=(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))(Ln||{}),Un=(r=>(r.STANDARD="48000x40",r.HIGH="48000x128",r))(Un||{}),rt=(r=>(r.VideoStreamChange="videoStreamChange",r.AudioStreamChange="audioStreamChange",r))(rt||{}),Nn=(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))(Nn||{});const Gn={SizeChange:"sizeChange"};var si=(r=>(r.Portrait="portrait",r.Landscape="landscape",r))(si||{});const Bn="720p-1",Vn="STANDARD";var pe=(r=>(r[r.DISCONNECTED=0]="DISCONNECTED",r[r.CONNECTING=1]="CONNECTING",r[r.CONNECTED=2]="CONNECTED",r[r.RECONNECTING=3]="RECONNECTING",r))(pe||{}),ft=(r=>(r[r.START=1]="START",r[r.WAITING=2]="WAITING",r[r.RECONNECTING=3]="RECONNECTING",r[r.SUCCESS=4]="SUCCESS",r[r.FAILED=5]="FAILED",r))(ft||{}),oi=(r=>(r[r.PushUrlInvalid=1001]="PushUrlInvalid",r[r.ReconnectTimeout=1002]="ReconnectTimeout",r))(oi||{}),M=(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))(M||{}),B=(r=>(r.AUDIO="audio",r.VIDEO="video",r))(B||{}),se=(r=>(r.ENDED="ended",r.MUTE="mute",r.UNMUTE="unmute",r.PLAY_FAILED="play-failed",r.SIZE_CHANGE="size-change",r))(se||{});const re=[];for(let r=0;r<256;++r)re.push((r+256).toString(16).slice(1));function zc(r,e=0){return(re[r[e+0]]+re[r[e+1]]+re[r[e+2]]+re[r[e+3]]+"-"+re[r[e+4]]+re[r[e+5]]+"-"+re[r[e+6]]+re[r[e+7]]+"-"+re[r[e+8]]+re[r[e+9]]+"-"+re[r[e+10]]+re[r[e+11]]+re[r[e+12]]+re[r[e+13]]+re[r[e+14]]+re[r[e+15]]).toLowerCase()}let ai;const kc=new Uint8Array(16);function Rc(){if(!ai){if(typeof crypto>"u"||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");ai=crypto.getRandomValues.bind(crypto)}return ai(kc)}const Fn={randomUUID:typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};function it(r,e,t){var n;if(Fn.randomUUID&&!r)return Fn.randomUUID();r=r||{};const i=r.random??((n=r.rng)==null?void 0:n.call(r))??Rc();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,zc(i)}class jn{constructor(){b(this,"id",it());b(this,"_nextNode");b(this,"_track");b(this,"_destNode")}gain(e){if(this._nextNode instanceof Hn)return this._nextNode.g=e,this._nextNode;const t=new Hn(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 Hn extends jn{constructor(t,i){super();b(this,"previousNode");b(this,"_node");b(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 Ac extends jn{constructor(t){super();b(this,"previousNode",null);b(this,"source");this.source=t}available(){return this.source.available()}destroy(){super.destroy()}}class Dc extends Ac{constructor(){super(...arguments);b(this,"_node")}createNode(t){if(this._node)return this._node;let i;if(this.source instanceof Qn){const n=this.source.element();i=new MediaElementAudioSourceNode(t,{mediaElement:n}),n.muted=!1}else{const n=this.source.track();i=new MediaStreamAudioSourceNode(t,{mediaStream:new MediaStream([n])})}return i}}class O extends Error{constructor(t,i,n){super(i);b(this,"code");b(this,"message");b(this,"error");this.code=t,this.message=i,this.error=n,Object.setPrototypeOf(this,O.prototype)}toString(){return`VeCapture Error: ${this.code} ${this.message}`}}const $n={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"}},qn="__debug__",xc="[VE-CAPTURE]";function Pc(){if(typeof location>"u"||typeof localStorage>"u")return!1;let r=!1;return location.href.includes(qn)&&(r=!0),localStorage.getItem(qn)&&(r=!0),r}let ce=class{constructor(e){b(this,"moduleName");this.moduleName=e}print(e,t,...i){const n=Ic();Pc()&&console.log(`${n}-${xc}%c[${$n[e].text}]%c[${this.moduleName}][${t}]`,`background-color:${$n[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(...s){i.info(`${t}-invoke`,...s);try{const a=e(...s);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 Ic(){const r=new Date;return`${r.toTimeString().split(" ")[0]}:${r.getMilliseconds().toString().padStart(3,"0")}`}function ci(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,n])=>{i==="muted"&&(t instanceof HTMLVideoElement||t instanceof HTMLAudioElement)?t.muted=!0:t.setAttribute(i,n)}),t}function Kn({width:r,height:e}){const t=document.createElement("canvas"),i=t.getContext("2d");if(!i)throw new O(M.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 ui{constructor(e){b(this,"target");b(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(n=>n!==t),this._eventDict.set(e,i),this.target.removeEventListener(e,t))}once(e,t){const i=n=>{t(n),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 J=()=>typeof window>"u";function $(){return navigator.userAgent.toLowerCase()}function di(r=$()){let e="none";return J()||(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 Wn=di()==="firefox",yr=di()==="safari";di(),!J()&&/crios/i.test($()),!J()&&/edg\//i.test($()),!J()&&/edgA/i.test($()),!J()&&/edgios/i.test($()),!J()&&/dingtalk/i.test($()),!J()&&/opr\//.test($()),!J()&&/(iphone|ipod)/i.exec($()),!J()&&(/(ipad)/i.exec($())||/macintosh/i.test($())&&"ontouchend"in document),!J()&&/macintosh/i.test($()),!J()&&/micromessenger/i.test($()),!J()&&$().includes("mobile"),!J()&&/sm-\w+/i.test($());const Oc=!J()&&!!/(iphone|ipad|ipod)/i.exec($());!J()&&/android/i.test($()),!J()&&/windows/i.test($()),!J()&&/openharmony/i.test($());let Jn="0";const Mc=!J()&&((dc=$().match(/version\/(\d+)/i))==null?void 0:dc[1]);yr&&Mc&&(Jn=(hc=navigator.userAgent.match(/version\/(\d+\.\d+)/i))==null?void 0:hc[1]),!J()&&((lc=$().match(/firefox\/(\d+)/i))==null||lc[1]);const hi=Jn;!J()&&((fc=(pc=$().match(/ ([\d_]+) like mac os x/i))==null?void 0:pc[1])==null||fc.split("_").map(r=>parseInt(r))),!J()&&((mc=$().match(/chrome\/(\d+)/i))==null||mc[1]);function Lc(){var r;return!!((r=navigator==null?void 0:navigator.permissions)!=null&&r.query)}function li(){return!!(navigator!=null&&navigator.mediaDevices)}function Uc(){var r;return li()&&!!((r=navigator==null?void 0:navigator.mediaDevices)!=null&&r.getUserMedia)}function Nc(){return!!Promise.withResolvers}function Gc(){return!(yr&&hi==="16.1")}function Bc(){return!(yr&&hi&&["16.1","16.2","16.3"].includes(hi))}function Vc(){return!Wn}function Fc(){return typeof CanvasCaptureMediaStreamTrack<"u"}function jc(r){return typeof r.requestFrame=="function"}function Hc(){return!!li()&&typeof navigator.mediaDevices.ondevicechange<"u"&&typeof navigator.mediaDevices.addEventListener=="function"}const Ae={permissionQuery:Lc,mediaDevices:li,settingResolutionInGetDisplayMedia:Gc,promiseWithResolvers:Nc,getUserMedia:Uc,isolateEnumerateDevices:Vc,supportIdealParamsInGetDisplayMedia:Bc,canvasCaptureMediaStreamTrack:Fc,requestFrameOnMediaStream:jc,ondevicechange:Hc};function $c(){if(Ae.promiseWithResolvers())return Promise.withResolvers();let r,e;const t=new Promise((i,n)=>{r=i,e=n});if(!r||!e)throw Error("resolver and rejector working unexpected");return{promise:t,resolve:r,reject:e}}function Zn(r={}){const{timeout:e,message:t}={timeout:0,message:new O(M.UNEXPECTED_ERROR,"unexpected timeout"),...r},{promise:i,resolve:n,reject:s}=$c();if(e<=0)return{promise:i,resolve:n,reject:s};const a=setTimeout(()=>{s(t)},e);return{promise:i,resolve:d=>{clearTimeout(a),n(d)},reject:s}}const qc={playsinline:"","webkit-playsinline":"","x5-playsinline":"","x5-video-player-type":"h5","x-webkit-airplay":"allow",preload:"metadata",muted:"",crossOrigin:"anonymous"},Kc={playsinline:"","webkit-playsinline":"",preload:"metadata",muted:"",crossOrigin:"anonymous"};class Ot{constructor(e,t=[]){b(this,"id",it());b(this,"_referenceTracks",[]);b(this,"_element");b(this,"_volumeMode",0);b(this,"_readyLock");b(this,"_releaseReadyLock");b(this,"_throwReadyLock");b(this,"_stream");let i;if(e instanceof MediaStreamTrack){const o=new MediaStream([e]);i=Wc(o),this._stream=o}else if(e.url)i=Jc(e);else throw new O(M.UNEXPECTED_TYPE,`got ${typeof e}, expected: MediaStreamTrack or constraints for creating element`);const{promise:n,resolve:s,reject:a}=Zn({timeout:2e3,message:new O(M.PLAY_FAILED,"load media timeout")});this._readyLock=n,this._releaseReadyLock=s,this._throwReadyLock=a,this._element=new ui(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===B.AUDIO){this._upgradeVolumeMode(1e-4);const i=t.getAudioTracks();if(i.length<1)throw new O(M.UNEXPECTED_TYPE,"got empty list of audio tracks");return i[0]}if(e===B.VIDEO){const i=t.getVideoTracks();if(i.length<1)throw new O(M.UNEXPECTED_TYPE,"got empty list of video tracks");return i[0]}throw new O(M.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 O(M.PLAY_FAILED,"play element failed",e)}}_bindPlayerEvent(e){e.on("loadedmetadata",()=>{this._releaseReadyLock()}),e.on("error",()=>{this._throwReadyLock(new O(M.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 Wc(r){let e="audio";r.getVideoTracks().length>0&&(e="video");const t=Xn(e==="video"?B.VIDEO:B.AUDIO);return t.srcObject=r,t}function Jc(r){const{url:e,kind:t,loop:i}=r,n=Xn(t);return n.src=e,n.loop=i,n}function Xn(r){if(r===B.VIDEO)return ci(B.VIDEO,{style:{width:"100%",height:"100%"},attributes:qc});if(r===B.AUDIO)return ci(B.AUDIO,{style:{display:"none"},attributes:Kc});throw new O(M.UNEXPECTED_TYPE,`got ${r}, expected: audio, video`)}class pi extends Ve{emit(e,...t){const i=this.listenerCount(e);return Promise.resolve().then(()=>{super.emit(e,...t)}),!!i}on(e,t,i){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,i)}once(e,t,i){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,i)}}function fi(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 O(M.UNEXPECTED_TYPE,"unexpected constraints type")}const br=1e3;class Yn{constructor(e){b(this,"id",it());b(this,"_context");b(this,"_canvas");b(this,"_image");b(this,"_config");b(this,"_readyLock");b(this,"_releaseReadyLock");b(this,"_throwReadyLock");b(this,"_loopTimer");b(this,"_referenceTracks",[]);b(this,"_stream");const t=fi(e.width),i=fi(e.height),n=fi(e.frameRate);this._config={width:t,height:i,frameRate:n};const{context:s,canvas:a}=Kn({width:t,height:i});this._context=s,this._canvas=a;const o=Zc({url:e.url,width:t,height:i});this._image=new ui(o);const{promise:d,resolve:c,reject:u}=Zn({timeout:2e3,message:new O(M.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 i=t.getVideoTracks();if(i.length<1)throw new O(M.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 O(M.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),br/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 Zc({url:r,height:e,width:t}){const i=ci("img",{style:{width:`${t}px`,height:`${e}px`},attributes:{crossOrigin:"anonymous"}});return i.src=r,i}class mi extends pi{constructor(t){super();b(this,"id",it());b(this,"_track");b(this,"_element");t instanceof MediaStreamTrack?(this._track=new ui(t),this._bindTrackEvent(this._track)):t instanceof Ot?(this._element=t,t.addReferenceTrack(this)):t instanceof Yn&&(this._element=t)}_bindTrackEvent(t){t.on("ended",this._handleTrackEnded.bind(this)),t.on("mute",()=>{this.emit(se.MUTE)}),t.on("unmute",()=>{this.emit(se.UNMUTE)})}_handleTrackEnded(){this.emit(se.ENDED),this.destroy()}handlePlayFailed(){this.emit(se.PLAY_FAILED)}track(){if(this.logger.info("track"),!this.available())throw new O(M.TRACK_NOT_AVAILABLE,"track is not available when creating MediaStreamTrack");if(this._track)return this._track.target;if(!this._element)throw new O(M.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 O(M.TRACK_NOT_AVAILABLE,"track is not available when creating HTMLMediaElement");if(this._element)return this._element.element();if(!this._track)throw new O(M.UNEXPECTED_TYPE,"got this._track falsy");const t=new Ot(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,n;(t=this._track)==null||t.clearAll(),(i=this._track)==null||i.target.stop(),this._track&&delete this._track,(n=this._element)==null||n.removeReference(this),delete this._element}}class Sr extends mi{constructor(){super(...arguments);b(this,"kind",B.AUDIO);b(this,"_node")}node(){if(this.logger.info("node",this.id),!this.available())throw new O(M.TRACK_NOT_AVAILABLE,"track is not avaiable when creating node");if(this._node)return this._node;const t=new Dc(this);return this._node=t,t}element(){if(this.logger.info("element",this.id),!this.available())throw new O(M.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 O(M.UNEXPECTED_TYPE,"source should be HTMLMediaElement");return i}if(!this._track)throw new O(M.UNEXPECTED_TYPE,"got this._track falsy");const t=new Ot(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 Xc extends Sr{constructor(){super(...arguments);b(this,"logger",new ce("MicrophoneAudioTrack"))}}class Yc extends Sr{constructor(){super(...arguments);b(this,"logger",new ce("ScreenAudioTrack"))}}class Qn extends Sr{constructor(){super(...arguments);b(this,"logger",new ce("MediaAudioTrack"))}handlePlayFailed(){this.emit(se.PLAY_FAILED)}async play(){if(this._element){if(!(this._element instanceof Ot))throw new O(M.UNEXPECTED_TYPE,"element is not TrackMediaElement");return this._element._playElement()}}}class Qc extends Sr{constructor(){super(...arguments);b(this,"logger",new ce("CustomAudioTrack"))}}let eu=1;const _i=new ce("PromiseQueue");class tu{constructor(e){b(this,"lockingPromise",Promise.resolve());b(this,"locks",0);b(this,"name","");b(this,"lockId");b(this,"closeReason");this.lockId=eu++,e&&(this.name=e),_i.info(`lock-${this.name}-${this.lockId}`,"is created.")}get isLocked(){return this.locks>0}lock(){this.locks+=1,_i.info(`lock-${this.name}-${this.lockId}`,`locked, current queue ${this.locks}.`);let e;const t=new Promise(n=>{e=()=>{this.locks-=1,_i.info(`lock-${this.name}-${this.lockId}`,`unlocked, current queue ${this.locks}.`),n()}}),i=this.lockingPromise.then(()=>e);return this.lockingPromise=this.lockingPromise.then(()=>t),i}}const ru=300,iu=3e3,Ce=new ce("Devices");class nu extends pi{constructor(){super();b(this,"_deviceMap",{audioinput:[],audiooutput:[],videoinput:[]});b(this,"_permissions",{[B.AUDIO]:!1,[B.VIDEO]:!1});b(this,"_changedQueue",new tu("device changed queue"));this._init()}async _init(){this._initDeviceChanged(),await this._initPermissionChanged();const t=is(this._permissions);t.length>0&&this._refreshDevices(t)}_initDeviceChanged(){if(Ce.info("_initDeviceChanged","invoked"),!Ae.ondevicechange()){Ce.error("_initDeviceChanged","no supported, use timer instead"),setInterval(()=>{this._handleDeviceChanged()},iu);return}Ae.ondevicechange()&&navigator.mediaDevices.addEventListener("devicechange",()=>{Ce.info("devicechange"),setTimeout(()=>{this._handleDeviceChanged()},ru)})}async _initPermissionChanged(){if(!Ae.permissionQuery()){Ce.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",()=>{Ce.info("_initPermissionChanged","update permission for audio"),this._permissions.audio=t.state==="granted"})}catch(t){Ce.error("_initPermissionChanged",t)}try{const t=await navigator.permissions.query({name:"camera"});this._permissions.video=t.state==="granted",t.addEventListener("change",()=>{Ce.info("_initPermissionChanged","update permission for video"),this._permissions.video=t.state==="granted"})}catch(t){Ce.error("_initPermissionChanged",t)}}async _refreshDevices(t){if(!Ae.mediaDevices())throw new O(M.NOT_SUPPORTED,"mediaDevices is not supported");if(t.length===0)throw new O(M.UNEXPECTED_TYPE,"kinds expect to containt values");let i;if(!Ae.isolateEnumerateDevices()){const a={};t.forEach(o=>{a[o]=!0}),i=await navigator.mediaDevices.getUserMedia(a)}let n=await navigator.mediaDevices.enumerateDevices();i&&es(i),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 i=!1;if(t.forEach(n=>{i=i||!this._permissions[n]}),!i)return{grant:!0};if(!Ae.getUserMedia())return{grant:!1,reason:new O(M.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[B.AUDIO]=!0),n.video&&(this._permissions[B.VIDEO]=!0),es(s),{grant:!0}):{grant:!1,reason:new O(M.UNEXPECTED_TYPE,"get stream falsy")}}catch(n){return{grant:!1,reason:new O(M.CAPTURE_FAILED,"acquire user permission failed",n)}}}async _handleDeviceChanged(){Ce.info("_handleDeviceChanged",this._deviceMap,this._permissions);const t=await this._changedQueue.lock();try{const i=rs(this._deviceMap);let n=[];const s=is(this._permissions);s.length===0?Ce.warn("_handleDeviceChanged","no permission, use empty list"):(await this._refreshDevices(s),n=rs(this._deviceMap)),n.forEach(a=>{i.findIndex(d=>ts(d,a))!==-1||this.emit("onDeviceStateChanged",{deviceInfo:a,deviceState:"active"})}),i.forEach(a=>{n.findIndex(d=>ts(d,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(B.AUDIO);else if(o==="videoinput")i.push(B.VIDEO);else throw new O(M.UNEXPECTED_TYPE,"kind in kinds should be enum MediaDeviceKind")});const{grant:n,reason:s}=await this._acquireUserPermission(i);if(!n)throw s;await this._refreshDevices(i);const a=[];return t.forEach(o=>{a.push(...this._deviceMap[o])}),a}async enableDevices(t){return this._acquireUserPermission(t)}}function es(r){r.getTracks().forEach(e=>e.stop())}function ts(r,e){return r.deviceId===e.deviceId}function rs(r){return Array.from([...r.audioinput.values(),...r.videoinput.values(),...r.audiooutput.values()])}function is(r){const e=[];return r.audio&&e.push(B.AUDIO),r.video&&e.push(B.VIDEO),e}const gi=new nu,vi={LeftToRight:"LeftToRight",UpToDown:"UpToDown",All:"All"};class yi{constructor(){b(this,"id",it())}position(e,t){return new su(this,{x:e,y:t})}scale(e){return new ns(this,{s:e})}mirror(e){return new ns(this,{mirrorType:e})}available(){var e;return((e=this.previousNode)==null?void 0:e.available())??!1}}class su extends yi{constructor(t,i){super();b(this,"previousNode");b(this,"_x");b(this,"_y");this.previousNode=t,this._x=i.x,this._y=i.y}paint(t){t.translate(this._x,this._y)}}class ns extends yi{constructor(t,i){super();b(this,"previousNode");b(this,"_scaleParams",[1,1]);if(this.previousNode=t,i.mirrorType)switch(i.mirrorType){case vi.LeftToRight:this._scaleParams=[-1,1];break;case vi.UpToDown:this._scaleParams=[1,-1];break;case vi.All:this._scaleParams=[-1,-1];break;default:this._scaleParams=[1,1];break}else i.s&&(this._scaleParams=[i.s,i.s])}paint(t){t.scale(this._scaleParams[0],this._scaleParams[1])}}class ou extends yi{constructor(t){super();b(this,"previousNode",null);b(this,"_source");this._source=t}available(){return this._source.available()}}class Er extends ou{constructor(t,i){super(t);b(this,"_targetWidth");b(this,"_targetHeight");const{width:n,height:s}=i??{};this._targetWidth=n??this._source.width(),this._targetHeight=s??this._source.height()}size(t,i){return new Er(this._source,{width:t,height:i})}paint(t){const i=this._targetWidth,n=this._targetHeight;t.drawImage(this._source.element(),-i/2,-n/2,i,n)}}class au extends mi{constructor(){super(...arguments);b(this,"logger",new ce("PictureTrack"));b(this,"kind",B.VIDEO)}element(){const t=super.element();if(!(t instanceof HTMLImageElement))throw new O(M.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 O(M.TRACK_NOT_AVAILABLE,"track is not avaiable when creating node");const t=new Er(this);return this.logger.info("node",t),t}destroy(){this.logger.warn("destroy"),super.destroy()}}const cu=500;class Cr extends mi{constructor(){super(...arguments);b(this,"kind",B.VIDEO);b(this,"sizeChangeTimer");b(this,"watchSizeChangeOnce",()=>{const t=this.width(),i=this.height();this.sizeChangeTimer=setTimeout(()=>{const n=this.width(),s=this.height();(i!==s||t!==n)&&this.emit(se.SIZE_CHANGE,{width:n,height:s})},cu)})}element(){const t=super.element();if(!(t instanceof HTMLVideoElement))throw new O(M.UNEXPECTED_TYPE,"source should be HTMLVideoElement");return t}node(){if(!this.available())throw new O(M.TRACK_NOT_AVAILABLE,"track is not avaiable when creating node");return new Er(this)}destroy(){clearTimeout(this.sizeChangeTimer),super.destroy()}}class uu extends Cr{constructor(t){super(t);b(this,"logger",new ce("CameraVideoTrack"));this.watchSizeChangeOnce()}height(){const{height:t}=this.track().getSettings();return t??0}width(){const{width:t}=this.track().getSettings();return t??0}}class du extends Cr{constructor(t){super(t);b(this,"logger",new ce("ScreenVideoTrack"));this.watchSizeChangeOnce()}height(){const{height:t}=this.track().getSettings();return t??0}width(){const{width:t}=this.track().getSettings();return t??0}}class hu extends Cr{constructor(){super(...arguments);b(this,"logger",new ce("MediaVideoTrack"))}height(){const{videoHeight:t}=this.element();return t??0}width(){const{videoWidth:t}=this.element();return t??0}}class lu extends Cr{constructor(){super(...arguments);b(this,"logger",new ce("CustomVideoTrack"))}height(){const{height:t}=this.track().getSettings();return t??0}width(){const{width:t}=this.track().getSettings();return t??0}}async function ss(r,e){let t;if(e!=null&&e.frameRate&&typeof e.frameRate=="number"&&(t=e.frameRate),t)try{await r.applyConstraints({...e,frameRate:{min:t,ideal:t}})}catch(i){console.warn("[VePusher Error]: frameRate limit failed",i)}}const De=new ce("Capture");async function pu(r){return gi.enumerateDevices(r)}async function fu(r){gi.removeAllListeners("onDeviceStateChanged"),gi.on("onDeviceStateChanged",r)}async function mu(r,e){let t;try{const n={video:r??!0};typeof n.video=="object"&&n.video.facingMode&&delete n.video.deviceId,t=await navigator.mediaDevices.getUserMedia(n)}catch(n){throw new O(M.CAPTURE_FAILED,"got error when capturing camera",n)}const i=t.getVideoTracks()[0];if(r!=null&&r.frameRate&&e&&ss(i,r),!i)throw new O(M.UNEXPECTED_TYPE,"got falsy in track");return new uu(i)}async function _u(r,e,t){const{video:i,audio:n}=r;let s=i===!0?{}:i;e!=null&&e.displaySurface&&(s.displaySurface=e.displaySurface,delete e.displaySurface),Ae.settingResolutionInGetDisplayMedia()||(s=!0),!Ae.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 O(M.CAPTURE_FAILED,"got error when capture screen",u)}const o=a.getVideoTracks()[0],d=a.getAudioTracks()[0];if(!o)throw new O(M.UNEXPECTED_TYPE,"got falsy in videoTrack");typeof s!="boolean"&&typeof s.frameRate=="number"&&t&&ss(o,s);const c=[];return c.push(new du(o)),d&&c.push(new Yc(d)),c}async function gu(r){const{url:e,audio:t,video:i,loop:n}=r,s=new Ot({url:e,kind:i?B.VIDEO:B.AUDIO,loop:n}),a=[];return t&&a.push(new Qn(s)),i&&a.push(new hu(s)),await s.isReady(),a}async function vu(r){const e=new Yn(r);return await e.isReady(),new au(e)}async function yu(r){let e;try{const i={audio:r??!0};e=await navigator.mediaDevices.getUserMedia(i)}catch(i){throw new O(M.CAPTURE_FAILED,"got error when capturing microphone",i)}const t=e.getAudioTracks()[0];if(!t)throw new O(M.UNEXPECTED_TYPE,"got falsy in track");return new Xc(t)}function bu(r){if(!r||r.kind!=="video")throw new O(M.UNEXPECTED_TYPE,"error custom video track type");return new lu(r)}function Su(r){if(!r||r.kind!=="audio")throw new O(M.UNEXPECTED_TYPE,"error custom audio track type");return new Qc(r)}const Eu=De.invoke(pu,"enumerateInputDevices"),Cu=De.invoke(mu,"createCameraTrack"),wu=De.invoke(vu,"createPictureTrack"),os=De.invoke(gu,"createMediaTracks"),Tu=De.invoke(yu,"createMicrophoneTrack"),zu=De.invoke(_u,"createScreenTracks"),ku=De.invoke(fu,"onDeviceChanged"),Ru=De.invoke(bu,"createCustomVideoTrack"),Au=De.invoke(Su,"createCustomAudioTrack");var bi=(r=>(r.PAUSING="pausing",r))(bi||{});const Du={sampleRate:48e3,keepAlive:!0},as=new Map,Mt=new ce("Mixer");class xu extends pi{constructor(t){super();b(this,"id",it());b(this,"_context");b(this,"_config");b(this,"_nodeList",[]);b(this,"_destNode");b(this,"_bufferNode");b(this,"_track");b(this,"unlockAudioContext",()=>{if(this._context.state!=="suspended")return;const t=document.body,i=["touchstart","touchend","mousedown","keydown"],n=()=>{i.forEach(a=>{t.removeEventListener(a,s)})},s=()=>{Lt(this._context).then(n)};i.forEach(a=>{t.addEventListener(a,s,!1)})});Mt.info("ctor",t),this._config={...Du,...t},this._context=Pu(this._config),this._bindContextEvent(this._context)}mix(t){Mt.info("mix",t),Lt(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 Mt.info("resume"),Lt(this._context)}_connect(t,i){for(const n of t)n.connect(this._context,i)}_appendSlience(t,i){if(!i||this._bufferNode)return;const{sampleRate:n}=t,s=new AudioBuffer({length:100,sampleRate:n}),a=new AudioBufferSourceNode(t,{buffer:s,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")&&(Mt.info("_emit_",bi.PAUSING),this.emit(bi.PAUSING))}track(){if(Mt.info("track"),Lt(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 i=t.stream.getAudioTracks()[0];return this._destNode=t,this._track=i,i}}function Pu(r){const{sampleRate:e,keepAlive:t}=r;let i=as.get(e);return(!i||i.state==="closed")&&(i=new AudioContext({sampleRate:e}),as.set(e,i)),t&&(i.onstatechange=()=>{Lt(i)}),i}function Lt(r){return r.state==="suspended"||r.state==="interrupted"?r.resume():Promise.resolve()}const Iu=r=>(e,t)=>(r.set(e,t),t),cs=Number.MAX_SAFE_INTEGER===void 0?9007199254740991:Number.MAX_SAFE_INTEGER,us=536870912,ds=us*2,Ou=(r,e)=>t=>{const i=e.get(t);let n=i===void 0?t.size:i<ds?i+1:0;if(!t.has(n))return r(t,n);if(t.size<us){for(;t.has(n);)n=Math.floor(Math.random()*ds);return r(t,n)}if(t.size>cs)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()*cs);return r(t,n)},hs=new WeakMap,Mu=Iu(hs),Fe=Ou(Mu,hs),Lu=r=>r.method!==void 0&&r.method==="call",Uu=r=>typeof r.id=="number"&&typeof r.result=="boolean",ls=((r,e)=>{let t=null;return()=>{if(t!==null)return t;const i=new Blob([e],{type:"application/javascript; charset=utf-8"}),n=URL.createObjectURL(i);return t=r(n),setTimeout(()=>URL.revokeObjectURL(n)),t}})(r=>{const e=new Map([[0,()=>{}]]),t=new Map([[0,()=>{}]]),i=new Map,n=new Worker(r);return n.addEventListener("message",({data:c})=>{if(Lu(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=i.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=i.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(Uu(c)){const{id:u}=c,l=i.get(u);if(l===void 0)throw new Error("The timer is in an undefined state.");const{timerId:h,timerType:p}=l;i.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=Fe(i);i.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=Fe(i);i.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=Fe(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=Fe(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})}}))})();`),Nu=r=>ls().clearTimeout(r),Gu=(...r)=>ls().setTimeout(...r),Bu=r=>r.method!==void 0&&r.method==="call",Vu=r=>typeof r.id=="number"&&typeof r.result=="boolean",Fu=r=>{const e=new Map([[0,()=>{}]]),t=new Map([[0,()=>{}]]),i=new Map,n=new Worker(r,{credentials:"omit"});return n.addEventListener("message",({data:c})=>{if(Bu(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=i.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=i.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(Vu(c)){const{id:u}=c,l=i.get(u);if(l===void 0)throw new Error("The timer is in an undefined state.");const{timerId:h,timerType:p}=l;i.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=Fe(i);i.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=Fe(i);i.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=Fe(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=Fe(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}}},ju={width:640,height:480,frameRate:30,backgroundColor:"#000000"},wr=new ce("View");class Hu{constructor(e){b(this,"id",it());b(this,"_context");b(this,"_canvas");b(this,"_config");b(this,"_nodeList",[]);b(this,"_track");b(this,"_stopped",!0);b(this,"_nextTime",Date.now());b(this,"_workerTimeoutId");b(this,"_raqId");b(this,"_workerTimerScriptUrl");b(this,"_customSetTimeout");b(this,"_customClearTimeout");b(this,"_drawCount",0);b(this,"_lastSecondDrawCount",0);b(this,"_lastCountResetTime",Date.now());b(this,"_loopTimer");b(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)},br/this._config.frameRate),this._raqId=requestAnimationFrame(this._paintLoop)});wr.info("ctor",e),this._config={...ju,...e};const{context:t,canvas:i}=Kn(this._config);this._context=t,this._canvas=i,this._customSetTimeout=Gu,this._customClearTimeout=Nu}setWorkerTimerScriptUrl(e){if(this._workerTimerScriptUrl=e,this._workerTimerScriptUrl){const t=Fu(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+=br/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=[]){wr.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>=br&&(this._lastSecondDrawCount=this._drawCount,this._drawCount=0,this._lastCountResetTime=e)}getDrawCountPerSecond(){return this._updateDrawCountPerSecond(),this._lastSecondDrawCount}_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(wr.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,i=this._canvas.captureStream(t);return this._track=i.getVideoTracks()[0],e.stop(),this._track}else return this.track()}element(){return wr.info("element"),this._paintLoop(),this._canvas}stop(){this._stopped=!0}}function $u(){return Math.random().toString(36).slice(-8)}const qu=`
2
2
  const SMOOTHING_FACTOR = 0.8;
3
3
  const MINIMUM_VALUE = 0.00001;
4
4
 
@@ -53,7 +53,7 @@ registerProcessor('vumeter', class extends AudioWorkletProcessor {
53
53
  return true;
54
54
  }
55
55
  });
56
- `,qu=URL.createObjectURL(new Blob([$u],{type:"application/javascript"}));class Ku{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||qu);const n=new MediaStream;n.addTrack(e);const s=i.createMediaStreamSource(n),a=new AudioWorkletNode(i,"vumeter");a.port.onmessage=o=>{const d=o.data.volume||0;this._volume=Math.min(d*100/2,10)},s.connect(a).connect(i.destination),this._audioCtx=i}stop(){var e;(e=this._audioCtx)==null||e.close(),this._audioCtx=null}}class Tr{constructor(){this._volumeDetectScriptUrl=void 0}static get instance(){return this._instance||(this._instance=new Tr),this._instance}get volumeDetectScriptUrl(){return this._volumeDetectScriptUrl}set volumeDetectScriptUrl(e){this._volumeDetectScriptUrl=e}}class ps extends Ve{constructor(e){super(),this._width=0,this._height=0,this._mediaStream=null,this._nextStream=null,this._trackMap={},this.type=e.type,this.id=Hu(),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[N.Camera,N.Screen,N.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 Ku),await this._volumeDetector.start(this.audioTrack,Tr.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 mt extends ps{constructor(){super(...arguments),this._frameRate=1}get isVideoStream(){return!0}get isAudioStream(){return!1}get frameRate(){return this._frameRate}bindTrackSizeChangeEvent(e){e.on(se.SIZE_CHANGE,({width:t,height:i})=>{this._width=t,this._height=i,this.emit(Gn.SizeChange,{width:t,height:i})})}}class zr extends ps{get isVideoStream(){return!1}get isAudioStream(){return!0}}class Wu extends mt{constructor(e,t){super({type:N.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(se.ENDED,e)}destroy(){this.source.destroy()}}var fs=typeof global=="object"&&global&&global.Object===Object&&global,Ju=typeof self=="object"&&self&&self.Object===Object&&self,xe=fs||Ju||Function("return this")(),je=xe.Symbol,ms=Object.prototype,Zu=ms.hasOwnProperty,Xu=ms.toString,Ut=je?je.toStringTag:void 0;function Yu(r){var e=Zu.call(r,Ut),t=r[Ut];try{r[Ut]=void 0;var i=!0}catch{}var n=Xu.call(r);return i&&(e?r[Ut]=t:delete r[Ut]),n}var Qu=Object.prototype,ed=Qu.toString;function td(r){return ed.call(r)}var rd="[object Null]",id="[object Undefined]",_s=je?je.toStringTag:void 0;function _t(r){return r==null?r===void 0?id:rd:_s&&_s in Object(r)?Yu(r):td(r)}function gt(r){return r!=null&&typeof r=="object"}var nd="[object Symbol]";function kr(r){return typeof r=="symbol"||gt(r)&&_t(r)==nd}function gs(r,e){for(var t=-1,i=r==null?0:r.length,n=Array(i);++t<i;)n[t]=e(r[t],t,r);return n}var X=Array.isArray,vs=je?je.prototype:void 0,ys=vs?vs.toString:void 0;function bs(r){if(typeof r=="string")return r;if(X(r))return gs(r,bs)+"";if(kr(r))return ys?ys.call(r):"";var e=r+"";return e=="0"&&1/r==-1/0?"-0":e}var sd=/\s/;function od(r){for(var e=r.length;e--&&sd.test(r.charAt(e)););return e}var ad=/^\s+/;function cd(r){return r&&r.slice(0,od(r)+1).replace(ad,"")}function Nt(r){var e=typeof r;return r!=null&&(e=="object"||e=="function")}var Ss=NaN,ud=/^[-+]0x[0-9a-f]+$/i,dd=/^0b[01]+$/i,hd=/^0o[0-7]+$/i,ld=parseInt;function pd(r){if(typeof r=="number")return r;if(kr(r))return Ss;if(Nt(r)){var e=typeof r.valueOf=="function"?r.valueOf():r;r=Nt(e)?e+"":e}if(typeof r!="string")return r===0?r:+r;r=cd(r);var t=dd.test(r);return t||hd.test(r)?ld(r.slice(2),t?2:8):ud.test(r)?Ss:+r}var fd=1/0,md=17976931348623157e292;function _d(r){if(!r)return r===0?r:0;if(r=pd(r),r===fd||r===-1/0){var e=r<0?-1:1;return e*md}return r===r?r:0}function gd(r){var e=_d(r),t=e%1;return e===e?t?e-t:e:0}function vd(r){return r}var yd="[object AsyncFunction]",bd="[object Function]",Sd="[object GeneratorFunction]",Ed="[object Proxy]";function Es(r){if(!Nt(r))return!1;var e=_t(r);return e==bd||e==Sd||e==yd||e==Ed}var Si=xe["__core-js_shared__"],Cs=function(){var r=/[^.]+$/.exec(Si&&Si.keys&&Si.keys.IE_PROTO||"");return r?"Symbol(src)_1."+r:""}();function Cd(r){return!!Cs&&Cs in r}var wd=Function.prototype,Td=wd.toString;function nt(r){if(r!=null){try{return Td.call(r)}catch{}try{return r+""}catch{}}return""}var zd=/[\\^$.*+?()[\]{}|]/g,kd=/^\[object .+?Constructor\]$/,Rd=Function.prototype,Ad=Object.prototype,Dd=Rd.toString,xd=Ad.hasOwnProperty,Pd=RegExp("^"+Dd.call(xd).replace(zd,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function Id(r){if(!Nt(r)||Cd(r))return!1;var e=Es(r)?Pd:kd;return e.test(nt(r))}function Od(r,e){return r==null?void 0:r[e]}function vt(r,e){var t=Od(r,e);return Id(t)?t:void 0}var Ei=vt(xe,"WeakMap");function Md(r,e,t,i){for(var n=r.length,s=t+-1;++s<n;)if(e(r[s],s,r))return s;return-1}var Ld=9007199254740991,Ud=/^(?:0|[1-9]\d*)$/;function ws(r,e){var t=typeof r;return e=e??Ld,!!e&&(t=="number"||t!="symbol"&&Ud.test(r))&&r>-1&&r%1==0&&r<e}function Ts(r,e){return r===e||r!==r&&e!==e}var Nd=9007199254740991;function Ci(r){return typeof r=="number"&&r>-1&&r%1==0&&r<=Nd}function Rr(r){return r!=null&&Ci(r.length)&&!Es(r)}var Gd=Object.prototype;function zs(r){var e=r&&r.constructor,t=typeof e=="function"&&e.prototype||Gd;return r===t}function Bd(r,e){for(var t=-1,i=Array(r);++t<r;)i[t]=e(t);return i}var Vd="[object Arguments]";function ks(r){return gt(r)&&_t(r)==Vd}var Rs=Object.prototype,Fd=Rs.hasOwnProperty,jd=Rs.propertyIsEnumerable,wi=ks(function(){return arguments}())?ks:function(r){return gt(r)&&Fd.call(r,"callee")&&!jd.call(r,"callee")};function Hd(){return!1}var As=typeof exports=="object"&&exports&&!exports.nodeType&&exports,Ds=As&&typeof module=="object"&&module&&!module.nodeType&&module,$d=Ds&&Ds.exports===As,xs=$d?xe.Buffer:void 0,qd=xs?xs.isBuffer:void 0,Ar=qd||Hd,Kd="[object Arguments]",Wd="[object Array]",Jd="[object Boolean]",Zd="[object Date]",Xd="[object Error]",Yd="[object Function]",Qd="[object Map]",eh="[object Number]",th="[object Object]",rh="[object RegExp]",ih="[object Set]",nh="[object String]",sh="[object WeakMap]",oh="[object ArrayBuffer]",ah="[object DataView]",ch="[object Float32Array]",uh="[object Float64Array]",dh="[object Int8Array]",hh="[object Int16Array]",lh="[object Int32Array]",ph="[object Uint8Array]",fh="[object Uint8ClampedArray]",mh="[object Uint16Array]",_h="[object Uint32Array]",F={};F[ch]=F[uh]=F[dh]=F[hh]=F[lh]=F[ph]=F[fh]=F[mh]=F[_h]=!0,F[Kd]=F[Wd]=F[oh]=F[Jd]=F[ah]=F[Zd]=F[Xd]=F[Yd]=F[Qd]=F[eh]=F[th]=F[rh]=F[ih]=F[nh]=F[sh]=!1;function gh(r){return gt(r)&&Ci(r.length)&&!!F[_t(r)]}function vh(r){return function(e){return r(e)}}var Ps=typeof exports=="object"&&exports&&!exports.nodeType&&exports,Gt=Ps&&typeof module=="object"&&module&&!module.nodeType&&module,yh=Gt&&Gt.exports===Ps,Ti=yh&&fs.process,Is=function(){try{var r=Gt&&Gt.require&&Gt.require("util").types;return r||Ti&&Ti.binding&&Ti.binding("util")}catch{}}(),Os=Is&&Is.isTypedArray,zi=Os?vh(Os):gh,bh=Object.prototype,Sh=bh.hasOwnProperty;function Eh(r,e){var t=X(r),i=!t&&wi(r),n=!t&&!i&&Ar(r),s=!t&&!i&&!n&&zi(r),a=t||i||n||s,o=a?Bd(r.length,String):[],d=o.length;for(var c in r)Sh.call(r,c)&&!(a&&(c=="length"||n&&(c=="offset"||c=="parent")||s&&(c=="buffer"||c=="byteLength"||c=="byteOffset")||ws(c,d)))&&o.push(c);return o}function Ch(r,e){return function(t){return r(e(t))}}var wh=Ch(Object.keys,Object),Th=Object.prototype,zh=Th.hasOwnProperty;function Ms(r){if(!zs(r))return wh(r);var e=[];for(var t in Object(r))zh.call(r,t)&&t!="constructor"&&e.push(t);return e}function Bt(r){return Rr(r)?Eh(r):Ms(r)}var kh=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,Rh=/^\w*$/;function ki(r,e){if(X(r))return!1;var t=typeof r;return t=="number"||t=="symbol"||t=="boolean"||r==null||kr(r)?!0:Rh.test(r)||!kh.test(r)||e!=null&&r in Object(e)}var Vt=vt(Object,"create");function Ah(){this.__data__=Vt?Vt(null):{},this.size=0}function Dh(r){var e=this.has(r)&&delete this.__data__[r];return this.size-=e?1:0,e}var xh="__lodash_hash_undefined__",Ph=Object.prototype,Ih=Ph.hasOwnProperty;function Oh(r){var e=this.__data__;if(Vt){var t=e[r];return t===xh?void 0:t}return Ih.call(e,r)?e[r]:void 0}var Mh=Object.prototype,Lh=Mh.hasOwnProperty;function Uh(r){var e=this.__data__;return Vt?e[r]!==void 0:Lh.call(e,r)}var Nh="__lodash_hash_undefined__";function Gh(r,e){var t=this.__data__;return this.size+=this.has(r)?0:1,t[r]=Vt&&e===void 0?Nh:e,this}function st(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])}}st.prototype.clear=Ah,st.prototype.delete=Dh,st.prototype.get=Oh,st.prototype.has=Uh,st.prototype.set=Gh;function Bh(){this.__data__=[],this.size=0}function Dr(r,e){for(var t=r.length;t--;)if(Ts(r[t][0],e))return t;return-1}var Vh=Array.prototype,Fh=Vh.splice;function jh(r){var e=this.__data__,t=Dr(e,r);if(t<0)return!1;var i=e.length-1;return t==i?e.pop():Fh.call(e,t,1),--this.size,!0}function Hh(r){var e=this.__data__,t=Dr(e,r);return t<0?void 0:e[t][1]}function $h(r){return Dr(this.__data__,r)>-1}function qh(r,e){var t=this.__data__,i=Dr(t,r);return i<0?(++this.size,t.push([r,e])):t[i][1]=e,this}function Pe(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])}}Pe.prototype.clear=Bh,Pe.prototype.delete=jh,Pe.prototype.get=Hh,Pe.prototype.has=$h,Pe.prototype.set=qh;var Ft=vt(xe,"Map");function Kh(){this.size=0,this.__data__={hash:new st,map:new(Ft||Pe),string:new st}}function Wh(r){var e=typeof r;return e=="string"||e=="number"||e=="symbol"||e=="boolean"?r!=="__proto__":r===null}function xr(r,e){var t=r.__data__;return Wh(e)?t[typeof e=="string"?"string":"hash"]:t.map}function Jh(r){var e=xr(this,r).delete(r);return this.size-=e?1:0,e}function Zh(r){return xr(this,r).get(r)}function Xh(r){return xr(this,r).has(r)}function Yh(r,e){var t=xr(this,r),i=t.size;return t.set(r,e),this.size+=t.size==i?0:1,this}function Ie(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])}}Ie.prototype.clear=Kh,Ie.prototype.delete=Jh,Ie.prototype.get=Zh,Ie.prototype.has=Xh,Ie.prototype.set=Yh;var Qh="Expected a function";function Ri(r,e){if(typeof r!="function"||e!=null&&typeof e!="function")throw new TypeError(Qh);var t=function(){var i=arguments,n=e?e.apply(this,i):i[0],s=t.cache;if(s.has(n))return s.get(n);var a=r.apply(this,i);return t.cache=s.set(n,a)||s,a};return t.cache=new(Ri.Cache||Ie),t}Ri.Cache=Ie;var el=500;function tl(r){var e=Ri(r,function(i){return t.size===el&&t.clear(),i}),t=e.cache;return e}var rl=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,il=/\\(\\)?/g,nl=tl(function(r){var e=[];return r.charCodeAt(0)===46&&e.push(""),r.replace(rl,function(t,i,n,s){e.push(n?s.replace(il,"$1"):i||t)}),e});function sl(r){return r==null?"":bs(r)}function Ls(r,e){return X(r)?r:ki(r,e)?[r]:nl(sl(r))}function Pr(r){if(typeof r=="string"||kr(r))return r;var e=r+"";return e=="0"&&1/r==-1/0?"-0":e}function Us(r,e){e=Ls(e,r);for(var t=0,i=e.length;r!=null&&t<i;)r=r[Pr(e[t++])];return t&&t==i?r:void 0}function ol(r,e,t){var i=r==null?void 0:Us(r,e);return i===void 0?t:i}function al(r,e){for(var t=-1,i=e.length,n=r.length;++t<i;)r[n+t]=e[t];return r}function cl(){this.__data__=new Pe,this.size=0}function ul(r){var e=this.__data__,t=e.delete(r);return this.size=e.size,t}function dl(r){return this.__data__.get(r)}function hl(r){return this.__data__.has(r)}var ll=200;function pl(r,e){var t=this.__data__;if(t instanceof Pe){var i=t.__data__;if(!Ft||i.length<ll-1)return i.push([r,e]),this.size=++t.size,this;t=this.__data__=new Ie(i)}return t.set(r,e),this.size=t.size,this}function Oe(r){var e=this.__data__=new Pe(r);this.size=e.size}Oe.prototype.clear=cl,Oe.prototype.delete=ul,Oe.prototype.get=dl,Oe.prototype.has=hl,Oe.prototype.set=pl;function Ns(r,e){for(var t=-1,i=r==null?0:r.length,n=0,s=[];++t<i;){var a=r[t];e(a,t,r)&&(s[n++]=a)}return s}function fl(){return[]}var ml=Object.prototype,_l=ml.propertyIsEnumerable,Gs=Object.getOwnPropertySymbols,gl=Gs?function(r){return r==null?[]:(r=Object(r),Ns(Gs(r),function(e){return _l.call(r,e)}))}:fl;function vl(r,e,t){var i=e(r);return X(r)?i:al(i,t(r))}function Bs(r){return vl(r,Bt,gl)}var Ai=vt(xe,"DataView"),Di=vt(xe,"Promise"),xi=vt(xe,"Set"),Vs="[object Map]",yl="[object Object]",Fs="[object Promise]",js="[object Set]",Hs="[object WeakMap]",$s="[object DataView]",bl=nt(Ai),Sl=nt(Ft),El=nt(Di),Cl=nt(xi),wl=nt(Ei),Me=_t;(Ai&&Me(new Ai(new ArrayBuffer(1)))!=$s||Ft&&Me(new Ft)!=Vs||Di&&Me(Di.resolve())!=Fs||xi&&Me(new xi)!=js||Ei&&Me(new Ei)!=Hs)&&(Me=function(r){var e=_t(r),t=e==yl?r.constructor:void 0,i=t?nt(t):"";if(i)switch(i){case bl:return $s;case Sl:return Vs;case El:return Fs;case Cl:return js;case wl:return Hs}return e});var qs=xe.Uint8Array,Tl="__lodash_hash_undefined__";function zl(r){return this.__data__.set(r,Tl),this}function kl(r){return this.__data__.has(r)}function Ir(r){var e=-1,t=r==null?0:r.length;for(this.__data__=new Ie;++e<t;)this.add(r[e])}Ir.prototype.add=Ir.prototype.push=zl,Ir.prototype.has=kl;function Rl(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 Al(r,e){return r.has(e)}var Dl=1,xl=2;function Ks(r,e,t,i,n,s){var a=t&Dl,o=r.length,d=e.length;if(o!=d&&!(a&&d>o))return!1;var c=s.get(r),u=s.get(e);if(c&&u)return c==e&&u==r;var l=-1,h=!0,p=t&xl?new Ir:void 0;for(s.set(r,e),s.set(e,r);++l<o;){var f=r[l],v=e[l];if(i)var m=a?i(v,f,l,e,r,s):i(f,v,l,r,e,s);if(m!==void 0){if(m)continue;h=!1;break}if(p){if(!Rl(e,function(E,y){if(!Al(p,y)&&(f===E||n(f,E,t,i,s)))return p.push(y)})){h=!1;break}}else if(!(f===v||n(f,v,t,i,s))){h=!1;break}}return s.delete(r),s.delete(e),h}function Pl(r){var e=-1,t=Array(r.size);return r.forEach(function(i,n){t[++e]=[n,i]}),t}function Il(r){var e=-1,t=Array(r.size);return r.forEach(function(i){t[++e]=i}),t}var Ol=1,Ml=2,Ll="[object Boolean]",Ul="[object Date]",Nl="[object Error]",Gl="[object Map]",Bl="[object Number]",Vl="[object RegExp]",Fl="[object Set]",jl="[object String]",Hl="[object Symbol]",$l="[object ArrayBuffer]",ql="[object DataView]",Ws=je?je.prototype:void 0,Pi=Ws?Ws.valueOf:void 0;function Kl(r,e,t,i,n,s,a){switch(t){case ql:if(r.byteLength!=e.byteLength||r.byteOffset!=e.byteOffset)return!1;r=r.buffer,e=e.buffer;case $l:return!(r.byteLength!=e.byteLength||!s(new qs(r),new qs(e)));case Ll:case Ul:case Bl:return Ts(+r,+e);case Nl:return r.name==e.name&&r.message==e.message;case Vl:case jl:return r==e+"";case Gl:var o=Pl;case Fl:var d=i&Ol;if(o||(o=Il),r.size!=e.size&&!d)return!1;var c=a.get(r);if(c)return c==e;i|=Ml,a.set(r,e);var u=Ks(o(r),o(e),i,n,s,a);return a.delete(r),u;case Hl:if(Pi)return Pi.call(r)==Pi.call(e)}return!1}var Wl=1,Jl=Object.prototype,Zl=Jl.hasOwnProperty;function Xl(r,e,t,i,n,s){var a=t&Wl,o=Bs(r),d=o.length,c=Bs(e),u=c.length;if(d!=u&&!a)return!1;for(var l=d;l--;){var h=o[l];if(!(a?h in e:Zl.call(e,h)))return!1}var p=s.get(r),f=s.get(e);if(p&&f)return p==e&&f==r;var v=!0;s.set(r,e),s.set(e,r);for(var m=a;++l<d;){h=o[l];var E=r[h],y=e[h];if(i)var _=a?i(y,E,h,e,r,s):i(E,y,h,r,e,s);if(!(_===void 0?E===y||n(E,y,t,i,s):_)){v=!1;break}m||(m=h=="constructor")}if(v&&!m){var C=r.constructor,z=e.constructor;C!=z&&"constructor"in r&&"constructor"in e&&!(typeof C=="function"&&C instanceof C&&typeof z=="function"&&z instanceof z)&&(v=!1)}return s.delete(r),s.delete(e),v}var Yl=1,Js="[object Arguments]",Zs="[object Array]",Or="[object Object]",Ql=Object.prototype,Xs=Ql.hasOwnProperty;function ep(r,e,t,i,n,s){var a=X(r),o=X(e),d=a?Zs:Me(r),c=o?Zs:Me(e);d=d==Js?Or:d,c=c==Js?Or:c;var u=d==Or,l=c==Or,h=d==c;if(h&&Ar(r)){if(!Ar(e))return!1;a=!0,u=!1}if(h&&!u)return s||(s=new Oe),a||zi(r)?Ks(r,e,t,i,n,s):Kl(r,e,d,t,i,n,s);if(!(t&Yl)){var p=u&&Xs.call(r,"__wrapped__"),f=l&&Xs.call(e,"__wrapped__");if(p||f){var v=p?r.value():r,m=f?e.value():e;return s||(s=new Oe),n(v,m,t,i,s)}}return h?(s||(s=new Oe),Xl(r,e,t,i,n,s)):!1}function Ii(r,e,t,i,n){return r===e?!0:r==null||e==null||!gt(r)&&!gt(e)?r!==r&&e!==e:ep(r,e,t,i,Ii,n)}var tp=1,rp=2;function ip(r,e,t,i){var n=t.length,s=n;if(r==null)return!s;for(r=Object(r);n--;){var a=t[n];if(a[2]?a[1]!==r[a[0]]:!(a[0]in r))return!1}for(;++n<s;){a=t[n];var o=a[0],d=r[o],c=a[1];if(a[2]){if(d===void 0&&!(o in r))return!1}else{var u=new Oe,l;if(!(l===void 0?Ii(c,d,tp|rp,i,u):l))return!1}}return!0}function Ys(r){return r===r&&!Nt(r)}function np(r){for(var e=Bt(r),t=e.length;t--;){var i=e[t],n=r[i];e[t]=[i,n,Ys(n)]}return e}function Qs(r,e){return function(t){return t==null?!1:t[r]===e&&(e!==void 0||r in Object(t))}}function sp(r){var e=np(r);return e.length==1&&e[0][2]?Qs(e[0][0],e[0][1]):function(t){return t===r||ip(t,r,e)}}function op(r,e){return r!=null&&e in Object(r)}function ap(r,e,t){e=Ls(e,r);for(var i=-1,n=e.length,s=!1;++i<n;){var a=Pr(e[i]);if(!(s=r!=null&&t(r,a)))break;r=r[a]}return s||++i!=n?s:(n=r==null?0:r.length,!!n&&Ci(n)&&ws(a,n)&&(X(r)||wi(r)))}function cp(r,e){return r!=null&&ap(r,e,op)}var up=1,dp=2;function hp(r,e){return ki(r)&&Ys(e)?Qs(Pr(r),e):function(t){var i=ol(t,r);return i===void 0&&i===e?cp(t,r):Ii(e,i,up|dp)}}function lp(r){return function(e){return e==null?void 0:e[r]}}function pp(r){return function(e){return Us(e,r)}}function fp(r){return ki(r)?lp(Pr(r)):pp(r)}function Oi(r){return typeof r=="function"?r:r==null?vd:typeof r=="object"?X(r)?hp(r[0],r[1]):sp(r):fp(r)}function mp(r){return function(e,t,i){for(var n=-1,s=Object(e),a=i(e),o=a.length;o--;){var d=a[++n];if(t(s[d],d,s)===!1)break}return e}}var _p=mp();function gp(r,e){return r&&_p(r,e,Bt)}function vp(r,e){return function(t,i){if(t==null)return t;if(!Rr(t))return r(t,i);for(var n=t.length,s=-1,a=Object(t);++s<n&&i(a[s],s,a)!==!1;);return t}}var yp=vp(gp);function bp(r,e){var t=[];return yp(r,function(i,n,s){e(i,n,s)&&t.push(i)}),t}function eo(r,e){var t=X(r)?Ns:bp;return t(r,Oi(e))}function Sp(r){return function(e,t,i){var n=Object(e);if(!Rr(e)){var s=Oi(t);e=Bt(e),t=function(o){return s(n[o],o,n)}}var a=r(e,t,i);return a>-1?n[s?e[a]:a]:void 0}}var Ep=Math.max;function Cp(r,e,t){var i=r==null?0:r.length;if(!i)return-1;var n=t==null?0:gd(t);return n<0&&(n=Ep(i+n,0)),Md(r,Oi(e),n)}var jt=Sp(Cp);function wp(r,e){return gs(e,function(t){return r[t]})}function Le(r){return r==null?[]:wp(r,Bt(r))}var Tp="[object Map]",zp="[object Set]",kp=Object.prototype,Rp=kp.hasOwnProperty;function Ap(r){if(r==null)return!0;if(Rr(r)&&(X(r)||typeof r=="string"||typeof r.splice=="function"||Ar(r)||zi(r)||wi(r)))return!r.length;var e=Me(r);if(e==Tp||e==zp)return!r.size;if(zs(r))return!Ms(r).length;for(var t in r)if(Rp.call(r,t))return!1;return!0}function Dp(r){return r==null}class xp extends zr{constructor(e){super({type:N.Microphone,stream:e}),this._trackMap.audio=e.track()}get source(){return this._source}get mixerNode(){return this.source.node()}bindTrackEnd(e){this.source.on(se.ENDED,e)}destroy(){this.source.destroy()}}class Pp extends mt{constructor(e){super({type:N.VideoFile,stream:e});const t=jt(e,n=>n.kind===B.VIDEO),i=jt(e,n=>n.kind===B.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(se.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 Ip extends mt{constructor(e,t){super({type:N.Screen,stream:e});const i=jt(e,s=>s.kind===B.VIDEO),n=jt(e,s=>s.kind===B.AUDIO);this._videoStream=i,this._audioStream=n,this._frameRate=(t==null?void 0:t.frameRate)??1,this._trackMap.video=i==null?void 0:i.track(),this._trackMap.audio=n==null?void 0:n.track(),i&&(this._height=i==null?void 0:i.height(),this._width=i==null?void 0:i.width(),this.bindTrackSizeChangeEvent(i))}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(se.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 Op extends zr{constructor(e){super({type:N.AudioFile,stream:e});const t=jt(e,i=>i.kind===B.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(se.ENDED,e)}destroy(){var e;(e=this._audioStream)==null||e.destroy()}}class Mp extends mt{constructor(e){super({type:N.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(se.ENDED,e)}destroy(){this.source.destroy()}}class Lp extends mt{constructor(e){super({type:N.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(se.ENDED,e)}destroy(){this.source.destroy()}}class Up extends zr{constructor(e){super({type:N.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(se.ENDED,e)}destroy(){var e;(e=this._audioStream)==null||e.destroy()}}const Np=["user","environment"],Gp=18e4,Bp=1e4,to=1e3;var de=(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[r.AUDIO_RESUME_FAILED=2004]="AUDIO_RESUME_FAILED",r))(de||{});class yt extends Error{constructor(e,t,i){super(),this.code=e,this.message=t,i&&(this.ext=i)}}function bt(r,e,t){const i=si.Landscape;if(e==="video"){const d=(i===si.Landscape?Mn:Ln)[r],[c,u,l,h]=d.split("x").map(p=>Number(p));return{width:c,height:u,frameRate:l,bitrate:h*1e3}}const n=Un[r],[s,a]=n.split("x").map(o=>Number(o));return{sampleRate:s,bitrate:a*1e3}}var U=function(){return(U=Object.assign||function(r){for(var e,t=1,i=arguments.length;t<i;t++)for(var n in e=arguments[t])Object.prototype.hasOwnProperty.call(e,n)&&(r[n]=e[n]);return r}).apply(this,arguments)};function Vp(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var i,n,s=t.call(r),a=[];try{for(;(e===void 0||e-- >0)&&!(i=s.next()).done;)a.push(i.value)}catch(o){n={error:o}}finally{try{i&&!i.done&&(t=s.return)&&t.call(s)}finally{if(n)throw n.error}}return a}function ot(){for(var r=[],e=0;e<arguments.length;e++)r=r.concat(Vp(arguments[e]));return r}var ro,Fp=function(){function r(){this._hooks={},this._cache=[],this._hooksCache={}}return r.prototype.on=function(e,t){e&&t&&typeof t=="function"&&(this._hooks[e]||(this._hooks[e]=[]),this._hooks[e].push(t))},r.prototype.once=function(e,t){var i=this;e&&t&&typeof t=="function"&&this.on(e,function n(s){t(s),i.off(e,n)})},r.prototype.off=function(e,t){if(e&&this._hooks[e]&&this._hooks[e].length)if(t){var i=this._hooks[e].indexOf(t);i!==-1&&this._hooks[e].splice(i,1)}else this._hooks[e]=[]},r.prototype.emit=function(e,t,i){if(i){if(!e)return;this._cache.indexOf(i)!==-1?this._emit(e,t):(this._hooksCache.hasOwnProperty(i)||(this._hooksCache[i]={}),this._hooksCache[i].hasOwnProperty(e)||(this._hooksCache[i][e]=[]),this._hooksCache[i][e].push(t))}else this._emit(e,t)},r.prototype._emit=function(e,t){e&&this._hooks[e]&&this._hooks[e].length&&ot(this._hooks[e]).forEach(function(i){try{i(t)}catch{}})},r.prototype.set=function(e){e&&this._cache.indexOf(e)===-1&&this._cache.push(e)},r}(),Ht=function(r){return r!=null&&Object.prototype.toString.call(r)=="[object Object]"},Mr=function(r){return Array.isArray(r)},jp=(ro=+Date.now()+Number((""+Math.random()).slice(2,8)),function(){return ro+=1}),Y=function(r){return function(e,t,i){if(typeof e=="string"&&typeof i=="number"){var n,s=[];i=i<=25?i:i%25;var a=String.fromCharCode(i+97);n=e.split(a);for(var o=0;o<n.length;o++){var d=parseInt(n[o],i);d=1*d^t;var c=String.fromCharCode(d);s.push(c)}return s.join("")}}(r,64,25)},io=function(){return!!navigator.userAgent.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/)},Mi=function(r){io()?window.addEventListener("pagehide",r,!1):window.addEventListener("beforeunload",r,!1)},Hp=function(r,e,t){var i=document.createElement("script");i.src=r,i.onerror=function(){t(r)},i.onload=function(){e()},document.getElementsByTagName("head")[0].appendChild(i)},no=function(){var r=0;return["hidden","msHidden","webkitHidden"].forEach(function(e){document[e]!==void 0&&(r=1)}),r},$p=function(r,e){r===void 0&&(r=function(){}),e===void 0&&(e=1e3);var t,i=Date.now()+e;return t=window.setTimeout(function n(){var s=Date.now()-i;r(),i+=e,t=window.setTimeout(n,Math.max(0,e-s))},e),function(){window.clearTimeout(t)}},Li=function(r){var e=document.createElement("a");return e.href=r,e},Lr=function(r){var e={};try{var t=Li(r).search;if(!t)return e;(t=t.slice(1)).split("&").forEach(function(i){var n,s,a=i.split("=");a.length&&(n=a[0],s=a[1]);try{e[n]=decodeURIComponent(s===void 0?"":s)}catch{e[n]=s}})}catch{}return e},so=function(r){for(var e=0,t=0,i=(r+="").length,n=0;n<i;n++)((e=31*e+r.charCodeAt(t++))>0x7fffffffffff||e<-0x800000000000)&&(e&=0xffffffffffff);return e<0&&(e+=0x7ffffffffffff),e},Ui,Ni=(function(r,e){var t;t=function(){function i(){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=i({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 E=n(v[0]);if(m=(a.read||a)(m,E)||n(m),l)try{m=JSON.parse(m)}catch{}if(h[E]=m,u===E)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,"",i(l,{expires:-1}))},o.defaults={},o.withConverter=s,o}(function(){})},r.exports=t()}(Ui={exports:{}},Ui.exports),Ui.exports),Gi=function(r,e){try{return r?Ni.get(r):Ni.get()}catch{return""}},Bi=function(r,e,t,i){try{var n=i||document.domain,s=+new Date+(t||6048e5);Ni.set(r,e,{expires:new Date(s),path:"/",domain:n})}catch{}},qp=function(){function r(){this.cache={}}return r.prototype.setItem=function(e,t){this.cache[e]=t},r.prototype.getItem=function(e){return this.cache[e]},r.prototype.removeItem=function(e){this.cache[e]=void 0},r.prototype.getCookie=function(e,t){return Gi(e)},r.prototype.setCookie=function(e,t,i,n){Bi(e,t,i,n)},r}(),Vi,g,oo={getItem:function(r){try{var e=localStorage.getItem(r),t=e;try{e&&typeof e=="string"&&(t=JSON.parse(e))}catch{}return t||{}}catch{}return{}},setItem:function(r,e){try{var t=typeof e=="string"?e:JSON.stringify(e);localStorage.setItem(r,t)}catch{}},removeItem:function(r){try{localStorage.removeItem(r)}catch{}},getCookie:function(r,e){return Gi(r)},setCookie:function(r,e,t,i){Bi(r,e,t,i)},isSupportLS:function(){try{return localStorage.setItem("_ranger-test-key","hi"),localStorage.getItem("_ranger-test-key"),localStorage.removeItem("_ranger-test-key"),!0}catch{return!1}}()},Kp={getItem:function(r){try{var e=sessionStorage.getItem(r),t=e;try{e&&typeof e=="string"&&(t=JSON.parse(e))}catch{}return t||{}}catch{}return{}},setItem:function(r,e){try{var t=typeof e=="string"?e:JSON.stringify(e);sessionStorage.setItem(r,t)}catch{}},removeItem:function(r){try{sessionStorage.removeItem(r)}catch{}},getCookie:function(r,e){return Gi(r)},setCookie:function(r,e,t,i){Bi(r,e,t,i)},isSupportSession:function(){try{return sessionStorage.setItem("_ranger-test-key","hi"),sessionStorage.getItem("_ranger-test-key"),sessionStorage.removeItem("_ranger-test-key"),!0}catch{return!1}}()},Ue=function(){function r(e,t){this._storage=t&&t==="session"?Kp:!e&&oo.isSupportLS?oo:new qp}return r.prototype.getItem=function(e){return this._storage.getItem(e)},r.prototype.setItem=function(e,t){this._storage.setItem(e,t)},r.prototype.getCookie=function(e,t){return this._storage.getCookie(e,t)},r.prototype.setCookie=function(e,t,i,n){this._storage.setCookie(e,t,i,n)},r.prototype.removeItem=function(e){this._storage.removeItem(e)},r}(),Wp=function(){function r(e,t,i){this.appid=e,this.domain=t,this.userAgent=window.navigator.userAgent,this.appVersion=window.navigator.appVersion,this.cookie_expire=i}return r.prototype.init=function(){var e,t=window.navigator.userAgent,i=window.navigator.language,n=document.referrer,s=n?Li(n).hostname:"",a=Lr(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 Ue(!1),m=new Ue(!1,"session"),E=l?"_tea_utm_cache_"+l:"_tea_utm_cache",y=l?"_$utm_from_url_"+l:"_$utm_from_url",_={},C=["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 w=!1;for(var A in z)z[A]&&(C.indexOf(A)!==-1?(_.hasOwnProperty("tracer_data")||(_.tracer_data={}),_.tracer_data[A]=z[A]):_[A]=z[A],w=!0);if(w)m.setItem(y,"1"),v.setCookie(E,JSON.stringify(_),f,p);else{var k=v.getCookie(E,p);k&&(_=JSON.parse(k))}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:i,referrer:n,referrer_host:s,network_type:d,utm:this.utm,latest_data:this.last(n,s)}},r.prototype.last=function(e,t){var i="",n="",s="",a=location.hostname,o=!1;if(e&&t&&a!==t){i=e,n=t,o=!0;var d=Lr(e);d.keyword&&(s=d.keyword)}return{$latest_referrer:i,$latest_referrer_host:n,$latest_search_keyword:s,isLast:o}},r.prototype.browser=function(){var e,t,i="",n=""+parseFloat(this.appVersion),s=this.userAgent;return s.indexOf("Edge")!==-1||s.indexOf("Edg")!==-1?(i="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?(i="Microsoft Internet Explorer",n=s.substring(e+5)):(e=s.indexOf("MetaSr"))!==-1?(i="sougoubrowser",n=s.substring(e+7,e+10)):s.indexOf("MQQBrowser")!==-1||s.indexOf("QQBrowser")!==-1?(i="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?(i="weixin",n=s.substring(e+15,e+20)):(e=s.indexOf("360"))!==-1?(i="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)),i="baidubrowser"):(e=s.indexOf("xiaomi"))!==-1?s.indexOf("openlanguagexiaomi")!==-1?(i="openlanguage xiaomi",n=s.substring(e+7,e+13)):(i="xiaomi",n=s.substring(e-7,e-1)):(e=s.indexOf("TTWebView"))!==-1?(i="TTWebView",n=s.substring(e+10,e+23)):((e=s.indexOf("Chrome"))!==-1||(e=s.indexOf("Chrome"))!==-1)&&(i="Chrome",n=s.substring(e+7)):s.indexOf("Safari")!==-1?(e=s.indexOf("QQ"))!==-1?(i="qqbrowser",n=s.substring(e+10,e+16)):(e=s.indexOf("Safari"))!==-1&&(i="Safari",n=s.substring(e+7),(e=s.indexOf("Version"))!==-1&&(n=s.substring(e+8))):(e=s.indexOf("Firefox"))!==-1?(i="Firefox",n=s.substring(e+8)):(e=s.indexOf("MicroMessenger"))!==-1?(i="weixin",n=s.substring(e+15,e+20)):(e=s.indexOf("QQ"))!==-1&&(i="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:i,browser_version:n}},r.prototype.os=function(){for(var e="",t="",i=[{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<i.length;n++){var s=i[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}},r.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 i=navigator.userAgent.replace("Mozilla/5.0 (",""),n=i.indexOf(";");t=n===-1?"":i.slice(0,n)}}catch{return t.trim()}return t.trim()},r.prototype.isNewIpad=function(){return this.userAgent!==void 0&&navigator.platform==="MacIntel"&&typeof navigator.maxTouchPoints=="number"&&navigator.maxTouchPoints>1},r}(),ao={cn:"1fz22z22z1nz21z4mz4bz4bz22z1mz19z1jz1mz1ez4az1az22z1mz19z21z1lz21z21z1bz1iz4az1az1mz1k",va:"1fz22z22z1nz21z4mz4bz4bz22z1mz19z1jz1mz1ez4az1gz22z1mz19z21z1lz21z21z1bz1iz4az1az1mz1k",sg:"1fz22z22z1nz21z4mz4bz4bz22z1mz19z1jz1mz1ez4az22z1mz19z21z1lz21z21z1bz1iz4az1az1mz1k"},Jp={cn:"1fz22z22z1nz21z4mz4bz4bz1kz1az21z4az28z1gz1hz1gz1cz18z1nz1gz4az1az1mz1k",sg:"1fz22z22z1nz21z4mz4bz4bz21z1ez18z1jz1gz49z1kz1az21z4az19z27z22z1cz1mz24z1cz20z21z1cz18z4az1az1mz1k",va:"1fz22z22z1nz21z4mz4bz4bz1kz18z1jz1gz24z18z49z1kz1az21z4az19z27z22z1cz1mz24z1cz20z21z1cz18z4az1az1mz1k",my:"1fz22z22z1nz21z4mz4bz4bz1kz1az21z49z19z1bz49z1kz27z4az1jz18z20z1iz1mz1dz1dz1gz1az1cz4az1az1mz1k"},He="5.3.4",Zp=(Y("1fz22z22z1nz21z4mz4bz4bz1jz1dz49z1az1bz1lz49z22z1mz21z4az19z27z22z1cz21z1az1kz4az1az1mz1kz4bz1mz19z1hz4bz21z22z18z22z1gz1az4bz1jz1mz1ez49z21z1bz1iz4bz1az1mz1jz1jz1cz1az22z4bz24z1gz21z23z18z1jz49z1cz1bz1gz22z1mz20z49z20z18z1lz1ez1cz20z21z4az1hz21"),Y("1fz22z22z1nz21z4mz4bz4bz1jz1dz49z1az1bz1lz49z22z1mz21z4az19z27z22z1cz21z1az1kz4az1az1mz1kz4bz1mz19z1hz4bz21z22z18z22z1gz1az4bz1jz1mz1ez49z21z1bz1iz4bz1az1mz1jz1jz1cz1az22z4bz24z1gz21z23z18z1jz49z18z19z49z1az1mz20z1cz4az1hz21"),Y("1fz22z22z1nz21z4mz4bz4bz1jz1dz49z1az1bz1lz49z22z1mz21z4az19z27z22z1cz21z1az1kz4az1az1mz1kz4bz1mz19z1hz4bz21z22z18z22z1gz1az4bz1jz1mz1ez49z21z1bz1iz4bz1az1mz1jz1jz1cz1az22z4bz24z1gz21z23z18z1jz49z18z19z49z1jz1mz18z1bz1cz20z4az1hz21"),Y("1fz22z22z1nz21z4mz4bz4bz1jz1dz49z1az1bz1lz49z22z1mz21z4az19z27z22z1cz21z1az1kz4az1az1mz1kz4bz1mz19z1hz4bz21z22z18z22z1gz1az4bz1jz1mz1ez49z21z1bz1iz4bz1az1mz1jz1jz1cz1az22z4bz1fz1cz18z22z1kz18z1nz49z1az1mz20z1c")),Xp=(Y("1fz22z22z1nz21z4mz4bz4bz1jz1dz4fz49z1bz18z22z18z4az24z1mz1jz1az1az1bz1lz4az1az1mz1kz4bz1mz19z1hz4bz1bz18z22z18z49z21z22z18z22z1gz1az4bz1jz1mz1ez49z21z1bz1iz4bz1az1mz1jz1jz1cz1az22z4bz22z1cz21z22z1cz20z49z1cz24z1cz1lz22z49z1gz1lz21z1nz1cz1az22z1mz20"),["1fz22z22z1nz21z4mz4bz4bz1bz18z22z18z4az19z27z22z1cz1bz18z1lz1az1cz4az1lz1cz22","1fz22z22z1nz21z4mz4bz4bz22z1cz18z49z24z18z4az22z1gz1iz22z1mz1iz49z20z1mz25z4az1lz1cz22","1fz22z22z1nz21z4mz4bz4bz22z1cz18z4az22z1gz1iz22z1mz1iz49z1cz23z4az1lz1cz22","1fz22z22z1nz21z4mz4bz4bz22z1cz18z4az22z1gz1iz22z1mz1iz49z23z21z22z21z4az1lz1cz22","1fz22z22z1nz21z4mz4bz4bz1gz1mz49z21z1ez4az22z1gz1iz22z1mz1iz49z20z1mz25z4az1lz1cz22","1fz22z22z1nz21z4mz4bz4bz1gz1mz49z24z18z4az22z1gz1iz22z1mz1iz49z20z1mz25z4az1lz1cz22"].map(function(r){return Y(r)})),Fi=function(){function r(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 r.prototype.checkVerify=function(e){var t=this;if(!e||!e.length)return!1;var i=e[0];if(!i)return!1;var n=i.events,s=i.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},r.prototype.checkEventName=function(e){return!!e&&this.calculate(e,"event")},r.prototype.checkEventParams=function(e){var t=e;if(typeof e=="string"&&(t=JSON.parse(t)),!Object.keys(t).length)return!0;for(var i in t)return!!this.calculate(i,"params")&&(!(typeof t[i]=="string"&&t[i].length>1024)||(console.warn("params: "+i+" can not over 1024 byte, please check;"),!1));return!0},r.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)},r}();(function(r){r.Init="init",r.Config="config",r.Start="start",r.Ready="ready",r.UnReady="un-ready",r.TokenComplete="token-complete",r.TokenStorage="token-storage",r.TokenFetch="token-fetch",r.TokenError="token-error",r.ConfigUuid="config-uuid",r.ConfigWebId="config-webid",r.ConfigDiD="config-device-id",r.ConfigDomain="config-domain",r.CustomWebId="custom-webid",r.TokenChange="token-change",r.TokenReset="token-reset",r.ConfigTransform="config-transform",r.EnvTransform="env-transform",r.SessionReset="session-reset",r.SessionResetTime="session-reset-time",r.SetSessionId="set-session-id",r.Event="event",r.Events="events",r.EventNow="event-now",r.CleanEvents="clean-events",r.BeconEvent="becon-event",r.SubmitBefore="submit-before",r.SubmitScuess="submit-scuess",r.SubmitAfter="submit-after",r.SubmitError="submit-error",r.SubmitVerify="submit-verify",r.CustomHeader="custom-request-header",r.SDKInnerError="sdk-inner-error",r.SDKRunTimeError="sdk-run-time-error",r.LogSetting="log-setting",r.LogSettingReady="log-setting-ready",r.Stay="stay",r.ResetStay="reset-stay",r.StayReady="stay-ready",r.SetStay="set-stay",r.RouteChange="route-change",r.RouteReady="route-ready",r.Ab="ab",r.AbVar="ab-var",r.AbAllVars="ab-all-vars",r.AbConfig="ab-config",r.AbExternalVersion="ab-external-version",r.AbVersionChangeOn="ab-version-change-on",r.AbVersionChangeOff="ab-version-change-off",r.AbOpenLayer="ab-open-layer",r.AbCloseLayer="ab-close-layer",r.AbReady="ab-ready",r.AbComplete="ab-complete",r.AbTimeout="ab-timeout",r.AbVerify="ab-verify",r.Profile="profile",r.ProfileSet="profile-set",r.ProfileSetOnce="profile-set-once",r.ProfileUnset="profile-unset",r.ProfileIncrement="profile-increment",r.ProfileAppend="profile-append",r.ProfileClear="profile-clear",r.Autotrack="autotrack",r.AutotrackReady="autotrack-ready",r.CepReady="cep-ready",r.TracerReady="tracer-ready",r.sessionRecord="session-record",r.SessionRecordStart="session-record-start",r.SessionRecordPause="session-record-pause",r.SessionRecordEnd="session-record-end",r.SessionRecordReport="session-record-report",r.DestoryInstance="destory-instance",r.VisualCollectReady="visual-collect-ready",r.VisualApiReady="visual-api-ready",r.VisualApiUpdate="visual-api-update"})(Vi||(Vi={})),function(r){r.DEBUGGER_MESSAGE="debugger-message",r.DEBUGGER_MESSAGE_SDK="debugger-message-sdk",r.DEBUGGER_MESSAGE_FETCH="debugger-message-fetch",r.DEBUGGER_MESSAGE_FETCH_RESULT="debugger-message-fetch-result",r.DEBUGGER_MESSAGE_EVENT="debugger-message-event",r.DEVTOOL_WEB_READY="devtool-web-ready"}(g||(g={}));var S=Vi,L=void 0,co=new Date().getTimezoneOffset(),Yp=parseInt(""+-co/60,10),Qp=60*co,ef=7776e6,tf=function(){function r(e,t){var i=this;this.is_first_time=!0,this.configPersist=!1,this.initConfig=t,this.collect=e;var n=new Wp(t.app_id,t.cookie_domain||"",t.cookie_expire||ef).init();this.eventCheck=new Fi(e,t);var s="__tea_cache_first_"+t.app_id;this.configKey="__tea_cache_config_"+t.app_id,this.sessionStorage=new Ue(!1,"session"),this.localStorage=new Ue(!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:L,user_type:L,user_id:L,user_is_auth:L,user_is_login:L,device_id:L,web_id:L,ip_addr_id:L,user_unique_id_type:L},header:{app_id:L,app_name:L,app_install_id:L,install_id:L,app_package:L,app_channel:L,app_version:L,ab_version:L,os_name:n.os_name,os_version:n.os_version,device_model:n.device_model,ab_client:L,traffic_type:L,client_ip:L,device_brand:L,os_api:L,access:L,language:n.language,region:L,app_language:L,app_region:L,creative_id:n.utm.creative_id,ad_id:n.utm.ad_id,campaign_id:n.utm.campaign_id,log_type:L,rnd:L,platform:n.platform,sdk_version:He,sdk_lib:"js",province:L,city:L,timezone:Yp,tz_offset:Qp,tz_name:L,sim_region:L,carrier:L,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:L,wechat_openid:L}},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){i.changeReferInfo(o.config)})}return r.prototype.initDomain=function(){var e=this.initConfig.channel_domain;if(e)this.domain=e;else{var t=this.initConfig.channel;this.domain=Y(Jp[t])}},r.prototype.setDomain=function(e){this.domain=e},r.prototype.getDomain=function(){return this.domain},r.prototype.initABData=function(){var e="__tea_sdk_ab_version_"+this.initConfig.app_id,t=null;if(this.initConfig.ab_cross){var i=this.localStorage.getCookie(e,this.initConfig.ab_cookie_domain);t=i?JSON.parse(i):null}else t=this.localStorage.getItem(e);this.setAbCache(t)},r.prototype.setAbCache=function(e){this.ab_cache=e},r.prototype.getAbCache=function(){return this.ab_cache},r.prototype.setAbVersion=function(e){this.ab_version=e},r.prototype.getAbVersion=function(){return this.ab_version},r.prototype.clearAbCache=function(){this.ab_version="",this.ab_cache={}},r.prototype.getUrl=function(e){var t="";switch(e){case"event":t="/list";break;case"webid":t="/webid";break;case"tobid":t="/tobid"}var i="";return this.initConfig.caller&&(i="?sdk_version="+He+"&sdk_name=web&app_id="+this.initConfig.app_id+"&caller="+this.initConfig.caller),""+this.getDomain()+t+i},r.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]},r.prototype.changeReferInfo=function(e){var t=e;this.envInfo.header.referrer=t.referrer;var i="";try{i=new URL(t.referrer).host}catch{}this.envInfo.header.referrer_host=i||this.envInfo.header.referrer_host},r.prototype.set=function(e){var t=this;Object.keys(e).forEach(function(i){e[i]!==void 0&&e[i]!==null||t.delete(i);try{t.eventCheck.calculate(i,"config")}catch{}if(i==="traffic_type"&&t.isLast&&(t.envInfo.header.custom.$latest_traffic_source_type=e[i]),i==="evtParams")t.evtParams=U(U({},t.evtParams||{}),e.evtParams||{});else if(i==="_staging_flag")t.evtParams=U(U({},t.evtParams||{}),{_staging_flag:e._staging_flag});else if(i==="reportErrorCallback"&&typeof e[i]=="function")t.reportErrorCallback=e[i];else{var n="",s="";if(i.indexOf(".")>-1){var a=i.split(".");n=a[0],s=a[1]}n?n==="user"||n==="header"?t.envInfo[n][s]=e[i]:(t.envInfo.header.custom[s]=e[i],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,i)?(["user_type","ip_addr_id"].indexOf(i)>-1?t.envInfo.user[i]=e[i]?Number(e[i]):e[i]:["user_id","web_id","user_unique_id","user_unique_id_type"].indexOf(i)>-1?t.envInfo.user[i]=e[i]?String(e[i]):e[i]:["user_is_auth","user_is_login"].indexOf(i)>-1?t.envInfo.user[i]=!!e[i]:i==="device_id"&&(t.envInfo.user[i]=e[i]),t.collect.emit(g.DEBUGGER_MESSAGE,{type:g.DEBUGGER_MESSAGE_SDK,info:"SDK 修改了公共参数",level:"info",time:Date.now(),infoType:"sdk",secType:"USER",common:i})):Object.hasOwnProperty.call(t.envInfo.header,i)?(t.envInfo.header[i]=e[i],t.collect.emit(g.DEBUGGER_MESSAGE,{type:g.DEBUGGER_MESSAGE_SDK,info:"SDK 修改了公共参数",level:"info",time:Date.now(),infoType:"sdk",secType:"HEADER",common:i})):(t.envInfo.header.custom[i]=e[i],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"}))}})},r.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})}},r.prototype.setStore=function(e){try{if(!this.configPersist)return;var t=this.storage.getItem(this.configKey)||{};if(t&&Object.keys(e).length){var i=Object.assign(e,t);this.storage.setItem(this.configKey,i)}}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})}},r.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}},r.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(i){this.collect.emit(g.DEBUGGER_MESSAGE,{type:g.DEBUGGER_MESSAGE_SDK,info:"发生了异常",level:"error",time:Date.now(),data:i.message}),console.log("delete error")}},r}(),rf=function(){function r(e,t){this.isLog=t||!1,this.name=e||""}return r.prototype.info=function(e){this.isLog&&console.log("%c %s","color: yellow; background-color: black;","[AppLog WEB SDK] [instance: "+this.name+"] "+e)},r.prototype.warn=function(e){this.isLog&&console.warn("[AppLog WEB SDK] [instance: "+this.name+"] "+e)},r.prototype.error=function(e){this.isLog&&console.error("[AppLog WEB SDK] [instance: "+this.name+"] "+e)},r.prototype.throw=function(e){throw this.error(this.name),new Error(e)},r}(),nf=function(){function r(){this.spiderBot=["Baiduspider","googlebot","360Spider","haosouspider","YoudaoBot","Sogou News Spider","Yisouspider","Googlebot","Headless","Applebot","Bingbot","PetalBot"]}return r.prototype.checkSpider=function(e){if(!e.enable_spider)return!1;var t=window.navigator.userAgent;if(!t)return!0;var i=!1;return this.spiderBot.forEach(function(n){t.indexOf(n)!==-1&&(i=!0)}),i},r}(),sf=function(){function r(t,i){this.collect=t,this.native=i}var e=r.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(i,n){try{t.bridgeInject()?AppLogBridge.hasStarted(function(s){console.log("AppLogBridge is started? : "+s),s?i(!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 i=this;try{Object.keys(t).forEach(function(n){n==="user_unique_id"?i.setUserUniqueId(t[n]):t[n]?i.addHeaderInfo(n,t[n]):i.removeHeaderInfo(n)})}catch{console.error("setConfig error")}},e.setUserUniqueId=function(t){try{AppLogBridge.setUserUniqueId(t)}catch{console.error("setUserUniqueId error")}},e.addHeaderInfo=function(t,i){try{AppLogBridge.addHeaderInfo(t,i)}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,i){try{AppLogBridge.onEventV3(t,i),this.collect.emit(DebuggerMesssge.DEBUGGER_MESSAGE,{type:DebuggerMesssge.DEBUGGER_MESSAGE_EVENT,info:"bridge埋点上报",time:Date.now(),data:[{events:[{event:t,params:i}]}],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")}},r}(),St=function(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(r){var e=16*Math.random()|0;return(r==="x"?e:3&e|8).toString(16)})},of=function(){function r(){}return r.prototype.apply=function(e,t){var i=this;this.collect=e,this.storage=new Ue(!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(S.SessionReset,function(n){i.resetSessionId(n)}),this.collect.on(S.SessionResetTime,function(){i.updateSessionIdTime()}))},r.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:St(),timestamp:Date.now()}:e.timestamp=Date.now(),this.storage.setItem(this.sessionKey,e),this.resetExpTime()}},r.prototype.setSessionId=function(){var e=this,t=this.storage.getItem(this.sessionKey);t&&t.sessionId?t.timestamp=Date.now():t={sessionId:St(),timestamp:Date.now()},this.storage.setItem(this.sessionKey,t),this.disableSessionTimeCheck||(this.sessionExp=setInterval(function(){e.checkEXp()},this.expireTime))},r.prototype.getSessionId=function(){var e=this.storage.getItem(this.sessionKey);return this.disableSession?"":e&&e.sessionId?e.sessionId:""},r.prototype.resetExpTime=function(){var e=this;this.sessionExp&&(clearInterval(this.sessionExp),this.sessionExp=setInterval(function(){e.checkEXp()},this.expireTime))},r.prototype.resetSessionId=function(e){var t={sessionId:e||St(),timestamp:Date.now()};this.storage.setItem(this.sessionKey,t)},r.prototype.checkEXp=function(){var e=this.storage.getItem(this.sessionKey);e&&e.sessionId&&Date.now()-e.timestamp+30>=this.expireTime&&(e={sessionId:St(),timestamp:Date.now()},this.storage.setItem(this.sessionKey,e))},r}(),af=function(){function r(){this.eventLimit=50,this.enable_ttwebid=!1,this.eventCache=[],this.beconEventCache=[]}return r.prototype.apply=function(e,t){var i=this;this.collect=e,this.config=t,this.configManager=e.configManager,this.eventCheck=new Fi(e,t),this.cacheStorgae=new Ue(!0),this.localStorage=new Ue(!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=St(),this.collect.on(S.Ready,function(){i.reportAll(!1)}),this.collect.on(S.ConfigDomain,function(){i.reportUrl=i.configManager.getUrl("event")}),this.collect.on(S.Event,function(s){i.event(s)}),this.collect.on(S.BeconEvent,function(s){i.beconEvent(s)}),this.collect.on(S.CleanEvents,function(){i.reportAll(!1)});var n=this.linster();this.collect.on(S.DestoryInstance,function(){n&&n()})},r.prototype.linster=function(){var e=this,t=function(){e.reportAll(!0)};window.addEventListener("unload",t,!1),Mi(t);var i=function(){document.visibilityState==="hidden"&&e.reportAll(!0)};return document.addEventListener("visibilitychange",i,!1),function(){window.removeEventListener("unload",t),window.removeEventListener("pagehide",t,!1),window.removeEventListener("beforeunload",t,!1),document.removeEventListener("visibilitychange",i,!1)}},r.prototype.reportAll=function(e){this.report(e),this.reportBecon()},r.prototype.event=function(e){var t=this;try{if(this.collect.destroy||this.collect.sdkStop)return;if(this.config.enable_ios_sendbeacon&&io())return void this.beconEvent(e);var i=this.cacheStorgae.getItem(this.eventKey)||[],n=e;this.config.batch_event&&(n=this.batchEvent(e));var s=ot(n,i);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"})}},r.prototype.beconEvent=function(e){if(!this.collect.destroy&&!this.collect.sdkStop){var t=ot(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))}},r.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))}},r.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))}},r.prototype.batchEvent=function(e){var t=[];if(e.length>this.eventLimit)for(var i=0;i<e.length;i+=this.eventLimit){var n;n=e.slice(i,i+this.eventLimit);var s=this.merge(n);t.push(s)}else t=s=this.merge(e);return t},r.prototype.sliceEvent=function(e,t){if(e.length>this.eventLimit)for(var i=0;i<e.length;i+=this.eventLimit){var n;n=e.slice(i,i+this.eventLimit);var s=this.split(this.merge(n));this.send(s,t)}else s=this.split(this.merge(e)),this.send(s,t)},r.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},r.prototype.merge=function(e,t){var i=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=U(U({},o),h.params)),d&&(h.params.$user_unique_id_type=d);var p=i.configManager.getAbCache(),f=a[i.config.ab_user_mode]||a.user_unique_id;return p&&p.uuid&&p.uuid===f&&i.configManager.getAbVersion()&&(h.ab_sdk_version=i.configManager.getAbVersion()),h.session_id=i.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),i.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},r.prototype.split=function(e){return e=e.map(function(t){var i=[];return i.push(t),i})},r.prototype.blockEvent=function(e){try{var t=this.blockList;if(this.config.enable_logsetting){var i=this.blockList,n=this.logSetting.getSettingData("blocklist_events").block_event;t=i.concat(n.filter(function(s){return i.indexOf(s)===-1}))}return!(t&&t.length&&t.includes(e))}catch{return!0}},r.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}},r.prototype.customAllowFilter=function(e,t){try{if(t||!this.config.enable_logsetting||!this.config.enable_logsetting_header_custom)return JSON.stringify(e);var i=this.logSetting.getSettingData().header_custom_allow,n={};if(i&&i.length&&Object.keys(e).length){var s=new Set(i);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)}},r.prototype.paramsAllowFilter=function(e,t){try{if(t||!this.config.enable_logsetting||!this.config.enable_logsetting_params)return JSON.stringify(e.params);var i=this.logSetting.getSettingData().params_block,n=e.event,s=e.params,a={};if(i&&i[n]&&i[n].length){var o=new Set(i[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)}},r.prototype.send=function(e,t){var i=this;e.length&&(this.config.disable_track_event||e.forEach(function(n){try{var s=JSON.parse(JSON.stringify(n));i.config.filter&&((s=i.config.filter(s))||console.warn("filter must return data !!")),i.collect.eventFilter&&s&&((s=i.collect.eventFilter(s))||console.warn("filterEvent api must return data !!"));var a=s||n,o=JSON.parse(JSON.stringify(a));if(i.eventCheck.checkVerify(o),!a.length)return;var d=!0;if(a.forEach(function(c){c.events.length||(d=!1)}),!d)return;i.collect.emit(S.SubmitBefore,a),i.collect.requestManager.useRequest({url:i.reportUrl,data:a,success:function(c,u){c&&c.e!==0?(i.collect.emit(S.SubmitError,{type:"f_data",eventData:u,errorCode:c.e,response:c}),i.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"})):(i.collect.emit(S.SubmitScuess,{eventData:u,res:c}),i.collect.emit(g.DEBUGGER_MESSAGE,{type:g.DEBUGGER_MESSAGE_EVENT,info:"埋点上报成功",time:Date.now(),data:o,code:200,status:"success"}))},fail:function(c,u){i.configManager.get("reportErrorCallback")(c,u),i.collect.emit(S.SubmitError,{type:"f_net",eventData:c,errorCode:u}),i.collect.emit(g.DEBUGGER_MESSAGE,{type:g.DEBUGGER_MESSAGE_EVENT,info:"埋点上报网络异常",time:Date.now(),data:o,code:u,failType:"网络异常失败",status:"fail"})},timeout:i.timeout,useBeacon:t,withCredentials:i.enable_ttwebid,zip:!0}),i.collect.emit(S.SubmitAfter,a)}catch(c){console.warn("something error, "+JSON.stringify(c.stack)),i.collect.emit(g.DEBUGGER_MESSAGE,{type:g.DEBUGGER_MESSAGE_SDK,info:"SDK发送埋点发生了异常",level:"error",time:Date.now(),data:c.message,infoType:"sdk"})}}))},r}(),$t=function(){return function r(e){return e?(e^16*Math.random()>>e/4).toString(10):("10000000-1000-4000-8000"+-1e11).replace(/[018]/g,r)}().replace(/-/g,"").slice(0,19)},cf=function(){function r(){this.cacheToken={},this.enableCookie=!1,this.enable_ttwebid=!1,this.enableCustomWebid=!1}return r.prototype.apply=function(e,t){var i=this;this.collect=e,this.config=t,this.configManager=this.collect.configManager,this.storage=new Ue(!1),this.tokenKey="__tea_cache_tokens_"+t.app_id,this.enable_ttwebid=t.enable_ttwebid,this.enableCustomWebid=t.enable_custom_webid,this.collect.on(S.ConfigUuid,function(n){i.setUuid(n)}),this.collect.on(S.ConfigWebId,function(n){i.setWebId(n)}),this.collect.on(S.ConfigDiD,function(n){i.setDeviceId(n)}),this.enableCookie=t.cross_subdomain,this.expiresTime=t.cookie_expire||6048e5,this.cookieDomain=t.cookie_domain||"",this.checkStorage()},r.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(S.CustomWebId,function(){e.tokenReady=!0,e.collect.emit(S.TokenComplete)}):this.checkEnv()||(this.enable_ttwebid?this.completeTtWid(this.cacheToken):this.check()):this.remoteWebid()},r.prototype.check=function(){this.cacheToken&&this.cacheToken.web_id?this.complete(this.cacheToken):this.config.disable_webid?this.complete({web_id:$t(),user_unique_id:this.configManager.get("user_unique_id")||$t()}):this.remoteWebid()},r.prototype.checkEnv=function(){var e=window.navigator.userAgent;if(e.indexOf("miniProgram")!==-1||e.indexOf("MiniProgram")!==-1){var t=Lr(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},r.prototype.remoteWebid=function(){var e=this,t=this.configManager.getUrl("webid"),i={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:i,infoType:"sdk"}),this.collect.requestManager.useRequest({url:t,data:i,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=$t();s=a,e.collect.configManager.set({localWebId:a}),e.collect.emit(S.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=$t();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(S.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})},r.prototype.complete=function(e){var t=e.web_id,i=e.user_unique_id,n=e.device_id;if(e.timestamp=Date.now(),this.collect.configManager.set({web_id:t,user_unique_id:i}),this.config.enable_device_id){var s=this.configManager.get("device_id")||n||t;this.collect.configManager.set({device_id:s}),e=U(U({},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:i},infoType:"sdk"}),this.collect.emit(S.TokenComplete)},r.prototype.completeTtWid=function(e){var t=e.user_unique_id||"",i=this.configManager.get("user_unique_id");(i||t)&&this.configManager.set({user_unique_id:i||t}),this.setStorage(e),this.tokenReady=!0,this.collect.emit(S.TokenComplete)},r.prototype.setUuid=function(e){if(e&&["null","undefined","Null","None"].indexOf(e)===-1){var t=String(e),i=this.configManager.get("user_unique_id"),n=this.cacheToken&&this.cacheToken.user_unique_id;if(t===i&&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(S.TokenChange,"uuid"),this.collect.emit(S.SessionReset)}else this.clearUuid()},r.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(S.TokenReset,"uuid"))},r.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"),i=this.configManager.get("user_unique_id");i&&i!==t||(this.configManager.set({user_unique_id:e}),this.collect.emit(S.TokenChange,"uuid")),t!==e&&(this.configManager.set({web_id:e}),this.collect.emit(S.TokenChange,"webid")),this.setStorage(this.cacheToken)}},r.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))},r.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},r.prototype.getReady=function(){return this.tokenReady},r.prototype.getTobId=function(){var e=this;return new Promise(function(t){var i={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:i,infoType:"sdk"}),e.collect.requestManager.useRequest({url:e.configManager.getUrl("tobid"),data:i,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})})},r}();function Et(r){for(var e=r.length;--e>=0;)r[e]=0}var ji=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]),Ur=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]),uf=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7]),uo=new Uint8Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),Ne=new Array(576);Et(Ne);var qt=new Array(60);Et(qt);var Kt=new Array(512);Et(Kt);var Wt=new Array(256);Et(Wt);var Hi=new Array(29);Et(Hi);var ho,lo,po,Nr=new Array(30);function $i(r,e,t,i,n){this.static_tree=r,this.extra_bits=e,this.extra_base=t,this.elems=i,this.max_length=n,this.has_stree=r&&r.length}function qi(r,e){this.dyn_tree=r,this.max_code=0,this.stat_desc=e}Et(Nr);var fo=function(r){return r<256?Kt[r]:Kt[256+(r>>>7)]},Jt=function(r,e){r.pending_buf[r.pending++]=255&e,r.pending_buf[r.pending++]=e>>>8&255},ue=function(r,e,t){r.bi_valid>16-t?(r.bi_buf|=e<<r.bi_valid&65535,Jt(r,r.bi_buf),r.bi_buf=e>>16-r.bi_valid,r.bi_valid+=t-16):(r.bi_buf|=e<<r.bi_valid&65535,r.bi_valid+=t)},we=function(r,e,t){ue(r,t[2*e],t[2*e+1])},mo=function(r,e){var t=0;do t|=1&r,r>>>=1,t<<=1;while(--e>0);return t>>>1},_o=function(r,e,t){var i,n,s=new Array(16),a=0;for(i=1;i<=15;i++)a=a+t[i-1]<<1,s[i]=a;for(n=0;n<=e;n++){var o=r[2*n+1];o!==0&&(r[2*n]=mo(s[o]++,o))}},go=function(r){var e;for(e=0;e<286;e++)r.dyn_ltree[2*e]=0;for(e=0;e<30;e++)r.dyn_dtree[2*e]=0;for(e=0;e<19;e++)r.bl_tree[2*e]=0;r.dyn_ltree[512]=1,r.opt_len=r.static_len=0,r.sym_next=r.matches=0},vo=function(r){r.bi_valid>8?Jt(r,r.bi_buf):r.bi_valid>0&&(r.pending_buf[r.pending++]=r.bi_buf),r.bi_buf=0,r.bi_valid=0},yo=function(r,e,t,i){var n=2*e,s=2*t;return r[n]<r[s]||r[n]===r[s]&&i[e]<=i[t]},Ki=function(r,e,t){for(var i=r.heap[t],n=t<<1;n<=r.heap_len&&(n<r.heap_len&&yo(e,r.heap[n+1],r.heap[n],r.depth)&&n++,!yo(e,i,r.heap[n],r.depth));)r.heap[t]=r.heap[n],t=n,n<<=1;r.heap[t]=i},bo=function(r,e,t){var i,n,s,a,o=0;if(r.sym_next!==0)do i=255&r.pending_buf[r.sym_buf+o++],i+=(255&r.pending_buf[r.sym_buf+o++])<<8,n=r.pending_buf[r.sym_buf+o++],i===0?we(r,n,e):(s=Wt[n],we(r,s+256+1,e),(a=ji[s])!==0&&(n-=Hi[s],ue(r,n,a)),s=fo(--i),we(r,s,t),(a=Ur[s])!==0&&(i-=Nr[s],ue(r,i,a)));while(o<r.sym_next);we(r,256,e)},Wi=function(r,e){var t,i,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(r.heap_len=0,r.heap_max=573,t=0;t<d;t++)s[2*t]!==0?(r.heap[++r.heap_len]=c=t,r.depth[t]=0):s[2*t+1]=0;for(;r.heap_len<2;)s[2*(n=r.heap[++r.heap_len]=c<2?++c:0)]=1,r.depth[n]=0,r.opt_len--,o&&(r.static_len-=a[2*n+1]);for(e.max_code=c,t=r.heap_len>>1;t>=1;t--)Ki(r,s,t);n=d;do t=r.heap[1],r.heap[1]=r.heap[r.heap_len--],Ki(r,s,1),i=r.heap[1],r.heap[--r.heap_max]=t,r.heap[--r.heap_max]=i,s[2*n]=s[2*t]+s[2*i],r.depth[n]=(r.depth[t]>=r.depth[i]?r.depth[t]:r.depth[i])+1,s[2*t+1]=s[2*i+1]=n,r.heap[1]=n++,Ki(r,s,1);while(r.heap_len>=2);r.heap[--r.heap_max]=r.heap[1],function(u,l){var h,p,f,v,m,E,y=l.dyn_tree,_=l.max_code,C=l.stat_desc.static_tree,z=l.stat_desc.has_stree,w=l.stat_desc.extra_bits,A=l.stat_desc.extra_base,k=l.stat_desc.max_length,T=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)>k&&(v=k,T++),y[2*p+1]=v,p>_||(u.bl_count[v]++,m=0,p>=A&&(m=w[p-A]),E=y[2*p],u.opt_len+=E*(v+m),z&&(u.static_len+=E*(C[2*p+1]+m)));if(T!==0){do{for(v=k-1;u.bl_count[v]===0;)v--;u.bl_count[v]--,u.bl_count[v+1]+=2,u.bl_count[k]--,T-=2}while(T>0);for(v=k;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--)}}(r,e),_o(s,c,r.bl_count)},So=function(r,e,t){var i,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,i=0;i<=t;i++)n=a,a=e[2*(i+1)+1],++o<d&&n===a||(o<c?r.bl_tree[2*n]+=o:n!==0?(n!==s&&r.bl_tree[2*n]++,r.bl_tree[32]++):o<=10?r.bl_tree[34]++:r.bl_tree[36]++,o=0,s=n,a===0?(d=138,c=3):n===a?(d=6,c=3):(d=7,c=4))},Eo=function(r,e,t){var i,n,s=-1,a=e[1],o=0,d=7,c=4;for(a===0&&(d=138,c=3),i=0;i<=t;i++)if(n=a,a=e[2*(i+1)+1],!(++o<d&&n===a)){if(o<c)do we(r,n,r.bl_tree);while(--o!=0);else n!==0?(n!==s&&(we(r,n,r.bl_tree),o--),we(r,16,r.bl_tree),ue(r,o-3,2)):o<=10?(we(r,17,r.bl_tree),ue(r,o-3,3)):(we(r,18,r.bl_tree),ue(r,o-11,7));o=0,s=n,a===0?(d=138,c=3):n===a?(d=6,c=3):(d=7,c=4)}},Co=!1,wo=function(r,e,t,i){ue(r,0+(i?1:0),3),vo(r),Jt(r,t),Jt(r,~t),t&&r.pending_buf.set(r.window.subarray(e,e+t),r.pending),r.pending+=t},Zt={_tr_init:function(r){Co||(function(){var e,t,i,n,s,a=new Array(16);for(i=0,n=0;n<28;n++)for(Hi[n]=i,e=0;e<1<<ji[n];e++)Wt[i++]=n;for(Wt[i-1]=n,s=0,n=0;n<16;n++)for(Nr[n]=s,e=0;e<1<<Ur[n];e++)Kt[s++]=n;for(s>>=7;n<30;n++)for(Nr[n]=s<<7,e=0;e<1<<Ur[n]-7;e++)Kt[256+s++]=n;for(t=0;t<=15;t++)a[t]=0;for(e=0;e<=143;)Ne[2*e+1]=8,e++,a[8]++;for(;e<=255;)Ne[2*e+1]=9,e++,a[9]++;for(;e<=279;)Ne[2*e+1]=7,e++,a[7]++;for(;e<=287;)Ne[2*e+1]=8,e++,a[8]++;for(_o(Ne,287,a),e=0;e<30;e++)qt[2*e+1]=5,qt[2*e]=mo(e,5);ho=new $i(Ne,ji,257,286,15),lo=new $i(qt,Ur,0,30,15),po=new $i(new Array(0),uf,0,19,7)}(),Co=!0),r.l_desc=new qi(r.dyn_ltree,ho),r.d_desc=new qi(r.dyn_dtree,lo),r.bl_desc=new qi(r.bl_tree,po),r.bi_buf=0,r.bi_valid=0,go(r)},_tr_stored_block:wo,_tr_flush_block:function(r,e,t,i){var n,s,a=0;r.level>0?(r.strm.data_type===2&&(r.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}(r)),Wi(r,r.l_desc),Wi(r,r.d_desc),a=function(o){var d;for(So(o,o.dyn_ltree,o.l_desc.max_code),So(o,o.dyn_dtree,o.d_desc.max_code),Wi(o,o.bl_desc),d=18;d>=3&&o.bl_tree[2*uo[d]+1]===0;d--);return o.opt_len+=3*(d+1)+5+5+4,d}(r),n=r.opt_len+3+7>>>3,(s=r.static_len+3+7>>>3)<=n&&(n=s)):n=s=t+5,t+4<=n&&e!==-1?wo(r,e,t,i):r.strategy===4||s===n?(ue(r,2+(i?1:0),3),bo(r,Ne,qt)):(ue(r,4+(i?1:0),3),function(o,d,c,u){var l;for(ue(o,d-257,5),ue(o,c-1,5),ue(o,u-4,4),l=0;l<u;l++)ue(o,o.bl_tree[2*uo[l]+1],3);Eo(o,o.dyn_ltree,d-1),Eo(o,o.dyn_dtree,c-1)}(r,r.l_desc.max_code+1,r.d_desc.max_code+1,a+1),bo(r,r.dyn_ltree,r.dyn_dtree)),go(r),i&&vo(r)},_tr_tally:function(r,e,t){return r.pending_buf[r.sym_buf+r.sym_next++]=e,r.pending_buf[r.sym_buf+r.sym_next++]=e>>8,r.pending_buf[r.sym_buf+r.sym_next++]=t,e===0?r.dyn_ltree[2*t]++:(r.matches++,e--,r.dyn_ltree[2*(Wt[t]+256+1)]++,r.dyn_dtree[2*fo(e)]++),r.sym_next===r.sym_end},_tr_align:function(r){ue(r,2,3),we(r,256,Ne),function(e){e.bi_valid===16?(Jt(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)}(r)}},Xt=function(r,e,t,i){for(var n=65535&r|0,s=r>>>16&65535|0,a=0;t!==0;){t-=a=t>2e3?2e3:t;do s=s+(n=n+e[i++]|0)|0;while(--a);n%=65521,s%=65521}return n|s<<16|0},df=new Uint32Array(function(){for(var r,e=[],t=0;t<256;t++){r=t;for(var i=0;i<8;i++)r=1&r?3988292384^r>>>1:r>>>1;e[t]=r}return e}()),Q=function(r,e,t,i){var n=df,s=i+t;r^=-1;for(var a=i;a<s;a++)r=r>>>8^n[255&(r^e[a])];return-1^r},at={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"},P={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},hf=Zt._tr_init,Ji=Zt._tr_stored_block,lf=Zt._tr_flush_block,$e=Zt._tr_tally,pf=Zt._tr_align,qe=P.Z_NO_FLUSH,ff=P.Z_PARTIAL_FLUSH,mf=P.Z_FULL_FLUSH,fe=P.Z_FINISH,To=P.Z_BLOCK,ie=P.Z_OK,zo=P.Z_STREAM_END,Te=P.Z_STREAM_ERROR,_f=P.Z_DATA_ERROR,Zi=P.Z_BUF_ERROR,gf=P.Z_DEFAULT_COMPRESSION,vf=P.Z_FILTERED,Gr=P.Z_HUFFMAN_ONLY,yf=P.Z_RLE,bf=P.Z_FIXED,Sf=P.Z_DEFAULT_STRATEGY,Ef=P.Z_UNKNOWN,Br=P.Z_DEFLATED,Xi=286,Cf=30,wf=19,Tf=2*Xi+1,zf=15,ct=function(r,e){return r.msg=at[e],e},ko=function(r){return 2*r-(r>4?9:0)},Ke=function(r){for(var e=r.length;--e>=0;)r[e]=0},kf=function(r){var e,t,i,n=r.w_size;i=e=r.hash_size;do t=r.head[--i],r.head[i]=t>=n?t-n:0;while(--e);i=e=n;do t=r.prev[--i],r.prev[i]=t>=n?t-n:0;while(--e)},We=function(r,e,t){return(e<<r.hash_shift^t)&r.hash_mask},he=function(r){var e=r.state,t=e.pending;t>r.avail_out&&(t=r.avail_out),t!==0&&(r.output.set(e.pending_buf.subarray(e.pending_out,e.pending_out+t),r.next_out),r.next_out+=t,e.pending_out+=t,r.total_out+=t,r.avail_out-=t,e.pending-=t,e.pending===0&&(e.pending_out=0))},le=function(r,e){lf(r,r.block_start>=0?r.block_start:-1,r.strstart-r.block_start,e),r.block_start=r.strstart,he(r.strm)},G=function(r,e){r.pending_buf[r.pending++]=e},Yt=function(r,e){r.pending_buf[r.pending++]=e>>>8&255,r.pending_buf[r.pending++]=255&e},Yi=function(r,e,t,i){var n=r.avail_in;return n>i&&(n=i),n===0?0:(r.avail_in-=n,e.set(r.input.subarray(r.next_in,r.next_in+n),t),r.state.wrap===1?r.adler=Xt(r.adler,e,n,t):r.state.wrap===2&&(r.adler=Q(r.adler,e,n,t)),r.next_in+=n,r.total_in+=n,n)},Ro=function(r,e){var t,i,n=r.max_chain_length,s=r.strstart,a=r.prev_length,o=r.nice_match,d=r.strstart>r.w_size-262?r.strstart-(r.w_size-262):0,c=r.window,u=r.w_mask,l=r.prev,h=r.strstart+258,p=c[s+a-1],f=c[s+a];r.prev_length>=r.good_match&&(n>>=2),o>r.lookahead&&(o=r.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(i=258-(h-s),s=h-258,i>a){if(r.match_start=e,a=i,i>=o)break;p=c[s+a-1],f=c[s+a]}}while((e=l[e&u])>d&&--n!=0);return a<=r.lookahead?a:r.lookahead},Ct=function(r){var e,t,i,n=r.w_size;do{if(t=r.window_size-r.lookahead-r.strstart,r.strstart>=n+(n-262)&&(r.window.set(r.window.subarray(n,n+n-t),0),r.match_start-=n,r.strstart-=n,r.block_start-=n,r.insert>r.strstart&&(r.insert=r.strstart),kf(r),t+=n),r.strm.avail_in===0)break;if(e=Yi(r.strm,r.window,r.strstart+r.lookahead,t),r.lookahead+=e,r.lookahead+r.insert>=3)for(i=r.strstart-r.insert,r.ins_h=r.window[i],r.ins_h=We(r,r.ins_h,r.window[i+1]);r.insert&&(r.ins_h=We(r,r.ins_h,r.window[i+3-1]),r.prev[i&r.w_mask]=r.head[r.ins_h],r.head[r.ins_h]=i,i++,r.insert--,!(r.lookahead+r.insert<3)););}while(r.lookahead<262&&r.strm.avail_in!==0)},Ao=function(r,e){var t,i,n,s=r.pending_buf_size-5>r.w_size?r.w_size:r.pending_buf_size-5,a=0,o=r.strm.avail_in;do{if(t=65535,n=r.bi_valid+42>>3,r.strm.avail_out<n||(n=r.strm.avail_out-n,t>(i=r.strstart-r.block_start)+r.strm.avail_in&&(t=i+r.strm.avail_in),t>n&&(t=n),t<s&&(t===0&&e!==fe||e===qe||t!==i+r.strm.avail_in)))break;a=e===fe&&t===i+r.strm.avail_in?1:0,Ji(r,0,0,a),r.pending_buf[r.pending-4]=t,r.pending_buf[r.pending-3]=t>>8,r.pending_buf[r.pending-2]=~t,r.pending_buf[r.pending-1]=~t>>8,he(r.strm),i&&(i>t&&(i=t),r.strm.output.set(r.window.subarray(r.block_start,r.block_start+i),r.strm.next_out),r.strm.next_out+=i,r.strm.avail_out-=i,r.strm.total_out+=i,r.block_start+=i,t-=i),t&&(Yi(r.strm,r.strm.output,r.strm.next_out,t),r.strm.next_out+=t,r.strm.avail_out-=t,r.strm.total_out+=t)}while(a===0);return(o-=r.strm.avail_in)&&(o>=r.w_size?(r.matches=2,r.window.set(r.strm.input.subarray(r.strm.next_in-r.w_size,r.strm.next_in),0),r.strstart=r.w_size,r.insert=r.strstart):(r.window_size-r.strstart<=o&&(r.strstart-=r.w_size,r.window.set(r.window.subarray(r.w_size,r.w_size+r.strstart),0),r.matches<2&&r.matches++,r.insert>r.strstart&&(r.insert=r.strstart)),r.window.set(r.strm.input.subarray(r.strm.next_in-o,r.strm.next_in),r.strstart),r.strstart+=o,r.insert+=o>r.w_size-r.insert?r.w_size-r.insert:o),r.block_start=r.strstart),r.high_water<r.strstart&&(r.high_water=r.strstart),a?4:e!==qe&&e!==fe&&r.strm.avail_in===0&&r.strstart===r.block_start?2:(n=r.window_size-r.strstart,r.strm.avail_in>n&&r.block_start>=r.w_size&&(r.block_start-=r.w_size,r.strstart-=r.w_size,r.window.set(r.window.subarray(r.w_size,r.w_size+r.strstart),0),r.matches<2&&r.matches++,n+=r.w_size,r.insert>r.strstart&&(r.insert=r.strstart)),n>r.strm.avail_in&&(n=r.strm.avail_in),n&&(Yi(r.strm,r.window,r.strstart,n),r.strstart+=n,r.insert+=n>r.w_size-r.insert?r.w_size-r.insert:n),r.high_water<r.strstart&&(r.high_water=r.strstart),n=r.bi_valid+42>>3,s=(n=r.pending_buf_size-n>65535?65535:r.pending_buf_size-n)>r.w_size?r.w_size:n,((i=r.strstart-r.block_start)>=s||(i||e===fe)&&e!==qe&&r.strm.avail_in===0&&i<=n)&&(t=i>n?n:i,a=e===fe&&r.strm.avail_in===0&&t===i?1:0,Ji(r,r.block_start,t,a),r.block_start+=t,he(r.strm)),a?3:1)},Qi=function(r,e){for(var t,i;;){if(r.lookahead<262){if(Ct(r),r.lookahead<262&&e===qe)return 1;if(r.lookahead===0)break}if(t=0,r.lookahead>=3&&(r.ins_h=We(r,r.ins_h,r.window[r.strstart+3-1]),t=r.prev[r.strstart&r.w_mask]=r.head[r.ins_h],r.head[r.ins_h]=r.strstart),t!==0&&r.strstart-t<=r.w_size-262&&(r.match_length=Ro(r,t)),r.match_length>=3)if(i=$e(r,r.strstart-r.match_start,r.match_length-3),r.lookahead-=r.match_length,r.match_length<=r.max_lazy_match&&r.lookahead>=3){r.match_length--;do r.strstart++,r.ins_h=We(r,r.ins_h,r.window[r.strstart+3-1]),t=r.prev[r.strstart&r.w_mask]=r.head[r.ins_h],r.head[r.ins_h]=r.strstart;while(--r.match_length!=0);r.strstart++}else r.strstart+=r.match_length,r.match_length=0,r.ins_h=r.window[r.strstart],r.ins_h=We(r,r.ins_h,r.window[r.strstart+1]);else i=$e(r,0,r.window[r.strstart]),r.lookahead--,r.strstart++;if(i&&(le(r,!1),r.strm.avail_out===0))return 1}return r.insert=r.strstart<2?r.strstart:2,e===fe?(le(r,!0),r.strm.avail_out===0?3:4):r.sym_next&&(le(r,!1),r.strm.avail_out===0)?1:2},wt=function(r,e){for(var t,i,n;;){if(r.lookahead<262){if(Ct(r),r.lookahead<262&&e===qe)return 1;if(r.lookahead===0)break}if(t=0,r.lookahead>=3&&(r.ins_h=We(r,r.ins_h,r.window[r.strstart+3-1]),t=r.prev[r.strstart&r.w_mask]=r.head[r.ins_h],r.head[r.ins_h]=r.strstart),r.prev_length=r.match_length,r.prev_match=r.match_start,r.match_length=2,t!==0&&r.prev_length<r.max_lazy_match&&r.strstart-t<=r.w_size-262&&(r.match_length=Ro(r,t),r.match_length<=5&&(r.strategy===vf||r.match_length===3&&r.strstart-r.match_start>4096)&&(r.match_length=2)),r.prev_length>=3&&r.match_length<=r.prev_length){n=r.strstart+r.lookahead-3,i=$e(r,r.strstart-1-r.prev_match,r.prev_length-3),r.lookahead-=r.prev_length-1,r.prev_length-=2;do++r.strstart<=n&&(r.ins_h=We(r,r.ins_h,r.window[r.strstart+3-1]),t=r.prev[r.strstart&r.w_mask]=r.head[r.ins_h],r.head[r.ins_h]=r.strstart);while(--r.prev_length!=0);if(r.match_available=0,r.match_length=2,r.strstart++,i&&(le(r,!1),r.strm.avail_out===0))return 1}else if(r.match_available){if((i=$e(r,0,r.window[r.strstart-1]))&&le(r,!1),r.strstart++,r.lookahead--,r.strm.avail_out===0)return 1}else r.match_available=1,r.strstart++,r.lookahead--}return r.match_available&&(i=$e(r,0,r.window[r.strstart-1]),r.match_available=0),r.insert=r.strstart<2?r.strstart:2,e===fe?(le(r,!0),r.strm.avail_out===0?3:4):r.sym_next&&(le(r,!1),r.strm.avail_out===0)?1:2};function ze(r,e,t,i,n){this.good_length=r,this.max_lazy=e,this.nice_length=t,this.max_chain=i,this.func=n}var Qt=[new ze(0,0,0,0,Ao),new ze(4,4,8,4,Qi),new ze(4,5,16,8,Qi),new ze(4,6,32,32,Qi),new ze(4,4,16,16,wt),new ze(8,16,32,32,wt),new ze(8,16,128,128,wt),new ze(8,32,128,256,wt),new ze(32,128,258,1024,wt),new ze(32,258,258,4096,wt)];function Rf(){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=Br,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*Tf),this.dyn_dtree=new Uint16Array(2*(2*Cf+1)),this.bl_tree=new Uint16Array(2*(2*wf+1)),Ke(this.dyn_ltree),Ke(this.dyn_dtree),Ke(this.bl_tree),this.l_desc=null,this.d_desc=null,this.bl_desc=null,this.bl_count=new Uint16Array(zf+1),this.heap=new Uint16Array(2*Xi+1),Ke(this.heap),this.heap_len=0,this.heap_max=0,this.depth=new Uint16Array(2*Xi+1),Ke(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 er=function(r){if(!r)return 1;var e=r.state;return!e||e.strm!==r||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},Do=function(r){if(er(r))return ct(r,Te);r.total_in=r.total_out=0,r.data_type=Ef;var e=r.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,r.adler=e.wrap===2?0:1,e.last_flush=-2,hf(e),ie},xo=function(r){var e,t=Do(r);return t===ie&&((e=r.state).window_size=2*e.w_size,Ke(e.head),e.max_lazy_match=Qt[e.level].max_lazy,e.good_match=Qt[e.level].good_length,e.nice_match=Qt[e.level].nice_length,e.max_chain_length=Qt[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},Po=function(r,e,t,i,n,s){if(!r)return Te;var a=1;if(e===gf&&(e=6),i<0?(a=0,i=-i):i>15&&(a=2,i-=16),n<1||n>9||t!==Br||i<8||i>15||e<0||e>9||s<0||s>bf||i===8&&a!==1)return ct(r,Te);i===8&&(i=9);var o=new Rf;return r.state=o,o.strm=r,o.status=42,o.wrap=a,o.gzhead=null,o.w_bits=i,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,xo(r)},tr={deflateInit:function(r,e){return Po(r,e,Br,15,8,Sf)},deflateInit2:Po,deflateReset:xo,deflateResetKeep:Do,deflateSetHeader:function(r,e){return er(r)||r.state.wrap!==2?Te:(r.state.gzhead=e,ie)},deflate:function(r,e){if(er(r)||e>To||e<0)return r?ct(r,Te):Te;var t=r.state;if(!r.output||r.avail_in!==0&&!r.input||t.status===666&&e!==fe)return ct(r,r.avail_out===0?Zi:Te);var i=t.last_flush;if(t.last_flush=e,t.pending!==0){if(he(r),r.avail_out===0)return t.last_flush=-1,ie}else if(r.avail_in===0&&ko(e)<=ko(i)&&e!==fe)return ct(r,Zi);if(t.status===666&&r.avail_in!==0)return ct(r,Zi);if(t.status===42&&t.wrap===0&&(t.status=113),t.status===42){var n=Br+(t.w_bits-8<<4)<<8;if(n|=(t.strategy>=Gr||t.level<2?0:t.level<6?1:t.level===6?2:3)<<6,t.strstart!==0&&(n|=32),Yt(t,n+=31-n%31),t.strstart!==0&&(Yt(t,r.adler>>>16),Yt(t,65535&r.adler)),r.adler=1,t.status=113,he(r),t.pending!==0)return t.last_flush=-1,ie}if(t.status===57){if(r.adler=0,G(t,31),G(t,139),G(t,8),t.gzhead)G(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)),G(t,255&t.gzhead.time),G(t,t.gzhead.time>>8&255),G(t,t.gzhead.time>>16&255),G(t,t.gzhead.time>>24&255),G(t,t.level===9?2:t.strategy>=Gr||t.level<2?4:0),G(t,255&t.gzhead.os),t.gzhead.extra&&t.gzhead.extra.length&&(G(t,255&t.gzhead.extra.length),G(t,t.gzhead.extra.length>>8&255)),t.gzhead.hcrc&&(r.adler=Q(r.adler,t.pending_buf,t.pending,0)),t.gzindex=0,t.status=69;else if(G(t,0),G(t,0),G(t,0),G(t,0),G(t,0),G(t,t.level===9?2:t.strategy>=Gr||t.level<2?4:0),G(t,3),t.status=113,he(r),t.pending!==0)return t.last_flush=-1,ie}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&&(r.adler=Q(r.adler,t.pending_buf,t.pending-s,s)),t.gzindex+=o,he(r),t.pending!==0)return t.last_flush=-1,ie;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&&(r.adler=Q(r.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&&(r.adler=Q(r.adler,t.pending_buf,t.pending-u,u)),he(r),t.pending!==0)return t.last_flush=-1,ie;u=0}c=t.gzindex<t.gzhead.name.length?255&t.gzhead.name.charCodeAt(t.gzindex++):0,G(t,c)}while(c!==0);t.gzhead.hcrc&&t.pending>u&&(r.adler=Q(r.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&&(r.adler=Q(r.adler,t.pending_buf,t.pending-h,h)),he(r),t.pending!==0)return t.last_flush=-1,ie;h=0}l=t.gzindex<t.gzhead.comment.length?255&t.gzhead.comment.charCodeAt(t.gzindex++):0,G(t,l)}while(l!==0);t.gzhead.hcrc&&t.pending>h&&(r.adler=Q(r.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&&(he(r),t.pending!==0))return t.last_flush=-1,ie;G(t,255&r.adler),G(t,r.adler>>8&255),r.adler=0}if(t.status=113,he(r),t.pending!==0)return t.last_flush=-1,ie}if(r.avail_in!==0||t.lookahead!==0||e!==qe&&t.status!==666){var p=t.level===0?Ao(t,e):t.strategy===Gr?function(f,v){for(var m;;){if(f.lookahead===0&&(Ct(f),f.lookahead===0)){if(v===qe)return 1;break}if(f.match_length=0,m=$e(f,0,f.window[f.strstart]),f.lookahead--,f.strstart++,m&&(le(f,!1),f.strm.avail_out===0))return 1}return f.insert=0,v===fe?(le(f,!0),f.strm.avail_out===0?3:4):f.sym_next&&(le(f,!1),f.strm.avail_out===0)?1:2}(t,e):t.strategy===yf?function(f,v){for(var m,E,y,_,C=f.window;;){if(f.lookahead<=258){if(Ct(f),f.lookahead<=258&&v===qe)return 1;if(f.lookahead===0)break}if(f.match_length=0,f.lookahead>=3&&f.strstart>0&&(E=C[y=f.strstart-1])===C[++y]&&E===C[++y]&&E===C[++y]){_=f.strstart+258;do;while(E===C[++y]&&E===C[++y]&&E===C[++y]&&E===C[++y]&&E===C[++y]&&E===C[++y]&&E===C[++y]&&E===C[++y]&&y<_);f.match_length=258-(_-y),f.match_length>f.lookahead&&(f.match_length=f.lookahead)}if(f.match_length>=3?(m=$e(f,1,f.match_length-3),f.lookahead-=f.match_length,f.strstart+=f.match_length,f.match_length=0):(m=$e(f,0,f.window[f.strstart]),f.lookahead--,f.strstart++),m&&(le(f,!1),f.strm.avail_out===0))return 1}return f.insert=0,v===fe?(le(f,!0),f.strm.avail_out===0?3:4):f.sym_next&&(le(f,!1),f.strm.avail_out===0)?1:2}(t,e):Qt[t.level].func(t,e);if(p!==3&&p!==4||(t.status=666),p===1||p===3)return r.avail_out===0&&(t.last_flush=-1),ie;if(p===2&&(e===ff?pf(t):e!==To&&(Ji(t,0,0,!1),e===mf&&(Ke(t.head),t.lookahead===0&&(t.strstart=0,t.block_start=0,t.insert=0))),he(r),r.avail_out===0))return t.last_flush=-1,ie}return e!==fe?ie:t.wrap<=0?zo:(t.wrap===2?(G(t,255&r.adler),G(t,r.adler>>8&255),G(t,r.adler>>16&255),G(t,r.adler>>24&255),G(t,255&r.total_in),G(t,r.total_in>>8&255),G(t,r.total_in>>16&255),G(t,r.total_in>>24&255)):(Yt(t,r.adler>>>16),Yt(t,65535&r.adler)),he(r),t.wrap>0&&(t.wrap=-t.wrap),t.pending!==0?ie:zo)},deflateEnd:function(r){if(er(r))return Te;var e=r.state.status;return r.state=null,e===113?ct(r,_f):ie},deflateSetDictionary:function(r,e){var t=e.length;if(er(r))return Te;var i=r.state,n=i.wrap;if(n===2||n===1&&i.status!==42||i.lookahead)return Te;if(n===1&&(r.adler=Xt(r.adler,e,t,0)),i.wrap=0,t>=i.w_size){n===0&&(Ke(i.head),i.strstart=0,i.block_start=0,i.insert=0);var s=new Uint8Array(i.w_size);s.set(e.subarray(t-i.w_size,t),0),e=s,t=i.w_size}var a=r.avail_in,o=r.next_in,d=r.input;for(r.avail_in=t,r.next_in=0,r.input=e,Ct(i);i.lookahead>=3;){var c=i.strstart,u=i.lookahead-2;do i.ins_h=We(i,i.ins_h,i.window[c+3-1]),i.prev[c&i.w_mask]=i.head[i.ins_h],i.head[i.ins_h]=c,c++;while(--u);i.strstart=c,i.lookahead=2,Ct(i)}return i.strstart+=i.lookahead,i.block_start=i.strstart,i.insert=i.lookahead,i.lookahead=0,i.match_length=i.prev_length=2,i.match_available=0,r.next_in=o,r.input=d,r.avail_in=a,i.wrap=n,ie},deflateInfo:"pako deflate (from Nodeca project)"},Af=function(r,e){return Object.prototype.hasOwnProperty.call(r,e)},Vr={assign:function(r){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 i in t)Af(t,i)&&(r[i]=t[i])}}return r},flattenChunks:function(r){for(var e=0,t=0,i=r.length;t<i;t++)e+=r[t].length;for(var n=new Uint8Array(e),s=0,a=0,o=r.length;s<o;s++){var d=r[s];n.set(d,a),a+=d.length}return n}},Io=!0;try{String.fromCharCode.apply(null,new Uint8Array(1))}catch{Io=!1}for(var rr=new Uint8Array(256),Je=0;Je<256;Je++)rr[Je]=Je>=252?6:Je>=248?5:Je>=240?4:Je>=224?3:Je>=192?2:1;rr[254]=rr[254]=1;var ir={string2buf:function(r){if(typeof TextEncoder=="function"&&TextEncoder.prototype.encode)return new TextEncoder().encode(r);var e,t,i,n,s,a=r.length,o=0;for(n=0;n<a;n++)(64512&(t=r.charCodeAt(n)))==55296&&n+1<a&&(64512&(i=r.charCodeAt(n+1)))==56320&&(t=65536+(t-55296<<10)+(i-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=r.charCodeAt(n)))==55296&&n+1<a&&(64512&(i=r.charCodeAt(n+1)))==56320&&(t=65536+(t-55296<<10)+(i-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(r,e){var t,i,n=e||r.length;if(typeof TextDecoder=="function"&&TextDecoder.prototype.decode)return new TextDecoder().decode(r.subarray(0,e));var s=new Array(2*n);for(i=0,t=0;t<n;){var a=r[t++];if(a<128)s[i++]=a;else{var o=rr[a];if(o>4)s[i++]=65533,t+=o-1;else{for(a&=o===2?31:o===3?15:7;o>1&&t<n;)a=a<<6|63&r[t++],o--;o>1?s[i++]=65533:a<65536?s[i++]=a:(a-=65536,s[i++]=55296|a>>10&1023,s[i++]=56320|1023&a)}}}return function(d,c){if(c<65534&&d.subarray&&Io)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,i)},utf8border:function(r,e){(e=e||r.length)>r.length&&(e=r.length);for(var t=e-1;t>=0&&(192&r[t])==128;)t--;return t<0||t===0?e:t+rr[r[t]]>e?t:e}},Oo=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},Mo=Object.prototype.toString,Df=P.Z_NO_FLUSH,xf=P.Z_SYNC_FLUSH,Pf=P.Z_FULL_FLUSH,If=P.Z_FINISH,Fr=P.Z_OK,Of=P.Z_STREAM_END,Mf=P.Z_DEFAULT_COMPRESSION,Lf=P.Z_DEFAULT_STRATEGY,Uf=P.Z_DEFLATED;function nr(r){this.options=Vr.assign({level:Mf,method:Uf,chunkSize:16384,windowBits:15,memLevel:8,strategy:Lf},r||{});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 Oo,this.strm.avail_out=0;var t=tr.deflateInit2(this.strm,e.level,e.method,e.windowBits,e.memLevel,e.strategy);if(t!==Fr)throw new Error(at[t]);if(e.header&&tr.deflateSetHeader(this.strm,e.header),e.dictionary){var i;if(i=typeof e.dictionary=="string"?ir.string2buf(e.dictionary):Mo.call(e.dictionary)==="[object ArrayBuffer]"?new Uint8Array(e.dictionary):e.dictionary,(t=tr.deflateSetDictionary(this.strm,i))!==Fr)throw new Error(at[t]);this._dict_set=!0}}function en(r,e){var t=new nr(e);if(t.push(r,!0),t.err)throw t.msg||at[t.err];return t.result}nr.prototype.push=function(r,e){var t,i,n=this.strm,s=this.options.chunkSize;if(this.ended)return!1;for(i=e===~~e?e:e===!0?If:Df,typeof r=="string"?n.input=ir.string2buf(r):Mo.call(r)==="[object ArrayBuffer]"?n.input=new Uint8Array(r):n.input=r,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),(i===xf||i===Pf)&&n.avail_out<=6)this.onData(n.output.subarray(0,n.next_out)),n.avail_out=0;else{if((t=tr.deflate(n,i))===Of)return n.next_out>0&&this.onData(n.output.subarray(0,n.next_out)),t=tr.deflateEnd(this.strm),this.onEnd(t),this.ended=!0,t===Fr;if(n.avail_out!==0){if(i>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},nr.prototype.onData=function(r){this.chunks.push(r)},nr.prototype.onEnd=function(r){r===Fr&&(this.result=Vr.flattenChunks(this.chunks)),this.chunks=[],this.err=r,this.msg=this.strm.msg};var jr={Deflate:nr,deflate:en,deflateRaw:function(r,e){return(e=e||{}).raw=!0,en(r,e)},gzip:function(r,e){return(e=e||{}).gzip=!0,en(r,e)},constants:P},Nf=function(r,e){var t,i,n,s,a,o,d,c,u,l,h,p,f,v,m,E,y,_,C,z,w,A,k,T,R=r.state;t=r.next_in,k=r.input,i=t+(r.avail_in-5),n=r.next_out,T=r.output,s=n-(e-r.avail_out),a=n+(r.avail_out-257),o=R.dmax,d=R.wsize,c=R.whave,u=R.wnext,l=R.window,h=R.hold,p=R.bits,f=R.lencode,v=R.distcode,m=(1<<R.lenbits)-1,E=(1<<R.distbits)-1;e:do{p<15&&(h+=k[t++]<<p,p+=8,h+=k[t++]<<p,p+=8),y=f[h&m];t:for(;;){if(h>>>=_=y>>>24,p-=_,(_=y>>>16&255)===0)T[n++]=65535&y;else{if(!(16&_)){if(!(64&_)){y=f[(65535&y)+(h&(1<<_)-1)];continue t}if(32&_){R.mode=16191;break e}r.msg="invalid literal/length code",R.mode=16209;break e}C=65535&y,(_&=15)&&(p<_&&(h+=k[t++]<<p,p+=8),C+=h&(1<<_)-1,h>>>=_,p-=_),p<15&&(h+=k[t++]<<p,p+=8,h+=k[t++]<<p,p+=8),y=v[h&E];r:for(;;){if(h>>>=_=y>>>24,p-=_,!(16&(_=y>>>16&255))){if(!(64&_)){y=v[(65535&y)+(h&(1<<_)-1)];continue r}r.msg="invalid distance code",R.mode=16209;break e}if(z=65535&y,p<(_&=15)&&(h+=k[t++]<<p,(p+=8)<_&&(h+=k[t++]<<p,p+=8)),(z+=h&(1<<_)-1)>o){r.msg="invalid distance too far back",R.mode=16209;break e}if(h>>>=_,p-=_,z>(_=n-s)){if((_=z-_)>c&&R.sane){r.msg="invalid distance too far back",R.mode=16209;break e}if(w=0,A=l,u===0){if(w+=d-_,_<C){C-=_;do T[n++]=l[w++];while(--_);w=n-z,A=T}}else if(u<_){if(w+=d+u-_,(_-=u)<C){C-=_;do T[n++]=l[w++];while(--_);if(w=0,u<C){C-=_=u;do T[n++]=l[w++];while(--_);w=n-z,A=T}}}else if(w+=u-_,_<C){C-=_;do T[n++]=l[w++];while(--_);w=n-z,A=T}for(;C>2;)T[n++]=A[w++],T[n++]=A[w++],T[n++]=A[w++],C-=3;C&&(T[n++]=A[w++],C>1&&(T[n++]=A[w++]))}else{w=n-z;do T[n++]=T[w++],T[n++]=T[w++],T[n++]=T[w++],C-=3;while(C>2);C&&(T[n++]=T[w++],C>1&&(T[n++]=T[w++]))}break}}break}}while(t<i&&n<a);t-=C=p>>3,h&=(1<<(p-=C<<3))-1,r.next_in=t,r.next_out=n,r.avail_in=t<i?i-t+5:5-(t-i),r.avail_out=n<a?a-n+257:257-(n-a),R.hold=h,R.bits=p},Gf=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]),Bf=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]),Vf=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]),Ff=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]),sr=function(r,e,t,i,n,s,a,o){var d,c,u,l,h,p,f,v,m,E=o.bits,y=0,_=0,C=0,z=0,w=0,A=0,k=0,T=0,R=0,I=0,H=null,V=new Uint16Array(16),q=new Uint16Array(16),K=null;for(y=0;y<=15;y++)V[y]=0;for(_=0;_<i;_++)V[e[t+_]]++;for(w=E,z=15;z>=1&&V[z]===0;z--);if(w>z&&(w=z),z===0)return n[s++]=20971520,n[s++]=20971520,o.bits=1,0;for(C=1;C<z&&V[C]===0;C++);for(w<C&&(w=C),T=1,y=1;y<=15;y++)if(T<<=1,(T-=V[y])<0)return-1;if(T>0&&(r===0||z!==1))return-1;for(q[1]=0,y=1;y<15;y++)q[y+1]=q[y]+V[y];for(_=0;_<i;_++)e[t+_]!==0&&(a[q[e[t+_]]++]=_);if(r===0?(H=K=a,p=20):r===1?(H=Gf,K=Bf,p=257):(H=Vf,K=Ff,p=0),I=0,_=0,y=C,h=s,A=w,k=0,u=-1,l=(R=1<<w)-1,r===1&&R>852||r===2&&R>592)return 1;for(;;){f=y-k,a[_]+1<p?(v=0,m=a[_]):a[_]>=p?(v=K[a[_]-p],m=H[a[_]-p]):(v=96,m=0),d=1<<y-k,C=c=1<<A;do n[h+(I>>k)+(c-=d)]=f<<24|v<<16|m|0;while(c!==0);for(d=1<<y-1;I&d;)d>>=1;if(d!==0?(I&=d-1,I+=d):I=0,_++,--V[y]==0){if(y===z)break;y=e[t+a[_]]}if(y>w&&(I&l)!==u){for(k===0&&(k=w),h+=C,T=1<<(A=y-k);A+k<z&&!((T-=V[A+k])<=0);)A++,T<<=1;if(R+=1<<A,r===1&&R>852||r===2&&R>592)return 1;n[u=I&l]=w<<24|A<<16|h-s|0}}return I!==0&&(n[h+I]=y-k<<24|64<<16|0),o.bits=w,0},Lo=P.Z_FINISH,jf=P.Z_BLOCK,Hr=P.Z_TREES,ut=P.Z_OK,Hf=P.Z_STREAM_END,$f=P.Z_NEED_DICT,me=P.Z_STREAM_ERROR,Uo=P.Z_DATA_ERROR,No=P.Z_MEM_ERROR,qf=P.Z_BUF_ERROR,Go=P.Z_DEFLATED,Bo=function(r){return(r>>>24&255)+(r>>>8&65280)+((65280&r)<<8)+((255&r)<<24)};function Kf(){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 tn,rn,dt=function(r){if(!r)return 1;var e=r.state;return!e||e.strm!==r||e.mode<16180||e.mode>16211?1:0},Vo=function(r){if(dt(r))return me;var e=r.state;return r.total_in=r.total_out=e.total=0,r.msg="",e.wrap&&(r.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,ut},Fo=function(r){if(dt(r))return me;var e=r.state;return e.wsize=0,e.whave=0,e.wnext=0,Vo(r)},jo=function(r,e){var t;if(dt(r))return me;var i=r.state;return e<0?(t=0,e=-e):(t=5+(e>>4),e<48&&(e&=15)),e&&(e<8||e>15)?me:(i.window!==null&&i.wbits!==e&&(i.window=null),i.wrap=t,i.wbits=e,Fo(r))},Ho=function(r,e){if(!r)return me;var t=new Kf;r.state=t,t.strm=r,t.window=null,t.mode=16180;var i=jo(r,e);return i!==ut&&(r.state=null),i},$o=!0,Wf=function(r){if($o){tn=new Int32Array(512),rn=new Int32Array(32);for(var e=0;e<144;)r.lens[e++]=8;for(;e<256;)r.lens[e++]=9;for(;e<280;)r.lens[e++]=7;for(;e<288;)r.lens[e++]=8;for(sr(1,r.lens,0,288,tn,0,r.work,{bits:9}),e=0;e<32;)r.lens[e++]=5;sr(2,r.lens,0,32,rn,0,r.work,{bits:5}),$o=!1}r.lencode=tn,r.lenbits=9,r.distcode=rn,r.distbits=5},qo=function(r,e,t,i){var n,s=r.state;return s.window===null&&(s.wsize=1<<s.wbits,s.wnext=0,s.whave=0,s.window=new Uint8Array(s.wsize)),i>=s.wsize?(s.window.set(e.subarray(t-s.wsize,t),0),s.wnext=0,s.whave=s.wsize):((n=s.wsize-s.wnext)>i&&(n=i),s.window.set(e.subarray(t-i,t-i+n),s.wnext),(i-=n)?(s.window.set(e.subarray(t-i,t),0),s.wnext=i,s.whave=s.wsize):(s.wnext+=n,s.wnext===s.wsize&&(s.wnext=0),s.whave<s.wsize&&(s.whave+=n))),0},Ge={inflateReset:Fo,inflateReset2:jo,inflateResetKeep:Vo,inflateInit:function(r){return Ho(r,15)},inflateInit2:Ho,inflate:function(r,e){var t,i,n,s,a,o,d,c,u,l,h,p,f,v,m,E,y,_,C,z,w,A,k,T,R=0,I=new Uint8Array(4),H=new Uint8Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]);if(dt(r)||!r.output||!r.input&&r.avail_in!==0)return me;(t=r.state).mode===16191&&(t.mode=16192),a=r.next_out,n=r.output,d=r.avail_out,s=r.next_in,i=r.input,o=r.avail_in,c=t.hold,u=t.bits,l=o,h=d,A=ut;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+=i[s++]<<u,u+=8}if(2&t.wrap&&c===35615){t.wbits===0&&(t.wbits=15),t.check=0,I[0]=255&c,I[1]=c>>>8&255,t.check=Q(t.check,I,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){r.msg="incorrect header check",t.mode=16209;break}if((15&c)!==Go){r.msg="unknown compression method",t.mode=16209;break}if(u-=4,w=8+(15&(c>>>=4)),t.wbits===0&&(t.wbits=w),w>15||w>t.wbits){r.msg="invalid window size",t.mode=16209;break}t.dmax=1<<t.wbits,t.flags=0,r.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+=i[s++]<<u,u+=8}if(t.flags=c,(255&t.flags)!==Go){r.msg="unknown compression method",t.mode=16209;break}if(57344&t.flags){r.msg="unknown header flags set",t.mode=16209;break}t.head&&(t.head.text=c>>8&1),512&t.flags&&4&t.wrap&&(I[0]=255&c,I[1]=c>>>8&255,t.check=Q(t.check,I,2,0)),c=0,u=0,t.mode=16182;case 16182:for(;u<32;){if(o===0)break e;o--,c+=i[s++]<<u,u+=8}t.head&&(t.head.time=c),512&t.flags&&4&t.wrap&&(I[0]=255&c,I[1]=c>>>8&255,I[2]=c>>>16&255,I[3]=c>>>24&255,t.check=Q(t.check,I,4,0)),c=0,u=0,t.mode=16183;case 16183:for(;u<16;){if(o===0)break e;o--,c+=i[s++]<<u,u+=8}t.head&&(t.head.xflags=255&c,t.head.os=c>>8),512&t.flags&&4&t.wrap&&(I[0]=255&c,I[1]=c>>>8&255,t.check=Q(t.check,I,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+=i[s++]<<u,u+=8}t.length=c,t.head&&(t.head.extra_len=c),512&t.flags&&4&t.wrap&&(I[0]=255&c,I[1]=c>>>8&255,t.check=Q(t.check,I,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&&(w=t.head.extra_len-t.length,t.head.extra||(t.head.extra=new Uint8Array(t.head.extra_len)),t.head.extra.set(i.subarray(s,s+p),w)),512&t.flags&&4&t.wrap&&(t.check=Q(t.check,i,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 w=i[s+p++],t.head&&w&&t.length<65536&&(t.head.name+=String.fromCharCode(w));while(w&&p<o);if(512&t.flags&&4&t.wrap&&(t.check=Q(t.check,i,p,s)),o-=p,s+=p,w)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 w=i[s+p++],t.head&&w&&t.length<65536&&(t.head.comment+=String.fromCharCode(w));while(w&&p<o);if(512&t.flags&&4&t.wrap&&(t.check=Q(t.check,i,p,s)),o-=p,s+=p,w)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+=i[s++]<<u,u+=8}if(4&t.wrap&&c!==(65535&t.check)){r.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),r.adler=t.check=0,t.mode=16191;break;case 16189:for(;u<32;){if(o===0)break e;o--,c+=i[s++]<<u,u+=8}r.adler=t.check=Bo(c),c=0,u=0,t.mode=16190;case 16190:if(t.havedict===0)return r.next_out=a,r.avail_out=d,r.next_in=s,r.avail_in=o,t.hold=c,t.bits=u,$f;r.adler=t.check=1,t.mode=16191;case 16191:if(e===jf||e===Hr)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+=i[s++]<<u,u+=8}switch(t.last=1&c,u-=1,3&(c>>>=1)){case 0:t.mode=16193;break;case 1:if(Wf(t),t.mode=16199,e===Hr){c>>>=2,u-=2;break e}break;case 2:t.mode=16196;break;case 3:r.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+=i[s++]<<u,u+=8}if((65535&c)!=(c>>>16^65535)){r.msg="invalid stored block lengths",t.mode=16209;break}if(t.length=65535&c,c=0,u=0,t.mode=16194,e===Hr)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(i.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+=i[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){r.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+=i[s++]<<u,u+=8}t.lens[H[t.have++]]=7&c,c>>>=3,u-=3}for(;t.have<19;)t.lens[H[t.have++]]=0;if(t.lencode=t.lendyn,t.lenbits=7,k={bits:t.lenbits},A=sr(0,t.lens,0,19,t.lencode,0,t.work,k),t.lenbits=k.bits,A){r.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(;E=(R=t.lencode[c&(1<<t.lenbits)-1])>>>16&255,y=65535&R,!((m=R>>>24)<=u);){if(o===0)break e;o--,c+=i[s++]<<u,u+=8}if(y<16)c>>>=m,u-=m,t.lens[t.have++]=y;else{if(y===16){for(T=m+2;u<T;){if(o===0)break e;o--,c+=i[s++]<<u,u+=8}if(c>>>=m,u-=m,t.have===0){r.msg="invalid bit length repeat",t.mode=16209;break}w=t.lens[t.have-1],p=3+(3&c),c>>>=2,u-=2}else if(y===17){for(T=m+3;u<T;){if(o===0)break e;o--,c+=i[s++]<<u,u+=8}u-=m,w=0,p=3+(7&(c>>>=m)),c>>>=3,u-=3}else{for(T=m+7;u<T;){if(o===0)break e;o--,c+=i[s++]<<u,u+=8}u-=m,w=0,p=11+(127&(c>>>=m)),c>>>=7,u-=7}if(t.have+p>t.nlen+t.ndist){r.msg="invalid bit length repeat",t.mode=16209;break}for(;p--;)t.lens[t.have++]=w}}if(t.mode===16209)break;if(t.lens[256]===0){r.msg="invalid code -- missing end-of-block",t.mode=16209;break}if(t.lenbits=9,k={bits:t.lenbits},A=sr(1,t.lens,0,t.nlen,t.lencode,0,t.work,k),t.lenbits=k.bits,A){r.msg="invalid literal/lengths set",t.mode=16209;break}if(t.distbits=6,t.distcode=t.distdyn,k={bits:t.distbits},A=sr(2,t.lens,t.nlen,t.ndist,t.distcode,0,t.work,k),t.distbits=k.bits,A){r.msg="invalid distances set",t.mode=16209;break}if(t.mode=16199,e===Hr)break e;case 16199:t.mode=16200;case 16200:if(o>=6&&d>=258){r.next_out=a,r.avail_out=d,r.next_in=s,r.avail_in=o,t.hold=c,t.bits=u,Nf(r,h),a=r.next_out,n=r.output,d=r.avail_out,s=r.next_in,i=r.input,o=r.avail_in,c=t.hold,u=t.bits,t.mode===16191&&(t.back=-1);break}for(t.back=0;E=(R=t.lencode[c&(1<<t.lenbits)-1])>>>16&255,y=65535&R,!((m=R>>>24)<=u);){if(o===0)break e;o--,c+=i[s++]<<u,u+=8}if(E&&!(240&E)){for(_=m,C=E,z=y;E=(R=t.lencode[z+((c&(1<<_+C)-1)>>_)])>>>16&255,y=65535&R,!(_+(m=R>>>24)<=u);){if(o===0)break e;o--,c+=i[s++]<<u,u+=8}c>>>=_,u-=_,t.back+=_}if(c>>>=m,u-=m,t.back+=m,t.length=y,E===0){t.mode=16205;break}if(32&E){t.back=-1,t.mode=16191;break}if(64&E){r.msg="invalid literal/length code",t.mode=16209;break}t.extra=15&E,t.mode=16201;case 16201:if(t.extra){for(T=t.extra;u<T;){if(o===0)break e;o--,c+=i[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(;E=(R=t.distcode[c&(1<<t.distbits)-1])>>>16&255,y=65535&R,!((m=R>>>24)<=u);){if(o===0)break e;o--,c+=i[s++]<<u,u+=8}if(!(240&E)){for(_=m,C=E,z=y;E=(R=t.distcode[z+((c&(1<<_+C)-1)>>_)])>>>16&255,y=65535&R,!(_+(m=R>>>24)<=u);){if(o===0)break e;o--,c+=i[s++]<<u,u+=8}c>>>=_,u-=_,t.back+=_}if(c>>>=m,u-=m,t.back+=m,64&E){r.msg="invalid distance code",t.mode=16209;break}t.offset=y,t.extra=15&E,t.mode=16203;case 16203:if(t.extra){for(T=t.extra;u<T;){if(o===0)break e;o--,c+=i[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){r.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){r.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|=i[s++]<<u,u+=8}if(h-=d,r.total_out+=h,t.total+=h,4&t.wrap&&h&&(r.adler=t.check=t.flags?Q(t.check,n,h,a-h):Xt(t.check,n,h,a-h)),h=d,4&t.wrap&&(t.flags?c:Bo(c))!==t.check){r.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+=i[s++]<<u,u+=8}if(4&t.wrap&&c!==(4294967295&t.total)){r.msg="incorrect length check",t.mode=16209;break}c=0,u=0}t.mode=16208;case 16208:A=Hf;break e;case 16209:A=Uo;break e;case 16210:return No;case 16211:default:return me}return r.next_out=a,r.avail_out=d,r.next_in=s,r.avail_in=o,t.hold=c,t.bits=u,(t.wsize||h!==r.avail_out&&t.mode<16209&&(t.mode<16206||e!==Lo))&&qo(r,r.output,r.next_out,h-r.avail_out),l-=r.avail_in,h-=r.avail_out,r.total_in+=l,r.total_out+=h,t.total+=h,4&t.wrap&&h&&(r.adler=t.check=t.flags?Q(t.check,n,h,r.next_out-h):Xt(t.check,n,h,r.next_out-h)),r.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===Lo)&&A===ut&&(A=qf),A},inflateEnd:function(r){if(dt(r))return me;var e=r.state;return e.window&&(e.window=null),r.state=null,ut},inflateGetHeader:function(r,e){if(dt(r))return me;var t=r.state;return 2&t.wrap?(t.head=e,e.done=!1,ut):me},inflateSetDictionary:function(r,e){var t,i=e.length;return dt(r)||(t=r.state).wrap!==0&&t.mode!==16190?me:t.mode===16190&&Xt(1,e,i,0)!==t.check?Uo:qo(r,e,i,i)?(t.mode=16210,No):(t.havedict=1,ut)},inflateInfo:"pako inflate (from Nodeca project)"},Jf=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},Ko=Object.prototype.toString,Zf=P.Z_NO_FLUSH,Xf=P.Z_FINISH,or=P.Z_OK,nn=P.Z_STREAM_END,sn=P.Z_NEED_DICT,Yf=P.Z_STREAM_ERROR,Wo=P.Z_DATA_ERROR,Qf=P.Z_MEM_ERROR;function ar(r){this.options=Vr.assign({chunkSize:65536,windowBits:15,to:""},r||{});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)||r&&r.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 Oo,this.strm.avail_out=0;var t=Ge.inflateInit2(this.strm,e.windowBits);if(t!==or)throw new Error(at[t]);if(this.header=new Jf,Ge.inflateGetHeader(this.strm,this.header),e.dictionary&&(typeof e.dictionary=="string"?e.dictionary=ir.string2buf(e.dictionary):Ko.call(e.dictionary)==="[object ArrayBuffer]"&&(e.dictionary=new Uint8Array(e.dictionary)),e.raw&&(t=Ge.inflateSetDictionary(this.strm,e.dictionary))!==or))throw new Error(at[t])}function on(r,e){var t=new ar(e);if(t.push(r),t.err)throw t.msg||at[t.err];return t.result}ar.prototype.push=function(r,e){var t,i,n,s=this.strm,a=this.options.chunkSize,o=this.options.dictionary;if(this.ended)return!1;for(i=e===~~e?e:e===!0?Xf:Zf,Ko.call(r)==="[object ArrayBuffer]"?s.input=new Uint8Array(r):s.input=r,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=Ge.inflate(s,i))===sn&&o&&((t=Ge.inflateSetDictionary(s,o))===or?t=Ge.inflate(s,i):t===Wo&&(t=sn));s.avail_in>0&&t===nn&&s.state.wrap>0&&r[s.next_in]!==0;)Ge.inflateReset(s),t=Ge.inflate(s,i);switch(t){case Yf:case Wo:case sn:case Qf:return this.onEnd(t),this.ended=!0,!1}if(n=s.avail_out,s.next_out&&(s.avail_out===0||t===nn))if(this.options.to==="string"){var d=ir.utf8border(s.output,s.next_out),c=s.next_out-d,u=ir.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!==or||n!==0){if(t===nn)return t=Ge.inflateEnd(this.strm),this.onEnd(t),this.ended=!0,!0;if(s.avail_in===0)break}}return!0},ar.prototype.onData=function(r){this.chunks.push(r)},ar.prototype.onEnd=function(r){r===or&&(this.options.to==="string"?this.result=this.chunks.join(""):this.result=Vr.flattenChunks(this.chunks)),this.chunks=[],this.err=r,this.msg=this.strm.msg};var cr,$r={Inflate:ar,inflate:on,inflateRaw:function(r,e){return(e=e||{}).raw=!0,on(r,e)},ungzip:on,constants:P},em={Deflate:jr.Deflate,deflate:jr.deflate,deflateRaw:jr.deflateRaw,gzip:jr.gzip,Inflate:$r.Inflate,inflate:$r.inflate,inflateRaw:$r.inflateRaw,ungzip:$r.ungzip,constants:P},tm=function(){return!(!window.navigator||!window.navigator.sendBeacon)},rm=function(){function r(e,t){var i=this;this.collector=e,this.config=t,this.requestType=t.request_type||"xhr",this.supportBeacon=tm(),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){i.setRequestHeader(n)})}return r.prototype.setRequestHeader=function(e){this.customHeader=Object.assign(this.customHeader,e)},r.prototype.useFetch=function(e){var t=e.url,i=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(i)}).then(function(c){return c.json()}).then(function(c){s&&s(c)}).catch(function(c){a&&a(i,c)}):(this.requestType="xhr",console.log("your brwoser not support fetch, use xhr"),this.useRequest({url:t,data:i,method:n,success:s,fail:a}))},r.prototype.useBeacon=function(e){var t=e.url,i=e.data,n=e.success,s=e.fail;window.navigator.sendBeacon(t,JSON.stringify(i))?n&&n():s&&s(i,this.errorCode.BEACON_FALSE)},r.prototype.useRequest=function(e){var t=this,i=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:i,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,""+i,!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 C=null;if(f.responseText){try{C=JSON.parse(f.responseText)}catch{C={}}a(C,n)}}},f.onerror=function(){f.abort(),o&&o(n,t.errorCode.XHR_ON)};try{var E=JSON.stringify(n);if(this.config.need_zip&&p){var y=new TextEncoder().encode(E),_=em.gzip(y);f.setRequestHeader("Content-Encoding","gzip"),f.send(_)}else f.send(E)}catch(C){this.collector.emit("sdk-inner-error",{type:"sdk_error_send",eventData:n,errorCode:1e3,msg:C.message||C.stack||"sdk_error_send"})}}catch(C){this.collector.emit("sdk-inner-error",{type:"sdk_error_request",eventData:n,errorCode:1001,msg:C.message||C.stack||"sdk_error_request"})}else this.useFetch({url:i,data:n,method:s,success:a,fail:o})},r}(),im=function(){function r(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 i=e.adapters.storage;this.cacheStorgae=new i(!1),this.loadUrl=t.devtool_url||Y("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 r.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(i){console.log("devTool load fail, "+i.message)}},r.prototype.parseUrl=function(){var e={};try{var t=window.location.href.split("?")[1].split("&");t.length&&t.forEach(function(i){var n=i.split("=");e[decodeURIComponent(n[0])]=decodeURIComponent(n[1])})}catch{}return e},r.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)}},r.prototype.getStorage=function(){var e=this.cacheStorgae.getItem("__applog_open_devtool_web");return e&&parseInt(e)===this.app_id},r.prototype.setStorage=function(){this.cacheStorgae.setItem("__applog_open_devtool_web",this.app_id)},r.prototype.loadDevTool=function(){this.loadScript(this.loadUrl)},r.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:He},{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||Y(ao[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 i={title:"客户端信息",type:3,content:[{name:"native",desc:"是否打通",value:!!this.collect.bridgeReport}]};this.setInfo("native",i)}if(He.includes("tob")){var n=this.getInfo("user");n.content.push({name:"sid",desc:"DISS".split("").reverse().join(""),value:"点击获取"}),this.setInfo("user",n)}},r.prototype.getInfo=function(e){var t=null;return this.info.forEach(function(i){i.key===e&&(t=i)}),t},r.prototype.setInfo=function(e,t){var i=!1;this.info.forEach(function(n){n.key===e&&(i=!0,n=t)}),i||this.info.push(t)},r.prototype.getSecondInfo=function(e,t){var i=this.getInfo(e),n=null;return i.content.forEach(function(s){s.name===t&&(n=s)}),n},r.prototype.setSecondInfo=function(e,t,i){var n=this.getInfo(e),s=!1;if(n.content.forEach(function(o){o.name===t&&(o.value=i,s=!0)}),!s){var a={name:t,value:i,desc:t.toLocaleUpperCase()};n.content.push(a)}this.setInfo(e,n)},r.prototype.loadHook=function(){var e=this;this.collect.on(g.DEBUGGER_MESSAGE,function(t){switch(t.type){case g.DEBUGGER_MESSAGE_SDK:var i={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&&(i.desc={content:JSON.stringify(t.data)}),e.updateLog(i),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}})},r.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:He.includes("tob")?"tob":"inner",appId:e.app_id}),e.sendAlready=!0}t&&t.data&&t.data.type==="devtool:web:ssid"&&e.collect.getToken(function(i){e.setSecondInfo("user","sid",i.tobid),e.updateInfo()})})},r.prototype.sendData=function(e,t){try{var i={type:e,payload:t};window&&window.postMessage(i,this.devToolOrigin)}catch{}},r.prototype.updateInfo=function(){this.devToolReady&&this.sendData("devtool:web:info",this.info)},r.prototype.updateLog=function(e){this.devToolReady?this.sendData("devtool:web:log",e):this.log.push(e)},r.prototype.updateEvent=function(e){this.devToolReady?this.sendData("devtool:web:event",e):this.event.push(e)},r.prototype.loadDebuggerModule=function(){var e=`#debugger-applog-web {
56
+ `,Ku=URL.createObjectURL(new Blob([qu],{type:"application/javascript"}));class Wu{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||Ku);const n=new MediaStream;n.addTrack(e);const s=i.createMediaStreamSource(n),a=new AudioWorkletNode(i,"vumeter");a.port.onmessage=o=>{const d=o.data.volume||0;this._volume=Math.min(d*100/2,10)},s.connect(a).connect(i.destination),this._audioCtx=i}stop(){var e;(e=this._audioCtx)==null||e.close(),this._audioCtx=null}}class Tr{constructor(){this._volumeDetectScriptUrl=void 0}static get instance(){return this._instance||(this._instance=new Tr),this._instance}get volumeDetectScriptUrl(){return this._volumeDetectScriptUrl}set volumeDetectScriptUrl(e){this._volumeDetectScriptUrl=e}}class ps extends Ve{constructor(e){super(),this._width=0,this._height=0,this._mediaStream=null,this._nextStream=null,this._trackMap={},this.type=e.type,this.id=$u(),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[N.Camera,N.Screen,N.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 Wu),await this._volumeDetector.start(this.audioTrack,Tr.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 mt extends ps{constructor(){super(...arguments),this._frameRate=1}get isVideoStream(){return!0}get isAudioStream(){return!1}get frameRate(){return this._frameRate}bindTrackSizeChangeEvent(e){e.on(se.SIZE_CHANGE,({width:t,height:i})=>{this._width=t,this._height=i,this.emit(Gn.SizeChange,{width:t,height:i})})}}class zr extends ps{get isVideoStream(){return!1}get isAudioStream(){return!0}}class Ju extends mt{constructor(e,t){super({type:N.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(se.ENDED,e)}destroy(){this.source.destroy()}}var fs=typeof global=="object"&&global&&global.Object===Object&&global,Zu=typeof self=="object"&&self&&self.Object===Object&&self,xe=fs||Zu||Function("return this")(),je=xe.Symbol,ms=Object.prototype,Xu=ms.hasOwnProperty,Yu=ms.toString,Ut=je?je.toStringTag:void 0;function Qu(r){var e=Xu.call(r,Ut),t=r[Ut];try{r[Ut]=void 0;var i=!0}catch{}var n=Yu.call(r);return i&&(e?r[Ut]=t:delete r[Ut]),n}var ed=Object.prototype,td=ed.toString;function rd(r){return td.call(r)}var id="[object Null]",nd="[object Undefined]",_s=je?je.toStringTag:void 0;function _t(r){return r==null?r===void 0?nd:id:_s&&_s in Object(r)?Qu(r):rd(r)}function gt(r){return r!=null&&typeof r=="object"}var sd="[object Symbol]";function kr(r){return typeof r=="symbol"||gt(r)&&_t(r)==sd}function gs(r,e){for(var t=-1,i=r==null?0:r.length,n=Array(i);++t<i;)n[t]=e(r[t],t,r);return n}var X=Array.isArray,vs=je?je.prototype:void 0,ys=vs?vs.toString:void 0;function bs(r){if(typeof r=="string")return r;if(X(r))return gs(r,bs)+"";if(kr(r))return ys?ys.call(r):"";var e=r+"";return e=="0"&&1/r==-1/0?"-0":e}var od=/\s/;function ad(r){for(var e=r.length;e--&&od.test(r.charAt(e)););return e}var cd=/^\s+/;function ud(r){return r&&r.slice(0,ad(r)+1).replace(cd,"")}function Nt(r){var e=typeof r;return r!=null&&(e=="object"||e=="function")}var Ss=NaN,dd=/^[-+]0x[0-9a-f]+$/i,hd=/^0b[01]+$/i,ld=/^0o[0-7]+$/i,pd=parseInt;function fd(r){if(typeof r=="number")return r;if(kr(r))return Ss;if(Nt(r)){var e=typeof r.valueOf=="function"?r.valueOf():r;r=Nt(e)?e+"":e}if(typeof r!="string")return r===0?r:+r;r=ud(r);var t=hd.test(r);return t||ld.test(r)?pd(r.slice(2),t?2:8):dd.test(r)?Ss:+r}var md=1/0,_d=17976931348623157e292;function gd(r){if(!r)return r===0?r:0;if(r=fd(r),r===md||r===-1/0){var e=r<0?-1:1;return e*_d}return r===r?r:0}function vd(r){var e=gd(r),t=e%1;return e===e?t?e-t:e:0}function yd(r){return r}var bd="[object AsyncFunction]",Sd="[object Function]",Ed="[object GeneratorFunction]",Cd="[object Proxy]";function Es(r){if(!Nt(r))return!1;var e=_t(r);return e==Sd||e==Ed||e==bd||e==Cd}var Si=xe["__core-js_shared__"],Cs=function(){var r=/[^.]+$/.exec(Si&&Si.keys&&Si.keys.IE_PROTO||"");return r?"Symbol(src)_1."+r:""}();function wd(r){return!!Cs&&Cs in r}var Td=Function.prototype,zd=Td.toString;function nt(r){if(r!=null){try{return zd.call(r)}catch{}try{return r+""}catch{}}return""}var kd=/[\\^$.*+?()[\]{}|]/g,Rd=/^\[object .+?Constructor\]$/,Ad=Function.prototype,Dd=Object.prototype,xd=Ad.toString,Pd=Dd.hasOwnProperty,Id=RegExp("^"+xd.call(Pd).replace(kd,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function Od(r){if(!Nt(r)||wd(r))return!1;var e=Es(r)?Id:Rd;return e.test(nt(r))}function Md(r,e){return r==null?void 0:r[e]}function vt(r,e){var t=Md(r,e);return Od(t)?t:void 0}var Ei=vt(xe,"WeakMap");function Ld(r,e,t,i){for(var n=r.length,s=t+-1;++s<n;)if(e(r[s],s,r))return s;return-1}var Ud=9007199254740991,Nd=/^(?:0|[1-9]\d*)$/;function ws(r,e){var t=typeof r;return e=e??Ud,!!e&&(t=="number"||t!="symbol"&&Nd.test(r))&&r>-1&&r%1==0&&r<e}function Ts(r,e){return r===e||r!==r&&e!==e}var Gd=9007199254740991;function Ci(r){return typeof r=="number"&&r>-1&&r%1==0&&r<=Gd}function Rr(r){return r!=null&&Ci(r.length)&&!Es(r)}var Bd=Object.prototype;function zs(r){var e=r&&r.constructor,t=typeof e=="function"&&e.prototype||Bd;return r===t}function Vd(r,e){for(var t=-1,i=Array(r);++t<r;)i[t]=e(t);return i}var Fd="[object Arguments]";function ks(r){return gt(r)&&_t(r)==Fd}var Rs=Object.prototype,jd=Rs.hasOwnProperty,Hd=Rs.propertyIsEnumerable,wi=ks(function(){return arguments}())?ks:function(r){return gt(r)&&jd.call(r,"callee")&&!Hd.call(r,"callee")};function $d(){return!1}var As=typeof exports=="object"&&exports&&!exports.nodeType&&exports,Ds=As&&typeof module=="object"&&module&&!module.nodeType&&module,qd=Ds&&Ds.exports===As,xs=qd?xe.Buffer:void 0,Kd=xs?xs.isBuffer:void 0,Ar=Kd||$d,Wd="[object Arguments]",Jd="[object Array]",Zd="[object Boolean]",Xd="[object Date]",Yd="[object Error]",Qd="[object Function]",eh="[object Map]",th="[object Number]",rh="[object Object]",ih="[object RegExp]",nh="[object Set]",sh="[object String]",oh="[object WeakMap]",ah="[object ArrayBuffer]",ch="[object DataView]",uh="[object Float32Array]",dh="[object Float64Array]",hh="[object Int8Array]",lh="[object Int16Array]",ph="[object Int32Array]",fh="[object Uint8Array]",mh="[object Uint8ClampedArray]",_h="[object Uint16Array]",gh="[object Uint32Array]",F={};F[uh]=F[dh]=F[hh]=F[lh]=F[ph]=F[fh]=F[mh]=F[_h]=F[gh]=!0,F[Wd]=F[Jd]=F[ah]=F[Zd]=F[ch]=F[Xd]=F[Yd]=F[Qd]=F[eh]=F[th]=F[rh]=F[ih]=F[nh]=F[sh]=F[oh]=!1;function vh(r){return gt(r)&&Ci(r.length)&&!!F[_t(r)]}function yh(r){return function(e){return r(e)}}var Ps=typeof exports=="object"&&exports&&!exports.nodeType&&exports,Gt=Ps&&typeof module=="object"&&module&&!module.nodeType&&module,bh=Gt&&Gt.exports===Ps,Ti=bh&&fs.process,Is=function(){try{var r=Gt&&Gt.require&&Gt.require("util").types;return r||Ti&&Ti.binding&&Ti.binding("util")}catch{}}(),Os=Is&&Is.isTypedArray,zi=Os?yh(Os):vh,Sh=Object.prototype,Eh=Sh.hasOwnProperty;function Ch(r,e){var t=X(r),i=!t&&wi(r),n=!t&&!i&&Ar(r),s=!t&&!i&&!n&&zi(r),a=t||i||n||s,o=a?Vd(r.length,String):[],d=o.length;for(var c in r)Eh.call(r,c)&&!(a&&(c=="length"||n&&(c=="offset"||c=="parent")||s&&(c=="buffer"||c=="byteLength"||c=="byteOffset")||ws(c,d)))&&o.push(c);return o}function wh(r,e){return function(t){return r(e(t))}}var Th=wh(Object.keys,Object),zh=Object.prototype,kh=zh.hasOwnProperty;function Ms(r){if(!zs(r))return Th(r);var e=[];for(var t in Object(r))kh.call(r,t)&&t!="constructor"&&e.push(t);return e}function Bt(r){return Rr(r)?Ch(r):Ms(r)}var Rh=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,Ah=/^\w*$/;function ki(r,e){if(X(r))return!1;var t=typeof r;return t=="number"||t=="symbol"||t=="boolean"||r==null||kr(r)?!0:Ah.test(r)||!Rh.test(r)||e!=null&&r in Object(e)}var Vt=vt(Object,"create");function Dh(){this.__data__=Vt?Vt(null):{},this.size=0}function xh(r){var e=this.has(r)&&delete this.__data__[r];return this.size-=e?1:0,e}var Ph="__lodash_hash_undefined__",Ih=Object.prototype,Oh=Ih.hasOwnProperty;function Mh(r){var e=this.__data__;if(Vt){var t=e[r];return t===Ph?void 0:t}return Oh.call(e,r)?e[r]:void 0}var Lh=Object.prototype,Uh=Lh.hasOwnProperty;function Nh(r){var e=this.__data__;return Vt?e[r]!==void 0:Uh.call(e,r)}var Gh="__lodash_hash_undefined__";function Bh(r,e){var t=this.__data__;return this.size+=this.has(r)?0:1,t[r]=Vt&&e===void 0?Gh:e,this}function st(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])}}st.prototype.clear=Dh,st.prototype.delete=xh,st.prototype.get=Mh,st.prototype.has=Nh,st.prototype.set=Bh;function Vh(){this.__data__=[],this.size=0}function Dr(r,e){for(var t=r.length;t--;)if(Ts(r[t][0],e))return t;return-1}var Fh=Array.prototype,jh=Fh.splice;function Hh(r){var e=this.__data__,t=Dr(e,r);if(t<0)return!1;var i=e.length-1;return t==i?e.pop():jh.call(e,t,1),--this.size,!0}function $h(r){var e=this.__data__,t=Dr(e,r);return t<0?void 0:e[t][1]}function qh(r){return Dr(this.__data__,r)>-1}function Kh(r,e){var t=this.__data__,i=Dr(t,r);return i<0?(++this.size,t.push([r,e])):t[i][1]=e,this}function Pe(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])}}Pe.prototype.clear=Vh,Pe.prototype.delete=Hh,Pe.prototype.get=$h,Pe.prototype.has=qh,Pe.prototype.set=Kh;var Ft=vt(xe,"Map");function Wh(){this.size=0,this.__data__={hash:new st,map:new(Ft||Pe),string:new st}}function Jh(r){var e=typeof r;return e=="string"||e=="number"||e=="symbol"||e=="boolean"?r!=="__proto__":r===null}function xr(r,e){var t=r.__data__;return Jh(e)?t[typeof e=="string"?"string":"hash"]:t.map}function Zh(r){var e=xr(this,r).delete(r);return this.size-=e?1:0,e}function Xh(r){return xr(this,r).get(r)}function Yh(r){return xr(this,r).has(r)}function Qh(r,e){var t=xr(this,r),i=t.size;return t.set(r,e),this.size+=t.size==i?0:1,this}function Ie(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])}}Ie.prototype.clear=Wh,Ie.prototype.delete=Zh,Ie.prototype.get=Xh,Ie.prototype.has=Yh,Ie.prototype.set=Qh;var el="Expected a function";function Ri(r,e){if(typeof r!="function"||e!=null&&typeof e!="function")throw new TypeError(el);var t=function(){var i=arguments,n=e?e.apply(this,i):i[0],s=t.cache;if(s.has(n))return s.get(n);var a=r.apply(this,i);return t.cache=s.set(n,a)||s,a};return t.cache=new(Ri.Cache||Ie),t}Ri.Cache=Ie;var tl=500;function rl(r){var e=Ri(r,function(i){return t.size===tl&&t.clear(),i}),t=e.cache;return e}var il=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,nl=/\\(\\)?/g,sl=rl(function(r){var e=[];return r.charCodeAt(0)===46&&e.push(""),r.replace(il,function(t,i,n,s){e.push(n?s.replace(nl,"$1"):i||t)}),e});function ol(r){return r==null?"":bs(r)}function Ls(r,e){return X(r)?r:ki(r,e)?[r]:sl(ol(r))}function Pr(r){if(typeof r=="string"||kr(r))return r;var e=r+"";return e=="0"&&1/r==-1/0?"-0":e}function Us(r,e){e=Ls(e,r);for(var t=0,i=e.length;r!=null&&t<i;)r=r[Pr(e[t++])];return t&&t==i?r:void 0}function al(r,e,t){var i=r==null?void 0:Us(r,e);return i===void 0?t:i}function cl(r,e){for(var t=-1,i=e.length,n=r.length;++t<i;)r[n+t]=e[t];return r}function ul(){this.__data__=new Pe,this.size=0}function dl(r){var e=this.__data__,t=e.delete(r);return this.size=e.size,t}function hl(r){return this.__data__.get(r)}function ll(r){return this.__data__.has(r)}var pl=200;function fl(r,e){var t=this.__data__;if(t instanceof Pe){var i=t.__data__;if(!Ft||i.length<pl-1)return i.push([r,e]),this.size=++t.size,this;t=this.__data__=new Ie(i)}return t.set(r,e),this.size=t.size,this}function Oe(r){var e=this.__data__=new Pe(r);this.size=e.size}Oe.prototype.clear=ul,Oe.prototype.delete=dl,Oe.prototype.get=hl,Oe.prototype.has=ll,Oe.prototype.set=fl;function Ns(r,e){for(var t=-1,i=r==null?0:r.length,n=0,s=[];++t<i;){var a=r[t];e(a,t,r)&&(s[n++]=a)}return s}function ml(){return[]}var _l=Object.prototype,gl=_l.propertyIsEnumerable,Gs=Object.getOwnPropertySymbols,vl=Gs?function(r){return r==null?[]:(r=Object(r),Ns(Gs(r),function(e){return gl.call(r,e)}))}:ml;function yl(r,e,t){var i=e(r);return X(r)?i:cl(i,t(r))}function Bs(r){return yl(r,Bt,vl)}var Ai=vt(xe,"DataView"),Di=vt(xe,"Promise"),xi=vt(xe,"Set"),Vs="[object Map]",bl="[object Object]",Fs="[object Promise]",js="[object Set]",Hs="[object WeakMap]",$s="[object DataView]",Sl=nt(Ai),El=nt(Ft),Cl=nt(Di),wl=nt(xi),Tl=nt(Ei),Me=_t;(Ai&&Me(new Ai(new ArrayBuffer(1)))!=$s||Ft&&Me(new Ft)!=Vs||Di&&Me(Di.resolve())!=Fs||xi&&Me(new xi)!=js||Ei&&Me(new Ei)!=Hs)&&(Me=function(r){var e=_t(r),t=e==bl?r.constructor:void 0,i=t?nt(t):"";if(i)switch(i){case Sl:return $s;case El:return Vs;case Cl:return Fs;case wl:return js;case Tl:return Hs}return e});var qs=xe.Uint8Array,zl="__lodash_hash_undefined__";function kl(r){return this.__data__.set(r,zl),this}function Rl(r){return this.__data__.has(r)}function Ir(r){var e=-1,t=r==null?0:r.length;for(this.__data__=new Ie;++e<t;)this.add(r[e])}Ir.prototype.add=Ir.prototype.push=kl,Ir.prototype.has=Rl;function Al(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 Dl(r,e){return r.has(e)}var xl=1,Pl=2;function Ks(r,e,t,i,n,s){var a=t&xl,o=r.length,d=e.length;if(o!=d&&!(a&&d>o))return!1;var c=s.get(r),u=s.get(e);if(c&&u)return c==e&&u==r;var l=-1,h=!0,p=t&Pl?new Ir:void 0;for(s.set(r,e),s.set(e,r);++l<o;){var f=r[l],v=e[l];if(i)var m=a?i(v,f,l,e,r,s):i(f,v,l,r,e,s);if(m!==void 0){if(m)continue;h=!1;break}if(p){if(!Al(e,function(E,y){if(!Dl(p,y)&&(f===E||n(f,E,t,i,s)))return p.push(y)})){h=!1;break}}else if(!(f===v||n(f,v,t,i,s))){h=!1;break}}return s.delete(r),s.delete(e),h}function Il(r){var e=-1,t=Array(r.size);return r.forEach(function(i,n){t[++e]=[n,i]}),t}function Ol(r){var e=-1,t=Array(r.size);return r.forEach(function(i){t[++e]=i}),t}var Ml=1,Ll=2,Ul="[object Boolean]",Nl="[object Date]",Gl="[object Error]",Bl="[object Map]",Vl="[object Number]",Fl="[object RegExp]",jl="[object Set]",Hl="[object String]",$l="[object Symbol]",ql="[object ArrayBuffer]",Kl="[object DataView]",Ws=je?je.prototype:void 0,Pi=Ws?Ws.valueOf:void 0;function Wl(r,e,t,i,n,s,a){switch(t){case Kl:if(r.byteLength!=e.byteLength||r.byteOffset!=e.byteOffset)return!1;r=r.buffer,e=e.buffer;case ql:return!(r.byteLength!=e.byteLength||!s(new qs(r),new qs(e)));case Ul:case Nl:case Vl:return Ts(+r,+e);case Gl:return r.name==e.name&&r.message==e.message;case Fl:case Hl:return r==e+"";case Bl:var o=Il;case jl:var d=i&Ml;if(o||(o=Ol),r.size!=e.size&&!d)return!1;var c=a.get(r);if(c)return c==e;i|=Ll,a.set(r,e);var u=Ks(o(r),o(e),i,n,s,a);return a.delete(r),u;case $l:if(Pi)return Pi.call(r)==Pi.call(e)}return!1}var Jl=1,Zl=Object.prototype,Xl=Zl.hasOwnProperty;function Yl(r,e,t,i,n,s){var a=t&Jl,o=Bs(r),d=o.length,c=Bs(e),u=c.length;if(d!=u&&!a)return!1;for(var l=d;l--;){var h=o[l];if(!(a?h in e:Xl.call(e,h)))return!1}var p=s.get(r),f=s.get(e);if(p&&f)return p==e&&f==r;var v=!0;s.set(r,e),s.set(e,r);for(var m=a;++l<d;){h=o[l];var E=r[h],y=e[h];if(i)var _=a?i(y,E,h,e,r,s):i(E,y,h,r,e,s);if(!(_===void 0?E===y||n(E,y,t,i,s):_)){v=!1;break}m||(m=h=="constructor")}if(v&&!m){var C=r.constructor,z=e.constructor;C!=z&&"constructor"in r&&"constructor"in e&&!(typeof C=="function"&&C instanceof C&&typeof z=="function"&&z instanceof z)&&(v=!1)}return s.delete(r),s.delete(e),v}var Ql=1,Js="[object Arguments]",Zs="[object Array]",Or="[object Object]",ep=Object.prototype,Xs=ep.hasOwnProperty;function tp(r,e,t,i,n,s){var a=X(r),o=X(e),d=a?Zs:Me(r),c=o?Zs:Me(e);d=d==Js?Or:d,c=c==Js?Or:c;var u=d==Or,l=c==Or,h=d==c;if(h&&Ar(r)){if(!Ar(e))return!1;a=!0,u=!1}if(h&&!u)return s||(s=new Oe),a||zi(r)?Ks(r,e,t,i,n,s):Wl(r,e,d,t,i,n,s);if(!(t&Ql)){var p=u&&Xs.call(r,"__wrapped__"),f=l&&Xs.call(e,"__wrapped__");if(p||f){var v=p?r.value():r,m=f?e.value():e;return s||(s=new Oe),n(v,m,t,i,s)}}return h?(s||(s=new Oe),Yl(r,e,t,i,n,s)):!1}function Ii(r,e,t,i,n){return r===e?!0:r==null||e==null||!gt(r)&&!gt(e)?r!==r&&e!==e:tp(r,e,t,i,Ii,n)}var rp=1,ip=2;function np(r,e,t,i){var n=t.length,s=n;if(r==null)return!s;for(r=Object(r);n--;){var a=t[n];if(a[2]?a[1]!==r[a[0]]:!(a[0]in r))return!1}for(;++n<s;){a=t[n];var o=a[0],d=r[o],c=a[1];if(a[2]){if(d===void 0&&!(o in r))return!1}else{var u=new Oe,l;if(!(l===void 0?Ii(c,d,rp|ip,i,u):l))return!1}}return!0}function Ys(r){return r===r&&!Nt(r)}function sp(r){for(var e=Bt(r),t=e.length;t--;){var i=e[t],n=r[i];e[t]=[i,n,Ys(n)]}return e}function Qs(r,e){return function(t){return t==null?!1:t[r]===e&&(e!==void 0||r in Object(t))}}function op(r){var e=sp(r);return e.length==1&&e[0][2]?Qs(e[0][0],e[0][1]):function(t){return t===r||np(t,r,e)}}function ap(r,e){return r!=null&&e in Object(r)}function cp(r,e,t){e=Ls(e,r);for(var i=-1,n=e.length,s=!1;++i<n;){var a=Pr(e[i]);if(!(s=r!=null&&t(r,a)))break;r=r[a]}return s||++i!=n?s:(n=r==null?0:r.length,!!n&&Ci(n)&&ws(a,n)&&(X(r)||wi(r)))}function up(r,e){return r!=null&&cp(r,e,ap)}var dp=1,hp=2;function lp(r,e){return ki(r)&&Ys(e)?Qs(Pr(r),e):function(t){var i=al(t,r);return i===void 0&&i===e?up(t,r):Ii(e,i,dp|hp)}}function pp(r){return function(e){return e==null?void 0:e[r]}}function fp(r){return function(e){return Us(e,r)}}function mp(r){return ki(r)?pp(Pr(r)):fp(r)}function Oi(r){return typeof r=="function"?r:r==null?yd:typeof r=="object"?X(r)?lp(r[0],r[1]):op(r):mp(r)}function _p(r){return function(e,t,i){for(var n=-1,s=Object(e),a=i(e),o=a.length;o--;){var d=a[++n];if(t(s[d],d,s)===!1)break}return e}}var gp=_p();function vp(r,e){return r&&gp(r,e,Bt)}function yp(r,e){return function(t,i){if(t==null)return t;if(!Rr(t))return r(t,i);for(var n=t.length,s=-1,a=Object(t);++s<n&&i(a[s],s,a)!==!1;);return t}}var bp=yp(vp);function Sp(r,e){var t=[];return bp(r,function(i,n,s){e(i,n,s)&&t.push(i)}),t}function eo(r,e){var t=X(r)?Ns:Sp;return t(r,Oi(e))}function Ep(r){return function(e,t,i){var n=Object(e);if(!Rr(e)){var s=Oi(t);e=Bt(e),t=function(o){return s(n[o],o,n)}}var a=r(e,t,i);return a>-1?n[s?e[a]:a]:void 0}}var Cp=Math.max;function wp(r,e,t){var i=r==null?0:r.length;if(!i)return-1;var n=t==null?0:vd(t);return n<0&&(n=Cp(i+n,0)),Ld(r,Oi(e),n)}var jt=Ep(wp);function Tp(r,e){return gs(e,function(t){return r[t]})}function Le(r){return r==null?[]:Tp(r,Bt(r))}var zp="[object Map]",kp="[object Set]",Rp=Object.prototype,Ap=Rp.hasOwnProperty;function Dp(r){if(r==null)return!0;if(Rr(r)&&(X(r)||typeof r=="string"||typeof r.splice=="function"||Ar(r)||zi(r)||wi(r)))return!r.length;var e=Me(r);if(e==zp||e==kp)return!r.size;if(zs(r))return!Ms(r).length;for(var t in r)if(Ap.call(r,t))return!1;return!0}function xp(r){return r==null}class Pp extends zr{constructor(e){super({type:N.Microphone,stream:e}),this._trackMap.audio=e.track()}get source(){return this._source}get mixerNode(){return this.source.node()}bindTrackEnd(e){this.source.on(se.ENDED,e)}destroy(){this.source.destroy()}}class Ip extends mt{constructor(e){super({type:N.VideoFile,stream:e});const t=jt(e,n=>n.kind===B.VIDEO),i=jt(e,n=>n.kind===B.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(se.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 Op extends mt{constructor(e,t){super({type:N.Screen,stream:e});const i=jt(e,s=>s.kind===B.VIDEO),n=jt(e,s=>s.kind===B.AUDIO);this._videoStream=i,this._audioStream=n,this._frameRate=(t==null?void 0:t.frameRate)??1,this._trackMap.video=i==null?void 0:i.track(),this._trackMap.audio=n==null?void 0:n.track(),i&&(this._height=i==null?void 0:i.height(),this._width=i==null?void 0:i.width(),this.bindTrackSizeChangeEvent(i))}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(se.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 Mp extends zr{constructor(e){super({type:N.AudioFile,stream:e});const t=jt(e,i=>i.kind===B.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(se.ENDED,e)}destroy(){var e;(e=this._audioStream)==null||e.destroy()}}class Lp extends mt{constructor(e){super({type:N.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(se.ENDED,e)}destroy(){this.source.destroy()}}class Up extends mt{constructor(e){super({type:N.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(se.ENDED,e)}destroy(){this.source.destroy()}}class Np extends zr{constructor(e){super({type:N.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(se.ENDED,e)}destroy(){var e;(e=this._audioStream)==null||e.destroy()}}const Gp=["user","environment"],Bp=18e4,Vp=1e4,to=1e3;var de=(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[r.AUDIO_RESUME_FAILED=2004]="AUDIO_RESUME_FAILED",r))(de||{});class yt extends Error{constructor(e,t,i){super(),this.code=e,this.message=t,i&&(this.ext=i)}}function bt(r,e,t){const i=si.Landscape;if(e==="video"){const d=(i===si.Landscape?Mn:Ln)[r],[c,u,l,h]=d.split("x").map(p=>Number(p));return{width:c,height:u,frameRate:l,bitrate:h*1e3}}const n=Un[r],[s,a]=n.split("x").map(o=>Number(o));return{sampleRate:s,bitrate:a*1e3}}var U=function(){return(U=Object.assign||function(r){for(var e,t=1,i=arguments.length;t<i;t++)for(var n in e=arguments[t])Object.prototype.hasOwnProperty.call(e,n)&&(r[n]=e[n]);return r}).apply(this,arguments)};function Fp(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var i,n,s=t.call(r),a=[];try{for(;(e===void 0||e-- >0)&&!(i=s.next()).done;)a.push(i.value)}catch(o){n={error:o}}finally{try{i&&!i.done&&(t=s.return)&&t.call(s)}finally{if(n)throw n.error}}return a}function ot(){for(var r=[],e=0;e<arguments.length;e++)r=r.concat(Fp(arguments[e]));return r}var ro,jp=function(){function r(){this._hooks={},this._cache=[],this._hooksCache={}}return r.prototype.on=function(e,t){e&&t&&typeof t=="function"&&(this._hooks[e]||(this._hooks[e]=[]),this._hooks[e].push(t))},r.prototype.once=function(e,t){var i=this;e&&t&&typeof t=="function"&&this.on(e,function n(s){t(s),i.off(e,n)})},r.prototype.off=function(e,t){if(e&&this._hooks[e]&&this._hooks[e].length)if(t){var i=this._hooks[e].indexOf(t);i!==-1&&this._hooks[e].splice(i,1)}else this._hooks[e]=[]},r.prototype.emit=function(e,t,i){if(i){if(!e)return;this._cache.indexOf(i)!==-1?this._emit(e,t):(this._hooksCache.hasOwnProperty(i)||(this._hooksCache[i]={}),this._hooksCache[i].hasOwnProperty(e)||(this._hooksCache[i][e]=[]),this._hooksCache[i][e].push(t))}else this._emit(e,t)},r.prototype._emit=function(e,t){e&&this._hooks[e]&&this._hooks[e].length&&ot(this._hooks[e]).forEach(function(i){try{i(t)}catch{}})},r.prototype.set=function(e){e&&this._cache.indexOf(e)===-1&&this._cache.push(e)},r}(),Ht=function(r){return r!=null&&Object.prototype.toString.call(r)=="[object Object]"},Mr=function(r){return Array.isArray(r)},Hp=(ro=+Date.now()+Number((""+Math.random()).slice(2,8)),function(){return ro+=1}),Y=function(r){return function(e,t,i){if(typeof e=="string"&&typeof i=="number"){var n,s=[];i=i<=25?i:i%25;var a=String.fromCharCode(i+97);n=e.split(a);for(var o=0;o<n.length;o++){var d=parseInt(n[o],i);d=1*d^t;var c=String.fromCharCode(d);s.push(c)}return s.join("")}}(r,64,25)},io=function(){return!!navigator.userAgent.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/)},Mi=function(r){io()?window.addEventListener("pagehide",r,!1):window.addEventListener("beforeunload",r,!1)},$p=function(r,e,t){var i=document.createElement("script");i.src=r,i.onerror=function(){t(r)},i.onload=function(){e()},document.getElementsByTagName("head")[0].appendChild(i)},no=function(){var r=0;return["hidden","msHidden","webkitHidden"].forEach(function(e){document[e]!==void 0&&(r=1)}),r},qp=function(r,e){r===void 0&&(r=function(){}),e===void 0&&(e=1e3);var t,i=Date.now()+e;return t=window.setTimeout(function n(){var s=Date.now()-i;r(),i+=e,t=window.setTimeout(n,Math.max(0,e-s))},e),function(){window.clearTimeout(t)}},Li=function(r){var e=document.createElement("a");return e.href=r,e},Lr=function(r){var e={};try{var t=Li(r).search;if(!t)return e;(t=t.slice(1)).split("&").forEach(function(i){var n,s,a=i.split("=");a.length&&(n=a[0],s=a[1]);try{e[n]=decodeURIComponent(s===void 0?"":s)}catch{e[n]=s}})}catch{}return e},so=function(r){for(var e=0,t=0,i=(r+="").length,n=0;n<i;n++)((e=31*e+r.charCodeAt(t++))>0x7fffffffffff||e<-0x800000000000)&&(e&=0xffffffffffff);return e<0&&(e+=0x7ffffffffffff),e},Ui,Ni=(function(r,e){var t;t=function(){function i(){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=i({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 E=n(v[0]);if(m=(a.read||a)(m,E)||n(m),l)try{m=JSON.parse(m)}catch{}if(h[E]=m,u===E)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,"",i(l,{expires:-1}))},o.defaults={},o.withConverter=s,o}(function(){})},r.exports=t()}(Ui={exports:{}},Ui.exports),Ui.exports),Gi=function(r,e){try{return r?Ni.get(r):Ni.get()}catch{return""}},Bi=function(r,e,t,i){try{var n=i||document.domain,s=+new Date+(t||6048e5);Ni.set(r,e,{expires:new Date(s),path:"/",domain:n})}catch{}},Kp=function(){function r(){this.cache={}}return r.prototype.setItem=function(e,t){this.cache[e]=t},r.prototype.getItem=function(e){return this.cache[e]},r.prototype.removeItem=function(e){this.cache[e]=void 0},r.prototype.getCookie=function(e,t){return Gi(e)},r.prototype.setCookie=function(e,t,i,n){Bi(e,t,i,n)},r}(),Vi,g,oo={getItem:function(r){try{var e=localStorage.getItem(r),t=e;try{e&&typeof e=="string"&&(t=JSON.parse(e))}catch{}return t||{}}catch{}return{}},setItem:function(r,e){try{var t=typeof e=="string"?e:JSON.stringify(e);localStorage.setItem(r,t)}catch{}},removeItem:function(r){try{localStorage.removeItem(r)}catch{}},getCookie:function(r,e){return Gi(r)},setCookie:function(r,e,t,i){Bi(r,e,t,i)},isSupportLS:function(){try{return localStorage.setItem("_ranger-test-key","hi"),localStorage.getItem("_ranger-test-key"),localStorage.removeItem("_ranger-test-key"),!0}catch{return!1}}()},Wp={getItem:function(r){try{var e=sessionStorage.getItem(r),t=e;try{e&&typeof e=="string"&&(t=JSON.parse(e))}catch{}return t||{}}catch{}return{}},setItem:function(r,e){try{var t=typeof e=="string"?e:JSON.stringify(e);sessionStorage.setItem(r,t)}catch{}},removeItem:function(r){try{sessionStorage.removeItem(r)}catch{}},getCookie:function(r,e){return Gi(r)},setCookie:function(r,e,t,i){Bi(r,e,t,i)},isSupportSession:function(){try{return sessionStorage.setItem("_ranger-test-key","hi"),sessionStorage.getItem("_ranger-test-key"),sessionStorage.removeItem("_ranger-test-key"),!0}catch{return!1}}()},Ue=function(){function r(e,t){this._storage=t&&t==="session"?Wp:!e&&oo.isSupportLS?oo:new Kp}return r.prototype.getItem=function(e){return this._storage.getItem(e)},r.prototype.setItem=function(e,t){this._storage.setItem(e,t)},r.prototype.getCookie=function(e,t){return this._storage.getCookie(e,t)},r.prototype.setCookie=function(e,t,i,n){this._storage.setCookie(e,t,i,n)},r.prototype.removeItem=function(e){this._storage.removeItem(e)},r}(),Jp=function(){function r(e,t,i){this.appid=e,this.domain=t,this.userAgent=window.navigator.userAgent,this.appVersion=window.navigator.appVersion,this.cookie_expire=i}return r.prototype.init=function(){var e,t=window.navigator.userAgent,i=window.navigator.language,n=document.referrer,s=n?Li(n).hostname:"",a=Lr(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 Ue(!1),m=new Ue(!1,"session"),E=l?"_tea_utm_cache_"+l:"_tea_utm_cache",y=l?"_$utm_from_url_"+l:"_$utm_from_url",_={},C=["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 w=!1;for(var A in z)z[A]&&(C.indexOf(A)!==-1?(_.hasOwnProperty("tracer_data")||(_.tracer_data={}),_.tracer_data[A]=z[A]):_[A]=z[A],w=!0);if(w)m.setItem(y,"1"),v.setCookie(E,JSON.stringify(_),f,p);else{var k=v.getCookie(E,p);k&&(_=JSON.parse(k))}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:i,referrer:n,referrer_host:s,network_type:d,utm:this.utm,latest_data:this.last(n,s)}},r.prototype.last=function(e,t){var i="",n="",s="",a=location.hostname,o=!1;if(e&&t&&a!==t){i=e,n=t,o=!0;var d=Lr(e);d.keyword&&(s=d.keyword)}return{$latest_referrer:i,$latest_referrer_host:n,$latest_search_keyword:s,isLast:o}},r.prototype.browser=function(){var e,t,i="",n=""+parseFloat(this.appVersion),s=this.userAgent;return s.indexOf("Edge")!==-1||s.indexOf("Edg")!==-1?(i="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?(i="Microsoft Internet Explorer",n=s.substring(e+5)):(e=s.indexOf("MetaSr"))!==-1?(i="sougoubrowser",n=s.substring(e+7,e+10)):s.indexOf("MQQBrowser")!==-1||s.indexOf("QQBrowser")!==-1?(i="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?(i="weixin",n=s.substring(e+15,e+20)):(e=s.indexOf("360"))!==-1?(i="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)),i="baidubrowser"):(e=s.indexOf("xiaomi"))!==-1?s.indexOf("openlanguagexiaomi")!==-1?(i="openlanguage xiaomi",n=s.substring(e+7,e+13)):(i="xiaomi",n=s.substring(e-7,e-1)):(e=s.indexOf("TTWebView"))!==-1?(i="TTWebView",n=s.substring(e+10,e+23)):((e=s.indexOf("Chrome"))!==-1||(e=s.indexOf("Chrome"))!==-1)&&(i="Chrome",n=s.substring(e+7)):s.indexOf("Safari")!==-1?(e=s.indexOf("QQ"))!==-1?(i="qqbrowser",n=s.substring(e+10,e+16)):(e=s.indexOf("Safari"))!==-1&&(i="Safari",n=s.substring(e+7),(e=s.indexOf("Version"))!==-1&&(n=s.substring(e+8))):(e=s.indexOf("Firefox"))!==-1?(i="Firefox",n=s.substring(e+8)):(e=s.indexOf("MicroMessenger"))!==-1?(i="weixin",n=s.substring(e+15,e+20)):(e=s.indexOf("QQ"))!==-1&&(i="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:i,browser_version:n}},r.prototype.os=function(){for(var e="",t="",i=[{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<i.length;n++){var s=i[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}},r.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 i=navigator.userAgent.replace("Mozilla/5.0 (",""),n=i.indexOf(";");t=n===-1?"":i.slice(0,n)}}catch{return t.trim()}return t.trim()},r.prototype.isNewIpad=function(){return this.userAgent!==void 0&&navigator.platform==="MacIntel"&&typeof navigator.maxTouchPoints=="number"&&navigator.maxTouchPoints>1},r}(),ao={cn:"1fz22z22z1nz21z4mz4bz4bz22z1mz19z1jz1mz1ez4az1az22z1mz19z21z1lz21z21z1bz1iz4az1az1mz1k",va:"1fz22z22z1nz21z4mz4bz4bz22z1mz19z1jz1mz1ez4az1gz22z1mz19z21z1lz21z21z1bz1iz4az1az1mz1k",sg:"1fz22z22z1nz21z4mz4bz4bz22z1mz19z1jz1mz1ez4az22z1mz19z21z1lz21z21z1bz1iz4az1az1mz1k"},Zp={cn:"1fz22z22z1nz21z4mz4bz4bz1kz1az21z4az28z1gz1hz1gz1cz18z1nz1gz4az1az1mz1k",sg:"1fz22z22z1nz21z4mz4bz4bz21z1ez18z1jz1gz49z1kz1az21z4az19z27z22z1cz1mz24z1cz20z21z1cz18z4az1az1mz1k",va:"1fz22z22z1nz21z4mz4bz4bz1kz18z1jz1gz24z18z49z1kz1az21z4az19z27z22z1cz1mz24z1cz20z21z1cz18z4az1az1mz1k",my:"1fz22z22z1nz21z4mz4bz4bz1kz1az21z49z19z1bz49z1kz27z4az1jz18z20z1iz1mz1dz1dz1gz1az1cz4az1az1mz1k"},He="5.3.4",Xp=(Y("1fz22z22z1nz21z4mz4bz4bz1jz1dz49z1az1bz1lz49z22z1mz21z4az19z27z22z1cz21z1az1kz4az1az1mz1kz4bz1mz19z1hz4bz21z22z18z22z1gz1az4bz1jz1mz1ez49z21z1bz1iz4bz1az1mz1jz1jz1cz1az22z4bz24z1gz21z23z18z1jz49z1cz1bz1gz22z1mz20z49z20z18z1lz1ez1cz20z21z4az1hz21"),Y("1fz22z22z1nz21z4mz4bz4bz1jz1dz49z1az1bz1lz49z22z1mz21z4az19z27z22z1cz21z1az1kz4az1az1mz1kz4bz1mz19z1hz4bz21z22z18z22z1gz1az4bz1jz1mz1ez49z21z1bz1iz4bz1az1mz1jz1jz1cz1az22z4bz24z1gz21z23z18z1jz49z18z19z49z1az1mz20z1cz4az1hz21"),Y("1fz22z22z1nz21z4mz4bz4bz1jz1dz49z1az1bz1lz49z22z1mz21z4az19z27z22z1cz21z1az1kz4az1az1mz1kz4bz1mz19z1hz4bz21z22z18z22z1gz1az4bz1jz1mz1ez49z21z1bz1iz4bz1az1mz1jz1jz1cz1az22z4bz24z1gz21z23z18z1jz49z18z19z49z1jz1mz18z1bz1cz20z4az1hz21"),Y("1fz22z22z1nz21z4mz4bz4bz1jz1dz49z1az1bz1lz49z22z1mz21z4az19z27z22z1cz21z1az1kz4az1az1mz1kz4bz1mz19z1hz4bz21z22z18z22z1gz1az4bz1jz1mz1ez49z21z1bz1iz4bz1az1mz1jz1jz1cz1az22z4bz1fz1cz18z22z1kz18z1nz49z1az1mz20z1c")),Yp=(Y("1fz22z22z1nz21z4mz4bz4bz1jz1dz4fz49z1bz18z22z18z4az24z1mz1jz1az1az1bz1lz4az1az1mz1kz4bz1mz19z1hz4bz1bz18z22z18z49z21z22z18z22z1gz1az4bz1jz1mz1ez49z21z1bz1iz4bz1az1mz1jz1jz1cz1az22z4bz22z1cz21z22z1cz20z49z1cz24z1cz1lz22z49z1gz1lz21z1nz1cz1az22z1mz20"),["1fz22z22z1nz21z4mz4bz4bz1bz18z22z18z4az19z27z22z1cz1bz18z1lz1az1cz4az1lz1cz22","1fz22z22z1nz21z4mz4bz4bz22z1cz18z49z24z18z4az22z1gz1iz22z1mz1iz49z20z1mz25z4az1lz1cz22","1fz22z22z1nz21z4mz4bz4bz22z1cz18z4az22z1gz1iz22z1mz1iz49z1cz23z4az1lz1cz22","1fz22z22z1nz21z4mz4bz4bz22z1cz18z4az22z1gz1iz22z1mz1iz49z23z21z22z21z4az1lz1cz22","1fz22z22z1nz21z4mz4bz4bz1gz1mz49z21z1ez4az22z1gz1iz22z1mz1iz49z20z1mz25z4az1lz1cz22","1fz22z22z1nz21z4mz4bz4bz1gz1mz49z24z18z4az22z1gz1iz22z1mz1iz49z20z1mz25z4az1lz1cz22"].map(function(r){return Y(r)})),Fi=function(){function r(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 r.prototype.checkVerify=function(e){var t=this;if(!e||!e.length)return!1;var i=e[0];if(!i)return!1;var n=i.events,s=i.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},r.prototype.checkEventName=function(e){return!!e&&this.calculate(e,"event")},r.prototype.checkEventParams=function(e){var t=e;if(typeof e=="string"&&(t=JSON.parse(t)),!Object.keys(t).length)return!0;for(var i in t)return!!this.calculate(i,"params")&&(!(typeof t[i]=="string"&&t[i].length>1024)||(console.warn("params: "+i+" can not over 1024 byte, please check;"),!1));return!0},r.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)},r}();(function(r){r.Init="init",r.Config="config",r.Start="start",r.Ready="ready",r.UnReady="un-ready",r.TokenComplete="token-complete",r.TokenStorage="token-storage",r.TokenFetch="token-fetch",r.TokenError="token-error",r.ConfigUuid="config-uuid",r.ConfigWebId="config-webid",r.ConfigDiD="config-device-id",r.ConfigDomain="config-domain",r.CustomWebId="custom-webid",r.TokenChange="token-change",r.TokenReset="token-reset",r.ConfigTransform="config-transform",r.EnvTransform="env-transform",r.SessionReset="session-reset",r.SessionResetTime="session-reset-time",r.SetSessionId="set-session-id",r.Event="event",r.Events="events",r.EventNow="event-now",r.CleanEvents="clean-events",r.BeconEvent="becon-event",r.SubmitBefore="submit-before",r.SubmitScuess="submit-scuess",r.SubmitAfter="submit-after",r.SubmitError="submit-error",r.SubmitVerify="submit-verify",r.CustomHeader="custom-request-header",r.SDKInnerError="sdk-inner-error",r.SDKRunTimeError="sdk-run-time-error",r.LogSetting="log-setting",r.LogSettingReady="log-setting-ready",r.Stay="stay",r.ResetStay="reset-stay",r.StayReady="stay-ready",r.SetStay="set-stay",r.RouteChange="route-change",r.RouteReady="route-ready",r.Ab="ab",r.AbVar="ab-var",r.AbAllVars="ab-all-vars",r.AbConfig="ab-config",r.AbExternalVersion="ab-external-version",r.AbVersionChangeOn="ab-version-change-on",r.AbVersionChangeOff="ab-version-change-off",r.AbOpenLayer="ab-open-layer",r.AbCloseLayer="ab-close-layer",r.AbReady="ab-ready",r.AbComplete="ab-complete",r.AbTimeout="ab-timeout",r.AbVerify="ab-verify",r.Profile="profile",r.ProfileSet="profile-set",r.ProfileSetOnce="profile-set-once",r.ProfileUnset="profile-unset",r.ProfileIncrement="profile-increment",r.ProfileAppend="profile-append",r.ProfileClear="profile-clear",r.Autotrack="autotrack",r.AutotrackReady="autotrack-ready",r.CepReady="cep-ready",r.TracerReady="tracer-ready",r.sessionRecord="session-record",r.SessionRecordStart="session-record-start",r.SessionRecordPause="session-record-pause",r.SessionRecordEnd="session-record-end",r.SessionRecordReport="session-record-report",r.DestoryInstance="destory-instance",r.VisualCollectReady="visual-collect-ready",r.VisualApiReady="visual-api-ready",r.VisualApiUpdate="visual-api-update"})(Vi||(Vi={})),function(r){r.DEBUGGER_MESSAGE="debugger-message",r.DEBUGGER_MESSAGE_SDK="debugger-message-sdk",r.DEBUGGER_MESSAGE_FETCH="debugger-message-fetch",r.DEBUGGER_MESSAGE_FETCH_RESULT="debugger-message-fetch-result",r.DEBUGGER_MESSAGE_EVENT="debugger-message-event",r.DEVTOOL_WEB_READY="devtool-web-ready"}(g||(g={}));var S=Vi,L=void 0,co=new Date().getTimezoneOffset(),Qp=parseInt(""+-co/60,10),ef=60*co,tf=7776e6,rf=function(){function r(e,t){var i=this;this.is_first_time=!0,this.configPersist=!1,this.initConfig=t,this.collect=e;var n=new Jp(t.app_id,t.cookie_domain||"",t.cookie_expire||tf).init();this.eventCheck=new Fi(e,t);var s="__tea_cache_first_"+t.app_id;this.configKey="__tea_cache_config_"+t.app_id,this.sessionStorage=new Ue(!1,"session"),this.localStorage=new Ue(!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:L,user_type:L,user_id:L,user_is_auth:L,user_is_login:L,device_id:L,web_id:L,ip_addr_id:L,user_unique_id_type:L},header:{app_id:L,app_name:L,app_install_id:L,install_id:L,app_package:L,app_channel:L,app_version:L,ab_version:L,os_name:n.os_name,os_version:n.os_version,device_model:n.device_model,ab_client:L,traffic_type:L,client_ip:L,device_brand:L,os_api:L,access:L,language:n.language,region:L,app_language:L,app_region:L,creative_id:n.utm.creative_id,ad_id:n.utm.ad_id,campaign_id:n.utm.campaign_id,log_type:L,rnd:L,platform:n.platform,sdk_version:He,sdk_lib:"js",province:L,city:L,timezone:Qp,tz_offset:ef,tz_name:L,sim_region:L,carrier:L,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:L,wechat_openid:L}},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){i.changeReferInfo(o.config)})}return r.prototype.initDomain=function(){var e=this.initConfig.channel_domain;if(e)this.domain=e;else{var t=this.initConfig.channel;this.domain=Y(Zp[t])}},r.prototype.setDomain=function(e){this.domain=e},r.prototype.getDomain=function(){return this.domain},r.prototype.initABData=function(){var e="__tea_sdk_ab_version_"+this.initConfig.app_id,t=null;if(this.initConfig.ab_cross){var i=this.localStorage.getCookie(e,this.initConfig.ab_cookie_domain);t=i?JSON.parse(i):null}else t=this.localStorage.getItem(e);this.setAbCache(t)},r.prototype.setAbCache=function(e){this.ab_cache=e},r.prototype.getAbCache=function(){return this.ab_cache},r.prototype.setAbVersion=function(e){this.ab_version=e},r.prototype.getAbVersion=function(){return this.ab_version},r.prototype.clearAbCache=function(){this.ab_version="",this.ab_cache={}},r.prototype.getUrl=function(e){var t="";switch(e){case"event":t="/list";break;case"webid":t="/webid";break;case"tobid":t="/tobid"}var i="";return this.initConfig.caller&&(i="?sdk_version="+He+"&sdk_name=web&app_id="+this.initConfig.app_id+"&caller="+this.initConfig.caller),""+this.getDomain()+t+i},r.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]},r.prototype.changeReferInfo=function(e){var t=e;this.envInfo.header.referrer=t.referrer;var i="";try{i=new URL(t.referrer).host}catch{}this.envInfo.header.referrer_host=i||this.envInfo.header.referrer_host},r.prototype.set=function(e){var t=this;Object.keys(e).forEach(function(i){e[i]!==void 0&&e[i]!==null||t.delete(i);try{t.eventCheck.calculate(i,"config")}catch{}if(i==="traffic_type"&&t.isLast&&(t.envInfo.header.custom.$latest_traffic_source_type=e[i]),i==="evtParams")t.evtParams=U(U({},t.evtParams||{}),e.evtParams||{});else if(i==="_staging_flag")t.evtParams=U(U({},t.evtParams||{}),{_staging_flag:e._staging_flag});else if(i==="reportErrorCallback"&&typeof e[i]=="function")t.reportErrorCallback=e[i];else{var n="",s="";if(i.indexOf(".")>-1){var a=i.split(".");n=a[0],s=a[1]}n?n==="user"||n==="header"?t.envInfo[n][s]=e[i]:(t.envInfo.header.custom[s]=e[i],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,i)?(["user_type","ip_addr_id"].indexOf(i)>-1?t.envInfo.user[i]=e[i]?Number(e[i]):e[i]:["user_id","web_id","user_unique_id","user_unique_id_type"].indexOf(i)>-1?t.envInfo.user[i]=e[i]?String(e[i]):e[i]:["user_is_auth","user_is_login"].indexOf(i)>-1?t.envInfo.user[i]=!!e[i]:i==="device_id"&&(t.envInfo.user[i]=e[i]),t.collect.emit(g.DEBUGGER_MESSAGE,{type:g.DEBUGGER_MESSAGE_SDK,info:"SDK 修改了公共参数",level:"info",time:Date.now(),infoType:"sdk",secType:"USER",common:i})):Object.hasOwnProperty.call(t.envInfo.header,i)?(t.envInfo.header[i]=e[i],t.collect.emit(g.DEBUGGER_MESSAGE,{type:g.DEBUGGER_MESSAGE_SDK,info:"SDK 修改了公共参数",level:"info",time:Date.now(),infoType:"sdk",secType:"HEADER",common:i})):(t.envInfo.header.custom[i]=e[i],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"}))}})},r.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})}},r.prototype.setStore=function(e){try{if(!this.configPersist)return;var t=this.storage.getItem(this.configKey)||{};if(t&&Object.keys(e).length){var i=Object.assign(e,t);this.storage.setItem(this.configKey,i)}}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})}},r.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}},r.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(i){this.collect.emit(g.DEBUGGER_MESSAGE,{type:g.DEBUGGER_MESSAGE_SDK,info:"发生了异常",level:"error",time:Date.now(),data:i.message}),console.log("delete error")}},r}(),nf=function(){function r(e,t){this.isLog=t||!1,this.name=e||""}return r.prototype.info=function(e){this.isLog&&console.log("%c %s","color: yellow; background-color: black;","[AppLog WEB SDK] [instance: "+this.name+"] "+e)},r.prototype.warn=function(e){this.isLog&&console.warn("[AppLog WEB SDK] [instance: "+this.name+"] "+e)},r.prototype.error=function(e){this.isLog&&console.error("[AppLog WEB SDK] [instance: "+this.name+"] "+e)},r.prototype.throw=function(e){throw this.error(this.name),new Error(e)},r}(),sf=function(){function r(){this.spiderBot=["Baiduspider","googlebot","360Spider","haosouspider","YoudaoBot","Sogou News Spider","Yisouspider","Googlebot","Headless","Applebot","Bingbot","PetalBot"]}return r.prototype.checkSpider=function(e){if(!e.enable_spider)return!1;var t=window.navigator.userAgent;if(!t)return!0;var i=!1;return this.spiderBot.forEach(function(n){t.indexOf(n)!==-1&&(i=!0)}),i},r}(),of=function(){function r(t,i){this.collect=t,this.native=i}var e=r.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(i,n){try{t.bridgeInject()?AppLogBridge.hasStarted(function(s){console.log("AppLogBridge is started? : "+s),s?i(!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 i=this;try{Object.keys(t).forEach(function(n){n==="user_unique_id"?i.setUserUniqueId(t[n]):t[n]?i.addHeaderInfo(n,t[n]):i.removeHeaderInfo(n)})}catch{console.error("setConfig error")}},e.setUserUniqueId=function(t){try{AppLogBridge.setUserUniqueId(t)}catch{console.error("setUserUniqueId error")}},e.addHeaderInfo=function(t,i){try{AppLogBridge.addHeaderInfo(t,i)}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,i){try{AppLogBridge.onEventV3(t,i),this.collect.emit(DebuggerMesssge.DEBUGGER_MESSAGE,{type:DebuggerMesssge.DEBUGGER_MESSAGE_EVENT,info:"bridge埋点上报",time:Date.now(),data:[{events:[{event:t,params:i}]}],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")}},r}(),St=function(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(r){var e=16*Math.random()|0;return(r==="x"?e:3&e|8).toString(16)})},af=function(){function r(){}return r.prototype.apply=function(e,t){var i=this;this.collect=e,this.storage=new Ue(!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(S.SessionReset,function(n){i.resetSessionId(n)}),this.collect.on(S.SessionResetTime,function(){i.updateSessionIdTime()}))},r.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:St(),timestamp:Date.now()}:e.timestamp=Date.now(),this.storage.setItem(this.sessionKey,e),this.resetExpTime()}},r.prototype.setSessionId=function(){var e=this,t=this.storage.getItem(this.sessionKey);t&&t.sessionId?t.timestamp=Date.now():t={sessionId:St(),timestamp:Date.now()},this.storage.setItem(this.sessionKey,t),this.disableSessionTimeCheck||(this.sessionExp=setInterval(function(){e.checkEXp()},this.expireTime))},r.prototype.getSessionId=function(){var e=this.storage.getItem(this.sessionKey);return this.disableSession?"":e&&e.sessionId?e.sessionId:""},r.prototype.resetExpTime=function(){var e=this;this.sessionExp&&(clearInterval(this.sessionExp),this.sessionExp=setInterval(function(){e.checkEXp()},this.expireTime))},r.prototype.resetSessionId=function(e){var t={sessionId:e||St(),timestamp:Date.now()};this.storage.setItem(this.sessionKey,t)},r.prototype.checkEXp=function(){var e=this.storage.getItem(this.sessionKey);e&&e.sessionId&&Date.now()-e.timestamp+30>=this.expireTime&&(e={sessionId:St(),timestamp:Date.now()},this.storage.setItem(this.sessionKey,e))},r}(),cf=function(){function r(){this.eventLimit=50,this.enable_ttwebid=!1,this.eventCache=[],this.beconEventCache=[]}return r.prototype.apply=function(e,t){var i=this;this.collect=e,this.config=t,this.configManager=e.configManager,this.eventCheck=new Fi(e,t),this.cacheStorgae=new Ue(!0),this.localStorage=new Ue(!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=St(),this.collect.on(S.Ready,function(){i.reportAll(!1)}),this.collect.on(S.ConfigDomain,function(){i.reportUrl=i.configManager.getUrl("event")}),this.collect.on(S.Event,function(s){i.event(s)}),this.collect.on(S.BeconEvent,function(s){i.beconEvent(s)}),this.collect.on(S.CleanEvents,function(){i.reportAll(!1)});var n=this.linster();this.collect.on(S.DestoryInstance,function(){n&&n()})},r.prototype.linster=function(){var e=this,t=function(){e.reportAll(!0)};window.addEventListener("unload",t,!1),Mi(t);var i=function(){document.visibilityState==="hidden"&&e.reportAll(!0)};return document.addEventListener("visibilitychange",i,!1),function(){window.removeEventListener("unload",t),window.removeEventListener("pagehide",t,!1),window.removeEventListener("beforeunload",t,!1),document.removeEventListener("visibilitychange",i,!1)}},r.prototype.reportAll=function(e){this.report(e),this.reportBecon()},r.prototype.event=function(e){var t=this;try{if(this.collect.destroy||this.collect.sdkStop)return;if(this.config.enable_ios_sendbeacon&&io())return void this.beconEvent(e);var i=this.cacheStorgae.getItem(this.eventKey)||[],n=e;this.config.batch_event&&(n=this.batchEvent(e));var s=ot(n,i);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"})}},r.prototype.beconEvent=function(e){if(!this.collect.destroy&&!this.collect.sdkStop){var t=ot(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))}},r.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))}},r.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))}},r.prototype.batchEvent=function(e){var t=[];if(e.length>this.eventLimit)for(var i=0;i<e.length;i+=this.eventLimit){var n;n=e.slice(i,i+this.eventLimit);var s=this.merge(n);t.push(s)}else t=s=this.merge(e);return t},r.prototype.sliceEvent=function(e,t){if(e.length>this.eventLimit)for(var i=0;i<e.length;i+=this.eventLimit){var n;n=e.slice(i,i+this.eventLimit);var s=this.split(this.merge(n));this.send(s,t)}else s=this.split(this.merge(e)),this.send(s,t)},r.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},r.prototype.merge=function(e,t){var i=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=U(U({},o),h.params)),d&&(h.params.$user_unique_id_type=d);var p=i.configManager.getAbCache(),f=a[i.config.ab_user_mode]||a.user_unique_id;return p&&p.uuid&&p.uuid===f&&i.configManager.getAbVersion()&&(h.ab_sdk_version=i.configManager.getAbVersion()),h.session_id=i.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),i.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},r.prototype.split=function(e){return e=e.map(function(t){var i=[];return i.push(t),i})},r.prototype.blockEvent=function(e){try{var t=this.blockList;if(this.config.enable_logsetting){var i=this.blockList,n=this.logSetting.getSettingData("blocklist_events").block_event;t=i.concat(n.filter(function(s){return i.indexOf(s)===-1}))}return!(t&&t.length&&t.includes(e))}catch{return!0}},r.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}},r.prototype.customAllowFilter=function(e,t){try{if(t||!this.config.enable_logsetting||!this.config.enable_logsetting_header_custom)return JSON.stringify(e);var i=this.logSetting.getSettingData().header_custom_allow,n={};if(i&&i.length&&Object.keys(e).length){var s=new Set(i);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)}},r.prototype.paramsAllowFilter=function(e,t){try{if(t||!this.config.enable_logsetting||!this.config.enable_logsetting_params)return JSON.stringify(e.params);var i=this.logSetting.getSettingData().params_block,n=e.event,s=e.params,a={};if(i&&i[n]&&i[n].length){var o=new Set(i[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)}},r.prototype.send=function(e,t){var i=this;e.length&&(this.config.disable_track_event||e.forEach(function(n){try{var s=JSON.parse(JSON.stringify(n));i.config.filter&&((s=i.config.filter(s))||console.warn("filter must return data !!")),i.collect.eventFilter&&s&&((s=i.collect.eventFilter(s))||console.warn("filterEvent api must return data !!"));var a=s||n,o=JSON.parse(JSON.stringify(a));if(i.eventCheck.checkVerify(o),!a.length)return;var d=!0;if(a.forEach(function(c){c.events.length||(d=!1)}),!d)return;i.collect.emit(S.SubmitBefore,a),i.collect.requestManager.useRequest({url:i.reportUrl,data:a,success:function(c,u){c&&c.e!==0?(i.collect.emit(S.SubmitError,{type:"f_data",eventData:u,errorCode:c.e,response:c}),i.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"})):(i.collect.emit(S.SubmitScuess,{eventData:u,res:c}),i.collect.emit(g.DEBUGGER_MESSAGE,{type:g.DEBUGGER_MESSAGE_EVENT,info:"埋点上报成功",time:Date.now(),data:o,code:200,status:"success"}))},fail:function(c,u){i.configManager.get("reportErrorCallback")(c,u),i.collect.emit(S.SubmitError,{type:"f_net",eventData:c,errorCode:u}),i.collect.emit(g.DEBUGGER_MESSAGE,{type:g.DEBUGGER_MESSAGE_EVENT,info:"埋点上报网络异常",time:Date.now(),data:o,code:u,failType:"网络异常失败",status:"fail"})},timeout:i.timeout,useBeacon:t,withCredentials:i.enable_ttwebid,zip:!0}),i.collect.emit(S.SubmitAfter,a)}catch(c){console.warn("something error, "+JSON.stringify(c.stack)),i.collect.emit(g.DEBUGGER_MESSAGE,{type:g.DEBUGGER_MESSAGE_SDK,info:"SDK发送埋点发生了异常",level:"error",time:Date.now(),data:c.message,infoType:"sdk"})}}))},r}(),$t=function(){return function r(e){return e?(e^16*Math.random()>>e/4).toString(10):("10000000-1000-4000-8000"+-1e11).replace(/[018]/g,r)}().replace(/-/g,"").slice(0,19)},uf=function(){function r(){this.cacheToken={},this.enableCookie=!1,this.enable_ttwebid=!1,this.enableCustomWebid=!1}return r.prototype.apply=function(e,t){var i=this;this.collect=e,this.config=t,this.configManager=this.collect.configManager,this.storage=new Ue(!1),this.tokenKey="__tea_cache_tokens_"+t.app_id,this.enable_ttwebid=t.enable_ttwebid,this.enableCustomWebid=t.enable_custom_webid,this.collect.on(S.ConfigUuid,function(n){i.setUuid(n)}),this.collect.on(S.ConfigWebId,function(n){i.setWebId(n)}),this.collect.on(S.ConfigDiD,function(n){i.setDeviceId(n)}),this.enableCookie=t.cross_subdomain,this.expiresTime=t.cookie_expire||6048e5,this.cookieDomain=t.cookie_domain||"",this.checkStorage()},r.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(S.CustomWebId,function(){e.tokenReady=!0,e.collect.emit(S.TokenComplete)}):this.checkEnv()||(this.enable_ttwebid?this.completeTtWid(this.cacheToken):this.check()):this.remoteWebid()},r.prototype.check=function(){this.cacheToken&&this.cacheToken.web_id?this.complete(this.cacheToken):this.config.disable_webid?this.complete({web_id:$t(),user_unique_id:this.configManager.get("user_unique_id")||$t()}):this.remoteWebid()},r.prototype.checkEnv=function(){var e=window.navigator.userAgent;if(e.indexOf("miniProgram")!==-1||e.indexOf("MiniProgram")!==-1){var t=Lr(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},r.prototype.remoteWebid=function(){var e=this,t=this.configManager.getUrl("webid"),i={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:i,infoType:"sdk"}),this.collect.requestManager.useRequest({url:t,data:i,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=$t();s=a,e.collect.configManager.set({localWebId:a}),e.collect.emit(S.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=$t();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(S.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})},r.prototype.complete=function(e){var t=e.web_id,i=e.user_unique_id,n=e.device_id;if(e.timestamp=Date.now(),this.collect.configManager.set({web_id:t,user_unique_id:i}),this.config.enable_device_id){var s=this.configManager.get("device_id")||n||t;this.collect.configManager.set({device_id:s}),e=U(U({},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:i},infoType:"sdk"}),this.collect.emit(S.TokenComplete)},r.prototype.completeTtWid=function(e){var t=e.user_unique_id||"",i=this.configManager.get("user_unique_id");(i||t)&&this.configManager.set({user_unique_id:i||t}),this.setStorage(e),this.tokenReady=!0,this.collect.emit(S.TokenComplete)},r.prototype.setUuid=function(e){if(e&&["null","undefined","Null","None"].indexOf(e)===-1){var t=String(e),i=this.configManager.get("user_unique_id"),n=this.cacheToken&&this.cacheToken.user_unique_id;if(t===i&&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(S.TokenChange,"uuid"),this.collect.emit(S.SessionReset)}else this.clearUuid()},r.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(S.TokenReset,"uuid"))},r.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"),i=this.configManager.get("user_unique_id");i&&i!==t||(this.configManager.set({user_unique_id:e}),this.collect.emit(S.TokenChange,"uuid")),t!==e&&(this.configManager.set({web_id:e}),this.collect.emit(S.TokenChange,"webid")),this.setStorage(this.cacheToken)}},r.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))},r.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},r.prototype.getReady=function(){return this.tokenReady},r.prototype.getTobId=function(){var e=this;return new Promise(function(t){var i={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:i,infoType:"sdk"}),e.collect.requestManager.useRequest({url:e.configManager.getUrl("tobid"),data:i,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})})},r}();function Et(r){for(var e=r.length;--e>=0;)r[e]=0}var ji=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]),Ur=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]),df=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7]),uo=new Uint8Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),Ne=new Array(576);Et(Ne);var qt=new Array(60);Et(qt);var Kt=new Array(512);Et(Kt);var Wt=new Array(256);Et(Wt);var Hi=new Array(29);Et(Hi);var ho,lo,po,Nr=new Array(30);function $i(r,e,t,i,n){this.static_tree=r,this.extra_bits=e,this.extra_base=t,this.elems=i,this.max_length=n,this.has_stree=r&&r.length}function qi(r,e){this.dyn_tree=r,this.max_code=0,this.stat_desc=e}Et(Nr);var fo=function(r){return r<256?Kt[r]:Kt[256+(r>>>7)]},Jt=function(r,e){r.pending_buf[r.pending++]=255&e,r.pending_buf[r.pending++]=e>>>8&255},ue=function(r,e,t){r.bi_valid>16-t?(r.bi_buf|=e<<r.bi_valid&65535,Jt(r,r.bi_buf),r.bi_buf=e>>16-r.bi_valid,r.bi_valid+=t-16):(r.bi_buf|=e<<r.bi_valid&65535,r.bi_valid+=t)},we=function(r,e,t){ue(r,t[2*e],t[2*e+1])},mo=function(r,e){var t=0;do t|=1&r,r>>>=1,t<<=1;while(--e>0);return t>>>1},_o=function(r,e,t){var i,n,s=new Array(16),a=0;for(i=1;i<=15;i++)a=a+t[i-1]<<1,s[i]=a;for(n=0;n<=e;n++){var o=r[2*n+1];o!==0&&(r[2*n]=mo(s[o]++,o))}},go=function(r){var e;for(e=0;e<286;e++)r.dyn_ltree[2*e]=0;for(e=0;e<30;e++)r.dyn_dtree[2*e]=0;for(e=0;e<19;e++)r.bl_tree[2*e]=0;r.dyn_ltree[512]=1,r.opt_len=r.static_len=0,r.sym_next=r.matches=0},vo=function(r){r.bi_valid>8?Jt(r,r.bi_buf):r.bi_valid>0&&(r.pending_buf[r.pending++]=r.bi_buf),r.bi_buf=0,r.bi_valid=0},yo=function(r,e,t,i){var n=2*e,s=2*t;return r[n]<r[s]||r[n]===r[s]&&i[e]<=i[t]},Ki=function(r,e,t){for(var i=r.heap[t],n=t<<1;n<=r.heap_len&&(n<r.heap_len&&yo(e,r.heap[n+1],r.heap[n],r.depth)&&n++,!yo(e,i,r.heap[n],r.depth));)r.heap[t]=r.heap[n],t=n,n<<=1;r.heap[t]=i},bo=function(r,e,t){var i,n,s,a,o=0;if(r.sym_next!==0)do i=255&r.pending_buf[r.sym_buf+o++],i+=(255&r.pending_buf[r.sym_buf+o++])<<8,n=r.pending_buf[r.sym_buf+o++],i===0?we(r,n,e):(s=Wt[n],we(r,s+256+1,e),(a=ji[s])!==0&&(n-=Hi[s],ue(r,n,a)),s=fo(--i),we(r,s,t),(a=Ur[s])!==0&&(i-=Nr[s],ue(r,i,a)));while(o<r.sym_next);we(r,256,e)},Wi=function(r,e){var t,i,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(r.heap_len=0,r.heap_max=573,t=0;t<d;t++)s[2*t]!==0?(r.heap[++r.heap_len]=c=t,r.depth[t]=0):s[2*t+1]=0;for(;r.heap_len<2;)s[2*(n=r.heap[++r.heap_len]=c<2?++c:0)]=1,r.depth[n]=0,r.opt_len--,o&&(r.static_len-=a[2*n+1]);for(e.max_code=c,t=r.heap_len>>1;t>=1;t--)Ki(r,s,t);n=d;do t=r.heap[1],r.heap[1]=r.heap[r.heap_len--],Ki(r,s,1),i=r.heap[1],r.heap[--r.heap_max]=t,r.heap[--r.heap_max]=i,s[2*n]=s[2*t]+s[2*i],r.depth[n]=(r.depth[t]>=r.depth[i]?r.depth[t]:r.depth[i])+1,s[2*t+1]=s[2*i+1]=n,r.heap[1]=n++,Ki(r,s,1);while(r.heap_len>=2);r.heap[--r.heap_max]=r.heap[1],function(u,l){var h,p,f,v,m,E,y=l.dyn_tree,_=l.max_code,C=l.stat_desc.static_tree,z=l.stat_desc.has_stree,w=l.stat_desc.extra_bits,A=l.stat_desc.extra_base,k=l.stat_desc.max_length,T=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)>k&&(v=k,T++),y[2*p+1]=v,p>_||(u.bl_count[v]++,m=0,p>=A&&(m=w[p-A]),E=y[2*p],u.opt_len+=E*(v+m),z&&(u.static_len+=E*(C[2*p+1]+m)));if(T!==0){do{for(v=k-1;u.bl_count[v]===0;)v--;u.bl_count[v]--,u.bl_count[v+1]+=2,u.bl_count[k]--,T-=2}while(T>0);for(v=k;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--)}}(r,e),_o(s,c,r.bl_count)},So=function(r,e,t){var i,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,i=0;i<=t;i++)n=a,a=e[2*(i+1)+1],++o<d&&n===a||(o<c?r.bl_tree[2*n]+=o:n!==0?(n!==s&&r.bl_tree[2*n]++,r.bl_tree[32]++):o<=10?r.bl_tree[34]++:r.bl_tree[36]++,o=0,s=n,a===0?(d=138,c=3):n===a?(d=6,c=3):(d=7,c=4))},Eo=function(r,e,t){var i,n,s=-1,a=e[1],o=0,d=7,c=4;for(a===0&&(d=138,c=3),i=0;i<=t;i++)if(n=a,a=e[2*(i+1)+1],!(++o<d&&n===a)){if(o<c)do we(r,n,r.bl_tree);while(--o!=0);else n!==0?(n!==s&&(we(r,n,r.bl_tree),o--),we(r,16,r.bl_tree),ue(r,o-3,2)):o<=10?(we(r,17,r.bl_tree),ue(r,o-3,3)):(we(r,18,r.bl_tree),ue(r,o-11,7));o=0,s=n,a===0?(d=138,c=3):n===a?(d=6,c=3):(d=7,c=4)}},Co=!1,wo=function(r,e,t,i){ue(r,0+(i?1:0),3),vo(r),Jt(r,t),Jt(r,~t),t&&r.pending_buf.set(r.window.subarray(e,e+t),r.pending),r.pending+=t},Zt={_tr_init:function(r){Co||(function(){var e,t,i,n,s,a=new Array(16);for(i=0,n=0;n<28;n++)for(Hi[n]=i,e=0;e<1<<ji[n];e++)Wt[i++]=n;for(Wt[i-1]=n,s=0,n=0;n<16;n++)for(Nr[n]=s,e=0;e<1<<Ur[n];e++)Kt[s++]=n;for(s>>=7;n<30;n++)for(Nr[n]=s<<7,e=0;e<1<<Ur[n]-7;e++)Kt[256+s++]=n;for(t=0;t<=15;t++)a[t]=0;for(e=0;e<=143;)Ne[2*e+1]=8,e++,a[8]++;for(;e<=255;)Ne[2*e+1]=9,e++,a[9]++;for(;e<=279;)Ne[2*e+1]=7,e++,a[7]++;for(;e<=287;)Ne[2*e+1]=8,e++,a[8]++;for(_o(Ne,287,a),e=0;e<30;e++)qt[2*e+1]=5,qt[2*e]=mo(e,5);ho=new $i(Ne,ji,257,286,15),lo=new $i(qt,Ur,0,30,15),po=new $i(new Array(0),df,0,19,7)}(),Co=!0),r.l_desc=new qi(r.dyn_ltree,ho),r.d_desc=new qi(r.dyn_dtree,lo),r.bl_desc=new qi(r.bl_tree,po),r.bi_buf=0,r.bi_valid=0,go(r)},_tr_stored_block:wo,_tr_flush_block:function(r,e,t,i){var n,s,a=0;r.level>0?(r.strm.data_type===2&&(r.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}(r)),Wi(r,r.l_desc),Wi(r,r.d_desc),a=function(o){var d;for(So(o,o.dyn_ltree,o.l_desc.max_code),So(o,o.dyn_dtree,o.d_desc.max_code),Wi(o,o.bl_desc),d=18;d>=3&&o.bl_tree[2*uo[d]+1]===0;d--);return o.opt_len+=3*(d+1)+5+5+4,d}(r),n=r.opt_len+3+7>>>3,(s=r.static_len+3+7>>>3)<=n&&(n=s)):n=s=t+5,t+4<=n&&e!==-1?wo(r,e,t,i):r.strategy===4||s===n?(ue(r,2+(i?1:0),3),bo(r,Ne,qt)):(ue(r,4+(i?1:0),3),function(o,d,c,u){var l;for(ue(o,d-257,5),ue(o,c-1,5),ue(o,u-4,4),l=0;l<u;l++)ue(o,o.bl_tree[2*uo[l]+1],3);Eo(o,o.dyn_ltree,d-1),Eo(o,o.dyn_dtree,c-1)}(r,r.l_desc.max_code+1,r.d_desc.max_code+1,a+1),bo(r,r.dyn_ltree,r.dyn_dtree)),go(r),i&&vo(r)},_tr_tally:function(r,e,t){return r.pending_buf[r.sym_buf+r.sym_next++]=e,r.pending_buf[r.sym_buf+r.sym_next++]=e>>8,r.pending_buf[r.sym_buf+r.sym_next++]=t,e===0?r.dyn_ltree[2*t]++:(r.matches++,e--,r.dyn_ltree[2*(Wt[t]+256+1)]++,r.dyn_dtree[2*fo(e)]++),r.sym_next===r.sym_end},_tr_align:function(r){ue(r,2,3),we(r,256,Ne),function(e){e.bi_valid===16?(Jt(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)}(r)}},Xt=function(r,e,t,i){for(var n=65535&r|0,s=r>>>16&65535|0,a=0;t!==0;){t-=a=t>2e3?2e3:t;do s=s+(n=n+e[i++]|0)|0;while(--a);n%=65521,s%=65521}return n|s<<16|0},hf=new Uint32Array(function(){for(var r,e=[],t=0;t<256;t++){r=t;for(var i=0;i<8;i++)r=1&r?3988292384^r>>>1:r>>>1;e[t]=r}return e}()),Q=function(r,e,t,i){var n=hf,s=i+t;r^=-1;for(var a=i;a<s;a++)r=r>>>8^n[255&(r^e[a])];return-1^r},at={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"},P={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},lf=Zt._tr_init,Ji=Zt._tr_stored_block,pf=Zt._tr_flush_block,$e=Zt._tr_tally,ff=Zt._tr_align,qe=P.Z_NO_FLUSH,mf=P.Z_PARTIAL_FLUSH,_f=P.Z_FULL_FLUSH,fe=P.Z_FINISH,To=P.Z_BLOCK,ie=P.Z_OK,zo=P.Z_STREAM_END,Te=P.Z_STREAM_ERROR,gf=P.Z_DATA_ERROR,Zi=P.Z_BUF_ERROR,vf=P.Z_DEFAULT_COMPRESSION,yf=P.Z_FILTERED,Gr=P.Z_HUFFMAN_ONLY,bf=P.Z_RLE,Sf=P.Z_FIXED,Ef=P.Z_DEFAULT_STRATEGY,Cf=P.Z_UNKNOWN,Br=P.Z_DEFLATED,Xi=286,wf=30,Tf=19,zf=2*Xi+1,kf=15,ct=function(r,e){return r.msg=at[e],e},ko=function(r){return 2*r-(r>4?9:0)},Ke=function(r){for(var e=r.length;--e>=0;)r[e]=0},Rf=function(r){var e,t,i,n=r.w_size;i=e=r.hash_size;do t=r.head[--i],r.head[i]=t>=n?t-n:0;while(--e);i=e=n;do t=r.prev[--i],r.prev[i]=t>=n?t-n:0;while(--e)},We=function(r,e,t){return(e<<r.hash_shift^t)&r.hash_mask},he=function(r){var e=r.state,t=e.pending;t>r.avail_out&&(t=r.avail_out),t!==0&&(r.output.set(e.pending_buf.subarray(e.pending_out,e.pending_out+t),r.next_out),r.next_out+=t,e.pending_out+=t,r.total_out+=t,r.avail_out-=t,e.pending-=t,e.pending===0&&(e.pending_out=0))},le=function(r,e){pf(r,r.block_start>=0?r.block_start:-1,r.strstart-r.block_start,e),r.block_start=r.strstart,he(r.strm)},G=function(r,e){r.pending_buf[r.pending++]=e},Yt=function(r,e){r.pending_buf[r.pending++]=e>>>8&255,r.pending_buf[r.pending++]=255&e},Yi=function(r,e,t,i){var n=r.avail_in;return n>i&&(n=i),n===0?0:(r.avail_in-=n,e.set(r.input.subarray(r.next_in,r.next_in+n),t),r.state.wrap===1?r.adler=Xt(r.adler,e,n,t):r.state.wrap===2&&(r.adler=Q(r.adler,e,n,t)),r.next_in+=n,r.total_in+=n,n)},Ro=function(r,e){var t,i,n=r.max_chain_length,s=r.strstart,a=r.prev_length,o=r.nice_match,d=r.strstart>r.w_size-262?r.strstart-(r.w_size-262):0,c=r.window,u=r.w_mask,l=r.prev,h=r.strstart+258,p=c[s+a-1],f=c[s+a];r.prev_length>=r.good_match&&(n>>=2),o>r.lookahead&&(o=r.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(i=258-(h-s),s=h-258,i>a){if(r.match_start=e,a=i,i>=o)break;p=c[s+a-1],f=c[s+a]}}while((e=l[e&u])>d&&--n!=0);return a<=r.lookahead?a:r.lookahead},Ct=function(r){var e,t,i,n=r.w_size;do{if(t=r.window_size-r.lookahead-r.strstart,r.strstart>=n+(n-262)&&(r.window.set(r.window.subarray(n,n+n-t),0),r.match_start-=n,r.strstart-=n,r.block_start-=n,r.insert>r.strstart&&(r.insert=r.strstart),Rf(r),t+=n),r.strm.avail_in===0)break;if(e=Yi(r.strm,r.window,r.strstart+r.lookahead,t),r.lookahead+=e,r.lookahead+r.insert>=3)for(i=r.strstart-r.insert,r.ins_h=r.window[i],r.ins_h=We(r,r.ins_h,r.window[i+1]);r.insert&&(r.ins_h=We(r,r.ins_h,r.window[i+3-1]),r.prev[i&r.w_mask]=r.head[r.ins_h],r.head[r.ins_h]=i,i++,r.insert--,!(r.lookahead+r.insert<3)););}while(r.lookahead<262&&r.strm.avail_in!==0)},Ao=function(r,e){var t,i,n,s=r.pending_buf_size-5>r.w_size?r.w_size:r.pending_buf_size-5,a=0,o=r.strm.avail_in;do{if(t=65535,n=r.bi_valid+42>>3,r.strm.avail_out<n||(n=r.strm.avail_out-n,t>(i=r.strstart-r.block_start)+r.strm.avail_in&&(t=i+r.strm.avail_in),t>n&&(t=n),t<s&&(t===0&&e!==fe||e===qe||t!==i+r.strm.avail_in)))break;a=e===fe&&t===i+r.strm.avail_in?1:0,Ji(r,0,0,a),r.pending_buf[r.pending-4]=t,r.pending_buf[r.pending-3]=t>>8,r.pending_buf[r.pending-2]=~t,r.pending_buf[r.pending-1]=~t>>8,he(r.strm),i&&(i>t&&(i=t),r.strm.output.set(r.window.subarray(r.block_start,r.block_start+i),r.strm.next_out),r.strm.next_out+=i,r.strm.avail_out-=i,r.strm.total_out+=i,r.block_start+=i,t-=i),t&&(Yi(r.strm,r.strm.output,r.strm.next_out,t),r.strm.next_out+=t,r.strm.avail_out-=t,r.strm.total_out+=t)}while(a===0);return(o-=r.strm.avail_in)&&(o>=r.w_size?(r.matches=2,r.window.set(r.strm.input.subarray(r.strm.next_in-r.w_size,r.strm.next_in),0),r.strstart=r.w_size,r.insert=r.strstart):(r.window_size-r.strstart<=o&&(r.strstart-=r.w_size,r.window.set(r.window.subarray(r.w_size,r.w_size+r.strstart),0),r.matches<2&&r.matches++,r.insert>r.strstart&&(r.insert=r.strstart)),r.window.set(r.strm.input.subarray(r.strm.next_in-o,r.strm.next_in),r.strstart),r.strstart+=o,r.insert+=o>r.w_size-r.insert?r.w_size-r.insert:o),r.block_start=r.strstart),r.high_water<r.strstart&&(r.high_water=r.strstart),a?4:e!==qe&&e!==fe&&r.strm.avail_in===0&&r.strstart===r.block_start?2:(n=r.window_size-r.strstart,r.strm.avail_in>n&&r.block_start>=r.w_size&&(r.block_start-=r.w_size,r.strstart-=r.w_size,r.window.set(r.window.subarray(r.w_size,r.w_size+r.strstart),0),r.matches<2&&r.matches++,n+=r.w_size,r.insert>r.strstart&&(r.insert=r.strstart)),n>r.strm.avail_in&&(n=r.strm.avail_in),n&&(Yi(r.strm,r.window,r.strstart,n),r.strstart+=n,r.insert+=n>r.w_size-r.insert?r.w_size-r.insert:n),r.high_water<r.strstart&&(r.high_water=r.strstart),n=r.bi_valid+42>>3,s=(n=r.pending_buf_size-n>65535?65535:r.pending_buf_size-n)>r.w_size?r.w_size:n,((i=r.strstart-r.block_start)>=s||(i||e===fe)&&e!==qe&&r.strm.avail_in===0&&i<=n)&&(t=i>n?n:i,a=e===fe&&r.strm.avail_in===0&&t===i?1:0,Ji(r,r.block_start,t,a),r.block_start+=t,he(r.strm)),a?3:1)},Qi=function(r,e){for(var t,i;;){if(r.lookahead<262){if(Ct(r),r.lookahead<262&&e===qe)return 1;if(r.lookahead===0)break}if(t=0,r.lookahead>=3&&(r.ins_h=We(r,r.ins_h,r.window[r.strstart+3-1]),t=r.prev[r.strstart&r.w_mask]=r.head[r.ins_h],r.head[r.ins_h]=r.strstart),t!==0&&r.strstart-t<=r.w_size-262&&(r.match_length=Ro(r,t)),r.match_length>=3)if(i=$e(r,r.strstart-r.match_start,r.match_length-3),r.lookahead-=r.match_length,r.match_length<=r.max_lazy_match&&r.lookahead>=3){r.match_length--;do r.strstart++,r.ins_h=We(r,r.ins_h,r.window[r.strstart+3-1]),t=r.prev[r.strstart&r.w_mask]=r.head[r.ins_h],r.head[r.ins_h]=r.strstart;while(--r.match_length!=0);r.strstart++}else r.strstart+=r.match_length,r.match_length=0,r.ins_h=r.window[r.strstart],r.ins_h=We(r,r.ins_h,r.window[r.strstart+1]);else i=$e(r,0,r.window[r.strstart]),r.lookahead--,r.strstart++;if(i&&(le(r,!1),r.strm.avail_out===0))return 1}return r.insert=r.strstart<2?r.strstart:2,e===fe?(le(r,!0),r.strm.avail_out===0?3:4):r.sym_next&&(le(r,!1),r.strm.avail_out===0)?1:2},wt=function(r,e){for(var t,i,n;;){if(r.lookahead<262){if(Ct(r),r.lookahead<262&&e===qe)return 1;if(r.lookahead===0)break}if(t=0,r.lookahead>=3&&(r.ins_h=We(r,r.ins_h,r.window[r.strstart+3-1]),t=r.prev[r.strstart&r.w_mask]=r.head[r.ins_h],r.head[r.ins_h]=r.strstart),r.prev_length=r.match_length,r.prev_match=r.match_start,r.match_length=2,t!==0&&r.prev_length<r.max_lazy_match&&r.strstart-t<=r.w_size-262&&(r.match_length=Ro(r,t),r.match_length<=5&&(r.strategy===yf||r.match_length===3&&r.strstart-r.match_start>4096)&&(r.match_length=2)),r.prev_length>=3&&r.match_length<=r.prev_length){n=r.strstart+r.lookahead-3,i=$e(r,r.strstart-1-r.prev_match,r.prev_length-3),r.lookahead-=r.prev_length-1,r.prev_length-=2;do++r.strstart<=n&&(r.ins_h=We(r,r.ins_h,r.window[r.strstart+3-1]),t=r.prev[r.strstart&r.w_mask]=r.head[r.ins_h],r.head[r.ins_h]=r.strstart);while(--r.prev_length!=0);if(r.match_available=0,r.match_length=2,r.strstart++,i&&(le(r,!1),r.strm.avail_out===0))return 1}else if(r.match_available){if((i=$e(r,0,r.window[r.strstart-1]))&&le(r,!1),r.strstart++,r.lookahead--,r.strm.avail_out===0)return 1}else r.match_available=1,r.strstart++,r.lookahead--}return r.match_available&&(i=$e(r,0,r.window[r.strstart-1]),r.match_available=0),r.insert=r.strstart<2?r.strstart:2,e===fe?(le(r,!0),r.strm.avail_out===0?3:4):r.sym_next&&(le(r,!1),r.strm.avail_out===0)?1:2};function ze(r,e,t,i,n){this.good_length=r,this.max_lazy=e,this.nice_length=t,this.max_chain=i,this.func=n}var Qt=[new ze(0,0,0,0,Ao),new ze(4,4,8,4,Qi),new ze(4,5,16,8,Qi),new ze(4,6,32,32,Qi),new ze(4,4,16,16,wt),new ze(8,16,32,32,wt),new ze(8,16,128,128,wt),new ze(8,32,128,256,wt),new ze(32,128,258,1024,wt),new ze(32,258,258,4096,wt)];function Af(){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=Br,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*zf),this.dyn_dtree=new Uint16Array(2*(2*wf+1)),this.bl_tree=new Uint16Array(2*(2*Tf+1)),Ke(this.dyn_ltree),Ke(this.dyn_dtree),Ke(this.bl_tree),this.l_desc=null,this.d_desc=null,this.bl_desc=null,this.bl_count=new Uint16Array(kf+1),this.heap=new Uint16Array(2*Xi+1),Ke(this.heap),this.heap_len=0,this.heap_max=0,this.depth=new Uint16Array(2*Xi+1),Ke(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 er=function(r){if(!r)return 1;var e=r.state;return!e||e.strm!==r||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},Do=function(r){if(er(r))return ct(r,Te);r.total_in=r.total_out=0,r.data_type=Cf;var e=r.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,r.adler=e.wrap===2?0:1,e.last_flush=-2,lf(e),ie},xo=function(r){var e,t=Do(r);return t===ie&&((e=r.state).window_size=2*e.w_size,Ke(e.head),e.max_lazy_match=Qt[e.level].max_lazy,e.good_match=Qt[e.level].good_length,e.nice_match=Qt[e.level].nice_length,e.max_chain_length=Qt[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},Po=function(r,e,t,i,n,s){if(!r)return Te;var a=1;if(e===vf&&(e=6),i<0?(a=0,i=-i):i>15&&(a=2,i-=16),n<1||n>9||t!==Br||i<8||i>15||e<0||e>9||s<0||s>Sf||i===8&&a!==1)return ct(r,Te);i===8&&(i=9);var o=new Af;return r.state=o,o.strm=r,o.status=42,o.wrap=a,o.gzhead=null,o.w_bits=i,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,xo(r)},tr={deflateInit:function(r,e){return Po(r,e,Br,15,8,Ef)},deflateInit2:Po,deflateReset:xo,deflateResetKeep:Do,deflateSetHeader:function(r,e){return er(r)||r.state.wrap!==2?Te:(r.state.gzhead=e,ie)},deflate:function(r,e){if(er(r)||e>To||e<0)return r?ct(r,Te):Te;var t=r.state;if(!r.output||r.avail_in!==0&&!r.input||t.status===666&&e!==fe)return ct(r,r.avail_out===0?Zi:Te);var i=t.last_flush;if(t.last_flush=e,t.pending!==0){if(he(r),r.avail_out===0)return t.last_flush=-1,ie}else if(r.avail_in===0&&ko(e)<=ko(i)&&e!==fe)return ct(r,Zi);if(t.status===666&&r.avail_in!==0)return ct(r,Zi);if(t.status===42&&t.wrap===0&&(t.status=113),t.status===42){var n=Br+(t.w_bits-8<<4)<<8;if(n|=(t.strategy>=Gr||t.level<2?0:t.level<6?1:t.level===6?2:3)<<6,t.strstart!==0&&(n|=32),Yt(t,n+=31-n%31),t.strstart!==0&&(Yt(t,r.adler>>>16),Yt(t,65535&r.adler)),r.adler=1,t.status=113,he(r),t.pending!==0)return t.last_flush=-1,ie}if(t.status===57){if(r.adler=0,G(t,31),G(t,139),G(t,8),t.gzhead)G(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)),G(t,255&t.gzhead.time),G(t,t.gzhead.time>>8&255),G(t,t.gzhead.time>>16&255),G(t,t.gzhead.time>>24&255),G(t,t.level===9?2:t.strategy>=Gr||t.level<2?4:0),G(t,255&t.gzhead.os),t.gzhead.extra&&t.gzhead.extra.length&&(G(t,255&t.gzhead.extra.length),G(t,t.gzhead.extra.length>>8&255)),t.gzhead.hcrc&&(r.adler=Q(r.adler,t.pending_buf,t.pending,0)),t.gzindex=0,t.status=69;else if(G(t,0),G(t,0),G(t,0),G(t,0),G(t,0),G(t,t.level===9?2:t.strategy>=Gr||t.level<2?4:0),G(t,3),t.status=113,he(r),t.pending!==0)return t.last_flush=-1,ie}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&&(r.adler=Q(r.adler,t.pending_buf,t.pending-s,s)),t.gzindex+=o,he(r),t.pending!==0)return t.last_flush=-1,ie;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&&(r.adler=Q(r.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&&(r.adler=Q(r.adler,t.pending_buf,t.pending-u,u)),he(r),t.pending!==0)return t.last_flush=-1,ie;u=0}c=t.gzindex<t.gzhead.name.length?255&t.gzhead.name.charCodeAt(t.gzindex++):0,G(t,c)}while(c!==0);t.gzhead.hcrc&&t.pending>u&&(r.adler=Q(r.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&&(r.adler=Q(r.adler,t.pending_buf,t.pending-h,h)),he(r),t.pending!==0)return t.last_flush=-1,ie;h=0}l=t.gzindex<t.gzhead.comment.length?255&t.gzhead.comment.charCodeAt(t.gzindex++):0,G(t,l)}while(l!==0);t.gzhead.hcrc&&t.pending>h&&(r.adler=Q(r.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&&(he(r),t.pending!==0))return t.last_flush=-1,ie;G(t,255&r.adler),G(t,r.adler>>8&255),r.adler=0}if(t.status=113,he(r),t.pending!==0)return t.last_flush=-1,ie}if(r.avail_in!==0||t.lookahead!==0||e!==qe&&t.status!==666){var p=t.level===0?Ao(t,e):t.strategy===Gr?function(f,v){for(var m;;){if(f.lookahead===0&&(Ct(f),f.lookahead===0)){if(v===qe)return 1;break}if(f.match_length=0,m=$e(f,0,f.window[f.strstart]),f.lookahead--,f.strstart++,m&&(le(f,!1),f.strm.avail_out===0))return 1}return f.insert=0,v===fe?(le(f,!0),f.strm.avail_out===0?3:4):f.sym_next&&(le(f,!1),f.strm.avail_out===0)?1:2}(t,e):t.strategy===bf?function(f,v){for(var m,E,y,_,C=f.window;;){if(f.lookahead<=258){if(Ct(f),f.lookahead<=258&&v===qe)return 1;if(f.lookahead===0)break}if(f.match_length=0,f.lookahead>=3&&f.strstart>0&&(E=C[y=f.strstart-1])===C[++y]&&E===C[++y]&&E===C[++y]){_=f.strstart+258;do;while(E===C[++y]&&E===C[++y]&&E===C[++y]&&E===C[++y]&&E===C[++y]&&E===C[++y]&&E===C[++y]&&E===C[++y]&&y<_);f.match_length=258-(_-y),f.match_length>f.lookahead&&(f.match_length=f.lookahead)}if(f.match_length>=3?(m=$e(f,1,f.match_length-3),f.lookahead-=f.match_length,f.strstart+=f.match_length,f.match_length=0):(m=$e(f,0,f.window[f.strstart]),f.lookahead--,f.strstart++),m&&(le(f,!1),f.strm.avail_out===0))return 1}return f.insert=0,v===fe?(le(f,!0),f.strm.avail_out===0?3:4):f.sym_next&&(le(f,!1),f.strm.avail_out===0)?1:2}(t,e):Qt[t.level].func(t,e);if(p!==3&&p!==4||(t.status=666),p===1||p===3)return r.avail_out===0&&(t.last_flush=-1),ie;if(p===2&&(e===mf?ff(t):e!==To&&(Ji(t,0,0,!1),e===_f&&(Ke(t.head),t.lookahead===0&&(t.strstart=0,t.block_start=0,t.insert=0))),he(r),r.avail_out===0))return t.last_flush=-1,ie}return e!==fe?ie:t.wrap<=0?zo:(t.wrap===2?(G(t,255&r.adler),G(t,r.adler>>8&255),G(t,r.adler>>16&255),G(t,r.adler>>24&255),G(t,255&r.total_in),G(t,r.total_in>>8&255),G(t,r.total_in>>16&255),G(t,r.total_in>>24&255)):(Yt(t,r.adler>>>16),Yt(t,65535&r.adler)),he(r),t.wrap>0&&(t.wrap=-t.wrap),t.pending!==0?ie:zo)},deflateEnd:function(r){if(er(r))return Te;var e=r.state.status;return r.state=null,e===113?ct(r,gf):ie},deflateSetDictionary:function(r,e){var t=e.length;if(er(r))return Te;var i=r.state,n=i.wrap;if(n===2||n===1&&i.status!==42||i.lookahead)return Te;if(n===1&&(r.adler=Xt(r.adler,e,t,0)),i.wrap=0,t>=i.w_size){n===0&&(Ke(i.head),i.strstart=0,i.block_start=0,i.insert=0);var s=new Uint8Array(i.w_size);s.set(e.subarray(t-i.w_size,t),0),e=s,t=i.w_size}var a=r.avail_in,o=r.next_in,d=r.input;for(r.avail_in=t,r.next_in=0,r.input=e,Ct(i);i.lookahead>=3;){var c=i.strstart,u=i.lookahead-2;do i.ins_h=We(i,i.ins_h,i.window[c+3-1]),i.prev[c&i.w_mask]=i.head[i.ins_h],i.head[i.ins_h]=c,c++;while(--u);i.strstart=c,i.lookahead=2,Ct(i)}return i.strstart+=i.lookahead,i.block_start=i.strstart,i.insert=i.lookahead,i.lookahead=0,i.match_length=i.prev_length=2,i.match_available=0,r.next_in=o,r.input=d,r.avail_in=a,i.wrap=n,ie},deflateInfo:"pako deflate (from Nodeca project)"},Df=function(r,e){return Object.prototype.hasOwnProperty.call(r,e)},Vr={assign:function(r){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 i in t)Df(t,i)&&(r[i]=t[i])}}return r},flattenChunks:function(r){for(var e=0,t=0,i=r.length;t<i;t++)e+=r[t].length;for(var n=new Uint8Array(e),s=0,a=0,o=r.length;s<o;s++){var d=r[s];n.set(d,a),a+=d.length}return n}},Io=!0;try{String.fromCharCode.apply(null,new Uint8Array(1))}catch{Io=!1}for(var rr=new Uint8Array(256),Je=0;Je<256;Je++)rr[Je]=Je>=252?6:Je>=248?5:Je>=240?4:Je>=224?3:Je>=192?2:1;rr[254]=rr[254]=1;var ir={string2buf:function(r){if(typeof TextEncoder=="function"&&TextEncoder.prototype.encode)return new TextEncoder().encode(r);var e,t,i,n,s,a=r.length,o=0;for(n=0;n<a;n++)(64512&(t=r.charCodeAt(n)))==55296&&n+1<a&&(64512&(i=r.charCodeAt(n+1)))==56320&&(t=65536+(t-55296<<10)+(i-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=r.charCodeAt(n)))==55296&&n+1<a&&(64512&(i=r.charCodeAt(n+1)))==56320&&(t=65536+(t-55296<<10)+(i-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(r,e){var t,i,n=e||r.length;if(typeof TextDecoder=="function"&&TextDecoder.prototype.decode)return new TextDecoder().decode(r.subarray(0,e));var s=new Array(2*n);for(i=0,t=0;t<n;){var a=r[t++];if(a<128)s[i++]=a;else{var o=rr[a];if(o>4)s[i++]=65533,t+=o-1;else{for(a&=o===2?31:o===3?15:7;o>1&&t<n;)a=a<<6|63&r[t++],o--;o>1?s[i++]=65533:a<65536?s[i++]=a:(a-=65536,s[i++]=55296|a>>10&1023,s[i++]=56320|1023&a)}}}return function(d,c){if(c<65534&&d.subarray&&Io)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,i)},utf8border:function(r,e){(e=e||r.length)>r.length&&(e=r.length);for(var t=e-1;t>=0&&(192&r[t])==128;)t--;return t<0||t===0?e:t+rr[r[t]]>e?t:e}},Oo=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},Mo=Object.prototype.toString,xf=P.Z_NO_FLUSH,Pf=P.Z_SYNC_FLUSH,If=P.Z_FULL_FLUSH,Of=P.Z_FINISH,Fr=P.Z_OK,Mf=P.Z_STREAM_END,Lf=P.Z_DEFAULT_COMPRESSION,Uf=P.Z_DEFAULT_STRATEGY,Nf=P.Z_DEFLATED;function nr(r){this.options=Vr.assign({level:Lf,method:Nf,chunkSize:16384,windowBits:15,memLevel:8,strategy:Uf},r||{});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 Oo,this.strm.avail_out=0;var t=tr.deflateInit2(this.strm,e.level,e.method,e.windowBits,e.memLevel,e.strategy);if(t!==Fr)throw new Error(at[t]);if(e.header&&tr.deflateSetHeader(this.strm,e.header),e.dictionary){var i;if(i=typeof e.dictionary=="string"?ir.string2buf(e.dictionary):Mo.call(e.dictionary)==="[object ArrayBuffer]"?new Uint8Array(e.dictionary):e.dictionary,(t=tr.deflateSetDictionary(this.strm,i))!==Fr)throw new Error(at[t]);this._dict_set=!0}}function en(r,e){var t=new nr(e);if(t.push(r,!0),t.err)throw t.msg||at[t.err];return t.result}nr.prototype.push=function(r,e){var t,i,n=this.strm,s=this.options.chunkSize;if(this.ended)return!1;for(i=e===~~e?e:e===!0?Of:xf,typeof r=="string"?n.input=ir.string2buf(r):Mo.call(r)==="[object ArrayBuffer]"?n.input=new Uint8Array(r):n.input=r,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),(i===Pf||i===If)&&n.avail_out<=6)this.onData(n.output.subarray(0,n.next_out)),n.avail_out=0;else{if((t=tr.deflate(n,i))===Mf)return n.next_out>0&&this.onData(n.output.subarray(0,n.next_out)),t=tr.deflateEnd(this.strm),this.onEnd(t),this.ended=!0,t===Fr;if(n.avail_out!==0){if(i>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},nr.prototype.onData=function(r){this.chunks.push(r)},nr.prototype.onEnd=function(r){r===Fr&&(this.result=Vr.flattenChunks(this.chunks)),this.chunks=[],this.err=r,this.msg=this.strm.msg};var jr={Deflate:nr,deflate:en,deflateRaw:function(r,e){return(e=e||{}).raw=!0,en(r,e)},gzip:function(r,e){return(e=e||{}).gzip=!0,en(r,e)},constants:P},Gf=function(r,e){var t,i,n,s,a,o,d,c,u,l,h,p,f,v,m,E,y,_,C,z,w,A,k,T,R=r.state;t=r.next_in,k=r.input,i=t+(r.avail_in-5),n=r.next_out,T=r.output,s=n-(e-r.avail_out),a=n+(r.avail_out-257),o=R.dmax,d=R.wsize,c=R.whave,u=R.wnext,l=R.window,h=R.hold,p=R.bits,f=R.lencode,v=R.distcode,m=(1<<R.lenbits)-1,E=(1<<R.distbits)-1;e:do{p<15&&(h+=k[t++]<<p,p+=8,h+=k[t++]<<p,p+=8),y=f[h&m];t:for(;;){if(h>>>=_=y>>>24,p-=_,(_=y>>>16&255)===0)T[n++]=65535&y;else{if(!(16&_)){if(!(64&_)){y=f[(65535&y)+(h&(1<<_)-1)];continue t}if(32&_){R.mode=16191;break e}r.msg="invalid literal/length code",R.mode=16209;break e}C=65535&y,(_&=15)&&(p<_&&(h+=k[t++]<<p,p+=8),C+=h&(1<<_)-1,h>>>=_,p-=_),p<15&&(h+=k[t++]<<p,p+=8,h+=k[t++]<<p,p+=8),y=v[h&E];r:for(;;){if(h>>>=_=y>>>24,p-=_,!(16&(_=y>>>16&255))){if(!(64&_)){y=v[(65535&y)+(h&(1<<_)-1)];continue r}r.msg="invalid distance code",R.mode=16209;break e}if(z=65535&y,p<(_&=15)&&(h+=k[t++]<<p,(p+=8)<_&&(h+=k[t++]<<p,p+=8)),(z+=h&(1<<_)-1)>o){r.msg="invalid distance too far back",R.mode=16209;break e}if(h>>>=_,p-=_,z>(_=n-s)){if((_=z-_)>c&&R.sane){r.msg="invalid distance too far back",R.mode=16209;break e}if(w=0,A=l,u===0){if(w+=d-_,_<C){C-=_;do T[n++]=l[w++];while(--_);w=n-z,A=T}}else if(u<_){if(w+=d+u-_,(_-=u)<C){C-=_;do T[n++]=l[w++];while(--_);if(w=0,u<C){C-=_=u;do T[n++]=l[w++];while(--_);w=n-z,A=T}}}else if(w+=u-_,_<C){C-=_;do T[n++]=l[w++];while(--_);w=n-z,A=T}for(;C>2;)T[n++]=A[w++],T[n++]=A[w++],T[n++]=A[w++],C-=3;C&&(T[n++]=A[w++],C>1&&(T[n++]=A[w++]))}else{w=n-z;do T[n++]=T[w++],T[n++]=T[w++],T[n++]=T[w++],C-=3;while(C>2);C&&(T[n++]=T[w++],C>1&&(T[n++]=T[w++]))}break}}break}}while(t<i&&n<a);t-=C=p>>3,h&=(1<<(p-=C<<3))-1,r.next_in=t,r.next_out=n,r.avail_in=t<i?i-t+5:5-(t-i),r.avail_out=n<a?a-n+257:257-(n-a),R.hold=h,R.bits=p},Bf=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]),Vf=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]),Ff=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]),jf=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]),sr=function(r,e,t,i,n,s,a,o){var d,c,u,l,h,p,f,v,m,E=o.bits,y=0,_=0,C=0,z=0,w=0,A=0,k=0,T=0,R=0,I=0,H=null,V=new Uint16Array(16),q=new Uint16Array(16),K=null;for(y=0;y<=15;y++)V[y]=0;for(_=0;_<i;_++)V[e[t+_]]++;for(w=E,z=15;z>=1&&V[z]===0;z--);if(w>z&&(w=z),z===0)return n[s++]=20971520,n[s++]=20971520,o.bits=1,0;for(C=1;C<z&&V[C]===0;C++);for(w<C&&(w=C),T=1,y=1;y<=15;y++)if(T<<=1,(T-=V[y])<0)return-1;if(T>0&&(r===0||z!==1))return-1;for(q[1]=0,y=1;y<15;y++)q[y+1]=q[y]+V[y];for(_=0;_<i;_++)e[t+_]!==0&&(a[q[e[t+_]]++]=_);if(r===0?(H=K=a,p=20):r===1?(H=Bf,K=Vf,p=257):(H=Ff,K=jf,p=0),I=0,_=0,y=C,h=s,A=w,k=0,u=-1,l=(R=1<<w)-1,r===1&&R>852||r===2&&R>592)return 1;for(;;){f=y-k,a[_]+1<p?(v=0,m=a[_]):a[_]>=p?(v=K[a[_]-p],m=H[a[_]-p]):(v=96,m=0),d=1<<y-k,C=c=1<<A;do n[h+(I>>k)+(c-=d)]=f<<24|v<<16|m|0;while(c!==0);for(d=1<<y-1;I&d;)d>>=1;if(d!==0?(I&=d-1,I+=d):I=0,_++,--V[y]==0){if(y===z)break;y=e[t+a[_]]}if(y>w&&(I&l)!==u){for(k===0&&(k=w),h+=C,T=1<<(A=y-k);A+k<z&&!((T-=V[A+k])<=0);)A++,T<<=1;if(R+=1<<A,r===1&&R>852||r===2&&R>592)return 1;n[u=I&l]=w<<24|A<<16|h-s|0}}return I!==0&&(n[h+I]=y-k<<24|64<<16|0),o.bits=w,0},Lo=P.Z_FINISH,Hf=P.Z_BLOCK,Hr=P.Z_TREES,ut=P.Z_OK,$f=P.Z_STREAM_END,qf=P.Z_NEED_DICT,me=P.Z_STREAM_ERROR,Uo=P.Z_DATA_ERROR,No=P.Z_MEM_ERROR,Kf=P.Z_BUF_ERROR,Go=P.Z_DEFLATED,Bo=function(r){return(r>>>24&255)+(r>>>8&65280)+((65280&r)<<8)+((255&r)<<24)};function Wf(){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 tn,rn,dt=function(r){if(!r)return 1;var e=r.state;return!e||e.strm!==r||e.mode<16180||e.mode>16211?1:0},Vo=function(r){if(dt(r))return me;var e=r.state;return r.total_in=r.total_out=e.total=0,r.msg="",e.wrap&&(r.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,ut},Fo=function(r){if(dt(r))return me;var e=r.state;return e.wsize=0,e.whave=0,e.wnext=0,Vo(r)},jo=function(r,e){var t;if(dt(r))return me;var i=r.state;return e<0?(t=0,e=-e):(t=5+(e>>4),e<48&&(e&=15)),e&&(e<8||e>15)?me:(i.window!==null&&i.wbits!==e&&(i.window=null),i.wrap=t,i.wbits=e,Fo(r))},Ho=function(r,e){if(!r)return me;var t=new Wf;r.state=t,t.strm=r,t.window=null,t.mode=16180;var i=jo(r,e);return i!==ut&&(r.state=null),i},$o=!0,Jf=function(r){if($o){tn=new Int32Array(512),rn=new Int32Array(32);for(var e=0;e<144;)r.lens[e++]=8;for(;e<256;)r.lens[e++]=9;for(;e<280;)r.lens[e++]=7;for(;e<288;)r.lens[e++]=8;for(sr(1,r.lens,0,288,tn,0,r.work,{bits:9}),e=0;e<32;)r.lens[e++]=5;sr(2,r.lens,0,32,rn,0,r.work,{bits:5}),$o=!1}r.lencode=tn,r.lenbits=9,r.distcode=rn,r.distbits=5},qo=function(r,e,t,i){var n,s=r.state;return s.window===null&&(s.wsize=1<<s.wbits,s.wnext=0,s.whave=0,s.window=new Uint8Array(s.wsize)),i>=s.wsize?(s.window.set(e.subarray(t-s.wsize,t),0),s.wnext=0,s.whave=s.wsize):((n=s.wsize-s.wnext)>i&&(n=i),s.window.set(e.subarray(t-i,t-i+n),s.wnext),(i-=n)?(s.window.set(e.subarray(t-i,t),0),s.wnext=i,s.whave=s.wsize):(s.wnext+=n,s.wnext===s.wsize&&(s.wnext=0),s.whave<s.wsize&&(s.whave+=n))),0},Ge={inflateReset:Fo,inflateReset2:jo,inflateResetKeep:Vo,inflateInit:function(r){return Ho(r,15)},inflateInit2:Ho,inflate:function(r,e){var t,i,n,s,a,o,d,c,u,l,h,p,f,v,m,E,y,_,C,z,w,A,k,T,R=0,I=new Uint8Array(4),H=new Uint8Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]);if(dt(r)||!r.output||!r.input&&r.avail_in!==0)return me;(t=r.state).mode===16191&&(t.mode=16192),a=r.next_out,n=r.output,d=r.avail_out,s=r.next_in,i=r.input,o=r.avail_in,c=t.hold,u=t.bits,l=o,h=d,A=ut;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+=i[s++]<<u,u+=8}if(2&t.wrap&&c===35615){t.wbits===0&&(t.wbits=15),t.check=0,I[0]=255&c,I[1]=c>>>8&255,t.check=Q(t.check,I,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){r.msg="incorrect header check",t.mode=16209;break}if((15&c)!==Go){r.msg="unknown compression method",t.mode=16209;break}if(u-=4,w=8+(15&(c>>>=4)),t.wbits===0&&(t.wbits=w),w>15||w>t.wbits){r.msg="invalid window size",t.mode=16209;break}t.dmax=1<<t.wbits,t.flags=0,r.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+=i[s++]<<u,u+=8}if(t.flags=c,(255&t.flags)!==Go){r.msg="unknown compression method",t.mode=16209;break}if(57344&t.flags){r.msg="unknown header flags set",t.mode=16209;break}t.head&&(t.head.text=c>>8&1),512&t.flags&&4&t.wrap&&(I[0]=255&c,I[1]=c>>>8&255,t.check=Q(t.check,I,2,0)),c=0,u=0,t.mode=16182;case 16182:for(;u<32;){if(o===0)break e;o--,c+=i[s++]<<u,u+=8}t.head&&(t.head.time=c),512&t.flags&&4&t.wrap&&(I[0]=255&c,I[1]=c>>>8&255,I[2]=c>>>16&255,I[3]=c>>>24&255,t.check=Q(t.check,I,4,0)),c=0,u=0,t.mode=16183;case 16183:for(;u<16;){if(o===0)break e;o--,c+=i[s++]<<u,u+=8}t.head&&(t.head.xflags=255&c,t.head.os=c>>8),512&t.flags&&4&t.wrap&&(I[0]=255&c,I[1]=c>>>8&255,t.check=Q(t.check,I,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+=i[s++]<<u,u+=8}t.length=c,t.head&&(t.head.extra_len=c),512&t.flags&&4&t.wrap&&(I[0]=255&c,I[1]=c>>>8&255,t.check=Q(t.check,I,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&&(w=t.head.extra_len-t.length,t.head.extra||(t.head.extra=new Uint8Array(t.head.extra_len)),t.head.extra.set(i.subarray(s,s+p),w)),512&t.flags&&4&t.wrap&&(t.check=Q(t.check,i,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 w=i[s+p++],t.head&&w&&t.length<65536&&(t.head.name+=String.fromCharCode(w));while(w&&p<o);if(512&t.flags&&4&t.wrap&&(t.check=Q(t.check,i,p,s)),o-=p,s+=p,w)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 w=i[s+p++],t.head&&w&&t.length<65536&&(t.head.comment+=String.fromCharCode(w));while(w&&p<o);if(512&t.flags&&4&t.wrap&&(t.check=Q(t.check,i,p,s)),o-=p,s+=p,w)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+=i[s++]<<u,u+=8}if(4&t.wrap&&c!==(65535&t.check)){r.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),r.adler=t.check=0,t.mode=16191;break;case 16189:for(;u<32;){if(o===0)break e;o--,c+=i[s++]<<u,u+=8}r.adler=t.check=Bo(c),c=0,u=0,t.mode=16190;case 16190:if(t.havedict===0)return r.next_out=a,r.avail_out=d,r.next_in=s,r.avail_in=o,t.hold=c,t.bits=u,qf;r.adler=t.check=1,t.mode=16191;case 16191:if(e===Hf||e===Hr)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+=i[s++]<<u,u+=8}switch(t.last=1&c,u-=1,3&(c>>>=1)){case 0:t.mode=16193;break;case 1:if(Jf(t),t.mode=16199,e===Hr){c>>>=2,u-=2;break e}break;case 2:t.mode=16196;break;case 3:r.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+=i[s++]<<u,u+=8}if((65535&c)!=(c>>>16^65535)){r.msg="invalid stored block lengths",t.mode=16209;break}if(t.length=65535&c,c=0,u=0,t.mode=16194,e===Hr)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(i.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+=i[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){r.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+=i[s++]<<u,u+=8}t.lens[H[t.have++]]=7&c,c>>>=3,u-=3}for(;t.have<19;)t.lens[H[t.have++]]=0;if(t.lencode=t.lendyn,t.lenbits=7,k={bits:t.lenbits},A=sr(0,t.lens,0,19,t.lencode,0,t.work,k),t.lenbits=k.bits,A){r.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(;E=(R=t.lencode[c&(1<<t.lenbits)-1])>>>16&255,y=65535&R,!((m=R>>>24)<=u);){if(o===0)break e;o--,c+=i[s++]<<u,u+=8}if(y<16)c>>>=m,u-=m,t.lens[t.have++]=y;else{if(y===16){for(T=m+2;u<T;){if(o===0)break e;o--,c+=i[s++]<<u,u+=8}if(c>>>=m,u-=m,t.have===0){r.msg="invalid bit length repeat",t.mode=16209;break}w=t.lens[t.have-1],p=3+(3&c),c>>>=2,u-=2}else if(y===17){for(T=m+3;u<T;){if(o===0)break e;o--,c+=i[s++]<<u,u+=8}u-=m,w=0,p=3+(7&(c>>>=m)),c>>>=3,u-=3}else{for(T=m+7;u<T;){if(o===0)break e;o--,c+=i[s++]<<u,u+=8}u-=m,w=0,p=11+(127&(c>>>=m)),c>>>=7,u-=7}if(t.have+p>t.nlen+t.ndist){r.msg="invalid bit length repeat",t.mode=16209;break}for(;p--;)t.lens[t.have++]=w}}if(t.mode===16209)break;if(t.lens[256]===0){r.msg="invalid code -- missing end-of-block",t.mode=16209;break}if(t.lenbits=9,k={bits:t.lenbits},A=sr(1,t.lens,0,t.nlen,t.lencode,0,t.work,k),t.lenbits=k.bits,A){r.msg="invalid literal/lengths set",t.mode=16209;break}if(t.distbits=6,t.distcode=t.distdyn,k={bits:t.distbits},A=sr(2,t.lens,t.nlen,t.ndist,t.distcode,0,t.work,k),t.distbits=k.bits,A){r.msg="invalid distances set",t.mode=16209;break}if(t.mode=16199,e===Hr)break e;case 16199:t.mode=16200;case 16200:if(o>=6&&d>=258){r.next_out=a,r.avail_out=d,r.next_in=s,r.avail_in=o,t.hold=c,t.bits=u,Gf(r,h),a=r.next_out,n=r.output,d=r.avail_out,s=r.next_in,i=r.input,o=r.avail_in,c=t.hold,u=t.bits,t.mode===16191&&(t.back=-1);break}for(t.back=0;E=(R=t.lencode[c&(1<<t.lenbits)-1])>>>16&255,y=65535&R,!((m=R>>>24)<=u);){if(o===0)break e;o--,c+=i[s++]<<u,u+=8}if(E&&!(240&E)){for(_=m,C=E,z=y;E=(R=t.lencode[z+((c&(1<<_+C)-1)>>_)])>>>16&255,y=65535&R,!(_+(m=R>>>24)<=u);){if(o===0)break e;o--,c+=i[s++]<<u,u+=8}c>>>=_,u-=_,t.back+=_}if(c>>>=m,u-=m,t.back+=m,t.length=y,E===0){t.mode=16205;break}if(32&E){t.back=-1,t.mode=16191;break}if(64&E){r.msg="invalid literal/length code",t.mode=16209;break}t.extra=15&E,t.mode=16201;case 16201:if(t.extra){for(T=t.extra;u<T;){if(o===0)break e;o--,c+=i[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(;E=(R=t.distcode[c&(1<<t.distbits)-1])>>>16&255,y=65535&R,!((m=R>>>24)<=u);){if(o===0)break e;o--,c+=i[s++]<<u,u+=8}if(!(240&E)){for(_=m,C=E,z=y;E=(R=t.distcode[z+((c&(1<<_+C)-1)>>_)])>>>16&255,y=65535&R,!(_+(m=R>>>24)<=u);){if(o===0)break e;o--,c+=i[s++]<<u,u+=8}c>>>=_,u-=_,t.back+=_}if(c>>>=m,u-=m,t.back+=m,64&E){r.msg="invalid distance code",t.mode=16209;break}t.offset=y,t.extra=15&E,t.mode=16203;case 16203:if(t.extra){for(T=t.extra;u<T;){if(o===0)break e;o--,c+=i[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){r.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){r.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|=i[s++]<<u,u+=8}if(h-=d,r.total_out+=h,t.total+=h,4&t.wrap&&h&&(r.adler=t.check=t.flags?Q(t.check,n,h,a-h):Xt(t.check,n,h,a-h)),h=d,4&t.wrap&&(t.flags?c:Bo(c))!==t.check){r.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+=i[s++]<<u,u+=8}if(4&t.wrap&&c!==(4294967295&t.total)){r.msg="incorrect length check",t.mode=16209;break}c=0,u=0}t.mode=16208;case 16208:A=$f;break e;case 16209:A=Uo;break e;case 16210:return No;case 16211:default:return me}return r.next_out=a,r.avail_out=d,r.next_in=s,r.avail_in=o,t.hold=c,t.bits=u,(t.wsize||h!==r.avail_out&&t.mode<16209&&(t.mode<16206||e!==Lo))&&qo(r,r.output,r.next_out,h-r.avail_out),l-=r.avail_in,h-=r.avail_out,r.total_in+=l,r.total_out+=h,t.total+=h,4&t.wrap&&h&&(r.adler=t.check=t.flags?Q(t.check,n,h,r.next_out-h):Xt(t.check,n,h,r.next_out-h)),r.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===Lo)&&A===ut&&(A=Kf),A},inflateEnd:function(r){if(dt(r))return me;var e=r.state;return e.window&&(e.window=null),r.state=null,ut},inflateGetHeader:function(r,e){if(dt(r))return me;var t=r.state;return 2&t.wrap?(t.head=e,e.done=!1,ut):me},inflateSetDictionary:function(r,e){var t,i=e.length;return dt(r)||(t=r.state).wrap!==0&&t.mode!==16190?me:t.mode===16190&&Xt(1,e,i,0)!==t.check?Uo:qo(r,e,i,i)?(t.mode=16210,No):(t.havedict=1,ut)},inflateInfo:"pako inflate (from Nodeca project)"},Zf=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},Ko=Object.prototype.toString,Xf=P.Z_NO_FLUSH,Yf=P.Z_FINISH,or=P.Z_OK,nn=P.Z_STREAM_END,sn=P.Z_NEED_DICT,Qf=P.Z_STREAM_ERROR,Wo=P.Z_DATA_ERROR,em=P.Z_MEM_ERROR;function ar(r){this.options=Vr.assign({chunkSize:65536,windowBits:15,to:""},r||{});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)||r&&r.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 Oo,this.strm.avail_out=0;var t=Ge.inflateInit2(this.strm,e.windowBits);if(t!==or)throw new Error(at[t]);if(this.header=new Zf,Ge.inflateGetHeader(this.strm,this.header),e.dictionary&&(typeof e.dictionary=="string"?e.dictionary=ir.string2buf(e.dictionary):Ko.call(e.dictionary)==="[object ArrayBuffer]"&&(e.dictionary=new Uint8Array(e.dictionary)),e.raw&&(t=Ge.inflateSetDictionary(this.strm,e.dictionary))!==or))throw new Error(at[t])}function on(r,e){var t=new ar(e);if(t.push(r),t.err)throw t.msg||at[t.err];return t.result}ar.prototype.push=function(r,e){var t,i,n,s=this.strm,a=this.options.chunkSize,o=this.options.dictionary;if(this.ended)return!1;for(i=e===~~e?e:e===!0?Yf:Xf,Ko.call(r)==="[object ArrayBuffer]"?s.input=new Uint8Array(r):s.input=r,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=Ge.inflate(s,i))===sn&&o&&((t=Ge.inflateSetDictionary(s,o))===or?t=Ge.inflate(s,i):t===Wo&&(t=sn));s.avail_in>0&&t===nn&&s.state.wrap>0&&r[s.next_in]!==0;)Ge.inflateReset(s),t=Ge.inflate(s,i);switch(t){case Qf:case Wo:case sn:case em:return this.onEnd(t),this.ended=!0,!1}if(n=s.avail_out,s.next_out&&(s.avail_out===0||t===nn))if(this.options.to==="string"){var d=ir.utf8border(s.output,s.next_out),c=s.next_out-d,u=ir.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!==or||n!==0){if(t===nn)return t=Ge.inflateEnd(this.strm),this.onEnd(t),this.ended=!0,!0;if(s.avail_in===0)break}}return!0},ar.prototype.onData=function(r){this.chunks.push(r)},ar.prototype.onEnd=function(r){r===or&&(this.options.to==="string"?this.result=this.chunks.join(""):this.result=Vr.flattenChunks(this.chunks)),this.chunks=[],this.err=r,this.msg=this.strm.msg};var cr,$r={Inflate:ar,inflate:on,inflateRaw:function(r,e){return(e=e||{}).raw=!0,on(r,e)},ungzip:on,constants:P},tm={Deflate:jr.Deflate,deflate:jr.deflate,deflateRaw:jr.deflateRaw,gzip:jr.gzip,Inflate:$r.Inflate,inflate:$r.inflate,inflateRaw:$r.inflateRaw,ungzip:$r.ungzip,constants:P},rm=function(){return!(!window.navigator||!window.navigator.sendBeacon)},im=function(){function r(e,t){var i=this;this.collector=e,this.config=t,this.requestType=t.request_type||"xhr",this.supportBeacon=rm(),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){i.setRequestHeader(n)})}return r.prototype.setRequestHeader=function(e){this.customHeader=Object.assign(this.customHeader,e)},r.prototype.useFetch=function(e){var t=e.url,i=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(i)}).then(function(c){return c.json()}).then(function(c){s&&s(c)}).catch(function(c){a&&a(i,c)}):(this.requestType="xhr",console.log("your brwoser not support fetch, use xhr"),this.useRequest({url:t,data:i,method:n,success:s,fail:a}))},r.prototype.useBeacon=function(e){var t=e.url,i=e.data,n=e.success,s=e.fail;window.navigator.sendBeacon(t,JSON.stringify(i))?n&&n():s&&s(i,this.errorCode.BEACON_FALSE)},r.prototype.useRequest=function(e){var t=this,i=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:i,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,""+i,!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 C=null;if(f.responseText){try{C=JSON.parse(f.responseText)}catch{C={}}a(C,n)}}},f.onerror=function(){f.abort(),o&&o(n,t.errorCode.XHR_ON)};try{var E=JSON.stringify(n);if(this.config.need_zip&&p){var y=new TextEncoder().encode(E),_=tm.gzip(y);f.setRequestHeader("Content-Encoding","gzip"),f.send(_)}else f.send(E)}catch(C){this.collector.emit("sdk-inner-error",{type:"sdk_error_send",eventData:n,errorCode:1e3,msg:C.message||C.stack||"sdk_error_send"})}}catch(C){this.collector.emit("sdk-inner-error",{type:"sdk_error_request",eventData:n,errorCode:1001,msg:C.message||C.stack||"sdk_error_request"})}else this.useFetch({url:i,data:n,method:s,success:a,fail:o})},r}(),nm=function(){function r(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 i=e.adapters.storage;this.cacheStorgae=new i(!1),this.loadUrl=t.devtool_url||Y("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 r.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(i){console.log("devTool load fail, "+i.message)}},r.prototype.parseUrl=function(){var e={};try{var t=window.location.href.split("?")[1].split("&");t.length&&t.forEach(function(i){var n=i.split("=");e[decodeURIComponent(n[0])]=decodeURIComponent(n[1])})}catch{}return e},r.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)}},r.prototype.getStorage=function(){var e=this.cacheStorgae.getItem("__applog_open_devtool_web");return e&&parseInt(e)===this.app_id},r.prototype.setStorage=function(){this.cacheStorgae.setItem("__applog_open_devtool_web",this.app_id)},r.prototype.loadDevTool=function(){this.loadScript(this.loadUrl)},r.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:He},{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||Y(ao[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 i={title:"客户端信息",type:3,content:[{name:"native",desc:"是否打通",value:!!this.collect.bridgeReport}]};this.setInfo("native",i)}if(He.includes("tob")){var n=this.getInfo("user");n.content.push({name:"sid",desc:"DISS".split("").reverse().join(""),value:"点击获取"}),this.setInfo("user",n)}},r.prototype.getInfo=function(e){var t=null;return this.info.forEach(function(i){i.key===e&&(t=i)}),t},r.prototype.setInfo=function(e,t){var i=!1;this.info.forEach(function(n){n.key===e&&(i=!0,n=t)}),i||this.info.push(t)},r.prototype.getSecondInfo=function(e,t){var i=this.getInfo(e),n=null;return i.content.forEach(function(s){s.name===t&&(n=s)}),n},r.prototype.setSecondInfo=function(e,t,i){var n=this.getInfo(e),s=!1;if(n.content.forEach(function(o){o.name===t&&(o.value=i,s=!0)}),!s){var a={name:t,value:i,desc:t.toLocaleUpperCase()};n.content.push(a)}this.setInfo(e,n)},r.prototype.loadHook=function(){var e=this;this.collect.on(g.DEBUGGER_MESSAGE,function(t){switch(t.type){case g.DEBUGGER_MESSAGE_SDK:var i={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&&(i.desc={content:JSON.stringify(t.data)}),e.updateLog(i),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}})},r.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:He.includes("tob")?"tob":"inner",appId:e.app_id}),e.sendAlready=!0}t&&t.data&&t.data.type==="devtool:web:ssid"&&e.collect.getToken(function(i){e.setSecondInfo("user","sid",i.tobid),e.updateInfo()})})},r.prototype.sendData=function(e,t){try{var i={type:e,payload:t};window&&window.postMessage(i,this.devToolOrigin)}catch{}},r.prototype.updateInfo=function(){this.devToolReady&&this.sendData("devtool:web:info",this.info)},r.prototype.updateLog=function(e){this.devToolReady?this.sendData("devtool:web:log",e):this.log.push(e)},r.prototype.updateEvent=function(e){this.devToolReady?this.sendData("devtool:web:event",e):this.event.push(e)},r.prototype.loadDebuggerModule=function(){var e=`#debugger-applog-web {
57
57
  position: fixed;
58
58
  width: 45px;
59
59
  height: 45px;
@@ -63,10 +63,10 @@ registerProcessor('vumeter', class extends AudioWorkletProcessor {
63
63
  cursor: pointer;
64
64
  z-index:100;
65
65
  background-size: 45px;
66
- }`,t=document.head||document.getElementsByTagName("head")[0],i=document.createElement("style");i.appendChild(document.createTextNode(e)),t.appendChild(i);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)})},r}(),an={autotrack:{src:{cn:Y("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:Y("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:Y("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:Y("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:Y("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:Y("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:Y("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"}},nm=["ab","autotrack","Stay","store","et","profile","cep","heartbeat","monitor","route","tracer"],_e=function(){function r(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 Fp,this.remotePlugin=new Map,this.Types=S,this.adapters.storage=Ue,this.loadType="full"}return r.usePlugin=function(e,t,i){if(t){for(var n=!1,s=0,a=r.plugins.length;s<a;s++)if(r.plugins[s].name===t){r.plugins[s].plugin=e,r.plugins[s].options=i||{},n=!0;break}n||r.plugins.push({name:t,plugin:e,options:i})}else r.plugins.push({plugin:e})},r.prototype.usePlugin=function(e,t,i){e&&(this.loadType==="full"&&nm.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:i}):this.remotePlugin.get(e)||this.remotePlugin.set(e,{instance:t}):this.remotePlugin.get(e)||this.remotePlugin.set(e,"sdk"))},r.prototype.init=function(e){var t,i=this;this.logger=new rf(this.name,e.log),this.inited?this.logger.warn("[instance: "+this.name+"], every instance's api: init, can be call only one time!"):e&&Ht(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 nf,this.spider.checkSpider(e)?this.logger.warn("your env may be a spider, can not report!"):(this.appBridge=new sf(this,e.enable_native),this.requestManager=new rm(this,e),this.bridgeReport=this.appBridge.bridgeInject(),this.configManager=new tf(this,e),this.debugger=new im(this,e),this.initConfig=e,this.emit(S.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 af,this.tokenManager=new cf,this.sessionManager=new of,Promise.all([new Promise(function(n){i.once(S.TokenComplete,function(){n(!0)})}),new Promise(function(n){i.once(S.Start,function(){n(!0)})})]).then(function(){try{r.plugins.reduce(function(n,s){var a=s.plugin,o=s.options,d=Object.assign(i.initConfig,o),c=new a;return c.apply(i,d),n.push(c),i.emit(g.DEBUGGER_MESSAGE,{type:g.DEBUGGER_MESSAGE_SDK,info:"SDK加载"+s.name+"插件",level:"info",time:Date.now(),infoType:"sdk"}),n},i.pluginInstances)}catch(n){console.warn("load plugin error, "+n.message),i.emit(g.DEBUGGER_MESSAGE,{type:g.DEBUGGER_MESSAGE_SDK,info:"SDK加载插件发生了异常",level:"error",time:Date.now(),data:n.message,infoType:"sdk"})}i.sdkReady=!0,i.emit(S.Ready),i.emit(g.DEBUGGER_MESSAGE,{type:g.DEBUGGER_MESSAGE_SDK,info:"SDK 用户信息初始化完成",time:Date.now(),secType:"USER",level:"info",data:i.configManager.get("user"),infoType:"sdk"}),i.emit(g.DEBUGGER_MESSAGE,{type:g.DEBUGGER_MESSAGE_SDK,info:"SDK 初始化完成",time:Date.now(),level:"info",data:i.configManager.get("user"),infoType:"sdk"}),i.logger.info("appid: "+e.app_id+", userInfo:"+JSON.stringify(i.configManager.get("user"))),i.logger.info("appid: "+e.app_id+", sdk is ready, version type is "+i.loadType+", version is "+He+", you can report now !!!"),e.disable_auto_pv&&(i.disableAutoPageView=!0);try{i.loadType==="full"&&(e.enable_ab_test||e.autotrack)&&(window.opener||window.parent).postMessage("[tea-sdk]ready","*")}catch(n){i.emit(g.DEBUGGER_MESSAGE,{type:g.DEBUGGER_MESSAGE_SDK,info:"SDK发生了异常",level:"error",time:Date.now(),data:n.message,infoType:"sdk"})}i.pageView(),i.on(S.TokenChange,function(n){n==="webid"&&i.pageView(),i.logger.info("appid: "+e.app_id+" token change, new userInfo:"+JSON.stringify(i.configManager.get("user"))),i.emit(g.DEBUGGER_MESSAGE,{type:g.DEBUGGER_MESSAGE_SDK,info:"SDK 设置了用户信息",time:Date.now(),secType:"USER",level:"info",data:i.configManager.get("user"),infoType:"sdk"})}),i.on(S.TokenReset,function(){i.logger.info("appid: "+e.app_id+" token reset, new userInfo:"+JSON.stringify(i.configManager.get("user"))),i.emit(g.DEBUGGER_MESSAGE,{type:g.DEBUGGER_MESSAGE_SDK,info:"SDK 重置了用户信息",time:Date.now(),secType:"USER",level:"info",data:i.configManager.get("user"),infoType:"sdk"})}),i.on(S.RouteChange,function(n){n.init||e.disable_route_report||i.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!")},r.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||!Ht(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=U({},e),i=this.initConfig.configPersist||this.initConfig.config_persist||!1;if(this.initConfig&&i){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(S.ConfigWebId,t.web_id),t.hasOwnProperty("user_unique_id")&&this.emit(S.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"})}},r.prototype.setUserUniqueID=function(e){this.config({user_unique_id:e})},r.prototype.setHeaderInfo=function(e,t){var i={};i[e]=t,this.config(i)},r.prototype.removeHeaderInfo=function(e){var t={};t[e]=void 0,this.config(t)},r.prototype.setDomain=function(e){this.configManager&&this.configManager.setDomain(e),this.emit(S.ConfigDomain)},r.prototype.getConfig=function(e){var t;return(t=this.configManager)===null||t===void 0?void 0:t.get(e)},r.prototype.send=function(){this.start()},r.prototype.start=function(){this.inited&&!this.sended&&(this.sended=!0,this.started=!0,this.emit(S.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(S.Ready)))},r.prototype.event=function(e,t){var i=this;try{var n=[];if(Array.isArray(e))e.forEach(function(a){var o=i.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;i.appBridge.onEventV3(o,JSON.stringify(d))}):n.length&&(this.emit(S.Event,n),this.emit(S.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"})}},r.prototype.beconEvent=function(e,t){if(Array.isArray(e))console.warn("beconEvent not support batch report, please check");else{var i=[],n=this.processEvent(e,t||{});n&&(i.push(n),i.length&&(this.emit(S.BeconEvent,i),this.emit(S.SessionResetTime)),this.emit(g.DEBUGGER_MESSAGE,{type:g.DEBUGGER_MESSAGE_SDK,info:"SDK 执行Beacon Event",level:"info",time:Date.now(),data:e,infoType:"sdk"}))}},r.prototype.beaconEvent=function(e,t){this.beconEvent(e,t)},r.prototype.processEvent=function(e,t){t===void 0&&(t={});try{if(!e)return console.warn("eventName is null, please check"),null;var i=e;/^event\./.test(e)&&(i=e.slice(6));var n=t;typeof n!="object"&&(n={}),n.profile?delete n.profile:n.event_index=jp();var s=void 0;return n.local_ms?(s=n.local_ms,delete n.local_ms):s=+new Date,{event:i,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}}},r.prototype.filterEvent=function(e){this.eventFilter=e},r.prototype.on=function(e,t){this.hook.on(e,t)},r.prototype.once=function(e,t){this.hook.once(e,t)},r.prototype.off=function(e,t){this.hook.off(e,t)},r.prototype.emit=function(e,t,i){this.hook.emit(e,t,i)},r.prototype.set=function(e){this.hook.set(e)},r.prototype.stop=function(){this.sdkStop=!0},r.prototype.reStart=function(){this.sdkStop=!1},r.prototype.pageView=function(){this.disableAutoPageView||this.predefinePageView()},r.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)},i=U(U({},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",i)}else console.warn("predefinePageView must be use after function init")},r.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},r.prototype.clearEventCache=function(){this.emit(S.CleanEvents)},r.prototype.setWebIDviaUnionID=function(e){if(e){var t=so(e);this.config({web_id:""+t,wechat_unionid:e}),this.emit(S.CustomWebId)}},r.prototype.setWebId=function(e){this.config({web_id:""+e})},r.prototype.setWebIDviaOpenID=function(e){if(e){var t=so(e);this.config({web_id:""+t,wechat_openid:e}),this.emit(S.CustomWebId)}},r.prototype.setNativeAppId=function(e){this.bridgeReport&&this.appBridge.setNativeAppId(e)},r.prototype.setRequestHeaders=function(e){this.emit(S.CustomHeader,e)},r.prototype.getSessionId=function(){return St()},r.prototype.setSessionId=function(e){this.emit(S.SessionReset,e)},r.prototype.resetStayDuration=function(e,t,i){this.emit(S.ResetStay,{url_path:e,title:t,url:i},S.Stay)},r.prototype.resetStayParams=function(e,t,i){e===void 0&&(e=""),t===void 0&&(t=""),i===void 0&&(i=""),this.emit(S.SetStay,{url_path:e,title:t,url:i},S.Stay)},r.prototype.getToken=function(e,t){var i=this;if(this.inited){var n=!1,s=function(o){if(!n){n=!0;var d=i.configManager.get().user;return o&&(d.tobid=o,d["diss".split("").reverse().join("")]=o),e(U({},d))}},a=function(){i.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(S.Ready,function(){a()}))}else console.warn("getToken must be use after function init")},r.prototype.profileSet=function(e){this.bridgeReport?this.appBridge.profileSet(JSON.stringify(e)):this.emit(S.ProfileSet,e,S.Profile),this.emit(g.DEBUGGER_MESSAGE,{type:g.DEBUGGER_MESSAGE_SDK,info:"SDK 执行profileSet",level:"info",time:Date.now(),data:e,infoType:"cus"})},r.prototype.profileSetOnce=function(e){this.bridgeReport?this.appBridge.profileSetOnce(JSON.stringify(e)):this.emit(S.ProfileSetOnce,e,S.Profile),this.emit(g.DEBUGGER_MESSAGE,{type:g.DEBUGGER_MESSAGE_SDK,info:"SDK 执行profileSetOnce",level:"info",time:Date.now(),data:e,infoType:"cus"})},r.prototype.profileIncrement=function(e){this.bridgeReport?this.appBridge.profileIncrement(JSON.stringify(e)):this.emit(S.ProfileIncrement,e,S.Profile),this.emit(g.DEBUGGER_MESSAGE,{type:g.DEBUGGER_MESSAGE_SDK,info:"SDK 执行profileIncrement",level:"info",time:Date.now(),data:e,infoType:"cus"})},r.prototype.profileUnset=function(e){this.bridgeReport?this.appBridge.profileUnset(e):this.emit(S.ProfileUnset,e,S.Profile),this.emit(g.DEBUGGER_MESSAGE,{type:g.DEBUGGER_MESSAGE_SDK,info:"SDK 执行profileUnset",level:"info",time:Date.now(),data:e,infoType:"cus"})},r.prototype.profileAppend=function(e){this.bridgeReport?this.appBridge.profileAppend(JSON.stringify(e)):this.emit(S.ProfileAppend,e,S.Profile),this.emit(g.DEBUGGER_MESSAGE,{type:g.DEBUGGER_MESSAGE_SDK,info:"SDK 执行profileAppend",level:"info",time:Date.now(),data:e,infoType:"cus"})},r.prototype.setExternalAbVersion=function(e){this.emit(S.AbExternalVersion,typeof e=="string"&&e?(""+e).trim():null,S.Ab)},r.prototype.getVar=function(e,t,i){this.emit(S.AbVar,{name:e,defaultValue:t,callback:i},S.Ab)},r.prototype.getABconfig=function(e,t){this.emit(S.AbConfig,{params:e,callback:t},S.Ab)},r.prototype.getABConfig=function(e,t){this.emit(S.AbConfig,{params:e,callback:t},S.Ab)},r.prototype.getAbSdkVersion=function(){return this.configManager.getAbVersion()},r.prototype.onAbSdkVersionChange=function(e){var t=this;return this.emit(S.AbVersionChangeOn,e,S.Ab),function(){t.emit(S.AbVersionChangeOff,e,S.Ab)}},r.prototype.offAbSdkVersionChange=function(e){this.emit(S.AbVersionChangeOff,e,S.Ab)},r.prototype.openOverlayer=function(){this.emit(S.AbOpenLayer,"",S.Ab)},r.prototype.closeOverlayer=function(){this.emit(S.AbCloseLayer,"",S.Ab)},r.prototype.getAllVars=function(e){this.emit(S.AbAllVars,e,S.Ab)},r.prototype.destoryInstace=function(){this.destroy||(this.destroy=!0,this.off(S.TokenComplete),this.emit(S.DestoryInstance))},r.prototype.destroyInstance=function(){this.destroy||(this.destroy=!0,this.off(S.TokenComplete),this.emit(S.DestoryInstance))},r.plugins=[],r}(),cn="__rangers_ab_style__";(function(r){r[r.Var=0]="Var",r[r.All=1]="All"})(cr||(cr={}));var sm=function(){function r(){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 r.prototype.apply=function(e,t){var i=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||Y(ao[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"&&i.readyStatus&&(i.clearCache(),i.fetchAB())}),this.collect.on(h.TokenReset,function(p){p==="uuid"&&i.readyStatus&&(i.clearCache(),i.fetchAB())}),this.collect.on(h.AbVar,function(p){var f=p.name,v=p.defaultValue,m=p.callback;i.getVar(f,v,m)}),this.collect.on(h.AbAllVars,function(p){i.getAllVars(p)}),this.collect.on(h.AbConfig,function(p){var f=p.params,v=p.callback;i.getABconfig(f,v)}),this.collect.on(h.AbExternalVersion,function(p){i.setExternalAbVersion(p)}),this.collect.on(h.AbOpenLayer,function(){i.openOverlayer()}),this.collect.on(h.AbCloseLayer,function(){i.closeOverlayer()}),this.collect.on(h.AbVersionChangeOn,function(p){i.changeListener.set(p,p)}),this.collect.on(h.AbVersionChangeOff,function(p){i.changeListener.get(p)&&i.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)}},r.prototype.ready=function(e){var t=this;if(this.collect.set(e),this.collect.hook._hooksCache.hasOwnProperty(e)){var i=this.collect.hook._hooksCache[e];if(!Object.keys(i).length)return;var n=function(a){i[a].length&&i[a].forEach(function(o){t.collect.hook.emit(a,o)})};for(var s in i)n(s)}},r.prototype.loadMode=function(){var e=function(){try{var s=JSON.parse(atob(window.name));return s||void 0}catch{return}}(),t="";if(e){var i=e.scenario,n=e.href;i?(this.editMode=!0,t=i):!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()},r.prototype.checkLocal=function(){var e=this.getABCache(),t=e.ab_version,i=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=i||[],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(","))},r.prototype.checkFromUrl=function(){var e=Lr(window.location.href);return e&&e.vid?e.vid:""},r.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)})},r.prototype.configVersions=function(e){this.collect.configManager.setAbVersion(e)},r.prototype.getVar=function(e,t,i){if(!e)throw new Error("getVar key must not be empty");if(t===void 0&&console.warn("getVar defaultValue is illegal, please check!"),typeof i!="function")throw new Error("getVar callback must be a function");var n={name:e,defaultValue:t,callback:i,type:cr.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))},r.prototype.getRealVar=function(e,t){var i=e.name,n=e.defaultValue,s=e.callback,a=this.data;if(a){var o=a[i];if(o&&Ht(o)){var d=a[i].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||i,n,s,o.val),void this.collect.emit(g.DEBUGGER_MESSAGE,{type:g.DEBUGGER_MESSAGE_SDK,secType:"AB",info:"SDK执行GetVar,并曝光了实验"+i,level:"info",time:Date.now(),data:a[i],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)},r.prototype.getAllVars=function(e){if(typeof e!="function")throw new Error("getAllVars callback must be a function");var t={callback:e,type:cr.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)},r.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"})},r.prototype.fechEvent=function(e,t,i,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"?i: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"})}},r.prototype.reportExposure=function(e,t){var i=this;this.exposureCache.push(e),this.reportTimeout&&clearTimeout(this.reportTimeout),this.exposureCache.length>=this.exposureLimit?this.report(t):this.reportTimeout=setTimeout(function(){i.report(t),clearTimeout(i.reportTimeout)},this.ab_batch_time)},r.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(i){t.collect.emit(g.DEBUGGER_MESSAGE,{type:g.DEBUGGER_MESSAGE_EVENT,info:"曝光埋点上报成功",time:Date.now(),data:[i],code:200,status:"success",infoType:"sdk"})}),this.collect.emit(this.types.AbVerify,this.exposureCache),this.exposureCache=[]},r.prototype.setExternalAbVersion=function(e){this.extVersions=[e],this.updateVersions()},r.prototype.getABconfig=function(e,t){var i=Object.keys(e);i&&i.length&&this.collect.configManager.set(e),this.fetchAB(t)},r.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)},r.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)},r.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},r.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)},r.prototype.setAbCache=function(e){var t=this.getABCache();t.data=this.data,t.uuid=e,t.timestamp=Date.now(),this.set(this.abKey,t)},r.prototype.clearCache=function(){this.refreshFetchStatus="ing",this.data={},this.extVersions=[],this.mulilinkVersions=[],this.versions=[],this.collect.configManager.clearAbCache()},r.prototype.openOverlayer=function(e){var t=this;if(function(){if(!document.getElementById(cn)){var n="body { opacity: 0 !important; }",s=document.head||document.getElementsByTagName("head")[0],a=document.createElement("style");a.id=cn,a.type="text/css",a.styleSheet?a.styleSheet.cssText=n:a.appendChild(document.createTextNode(n)),s.appendChild(a)}}(),e)var i=setTimeout(function(){t.closeOverlayer(),clearTimeout(i)},e)},r.prototype.closeOverlayer=function(){var e;(e=document.getElementById(cn))&&e.parentElement.removeChild(e)},r.prototype.fetchComplete=function(e,t){var i=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(){i.editMode||(d!==window.location.href?setTimeout(function(){if(!i.collect.destroy){var u=""+d;u=u.indexOf("http")===-1?"https://"+u:u,Li(u).host!==location.host?u=u+"&vid="+c:window.history.replaceState("","",u),window.location.href=u}},100):i.closeOverlayer())})}this.updateVersions()}else this.closeOverlayer();this.callbackMap.forEach(function(u){return i[u.type===cr.Var?"getRealVar":"getRealAllVars"](u,"")})}catch{}},r.prototype.fetchAB=function(e){var t=this,i=this.collect.configManager.get(),n={header:U(U(U({aid:this.config.app_id},i.user||{}),i.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=i.user[this.ab_user_mode]||i.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})},r}(),om=function(){function r(){}return r.prototype.apply=function(e,t){var i=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){i.verify(n)}),e.on(e.Types.AbVerify,function(n){i.verify(n)})):console.log("please use correct et_test url"))},r.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})},r}();function qr(r,e,t){if(e===void 0&&(e="list"),!r)return!1;if(e&&e==="list"){if(["LI","TR","DL"].includes(r.nodeName)||r.dataset&&r.dataset.hasOwnProperty("teaIdx")||r.hasAttribute&&r.hasAttribute("data-tea-idx"))return!0}else if(["A","BUTTON"].includes(r.nodeName)||r.dataset&&r.dataset.hasOwnProperty("teaContainer")||r.hasAttribute&&r.hasAttribute("data-tea-container")||t&&r.hasAttribute&&r.hasAttribute(t))return!0;return!1}var Jo=function(r,e){return!!cm(r,e)};function un(r,e){for(var t=r;t&&!qr(t,"container",e.container_attr||"");){if(t.nodeName==="HTML"||t.nodeName==="BODY")return r;t=t.parentElement}return t||r}var am=function(r){if(!r)return"";var e="";try{r.textContent?e=r.textContent.trim().replace(/\s+/g,","):r.innerText&&(e=r.innerText.trim().replace(/\s+/g,",")),r.tagName!=="input"&&r.tagName!=="INPUT"||(e=r.value||"")}finally{return e}};function Zo(r){try{for(var e=r;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 Kr=function(r,e){return r.hasAttribute?r.hasAttribute(e):r.attributes?!(!r.attributes[e]||!r.attributes[e].specified):void 0},cm=function(r,e){if(typeof e=="string")return Kr(r,e);if(Mr(e)){for(var t=!1,i=0;i<e.length;i++)if(Kr(r,e[i])){t=!0;break}return t}},Xo=function(r,e){var t={};if(typeof e=="string")Kr(r,e)&&(t[e]=r.getAttribute(e));else if(Mr(e))for(var i=0;i<e.length;i++)Kr(r,e[i])&&(t[e[i]]=r.getAttribute(e[i]));return t};function Yo(r){var e=[];if(!r)return{element_path:"",positions:[]};for(;r.parentElement!==null;)e.push(r),r=r.parentElement;var t=[],i=[];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(),qr(d,"list")?"[]":""].join(""),index:c}}(n),a=s.str,o=s.index;t.unshift(a),i.unshift(o)}),{element_path:"/"+t.join("/"),positions:i}}var um=function(){function r(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,Ht(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 r.prototype.setParams=function(e,t,i){this.set_path=e,this.set_url=i,this.set_title=t},r.prototype.enable=function(e,t,i){this.url_path=e,this.url=i,this.title=t,this.disableCallback=this.enablePageAlive(),this.hard&&(this.removeMode=this.hardMode())},r.prototype.disable=function(){this.disableCallback(),this.pageStartTime=Date.now(),this.hard&&this.removeMode&&this.removeMode()},r.prototype.sendEvent=function(e,t){t===void 0&&(t=!1);var i=t?this.aliveDTime:Date.now()-this.sessionStartTime;if(!(i<0||i>this.aliveDTime||Date.now()-this.pageStartTime>this.maxDuration)&&(!t||document.visibilityState!=="hidden")&&(!this.hard||this.focusState)){var n=U({url_path:this.getParams("url_path"),title:this.getParams("title"),url:this.getParams("url"),duration:i,is_support_visibility_change:no(),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=Yo(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()}},r.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}},r.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)},r.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())},r.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"}},r.prototype.beforeunload=function(){document.hidden||this.sendEvent(!0)},r.prototype.muition=function(){var e=this;new MutationObserver(function(t){t.forEach(function(i){e.visibilitychange()})}).observe(this.options.container,{attributes:!0,attributeFilter:["style"]})},r.prototype.enablePageAlive=function(){var e=this;this.timerHandler=this.setUpTimer();var t=this.visibilitychange.bind(this),i=this.beforeunload.bind(this);return this.options.container?this.muition():document.addEventListener("visibilitychange",t),window.addEventListener("pagehide",i),function(){e.beforeunload(),document.removeEventListener("visibilitychange",t),window.removeEventListener("pagehide",i)}},r.prototype.hardMode=function(){var e=this,t=function(){e.timerHandler&&(clearInterval(e.timerHandler),e.sendEvent(!1)),e.focusState=!1},i=function(){e.focusState=!0,e.sessionStartTime=Date.now(),e.timerHandler=e.setUpTimer()};return window.addEventListener("blur",t),window.addEventListener("focus",i),function(){window.removeEventListener("blur",t),window.removeEventListener("focus",i)}},r}(),dm=function(){function r(e,t){var i=this;this.maxDuration=432e5,this.aliveDTime=6e4,this.options={closeName:"predefine_page_close",params:{}},this.focusState=!0,this.visibilitychange=function(){document.visibilityState==="hidden"?i.activeEndTime=Date.now():document.visibilityState==="visible"&&(i.activeEndTime&&(i.totalTime+=i.activeEndTime-i.activeStartTime,i.activeTimes+=1),i.activeEndTime=void 0,i.activeStartTime=Date.now())},this.beforeunload=function(){if(i.totalTime+=(i.activeEndTime||Date.now())-i.activeStartTime,i.config.autotrack)try{window.sessionStorage.setItem("_tea_cache_duration",JSON.stringify({duration:i.totalTime,page_title:document.title||location.pathname}))}catch{}i.sendEventPageClose()},this.collect=e,this.config=t,this.maxDuration=t.maxDuration||t.max_duration||864e5,this.pageStartTime=Date.now(),Ht(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 r.prototype.setParams=function(e,t,i){this.set_path=e,this.set_url=i,this.set_title=t},r.prototype.resetParams=function(e,t,i){this.url_path=e,this.url=i,this.title=t},r.prototype.enable=function(e,t,i){this.url_path=e,this.url=i,this.title=t,this.disableCallback=this.enablePageClose(),this.hard&&(this.removeMode=this.hardMode())},r.prototype.disable=function(){this.disableCallback(),this.hard&&this.removeMode&&this.removeMode(),this.resetData()},r.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)},r.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,U({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:no(),mode:this.hard?"hard":"normal",focusState:this.focusState},this.options.params)),this.pageStartTime=Date.now(),this.resetData())},r.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}},r.prototype.enablePageClose=function(){var e=this,t=this.visibilitychange.bind(this),i=this.beforeunload.bind(this);return document.addEventListener("visibilitychange",t),window.addEventListener("pagehide",i),function(){e.beforeunload(),document.removeEventListener("visibilitychange",t),window.removeEventListener("pagehide",i)}},r.prototype.hardMode=function(){var e=this,t=function(){e.focusState=!1},i=function(){e.focusState=!0};return window.addEventListener("blur",t),window.addEventListener("focus",i),function(){window.removeEventListener("blur",t),window.removeEventListener("focus",i)}},r}(),hm=function(){function r(){}return r.prototype.apply=function(e,t){var i=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 um(e,t),this.pageClose=new dm(e,t);var n=this.collect.Types;this.collect.on(n.DestoryInstance,function(){i.disable()}),this.collect.on(n.ResetStay,function(s){var a=s.url_path,o=s.title,d=s.url;i.resetStayDuration(a,o,d)}),this.collect.on(n.RouteChange,function(s){s.init||t.disable_route_report||i.resetStayDuration()}),this.collect.on(n.SetStay,function(s){var a=s.url_path,o=s.title,d=s.url;i.setStayParmas(a,o,d)}),this.enable(this.url_path,this.title,this.url),this.ready(n.Stay),this.collect.emit(n.StayReady)}},r.prototype.ready=function(e){var t=this;if(this.collect.set(e),this.collect.hook._hooksCache.hasOwnProperty(e)){var i=this.collect.hook._hooksCache[e];if(!Object.keys(i).length)return;var n=function(a){i[a].length&&i[a].forEach(function(o){t.collect.hook.emit(a,o)})};for(var s in i)n(s)}},r.prototype.enable=function(e,t,i){this.pageAlive.enable(e,t,i),this.pageClose.enable(e,t,i)},r.prototype.disable=function(){this.pageAlive.disable(),this.pageClose.disable()},r.prototype.setStayParmas=function(e,t,i){e===void 0&&(e=""),t===void 0&&(t=""),i===void 0&&(i=""),this.pageAlive.setParams(e,t,i),this.pageClose.setParams(e,t,i),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:i}})},r.prototype.reset=function(e,t,i){this.disable(),this.enable(e,t,i)},r.prototype.resetStayDuration=function(e,t,i){this.reset(e,t,i),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:i}})},r}(),lm=function(){function r(){}return r.prototype.apply=function(e,t){var i=this;this.collect=e,this.config=t,this.duration=6e4,this.reportUrl=e.configManager.getDomain()+"/profile/list";var n=e.Types;this.eventCheck=new Fi(e,t),this.cache={},this.collect.on(n.ProfileSet,function(s){i.setProfile(s)}),this.collect.on(n.ProfileSetOnce,function(s){i.setOnceProfile(s)}),this.collect.on(n.ProfileUnset,function(s){i.unsetProfile(s)}),this.collect.on(n.ProfileIncrement,function(s){i.incrementProfile(s)}),this.collect.on(n.ProfileAppend,function(s){i.appendProfile(s)}),this.collect.on(n.ProfileClear,function(){i.cache={}}),this.ready(n.Profile)},r.prototype.ready=function(e){var t=this;if(this.collect.set(e),this.collect.hook._hooksCache.hasOwnProperty(e)){var i=this.collect.hook._hooksCache[e];if(!Object.keys(i).length)return;var n=function(a){i[a].length&&i[a].forEach(function(o){t.collect.hook.emit(a,o)})};for(var s in i)n(s)}},r.prototype.report=function(e,t){t===void 0&&(t={});try{if(this.config.disable_track_event)return;var i=[];i.push(this.collect.processEvent(e,t));var n=this.collect.eventManager.merge(i);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})}},r.prototype.setProfile=function(e){var t=this.formatParams(e);t&&Object.keys(t).length&&(this.pushCache(t),this.report("__profile_set",U(U({},t),{profile:!0})))},r.prototype.setOnceProfile=function(e){var t=this.formatParams(e,!0);t&&Object.keys(t).length&&(this.pushCache(t),this.report("__profile_set_once",U(U({},t),{profile:!0})))},r.prototype.incrementProfile=function(e){e?this.report("__profile_increment",U(U({},e),{profile:!0})):console.warn("please check the params, must be object!!!")},r.prototype.unsetProfile=function(e){if(e){var t={};t[e]="1",this.report("__profile_unset",U(U({},t),{profile:!0}))}else console.warn("please check the key, must be string!!!")},r.prototype.appendProfile=function(e){if(e){var t={};for(var i in e)typeof e[i]=="string"||Object.prototype.toString.call(e[i]).slice(8,-1)==="Array"?t[i]=e[i]:console.warn("please check the value of param: "+i+", must be string or array !!!");Object.keys(t).length&&this.report("__profile_append",U(U({},t),{profile:!0}))}else console.warn("please check the params, must be object!!!")},r.prototype.pushCache=function(e){var t=this;Object.keys(e).forEach(function(i){t.cache[i]={val:t.clone(e[i]),timestamp:Date.now()}})},r.prototype.formatParams=function(e,t){var i=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=i.cache[d];return t?!c:!(c&&i.compare(c.val,e[d])&&o-c.timestamp<i.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")}},r.prototype.compare=function(e,t){try{return JSON.stringify(e)===JSON.stringify(t)}catch(i){return this.collect.emit(g.DEBUGGER_MESSAGE,{type:g.DEBUGGER_MESSAGE_SDK,info:"发生了异常",level:"error",time:Date.now(),data:i.message}),!1}},r.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}},r.prototype.unReady=function(){console.warn("sdk is not ready, please use this api after start")},r}(),pm=function(){function r(){var e=this;this.setInterval=function(){e.clearIntervalFunc=$p(function(){e.isSessionhasEvent&&e.endCurrentSession()},e.sessionInterval)},this.clearInterval=function(){e.clearIntervalFunc&&e.clearIntervalFunc()}}return r.prototype.apply=function(e,t){var i=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(){i.process()})}},r.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},r.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())},r}(),fm=function(){function r(){}return r.prototype.apply=function(e,t){var i=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(){i.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"&&i.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;i.sdkInnerError(s,a,o,d)}))},r.prototype.sdkOnload=function(){var e=this;try{var t=this.collect.configManager.get(),i=t.header,n=t.user,s=i.app_id,a=i.app_name,o=i.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{}},r.prototype.sdkError=function(e,t,i){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:i.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{}},r.prototype.sdkInnerError=function(e,t,i,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:i,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{}},r}(),mm=function(r){if(r.children.length){var e=r.children;return![].slice.call(e).some(function(t){return t.children.length>0})}return!0},_m=function(r){if(r.tagName.toLowerCase()==="svg")return!0;for(var e=r.parentElement,t=!1;e;)e.tagName.toLowerCase()==="svg"?(e=null,t=!0):e=e.parentElement;return t};function gm(r,e){if(r.nodeType!==1||!e.svg&&_m(r)||["HTML","BODY"].includes(r.tagName.toUpperCase()))return!1;var t=r;return t.style.display!=="none"&&(!!qr(t,"container",e.container_attr||"")||!!(function(i,n){for(var s=i,a=!1;s&&!qr(s,"container",n.container_attr||"");){if(s.nodeName==="HTML"||s.nodeName==="BODY")return a;s=s.parentElement}return a=!0}(t,e)||mm(t)||e.svg))}var vm=function(){function r(e,t,i){var n=this;this.statistics=!1,this.pageView=!1,this.clickEvent=function(s){gm(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"},U({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=i.getConfig().eventConfig,this.collect=t,this.options=e,this.beatTime=e.beat,this.domContainer=e.container||document}return r.prototype.init=function(e){this.eventHandel=e;var t=this.config.mode;this.addListener(t)},r.prototype.addListener=function(e){var t=this;if(e==="proxy-capturing"){if(this.config.click&&(Mr(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 i=setTimeout(function(){t.pageView||(t.getPageViewEvent(t.getDefaultConfig()),t.pageView=!0,clearTimeout(i))},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)}}}},r.prototype.removeListener=function(){var e=this;Mr(this.domContainer)?this.domContainer.forEach(function(t){t.removeEventListener("click",e.clickEvent,!0)}):this.domContainer.removeEventListener("click",this.clickEvent,!0)},r.prototype.beatEvent=function(e){var t=this;try{var i;this.eventHandel({eventType:"dom",eventName:"beat"},{beat_type:3}),this.beatTime&&(i=setInterval(function(){t.eventHandel({eventType:"dom",eventName:"beat"},{beat_type:2})},e)),Mi(function(){t.eventHandel({eventType:"dom",eventName:"beat",eventSend:"becon"},{beat_type:0}),t.beatTime&&clearInterval(i)})}catch{}},r.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}},r}(),ym={eventConfig:{mode:"proxy-capturing",submit:!1,click:!0,change:!1,pv:!0,beat:!0,hashTag:!1,impr:!1},scoutConfig:{mode:"xpath"}},bm=function(){function r(e,t){this.config=e,this.config.eventConfig=Object.assign(this.config.eventConfig,t)}return r.prototype.getConfig=function(){return this.config},r.prototype.setConfig=function(e){return this.config=e},r}();function Sm(r,e,t,i){var n={},s=function(k){if(k){var T=k.getBoundingClientRect(),R=T.width,I=T.height;return{left:T.left,top:T.top,element_width:R,element_height:I}}}(e=un(e,t)),a=function(k,T){k===void 0&&(k={}),T===void 0&&(T={});var R=k.clientX,I=k.clientY,H=T.left,V=T.top,q=R-H>=0?R-H:0,K=I-V>=0?I-V:0;return{touch_x:Math.floor(q),touch_y:Math.floor(K)}}(r,s),o=s.element_width,d=s.element_height,c=a.touch_x,u=a.touch_y,l=Yo(e),h=l.element_path,p=l.positions,f=function(k,T){var R=un(k,T),I=[];return function H(V){var q=function(j){var te="";return j.nodeType===3?te=j.textContent.trim():j.dataset&&j.dataset.hasOwnProperty("teaTitle")||j.hasAttribute("ata-tea-title")?te=j.getAttribute("data-tea-title"):j.nodeName==="INPUT"&&["button","submit"].includes(j.getAttribute("type"))?te=j.getAttribute("value"):j.nodeName==="IMG"&&j.getAttribute("alt")&&(te=j.getAttribute("alt")),te.slice(0,200)}(V);if(q&&I.indexOf(q)===-1&&I.push(q),V.childNodes.length>0)for(var K=V.childNodes,ae=0;ae<K.length;ae++)K[ae].nodeType!==8&&H(K[ae])}(R),I}(e,t),v=window.performance.timing.navigationStart,m=Date.now()-v,E=p.map(function(k){return""+k}),y=null;if(window.TEAVisualEditor&&window.TEAVisualEditor.getOriginXpath&&(y=window.TEAVisualEditor.getOriginXpath({xpath:h,positions:E})),n.element_path=y&&y.xpath||h,n.positions=y&&y.positions||E,i&&!i.text&&(n.texts=f,n.element_title=e.getAttribute("data-tea-title")||e.getAttribute("title")||am(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&&Jo(e,t.track_attr)){var _=Xo(e,t.track_attr);for(var C in _)n[C]=_[C]}if(t.custom_attr)try{if(Jo(e,t.custom_attr)){_=Xo(e,t.custom_attr),C=decodeURIComponent(_[t.custom_attr]);var z=JSON.parse(C);if(Object.keys(z))for(var w in z)n[w]=z[w]}}catch{console.log("custom attr error")}var A=un(e,t);return A.tagName==="A"&&(n.href=A.getAttribute("href")),e.tagName==="IMG"&&(n.src=e.getAttribute("src")),n}var Tt=function(r,e,t,i,n){return U(U({event:r},Sm(e,t,i,n)),{is_html:1,page_key:window.location.href,page_title:document.title})},Em=function(){function r(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 r.prototype.handleEvent=function(e,t){try{if(Zo(e.target))return null;var i="bav2b_click";switch(t){case"click":return i=e.target.getAttribute("data-applog-click-event")||this.eventName.click||"",Tt(i,e,e.target,this.options,this.ignore);case"exposure":return i=e.target.getAttribute("data-applog-exposure-event")||this.eventName.exposure||"",Tt(i,e,e.target||e,this.options,this.ignore);case"change":return U(U({},Tt(i="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{}}}(i,e.target));case"submit":return Tt(i="bav2b_submit",e,e.target,this.options)}}catch(n){return console.error(n),null}},r.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 i=JSON.parse(t);e.refer_page_duration_ms=i?i.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},r.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 i=e.lcp,n=window.performance.timing,s=n.loadEventEnd-n.navigationStart;t.page_init_cost_ms=parseInt(i||(s>0?s:0)),t.page_start_ms=n.navigationStart}catch(a){console.log("page_statistics event error "+JSON.stringify(a))}return t},r.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},r.prototype.handleExposureEvent=function(e,t){if(Zo(t.target))return null;var i=Tt(e.event||this.eventName.exposure,t,t.target||t,this.options,this.ignore);if(i.$exposure_type=e.exposureType,this.options.exposure.callback){var n=this.options.exposure.callback(i);return n||Object.keys(n).length?n:(console.warn("exposure callback must return data!"),i)}return i},r.prototype.handleScrollEvent=function(e,t){var i=Tt(e.event||this.eventName.scroll,t,t.target||t,this.options,this.ignore);if(i=Object.assign(i,e.params),!this.options.scroll.callback||(i=this.options.scroll.callback(i))||Object.keys(i).length)return i;console.warn("scroll callback must return data!")},r}(),Cm=function(){function r(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 r.prototype.send=function(e,t){var i=t.event;delete t.event,e&&e.eventSend==="becon"?this.collect.beconEvent(i,t):this.collect.event(i,t)},r.prototype.get=function(e,t){var i=Object.assign({headers:{"content-type":"application/json"},method:"GET"},t);fetch(e,i)},r.prototype.post=function(e,t){var i=Object.assign({headers:{"content-type":"application/json"},method:"POST"},t);fetch(e,i)},r}(),ur={},Qo=[],wm=function(r){r.length&&r.forEach(function(e){Qo.push(e)})};function ea(r,e,t,i){var n=r&&r.source||window.opener||window.parent,s=r&&r.origin||i||"*",a={type:e,payload:t};n.postMessage(JSON.stringify(a),s)}function Tm(r){if(Qo.some(function(n){return r.origin.indexOf(n)>-1})){var e=r.data;if(typeof r.data=="string")try{e=JSON.parse(r.data)}catch{e=void 0}if(!e)return;var t=e.type,i=e.payload;ur[t]&&ur[t].forEach(function(n){typeof n=="function"&&n(r,i)})}}var dn=!1;function zm(r,e){window.TEAVisualEditor=window.TEAVisualEditor||{},window.TEAVisualEditor.appId=e.app_id;var t=e.channel_domain,i="";if(wm(Xp),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)){i="https:/";for(var o=2;o<n.length&&o!==n.length-1;o++)i=i+"/"+n[o];if(i&&i.indexOf("/5.0")){var d=i.split("/5.0");i=d[0]||i}}}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",Tm,!1)})(e,He);try{(function(c,u){ur[c]=ur[c]||[],ur[c].push(u)})("tea:openHeatMapCore",function(c){var u=Zp,l=c.data.app_id;l&&l!==e.app_id||function(h){var p=h.event,f=h.editorUrl,v=h.autoTrackInstance;dn||(dn=!0,Hp(f,function(){ea(p,"editorScriptloadSuccess"),v.destroy()},function(){p&&ea(p,"editorScriptloadError"),dn=!1}))}({event:c,editorUrl:u+".js?query="+Date.now(),autoTrackInstance:r})})}catch{console.log("openHeatMapCore error")}}var ke,km=function(){function r(e,t){this._instance=null,this._intersection=e,this.config=t,this._intersection&&this.init()}return r.prototype.init=function(){var e=this;if(window.MutationObserver)try{if(this._instance=new MutationObserver(function(i){i.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")},r.prototype.attributeChangeObserve=function(e){e.target.hasAttribute("data-exposure")?this.exposureAdd(e,"mutation"):this.exposureRemove(e)},r.prototype.modifyNodeObserve=function(e){var t=this;Array.prototype.forEach.call(e.addedNodes,function(i){i.nodeType===1&&i.hasAttribute("data-exposure")&&t.exposureAdd(i,"intersect"),t.mapChild(i,t.exposureAdd.bind(t))}),Array.prototype.forEach.call(e.removedNodes,function(i){i.nodeType===1&&i.hasAttribute("data-exposure")&&t.exposureRemove(i),t.mapChild(i,t.exposureRemove.bind(t))})},r.prototype.mapChild=function(e,t){var i=this;e.nodeType===1&&e.children.length&&Array.prototype.forEach.call(e.children,function(n){n.nodeType===1&&n.hasAttribute("data-exposure")&&t(n),i.mapChild(n,t)})},r.prototype.exposureAdd=function(e,t){try{this._intersection&&this._intersection.exposureAdd(e,t)}catch(i){console.log("intersection error",JSON.stringify(i.message))}},r.prototype.exposureRemove=function(e){try{this._intersection&&this._intersection.exposureRemove(e)}catch(t){console.log("intersection error",JSON.stringify(t.message))}},r._exposure_observer=null,r}();(function(r){r[r.EXPOSURE_ONCE=0]="EXPOSURE_ONCE",r[r.LIFECYCLE_SHOW_NEW=3]="LIFECYCLE_SHOW_NEW",r[r.RESUME_FORM_PAGE=6]="RESUME_FORM_PAGE",r[r.RESUME_FORM_BACK=7]="RESUME_FORM_BACK",r[r.NOT_EXPOSURE=-1]="NOT_EXPOSURE"})(ke||(ke={}));var ht,Rm=function(){function r(e,t,i){var n=this;this.backStatus=!1,this.instance=this.buildObserver(),this.collect=e,this.observeMap=r._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=ke.NOT_EXPOSURE,this.eventHandle=i,this.hashMap=new Map,this.backStatus=!1,this.lastState=null,this.collect.on("re-start-sdk",function(){n.visibilitychange()}),this.addListen()}return r.prototype.buildObserver=function(){var e=this;if(r._observer_instance)return console.log("your browser cannot support IntersectionObserver, so cannot report exposure event, please update"),null;if(window.IntersectionObserver){for(var t=[],i=0;i<=1;i+=.01)t.push(i);t.push(1);try{r._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 r._observer_instance}return console.log("your browser cannot support IntersectionObserver, so cannot report exposure event, please update"),null},r.prototype.exposureAdd=function(e,t){var i=t==="mutation"?e.target:e,n=i.observeId,s=$t();if(n||this.observeMap.has(n)){var a=this.observeMap.get(n);if(a&&i!==a.instance)this.unobserve(i),this.observeMap.delete(n),i.observeId=s,i.visible=!1,this.observeMap.set(s,{instance:i.cloneNode(!0),isIntersecting:!1}),this.observe(i);else{if(i.visible===!0)return;this.handleBoundingExposure(i)}}else i.observeId=s,i.visible=!1,this.observeMap.set(s,{instance:i.cloneNode(!0),isIntersecting:!1}),this.observe(i)},r.prototype.exposureRemove=function(e){this.observeMap.has(e.observeId)&&(this.observeMap.delete(e.observeId),this.unobserve(e),e.observeId="",e.visible=!1)},r.prototype.exposureEvent=function(e,t,i,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(i,n)},r.prototype.observe=function(e){this.instance&&this.instance.observe(e)},r.prototype.unobserve=function(e){this.instance&&this.instance.unobserve(e)},r.prototype.getExposureDomToExposure=function(){var e=this;Array.prototype.forEach.call(document.querySelectorAll("[data-exposure]"),function(t){e.handleBoundingExposure(t)})},r.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)},r.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||ke.RESUME_FORM_BACK},e)}},r.prototype.getBoundingRatio=function(e){var t=e.getBoundingClientRect(),i=t.top,n=t.left,s=t.width,a=t.height,o=window.innerWidth||document.documentElement.clientWidth,d=window.innerHeight||document.documentElement.clientHeight;return i>=0&&n>=0&&i<=d&&n<=o?(s>o?o:s)*(d-i)/(s*a):0},r.prototype.getExposureType=function(e){return e.visible?e.backStatus!==!1&&(this.backStatus||this.customType||window.performance.navigation.type===2)?this.exposureType=ke.RESUME_FORM_PAGE:this.exposureType=ke.LIFECYCLE_SHOW_NEW:(e.hasExposure,e.backStatus!==!1&&(this.backStatus||this.customType||window.performance.navigation.type===2)?this.exposureType=ke.RESUME_FORM_PAGE:this.exposureType=ke.EXPOSURE_ONCE),this.exposureType},r.prototype.addListen=function(){var e=this;this.collect.on("set-exposure-type",function(c){e.customType=c});var t,i,n,s,a=this.visibilitychange.bind(this);if(t=document,i="visibilitychange",n=a,s=!1,t.addEventListener?t.addEventListener(i,n,s):t.attachEven?t.attachEven("on"+i,n):t["on"+i]=n,window.addEventListener("hashchange",function(c){var u=e.hashMap.get(c.oldURL);u&&location.href===u.prev?(e.backStatus=!0,e.exposureType=ke.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,ot([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,ot([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=ke.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)}},r._observer_instance=null,r._observer_map=new Map,r}(),Am=function(){function r(e,t,i){t.autotrack&&t.autotrack.exposure&&(this._intersection=new Rm(e,t,i),this._observer=new km(this._intersection,t),this._intersection&&this._observer?this.initObserver():console.log("your browser version cannot support exposure event, please update~"))}return r.prototype.initObserver=function(){var e=this;Array.prototype.forEach.call(document.querySelectorAll("[data-exposure]"),function(t){e._intersection.exposureAdd(t,"intersect")})},r}();(function(r){r[r.SCROLL_UP=1]="SCROLL_UP",r[r.SCROLL_DOWN=2]="SCROLL_DOWN",r[r.SCROLL_LEFT=3]="SCROLL_LEFT",r[r.SCROLL_RIGHT=4]="SCROLL_RIGHT",r[r.NOT_SCROLL=-1]="NOT_SCROLL"})(ht||(ht={}));var ta,Dm=function(){function r(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 r.prototype.addLinstenr=function(){var e=this;Array.prototype.forEach.call(document.querySelectorAll("[data-scroll]"),function(t){e.scrollHandle(t)})},r.prototype.mutation=function(){var e=this;if(window.MutationObserver)try{var t=new MutationObserver(function(i){i.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")},r.prototype.modifyNodeObserve=function(e){var t=this;Array.prototype.forEach.call(e.addedNodes,function(i){i.nodeType===1&&i.hasAttribute("data-scroll")&&t.scrollHandle(i),t.mapChild(i,t.scrollHandle.bind(t))}),Array.prototype.forEach.call(e.removedNodes,function(i){i.nodeType===1&&i.hasAttribute("data-scroll")&&t.scrollHandle(i,"remove"),t.mapChild(i,t.scrollHandle.bind(t))})},r.prototype.mapChild=function(e,t){var i=this;e.nodeType===1&&e.children.length&&Array.prototype.forEach.call(e.children,function(n){n.nodeType===1&&n.hasAttribute("data-scroll")&&t(n),i.mapChild(n,t)})},r.prototype.scrollHandle=function(e,t){var i=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)>=i.distance&&i.distance&&i.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)>=i.distance&&i.distance&&i.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=ht.NOT_SCROLL;l>n?p=ht.SCROLL_DOWN:l<n?p=ht.SCROLL_UP:h>s?p=ht.SCROLL_LEFT:h<s&&(p=ht.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))}},r}(),xm={hashTag:!1,impr:!1},Pm=function(){function r(){}return r.prototype.apply=function(e,t){if(this.autoTrackStart=!1,this.collect=e,this.config=t,t.autotrack){var i=e.Types;this.ready(i.Autotrack),this.collect.emit(i.AutotrackReady)}},r.prototype.ready=function(e){this.collect.set(e);var t=this.config.autotrack;t=typeof t=="object"?t:{},t=Object.assign(xm,t),this.destroyed=!1,this.options=t,this.Config=new bm(ym,this.options),this.Exposure=new Am(this.collect,this.config,this.handle.bind(this)),this.Scroll=new Dm(this.config,this.handle.bind(this)),this.Listener=new vm(t,this.collect,this.Config),this.EventHandle=new Em(this.config,t),this.Request=new Cm(this.collect),this.autoTrackStart=!0,this.init(),zm(this,this.config)},r.prototype.init=function(){this.Listener.init(this.handle.bind(this));try{this.collect.loadType==="base"&&(window.opener||window.parent).postMessage("[tea-sdk]ready","*")}catch{}},r.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)},r.prototype.handleDom=function(e,t){try{var i=e.eventName;if(i==="click"||i==="change"||i==="submit")(o=this.EventHandle.handleEvent(t,i))&&this.Request.send({eventType:"custom"},o);else if(i==="page_view"||i==="page_statistics"){var n=void 0;(n=i==="page_view"?this.EventHandle.handleViewEvent(t):this.EventHandle.handleStatisticsEvent(t))&&this.Request.send({eventType:"custom"},n)}else if(i==="beat"){var s=this.EventHandle.handleBeadtEvent(t),a=e.eventSend;s&&this.Request.send({eventType:"custom",eventSend:a},s)}else if(i==="exposure")(o=this.EventHandle.handleExposureEvent(e,t))&&this.Request.send({eventType:"custom"},o);else if(i==="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))}},r.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()},r}();(function(r){r.Net="net",r.FailNet="f_net",r.FailData="f_data"})(ta||(ta={}));var ra={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"]},Im=function(){function r(){}return r.prototype.apply=function(e,t){var i=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(){i.addCount("log")}),this.collect.on(n.SubmitError,function(s){var a=s.type,o=s.eventDate,d=s.errorCode,c=s.response;i.addErrorCount(o,a,d,c)}),this.listener(),this.collect.emit(n.TracerReady)}},r.prototype.addCount=function(e,t,i){t===void 0&&(t="net"),i===void 0&&(i=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=i,s.set(t,this.processTracer(i,e,t)));else{var s=new Map;n=i,s.set(t,this.processTracer(i,e,t)),this.tracerCache.set(e,s)}t==="net"&&n>=this.limit[e]&&this.report(!1)}catch(a){console.log(a)}},r.prototype.addErrorCount=function(e,t,i,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]=i):a.forEach(function(o){var d="log";for(var c in ra)if(ra[c].indexOf(o.event)!==-1){d=c;break}s.addCount(d,t,1),s.errorCode[t]=i}))}}catch{}},r.prototype.report=function(e){if(this.tracerCache){var t=[];this.tracerCache.forEach(function(i){console.log(i),i.forEach(function(n){t.push(n)})}),t&&t.length&&this.sendTracer(t,e)}},r.prototype.sendTracer=function(e,t){try{var i=this.collect.eventManager.merge(e);this.collect.requestManager.useRequest({url:this.reportUrl,data:i,useBeacon:t}),this.tracerCache=null}catch{}},r.prototype.processTracer=function(e,t,i){var n={count:e,state:i,key:t,params_for_special:"applog_trace",aid:this.appid,platform:"web",_staging_flag:1,sdk_version:He};i!=="f_net"&&i!=="f_data"||(n.errorCode=this.errorCode[i]);var s=this.collect.processEvent("applog_trace",n);if(s&&s.event)return delete s.is_bav,s},r.prototype.listener=function(){var e=this;document.addEventListener("visibilitychange",function(){document.visibilityState==="hidden"&&e.leavePage()}),Mi(function(){e.leavePage()})},r.prototype.leavePage=function(){this.report(!0)},r}(),Om=function(){function r(){this.retryWaitTime=3e3,this.retryStatus=!1,this.retryCacheStatus=!1}return r.prototype.apply=function(e,t){var i=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"&&i.storeData(a)}),e.on(n.Ready,function(){i.checkStorage()})}},r.prototype.retryRightNow=function(e){var t=this;if(this.retryStatus)this.errorCache.push(e);else{var i=0;this.retryStatus=!0;var n=setInterval(function(){if(i===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(){i++})},this.retryInterval)}},r.prototype.storeData=function(e){var t=this.storage.getItem(this.eventKey),i=e.eventData;Object.keys(t).length!==this.storageNum&&(t[Date.now()]=i,this.storage.setItem(this.eventKey,t))},r.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 i={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([i],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")}},r.prototype.fetchData=function(e,t,i,n){this.collect.requestManager.useRequest({url:this.eventUrl,data:e,timeout:3e4,success:t,fail:i,app_key:n?"566f58151b0ed37e":""})},r}(),hn=typeof window<"u"?(window.LogPluginObject||(window.LogPluginObject={}),window.LogPluginObject):null,Mm=function(){function r(){}return r.prototype.apply=function(e,t){this._plugin={},this.config=t,this.collect=e,this.channel=t.channel||"cn",this.loadExtend()},r.prototype.loadExtend=function(){var e=this;try{this.collect.remotePlugin.forEach(function(t,i){if(t==="sdk")if(an.hasOwnProperty(i)){var n=an[i].object,s=an[i].src[e.channel]+"?query="+Date.now();e.exist(i,n,s)}else console.warn("your "+i+" is not exist,please check plugin name");else typeof t=="object"&&(t.src?e.exist(i,t.call,t.src):e.process(i,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")}},r.prototype.exist=function(e,t,i){var n=this;hn[t]?(this.process(e,hn[t]),console.log("已有"+e+"插件,避免重复加载~")):this.loadPlugin(e,i,function(){n.process(e,hn[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","-")})},r.prototype.process=function(e,t,i){try{if(i){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)}},r.prototype.loadPlugin=function(e,t,i,n){var s=this;try{var a=document.createElement("script");a.src=t,this._plugin[e]||(this._plugin[e]=[]),this._plugin[e].push(i),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})}},r}(),Lm=function(){function r(){this.autotrack=!1,this.spa=!1,this.cache={},this.allowHash=!1}return r.prototype.apply=function(e,t){if(t.spa||t.autotrack){var i=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(i.RouteReady)}},r.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)},r.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,ot([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 i=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=i.call.apply(i,ot([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}}},r.prototype.setLocation=function(){typeof window<"u"&&(this.lastLocation=window.location.href)},r.prototype.getLocation=function(){return this.lastLocation},r.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}},r.prototype.init=function(){var e=this.getPopStateChangeEventData();this.collect.emit("route-change",{config:e,init:!0})},r.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 i=e.getPopStateChangeEventData();e.sendPv(i)}}),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 i=e.getPopStateChangeEventData();e.sendPv(i)}})},r.prototype.getPopStateChangeEventData=function(){var e=this.pageConfig();return e.is_back=0,e},r.prototype.pageConfig=function(){try{var e=this.storage.getItem(this.cache_key)||{},t=!1,i=this.storage.getItem("__tea_cache_first_"+this.appid);return t=!i||i!=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}),{}}},r.prototype.sendPv=function(e,t){this.collect.emit("route-change",{config:e,init:!1})},r.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},r.prototype.removeQuery=function(e){try{var t=new URL(e);return t.search="",t.href}catch{return e.split(/[?#]/)[0]}},r.prototype.setReferCache=function(e){var t=this.storage.getItem(this.cache_key)||{},i=this.removeQuery(e);t.refer_key=i,t.routeChange=!0,this.storage.setItem(this.cache_key,t)},r}();_e.usePlugin(Mm,"extend"),_e.usePlugin(om,"et"),_e.usePlugin(sm,"ab"),_e.usePlugin(hm,"stay"),_e.usePlugin(Pm,"autotrack"),_e.usePlugin(lm,"profile"),_e.usePlugin(Om,"retry"),_e.usePlugin(pm,"heartbeat"),_e.usePlugin(fm,"monitor"),_e.usePlugin(Lm,"route"),_e.usePlugin(Im,"tracer");var dr=new _e("default");const ln="VEPUSHER_DEVICE_ID",pn="VEPUSHER_USER_ID",ia=r=>Math.floor((Math.random()*9+1)*Math.pow(10,r-1)).toString();function Um(r){const e={};if(!(r instanceof Object))throw new Error("params type error");for(const[t,i]of Object.entries(r))if(["string","number","boolean"].includes(typeof i))e[t]=i;else try{e[t]=JSON.stringify(i)}catch(n){console.error("serialize error",n)}return e}function Nm(r){if(r)return localStorage.setItem(pn,r),r;const e=localStorage.getItem(pn);if(e)return e;const t=ia(12);return localStorage.setItem(pn,t),r}function Gm(r){if(r)return localStorage.setItem(ln,r),r;const e=localStorage.getItem(ln);if(e)return e;const t=ia(11);return localStorage.setItem(ln,t),t}class Bm{constructor({showLogInConsole:e=!1}){this._showLogInConsole=!1,this.markCollectTeaEventReady=()=>{this.isReady=!0,dr.start(),this.queueTeaEvent.forEach(t=>this.sendTeaEvent(...t)),this.queueTeaEvent=[]},this.configTea=(t,i)=>{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.93",...i}};dr.config(n),this.markCollectTeaEventReady()},this.isReady=!1,this.queueTeaEvent=[],dr.init({app_id:699880,channel:"cn"}),this._showLogInConsole=e}sendTeaEvent(e,t,i=!1){if(e)if(this.isReady)try{const n={...Um(t||{})};dr.event(e,n),this._showLogInConsole&&!i&&console.log("[VePusher logger]:",e,n)}catch(n){console.error(n)}else this._showLogInConsole&&!i&&console.log("[VePusher logger]:",e,t),this.queueTeaEvent.push([e,t])}getIsReady(){return this.isReady}getRawTea(){return dr}}let hr;function Vm({showLogInConsole:r}){hr=new Bm({showLogInConsole:r})}function D(r,e,t=!1){hr&&hr.sendTeaEvent(r,e,t)}function Fm(r,e){hr&&hr.configTea(r,e)}const x={PUSHER_INIT:"pusher_init",SET_PROPERTY_CALL:"set_property_call",SET_VIDEO_QUALITY:"set_video_quality",SET_AUDIO_QUALITY:"set_audio_quality",...{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"}};function zt(r){var e;return{error:r,error_code:r.code,error_message:r.message,original_error_message:(e=r.error)==null?void 0:e.message}}class jm extends Ve{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:i,frameRate:n}=bt(Bn,"video"),{sampleRate:s}=bt(Vn,"audio");this._videoConstraints={width:t,height:i,frameRate:n},this._audioConstraints={sampleRate:s,enableAutoGainControl:!0,enableNoiseSuppression:!0,enableEchoCancellation:!0},this._livePusher=e}_notifyCaptured(e){this.emit(Ee.DeviceCaptured,e)}_notifyStopCapture(e){this.emit(Ee.DeviceStopCapture,e)}_bindStreamEvent(e){e.bindTrackEnd(()=>{this.emit(Ee.Interrupted,e),this.stopCapture({streamId:e.id,type:e.type})})}_handleError(e,t){const i=new yt(t,e.message);this.emit(Ee.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){try{const t=await Su(e?[e]:["audioinput","videoinput"]);return D(x.GET_DEVICES_RESULT,{type:e,is_success:!0,devices:t}),t}catch(t){return D(x.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 i;switch(t){case N.Camera:i="_cameraStreams";break;case N.Screen:i="_screenStreams";break;case N.VideoFile:i="_videoFileStreams";break;case N.Microphone:i="_microphoneStreams";break;case N.AudioFile:i="_audioFileStreams";break;case N.Image:i="_imageStreams";break;case N.CustomVideo:i="_customVideoStreams";break;case N.CustomAudio:i="_customAudioStreams";break}if(i){let n=[];if(e){const s=this[i][e];n.push(s)}else n=Le(this[i]);D(x.STOP_CAPTURE,{stream_id:e,type:t,number:n.length}),n.forEach(s=>{this._notifyStopCapture(s),s.destroy(),delete this[i][s.id]})}}async startCameraCapture(e){let t={};Np.includes(e)?t={facingMode:e}:t={deviceId:e};const i={...t,...this._videoConstraints};try{const n=await Eu(i,!this._livePusher.isEnableMixing),s=new Wu(n,{frameRate:this._videoConstraints.frameRate});return this._cameraStreams[s.id]=s,this._notifyCaptured(s),this._bindStreamEvent(s),D(x.CAMERA_CAPTURE_RESULT,{is_success:!0,stream_id:s.id,device_id:e,capture_params:i}),s.id}catch(n){throw D(x.CAMERA_CAPTURE_RESULT,{is_success:!1,device_id:e,capture_params:i,...zt(n)}),this._handleError(n,de.OPEN_CAMERA_FAILED),n}}async startMicrophoneCapture(e){const t={...this._audioConstraints,deviceId:e};try{const i=await wu(t),n=new xp(i);return this._microphoneStreams[n.id]=n,this._notifyCaptured(n),this._bindStreamEvent(n),D(x.MICROPHONE_CAPTURE_RESULT,{is_success:!0,stream_id:n.id,device_id:e,capture_params:t}),n.id}catch(i){throw D(x.MICROPHONE_CAPTURE_RESULT,{is_success:!1,device_id:e,capture_params:t,...zt(i)}),this._handleError(i,de.OPEN_MICROPHONE_FAILED),i}}async startScreenCapture(e){const t={audio:e,video:this._videoConstraints};try{const i=await Tu(t,void 0,!this._livePusher.isEnableMixing),n=new Ip(i,{frameRate:this._videoConstraints.frameRate});return this._screenStreams[n.id]=n,this._notifyCaptured(n),this._bindStreamEvent(n),D(x.SCREEN_CAPTURE_RESULT,{is_success:!0,stream_id:n.id,capture_params:t}),n.id}catch(i){throw D(x.SCREEN_CAPTURE_RESULT,{is_success:!1,capture_params:t,...zt(i)}),this._handleError(i,de.OPEN_SCREEN_FAILED),i}}async startVideoFileCapture(e){try{const t=await os({url:e,video:!0,audio:!0,loop:!0}),i=new Pp(t);return this._videoFileStreams[i.id]=i,this._notifyCaptured(i),this._bindStreamEvent(i),D(x.VIDEO_FILE_CAPTURE_RESULT,{is_success:!0,stream_id:i.id,file_url:e}),i.id}catch(t){throw this._handleError(t,de.VIDEO_FILE_CAPTURE_FAILED),D(x.VIDEO_FILE_CAPTURE_RESULT,{is_success:!1,file_url:e,...zt(t)}),t}}async startAudioFileCapture(e){try{const t=await os({url:e,video:!1,audio:!0,loop:!0}),i=new Op(t);return this._audioFileStreams[i.id]=i,this._notifyCaptured(i),this._bindStreamEvent(i),D(x.AUDIO_FILE_CAPTURE_RESULT,{is_success:!0,stream_id:i.id,file_url:e}),i.id}catch(t){throw D(x.AUDIO_FILE_CAPTURE_RESULT,{is_success:!1,file_url:e,...zt(t)}),this._handleError(t,de.AUDIO_FILE_CAPTURE_FAILED),t}}async startImageCapture(e){try{const t=await Cu({url:e,width:0,height:0,frameRate:30}),i=new Mp(t);return this._imageStreams[i.id]=i,this._notifyCaptured(i),this._bindStreamEvent(i),D(x.IMAGE_FILE_CAPTURE_RESULT,{is_success:!0,stream_id:i.id,file_url:e}),i.id}catch(t){throw D(x.IMAGE_FILE_CAPTURE_RESULT,{is_success:!1,file_url:e,...zt(t)}),this._handleError(t,de.IMAGE_FILE_CAPTURE_FAILED),t}}startCustomVideoCapture(e){const t=ku(e);if(t){const i=new Lp(t);return this._customVideoStreams[i.id]=i,this._notifyCaptured(i),this._bindStreamEvent(i),i.id}}startCustomAudioCapture(e){const t=Ru(e);if(t){const i=new Up(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(),D(x.VOLUME_DETECTOR_START_RESULT,{is_success:!0,stream_id:t.id})}catch(i){D(x.VOLUME_DETECTOR_START_RESULT,{is_success:!1,stream_id:t.id,error_message:i.message}),this._handleError(i,de.VOLUME_DETECT_FAILED)}}stopVolumeDetect(e){const t=this.getStreamById(e);t&&t.stopVolumeDetect()}getDefaultVideoStream(){return Le(this._cameraStreams)[0]||Le(this._screenStreams)[0]||Le(this._videoFileStreams)[0]||Le(this._imageStreams)[0]||Le(this._customVideoStreams)[0]}getDefaultAudioStream(){return Le(this._microphoneStreams)[0]||Le(this._audioFileStreams)[0]||Le(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(N).forEach(e=>{this.stopCapture({type:e})})}}let Ze=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 fn{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(Ee.DeviceCaptured,e=>{this._active&&this.onStreamCapture(e)}),this._streamManagerController.on(Ee.DeviceStopCapture,e=>{this._active&&this.onStreamStopCapture(e)})}getComposedStream(){return this._composedStream}enable(){this._active=!0}disable(){this._active=!1}}const na=new Ze("SingleComposer");class Hm extends fn{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 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:i,ideal:i}}))}catch(a){na.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):na.error("all video stream stop capture")}}_handleAudioStreamStopCapture(e){this._streamComposeController.removeAudioStream(e.id)}getComposedStream(){return this._composedStream}}class $m extends Ve{constructor(e,{width:t,height:i,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=i??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 i=this._rect.width,n=this._rect.height;if(i===0&&n===0)return{width:0,height:0};if(i===0)return{height:n,width:e*(n/t)};if(n===0)return{width:i,height:t*(i/e)};const s=e/t,a=i/n;let o=i,d=n;return s>a?(o=i,d=2*Math.round(i/s/2)):s<a&&(o=2*Math.round(n*s/2),d=n),{width:o,height:d}}_bindVideoTrackSizeChange(){this._stream.on(Gn.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 i;return this._rect.mirrorType!==void 0&&this._rect.mirrorType!==On.None?i=t==null?void 0:t.mirror(this._rect.mirrorType):i=t,i=i==null?void 0:i.position(this._rect.x,this._rect.y),i}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 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;case"mirrorType":this._rect.mirrorType=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 sa extends mt{constructor(e,t){super({type:N.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 qm=Object.defineProperty,Km=Object.getOwnPropertyDescriptor,lr=(r,e,t,i)=>{for(var n=Km(e,t),s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=a(e,t,n)||n);return n&&qm(e,t,n),n};const oa=new Ze("composition-composer");function pr(r,e,t){const i=t.value;return t.value=function(...n){return this._active||oa.error("composer is not active"),i.apply(this,n)},t}class kt extends fn{constructor(e){super(e),this._compositionViewConfig={width:1080,height:720,frameRate:30,backgroundColor:"#000000"},this._sprites=[],this._videoMixer=new ju}onStreamCapture(e){}onStreamStopCapture(e){e&&e.isVideoStream&&this.removeVideoStream(e.id)}enable(){var i;if(this._active)return;super.enable();const e=this._videoMixer.track(),t=this._mixedVideoStream;this._mixedVideoStream=new sa(e,{frameRate:this._compositionViewConfig.frameRate}),this._composedStream.setVideoStream(this._mixedVideoStream),t&&((i=t.videoTrack)==null?void 0:i.id)!==e.id&&t.destroy()}disable(){super.disable(),this._videoMixer.stop()}_updateSpriteToMixer(){const e=eo(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=>{Dp(t.zOrder)||(this._sprites=this._sprites.sort((i,n)=>i.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 i=this._mixedVideoStream,n=this._videoMixer.updateFps();this._mixedVideoStream=new sa(n,{frameRate:this._compositionViewConfig.frameRate}),this._composedStream.setVideoStream(this._mixedVideoStream),i.destroy()}}getMixingConfig(){return this._compositionViewConfig}addVideoStream(e,t){if(!e.viewNode){oa.error("have no viewNode for composition");return}e.audioTrack&&this._streamComposeController.addAudioStream({streamId:e.id,volume:100});const i=new $m(e,t);this._addSprite(i)}_updateSingleVideoStream(e){const t=e.streamId;if(!t)return;const i=this._sprites.find(n=>n.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,i.mirrorType=e.mirrorType)}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)}getVideoStreamRenderConfig(e){const t=this._sprites.find(i=>i.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()}}lr([pr],kt.prototype,"addVideoStream"),lr([pr],kt.prototype,"updateVideoStream"),lr([pr],kt.prototype,"removeVideoStream"),lr([pr],kt.prototype,"muteVideoStream"),lr([pr],kt.prototype,"unmuteVideoStream");class Wm extends Ve{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 Jm extends zr{constructor(e){super({type:N.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 Zm extends fn{constructor(e){super(e),this._spriteList=[],this._audioMixer=new Du({keepAlive:!0})}onStreamCapture(e){}onStreamStopCapture(e){e&&this.removeAudioStream(e.id)}_updateSpriteToMixer(){const e=eo(this._spriteList.map(t=>t.isMute?null:t.getMixerNode()));this._audioMixer.mix(e)}_updateSingleAudioStream(e){const{streamId:t,volume:i}=e,n=this._spriteList.find(s=>s.stream.id===t);n?i!==void 0&&(n.volume=i):console.error("can not find stream"+t)}enable(){super.enable();const e=this._audioMixer.track(),t=new Jm(e);this._composedStream.setAudioStream(t),this._audioMixer.mix([])}addAudioStream(e,t){const i=new Wm(e,t);this._spriteList.push(i),this._updateSpriteToMixer()}tryResume(){return this._audioMixer.resume()}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 Xm extends Ve{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(rt.VideoStreamChange,e))}setAudioStream(e){var t;((t=this._audioStream)==null?void 0:t.id)!==e.id&&(this._audioStream=e,this.emit(rt.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 Ym=new Ze("streamComposeController");class Qm{constructor(e){this._streamManagerController=e,this._composedStream=new Xm,this.singleComposer=new Hm({streamManagerController:this._streamManagerController,composedStream:this._composedStream,streamComposeController:this}),this.compositionComposer=new kt({streamManagerController:this._streamManagerController,composedStream:this._composedStream,streamComposeController:this}),this.mixerComposer=new Zm({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)}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){Ym.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)}getVideoStreamRenderConfig(e){if(this.compositionComposer._active)return this.compositionComposer.getVideoStreamRenderConfig(e)}resumeMixer(){return this.mixerComposer.tryResume()}getCompositionDrawCountPerSecond(){return this.compositionComposer.getDrawCountPerSecond()}}class aa{constructor(e){this._hasBindComposedStreamEvent=!1,this._composedStream=e}bindComposedStreamEvent(){this._hasBindComposedStreamEvent||(this._composedStream.on(rt.VideoStreamChange,this.handleVideoStreamChange),this._composedStream.on(rt.AudioStreamChange,this.handleAudioStreamChange),this._hasBindComposedStreamEvent=!0)}unbindComposedStreamEvent(){this._hasBindComposedStreamEvent&&(this._composedStream.off(rt.VideoStreamChange,this.handleVideoStreamChange),this._composedStream.off(rt.AudioStreamChange,this.handleAudioStreamChange),this._hasBindComposedStreamEvent=!1)}}const Rt=new Ze("PreviewConsumer");class e_ extends aa{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 n={video:null,audio:null};i.addEventListener("loadeddata",()=>{const s=i.srcObject.getVideoTracks()[0],a=i.srcObject.getAudioTracks()[0];s&&s!==n.video&&(this._streamConsumeController.emit(W.CaptureFirstVideoFrame),n.video=s),a&&a!==n.audio&&(this._streamConsumeController.emit(W.CaptureFirstAudioFrame),n.audio=a)}),t.appendChild(i)}startPreview(){if(Rt.log("startPreview"),!this._previewElement){Rt.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(W.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(n=>n.id===t.id)||(t.kind==="audio"&&i.getTracks().forEach(n=>{n.kind==="audio"&&(Rt.log(`remove preview track, ${n.label}, readyState=${n.readyState}`),i.removeTrack(n))}),t.kind==="video"&&i.getTracks().forEach(n=>{n.kind==="video"&&(i.removeTrack(n),Rt.log(`remove preview track, ${n.label}, readyState=${n.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(n=>{(n.id===(t==null?void 0:t.id)||n.readyState==="ended")&&(Rt.log(`remove preview track ${n.label}`),i.removeTrack(n))}),i.getTracks().length===0&&(e.srcObject=null,Rt.log("set srcObject null")))}getPreviewElement(){if(this.isPreviewing)return this._previewElement}get isPreviewing(){return this._isPreviewing}}var be={},mn={},_n={exports:{}},ca;function gn(){if(ca)return _n.exports;ca=1;var r=_n.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")})}),_n.exports}var ua;function t_(){return ua||(ua=1,function(r){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]))},i=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=gn(),s=RegExp.prototype.test.bind(/^([a-z])=(.*)/);r.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 i(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};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 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},r.parseImageAttributes=function(o){return o.split(" ").map(function(d){return d.substring(1,d.length-1).split(",").reduce(a,{})})},r.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}})})}}(mn)),mn}var vn,da;function r_(){if(da)return vn;da=1;var r=gn(),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""}})},i=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 vn=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){r[l].forEach(function(h){h.name in a&&a[h.name]!=null?u.push(i(l,h,a)):h.push in a&&a[h.push]!=null&&a[h.push].forEach(function(p){u.push(i(l,h,p))})})}),a.media.forEach(function(l){u.push(i("m",r.m[0],l)),c.forEach(function(h){r[h].forEach(function(p){p.name in l&&l[p.name]!=null?u.push(i(h,p,l)):p.push in l&&l[p.push]!=null&&l[p.push].forEach(function(f){u.push(i(h,p,f))})})})}),u.join(`\r
66
+ }`,t=document.head||document.getElementsByTagName("head")[0],i=document.createElement("style");i.appendChild(document.createTextNode(e)),t.appendChild(i);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)})},r}(),an={autotrack:{src:{cn:Y("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:Y("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:Y("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:Y("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:Y("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:Y("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:Y("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"}},sm=["ab","autotrack","Stay","store","et","profile","cep","heartbeat","monitor","route","tracer"],_e=function(){function r(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 jp,this.remotePlugin=new Map,this.Types=S,this.adapters.storage=Ue,this.loadType="full"}return r.usePlugin=function(e,t,i){if(t){for(var n=!1,s=0,a=r.plugins.length;s<a;s++)if(r.plugins[s].name===t){r.plugins[s].plugin=e,r.plugins[s].options=i||{},n=!0;break}n||r.plugins.push({name:t,plugin:e,options:i})}else r.plugins.push({plugin:e})},r.prototype.usePlugin=function(e,t,i){e&&(this.loadType==="full"&&sm.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:i}):this.remotePlugin.get(e)||this.remotePlugin.set(e,{instance:t}):this.remotePlugin.get(e)||this.remotePlugin.set(e,"sdk"))},r.prototype.init=function(e){var t,i=this;this.logger=new nf(this.name,e.log),this.inited?this.logger.warn("[instance: "+this.name+"], every instance's api: init, can be call only one time!"):e&&Ht(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 sf,this.spider.checkSpider(e)?this.logger.warn("your env may be a spider, can not report!"):(this.appBridge=new of(this,e.enable_native),this.requestManager=new im(this,e),this.bridgeReport=this.appBridge.bridgeInject(),this.configManager=new rf(this,e),this.debugger=new nm(this,e),this.initConfig=e,this.emit(S.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 cf,this.tokenManager=new uf,this.sessionManager=new af,Promise.all([new Promise(function(n){i.once(S.TokenComplete,function(){n(!0)})}),new Promise(function(n){i.once(S.Start,function(){n(!0)})})]).then(function(){try{r.plugins.reduce(function(n,s){var a=s.plugin,o=s.options,d=Object.assign(i.initConfig,o),c=new a;return c.apply(i,d),n.push(c),i.emit(g.DEBUGGER_MESSAGE,{type:g.DEBUGGER_MESSAGE_SDK,info:"SDK加载"+s.name+"插件",level:"info",time:Date.now(),infoType:"sdk"}),n},i.pluginInstances)}catch(n){console.warn("load plugin error, "+n.message),i.emit(g.DEBUGGER_MESSAGE,{type:g.DEBUGGER_MESSAGE_SDK,info:"SDK加载插件发生了异常",level:"error",time:Date.now(),data:n.message,infoType:"sdk"})}i.sdkReady=!0,i.emit(S.Ready),i.emit(g.DEBUGGER_MESSAGE,{type:g.DEBUGGER_MESSAGE_SDK,info:"SDK 用户信息初始化完成",time:Date.now(),secType:"USER",level:"info",data:i.configManager.get("user"),infoType:"sdk"}),i.emit(g.DEBUGGER_MESSAGE,{type:g.DEBUGGER_MESSAGE_SDK,info:"SDK 初始化完成",time:Date.now(),level:"info",data:i.configManager.get("user"),infoType:"sdk"}),i.logger.info("appid: "+e.app_id+", userInfo:"+JSON.stringify(i.configManager.get("user"))),i.logger.info("appid: "+e.app_id+", sdk is ready, version type is "+i.loadType+", version is "+He+", you can report now !!!"),e.disable_auto_pv&&(i.disableAutoPageView=!0);try{i.loadType==="full"&&(e.enable_ab_test||e.autotrack)&&(window.opener||window.parent).postMessage("[tea-sdk]ready","*")}catch(n){i.emit(g.DEBUGGER_MESSAGE,{type:g.DEBUGGER_MESSAGE_SDK,info:"SDK发生了异常",level:"error",time:Date.now(),data:n.message,infoType:"sdk"})}i.pageView(),i.on(S.TokenChange,function(n){n==="webid"&&i.pageView(),i.logger.info("appid: "+e.app_id+" token change, new userInfo:"+JSON.stringify(i.configManager.get("user"))),i.emit(g.DEBUGGER_MESSAGE,{type:g.DEBUGGER_MESSAGE_SDK,info:"SDK 设置了用户信息",time:Date.now(),secType:"USER",level:"info",data:i.configManager.get("user"),infoType:"sdk"})}),i.on(S.TokenReset,function(){i.logger.info("appid: "+e.app_id+" token reset, new userInfo:"+JSON.stringify(i.configManager.get("user"))),i.emit(g.DEBUGGER_MESSAGE,{type:g.DEBUGGER_MESSAGE_SDK,info:"SDK 重置了用户信息",time:Date.now(),secType:"USER",level:"info",data:i.configManager.get("user"),infoType:"sdk"})}),i.on(S.RouteChange,function(n){n.init||e.disable_route_report||i.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!")},r.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||!Ht(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=U({},e),i=this.initConfig.configPersist||this.initConfig.config_persist||!1;if(this.initConfig&&i){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(S.ConfigWebId,t.web_id),t.hasOwnProperty("user_unique_id")&&this.emit(S.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"})}},r.prototype.setUserUniqueID=function(e){this.config({user_unique_id:e})},r.prototype.setHeaderInfo=function(e,t){var i={};i[e]=t,this.config(i)},r.prototype.removeHeaderInfo=function(e){var t={};t[e]=void 0,this.config(t)},r.prototype.setDomain=function(e){this.configManager&&this.configManager.setDomain(e),this.emit(S.ConfigDomain)},r.prototype.getConfig=function(e){var t;return(t=this.configManager)===null||t===void 0?void 0:t.get(e)},r.prototype.send=function(){this.start()},r.prototype.start=function(){this.inited&&!this.sended&&(this.sended=!0,this.started=!0,this.emit(S.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(S.Ready)))},r.prototype.event=function(e,t){var i=this;try{var n=[];if(Array.isArray(e))e.forEach(function(a){var o=i.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;i.appBridge.onEventV3(o,JSON.stringify(d))}):n.length&&(this.emit(S.Event,n),this.emit(S.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"})}},r.prototype.beconEvent=function(e,t){if(Array.isArray(e))console.warn("beconEvent not support batch report, please check");else{var i=[],n=this.processEvent(e,t||{});n&&(i.push(n),i.length&&(this.emit(S.BeconEvent,i),this.emit(S.SessionResetTime)),this.emit(g.DEBUGGER_MESSAGE,{type:g.DEBUGGER_MESSAGE_SDK,info:"SDK 执行Beacon Event",level:"info",time:Date.now(),data:e,infoType:"sdk"}))}},r.prototype.beaconEvent=function(e,t){this.beconEvent(e,t)},r.prototype.processEvent=function(e,t){t===void 0&&(t={});try{if(!e)return console.warn("eventName is null, please check"),null;var i=e;/^event\./.test(e)&&(i=e.slice(6));var n=t;typeof n!="object"&&(n={}),n.profile?delete n.profile:n.event_index=Hp();var s=void 0;return n.local_ms?(s=n.local_ms,delete n.local_ms):s=+new Date,{event:i,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}}},r.prototype.filterEvent=function(e){this.eventFilter=e},r.prototype.on=function(e,t){this.hook.on(e,t)},r.prototype.once=function(e,t){this.hook.once(e,t)},r.prototype.off=function(e,t){this.hook.off(e,t)},r.prototype.emit=function(e,t,i){this.hook.emit(e,t,i)},r.prototype.set=function(e){this.hook.set(e)},r.prototype.stop=function(){this.sdkStop=!0},r.prototype.reStart=function(){this.sdkStop=!1},r.prototype.pageView=function(){this.disableAutoPageView||this.predefinePageView()},r.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)},i=U(U({},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",i)}else console.warn("predefinePageView must be use after function init")},r.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},r.prototype.clearEventCache=function(){this.emit(S.CleanEvents)},r.prototype.setWebIDviaUnionID=function(e){if(e){var t=so(e);this.config({web_id:""+t,wechat_unionid:e}),this.emit(S.CustomWebId)}},r.prototype.setWebId=function(e){this.config({web_id:""+e})},r.prototype.setWebIDviaOpenID=function(e){if(e){var t=so(e);this.config({web_id:""+t,wechat_openid:e}),this.emit(S.CustomWebId)}},r.prototype.setNativeAppId=function(e){this.bridgeReport&&this.appBridge.setNativeAppId(e)},r.prototype.setRequestHeaders=function(e){this.emit(S.CustomHeader,e)},r.prototype.getSessionId=function(){return St()},r.prototype.setSessionId=function(e){this.emit(S.SessionReset,e)},r.prototype.resetStayDuration=function(e,t,i){this.emit(S.ResetStay,{url_path:e,title:t,url:i},S.Stay)},r.prototype.resetStayParams=function(e,t,i){e===void 0&&(e=""),t===void 0&&(t=""),i===void 0&&(i=""),this.emit(S.SetStay,{url_path:e,title:t,url:i},S.Stay)},r.prototype.getToken=function(e,t){var i=this;if(this.inited){var n=!1,s=function(o){if(!n){n=!0;var d=i.configManager.get().user;return o&&(d.tobid=o,d["diss".split("").reverse().join("")]=o),e(U({},d))}},a=function(){i.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(S.Ready,function(){a()}))}else console.warn("getToken must be use after function init")},r.prototype.profileSet=function(e){this.bridgeReport?this.appBridge.profileSet(JSON.stringify(e)):this.emit(S.ProfileSet,e,S.Profile),this.emit(g.DEBUGGER_MESSAGE,{type:g.DEBUGGER_MESSAGE_SDK,info:"SDK 执行profileSet",level:"info",time:Date.now(),data:e,infoType:"cus"})},r.prototype.profileSetOnce=function(e){this.bridgeReport?this.appBridge.profileSetOnce(JSON.stringify(e)):this.emit(S.ProfileSetOnce,e,S.Profile),this.emit(g.DEBUGGER_MESSAGE,{type:g.DEBUGGER_MESSAGE_SDK,info:"SDK 执行profileSetOnce",level:"info",time:Date.now(),data:e,infoType:"cus"})},r.prototype.profileIncrement=function(e){this.bridgeReport?this.appBridge.profileIncrement(JSON.stringify(e)):this.emit(S.ProfileIncrement,e,S.Profile),this.emit(g.DEBUGGER_MESSAGE,{type:g.DEBUGGER_MESSAGE_SDK,info:"SDK 执行profileIncrement",level:"info",time:Date.now(),data:e,infoType:"cus"})},r.prototype.profileUnset=function(e){this.bridgeReport?this.appBridge.profileUnset(e):this.emit(S.ProfileUnset,e,S.Profile),this.emit(g.DEBUGGER_MESSAGE,{type:g.DEBUGGER_MESSAGE_SDK,info:"SDK 执行profileUnset",level:"info",time:Date.now(),data:e,infoType:"cus"})},r.prototype.profileAppend=function(e){this.bridgeReport?this.appBridge.profileAppend(JSON.stringify(e)):this.emit(S.ProfileAppend,e,S.Profile),this.emit(g.DEBUGGER_MESSAGE,{type:g.DEBUGGER_MESSAGE_SDK,info:"SDK 执行profileAppend",level:"info",time:Date.now(),data:e,infoType:"cus"})},r.prototype.setExternalAbVersion=function(e){this.emit(S.AbExternalVersion,typeof e=="string"&&e?(""+e).trim():null,S.Ab)},r.prototype.getVar=function(e,t,i){this.emit(S.AbVar,{name:e,defaultValue:t,callback:i},S.Ab)},r.prototype.getABconfig=function(e,t){this.emit(S.AbConfig,{params:e,callback:t},S.Ab)},r.prototype.getABConfig=function(e,t){this.emit(S.AbConfig,{params:e,callback:t},S.Ab)},r.prototype.getAbSdkVersion=function(){return this.configManager.getAbVersion()},r.prototype.onAbSdkVersionChange=function(e){var t=this;return this.emit(S.AbVersionChangeOn,e,S.Ab),function(){t.emit(S.AbVersionChangeOff,e,S.Ab)}},r.prototype.offAbSdkVersionChange=function(e){this.emit(S.AbVersionChangeOff,e,S.Ab)},r.prototype.openOverlayer=function(){this.emit(S.AbOpenLayer,"",S.Ab)},r.prototype.closeOverlayer=function(){this.emit(S.AbCloseLayer,"",S.Ab)},r.prototype.getAllVars=function(e){this.emit(S.AbAllVars,e,S.Ab)},r.prototype.destoryInstace=function(){this.destroy||(this.destroy=!0,this.off(S.TokenComplete),this.emit(S.DestoryInstance))},r.prototype.destroyInstance=function(){this.destroy||(this.destroy=!0,this.off(S.TokenComplete),this.emit(S.DestoryInstance))},r.plugins=[],r}(),cn="__rangers_ab_style__";(function(r){r[r.Var=0]="Var",r[r.All=1]="All"})(cr||(cr={}));var om=function(){function r(){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 r.prototype.apply=function(e,t){var i=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||Y(ao[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"&&i.readyStatus&&(i.clearCache(),i.fetchAB())}),this.collect.on(h.TokenReset,function(p){p==="uuid"&&i.readyStatus&&(i.clearCache(),i.fetchAB())}),this.collect.on(h.AbVar,function(p){var f=p.name,v=p.defaultValue,m=p.callback;i.getVar(f,v,m)}),this.collect.on(h.AbAllVars,function(p){i.getAllVars(p)}),this.collect.on(h.AbConfig,function(p){var f=p.params,v=p.callback;i.getABconfig(f,v)}),this.collect.on(h.AbExternalVersion,function(p){i.setExternalAbVersion(p)}),this.collect.on(h.AbOpenLayer,function(){i.openOverlayer()}),this.collect.on(h.AbCloseLayer,function(){i.closeOverlayer()}),this.collect.on(h.AbVersionChangeOn,function(p){i.changeListener.set(p,p)}),this.collect.on(h.AbVersionChangeOff,function(p){i.changeListener.get(p)&&i.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)}},r.prototype.ready=function(e){var t=this;if(this.collect.set(e),this.collect.hook._hooksCache.hasOwnProperty(e)){var i=this.collect.hook._hooksCache[e];if(!Object.keys(i).length)return;var n=function(a){i[a].length&&i[a].forEach(function(o){t.collect.hook.emit(a,o)})};for(var s in i)n(s)}},r.prototype.loadMode=function(){var e=function(){try{var s=JSON.parse(atob(window.name));return s||void 0}catch{return}}(),t="";if(e){var i=e.scenario,n=e.href;i?(this.editMode=!0,t=i):!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()},r.prototype.checkLocal=function(){var e=this.getABCache(),t=e.ab_version,i=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=i||[],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(","))},r.prototype.checkFromUrl=function(){var e=Lr(window.location.href);return e&&e.vid?e.vid:""},r.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)})},r.prototype.configVersions=function(e){this.collect.configManager.setAbVersion(e)},r.prototype.getVar=function(e,t,i){if(!e)throw new Error("getVar key must not be empty");if(t===void 0&&console.warn("getVar defaultValue is illegal, please check!"),typeof i!="function")throw new Error("getVar callback must be a function");var n={name:e,defaultValue:t,callback:i,type:cr.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))},r.prototype.getRealVar=function(e,t){var i=e.name,n=e.defaultValue,s=e.callback,a=this.data;if(a){var o=a[i];if(o&&Ht(o)){var d=a[i].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||i,n,s,o.val),void this.collect.emit(g.DEBUGGER_MESSAGE,{type:g.DEBUGGER_MESSAGE_SDK,secType:"AB",info:"SDK执行GetVar,并曝光了实验"+i,level:"info",time:Date.now(),data:a[i],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)},r.prototype.getAllVars=function(e){if(typeof e!="function")throw new Error("getAllVars callback must be a function");var t={callback:e,type:cr.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)},r.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"})},r.prototype.fechEvent=function(e,t,i,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"?i: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"})}},r.prototype.reportExposure=function(e,t){var i=this;this.exposureCache.push(e),this.reportTimeout&&clearTimeout(this.reportTimeout),this.exposureCache.length>=this.exposureLimit?this.report(t):this.reportTimeout=setTimeout(function(){i.report(t),clearTimeout(i.reportTimeout)},this.ab_batch_time)},r.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(i){t.collect.emit(g.DEBUGGER_MESSAGE,{type:g.DEBUGGER_MESSAGE_EVENT,info:"曝光埋点上报成功",time:Date.now(),data:[i],code:200,status:"success",infoType:"sdk"})}),this.collect.emit(this.types.AbVerify,this.exposureCache),this.exposureCache=[]},r.prototype.setExternalAbVersion=function(e){this.extVersions=[e],this.updateVersions()},r.prototype.getABconfig=function(e,t){var i=Object.keys(e);i&&i.length&&this.collect.configManager.set(e),this.fetchAB(t)},r.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)},r.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)},r.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},r.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)},r.prototype.setAbCache=function(e){var t=this.getABCache();t.data=this.data,t.uuid=e,t.timestamp=Date.now(),this.set(this.abKey,t)},r.prototype.clearCache=function(){this.refreshFetchStatus="ing",this.data={},this.extVersions=[],this.mulilinkVersions=[],this.versions=[],this.collect.configManager.clearAbCache()},r.prototype.openOverlayer=function(e){var t=this;if(function(){if(!document.getElementById(cn)){var n="body { opacity: 0 !important; }",s=document.head||document.getElementsByTagName("head")[0],a=document.createElement("style");a.id=cn,a.type="text/css",a.styleSheet?a.styleSheet.cssText=n:a.appendChild(document.createTextNode(n)),s.appendChild(a)}}(),e)var i=setTimeout(function(){t.closeOverlayer(),clearTimeout(i)},e)},r.prototype.closeOverlayer=function(){var e;(e=document.getElementById(cn))&&e.parentElement.removeChild(e)},r.prototype.fetchComplete=function(e,t){var i=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(){i.editMode||(d!==window.location.href?setTimeout(function(){if(!i.collect.destroy){var u=""+d;u=u.indexOf("http")===-1?"https://"+u:u,Li(u).host!==location.host?u=u+"&vid="+c:window.history.replaceState("","",u),window.location.href=u}},100):i.closeOverlayer())})}this.updateVersions()}else this.closeOverlayer();this.callbackMap.forEach(function(u){return i[u.type===cr.Var?"getRealVar":"getRealAllVars"](u,"")})}catch{}},r.prototype.fetchAB=function(e){var t=this,i=this.collect.configManager.get(),n={header:U(U(U({aid:this.config.app_id},i.user||{}),i.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=i.user[this.ab_user_mode]||i.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})},r}(),am=function(){function r(){}return r.prototype.apply=function(e,t){var i=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){i.verify(n)}),e.on(e.Types.AbVerify,function(n){i.verify(n)})):console.log("please use correct et_test url"))},r.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})},r}();function qr(r,e,t){if(e===void 0&&(e="list"),!r)return!1;if(e&&e==="list"){if(["LI","TR","DL"].includes(r.nodeName)||r.dataset&&r.dataset.hasOwnProperty("teaIdx")||r.hasAttribute&&r.hasAttribute("data-tea-idx"))return!0}else if(["A","BUTTON"].includes(r.nodeName)||r.dataset&&r.dataset.hasOwnProperty("teaContainer")||r.hasAttribute&&r.hasAttribute("data-tea-container")||t&&r.hasAttribute&&r.hasAttribute(t))return!0;return!1}var Jo=function(r,e){return!!um(r,e)};function un(r,e){for(var t=r;t&&!qr(t,"container",e.container_attr||"");){if(t.nodeName==="HTML"||t.nodeName==="BODY")return r;t=t.parentElement}return t||r}var cm=function(r){if(!r)return"";var e="";try{r.textContent?e=r.textContent.trim().replace(/\s+/g,","):r.innerText&&(e=r.innerText.trim().replace(/\s+/g,",")),r.tagName!=="input"&&r.tagName!=="INPUT"||(e=r.value||"")}finally{return e}};function Zo(r){try{for(var e=r;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 Kr=function(r,e){return r.hasAttribute?r.hasAttribute(e):r.attributes?!(!r.attributes[e]||!r.attributes[e].specified):void 0},um=function(r,e){if(typeof e=="string")return Kr(r,e);if(Mr(e)){for(var t=!1,i=0;i<e.length;i++)if(Kr(r,e[i])){t=!0;break}return t}},Xo=function(r,e){var t={};if(typeof e=="string")Kr(r,e)&&(t[e]=r.getAttribute(e));else if(Mr(e))for(var i=0;i<e.length;i++)Kr(r,e[i])&&(t[e[i]]=r.getAttribute(e[i]));return t};function Yo(r){var e=[];if(!r)return{element_path:"",positions:[]};for(;r.parentElement!==null;)e.push(r),r=r.parentElement;var t=[],i=[];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(),qr(d,"list")?"[]":""].join(""),index:c}}(n),a=s.str,o=s.index;t.unshift(a),i.unshift(o)}),{element_path:"/"+t.join("/"),positions:i}}var dm=function(){function r(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,Ht(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 r.prototype.setParams=function(e,t,i){this.set_path=e,this.set_url=i,this.set_title=t},r.prototype.enable=function(e,t,i){this.url_path=e,this.url=i,this.title=t,this.disableCallback=this.enablePageAlive(),this.hard&&(this.removeMode=this.hardMode())},r.prototype.disable=function(){this.disableCallback(),this.pageStartTime=Date.now(),this.hard&&this.removeMode&&this.removeMode()},r.prototype.sendEvent=function(e,t){t===void 0&&(t=!1);var i=t?this.aliveDTime:Date.now()-this.sessionStartTime;if(!(i<0||i>this.aliveDTime||Date.now()-this.pageStartTime>this.maxDuration)&&(!t||document.visibilityState!=="hidden")&&(!this.hard||this.focusState)){var n=U({url_path:this.getParams("url_path"),title:this.getParams("title"),url:this.getParams("url"),duration:i,is_support_visibility_change:no(),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=Yo(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()}},r.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}},r.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)},r.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())},r.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"}},r.prototype.beforeunload=function(){document.hidden||this.sendEvent(!0)},r.prototype.muition=function(){var e=this;new MutationObserver(function(t){t.forEach(function(i){e.visibilitychange()})}).observe(this.options.container,{attributes:!0,attributeFilter:["style"]})},r.prototype.enablePageAlive=function(){var e=this;this.timerHandler=this.setUpTimer();var t=this.visibilitychange.bind(this),i=this.beforeunload.bind(this);return this.options.container?this.muition():document.addEventListener("visibilitychange",t),window.addEventListener("pagehide",i),function(){e.beforeunload(),document.removeEventListener("visibilitychange",t),window.removeEventListener("pagehide",i)}},r.prototype.hardMode=function(){var e=this,t=function(){e.timerHandler&&(clearInterval(e.timerHandler),e.sendEvent(!1)),e.focusState=!1},i=function(){e.focusState=!0,e.sessionStartTime=Date.now(),e.timerHandler=e.setUpTimer()};return window.addEventListener("blur",t),window.addEventListener("focus",i),function(){window.removeEventListener("blur",t),window.removeEventListener("focus",i)}},r}(),hm=function(){function r(e,t){var i=this;this.maxDuration=432e5,this.aliveDTime=6e4,this.options={closeName:"predefine_page_close",params:{}},this.focusState=!0,this.visibilitychange=function(){document.visibilityState==="hidden"?i.activeEndTime=Date.now():document.visibilityState==="visible"&&(i.activeEndTime&&(i.totalTime+=i.activeEndTime-i.activeStartTime,i.activeTimes+=1),i.activeEndTime=void 0,i.activeStartTime=Date.now())},this.beforeunload=function(){if(i.totalTime+=(i.activeEndTime||Date.now())-i.activeStartTime,i.config.autotrack)try{window.sessionStorage.setItem("_tea_cache_duration",JSON.stringify({duration:i.totalTime,page_title:document.title||location.pathname}))}catch{}i.sendEventPageClose()},this.collect=e,this.config=t,this.maxDuration=t.maxDuration||t.max_duration||864e5,this.pageStartTime=Date.now(),Ht(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 r.prototype.setParams=function(e,t,i){this.set_path=e,this.set_url=i,this.set_title=t},r.prototype.resetParams=function(e,t,i){this.url_path=e,this.url=i,this.title=t},r.prototype.enable=function(e,t,i){this.url_path=e,this.url=i,this.title=t,this.disableCallback=this.enablePageClose(),this.hard&&(this.removeMode=this.hardMode())},r.prototype.disable=function(){this.disableCallback(),this.hard&&this.removeMode&&this.removeMode(),this.resetData()},r.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)},r.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,U({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:no(),mode:this.hard?"hard":"normal",focusState:this.focusState},this.options.params)),this.pageStartTime=Date.now(),this.resetData())},r.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}},r.prototype.enablePageClose=function(){var e=this,t=this.visibilitychange.bind(this),i=this.beforeunload.bind(this);return document.addEventListener("visibilitychange",t),window.addEventListener("pagehide",i),function(){e.beforeunload(),document.removeEventListener("visibilitychange",t),window.removeEventListener("pagehide",i)}},r.prototype.hardMode=function(){var e=this,t=function(){e.focusState=!1},i=function(){e.focusState=!0};return window.addEventListener("blur",t),window.addEventListener("focus",i),function(){window.removeEventListener("blur",t),window.removeEventListener("focus",i)}},r}(),lm=function(){function r(){}return r.prototype.apply=function(e,t){var i=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 dm(e,t),this.pageClose=new hm(e,t);var n=this.collect.Types;this.collect.on(n.DestoryInstance,function(){i.disable()}),this.collect.on(n.ResetStay,function(s){var a=s.url_path,o=s.title,d=s.url;i.resetStayDuration(a,o,d)}),this.collect.on(n.RouteChange,function(s){s.init||t.disable_route_report||i.resetStayDuration()}),this.collect.on(n.SetStay,function(s){var a=s.url_path,o=s.title,d=s.url;i.setStayParmas(a,o,d)}),this.enable(this.url_path,this.title,this.url),this.ready(n.Stay),this.collect.emit(n.StayReady)}},r.prototype.ready=function(e){var t=this;if(this.collect.set(e),this.collect.hook._hooksCache.hasOwnProperty(e)){var i=this.collect.hook._hooksCache[e];if(!Object.keys(i).length)return;var n=function(a){i[a].length&&i[a].forEach(function(o){t.collect.hook.emit(a,o)})};for(var s in i)n(s)}},r.prototype.enable=function(e,t,i){this.pageAlive.enable(e,t,i),this.pageClose.enable(e,t,i)},r.prototype.disable=function(){this.pageAlive.disable(),this.pageClose.disable()},r.prototype.setStayParmas=function(e,t,i){e===void 0&&(e=""),t===void 0&&(t=""),i===void 0&&(i=""),this.pageAlive.setParams(e,t,i),this.pageClose.setParams(e,t,i),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:i}})},r.prototype.reset=function(e,t,i){this.disable(),this.enable(e,t,i)},r.prototype.resetStayDuration=function(e,t,i){this.reset(e,t,i),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:i}})},r}(),pm=function(){function r(){}return r.prototype.apply=function(e,t){var i=this;this.collect=e,this.config=t,this.duration=6e4,this.reportUrl=e.configManager.getDomain()+"/profile/list";var n=e.Types;this.eventCheck=new Fi(e,t),this.cache={},this.collect.on(n.ProfileSet,function(s){i.setProfile(s)}),this.collect.on(n.ProfileSetOnce,function(s){i.setOnceProfile(s)}),this.collect.on(n.ProfileUnset,function(s){i.unsetProfile(s)}),this.collect.on(n.ProfileIncrement,function(s){i.incrementProfile(s)}),this.collect.on(n.ProfileAppend,function(s){i.appendProfile(s)}),this.collect.on(n.ProfileClear,function(){i.cache={}}),this.ready(n.Profile)},r.prototype.ready=function(e){var t=this;if(this.collect.set(e),this.collect.hook._hooksCache.hasOwnProperty(e)){var i=this.collect.hook._hooksCache[e];if(!Object.keys(i).length)return;var n=function(a){i[a].length&&i[a].forEach(function(o){t.collect.hook.emit(a,o)})};for(var s in i)n(s)}},r.prototype.report=function(e,t){t===void 0&&(t={});try{if(this.config.disable_track_event)return;var i=[];i.push(this.collect.processEvent(e,t));var n=this.collect.eventManager.merge(i);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})}},r.prototype.setProfile=function(e){var t=this.formatParams(e);t&&Object.keys(t).length&&(this.pushCache(t),this.report("__profile_set",U(U({},t),{profile:!0})))},r.prototype.setOnceProfile=function(e){var t=this.formatParams(e,!0);t&&Object.keys(t).length&&(this.pushCache(t),this.report("__profile_set_once",U(U({},t),{profile:!0})))},r.prototype.incrementProfile=function(e){e?this.report("__profile_increment",U(U({},e),{profile:!0})):console.warn("please check the params, must be object!!!")},r.prototype.unsetProfile=function(e){if(e){var t={};t[e]="1",this.report("__profile_unset",U(U({},t),{profile:!0}))}else console.warn("please check the key, must be string!!!")},r.prototype.appendProfile=function(e){if(e){var t={};for(var i in e)typeof e[i]=="string"||Object.prototype.toString.call(e[i]).slice(8,-1)==="Array"?t[i]=e[i]:console.warn("please check the value of param: "+i+", must be string or array !!!");Object.keys(t).length&&this.report("__profile_append",U(U({},t),{profile:!0}))}else console.warn("please check the params, must be object!!!")},r.prototype.pushCache=function(e){var t=this;Object.keys(e).forEach(function(i){t.cache[i]={val:t.clone(e[i]),timestamp:Date.now()}})},r.prototype.formatParams=function(e,t){var i=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=i.cache[d];return t?!c:!(c&&i.compare(c.val,e[d])&&o-c.timestamp<i.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")}},r.prototype.compare=function(e,t){try{return JSON.stringify(e)===JSON.stringify(t)}catch(i){return this.collect.emit(g.DEBUGGER_MESSAGE,{type:g.DEBUGGER_MESSAGE_SDK,info:"发生了异常",level:"error",time:Date.now(),data:i.message}),!1}},r.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}},r.prototype.unReady=function(){console.warn("sdk is not ready, please use this api after start")},r}(),fm=function(){function r(){var e=this;this.setInterval=function(){e.clearIntervalFunc=qp(function(){e.isSessionhasEvent&&e.endCurrentSession()},e.sessionInterval)},this.clearInterval=function(){e.clearIntervalFunc&&e.clearIntervalFunc()}}return r.prototype.apply=function(e,t){var i=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(){i.process()})}},r.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},r.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())},r}(),mm=function(){function r(){}return r.prototype.apply=function(e,t){var i=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(){i.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"&&i.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;i.sdkInnerError(s,a,o,d)}))},r.prototype.sdkOnload=function(){var e=this;try{var t=this.collect.configManager.get(),i=t.header,n=t.user,s=i.app_id,a=i.app_name,o=i.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{}},r.prototype.sdkError=function(e,t,i){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:i.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{}},r.prototype.sdkInnerError=function(e,t,i,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:i,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{}},r}(),_m=function(r){if(r.children.length){var e=r.children;return![].slice.call(e).some(function(t){return t.children.length>0})}return!0},gm=function(r){if(r.tagName.toLowerCase()==="svg")return!0;for(var e=r.parentElement,t=!1;e;)e.tagName.toLowerCase()==="svg"?(e=null,t=!0):e=e.parentElement;return t};function vm(r,e){if(r.nodeType!==1||!e.svg&&gm(r)||["HTML","BODY"].includes(r.tagName.toUpperCase()))return!1;var t=r;return t.style.display!=="none"&&(!!qr(t,"container",e.container_attr||"")||!!(function(i,n){for(var s=i,a=!1;s&&!qr(s,"container",n.container_attr||"");){if(s.nodeName==="HTML"||s.nodeName==="BODY")return a;s=s.parentElement}return a=!0}(t,e)||_m(t)||e.svg))}var ym=function(){function r(e,t,i){var n=this;this.statistics=!1,this.pageView=!1,this.clickEvent=function(s){vm(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"},U({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=i.getConfig().eventConfig,this.collect=t,this.options=e,this.beatTime=e.beat,this.domContainer=e.container||document}return r.prototype.init=function(e){this.eventHandel=e;var t=this.config.mode;this.addListener(t)},r.prototype.addListener=function(e){var t=this;if(e==="proxy-capturing"){if(this.config.click&&(Mr(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 i=setTimeout(function(){t.pageView||(t.getPageViewEvent(t.getDefaultConfig()),t.pageView=!0,clearTimeout(i))},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)}}}},r.prototype.removeListener=function(){var e=this;Mr(this.domContainer)?this.domContainer.forEach(function(t){t.removeEventListener("click",e.clickEvent,!0)}):this.domContainer.removeEventListener("click",this.clickEvent,!0)},r.prototype.beatEvent=function(e){var t=this;try{var i;this.eventHandel({eventType:"dom",eventName:"beat"},{beat_type:3}),this.beatTime&&(i=setInterval(function(){t.eventHandel({eventType:"dom",eventName:"beat"},{beat_type:2})},e)),Mi(function(){t.eventHandel({eventType:"dom",eventName:"beat",eventSend:"becon"},{beat_type:0}),t.beatTime&&clearInterval(i)})}catch{}},r.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}},r}(),bm={eventConfig:{mode:"proxy-capturing",submit:!1,click:!0,change:!1,pv:!0,beat:!0,hashTag:!1,impr:!1},scoutConfig:{mode:"xpath"}},Sm=function(){function r(e,t){this.config=e,this.config.eventConfig=Object.assign(this.config.eventConfig,t)}return r.prototype.getConfig=function(){return this.config},r.prototype.setConfig=function(e){return this.config=e},r}();function Em(r,e,t,i){var n={},s=function(k){if(k){var T=k.getBoundingClientRect(),R=T.width,I=T.height;return{left:T.left,top:T.top,element_width:R,element_height:I}}}(e=un(e,t)),a=function(k,T){k===void 0&&(k={}),T===void 0&&(T={});var R=k.clientX,I=k.clientY,H=T.left,V=T.top,q=R-H>=0?R-H:0,K=I-V>=0?I-V:0;return{touch_x:Math.floor(q),touch_y:Math.floor(K)}}(r,s),o=s.element_width,d=s.element_height,c=a.touch_x,u=a.touch_y,l=Yo(e),h=l.element_path,p=l.positions,f=function(k,T){var R=un(k,T),I=[];return function H(V){var q=function(j){var te="";return j.nodeType===3?te=j.textContent.trim():j.dataset&&j.dataset.hasOwnProperty("teaTitle")||j.hasAttribute("ata-tea-title")?te=j.getAttribute("data-tea-title"):j.nodeName==="INPUT"&&["button","submit"].includes(j.getAttribute("type"))?te=j.getAttribute("value"):j.nodeName==="IMG"&&j.getAttribute("alt")&&(te=j.getAttribute("alt")),te.slice(0,200)}(V);if(q&&I.indexOf(q)===-1&&I.push(q),V.childNodes.length>0)for(var K=V.childNodes,ae=0;ae<K.length;ae++)K[ae].nodeType!==8&&H(K[ae])}(R),I}(e,t),v=window.performance.timing.navigationStart,m=Date.now()-v,E=p.map(function(k){return""+k}),y=null;if(window.TEAVisualEditor&&window.TEAVisualEditor.getOriginXpath&&(y=window.TEAVisualEditor.getOriginXpath({xpath:h,positions:E})),n.element_path=y&&y.xpath||h,n.positions=y&&y.positions||E,i&&!i.text&&(n.texts=f,n.element_title=e.getAttribute("data-tea-title")||e.getAttribute("title")||cm(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&&Jo(e,t.track_attr)){var _=Xo(e,t.track_attr);for(var C in _)n[C]=_[C]}if(t.custom_attr)try{if(Jo(e,t.custom_attr)){_=Xo(e,t.custom_attr),C=decodeURIComponent(_[t.custom_attr]);var z=JSON.parse(C);if(Object.keys(z))for(var w in z)n[w]=z[w]}}catch{console.log("custom attr error")}var A=un(e,t);return A.tagName==="A"&&(n.href=A.getAttribute("href")),e.tagName==="IMG"&&(n.src=e.getAttribute("src")),n}var Tt=function(r,e,t,i,n){return U(U({event:r},Em(e,t,i,n)),{is_html:1,page_key:window.location.href,page_title:document.title})},Cm=function(){function r(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 r.prototype.handleEvent=function(e,t){try{if(Zo(e.target))return null;var i="bav2b_click";switch(t){case"click":return i=e.target.getAttribute("data-applog-click-event")||this.eventName.click||"",Tt(i,e,e.target,this.options,this.ignore);case"exposure":return i=e.target.getAttribute("data-applog-exposure-event")||this.eventName.exposure||"",Tt(i,e,e.target||e,this.options,this.ignore);case"change":return U(U({},Tt(i="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{}}}(i,e.target));case"submit":return Tt(i="bav2b_submit",e,e.target,this.options)}}catch(n){return console.error(n),null}},r.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 i=JSON.parse(t);e.refer_page_duration_ms=i?i.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},r.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 i=e.lcp,n=window.performance.timing,s=n.loadEventEnd-n.navigationStart;t.page_init_cost_ms=parseInt(i||(s>0?s:0)),t.page_start_ms=n.navigationStart}catch(a){console.log("page_statistics event error "+JSON.stringify(a))}return t},r.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},r.prototype.handleExposureEvent=function(e,t){if(Zo(t.target))return null;var i=Tt(e.event||this.eventName.exposure,t,t.target||t,this.options,this.ignore);if(i.$exposure_type=e.exposureType,this.options.exposure.callback){var n=this.options.exposure.callback(i);return n||Object.keys(n).length?n:(console.warn("exposure callback must return data!"),i)}return i},r.prototype.handleScrollEvent=function(e,t){var i=Tt(e.event||this.eventName.scroll,t,t.target||t,this.options,this.ignore);if(i=Object.assign(i,e.params),!this.options.scroll.callback||(i=this.options.scroll.callback(i))||Object.keys(i).length)return i;console.warn("scroll callback must return data!")},r}(),wm=function(){function r(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 r.prototype.send=function(e,t){var i=t.event;delete t.event,e&&e.eventSend==="becon"?this.collect.beconEvent(i,t):this.collect.event(i,t)},r.prototype.get=function(e,t){var i=Object.assign({headers:{"content-type":"application/json"},method:"GET"},t);fetch(e,i)},r.prototype.post=function(e,t){var i=Object.assign({headers:{"content-type":"application/json"},method:"POST"},t);fetch(e,i)},r}(),ur={},Qo=[],Tm=function(r){r.length&&r.forEach(function(e){Qo.push(e)})};function ea(r,e,t,i){var n=r&&r.source||window.opener||window.parent,s=r&&r.origin||i||"*",a={type:e,payload:t};n.postMessage(JSON.stringify(a),s)}function zm(r){if(Qo.some(function(n){return r.origin.indexOf(n)>-1})){var e=r.data;if(typeof r.data=="string")try{e=JSON.parse(r.data)}catch{e=void 0}if(!e)return;var t=e.type,i=e.payload;ur[t]&&ur[t].forEach(function(n){typeof n=="function"&&n(r,i)})}}var dn=!1;function km(r,e){window.TEAVisualEditor=window.TEAVisualEditor||{},window.TEAVisualEditor.appId=e.app_id;var t=e.channel_domain,i="";if(Tm(Yp),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)){i="https:/";for(var o=2;o<n.length&&o!==n.length-1;o++)i=i+"/"+n[o];if(i&&i.indexOf("/5.0")){var d=i.split("/5.0");i=d[0]||i}}}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",zm,!1)})(e,He);try{(function(c,u){ur[c]=ur[c]||[],ur[c].push(u)})("tea:openHeatMapCore",function(c){var u=Xp,l=c.data.app_id;l&&l!==e.app_id||function(h){var p=h.event,f=h.editorUrl,v=h.autoTrackInstance;dn||(dn=!0,$p(f,function(){ea(p,"editorScriptloadSuccess"),v.destroy()},function(){p&&ea(p,"editorScriptloadError"),dn=!1}))}({event:c,editorUrl:u+".js?query="+Date.now(),autoTrackInstance:r})})}catch{console.log("openHeatMapCore error")}}var ke,Rm=function(){function r(e,t){this._instance=null,this._intersection=e,this.config=t,this._intersection&&this.init()}return r.prototype.init=function(){var e=this;if(window.MutationObserver)try{if(this._instance=new MutationObserver(function(i){i.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")},r.prototype.attributeChangeObserve=function(e){e.target.hasAttribute("data-exposure")?this.exposureAdd(e,"mutation"):this.exposureRemove(e)},r.prototype.modifyNodeObserve=function(e){var t=this;Array.prototype.forEach.call(e.addedNodes,function(i){i.nodeType===1&&i.hasAttribute("data-exposure")&&t.exposureAdd(i,"intersect"),t.mapChild(i,t.exposureAdd.bind(t))}),Array.prototype.forEach.call(e.removedNodes,function(i){i.nodeType===1&&i.hasAttribute("data-exposure")&&t.exposureRemove(i),t.mapChild(i,t.exposureRemove.bind(t))})},r.prototype.mapChild=function(e,t){var i=this;e.nodeType===1&&e.children.length&&Array.prototype.forEach.call(e.children,function(n){n.nodeType===1&&n.hasAttribute("data-exposure")&&t(n),i.mapChild(n,t)})},r.prototype.exposureAdd=function(e,t){try{this._intersection&&this._intersection.exposureAdd(e,t)}catch(i){console.log("intersection error",JSON.stringify(i.message))}},r.prototype.exposureRemove=function(e){try{this._intersection&&this._intersection.exposureRemove(e)}catch(t){console.log("intersection error",JSON.stringify(t.message))}},r._exposure_observer=null,r}();(function(r){r[r.EXPOSURE_ONCE=0]="EXPOSURE_ONCE",r[r.LIFECYCLE_SHOW_NEW=3]="LIFECYCLE_SHOW_NEW",r[r.RESUME_FORM_PAGE=6]="RESUME_FORM_PAGE",r[r.RESUME_FORM_BACK=7]="RESUME_FORM_BACK",r[r.NOT_EXPOSURE=-1]="NOT_EXPOSURE"})(ke||(ke={}));var ht,Am=function(){function r(e,t,i){var n=this;this.backStatus=!1,this.instance=this.buildObserver(),this.collect=e,this.observeMap=r._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=ke.NOT_EXPOSURE,this.eventHandle=i,this.hashMap=new Map,this.backStatus=!1,this.lastState=null,this.collect.on("re-start-sdk",function(){n.visibilitychange()}),this.addListen()}return r.prototype.buildObserver=function(){var e=this;if(r._observer_instance)return console.log("your browser cannot support IntersectionObserver, so cannot report exposure event, please update"),null;if(window.IntersectionObserver){for(var t=[],i=0;i<=1;i+=.01)t.push(i);t.push(1);try{r._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 r._observer_instance}return console.log("your browser cannot support IntersectionObserver, so cannot report exposure event, please update"),null},r.prototype.exposureAdd=function(e,t){var i=t==="mutation"?e.target:e,n=i.observeId,s=$t();if(n||this.observeMap.has(n)){var a=this.observeMap.get(n);if(a&&i!==a.instance)this.unobserve(i),this.observeMap.delete(n),i.observeId=s,i.visible=!1,this.observeMap.set(s,{instance:i.cloneNode(!0),isIntersecting:!1}),this.observe(i);else{if(i.visible===!0)return;this.handleBoundingExposure(i)}}else i.observeId=s,i.visible=!1,this.observeMap.set(s,{instance:i.cloneNode(!0),isIntersecting:!1}),this.observe(i)},r.prototype.exposureRemove=function(e){this.observeMap.has(e.observeId)&&(this.observeMap.delete(e.observeId),this.unobserve(e),e.observeId="",e.visible=!1)},r.prototype.exposureEvent=function(e,t,i,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(i,n)},r.prototype.observe=function(e){this.instance&&this.instance.observe(e)},r.prototype.unobserve=function(e){this.instance&&this.instance.unobserve(e)},r.prototype.getExposureDomToExposure=function(){var e=this;Array.prototype.forEach.call(document.querySelectorAll("[data-exposure]"),function(t){e.handleBoundingExposure(t)})},r.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)},r.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||ke.RESUME_FORM_BACK},e)}},r.prototype.getBoundingRatio=function(e){var t=e.getBoundingClientRect(),i=t.top,n=t.left,s=t.width,a=t.height,o=window.innerWidth||document.documentElement.clientWidth,d=window.innerHeight||document.documentElement.clientHeight;return i>=0&&n>=0&&i<=d&&n<=o?(s>o?o:s)*(d-i)/(s*a):0},r.prototype.getExposureType=function(e){return e.visible?e.backStatus!==!1&&(this.backStatus||this.customType||window.performance.navigation.type===2)?this.exposureType=ke.RESUME_FORM_PAGE:this.exposureType=ke.LIFECYCLE_SHOW_NEW:(e.hasExposure,e.backStatus!==!1&&(this.backStatus||this.customType||window.performance.navigation.type===2)?this.exposureType=ke.RESUME_FORM_PAGE:this.exposureType=ke.EXPOSURE_ONCE),this.exposureType},r.prototype.addListen=function(){var e=this;this.collect.on("set-exposure-type",function(c){e.customType=c});var t,i,n,s,a=this.visibilitychange.bind(this);if(t=document,i="visibilitychange",n=a,s=!1,t.addEventListener?t.addEventListener(i,n,s):t.attachEven?t.attachEven("on"+i,n):t["on"+i]=n,window.addEventListener("hashchange",function(c){var u=e.hashMap.get(c.oldURL);u&&location.href===u.prev?(e.backStatus=!0,e.exposureType=ke.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,ot([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,ot([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=ke.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)}},r._observer_instance=null,r._observer_map=new Map,r}(),Dm=function(){function r(e,t,i){t.autotrack&&t.autotrack.exposure&&(this._intersection=new Am(e,t,i),this._observer=new Rm(this._intersection,t),this._intersection&&this._observer?this.initObserver():console.log("your browser version cannot support exposure event, please update~"))}return r.prototype.initObserver=function(){var e=this;Array.prototype.forEach.call(document.querySelectorAll("[data-exposure]"),function(t){e._intersection.exposureAdd(t,"intersect")})},r}();(function(r){r[r.SCROLL_UP=1]="SCROLL_UP",r[r.SCROLL_DOWN=2]="SCROLL_DOWN",r[r.SCROLL_LEFT=3]="SCROLL_LEFT",r[r.SCROLL_RIGHT=4]="SCROLL_RIGHT",r[r.NOT_SCROLL=-1]="NOT_SCROLL"})(ht||(ht={}));var ta,xm=function(){function r(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 r.prototype.addLinstenr=function(){var e=this;Array.prototype.forEach.call(document.querySelectorAll("[data-scroll]"),function(t){e.scrollHandle(t)})},r.prototype.mutation=function(){var e=this;if(window.MutationObserver)try{var t=new MutationObserver(function(i){i.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")},r.prototype.modifyNodeObserve=function(e){var t=this;Array.prototype.forEach.call(e.addedNodes,function(i){i.nodeType===1&&i.hasAttribute("data-scroll")&&t.scrollHandle(i),t.mapChild(i,t.scrollHandle.bind(t))}),Array.prototype.forEach.call(e.removedNodes,function(i){i.nodeType===1&&i.hasAttribute("data-scroll")&&t.scrollHandle(i,"remove"),t.mapChild(i,t.scrollHandle.bind(t))})},r.prototype.mapChild=function(e,t){var i=this;e.nodeType===1&&e.children.length&&Array.prototype.forEach.call(e.children,function(n){n.nodeType===1&&n.hasAttribute("data-scroll")&&t(n),i.mapChild(n,t)})},r.prototype.scrollHandle=function(e,t){var i=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)>=i.distance&&i.distance&&i.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)>=i.distance&&i.distance&&i.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=ht.NOT_SCROLL;l>n?p=ht.SCROLL_DOWN:l<n?p=ht.SCROLL_UP:h>s?p=ht.SCROLL_LEFT:h<s&&(p=ht.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))}},r}(),Pm={hashTag:!1,impr:!1},Im=function(){function r(){}return r.prototype.apply=function(e,t){if(this.autoTrackStart=!1,this.collect=e,this.config=t,t.autotrack){var i=e.Types;this.ready(i.Autotrack),this.collect.emit(i.AutotrackReady)}},r.prototype.ready=function(e){this.collect.set(e);var t=this.config.autotrack;t=typeof t=="object"?t:{},t=Object.assign(Pm,t),this.destroyed=!1,this.options=t,this.Config=new Sm(bm,this.options),this.Exposure=new Dm(this.collect,this.config,this.handle.bind(this)),this.Scroll=new xm(this.config,this.handle.bind(this)),this.Listener=new ym(t,this.collect,this.Config),this.EventHandle=new Cm(this.config,t),this.Request=new wm(this.collect),this.autoTrackStart=!0,this.init(),km(this,this.config)},r.prototype.init=function(){this.Listener.init(this.handle.bind(this));try{this.collect.loadType==="base"&&(window.opener||window.parent).postMessage("[tea-sdk]ready","*")}catch{}},r.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)},r.prototype.handleDom=function(e,t){try{var i=e.eventName;if(i==="click"||i==="change"||i==="submit")(o=this.EventHandle.handleEvent(t,i))&&this.Request.send({eventType:"custom"},o);else if(i==="page_view"||i==="page_statistics"){var n=void 0;(n=i==="page_view"?this.EventHandle.handleViewEvent(t):this.EventHandle.handleStatisticsEvent(t))&&this.Request.send({eventType:"custom"},n)}else if(i==="beat"){var s=this.EventHandle.handleBeadtEvent(t),a=e.eventSend;s&&this.Request.send({eventType:"custom",eventSend:a},s)}else if(i==="exposure")(o=this.EventHandle.handleExposureEvent(e,t))&&this.Request.send({eventType:"custom"},o);else if(i==="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))}},r.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()},r}();(function(r){r.Net="net",r.FailNet="f_net",r.FailData="f_data"})(ta||(ta={}));var ra={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"]},Om=function(){function r(){}return r.prototype.apply=function(e,t){var i=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(){i.addCount("log")}),this.collect.on(n.SubmitError,function(s){var a=s.type,o=s.eventDate,d=s.errorCode,c=s.response;i.addErrorCount(o,a,d,c)}),this.listener(),this.collect.emit(n.TracerReady)}},r.prototype.addCount=function(e,t,i){t===void 0&&(t="net"),i===void 0&&(i=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=i,s.set(t,this.processTracer(i,e,t)));else{var s=new Map;n=i,s.set(t,this.processTracer(i,e,t)),this.tracerCache.set(e,s)}t==="net"&&n>=this.limit[e]&&this.report(!1)}catch(a){console.log(a)}},r.prototype.addErrorCount=function(e,t,i,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]=i):a.forEach(function(o){var d="log";for(var c in ra)if(ra[c].indexOf(o.event)!==-1){d=c;break}s.addCount(d,t,1),s.errorCode[t]=i}))}}catch{}},r.prototype.report=function(e){if(this.tracerCache){var t=[];this.tracerCache.forEach(function(i){console.log(i),i.forEach(function(n){t.push(n)})}),t&&t.length&&this.sendTracer(t,e)}},r.prototype.sendTracer=function(e,t){try{var i=this.collect.eventManager.merge(e);this.collect.requestManager.useRequest({url:this.reportUrl,data:i,useBeacon:t}),this.tracerCache=null}catch{}},r.prototype.processTracer=function(e,t,i){var n={count:e,state:i,key:t,params_for_special:"applog_trace",aid:this.appid,platform:"web",_staging_flag:1,sdk_version:He};i!=="f_net"&&i!=="f_data"||(n.errorCode=this.errorCode[i]);var s=this.collect.processEvent("applog_trace",n);if(s&&s.event)return delete s.is_bav,s},r.prototype.listener=function(){var e=this;document.addEventListener("visibilitychange",function(){document.visibilityState==="hidden"&&e.leavePage()}),Mi(function(){e.leavePage()})},r.prototype.leavePage=function(){this.report(!0)},r}(),Mm=function(){function r(){this.retryWaitTime=3e3,this.retryStatus=!1,this.retryCacheStatus=!1}return r.prototype.apply=function(e,t){var i=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"&&i.storeData(a)}),e.on(n.Ready,function(){i.checkStorage()})}},r.prototype.retryRightNow=function(e){var t=this;if(this.retryStatus)this.errorCache.push(e);else{var i=0;this.retryStatus=!0;var n=setInterval(function(){if(i===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(){i++})},this.retryInterval)}},r.prototype.storeData=function(e){var t=this.storage.getItem(this.eventKey),i=e.eventData;Object.keys(t).length!==this.storageNum&&(t[Date.now()]=i,this.storage.setItem(this.eventKey,t))},r.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 i={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([i],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")}},r.prototype.fetchData=function(e,t,i,n){this.collect.requestManager.useRequest({url:this.eventUrl,data:e,timeout:3e4,success:t,fail:i,app_key:n?"566f58151b0ed37e":""})},r}(),hn=typeof window<"u"?(window.LogPluginObject||(window.LogPluginObject={}),window.LogPluginObject):null,Lm=function(){function r(){}return r.prototype.apply=function(e,t){this._plugin={},this.config=t,this.collect=e,this.channel=t.channel||"cn",this.loadExtend()},r.prototype.loadExtend=function(){var e=this;try{this.collect.remotePlugin.forEach(function(t,i){if(t==="sdk")if(an.hasOwnProperty(i)){var n=an[i].object,s=an[i].src[e.channel]+"?query="+Date.now();e.exist(i,n,s)}else console.warn("your "+i+" is not exist,please check plugin name");else typeof t=="object"&&(t.src?e.exist(i,t.call,t.src):e.process(i,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")}},r.prototype.exist=function(e,t,i){var n=this;hn[t]?(this.process(e,hn[t]),console.log("已有"+e+"插件,避免重复加载~")):this.loadPlugin(e,i,function(){n.process(e,hn[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","-")})},r.prototype.process=function(e,t,i){try{if(i){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)}},r.prototype.loadPlugin=function(e,t,i,n){var s=this;try{var a=document.createElement("script");a.src=t,this._plugin[e]||(this._plugin[e]=[]),this._plugin[e].push(i),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})}},r}(),Um=function(){function r(){this.autotrack=!1,this.spa=!1,this.cache={},this.allowHash=!1}return r.prototype.apply=function(e,t){if(t.spa||t.autotrack){var i=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(i.RouteReady)}},r.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)},r.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,ot([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 i=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=i.call.apply(i,ot([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}}},r.prototype.setLocation=function(){typeof window<"u"&&(this.lastLocation=window.location.href)},r.prototype.getLocation=function(){return this.lastLocation},r.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}},r.prototype.init=function(){var e=this.getPopStateChangeEventData();this.collect.emit("route-change",{config:e,init:!0})},r.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 i=e.getPopStateChangeEventData();e.sendPv(i)}}),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 i=e.getPopStateChangeEventData();e.sendPv(i)}})},r.prototype.getPopStateChangeEventData=function(){var e=this.pageConfig();return e.is_back=0,e},r.prototype.pageConfig=function(){try{var e=this.storage.getItem(this.cache_key)||{},t=!1,i=this.storage.getItem("__tea_cache_first_"+this.appid);return t=!i||i!=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}),{}}},r.prototype.sendPv=function(e,t){this.collect.emit("route-change",{config:e,init:!1})},r.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},r.prototype.removeQuery=function(e){try{var t=new URL(e);return t.search="",t.href}catch{return e.split(/[?#]/)[0]}},r.prototype.setReferCache=function(e){var t=this.storage.getItem(this.cache_key)||{},i=this.removeQuery(e);t.refer_key=i,t.routeChange=!0,this.storage.setItem(this.cache_key,t)},r}();_e.usePlugin(Lm,"extend"),_e.usePlugin(am,"et"),_e.usePlugin(om,"ab"),_e.usePlugin(lm,"stay"),_e.usePlugin(Im,"autotrack"),_e.usePlugin(pm,"profile"),_e.usePlugin(Mm,"retry"),_e.usePlugin(fm,"heartbeat"),_e.usePlugin(mm,"monitor"),_e.usePlugin(Um,"route"),_e.usePlugin(Om,"tracer");var dr=new _e("default");const ln="VEPUSHER_DEVICE_ID",pn="VEPUSHER_USER_ID",ia=r=>Math.floor((Math.random()*9+1)*Math.pow(10,r-1)).toString();function Nm(r){const e={};if(!(r instanceof Object))throw new Error("params type error");for(const[t,i]of Object.entries(r))if(["string","number","boolean"].includes(typeof i))e[t]=i;else try{e[t]=JSON.stringify(i)}catch(n){console.error("serialize error",n)}return e}function Gm(r){if(r)return localStorage.setItem(pn,r),r;const e=localStorage.getItem(pn);if(e)return e;const t=ia(12);return localStorage.setItem(pn,t),r}function Bm(r){if(r)return localStorage.setItem(ln,r),r;const e=localStorage.getItem(ln);if(e)return e;const t=ia(11);return localStorage.setItem(ln,t),t}const D={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 Vm{constructor({showLogInConsole:e=!1}){this._showLogInConsole=!1,this.markCollectTeaEventReady=()=>{this.isReady=!0,dr.start(),this.queueTeaEvent.forEach(t=>this.sendTeaEvent(...t)),this.queueTeaEvent=[]},this.configTea=(t,i)=>{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.95",...i}};dr.config(n),this.markCollectTeaEventReady()},this.isReady=!1,this.queueTeaEvent=[],dr.init({app_id:699880,channel:"cn"}),this._showLogInConsole=e}sendTeaEvent(e,t,i=!1){if(e)if(this.isReady)try{const n={...Nm(t||{})};dr.event(e,n),this._showLogInConsole&&!i&&console.log("[VePusher logger]:",e,n)}catch(n){console.error(n)}else this._showLogInConsole&&!i&&console.log("[VePusher logger]:",e,t),this.queueTeaEvent.push([e,t])}getIsReady(){return this.isReady}getRawTea(){return dr}}let hr;function Fm({showLogInConsole:r}){hr=new Vm({showLogInConsole:r})}function x(r,e,t=!1){hr&&hr.sendTeaEvent(r,e,t)}function jm(r,e){hr&&hr.configTea(r,e)}const na=()=>{x(D.PAGE_VISIBLE_CHANGE,{page_visible:!document.hidden})},Hm=()=>{document.addEventListener("visibilitychange",na)},$m=()=>{document.removeEventListener("visibilitychange",na)};function zt(r){var e;return{error:r,error_code:r.code,error_message:r.message,original_error_message:(e=r.error)==null?void 0:e.message}}class qm extends Ve{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:i,frameRate:n}=bt(Bn,"video"),{sampleRate:s}=bt(Vn,"audio");this._videoConstraints={width:t,height:i,frameRate:n},this._audioConstraints={sampleRate:s,enableAutoGainControl:!0,enableNoiseSuppression:!0,enableEchoCancellation:!0},this._livePusher=e}_notifyCaptured(e){this.emit(Ee.DeviceCaptured,e)}_notifyStopCapture(e){this.emit(Ee.DeviceStopCapture,e)}_bindStreamEvent(e){e.bindTrackEnd(()=>{this.emit(Ee.Interrupted,e),this.stopCapture({streamId:e.id,type:e.type})})}_handleError(e,t){const i=new yt(t,e.message);this.emit(Ee.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){try{const t=await Eu(e?[e]:["audioinput","videoinput"]);return x(D.GET_DEVICES_RESULT,{type:e,is_success:!0,devices:t}),t}catch(t){return x(D.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 i;switch(t){case N.Camera:i="_cameraStreams";break;case N.Screen:i="_screenStreams";break;case N.VideoFile:i="_videoFileStreams";break;case N.Microphone:i="_microphoneStreams";break;case N.AudioFile:i="_audioFileStreams";break;case N.Image:i="_imageStreams";break;case N.CustomVideo:i="_customVideoStreams";break;case N.CustomAudio:i="_customAudioStreams";break}if(i){let n=[];if(e){const s=this[i][e];n.push(s)}else n=Le(this[i]);x(D.STOP_CAPTURE,{stream_id:e,type:t,number:n.length}),n.forEach(s=>{this._notifyStopCapture(s),s.destroy(),delete this[i][s.id]})}}async startCameraCapture(e){let t={};Gp.includes(e)?t={facingMode:e}:e&&(t={deviceId:{exact:e}});const i={...t,...this._videoConstraints};try{const n=await Cu(i,!this._livePusher.isEnableMixing),s=new Ju(n,{frameRate:this._videoConstraints.frameRate});return this._cameraStreams[s.id]=s,this._notifyCaptured(s),this._bindStreamEvent(s),x(D.CAMERA_CAPTURE_RESULT,{is_success:!0,stream_id:s.id,device_id:e,capture_params:i}),s.id}catch(n){throw x(D.CAMERA_CAPTURE_RESULT,{is_success:!1,device_id:e,capture_params:i,...zt(n)}),this._handleError(n,de.OPEN_CAMERA_FAILED),n}}async startMicrophoneCapture(e){let t={};e&&(t={deviceId:{exact:e}});const i={...this._audioConstraints,...t};try{const n=await Tu(i),s=new Pp(n);return this._microphoneStreams[s.id]=s,this._notifyCaptured(s),this._bindStreamEvent(s),x(D.MICROPHONE_CAPTURE_RESULT,{is_success:!0,stream_id:s.id,device_id:e,capture_params:i}),s.id}catch(n){throw x(D.MICROPHONE_CAPTURE_RESULT,{is_success:!1,device_id:e,capture_params:i,...zt(n)}),this._handleError(n,de.OPEN_MICROPHONE_FAILED),n}}async startScreenCapture(e){const t={audio:e,video:this._videoConstraints};try{const i=await zu(t,void 0,!this._livePusher.isEnableMixing),n=new Op(i,{frameRate:this._videoConstraints.frameRate});return this._screenStreams[n.id]=n,this._notifyCaptured(n),this._bindStreamEvent(n),x(D.SCREEN_CAPTURE_RESULT,{is_success:!0,stream_id:n.id,capture_params:t}),n.id}catch(i){throw x(D.SCREEN_CAPTURE_RESULT,{is_success:!1,capture_params:t,...zt(i)}),this._handleError(i,de.OPEN_SCREEN_FAILED),i}}async startVideoFileCapture(e){try{const t=await os({url:e,video:!0,audio:!0,loop:!0}),i=new Ip(t);return this._videoFileStreams[i.id]=i,this._notifyCaptured(i),this._bindStreamEvent(i),x(D.VIDEO_FILE_CAPTURE_RESULT,{is_success:!0,stream_id:i.id,file_url:e}),i.id}catch(t){throw this._handleError(t,de.VIDEO_FILE_CAPTURE_FAILED),x(D.VIDEO_FILE_CAPTURE_RESULT,{is_success:!1,file_url:e,...zt(t)}),t}}async startAudioFileCapture(e){try{const t=await os({url:e,video:!1,audio:!0,loop:!0}),i=new Mp(t);return this._audioFileStreams[i.id]=i,this._notifyCaptured(i),this._bindStreamEvent(i),x(D.AUDIO_FILE_CAPTURE_RESULT,{is_success:!0,stream_id:i.id,file_url:e}),i.id}catch(t){throw x(D.AUDIO_FILE_CAPTURE_RESULT,{is_success:!1,file_url:e,...zt(t)}),this._handleError(t,de.AUDIO_FILE_CAPTURE_FAILED),t}}async startImageCapture(e){try{const t=await wu({url:e,width:0,height:0,frameRate:30}),i=new Lp(t);return this._imageStreams[i.id]=i,this._notifyCaptured(i),this._bindStreamEvent(i),x(D.IMAGE_FILE_CAPTURE_RESULT,{is_success:!0,stream_id:i.id,file_url:e}),i.id}catch(t){throw x(D.IMAGE_FILE_CAPTURE_RESULT,{is_success:!1,file_url:e,...zt(t)}),this._handleError(t,de.IMAGE_FILE_CAPTURE_FAILED),t}}startCustomVideoCapture(e){const t=Ru(e);if(t){const i=new Up(t);return this._customVideoStreams[i.id]=i,this._notifyCaptured(i),this._bindStreamEvent(i),i.id}}startCustomAudioCapture(e){const t=Au(e);if(t){const i=new Np(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(),x(D.VOLUME_DETECTOR_START_RESULT,{is_success:!0,stream_id:t.id})}catch(i){x(D.VOLUME_DETECTOR_START_RESULT,{is_success:!1,stream_id:t.id,error_message:i.message}),this._handleError(i,de.VOLUME_DETECT_FAILED)}}stopVolumeDetect(e){const t=this.getStreamById(e);t&&t.stopVolumeDetect()}getDefaultVideoStream(){return Le(this._cameraStreams)[0]||Le(this._screenStreams)[0]||Le(this._videoFileStreams)[0]||Le(this._imageStreams)[0]||Le(this._customVideoStreams)[0]}getDefaultAudioStream(){return Le(this._microphoneStreams)[0]||Le(this._audioFileStreams)[0]||Le(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(N).forEach(e=>{this.stopCapture({type:e})})}}let Ze=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 fn{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(Ee.DeviceCaptured,e=>{this._active&&this.onStreamCapture(e)}),this._streamManagerController.on(Ee.DeviceStopCapture,e=>{this._active&&this.onStreamStopCapture(e)})}getComposedStream(){return this._composedStream}enable(){this._active=!0}disable(){this._active=!1}}const sa=new Ze("SingleComposer");class Km extends fn{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 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:i,ideal:i}}))}catch(a){sa.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):sa.error("all video stream stop capture")}}_handleAudioStreamStopCapture(e){this._streamComposeController.removeAudioStream(e.id)}getComposedStream(){return this._composedStream}}class Wm extends Ve{constructor(e,{width:t,height:i,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=i??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 i=this._rect.width,n=this._rect.height;if(i===0&&n===0)return{width:0,height:0};if(i===0)return{height:n,width:e*(n/t)};if(n===0)return{width:i,height:t*(i/e)};const s=e/t,a=i/n;let o=i,d=n;return s>a?(o=i,d=2*Math.round(i/s/2)):s<a&&(o=2*Math.round(n*s/2),d=n),{width:o,height:d}}_bindVideoTrackSizeChange(){this._stream.on(Gn.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 i;return this._rect.mirrorType!==void 0&&this._rect.mirrorType!==On.None?i=t==null?void 0:t.mirror(this._rect.mirrorType):i=t,i=i==null?void 0:i.position(this._rect.x,this._rect.y),i}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 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;case"mirrorType":this._rect.mirrorType=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 oa extends mt{constructor(e,t){super({type:N.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 Jm=Object.defineProperty,Zm=Object.getOwnPropertyDescriptor,lr=(r,e,t,i)=>{for(var n=Zm(e,t),s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=a(e,t,n)||n);return n&&Jm(e,t,n),n};const aa=new Ze("composition-composer");function pr(r,e,t){const i=t.value;return t.value=function(...n){return this._active||aa.error("composer is not active"),i.apply(this,n)},t}class kt extends fn{constructor(e){super(e),this._compositionViewConfig={width:1080,height:720,frameRate:30,backgroundColor:"#000000"},this._sprites=[],this._videoMixer=new Hu}onStreamCapture(e){}onStreamStopCapture(e){e&&e.isVideoStream&&this.removeVideoStream(e.id)}enable(){var i;if(this._active)return;super.enable();const e=this._videoMixer.track(),t=this._mixedVideoStream;this._mixedVideoStream=new oa(e,{frameRate:this._compositionViewConfig.frameRate}),this._composedStream.setVideoStream(this._mixedVideoStream),t&&((i=t.videoTrack)==null?void 0:i.id)!==e.id&&t.destroy()}disable(){super.disable(),this._videoMixer.stop()}_updateSpriteToMixer(){const e=eo(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=>{xp(t.zOrder)||(this._sprites=this._sprites.sort((i,n)=>i.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 i=this._mixedVideoStream,n=this._videoMixer.updateFps();this._mixedVideoStream=new oa(n,{frameRate:this._compositionViewConfig.frameRate}),this._composedStream.setVideoStream(this._mixedVideoStream),i.destroy()}}getMixingConfig(){return this._compositionViewConfig}addVideoStream(e,t){if(!e.viewNode){aa.error("have no viewNode for composition");return}e.audioTrack&&this._streamComposeController.addAudioStream({streamId:e.id,volume:100});const i=new Wm(e,t);this._addSprite(i)}_updateSingleVideoStream(e){const t=e.streamId;if(!t)return;const i=this._sprites.find(n=>n.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,i.mirrorType=e.mirrorType)}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)}getVideoStreamRenderConfig(e){const t=this._sprites.find(i=>i.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()}}lr([pr],kt.prototype,"addVideoStream"),lr([pr],kt.prototype,"updateVideoStream"),lr([pr],kt.prototype,"removeVideoStream"),lr([pr],kt.prototype,"muteVideoStream"),lr([pr],kt.prototype,"unmuteVideoStream");class Xm extends Ve{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 Ym extends zr{constructor(e){super({type:N.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 Qm extends fn{constructor(e){super(e),this._spriteList=[],this._audioMixer=new xu({keepAlive:!0})}onStreamCapture(e){}onStreamStopCapture(e){e&&this.removeAudioStream(e.id)}_updateSpriteToMixer(){const e=eo(this._spriteList.map(t=>t.isMute?null:t.getMixerNode()));this._audioMixer.mix(e)}_updateSingleAudioStream(e){const{streamId:t,volume:i}=e,n=this._spriteList.find(s=>s.stream.id===t);n?i!==void 0&&(n.volume=i):console.error("can not find stream"+t)}enable(){super.enable();const e=this._audioMixer.track(),t=new Ym(e);this._composedStream.setAudioStream(t),this._audioMixer.mix([])}addAudioStream(e,t){const i=new Xm(e,t);this._spriteList.push(i),this._updateSpriteToMixer()}tryResume(){return this._audioMixer.resume()}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 e_ extends Ve{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(rt.VideoStreamChange,e))}setAudioStream(e){var t;((t=this._audioStream)==null?void 0:t.id)!==e.id&&(this._audioStream=e,this.emit(rt.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 t_=new Ze("streamComposeController");class r_{constructor(e){this._streamManagerController=e,this._composedStream=new e_,this.singleComposer=new Km({streamManagerController:this._streamManagerController,composedStream:this._composedStream,streamComposeController:this}),this.compositionComposer=new kt({streamManagerController:this._streamManagerController,composedStream:this._composedStream,streamComposeController:this}),this.mixerComposer=new Qm({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)}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){t_.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)}getVideoStreamRenderConfig(e){if(this.compositionComposer._active)return this.compositionComposer.getVideoStreamRenderConfig(e)}resumeMixer(){return this.mixerComposer.tryResume()}getCompositionDrawCountPerSecond(){return this.compositionComposer.getDrawCountPerSecond()}}class ca{constructor(e){this._hasBindComposedStreamEvent=!1,this._composedStream=e}bindComposedStreamEvent(){this._hasBindComposedStreamEvent||(this._composedStream.on(rt.VideoStreamChange,this.handleVideoStreamChange),this._composedStream.on(rt.AudioStreamChange,this.handleAudioStreamChange),this._hasBindComposedStreamEvent=!0)}unbindComposedStreamEvent(){this._hasBindComposedStreamEvent&&(this._composedStream.off(rt.VideoStreamChange,this.handleVideoStreamChange),this._composedStream.off(rt.AudioStreamChange,this.handleAudioStreamChange),this._hasBindComposedStreamEvent=!1)}}const Rt=new Ze("PreviewConsumer");class i_ extends ca{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 n={video:null,audio:null};i.addEventListener("loadeddata",()=>{const s=i.srcObject.getVideoTracks()[0],a=i.srcObject.getAudioTracks()[0];s&&s!==n.video&&(this._streamConsumeController.emit(W.CaptureFirstVideoFrame),n.video=s),a&&a!==n.audio&&(this._streamConsumeController.emit(W.CaptureFirstAudioFrame),n.audio=a)}),t.appendChild(i)}startPreview(){if(Rt.log("startPreview"),!this._previewElement){Rt.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(W.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(n=>n.id===t.id)||(t.kind==="audio"&&i.getTracks().forEach(n=>{n.kind==="audio"&&(Rt.log(`remove preview track, ${n.label}, readyState=${n.readyState}`),i.removeTrack(n))}),t.kind==="video"&&i.getTracks().forEach(n=>{n.kind==="video"&&(i.removeTrack(n),Rt.log(`remove preview track, ${n.label}, readyState=${n.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(n=>{(n.id===(t==null?void 0:t.id)||n.readyState==="ended")&&(Rt.log(`remove preview track ${n.label}`),i.removeTrack(n))}),i.getTracks().length===0&&(e.srcObject=null,Rt.log("set srcObject null")))}getPreviewElement(){if(this.isPreviewing)return this._previewElement}get isPreviewing(){return this._isPreviewing}}var be={},mn={},_n={exports:{}},ua;function gn(){if(ua)return _n.exports;ua=1;var r=_n.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")})}),_n.exports}var da;function n_(){return da||(da=1,function(r){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]))},i=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=gn(),s=RegExp.prototype.test.bind(/^([a-z])=(.*)/);r.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 i(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};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 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},r.parseImageAttributes=function(o){return o.split(" ").map(function(d){return d.substring(1,d.length-1).split(",").reduce(a,{})})},r.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}})})}}(mn)),mn}var vn,ha;function s_(){if(ha)return vn;ha=1;var r=gn(),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""}})},i=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 vn=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){r[l].forEach(function(h){h.name in a&&a[h.name]!=null?u.push(i(l,h,a)):h.push in a&&a[h.push]!=null&&a[h.push].forEach(function(p){u.push(i(l,h,p))})})}),a.media.forEach(function(l){u.push(i("m",r.m[0],l)),c.forEach(function(h){r[h].forEach(function(p){p.name in l&&l[p.name]!=null?u.push(i(h,p,l)):p.push in l&&l[p.push]!=null&&l[p.push].forEach(function(f){u.push(i(h,p,f))})})})}),u.join(`\r
67
67
  `)+`\r
68
- `},vn}var ha;function i_(){if(ha)return be;ha=1;var r=t_(),e=r_(),t=gn();return be.grammar=t,be.write=e,be.parse=r.parse,be.parseParams=r.parseParams,be.parseFmtpConfig=r.parseFmtpConfig,be.parsePayloads=r.parsePayloads,be.parseRemoteCandidates=r.parseRemoteCandidates,be.parseImageAttributes=r.parseImageAttributes,be.parseSimulcastStreamList=r.parseSimulcastStreamList,be}var n_=i_();const At=ne(n_);function Wr(r){return new Promise(e=>{setTimeout(e,r)})}async function s_(r,e={},t=0){const i=new AbortController;let n=!1;e=Object.assign({},e,{signal:i.signal});const s=[fetch(r,e)];t&&s.push(new Promise((a,o)=>{setTimeout(()=>{n||(o({httpCode:0,message:"Timeout"}),i.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 la(r,e={},t={}){const{timeout:i=0,retryDelay:n=0}=t;let{retryCount:s=0}=t;try{return await s_(r,e,i)}catch(a){if(s--,t.retryCount=s,s<0)throw a;return await Wr(n),await la(r,e,t)}}const yn=-1;function ee(r,e){let t;return e.forEach(i=>{i.type===r&&(t=i)}),t}async function bn(r,e){const t={},i=await(r==null?void 0:r.getStats()),n=await(e==null?void 0:e.getStats());return i&&(t.audio={mediaSource:ee("media-source",i),codec:ee("codec",i),candidatePair:ee("candidate-pair",i),remoteCandidate:ee("remote-candidate",i),localCandidate:ee("local-candidate",i),track:ee("track",i),outboundRtp:ee("outbound-rtp",i),remoteInboundRtp:ee("remote-inbound-rtp",i),transport:ee("transport",i)}),n&&(t.video={mediaSource:ee("media-source",n),codec:ee("codec",n),candidatePair:ee("candidate-pair",n),remoteCandidate:ee("remote-candidate",n),localCandidate:ee("local-candidate",n),track:ee("track",n),outboundRtp:ee("outbound-rtp",n),remoteInboundRtp:ee("remote-inbound-rtp",n),transport:ee("transport",n)}),t}async function o_(r,e,t){var u,l,h,p,f,v,m,E,y,_,C,z,w,A,k,T,R,I,H,V,q,K,ae,j,te,Se,et,tt,mr,_r,gr,vr,mc,_c,gc,vc,yc,bc,Sc;const i=await bn(e,t);await Wr(r);const n=await bn(e,t),{audio:s,video:a}=i,{audio:o,video:d}=n,c={};if(s!=null&&s.codec&&(o!=null&&o.codec)){const It=((u=o.outboundRtp)==null?void 0:u.timestamp)-((l=s.outboundRtp)==null?void 0:l.timestamp),Dn=((h=o.outboundRtp)==null?void 0:h.bytesSent)-((p=s.outboundRtp)==null?void 0:p.bytesSent),ni=((f=o.remoteInboundRtp)==null?void 0:f.packetsLost)-((v=s.remoteInboundRtp)==null?void 0:v.packetsLost),xn=((m=o.outboundRtp)==null?void 0:m.packetsSent)-((E=s.outboundRtp)==null?void 0:E.packetsSent),Pn=(((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:Dn/It*8e3,packetsSent:(C=o.outboundRtp)==null?void 0:C.packetsSent,nackCount:(z=o.outboundRtp)==null?void 0:z.nackCount,packetsLost:(w=o.remoteInboundRtp)==null?void 0:w.packetsLost,packetsLostPercent:ni/xn,deltaAudioEnergy:Pn}}if(a!=null&&a.codec&&(d!=null&&d.codec)){const It=((A=d.outboundRtp)==null?void 0:A.timestamp)-((k=a.outboundRtp)==null?void 0:k.timestamp),Dn=((T=d.outboundRtp)==null?void 0:T.bytesSent)-((R=a.outboundRtp)==null?void 0:R.bytesSent),ni=((I=d.outboundRtp)==null?void 0:I.framesEncoded)-((H=a.outboundRtp)==null?void 0:H.framesEncoded),xn=((V=d.outboundRtp)==null?void 0:V.totalEncodeTime)-((q=a.outboundRtp)==null?void 0:q.totalEncodeTime),Pn=((K=d.outboundRtp)==null?void 0:K.framesSent)-((ae=a.outboundRtp)==null?void 0:ae.framesSent),Ec=((j=d.outboundRtp)==null?void 0:j.packetsSent)-((te=a.outboundRtp)==null?void 0:te.packetsSent),H_=((Se=d.outboundRtp)==null?void 0:Se.totalPacketSendDelay)-((et=a.outboundRtp)==null?void 0:et.totalPacketSendDelay),$_=((tt=d.remoteInboundRtp)==null?void 0:tt.packetsLost)-((mr=a.remoteInboundRtp)==null?void 0:mr.packetsLost);c.video={codec:d.codec.mimeType,sendBitrate:Dn/It*8e3,frameWidth:(_r=d.outboundRtp)==null?void 0:_r.frameWidth,frameHeight:(gr=d.outboundRtp)==null?void 0:gr.frameHeight,framesPerSecond:Math.floor(Pn/It*1e3||0),framesEncoded:(vr=d.outboundRtp)==null?void 0:vr.framesEncoded,framesEncodedPerSecond:ni*1e3/It,keyFramesEncoded:(mc=d.outboundRtp)==null?void 0:mc.keyFramesEncoded,framesSent:(_c=d.outboundRtp)==null?void 0:_c.frameHeight,frameEncodeAvgTime:xn*1e3/ni,packetsSent:(gc=d.outboundRtp)==null?void 0:gc.packetsSent,packetSendDelay:H_*1e3/Ec,nackCount:(vc=d.outboundRtp)==null?void 0:vc.nackCount,firCount:(yc=d.outboundRtp)==null?void 0:yc.firCount,pliCount:(bc=d.outboundRtp)==null?void 0:bc.pliCount,packetsLost:(Sc=d.remoteInboundRtp)==null?void 0:Sc.packetsLost,packetsLostPercent:$_/Ec,deltaTime:It}}return{stats:c,originStats:{audio:o,video:d}}}function Z(r,e=yn){return r??e}function a_(r){var e,t,i,n,s,a,o,d,c,u,l,h,p,f,v,m,E,y,_,C,z,w,A,k,T,R,I,H,V,q,K,ae,j,te,Se,et,tt,mr,_r,gr,vr;return{audio_bytes:(e=r.outboundRtp)==null?void 0:e.bytesSent,audio_packets_sent:(t=r.outboundRtp)==null?void 0:t.packetsSent,audio_nack_count:(i=r.outboundRtp)==null?void 0:i.nackCount,audio_ssrc:(n=r.outboundRtp)==null?void 0:n.ssrc,audio_retransmitted_bytes_sent:(s=r.outboundRtp)==null?void 0:s.retransmittedBytesSent,audio_retransmitted_packets_sent:(a=r.outboundRtp)==null?void 0:a.retransmittedPacketsSent,audio_record_sample_rate:(o=r.codec)==null?void 0:o.clockRate,audio_num_channels:(d=r.codec)==null?void 0:d.channels,audio_level:(c=r.mediaSource)!=null&&c.audioLevel?-10*Math.log10(Math.pow((u=r.mediaSource)==null?void 0:u.audioLevel,2)):(l=r.mediaSource)==null?void 0:l.audioLevel,audio_volume:(h=r.mediaSource)!=null&&h.audioLevel?((p=r.mediaSource)==null?void 0:p.audioLevel)*255:(f=r.mediaSource)==null?void 0:f.audioLevel,audio_total_audio_energy:(v=r.mediaSource)==null?void 0:v.totalAudioEnergy,audio_total_input_duration:(m=r.mediaSource)==null?void 0:m.totalSamplesDuration,audio_send_level:(E=r.mediaSource)==null?void 0:E.audioLevel,audio_ice_available_outgoing_bitrate:(y=r.candidatePair)==null?void 0:y.availableOutgoingBitrate,audio_ice_bytes_received:(_=r.candidatePair)==null?void 0:_.bytesReceived,audio_ice_bytes_sent:(C=r.candidatePair)==null?void 0:C.bytesSent,audio_ice_nominated:(z=r.candidatePair)==null?void 0:z.nominated,audio_ice_pair_id:(w=r.candidatePair)==null?void 0:w.id,audio_ice_pair_rtt:(A=r.candidatePair)==null?void 0:A.currentRoundTripTime,audio_ice_pair_state:(k=r.candidatePair)==null?void 0:k.state,audio_ice_pair_writable:(T=r.candidatePair)==null?void 0:T.writable,audio_recv_ping_requests:(R=r.candidatePair)==null?void 0:R.requestsReceived,audio_recv_ping_responses:(I=r.candidatePair)==null?void 0:I.responsesReceived,audio_sent_ping_requests_before_first_response:(H=r.candidatePair)==null?void 0:H.requestsSent,audio_sent_ping_requests_total:(((V=r.candidatePair)==null?void 0:V.requestsSent)??0)+(((q=r.candidatePair)==null?void 0:q.consentRequestsSent)??0),audio_sent_ping_responses:(K=r.candidatePair)==null?void 0:K.responsesSent,audio_local_candidate_type:(ae=r.localCandidate)==null?void 0:ae.candidateType,audio_local_ip:((j=r.localCandidate)==null?void 0:j.ip)||((te=r.localCandidate)==null?void 0:te.address),audio_local_network_type:(Se=r.localCandidate)==null?void 0:Se.networkType,audio_local_port:(et=r.localCandidate)==null?void 0:et.port,audio_local_protocol:(tt=r.localCandidate)==null?void 0:tt.protocol,audio_remote_candidate_type:(mr=r.remoteCandidate)==null?void 0:mr.candidateType,audio_remote_ip:((_r=r.remoteCandidate)==null?void 0:_r.ip)||((gr=r.remoteCandidate)==null?void 0:gr.address),audio_remote_port:(vr=r.remoteCandidate)==null?void 0:vr.port}}function c_(r){var e,t,i,n,s,a,o,d,c,u,l,h,p,f,v,m,E,y,_,C,z,w,A,k,T,R,I,H,V,q,K,ae,j,te,Se,et,tt;return{video_qp_sum:(e=r.outboundRtp)==null?void 0:e.qpSum,video_pli_count:(t=r.outboundRtp)==null?void 0:t.pliCount,video_ssrc:(i=r.outboundRtp)==null?void 0:i.ssrc,video_quality_limitation_reason:(n=r.outboundRtp)==null?void 0:n.qualityLimitationReason,video_quality_limitation_durations:(s=r.outboundRtp)==null?void 0:s.qualityLimitationDurations,video_target_bitrate:(a=r.outboundRtp)==null?void 0:a.targetBitrate,video_rtt:(((o=r.remoteInboundRtp)==null?void 0:o.roundTripTime)||0)*1e3,video_jitter:(((d=r.remoteInboundRtp)==null?void 0:d.jitter)||0)*1e3,video_packets_lost:(c=r.remoteInboundRtp)==null?void 0:c.packetsLost,video_fraction_lost:(u=r.remoteInboundRtp)==null?void 0:u.fractionLost,video_ice_available_outgoing_bitrate:(l=r.candidatePair)==null?void 0:l.availableOutgoingBitrate,video_ice_bytes_received:(h=r.candidatePair)==null?void 0:h.bytesReceived,video_ice_bytes_sent:(p=r.candidatePair)==null?void 0:p.bytesSent,video_ice_nominated:(f=r.candidatePair)==null?void 0:f.nominated,video_ice_pair_id:(v=r.candidatePair)==null?void 0:v.id,video_ice_pair_rtt:(m=r.candidatePair)==null?void 0:m.currentRoundTripTime,video_ice_pair_state:(E=r.candidatePair)==null?void 0:E.state,video_ice_pair_writable:(y=r.candidatePair)==null?void 0:y.writable,video_recv_ping_requests:(_=r.candidatePair)==null?void 0:_.requestsReceived,video_recv_ping_responses:(C=r.candidatePair)==null?void 0:C.responsesReceived,video_sent_ping_requests_before_first_response:(z=r.candidatePair)==null?void 0:z.requestsSent,video_sent_ping_requests_total:(((w=r.candidatePair)==null?void 0:w.requestsSent)??0)+(((A=r.candidatePair)==null?void 0:A.consentRequestsSent)??0),video_sent_ping_responses:(k=r.candidatePair)==null?void 0:k.responsesSent,video_local_candidate_type:(T=r.localCandidate)==null?void 0:T.candidateType,video_local_ip:((R=r.localCandidate)==null?void 0:R.ip)||((I=r.localCandidate)==null?void 0:I.address),video_local_network_type:(H=r.localCandidate)==null?void 0:H.networkType,video_local_port:(V=r.localCandidate)==null?void 0:V.port,video_local_protocol:(q=r.localCandidate)==null?void 0:q.protocol,video_remote_candidate_type:(K=r.remoteCandidate)==null?void 0:K.candidateType,video_remote_ip:((ae=r.remoteCandidate)==null?void 0:ae.ip)||((j=r.remoteCandidate)==null?void 0:j.address),video_remote_port:(te=r.remoteCandidate)==null?void 0:te.port,video_input_frame_rate:(Se=r.mediaSource)==null?void 0:Se.framesPerSecond,video_input_frame_width:(et=r.mediaSource)==null?void 0:et.width,video_input_frame_height:(tt=r.mediaSource)==null?void 0:tt.height}}function u_(r,e,t){var c,u,l,h,p,f,v,m,E,y,_,C,z,w,A,k,T,R,I,H,V,q,K,ae,j,te,Se;const i=c_(e.video??{}),{video_input_frame_width:n,video_input_frame_height:s}=i,a=Z((c=r.video)==null?void 0:c.frameWidth),o=Z((u=r.video)==null?void 0:u.frameHeight),d=a<Number(n)||o<Number(s);return{...i,video_send_k_bitrate:Z((l=r.video)==null?void 0:l.sendBitrate)/1e3,video_send_frame_rate:Z((h=r.video)==null?void 0:h.framesPerSecond),video_encode_avg_time:Z((p=r.video)==null?void 0:p.frameEncodeAvgTime),video_encoder_output_frame_rate:Z((f=r.video)==null?void 0:f.framesEncodedPerSecond),video_encoded_frame_width:Z((v=r.video)==null?void 0:v.frameWidth),video_encoded_frame_height:Z((m=r.video)==null?void 0:m.frameHeight),video_encoded_key_frames:Z((E=r.video)==null?void 0:E.keyFramesEncoded),video_delta_time:Z((y=r.video)==null?void 0:y.deltaTime,2e3),video_packets_sent:Z((_=r.video)==null?void 0:_.packetsSent),video_nack_count:Z((C=r.video)==null?void 0:C.nackCount),video_fir_count:Z((z=r.video)==null?void 0:z.firCount),video_pli_count:Z((w=r.video)==null?void 0:w.pliCount),video_packets_lost:Z((A=r.video)==null?void 0:A.packetsLost),video_packets_lost_percent:(k=r.video)==null?void 0:k.packetsLostPercent,video_codec:(T=r.video)==null?void 0:T.codec,video_duration:(R=r.video)==null?void 0:R.deltaTime,video_frame_rate_compliance:t!=null&&t.idealFrameRate?Math.min(Z((I=r.video)==null?void 0:I.framesPerSecond)/t.idealFrameRate,1)*100:yn,video_bitrate_compliance:t!=null&&t.idealBitrate?Math.min(Z((H=r.video)==null?void 0:H.sendBitrate)/t.idealBitrate,1)*100:yn,video_resolution_downgrade:d,...a_(e.audio??{}),audio_send_k_bitrate:Z((V=r.audio)==null?void 0:V.sendBitrate)/1e3,audio_send_channels:Z((q=r.audio)==null?void 0:q.channels),audio_packets_sent:Z((K=r.audio)==null?void 0:K.packetsSent),audio_packets_lost:Z((ae=r.audio)==null?void 0:ae.packetsLost),audio_packets_lost_percent:(j=r.audio)==null?void 0:j.packetsLostPercent,audio_codec:(te=r.audio)==null?void 0:te.codec,audio_delta_energy:(Se=r.audio)==null?void 0:Se.deltaAudioEnergy}}function d_(r){return{video_send_k_bitrate:r.video.sendBitrate/1e3,video_send_frame_rate:r.video.framesPerSecond,video_encoded_frame_width:r.video.frameWidth,video_encoded_frame_height:r.video.frameHeight,video_encoded_key_frames:r.video.keyFramesEncoded,video_send_speed:r.video.sendSpeed/1e3,video_gop_size:r.video.gopSize,video_codec:r.video.codec,video_duration:0,audio_send_k_bitrate:r.audio.sendBitrate/1e3,audio_codec:r.audio.codec,audio_send_channels:r.audio.channels,audio_send_sample_rate:r.audio.sampleRate}}const h_="42001f",l_="42e01f",p_=r=>{var t;if(!Wn)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")})},f_=r=>{r.ext&&(Ic||yr)&&(r.ext=r.ext.filter(e=>{var t;return!((t=e.uri)!=null&&t.includes("video-orientation"))}))};function m_(r,e){r==null||r.rtp.forEach(({codec:t,payload:i})=>{if(["vp8","h264"].includes(t.toLocaleLowerCase())){const n=r.fmtp.find(s=>s.payload===i);n?n.config=[...n.config.split(";"),`x-google-min-bitrate=${e*.4}`,`x-google-start-bitrate=${e}`].join(";"):r.fmtp.push({payload:i,config:`x-google-min-bitrate=${e*.4};x-google-start-bitrate=${e}`})}})}function pa(r,e){if(!Array.isArray(r.fmtp)||!Array.isArray(r.rtp))return;const t=r.fmtp.find(a=>a.config&&a.config.includes(h_)),i=r.fmtp.find(a=>a.config&&a.config.includes(l_));if(!t||!i)return;const n=r.rtp.findIndex(a=>a.payload===t.payload),s=r.rtp.findIndex(a=>a.payload===i.payload);if(n!==-1&&s!==-1){if(e==="hardware"){if(s<n){const a=r.rtp[s];r.rtp[s]=r.rtp[n],r.rtp[n]=a}}else if(n<s){const a=r.rtp[n];r.rtp[n]=r.rtp[s],r.rtp[s]=a}}r.payloads=r.rtp.map(a=>a.payload).join(" ")}const oe=new Ze("PCConnect");class __{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,n;return!!((t=(e=this._videoTransceiver)==null?void 0:e.sender)!=null&&t.track||(n=(i=this._audioTransceiver)==null?void 0:i.sender)!=null&&n.track)}get videoSenderTrackStats(){var e,t,i,n;return{track_enabled:(t=(e=this._videoTransceiver)==null?void 0:e.sender.track)==null?void 0:t.enabled,track_muted:(n=(i=this._videoTransceiver)==null?void 0:i.sender.track)==null?void 0:n.muted}}get pushUrl(){return this._signalUrl}get sessionId(){return this._sessionId}async publish(e,t,i){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]}),oe.log("add track to pc,",s),this._videoTransceiver=n.addTransceiver(a||"video",{direction:"sendonly",sendEncodings:[{maxBitrate:t[1]}],streams:[this._ms]}),oe.log("add track to pc,",a);const o=await n.createOffer();oe.groupCollapsed("local offer"),oe.log(o.sdp);const d=At.parse(o.sdp);d.media.forEach(h=>{h.type==="audio"?p_(h):h.type==="video"&&(f_(h),pa(h,"software"),m_(h,t[1]))}),o.sdp=At.write(d),oe.log("local offer modified"),oe.log(o.sdp),await n.setLocalDescription(o);const c=await la(this._signalUrl,{method:"POST",mode:"cors",body:JSON.stringify({sessionId:""+this._sessionId,version:"1.0-html",localSdp:o,metadata:{platform:"Web"}})},{...this._opts,timeout:i!=null&&i.isReconnect?10*to:(l=this._opts)==null?void 0:l.timeout});if((c==null?void 0:c.code)!==200)throw{code:c.code,message:c.message};oe.log("remote answer:"),oe.log(c.remoteSdp.sdp);const u=At.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=At.write(u),oe.log("remote answer modified"),oe.log(c.remoteSdp.sdp),oe.groupEnd(),n.connectionState==="closed"){oe.log("PeerConnection is closed, skipping setRemoteDescription");return}D(x.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,i=(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(i&&n){const o=At.parse(n);o.media.forEach(d=>{d.type==="video"&&pa(d,e)}),t.setLocalDescription(t.localDescription),t.setRemoteDescription({type:"answer",sdp:At.write(o)})}}async updatePublish(e,t){var s,a;let i;t==="video"?i=this._videoTransceiver:i=this._audioTransceiver;const n=(s=i==null?void 0:i.sender)==null?void 0:s.track;(n==null?void 0:n.id)!==(e==null?void 0:e.id)&&(await((a=i==null?void 0:i.sender)==null?void 0:a.replaceTrack(e)),oe.log(`replace ${t} track done! ${n==null?void 0:n.label} -> ${e==null?void 0:e.label}`))}applyBitrate(e,t,i){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:[{}],i?s.encodings[0].minBitrate=e:s.encodings[0].maxBitrate=e,n.setParameters(s),oe.log(`set bitrate for ${t}, ${e} bps, min:${i}`)}unpublish(){var e,t;(e=this._pc)==null||e.getSenders().forEach(i=>{var n;(n=this._pc)==null||n.removeTrack(i)}),(t=this._pc)==null||t.close(),this._audioTransceiver=null,this._videoTransceiver=null,this._pc=null,oe.log("close pc!")}getStats(){var e,t;return bn((e=this._audioTransceiver)==null?void 0:e.sender,(t=this._videoTransceiver)==null?void 0:t.sender)}getStatsSnapshoot(e){var t,i;return o_(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",()=>{oe.log("onconnectionstatechange:",e.connectionState),this._onConnectStateChange(e.connectionState)})}}var Xe=(r=>(r.OnError="onerror",r.OnConnectClosed="onconnectclosed",r.OnFirstFramePushed="onfirstframepushed",r))(Xe||{}),Ye=(r=>(r.Video="video",r.Audio="audio",r))(Ye||{}),ge=(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))(ge||{}),lt=(r=>(r.Ready="ready",r.Error="error",r.FirstFramePushed="firstframepushed",r.Flvfile="flvfile",r.STATS="stats",r.Close="close",r))(lt||{}),Sn={exports:{}},fa;function g_(){return fa||(fa=1,function(r){var e=Object.prototype.hasOwnProperty,t="~";function i(){}Object.create&&(i.prototype=Object.create(null),new i().__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 i:delete d._events[c]}function o(){this._events=new i,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],E=arguments.length,y,_;if(m.fn){switch(m.once&&this.removeListener(c,m.fn,void 0,!0),E){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(E-1);_<E;_++)y[_-1]=arguments[_];m.fn.apply(m.context,y)}else{var C=m.length,z;for(_=0;_<C;_++)switch(m[_].once&&this.removeListener(c,m[_].fn,void 0,!0),E){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(E-1);z<E;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=[],E=f.length;v<E;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 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}(Sn)),Sn.exports}var v_=g_();const y_=ne(v_);var Jr=(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))(Jr||{});class ma 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 _a(r,e,t){return new ma(r,e,t)}const Pt=class Pt{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 Pt.enable}get _enableLong(){return Pt.enableLong}get long(){return this._enableLong}};Pt.enable=!1,Pt.enableLong=!1;let Qe=Pt;const ve=new Qe("RTMP_Capture");class b_{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(ve.log(`replace ${e} track`),e===Ye.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){ve.log("no video track to capture");return}if(this.videoTrack.readyState!=="live"){ve.warn("video track not live");return}const e=new MediaStreamTrackProcessor(this.videoTrack);e.track=this.videoTrack;const t=e.readable.getReader();this._videoProcessorReader=t,ve.log("start capture video frame",this.videoTrack);let i;for(;;){i&&clearInterval(i),i=setTimeout(()=>{ve.warn("long time no capture output"),this._bridge._postMockVideoEncodeFlag()},1500);const s=await t.read();if(clearInterval(i),this._videoFirstframeCaptured||(this._videoFirstframeCaptured=!0,ve.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(i),this._videoFirstframeCaptured=!1,this._videoProcessorReader=null,ve.log("video track read done!",e.track)}async _startAudioCapture(){if(!this.audioTrack){ve.log("no audio track to capture");return}if(this.audioTrack.readyState!=="live"){ve.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,ve.log("start capture audio frame");;){const i=await t.read();if(this._audioFirstframeCaptured||(this._audioFirstframeCaptured=!0,ve.log("audio first frame captured")),i.done||!i.value)break;this._bridge._postAudioFrame(i.value,this.audioTrack.getSettings())}this._audioFirstframeCaptured=!1,this._audioProcessorReader=null,ve.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 ga='(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,N,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,N=new Array(C-1);p<C;p++)N[p-1]=arguments[p];d.fn.apply(d.context,N)}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(!N)for(R=1,N=new Array(C-1);R<C;R++)N[R-1]=arguments[R];d[p].fn.apply(d[p].context,N)}}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 x=class x{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 x.enable}get _enableLong(){return x.enableLong}get long(){return this._enableLong}};x.enable=!1,x.enableLong=!1;let E=x;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 L=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){L.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(),L.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),L.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,L.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);L.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 B=(i=>(i[i.AUDIO=8]="AUDIO",i[i.VIDEO=9]="VIDEO",i[i.SCRIPT_DATA=18]="SCRIPT_DATA",i))(B||{});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(B.VIDEO,s);this._core.emit(l.OnPacketed,c)}if(o.hasAudio){const c=this._flv.genSeqTag(B.AUDIO,s);this._core.emit(l.OnPacketed,c)}this._firstFrame=!1,ae.log("first frame encoded & packed")}const r=this._flv.genFrameTag(e==="video"?B.VIDEO:B.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.videoBitrate}`),this._core.emit(l.OnUpstreamFeedback,{videoBitrate:t.videoBitrate,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,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}),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}),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',va=typeof self<"u"&&self.Blob&&new Blob([ga],{type:"text/javascript;charset=utf-8"});function S_(r){let e;try{if(e=va&&(self.URL||self.webkitURL).createObjectURL(va),!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(ga),{name:r==null?void 0:r.name})}finally{e&&(self.URL||self.webkitURL).revokeObjectURL(e)}}try{Qe.enable=location.href.indexOf("rtmpdebug")!==-1,Qe.enableLong=location.href.indexOf("rtmpdebug=long")!==-1}catch{}const Zr=new Qe("Bridge");class ya extends y_{constructor(){super(),this._worker=null,this._audioMsTrack=null,this._videoMsTrack=null,this._capture=new b_(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 i=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 lt.Error:t(o.data.data);break;default:this._bindWorkerEvent(),Zr.log("rtmp ready!"),e(!0)}};try{this._worker=new S_}catch(o){t(_a(Jr.RTMP_INIT_FAIL,o.message))}return(s=this._worker)==null||s.postMessage({type:ge.Init,options:{logEnable:Qe.enable,logEnableLong:Qe.enableLong}}),(a=this._worker)==null||a.addEventListener("message",n),i}_bindWorkerEvent(){var e,t;(e=this._worker)==null||e.addEventListener("message",i=>{switch(i.data.type){case lt.Error:Zr.table(i.data.data),this.emit(Xe.OnError,i.data.data);break;case lt.Flvfile:E_(i.data.buffer);break;case lt.FirstFramePushed:this.emit(Xe.OnFirstFramePushed);break;case lt.Close:this.emit(Xe.OnConnectClosed),this.destroy();break}}),(t=this._worker)==null||t.addEventListener("error",i=>{this.emit(Xe.OnError,_a(Jr.WORKER_ERROR,i.message))})}addTrack(e){e.kind===Ye.Video&&(this._videoMsTrack=e),e.kind===Ye.Audio&&(this._audioMsTrack=e),this._setAVExist(!!this._videoMsTrack,!!this._audioMsTrack)}replaceTrack(e,t){e===Ye.Video&&(this._videoMsTrack=t),e===Ye.Audio&&(this._audioMsTrack=t),this._setAVExist(!!this._videoMsTrack,!!this._audioMsTrack),this._capture.restartCapture(e)}async getStats(){var s,a;let e,t;const i=new Promise((o,d)=>{e=o,t=d});this._worker||setTimeout(()=>{t()},0);const n=o=>{var d;switch(o.data.type){case lt.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:ge.GetStats}),i}_postVideoFrame(e,t){var i;(i=this._worker)==null||i.postMessage({type:ge.VideoFrame,frame:e,setting:t},[e])}_postMockVideoEncodeFlag(){var e;(e=this._worker)==null||e.postMessage({type:ge.MockVideoEncode})}_setAVExist(e,t){var i;(i=this._worker)==null||i.postMessage({type:ge.AvExist,hasVideo:e,hasAudio:t})}_postAudioFrame(e,t){var i;(i=this._worker)==null||i.postMessage({type:ge.AudioFrame,frame:e,setting:t},[e])}setEncodeCapacity(e){var t;(t=this._worker)==null||t.postMessage({type:ge.EncodeConfig,cfg:e})}adjustBitrate(e,t){var i;(i=this._worker)==null||i.postMessage({type:ge.AdjustBitrate,kind:e,bitrate:t})}publish(e){var t;Zr.log("start capture & connect"),this._capture.start(),(t=this._worker)==null||t.postMessage({type:ge.Publish,url:e})}unpublish(){var e;this._capture.destroy(),(e=this._worker)==null||e.postMessage({type:ge.UnPublish})}destroy(){var e;Zr.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:ge.Download})}}function E_(r){const e=document.createElement("a");e.href=URL.createObjectURL(new Blob([r])),e.download=Date.now()+".flv",e.click()}const ba=new Ze("RTMPConnect");class C_{constructor(e,t,i,n){this._opts=void 0,this._isPushing=!1,this._url=e,this._opts=t,this._onError=i,this._OnSuccess=n,this._rtmp=new ya,this._bindEvents()}get isPushing(){return this._isPushing}get pushUrl(){return this._url}get sessionId(){return 0}_bindEvents(){this._rtmp.on(Xe.OnError,e=>{this._isPushing=!1,this._onError(e)}),this._rtmp.on(Xe.OnConnectClosed,()=>{this._isPushing=!1,this._onError(new ma(Jr.WTP_CONNECT_FAIL,"connect lost"))}),this._rtmp.on(Xe.OnFirstFramePushed,()=>{this._isPushing=!0,this._OnSuccess()})}async publish(e,t,i){await this._rtmp.ready(),i!=null&&i.cfg&&this._rtmp.setEncodeCapacity(i.cfg),e.filter(Boolean).forEach(n=>this._rtmp.addTrack(n)),t[0]&&this._rtmp.adjustBitrate(Ye.Audio,t[0]),t[1]&&this._rtmp.adjustBitrate(Ye.Video,t[1]),this._rtmp.publish(this._url)}updatePublish(e,t){ba.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 Wr(e),{stats:await this._rtmp.getStats(),originStats:void 0}}unpublish(){ba.warn("unpublish"),this._rtmp.unpublish(),this._isPushing=!1}}function Sa({pushUrl:r,addPri:e=!1,disableTCC:t=!1}){const i=new URL(r),n=Date.now();return e&&i.searchParams.set("pri",n.toString()),t&&i.searchParams.set("tcc","false"),i.href}class w_{constructor(e,t=Gp){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=(i=!1)=>{var n;this._logger.log("start reconnect strategy"),this.state==="idle"&&(this._reconnectStartTime=Date.now(),this._totalReconnectInfo.totalReconnectCount+=1,D(x.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:ft.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(i))},this.attemptReconnect=async()=>{var i;if(this.state==="executing"){this.setStrategyState("reconnecting"),this._reconnectCount+=1;const n=this.getNextPushUrl();try{if(this._pushConsumer.emitReconnectStateChange({state:ft.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:oi.PushUrlInvalid,failedError:s}),(i=this._onReconnectError)==null||i.call(this,"pushError",s);else{if(!this.isActive())return;this.setStrategyState("executing"),this.execute()}}}},this.executeStrategy=(i=!1)=>{const n=i?0:this._reconnectDelay;this._pushConsumer.emitReconnectStateChange({state:ft.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,Bp)},this.state="idle",this._pushConsumer=e,this._maxTimeout=t,this._logger=new Ze("ReconnectStrategy")}getNextPushUrl(){const e=this._pushConsumer.pushUrl;return e?Sa({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:i=!1,failedError:n}){var a;if(this.state==="idle")return;const s=(Date.now()-this._reconnectStartTime)/1e3;i||(e?this._pushConsumer.emitReconnectStateChange({state:ft.SUCCESS,teaParams:{reconnect_duration:s,session_id:this._pushConsumer.pushSessionId}}):(this._logger.log("Reconnect strategy stopped: ",t),this._pushConsumer.emitReconnectStateChange({state:ft.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:oi.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 fr={ManualStop:0,ReconnectFailed:1,StartPushError:2,PushError:3},Dt={PushCheck:0,PushError:1},Ea=new Ze("PushController");class T_ extends aa{constructor(e,{config:t,streamConsumeController:i,streamComposedController:n}){var s,a;if(super(e),this._connect=null,this._connectionState=pe.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=bt(Vn,"audio").bitrate,this._videoBitrate=bt(Bn,"video").bitrate,this.handleReconnectError=(o,d)=>{var c,u;D(x.STOP_PUSH_STREAM,{reason:fr.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(pe.CONNECTED)},this._OnRTMPError=o=>{const d=new yt(de.PUBLISH_FAILED,`code:${o.code}, message: ${o.message}`);this._streamConsumeController.emit(W.PushError,d),D(x.STOP_PUSH_STREAM,{reason:fr.PushError,duration:this.pushDuration,session_id:this._pushSessionId,push_mode:this._pushMode,error_msg:o.message,error_code:o.code}),D(x.START_PUSH_STATUS,{is_success:!1,reason:Dt.PushError,error_message:o.message,session_id:this._pushSessionId,push_mode:this._pushMode,push_url:this._pushUrl}),this.unpublish()},this._executeReconnect=()=>{var o;(o=this._reconnectStrategy)==null||o.execute(),this.setConnectState(pe.RECONNECTING),this.unpublish({isReconnecting:!0})},this._OnRtcStateChange=o=>{var d;switch(D(x.PUSH_RTC_STATE_CHANGE,{state:o,push_url:this._pushUrl,session_id:this._pushSessionId,push_mode:this._pushMode}),this._streamConsumeController.emit(W.RTCConnectStateChanged,o),o){case"connected":this.setConnectState(pe.CONNECTED);break;case"disconnected":this._reconnectStrategy&&this._executeReconnect();break;case"failed":(d=this._reconnectStrategy)!=null&&d.isActive()?this._executeReconnect():(this.connectionState===pe.CONNECTED?D(x.STOP_PUSH_STREAM,{reason:fr.PushError,error_message:"peerconnection failed",duration:this.pushDuration,session_id:this._pushSessionId,push_mode:this._pushMode}):D(x.START_PUSH_STATUS,{is_success:!1,reason:Dt.PushError,error_message:"peerconnection failed",session_id:this._pushSessionId,push_mode:this._pushMode,push_url:this._pushUrl}),this.unpublish(),this._streamConsumeController.emit(W.PushError,new yt(de.PUSH_CONNECT_FAILED,"pc failed")));break}},this._pushMode=(t==null?void 0:t.mode)||"rtm",this._streamConsumeController=i,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*to:void 0;this._reconnectStrategy=new w_(this,o),this._reconnectStrategy.onReconnectError=this.handleReconnectError}this._streamComposedController=n}get isPushing(){return this._connectionState===pe.CONNECTED||this._connectionState===pe.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(W.LiveConnectStateChange,e),e){case pe.CONNECTED:(t=this._reconnectStrategy)!=null&&t.isActive()?this._reconnectStrategy.stop({isSuccess:!0}):(this._streamConsumeController.emit(W.PushStart),this.setPushStatsInterval(),D(x.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(),D(x.START_PUSH,{push_url:e,session_id:this._pushSessionId})),!e)throw D(x.START_PUSH_STATUS,{is_success:!1,session_id:this._pushSessionId,reason:Dt.PushCheck,push_url:this._pushUrl}),new Error("lack publish url");if(this._connect)return;this.start(),this._pushUrl=Sa({pushUrl:e,disableTCC:!0}),this._pushEncodeConfig=t.cfg;const i=this._composedStream.videoTrack,n=this._composedStream.audioTrack;if(this._needCheckAudioTrack&&(!i||!n)){D(x.START_PUSH_STATUS,{is_success:!1,reason:Dt.PushCheck,push_url:this._pushUrl,error_message:"lack videoTrack or audioTrack",video_track_id:i==null?void 0:i.id,audio_track_id:n==null?void 0:n.id,video_track_name:i==null?void 0:i.label,audio_track_name:n==null?void 0:n.label,push_mode:this._pushMode,session_id:this._pushSessionId}),console.warn("lack videoTrack or audioTrack","videoTrack: ",i==null?void 0:i.id,"audioTrack: ",n==null?void 0:n.id);return}else if(!i&&!n){D(x.START_PUSH_STATUS,{is_success:!1,reason:Dt.PushCheck,push_url:this._pushUrl,error_message:"lack videoTrack and audioTrack",push_mode:this._pushMode,session_id:this._pushSessionId});return}let s;this._pushMode==="rtm"?s=new __(this._pushUrl,this._pushConfig,this._OnRtcStateChange):s=new C_(e,this._pushConfig,this._OnRTMPError,this._OnRTMPSuccess),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(pe.CONNECTING),await s.publish([n,i],[this._audioBitrate,this._videoBitrate],{cfg:t.cfg,isReconnect:t.isReconnect}),t.isReconnect||(Ea.log("startPush begin"),this._connectionStartDate=Date.now())}catch(c){const u=new yt(de.PUBLISH_FAILED,c.message,c);if(Ea.groupEnd(),(d=this._reconnectStrategy)!=null&&d.isActive())throw this.unpublish({isReconnecting:!0}),u;this._streamConsumeController.emit(W.PushError,u),D(x.STOP_PUSH_STREAM,{reason:fr.PushError,error_message:u.message,enable_reconnect:!1,push_mode:this._pushMode,session_id:this._pushSessionId,duration:this.pushDuration}),D(x.START_PUSH_STATUS,{is_success:!1,push_url:this._pushUrl,reason:Dt.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,i,n,s;if((t=this._connect)!=null&&t.isPushing){const a=Date.now(),{stats:o,originStats:d}=await this._connect.getStatsSnapshoot(2e3),u=Date.now()-a;Ap(o)?this._prevStats=void 0:this._prevStats=o;const l=this.pushMode==="rtm"?u_(o,d,{idealFrameRate:(i=this._composedStream._videoStream)==null?void 0:i.frameRate,idealBitrate:this._videoBitrate}):d_(o),h=this.pushMode==="rtm"?(n=this._connect)==null?void 0:n.videoSenderTrackStats:{};D(x.PUSH_STATS,{...l,...h,video_draw_frame:this._streamComposedController.getCompositionDrawCountPerSecond(),stats:o,push_url:this._pushUrl,push_mode:this._pushMode,session_id:this._pushSessionId,duration:l.video_duration||u,video_duration:l.video_duration||u,is_push:!0},!0)}else await Wr(2e3),D(x.PUSH_STATS,{push_url:this._pushUrl,push_mode:this._pushMode,session_id:this._pushSessionId,duration:2e3,is_push:!1,is_reconnecting:((s=this._reconnectStrategy)==null?void 0:s.isActive())??!1},!0);this.connectionState!==pe.DISCONNECTED&&(this._statsLoopTimer=window.setTimeout(e,0))};e()}async reconnect(e){if(this.pushMode==="rtm")return this.startPush(e,{isReconnect:!0})}async updatePush({videoTrack:e,audioTrack:t}){if(this._connect)try{const i=[];e&&i.push(()=>{var n;return(n=this._connect)==null?void 0:n.updatePublish(e,"video")}),t&&i.push(()=>{var n;return(n=this._connect)==null?void 0:n.updatePublish(t,"audio")}),await Promise.all(i.map(n=>n()))}catch(i){const n=new yt(de.UPDATE_PUBLISH_FAILED,`${i.name}, code:${i.code}`);this._streamConsumeController.emit(W.PushError,n)}}unpublish(e={isReconnecting:!1,isManual:!1}){var t,i,n,s,a;(t=this._connect)==null||t.unpublish(),this._connect=null,e.isManual&&(D(x.STOP_PUSH_STREAM,{reason:fr.ManualStop,duration:this.pushDuration,session_id:this._streamConsumeController.pushSessionId,push_mode:this._pushMode,reconnect_times:(i=this._reconnectStrategy)==null?void 0:i.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._prevStats=void 0,this._isReportStart=!1,this._pushEncodeConfig=void 0,this._pushUrl=void 0,this._connectionStartDate=void 0,this._pushSessionId=0,this.setConnectState(pe.DISCONNECTED),(a=this._reconnectStrategy)==null||a.stop({quiet:!0}),this._streamConsumeController.emit(W.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,i){var n;t==="video"?this._videoBitrate=e:this._audioBitrate=e,(n=this._connect)==null||n.applyBitrate(e,t,i)}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:i}){D(x.PUSH_RECONNECT_STATUS,{status:e,...t,...i}),this._streamConsumeController.emit(W.ReconnectStateChange,e,t)}}class z_ extends Ve{constructor(e,t){super(),this._previewConsumer=new e_(e.getComposedStream(),{streamConsumeController:this}),this._pushConsumer=new T_(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,i){this._pushConsumer.setBitrate(e,t,i)}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()}}const k_=()=>typeof window>"u",Re={},Xr=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 Ca(r){const e=r.split(`
69
- `);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 n=!1;const s=[/miuibrowser/,/70.*HeyTapBrowser/i];for(const a of s)a.test(i)&&(n=!0);return!n}return!1}const R_=async()=>{let r=await Xr("sendonly");return navigator.userAgent.includes("VivoBrowser")&&(r=await Xr("sendonly")),Re.h264encode=Ca(r),Re.vp8encode=r.indexOf("vp8")>-1,Re},A_=async()=>{let r=await Xr("recvonly");return navigator.userAgent.includes("VivoBrowser")&&(r=await Xr("recvonly")),Re.h264decode=Ca(r),Re.vp8decode=r.indexOf("vp8")>-1,Re},D_=async()=>{if(typeof Re.h264encode>"u")try{await R_()}catch{return!1}return Re.h264encode||!1},x_=async()=>{if(typeof Re.h264decode>"u")try{await A_()}catch{return!1}return Re.h264decode||!1};class P_{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=>{},this.onLiveConnectStateChange=e=>{},this.onReconnectStateChange=(e,t)=>{}}}const I_=new P_;let wa=!0,Ta=!0;function Yr(r,e,t){const i=r.match(e);return i&&i.length>=t&&parseInt(i[t],10)}function pt(r,e,t){if(!r.RTCPeerConnection)return;const i=r.RTCPeerConnection.prototype,n=i.addEventListener;i.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=i.removeEventListener;i.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(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 O_(r){return typeof r!="boolean"?new Error("Argument type: "+typeof r+". Please use a boolean."):(wa=r,r?"adapter.js logging disabled":"adapter.js logging enabled")}function M_(r){return typeof r!="boolean"?new Error("Argument type: "+typeof r+". Please use a boolean."):(Ta=!r,"adapter.js deprecation warnings "+(r?"disabled":"enabled"))}function za(){if(typeof window=="object"){if(wa)return;typeof console<"u"&&typeof console.log=="function"&&console.log.apply(console,arguments)}}function En(r,e){Ta&&console.warn(r+" is deprecated, please use "+e+" instead.")}function L_(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(n=>n.brand==="Chromium");if(i)return{browser:"chrome",version:parseInt(i.version,10)}}if(t.mozGetUserMedia)e.browser="firefox",e.version=Yr(t.userAgent,/Firefox\/(\d+)\./,1);else if(t.webkitGetUserMedia||r.isSecureContext===!1&&r.webkitRTCPeerConnection)e.browser="chrome",e.version=Yr(t.userAgent,/Chrom(e|ium)\/(\d+)\./,2);else if(r.RTCPeerConnection&&t.userAgent.match(/AppleWebKit\/(\d+)\./))e.browser="safari",e.version=Yr(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 ka(r){return Object.prototype.toString.call(r)==="[object Object]"}function Ra(r){return ka(r)?Object.keys(r).reduce(function(e,t){const i=ka(r[t]),n=i?Ra(r[t]):r[t],s=i&&!Object.keys(n).length;return n===void 0||s?e:Object.assign(e,{[t]:n})},{}):r}function Cn(r,e,t){!e||t.has(e.id)||(t.set(e.id,e),Object.keys(e).forEach(i=>{i.endsWith("Id")?Cn(r,r.get(e[i]),t):i.endsWith("Ids")&&e[i].forEach(n=>{Cn(r,r.get(n),t)})}))}function Aa(r,e,t){const i=t?"outbound-rtp":"inbound-rtp",n=new Map;if(e===null)return n;const s=[];return r.forEach(a=>{a.type==="track"&&a.trackIdentifier===e.id&&s.push(a)}),s.forEach(a=>{r.forEach(o=>{o.type===i&&o.trackId===a.id&&Cn(r,o,n)})}),n}const Da=za;function xa(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 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=i(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=i(o.video),Da("chrome: "+JSON.stringify(o)),d(o)})}o.video=i(o.video)}return Da("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 Pa(r){r.MediaStream=r.MediaStream||r.webkitMediaStream}function Ia(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",n=>{let s;r.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=[i.stream],this.dispatchEvent(a)}),i.stream.getTracks().forEach(n=>{let s;r.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=[i.stream],this.dispatchEvent(a)})},this.addEventListener("addstream",this._ontrackpoly)),e.apply(this,arguments)}}else pt(r,"track",e=>(e.transceiver||Object.defineProperty(e,"transceiver",{value:{receiver:e.receiver}}),e))}function Oa(r){if(typeof r=="object"&&r.RTCPeerConnection&&!("getSenders"in r.RTCPeerConnection.prototype)&&"createDTMFSender"in r.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(!r.RTCPeerConnection.prototype.getSenders){r.RTCPeerConnection.prototype.getSenders=function(){return this._senders=this._senders||[],this._senders.slice()};const n=r.RTCPeerConnection.prototype.addTrack;r.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=r.RTCPeerConnection.prototype.removeTrack;r.RTCPeerConnection.prototype.removeTrack=function(o){s.apply(this,arguments);const d=this._senders.indexOf(o);d!==-1&&this._senders.splice(d,1)}}const t=r.RTCPeerConnection.prototype.addStream;r.RTCPeerConnection.prototype.addStream=function(s){this._senders=this._senders||[],t.apply(this,[s]),s.getTracks().forEach(a=>{this._senders.push(e(this,a))})};const i=r.RTCPeerConnection.prototype.removeStream;r.RTCPeerConnection.prototype.removeStream=function(s){this._senders=this._senders||[],i.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 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(n=>n._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 Ma(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 s=t.apply(this,[]);return s.forEach(a=>a._pc=this),s});const i=r.RTCPeerConnection.prototype.addTrack;i&&(r.RTCPeerConnection.prototype.addTrack=function(){const s=i.apply(this,arguments);return s._pc=this,s}),r.RTCRtpSender.prototype.getStats=function(){const s=this;return this._pc.getStats().then(a=>Aa(a,s.track,!0))}}if(!("getStats"in r.RTCRtpReceiver.prototype)){const t=r.RTCPeerConnection.prototype.getReceivers;t&&(r.RTCPeerConnection.prototype.getReceivers=function(){const n=t.apply(this,[]);return n.forEach(s=>s._pc=this),n}),pt(r,"track",i=>(i.receiver._pc=i.srcElement,i)),r.RTCRtpReceiver.prototype.getStats=function(){const n=this;return this._pc.getStats().then(s=>Aa(s,n.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 n,s,a;return this.getSenders().forEach(o=>{o.track===i&&(n?a=!0:n=o)}),this.getReceivers().forEach(o=>(o.track===i&&(s?a=!0:s=o),o.track===i)),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 La(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 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=r.RTCPeerConnection.prototype.addStream;r.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 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 n=r.RTCPeerConnection.prototype.removeTrack;r.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 Ua(r,e){if(!r.RTCPeerConnection)return;if(r.RTCPeerConnection.prototype.addTrack&&e.version>=65)return La(r);const t=r.RTCPeerConnection.prototype.getLocalStreams;r.RTCPeerConnection.prototype.getLocalStreams=function(){const u=t.apply(this);return this._reverseStreams=this._reverseStreams||{},u.map(l=>this._reverseStreams[l.id])};const i=r.RTCPeerConnection.prototype.addStream;r.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 r.MediaStream(u.getTracks());this._streams[u.id]=l,this._reverseStreams[l.id]=u,u=l}i.apply(this,[u])};const n=r.RTCPeerConnection.prototype.removeStream;r.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]},r.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 r.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=r.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))}};r.RTCPeerConnection.prototype[c]=l[c]});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 d=Object.getOwnPropertyDescriptor(r.RTCPeerConnection.prototype,"localDescription");Object.defineProperty(r.RTCPeerConnection.prototype,"localDescription",{get(){const c=d.get.apply(this);return c.type===""?c:s(this,c)}}),r.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 wn(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],n={[t](){return arguments[0]=new(t==="addIceCandidate"?r.RTCIceCandidate:r.RTCSessionDescription)(arguments[0]),i.apply(this,arguments)}};r.RTCPeerConnection.prototype[t]=n[t]})}function Na(r,e){pt(r,"negotiationneeded",t=>{const i=t.target;if(!((e.version<72||i.getConfiguration&&i.getConfiguration().sdpSemantics==="plan-b")&&i.signalingState!=="stable"))return t})}const Ga=Object.freeze(Object.defineProperty({__proto__:null,fixNegotiationNeeded:Na,shimAddTrackRemoveTrack:Ua,shimAddTrackRemoveTrackWithNative:La,shimGetSendersWithDtmf:Oa,shimGetUserMedia:xa,shimMediaStream:Pa,shimOnTrack:Ia,shimPeerConnection:wn,shimSenderReceiverGetStats:Ma},Symbol.toStringTag,{value:"Module"}));function Ba(r,e){const t=r&&r.navigator,i=r&&r.MediaStreamTrack;if(t.getUserMedia=function(n,s,a){En("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)},i&&i.prototype.getSettings){const a=i.prototype.getSettings;i.prototype.getSettings=function(){const o=a.apply(this,arguments);return n(o,"mozAutoGainControl","autoGainControl"),n(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)),n(o,"autoGainControl","mozAutoGainControl"),n(o,"noiseSuppression","mozNoiseSuppression")),a.apply(this,[o])}}}}function U_(r,e){r.navigator.mediaDevices&&"getDisplayMedia"in r.navigator.mediaDevices||r.navigator.mediaDevices&&(r.navigator.mediaDevices.getDisplayMedia=function(i){if(!(i&&i.video)){const n=new DOMException("getDisplayMedia without video constraints is undefined");return n.name="NotFoundError",n.code=8,Promise.reject(n)}return i.video===!0?i.video={mediaSource:e}:i.video.mediaSource=e,r.navigator.mediaDevices.getUserMedia(i)})}function Va(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 Tn(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(n){const s=r.RTCPeerConnection.prototype[n],a={[n](){return arguments[0]=new(n==="addIceCandidate"?r.RTCIceCandidate:r.RTCSessionDescription)(arguments[0]),s.apply(this,arguments)}};r.RTCPeerConnection.prototype[n]=a[n]});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[s,a,o]=arguments;return i.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 Fa(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 n=e.apply(this,[]);return n.forEach(s=>s._pc=this),n});const t=r.RTCPeerConnection.prototype.addTrack;t&&(r.RTCPeerConnection.prototype.addTrack=function(){const n=t.apply(this,arguments);return n._pc=this,n}),r.RTCRtpSender.prototype.getStats=function(){return this.track?this._pc.getStats(this.track):Promise.resolve(new Map)}}function ja(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(n=>n._pc=this),i}),pt(r,"track",t=>(t.receiver._pc=t.srcElement,t)),r.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track)}}function Ha(r){!r.RTCPeerConnection||"removeStream"in r.RTCPeerConnection.prototype||(r.RTCPeerConnection.prototype.removeStream=function(t){En("removeStream","removeTrack"),this.getSenders().forEach(i=>{i.track&&t.getTracks().includes(i.track)&&this.removeTrack(i)})})}function $a(r){r.DataChannel&&!r.RTCDataChannel&&(r.RTCDataChannel=r.DataChannel)}function qa(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 n=i.length>0;n&&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 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=i,a.sendEncodings=i,this.setParametersPromises.push(a.setParameters(o).then(()=>{delete a.sendEncodings}).catch(()=>{delete a.sendEncodings})))}return s})}function Ka(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 Wa(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 Ja(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 Za=Object.freeze(Object.defineProperty({__proto__:null,shimAddTransceiver:qa,shimCreateAnswer:Ja,shimCreateOffer:Wa,shimGetDisplayMedia:U_,shimGetParameters:Ka,shimGetUserMedia:Ba,shimOnTrack:Va,shimPeerConnection:Tn,shimRTCDataChannel:$a,shimReceiverGetStats:ja,shimRemoveStream:Ha,shimSenderGetStats:Fa},Symbol.toStringTag,{value:"Module"}));function Xa(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(n=>e.call(this,n,i)),i.getVideoTracks().forEach(n=>e.call(this,n,i))},r.RTCPeerConnection.prototype.addTrack=function(i,...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 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 n=t.getTracks();this.getSenders().forEach(s=>{n.includes(s.track)&&this.removeTrack(s)})})}}function Ya(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(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=r.RTCPeerConnection.prototype.setRemoteDescription;r.RTCPeerConnection.prototype.setRemoteDescription=function(){const i=this;return this._onaddstreampoly||this.addEventListener("track",this._onaddstreampoly=function(n){n.streams.forEach(s=>{if(i._remoteStreams||(i._remoteStreams=[]),i._remoteStreams.indexOf(s)>=0)return;i._remoteStreams.push(s);const a=new Event("addstream");a.stream=s,i.dispatchEvent(a)})}),e.apply(i,arguments)}}}function Qa(r){if(typeof r!="object"||!r.RTCPeerConnection)return;const e=r.RTCPeerConnection.prototype,t=e.createOffer,i=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=i.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 ec(r){const e=r&&r.navigator;if(e.mediaDevices&&e.mediaDevices.getUserMedia){const t=e.mediaDevices,i=t.getUserMedia.bind(t);e.mediaDevices.getUserMedia=n=>i(tc(n))}!e.getUserMedia&&e.mediaDevices&&e.mediaDevices.getUserMedia&&(e.getUserMedia=(function(i,n,s){e.mediaDevices.getUserMedia(i).then(n,s)}).bind(e))}function tc(r){return r&&r.video!==void 0?Object.assign({},r,{video:Ra(r.video)}):r}function rc(r){if(!r.RTCPeerConnection)return;const e=r.RTCPeerConnection;r.RTCPeerConnection=function(i,n){if(i&&i.iceServers){const s=[];for(let a=0;a<i.iceServers.length;a++){let o=i.iceServers[a];o.urls===void 0&&o.url?(En("RTCIceServer.url","RTCIceServer.urls"),o=JSON.parse(JSON.stringify(o)),o.urls=o.url,delete o.url,s.push(o)):s.push(i.iceServers[a])}i.iceServers=s}return new e(i,n)},r.RTCPeerConnection.prototype=e.prototype,"generateCertificate"in e&&Object.defineProperty(r.RTCPeerConnection,"generateCertificate",{get(){return e.generateCertificate}})}function ic(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 nc(r){const e=r.RTCPeerConnection.prototype.createOffer;r.RTCPeerConnection.prototype.createOffer=function(i){if(i){typeof i.offerToReceiveAudio<"u"&&(i.offerToReceiveAudio=!!i.offerToReceiveAudio);const n=this.getTransceivers().find(a=>a.receiver.track.kind==="audio");i.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"):i.offerToReceiveAudio===!0&&!n&&this.addTransceiver("audio",{direction:"recvonly"}),typeof i.offerToReceiveVideo<"u"&&(i.offerToReceiveVideo=!!i.offerToReceiveVideo);const s=this.getTransceivers().find(a=>a.receiver.track.kind==="video");i.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"):i.offerToReceiveVideo===!0&&!s&&this.addTransceiver("video",{direction:"recvonly"})}return e.apply(this,arguments)}}function sc(r){typeof r!="object"||r.AudioContext||(r.AudioContext=r.webkitAudioContext)}const oc=Object.freeze(Object.defineProperty({__proto__:null,shimAudioContext:sc,shimCallbacksAPI:Qa,shimConstraints:tc,shimCreateOfferLegacy:nc,shimGetUserMedia:ec,shimLocalStreamsAPI:Xa,shimRTCIceServerUrls:rc,shimRemoteStreamsAPI:Ya,shimTrackEventTransceiver:ic},Symbol.toStringTag,{value:"Module"}));var zn={exports:{}},ac;function N_(){return ac||(ac=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(`
68
+ `},vn}var la;function o_(){if(la)return be;la=1;var r=n_(),e=s_(),t=gn();return be.grammar=t,be.write=e,be.parse=r.parse,be.parseParams=r.parseParams,be.parseFmtpConfig=r.parseFmtpConfig,be.parsePayloads=r.parsePayloads,be.parseRemoteCandidates=r.parseRemoteCandidates,be.parseImageAttributes=r.parseImageAttributes,be.parseSimulcastStreamList=r.parseSimulcastStreamList,be}var a_=o_();const At=ne(a_);function Wr(r){return new Promise(e=>{setTimeout(e,r)})}async function c_(r,e={},t=0){const i=new AbortController;let n=!1;e=Object.assign({},e,{signal:i.signal});const s=[fetch(r,e)];t&&s.push(new Promise((a,o)=>{setTimeout(()=>{n||(o({httpCode:0,message:"Timeout"}),i.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 pa(r,e={},t={}){const{timeout:i=0,retryDelay:n=0}=t;let{retryCount:s=0}=t;try{return await c_(r,e,i)}catch(a){if(s--,t.retryCount=s,s<0)throw a;return await Wr(n),await pa(r,e,t)}}const yn=-1;function ee(r,e){let t;return e.forEach(i=>{i.type===r&&(t=i)}),t}async function bn(r,e){const t={},i=await(r==null?void 0:r.getStats()),n=await(e==null?void 0:e.getStats());return i&&(t.audio={mediaSource:ee("media-source",i),codec:ee("codec",i),candidatePair:ee("candidate-pair",i),remoteCandidate:ee("remote-candidate",i),localCandidate:ee("local-candidate",i),track:ee("track",i),outboundRtp:ee("outbound-rtp",i),remoteInboundRtp:ee("remote-inbound-rtp",i),transport:ee("transport",i)}),n&&(t.video={mediaSource:ee("media-source",n),codec:ee("codec",n),candidatePair:ee("candidate-pair",n),remoteCandidate:ee("remote-candidate",n),localCandidate:ee("local-candidate",n),track:ee("track",n),outboundRtp:ee("outbound-rtp",n),remoteInboundRtp:ee("remote-inbound-rtp",n),transport:ee("transport",n)}),t}async function u_(r,e,t){var u,l,h,p,f,v,m,E,y,_,C,z,w,A,k,T,R,I,H,V,q,K,ae,j,te,Se,et,tt,mr,_r,gr,vr,_c,gc,vc,yc,bc,Sc,Ec;const i=await bn(e,t);await Wr(r);const n=await bn(e,t),{audio:s,video:a}=i,{audio:o,video:d}=n,c={};if(s!=null&&s.codec&&(o!=null&&o.codec)){const It=((u=o.outboundRtp)==null?void 0:u.timestamp)-((l=s.outboundRtp)==null?void 0:l.timestamp),Dn=((h=o.outboundRtp)==null?void 0:h.bytesSent)-((p=s.outboundRtp)==null?void 0:p.bytesSent),ni=((f=o.remoteInboundRtp)==null?void 0:f.packetsLost)-((v=s.remoteInboundRtp)==null?void 0:v.packetsLost),xn=((m=o.outboundRtp)==null?void 0:m.packetsSent)-((E=s.outboundRtp)==null?void 0:E.packetsSent),Pn=(((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:Dn/It*8e3,packetsSent:(C=o.outboundRtp)==null?void 0:C.packetsSent,nackCount:(z=o.outboundRtp)==null?void 0:z.nackCount,packetsLost:(w=o.remoteInboundRtp)==null?void 0:w.packetsLost,packetsLostPercent:ni/xn,deltaAudioEnergy:Pn}}if(a!=null&&a.codec&&(d!=null&&d.codec)){const It=((A=d.outboundRtp)==null?void 0:A.timestamp)-((k=a.outboundRtp)==null?void 0:k.timestamp),Dn=((T=d.outboundRtp)==null?void 0:T.bytesSent)-((R=a.outboundRtp)==null?void 0:R.bytesSent),ni=((I=d.outboundRtp)==null?void 0:I.framesEncoded)-((H=a.outboundRtp)==null?void 0:H.framesEncoded),xn=((V=d.outboundRtp)==null?void 0:V.totalEncodeTime)-((q=a.outboundRtp)==null?void 0:q.totalEncodeTime),Pn=((K=d.outboundRtp)==null?void 0:K.framesSent)-((ae=a.outboundRtp)==null?void 0:ae.framesSent),Cc=((j=d.outboundRtp)==null?void 0:j.packetsSent)-((te=a.outboundRtp)==null?void 0:te.packetsSent),K_=((Se=d.outboundRtp)==null?void 0:Se.totalPacketSendDelay)-((et=a.outboundRtp)==null?void 0:et.totalPacketSendDelay),W_=((tt=d.remoteInboundRtp)==null?void 0:tt.packetsLost)-((mr=a.remoteInboundRtp)==null?void 0:mr.packetsLost);c.video={codec:d.codec.mimeType,sendBitrate:Dn/It*8e3,frameWidth:(_r=d.outboundRtp)==null?void 0:_r.frameWidth,frameHeight:(gr=d.outboundRtp)==null?void 0:gr.frameHeight,framesPerSecond:Math.floor(Pn/It*1e3||0),framesEncoded:(vr=d.outboundRtp)==null?void 0:vr.framesEncoded,framesEncodedPerSecond:ni*1e3/It,keyFramesEncoded:(_c=d.outboundRtp)==null?void 0:_c.keyFramesEncoded,framesSent:(gc=d.outboundRtp)==null?void 0:gc.frameHeight,frameEncodeAvgTime:xn*1e3/ni,packetsSent:(vc=d.outboundRtp)==null?void 0:vc.packetsSent,packetSendDelay:K_*1e3/Cc,nackCount:(yc=d.outboundRtp)==null?void 0:yc.nackCount,firCount:(bc=d.outboundRtp)==null?void 0:bc.firCount,pliCount:(Sc=d.outboundRtp)==null?void 0:Sc.pliCount,packetsLost:(Ec=d.remoteInboundRtp)==null?void 0:Ec.packetsLost,packetsLostPercent:W_/Cc,deltaTime:It}}return{stats:c,originStats:{audio:o,video:d}}}function Z(r,e=yn){return r??e}function d_(r){var e,t,i,n,s,a,o,d,c,u,l,h,p,f,v,m,E,y,_,C,z,w,A,k,T,R,I,H,V,q,K,ae,j,te,Se,et,tt,mr,_r,gr,vr;return{audio_bytes:(e=r.outboundRtp)==null?void 0:e.bytesSent,audio_packets_sent:(t=r.outboundRtp)==null?void 0:t.packetsSent,audio_nack_count:(i=r.outboundRtp)==null?void 0:i.nackCount,audio_ssrc:(n=r.outboundRtp)==null?void 0:n.ssrc,audio_retransmitted_bytes_sent:(s=r.outboundRtp)==null?void 0:s.retransmittedBytesSent,audio_retransmitted_packets_sent:(a=r.outboundRtp)==null?void 0:a.retransmittedPacketsSent,audio_record_sample_rate:(o=r.codec)==null?void 0:o.clockRate,audio_num_channels:(d=r.codec)==null?void 0:d.channels,audio_level:(c=r.mediaSource)!=null&&c.audioLevel?-10*Math.log10(Math.pow((u=r.mediaSource)==null?void 0:u.audioLevel,2)):(l=r.mediaSource)==null?void 0:l.audioLevel,audio_volume:(h=r.mediaSource)!=null&&h.audioLevel?((p=r.mediaSource)==null?void 0:p.audioLevel)*255:(f=r.mediaSource)==null?void 0:f.audioLevel,audio_total_audio_energy:(v=r.mediaSource)==null?void 0:v.totalAudioEnergy,audio_total_input_duration:(m=r.mediaSource)==null?void 0:m.totalSamplesDuration,audio_send_level:(E=r.mediaSource)==null?void 0:E.audioLevel,audio_ice_available_outgoing_bitrate:(y=r.candidatePair)==null?void 0:y.availableOutgoingBitrate,audio_ice_bytes_received:(_=r.candidatePair)==null?void 0:_.bytesReceived,audio_ice_bytes_sent:(C=r.candidatePair)==null?void 0:C.bytesSent,audio_ice_nominated:(z=r.candidatePair)==null?void 0:z.nominated,audio_ice_pair_id:(w=r.candidatePair)==null?void 0:w.id,audio_ice_pair_rtt:(A=r.candidatePair)==null?void 0:A.currentRoundTripTime,audio_ice_pair_state:(k=r.candidatePair)==null?void 0:k.state,audio_ice_pair_writable:(T=r.candidatePair)==null?void 0:T.writable,audio_recv_ping_requests:(R=r.candidatePair)==null?void 0:R.requestsReceived,audio_recv_ping_responses:(I=r.candidatePair)==null?void 0:I.responsesReceived,audio_sent_ping_requests_before_first_response:(H=r.candidatePair)==null?void 0:H.requestsSent,audio_sent_ping_requests_total:(((V=r.candidatePair)==null?void 0:V.requestsSent)??0)+(((q=r.candidatePair)==null?void 0:q.consentRequestsSent)??0),audio_sent_ping_responses:(K=r.candidatePair)==null?void 0:K.responsesSent,audio_local_candidate_type:(ae=r.localCandidate)==null?void 0:ae.candidateType,audio_local_ip:((j=r.localCandidate)==null?void 0:j.ip)||((te=r.localCandidate)==null?void 0:te.address),audio_local_network_type:(Se=r.localCandidate)==null?void 0:Se.networkType,audio_local_port:(et=r.localCandidate)==null?void 0:et.port,audio_local_protocol:(tt=r.localCandidate)==null?void 0:tt.protocol,audio_remote_candidate_type:(mr=r.remoteCandidate)==null?void 0:mr.candidateType,audio_remote_ip:((_r=r.remoteCandidate)==null?void 0:_r.ip)||((gr=r.remoteCandidate)==null?void 0:gr.address),audio_remote_port:(vr=r.remoteCandidate)==null?void 0:vr.port}}function h_(r){var e,t,i,n,s,a,o,d,c,u,l,h,p,f,v,m,E,y,_,C,z,w,A,k,T,R,I,H,V,q,K,ae,j,te,Se,et,tt;return{video_qp_sum:(e=r.outboundRtp)==null?void 0:e.qpSum,video_pli_count:(t=r.outboundRtp)==null?void 0:t.pliCount,video_ssrc:(i=r.outboundRtp)==null?void 0:i.ssrc,video_quality_limitation_reason:(n=r.outboundRtp)==null?void 0:n.qualityLimitationReason,video_quality_limitation_durations:(s=r.outboundRtp)==null?void 0:s.qualityLimitationDurations,video_target_bitrate:(a=r.outboundRtp)==null?void 0:a.targetBitrate,video_rtt:(((o=r.remoteInboundRtp)==null?void 0:o.roundTripTime)||0)*1e3,video_jitter:(((d=r.remoteInboundRtp)==null?void 0:d.jitter)||0)*1e3,video_packets_lost:(c=r.remoteInboundRtp)==null?void 0:c.packetsLost,video_fraction_lost:(u=r.remoteInboundRtp)==null?void 0:u.fractionLost,video_ice_available_outgoing_bitrate:(l=r.candidatePair)==null?void 0:l.availableOutgoingBitrate,video_ice_bytes_received:(h=r.candidatePair)==null?void 0:h.bytesReceived,video_ice_bytes_sent:(p=r.candidatePair)==null?void 0:p.bytesSent,video_ice_nominated:(f=r.candidatePair)==null?void 0:f.nominated,video_ice_pair_id:(v=r.candidatePair)==null?void 0:v.id,video_ice_pair_rtt:(m=r.candidatePair)==null?void 0:m.currentRoundTripTime,video_ice_pair_state:(E=r.candidatePair)==null?void 0:E.state,video_ice_pair_writable:(y=r.candidatePair)==null?void 0:y.writable,video_recv_ping_requests:(_=r.candidatePair)==null?void 0:_.requestsReceived,video_recv_ping_responses:(C=r.candidatePair)==null?void 0:C.responsesReceived,video_sent_ping_requests_before_first_response:(z=r.candidatePair)==null?void 0:z.requestsSent,video_sent_ping_requests_total:(((w=r.candidatePair)==null?void 0:w.requestsSent)??0)+(((A=r.candidatePair)==null?void 0:A.consentRequestsSent)??0),video_sent_ping_responses:(k=r.candidatePair)==null?void 0:k.responsesSent,video_local_candidate_type:(T=r.localCandidate)==null?void 0:T.candidateType,video_local_ip:((R=r.localCandidate)==null?void 0:R.ip)||((I=r.localCandidate)==null?void 0:I.address),video_local_network_type:(H=r.localCandidate)==null?void 0:H.networkType,video_local_port:(V=r.localCandidate)==null?void 0:V.port,video_local_protocol:(q=r.localCandidate)==null?void 0:q.protocol,video_remote_candidate_type:(K=r.remoteCandidate)==null?void 0:K.candidateType,video_remote_ip:((ae=r.remoteCandidate)==null?void 0:ae.ip)||((j=r.remoteCandidate)==null?void 0:j.address),video_remote_port:(te=r.remoteCandidate)==null?void 0:te.port,video_input_frame_rate:(Se=r.mediaSource)==null?void 0:Se.framesPerSecond,video_input_frame_width:(et=r.mediaSource)==null?void 0:et.width,video_input_frame_height:(tt=r.mediaSource)==null?void 0:tt.height}}function l_(r,e,t){var c,u,l,h,p,f,v,m,E,y,_,C,z,w,A,k,T,R,I,H,V,q,K,ae,j,te,Se;const i=h_(e.video??{}),{video_input_frame_width:n,video_input_frame_height:s}=i,a=Z((c=r.video)==null?void 0:c.frameWidth),o=Z((u=r.video)==null?void 0:u.frameHeight),d=a<Number(n)||o<Number(s);return{...i,video_send_k_bitrate:Z((l=r.video)==null?void 0:l.sendBitrate)/1e3,video_send_frame_rate:Z((h=r.video)==null?void 0:h.framesPerSecond),video_encode_avg_time:Z((p=r.video)==null?void 0:p.frameEncodeAvgTime),video_encoder_output_frame_rate:Z((f=r.video)==null?void 0:f.framesEncodedPerSecond),video_encoded_frame_width:Z((v=r.video)==null?void 0:v.frameWidth),video_encoded_frame_height:Z((m=r.video)==null?void 0:m.frameHeight),video_encoded_key_frames:Z((E=r.video)==null?void 0:E.keyFramesEncoded),video_delta_time:Z((y=r.video)==null?void 0:y.deltaTime,2e3),video_packets_sent:Z((_=r.video)==null?void 0:_.packetsSent),video_nack_count:Z((C=r.video)==null?void 0:C.nackCount),video_fir_count:Z((z=r.video)==null?void 0:z.firCount),video_pli_count:Z((w=r.video)==null?void 0:w.pliCount),video_packets_lost:Z((A=r.video)==null?void 0:A.packetsLost),video_packets_lost_percent:(k=r.video)==null?void 0:k.packetsLostPercent,video_codec:(T=r.video)==null?void 0:T.codec,video_duration:(R=r.video)==null?void 0:R.deltaTime,video_frame_rate_compliance:t!=null&&t.idealFrameRate?Math.min(Z((I=r.video)==null?void 0:I.framesPerSecond)/t.idealFrameRate,1)*100:yn,video_bitrate_compliance:t!=null&&t.idealBitrate?Math.min(Z((H=r.video)==null?void 0:H.sendBitrate)/t.idealBitrate,1)*100:yn,video_resolution_downgrade:d,...d_(e.audio??{}),audio_send_k_bitrate:Z((V=r.audio)==null?void 0:V.sendBitrate)/1e3,audio_send_channels:Z((q=r.audio)==null?void 0:q.channels),audio_packets_sent:Z((K=r.audio)==null?void 0:K.packetsSent),audio_packets_lost:Z((ae=r.audio)==null?void 0:ae.packetsLost),audio_packets_lost_percent:(j=r.audio)==null?void 0:j.packetsLostPercent,audio_codec:(te=r.audio)==null?void 0:te.codec,audio_delta_energy:(Se=r.audio)==null?void 0:Se.deltaAudioEnergy}}function p_(r){return{video_send_k_bitrate:r.video.sendBitrate/1e3,video_send_frame_rate:r.video.framesPerSecond,video_encoded_frame_width:r.video.frameWidth,video_encoded_frame_height:r.video.frameHeight,video_encoded_key_frames:r.video.keyFramesEncoded,video_send_speed:r.video.sendSpeed/1e3,video_gop_size:r.video.gopSize,video_codec:r.video.codec,video_duration:0,audio_send_k_bitrate:r.audio.sendBitrate/1e3,audio_codec:r.audio.codec,audio_send_channels:r.audio.channels,audio_send_sample_rate:r.audio.sampleRate}}const f_="42001f",m_="42e01f",__=r=>{var t;if(!Wn)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")})},g_=r=>{r.ext&&(Oc||yr)&&(r.ext=r.ext.filter(e=>{var t;return!((t=e.uri)!=null&&t.includes("video-orientation"))}))};function v_(r,e){r==null||r.rtp.forEach(({codec:t,payload:i})=>{if(["vp8","h264"].includes(t.toLocaleLowerCase())){const n=r.fmtp.find(s=>s.payload===i);n?n.config=[...n.config.split(";"),`x-google-min-bitrate=${e*.4}`,`x-google-start-bitrate=${e}`].join(";"):r.fmtp.push({payload:i,config:`x-google-min-bitrate=${e*.4};x-google-start-bitrate=${e}`})}})}function fa(r,e){if(!Array.isArray(r.fmtp)||!Array.isArray(r.rtp))return;const t=r.fmtp.find(a=>a.config&&a.config.includes(f_)),i=r.fmtp.find(a=>a.config&&a.config.includes(m_));if(!t||!i)return;const n=r.rtp.findIndex(a=>a.payload===t.payload),s=r.rtp.findIndex(a=>a.payload===i.payload);if(n!==-1&&s!==-1){if(e==="hardware"){if(s<n){const a=r.rtp[s];r.rtp[s]=r.rtp[n],r.rtp[n]=a}}else if(n<s){const a=r.rtp[n];r.rtp[n]=r.rtp[s],r.rtp[s]=a}}r.payloads=r.rtp.map(a=>a.payload).join(" ")}const oe=new Ze("PCConnect");class y_{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,n;return!!((t=(e=this._videoTransceiver)==null?void 0:e.sender)!=null&&t.track||(n=(i=this._audioTransceiver)==null?void 0:i.sender)!=null&&n.track)}get videoSenderTrackStats(){var e,t,i,n;return{track_enabled:(t=(e=this._videoTransceiver)==null?void 0:e.sender.track)==null?void 0:t.enabled,track_muted:(n=(i=this._videoTransceiver)==null?void 0:i.sender.track)==null?void 0:n.muted}}get pushUrl(){return this._signalUrl}get sessionId(){return this._sessionId}async publish(e,t,i){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]}),oe.log("add track to pc,",s),this._videoTransceiver=n.addTransceiver(a||"video",{direction:"sendonly",sendEncodings:[{maxBitrate:t[1]}],streams:[this._ms]}),oe.log("add track to pc,",a);const o=await n.createOffer();oe.groupCollapsed("local offer"),oe.log(o.sdp);const d=At.parse(o.sdp);d.media.forEach(h=>{h.type==="audio"?__(h):h.type==="video"&&(g_(h),fa(h,"software"),v_(h,t[1]))}),o.sdp=At.write(d),oe.log("local offer modified"),oe.log(o.sdp),await n.setLocalDescription(o);const c=await pa(this._signalUrl,{method:"POST",mode:"cors",body:JSON.stringify({sessionId:""+this._sessionId,version:"1.0-html",localSdp:o,metadata:{platform:"Web"}})},{...this._opts,timeout:i!=null&&i.isReconnect?10*to:(l=this._opts)==null?void 0:l.timeout});if((c==null?void 0:c.code)!==200)throw{code:c.code,message:c.message};oe.log("remote answer:"),oe.log(c.remoteSdp.sdp);const u=At.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=At.write(u),oe.log("remote answer modified"),oe.log(c.remoteSdp.sdp),oe.groupEnd(),n.connectionState==="closed"){oe.log("PeerConnection is closed, skipping setRemoteDescription");return}x(D.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,i=(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(i&&n){const o=At.parse(n);o.media.forEach(d=>{d.type==="video"&&fa(d,e)}),t.setLocalDescription(t.localDescription),t.setRemoteDescription({type:"answer",sdp:At.write(o)})}}async updatePublish(e,t){var s,a;let i;t==="video"?i=this._videoTransceiver:i=this._audioTransceiver;const n=(s=i==null?void 0:i.sender)==null?void 0:s.track;(n==null?void 0:n.id)!==(e==null?void 0:e.id)&&(await((a=i==null?void 0:i.sender)==null?void 0:a.replaceTrack(e)),oe.log(`replace ${t} track done! ${n==null?void 0:n.label} -> ${e==null?void 0:e.label}`))}applyBitrate(e,t,i){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:[{}],i?s.encodings[0].minBitrate=e:s.encodings[0].maxBitrate=e,n.setParameters(s),oe.log(`set bitrate for ${t}, ${e} bps, min:${i}`)}unpublish(){var e,t;(e=this._pc)==null||e.getSenders().forEach(i=>{var n;(n=this._pc)==null||n.removeTrack(i)}),(t=this._pc)==null||t.close(),this._audioTransceiver=null,this._videoTransceiver=null,this._pc=null,oe.log("close pc!")}getStats(){var e,t;return bn((e=this._audioTransceiver)==null?void 0:e.sender,(t=this._videoTransceiver)==null?void 0:t.sender)}getStatsSnapshoot(e){var t,i;return u_(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",()=>{oe.log("onconnectionstatechange:",e.connectionState),this._onConnectStateChange(e.connectionState)})}}var Xe=(r=>(r.OnError="onerror",r.OnConnectClosed="onconnectclosed",r.OnFirstFramePushed="onfirstframepushed",r))(Xe||{}),Ye=(r=>(r.Video="video",r.Audio="audio",r))(Ye||{}),ge=(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))(ge||{}),lt=(r=>(r.Ready="ready",r.Error="error",r.FirstFramePushed="firstframepushed",r.Flvfile="flvfile",r.STATS="stats",r.Close="close",r))(lt||{}),Sn={exports:{}},ma;function b_(){return ma||(ma=1,function(r){var e=Object.prototype.hasOwnProperty,t="~";function i(){}Object.create&&(i.prototype=Object.create(null),new i().__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 i:delete d._events[c]}function o(){this._events=new i,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],E=arguments.length,y,_;if(m.fn){switch(m.once&&this.removeListener(c,m.fn,void 0,!0),E){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(E-1);_<E;_++)y[_-1]=arguments[_];m.fn.apply(m.context,y)}else{var C=m.length,z;for(_=0;_<C;_++)switch(m[_].once&&this.removeListener(c,m[_].fn,void 0,!0),E){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(E-1);z<E;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=[],E=f.length;v<E;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 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}(Sn)),Sn.exports}var S_=b_();const E_=ne(S_);var Jr=(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))(Jr||{});class _a 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 ga(r,e,t){return new _a(r,e,t)}const Pt=class Pt{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 Pt.enable}get _enableLong(){return Pt.enableLong}get long(){return this._enableLong}};Pt.enable=!1,Pt.enableLong=!1;let Qe=Pt;const ve=new Qe("RTMP_Capture");class C_{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(ve.log(`replace ${e} track`),e===Ye.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){ve.log("no video track to capture");return}if(this.videoTrack.readyState!=="live"){ve.warn("video track not live");return}const e=new MediaStreamTrackProcessor(this.videoTrack);e.track=this.videoTrack;const t=e.readable.getReader();this._videoProcessorReader=t,ve.log("start capture video frame",this.videoTrack);let i;for(;;){i&&clearInterval(i),i=setTimeout(()=>{ve.warn("long time no capture output"),this._bridge._postMockVideoEncodeFlag()},1500);const s=await t.read();if(clearInterval(i),this._videoFirstframeCaptured||(this._videoFirstframeCaptured=!0,ve.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(i),this._videoFirstframeCaptured=!1,this._videoProcessorReader=null,ve.log("video track read done!",e.track)}async _startAudioCapture(){if(!this.audioTrack){ve.log("no audio track to capture");return}if(this.audioTrack.readyState!=="live"){ve.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,ve.log("start capture audio frame");;){const i=await t.read();if(this._audioFirstframeCaptured||(this._audioFirstframeCaptured=!0,ve.log("audio first frame captured")),i.done||!i.value)break;this._bridge._postAudioFrame(i.value,this.audioTrack.getSettings())}this._audioFirstframeCaptured=!1,this._audioProcessorReader=null,ve.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 va='(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,N,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,N=new Array(C-1);p<C;p++)N[p-1]=arguments[p];d.fn.apply(d.context,N)}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(!N)for(R=1,N=new Array(C-1);R<C;R++)N[R-1]=arguments[R];d[p].fn.apply(d[p].context,N)}}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 x=class x{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 x.enable}get _enableLong(){return x.enableLong}get long(){return this._enableLong}};x.enable=!1,x.enableLong=!1;let E=x;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 L=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){L.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(),L.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),L.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,L.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);L.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 B=(i=>(i[i.AUDIO=8]="AUDIO",i[i.VIDEO=9]="VIDEO",i[i.SCRIPT_DATA=18]="SCRIPT_DATA",i))(B||{});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(B.VIDEO,s);this._core.emit(l.OnPacketed,c)}if(o.hasAudio){const c=this._flv.genSeqTag(B.AUDIO,s);this._core.emit(l.OnPacketed,c)}this._firstFrame=!1,ae.log("first frame encoded & packed")}const r=this._flv.genFrameTag(e==="video"?B.VIDEO:B.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.videoBitrate}`),this._core.emit(l.OnUpstreamFeedback,{videoBitrate:t.videoBitrate,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,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}),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}),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',ya=typeof self<"u"&&self.Blob&&new Blob([va],{type:"text/javascript;charset=utf-8"});function w_(r){let e;try{if(e=ya&&(self.URL||self.webkitURL).createObjectURL(ya),!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(va),{name:r==null?void 0:r.name})}finally{e&&(self.URL||self.webkitURL).revokeObjectURL(e)}}try{Qe.enable=location.href.indexOf("rtmpdebug")!==-1,Qe.enableLong=location.href.indexOf("rtmpdebug=long")!==-1}catch{}const Zr=new Qe("Bridge");class ba extends E_{constructor(){super(),this._worker=null,this._audioMsTrack=null,this._videoMsTrack=null,this._capture=new C_(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 i=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 lt.Error:t(o.data.data);break;default:this._bindWorkerEvent(),Zr.log("rtmp ready!"),e(!0)}};try{this._worker=new w_}catch(o){t(ga(Jr.RTMP_INIT_FAIL,o.message))}return(s=this._worker)==null||s.postMessage({type:ge.Init,options:{logEnable:Qe.enable,logEnableLong:Qe.enableLong}}),(a=this._worker)==null||a.addEventListener("message",n),i}_bindWorkerEvent(){var e,t;(e=this._worker)==null||e.addEventListener("message",i=>{switch(i.data.type){case lt.Error:Zr.table(i.data.data),this.emit(Xe.OnError,i.data.data);break;case lt.Flvfile:T_(i.data.buffer);break;case lt.FirstFramePushed:this.emit(Xe.OnFirstFramePushed);break;case lt.Close:this.emit(Xe.OnConnectClosed),this.destroy();break}}),(t=this._worker)==null||t.addEventListener("error",i=>{this.emit(Xe.OnError,ga(Jr.WORKER_ERROR,i.message))})}addTrack(e){e.kind===Ye.Video&&(this._videoMsTrack=e),e.kind===Ye.Audio&&(this._audioMsTrack=e),this._setAVExist(!!this._videoMsTrack,!!this._audioMsTrack)}replaceTrack(e,t){e===Ye.Video&&(this._videoMsTrack=t),e===Ye.Audio&&(this._audioMsTrack=t),this._setAVExist(!!this._videoMsTrack,!!this._audioMsTrack),this._capture.restartCapture(e)}async getStats(){var s,a;let e,t;const i=new Promise((o,d)=>{e=o,t=d});this._worker||setTimeout(()=>{t()},0);const n=o=>{var d;switch(o.data.type){case lt.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:ge.GetStats}),i}_postVideoFrame(e,t){var i;(i=this._worker)==null||i.postMessage({type:ge.VideoFrame,frame:e,setting:t},[e])}_postMockVideoEncodeFlag(){var e;(e=this._worker)==null||e.postMessage({type:ge.MockVideoEncode})}_setAVExist(e,t){var i;(i=this._worker)==null||i.postMessage({type:ge.AvExist,hasVideo:e,hasAudio:t})}_postAudioFrame(e,t){var i;(i=this._worker)==null||i.postMessage({type:ge.AudioFrame,frame:e,setting:t},[e])}setEncodeCapacity(e){var t;(t=this._worker)==null||t.postMessage({type:ge.EncodeConfig,cfg:e})}adjustBitrate(e,t){var i;(i=this._worker)==null||i.postMessage({type:ge.AdjustBitrate,kind:e,bitrate:t})}publish(e){var t;Zr.log("start capture & connect"),this._capture.start(),(t=this._worker)==null||t.postMessage({type:ge.Publish,url:e})}unpublish(){var e;this._capture.destroy(),(e=this._worker)==null||e.postMessage({type:ge.UnPublish})}destroy(){var e;Zr.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:ge.Download})}}function T_(r){const e=document.createElement("a");e.href=URL.createObjectURL(new Blob([r])),e.download=Date.now()+".flv",e.click()}const Sa=new Ze("RTMPConnect");class z_{constructor(e,t,i,n){this._opts=void 0,this._isPushing=!1,this._url=e,this._opts=t,this._onError=i,this._OnSuccess=n,this._rtmp=new ba,this._bindEvents()}get isPushing(){return this._isPushing}get pushUrl(){return this._url}get sessionId(){return 0}_bindEvents(){this._rtmp.on(Xe.OnError,e=>{this._isPushing=!1,this._onError(e)}),this._rtmp.on(Xe.OnConnectClosed,()=>{this._isPushing=!1,this._onError(new _a(Jr.WTP_CONNECT_FAIL,"connect lost"))}),this._rtmp.on(Xe.OnFirstFramePushed,()=>{this._isPushing=!0,this._OnSuccess()})}async publish(e,t,i){await this._rtmp.ready(),i!=null&&i.cfg&&this._rtmp.setEncodeCapacity(i.cfg),e.filter(Boolean).forEach(n=>this._rtmp.addTrack(n)),t[0]&&this._rtmp.adjustBitrate(Ye.Audio,t[0]),t[1]&&this._rtmp.adjustBitrate(Ye.Video,t[1]),this._rtmp.publish(this._url)}updatePublish(e,t){Sa.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 Wr(e),{stats:await this._rtmp.getStats(),originStats:void 0}}unpublish(){Sa.warn("unpublish"),this._rtmp.unpublish(),this._isPushing=!1}}function Ea({pushUrl:r,addPri:e=!1,disableTCC:t=!1}){const i=new URL(r),n=Date.now();return e&&i.searchParams.set("pri",n.toString()),t&&i.searchParams.set("tcc","false"),i.href}class k_{constructor(e,t=Bp){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=(i=!1)=>{var n;this._logger.log("start reconnect strategy"),this.state==="idle"&&(this._reconnectStartTime=Date.now(),this._totalReconnectInfo.totalReconnectCount+=1,x(D.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:ft.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(i))},this.attemptReconnect=async()=>{var i;if(this.state==="executing"){this.setStrategyState("reconnecting"),this._reconnectCount+=1;const n=this.getNextPushUrl();try{if(this._pushConsumer.emitReconnectStateChange({state:ft.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:oi.PushUrlInvalid,failedError:s}),(i=this._onReconnectError)==null||i.call(this,"pushError",s);else{if(!this.isActive())return;this.setStrategyState("executing"),this.execute()}}}},this.executeStrategy=(i=!1)=>{const n=i?0:this._reconnectDelay;this._pushConsumer.emitReconnectStateChange({state:ft.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,Vp)},this.state="idle",this._pushConsumer=e,this._maxTimeout=t,this._logger=new Ze("ReconnectStrategy")}getNextPushUrl(){const e=this._pushConsumer.pushUrl;return e?Ea({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:i=!1,failedError:n}){var a;if(this.state==="idle")return;const s=(Date.now()-this._reconnectStartTime)/1e3;i||(e?this._pushConsumer.emitReconnectStateChange({state:ft.SUCCESS,teaParams:{reconnect_duration:s,session_id:this._pushConsumer.pushSessionId}}):(this._logger.log("Reconnect strategy stopped: ",t),this._pushConsumer.emitReconnectStateChange({state:ft.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:oi.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 fr={ManualStop:0,ReconnectFailed:1,StartPushError:2,PushError:3},Dt={PushCheck:0,PushError:1},Ca=new Ze("PushController");class R_ extends ca{constructor(e,{config:t,streamConsumeController:i,streamComposedController:n}){var s,a;if(super(e),this._connect=null,this._connectionState=pe.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=bt(Vn,"audio").bitrate,this._videoBitrate=bt(Bn,"video").bitrate,this.handleReconnectError=(o,d)=>{var c,u;x(D.STOP_PUSH_STREAM,{reason:fr.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(pe.CONNECTED)},this._OnRTMPError=o=>{const d=new yt(de.PUBLISH_FAILED,`code:${o.code}, message: ${o.message}`);this._streamConsumeController.emit(W.PushError,d),x(D.STOP_PUSH_STREAM,{reason:fr.PushError,duration:this.pushDuration,session_id:this._pushSessionId,push_mode:this._pushMode,error_msg:o.message,error_code:o.code}),x(D.START_PUSH_STATUS,{is_success:!1,reason:Dt.PushError,error_message:o.message,session_id:this._pushSessionId,push_mode:this._pushMode,push_url:this._pushUrl}),this.unpublish()},this._executeReconnect=()=>{var o;(o=this._reconnectStrategy)==null||o.execute(),this.setConnectState(pe.RECONNECTING),this.unpublish({isReconnecting:!0})},this._OnRtcStateChange=o=>{var d;switch(x(D.PUSH_RTC_STATE_CHANGE,{state:o,push_url:this._pushUrl,session_id:this._pushSessionId,push_mode:this._pushMode}),this._streamConsumeController.emit(W.RTCConnectStateChanged,o),o){case"connected":this.setConnectState(pe.CONNECTED);break;case"disconnected":this._reconnectStrategy&&this._executeReconnect();break;case"failed":(d=this._reconnectStrategy)!=null&&d.isActive()?this._executeReconnect():(this.connectionState===pe.CONNECTED?x(D.STOP_PUSH_STREAM,{reason:fr.PushError,error_message:"peerconnection failed",duration:this.pushDuration,session_id:this._pushSessionId,push_mode:this._pushMode}):x(D.START_PUSH_STATUS,{is_success:!1,reason:Dt.PushError,error_message:"peerconnection failed",session_id:this._pushSessionId,push_mode:this._pushMode,push_url:this._pushUrl}),this.unpublish(),this._streamConsumeController.emit(W.PushError,new yt(de.PUSH_CONNECT_FAILED,"pc failed")));break}},this._pushMode=(t==null?void 0:t.mode)||"rtm",this._streamConsumeController=i,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*to:void 0;this._reconnectStrategy=new k_(this,o),this._reconnectStrategy.onReconnectError=this.handleReconnectError}this._streamComposedController=n}get isPushing(){return this._connectionState===pe.CONNECTED||this._connectionState===pe.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(W.LiveConnectStateChange,e),e){case pe.CONNECTED:(t=this._reconnectStrategy)!=null&&t.isActive()?this._reconnectStrategy.stop({isSuccess:!0}):(this._streamConsumeController.emit(W.PushStart),this.setPushStatsInterval(),x(D.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(),x(D.START_PUSH,{push_url:e,session_id:this._pushSessionId})),!e)throw x(D.START_PUSH_STATUS,{is_success:!1,session_id:this._pushSessionId,reason:Dt.PushCheck,push_url:this._pushUrl}),new Error("lack publish url");if(this._connect)return;this.start(),this._pushUrl=Ea({pushUrl:e,disableTCC:!0}),this._pushEncodeConfig=t.cfg;const i=this._composedStream.videoTrack,n=this._composedStream.audioTrack;if(this._needCheckAudioTrack&&(!i||!n)){x(D.START_PUSH_STATUS,{is_success:!1,reason:Dt.PushCheck,push_url:this._pushUrl,error_message:"lack videoTrack or audioTrack",video_track_id:i==null?void 0:i.id,audio_track_id:n==null?void 0:n.id,video_track_name:i==null?void 0:i.label,audio_track_name:n==null?void 0:n.label,push_mode:this._pushMode,session_id:this._pushSessionId}),console.warn("lack videoTrack or audioTrack","videoTrack: ",i==null?void 0:i.id,"audioTrack: ",n==null?void 0:n.id);return}else if(!i&&!n){x(D.START_PUSH_STATUS,{is_success:!1,reason:Dt.PushCheck,push_url:this._pushUrl,error_message:"lack videoTrack and audioTrack",push_mode:this._pushMode,session_id:this._pushSessionId});return}let s;this._pushMode==="rtm"?s=new y_(this._pushUrl,this._pushConfig,this._OnRtcStateChange):s=new z_(e,this._pushConfig,this._OnRTMPError,this._OnRTMPSuccess),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(pe.CONNECTING),await s.publish([n,i],[this._audioBitrate,this._videoBitrate],{cfg:t.cfg,isReconnect:t.isReconnect}),t.isReconnect||(Ca.log("startPush begin"),this._connectionStartDate=Date.now())}catch(c){const u=new yt(de.PUBLISH_FAILED,c.message,c);if(Ca.groupEnd(),(d=this._reconnectStrategy)!=null&&d.isActive())throw this.unpublish({isReconnecting:!0}),u;this._streamConsumeController.emit(W.PushError,u),x(D.STOP_PUSH_STREAM,{reason:fr.PushError,error_message:u.message,enable_reconnect:!1,push_mode:this._pushMode,session_id:this._pushSessionId,duration:this.pushDuration}),x(D.START_PUSH_STATUS,{is_success:!1,push_url:this._pushUrl,reason:Dt.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,i,n,s;if((t=this._connect)!=null&&t.isPushing){const a=Date.now(),{stats:o,originStats:d}=await this._connect.getStatsSnapshoot(2e3),u=Date.now()-a;Dp(o)?this._prevStats=void 0:this._prevStats=o;const l=this.pushMode==="rtm"?l_(o,d,{idealFrameRate:(i=this._composedStream._videoStream)==null?void 0:i.frameRate,idealBitrate:this._videoBitrate}):p_(o),h=this.pushMode==="rtm"?(n=this._connect)==null?void 0:n.videoSenderTrackStats:{};x(D.PUSH_STATS,{...l,...h,video_draw_frame:this._streamComposedController.getCompositionDrawCountPerSecond(),stats:o,push_url:this._pushUrl,push_mode:this._pushMode,session_id:this._pushSessionId,duration:l.video_duration||u,video_duration:l.video_duration||u,is_push:!0},!0)}else await Wr(2e3),x(D.PUSH_STATS,{push_url:this._pushUrl,push_mode:this._pushMode,session_id:this._pushSessionId,duration:2e3,is_push:!1,is_reconnecting:((s=this._reconnectStrategy)==null?void 0:s.isActive())??!1},!0);this.connectionState!==pe.DISCONNECTED&&(this._statsLoopTimer=window.setTimeout(e,0))};e()}async reconnect(e){if(this.pushMode==="rtm")return this.startPush(e,{isReconnect:!0})}async updatePush({videoTrack:e,audioTrack:t}){if(this._connect)try{const i=[];e&&i.push(()=>{var n;return(n=this._connect)==null?void 0:n.updatePublish(e,"video")}),t&&i.push(()=>{var n;return(n=this._connect)==null?void 0:n.updatePublish(t,"audio")}),await Promise.all(i.map(n=>n()))}catch(i){const n=new yt(de.UPDATE_PUBLISH_FAILED,`${i.name}, code:${i.code}`);this._streamConsumeController.emit(W.PushError,n)}}unpublish(e={isReconnecting:!1,isManual:!1}){var t,i,n,s,a;(t=this._connect)==null||t.unpublish(),this._connect=null,e.isManual&&(x(D.STOP_PUSH_STREAM,{reason:fr.ManualStop,duration:this.pushDuration,session_id:this._streamConsumeController.pushSessionId,push_mode:this._pushMode,reconnect_times:(i=this._reconnectStrategy)==null?void 0:i.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._prevStats=void 0,this._isReportStart=!1,this._pushEncodeConfig=void 0,this._pushUrl=void 0,this._connectionStartDate=void 0,this._pushSessionId=0,this.setConnectState(pe.DISCONNECTED),(a=this._reconnectStrategy)==null||a.stop({quiet:!0}),this._streamConsumeController.emit(W.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,i){var n;t==="video"?this._videoBitrate=e:this._audioBitrate=e,(n=this._connect)==null||n.applyBitrate(e,t,i)}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:i}){x(D.PUSH_RECONNECT_STATUS,{status:e,...t,...i}),this._streamConsumeController.emit(W.ReconnectStateChange,e,t)}}class A_ extends Ve{constructor(e,t){super(),this._previewConsumer=new i_(e.getComposedStream(),{streamConsumeController:this}),this._pushConsumer=new R_(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,i){this._pushConsumer.setBitrate(e,t,i)}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()}}const D_=()=>typeof window>"u",Re={},Xr=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 wa(r){const e=r.split(`
69
+ `);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 n=!1;const s=[/miuibrowser/,/70.*HeyTapBrowser/i];for(const a of s)a.test(i)&&(n=!0);return!n}return!1}const x_=async()=>{let r=await Xr("sendonly");return navigator.userAgent.includes("VivoBrowser")&&(r=await Xr("sendonly")),Re.h264encode=wa(r),Re.vp8encode=r.indexOf("vp8")>-1,Re},P_=async()=>{let r=await Xr("recvonly");return navigator.userAgent.includes("VivoBrowser")&&(r=await Xr("recvonly")),Re.h264decode=wa(r),Re.vp8decode=r.indexOf("vp8")>-1,Re},I_=async()=>{if(typeof Re.h264encode>"u")try{await x_()}catch{return!1}return Re.h264encode||!1},O_=async()=>{if(typeof Re.h264decode>"u")try{await P_()}catch{return!1}return Re.h264decode||!1};class M_{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=>{},this.onLiveConnectStateChange=e=>{},this.onReconnectStateChange=(e,t)=>{}}}const L_=new M_;let Ta=!0,za=!0;function Yr(r,e,t){const i=r.match(e);return i&&i.length>=t&&parseInt(i[t],10)}function pt(r,e,t){if(!r.RTCPeerConnection)return;const i=r.RTCPeerConnection.prototype,n=i.addEventListener;i.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=i.removeEventListener;i.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(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 U_(r){return typeof r!="boolean"?new Error("Argument type: "+typeof r+". Please use a boolean."):(Ta=r,r?"adapter.js logging disabled":"adapter.js logging enabled")}function N_(r){return typeof r!="boolean"?new Error("Argument type: "+typeof r+". Please use a boolean."):(za=!r,"adapter.js deprecation warnings "+(r?"disabled":"enabled"))}function ka(){if(typeof window=="object"){if(Ta)return;typeof console<"u"&&typeof console.log=="function"&&console.log.apply(console,arguments)}}function En(r,e){za&&console.warn(r+" is deprecated, please use "+e+" instead.")}function G_(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(n=>n.brand==="Chromium");if(i)return{browser:"chrome",version:parseInt(i.version,10)}}if(t.mozGetUserMedia)e.browser="firefox",e.version=Yr(t.userAgent,/Firefox\/(\d+)\./,1);else if(t.webkitGetUserMedia||r.isSecureContext===!1&&r.webkitRTCPeerConnection)e.browser="chrome",e.version=Yr(t.userAgent,/Chrom(e|ium)\/(\d+)\./,2);else if(r.RTCPeerConnection&&t.userAgent.match(/AppleWebKit\/(\d+)\./))e.browser="safari",e.version=Yr(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 Ra(r){return Object.prototype.toString.call(r)==="[object Object]"}function Aa(r){return Ra(r)?Object.keys(r).reduce(function(e,t){const i=Ra(r[t]),n=i?Aa(r[t]):r[t],s=i&&!Object.keys(n).length;return n===void 0||s?e:Object.assign(e,{[t]:n})},{}):r}function Cn(r,e,t){!e||t.has(e.id)||(t.set(e.id,e),Object.keys(e).forEach(i=>{i.endsWith("Id")?Cn(r,r.get(e[i]),t):i.endsWith("Ids")&&e[i].forEach(n=>{Cn(r,r.get(n),t)})}))}function Da(r,e,t){const i=t?"outbound-rtp":"inbound-rtp",n=new Map;if(e===null)return n;const s=[];return r.forEach(a=>{a.type==="track"&&a.trackIdentifier===e.id&&s.push(a)}),s.forEach(a=>{r.forEach(o=>{o.type===i&&o.trackId===a.id&&Cn(r,o,n)})}),n}const xa=ka;function Pa(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 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=i(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=i(o.video),xa("chrome: "+JSON.stringify(o)),d(o)})}o.video=i(o.video)}return xa("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 Ia(r){r.MediaStream=r.MediaStream||r.webkitMediaStream}function Oa(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",n=>{let s;r.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=[i.stream],this.dispatchEvent(a)}),i.stream.getTracks().forEach(n=>{let s;r.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=[i.stream],this.dispatchEvent(a)})},this.addEventListener("addstream",this._ontrackpoly)),e.apply(this,arguments)}}else pt(r,"track",e=>(e.transceiver||Object.defineProperty(e,"transceiver",{value:{receiver:e.receiver}}),e))}function Ma(r){if(typeof r=="object"&&r.RTCPeerConnection&&!("getSenders"in r.RTCPeerConnection.prototype)&&"createDTMFSender"in r.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(!r.RTCPeerConnection.prototype.getSenders){r.RTCPeerConnection.prototype.getSenders=function(){return this._senders=this._senders||[],this._senders.slice()};const n=r.RTCPeerConnection.prototype.addTrack;r.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=r.RTCPeerConnection.prototype.removeTrack;r.RTCPeerConnection.prototype.removeTrack=function(o){s.apply(this,arguments);const d=this._senders.indexOf(o);d!==-1&&this._senders.splice(d,1)}}const t=r.RTCPeerConnection.prototype.addStream;r.RTCPeerConnection.prototype.addStream=function(s){this._senders=this._senders||[],t.apply(this,[s]),s.getTracks().forEach(a=>{this._senders.push(e(this,a))})};const i=r.RTCPeerConnection.prototype.removeStream;r.RTCPeerConnection.prototype.removeStream=function(s){this._senders=this._senders||[],i.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 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(n=>n._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 La(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 s=t.apply(this,[]);return s.forEach(a=>a._pc=this),s});const i=r.RTCPeerConnection.prototype.addTrack;i&&(r.RTCPeerConnection.prototype.addTrack=function(){const s=i.apply(this,arguments);return s._pc=this,s}),r.RTCRtpSender.prototype.getStats=function(){const s=this;return this._pc.getStats().then(a=>Da(a,s.track,!0))}}if(!("getStats"in r.RTCRtpReceiver.prototype)){const t=r.RTCPeerConnection.prototype.getReceivers;t&&(r.RTCPeerConnection.prototype.getReceivers=function(){const n=t.apply(this,[]);return n.forEach(s=>s._pc=this),n}),pt(r,"track",i=>(i.receiver._pc=i.srcElement,i)),r.RTCRtpReceiver.prototype.getStats=function(){const n=this;return this._pc.getStats().then(s=>Da(s,n.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 n,s,a;return this.getSenders().forEach(o=>{o.track===i&&(n?a=!0:n=o)}),this.getReceivers().forEach(o=>(o.track===i&&(s?a=!0:s=o),o.track===i)),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 Ua(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 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=r.RTCPeerConnection.prototype.addStream;r.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 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 n=r.RTCPeerConnection.prototype.removeTrack;r.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 Na(r,e){if(!r.RTCPeerConnection)return;if(r.RTCPeerConnection.prototype.addTrack&&e.version>=65)return Ua(r);const t=r.RTCPeerConnection.prototype.getLocalStreams;r.RTCPeerConnection.prototype.getLocalStreams=function(){const u=t.apply(this);return this._reverseStreams=this._reverseStreams||{},u.map(l=>this._reverseStreams[l.id])};const i=r.RTCPeerConnection.prototype.addStream;r.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 r.MediaStream(u.getTracks());this._streams[u.id]=l,this._reverseStreams[l.id]=u,u=l}i.apply(this,[u])};const n=r.RTCPeerConnection.prototype.removeStream;r.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]},r.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 r.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=r.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))}};r.RTCPeerConnection.prototype[c]=l[c]});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 d=Object.getOwnPropertyDescriptor(r.RTCPeerConnection.prototype,"localDescription");Object.defineProperty(r.RTCPeerConnection.prototype,"localDescription",{get(){const c=d.get.apply(this);return c.type===""?c:s(this,c)}}),r.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 wn(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],n={[t](){return arguments[0]=new(t==="addIceCandidate"?r.RTCIceCandidate:r.RTCSessionDescription)(arguments[0]),i.apply(this,arguments)}};r.RTCPeerConnection.prototype[t]=n[t]})}function Ga(r,e){pt(r,"negotiationneeded",t=>{const i=t.target;if(!((e.version<72||i.getConfiguration&&i.getConfiguration().sdpSemantics==="plan-b")&&i.signalingState!=="stable"))return t})}const Ba=Object.freeze(Object.defineProperty({__proto__:null,fixNegotiationNeeded:Ga,shimAddTrackRemoveTrack:Na,shimAddTrackRemoveTrackWithNative:Ua,shimGetSendersWithDtmf:Ma,shimGetUserMedia:Pa,shimMediaStream:Ia,shimOnTrack:Oa,shimPeerConnection:wn,shimSenderReceiverGetStats:La},Symbol.toStringTag,{value:"Module"}));function Va(r,e){const t=r&&r.navigator,i=r&&r.MediaStreamTrack;if(t.getUserMedia=function(n,s,a){En("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)},i&&i.prototype.getSettings){const a=i.prototype.getSettings;i.prototype.getSettings=function(){const o=a.apply(this,arguments);return n(o,"mozAutoGainControl","autoGainControl"),n(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)),n(o,"autoGainControl","mozAutoGainControl"),n(o,"noiseSuppression","mozNoiseSuppression")),a.apply(this,[o])}}}}function B_(r,e){r.navigator.mediaDevices&&"getDisplayMedia"in r.navigator.mediaDevices||r.navigator.mediaDevices&&(r.navigator.mediaDevices.getDisplayMedia=function(i){if(!(i&&i.video)){const n=new DOMException("getDisplayMedia without video constraints is undefined");return n.name="NotFoundError",n.code=8,Promise.reject(n)}return i.video===!0?i.video={mediaSource:e}:i.video.mediaSource=e,r.navigator.mediaDevices.getUserMedia(i)})}function Fa(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 Tn(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(n){const s=r.RTCPeerConnection.prototype[n],a={[n](){return arguments[0]=new(n==="addIceCandidate"?r.RTCIceCandidate:r.RTCSessionDescription)(arguments[0]),s.apply(this,arguments)}};r.RTCPeerConnection.prototype[n]=a[n]});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[s,a,o]=arguments;return i.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 ja(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 n=e.apply(this,[]);return n.forEach(s=>s._pc=this),n});const t=r.RTCPeerConnection.prototype.addTrack;t&&(r.RTCPeerConnection.prototype.addTrack=function(){const n=t.apply(this,arguments);return n._pc=this,n}),r.RTCRtpSender.prototype.getStats=function(){return this.track?this._pc.getStats(this.track):Promise.resolve(new Map)}}function Ha(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(n=>n._pc=this),i}),pt(r,"track",t=>(t.receiver._pc=t.srcElement,t)),r.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track)}}function $a(r){!r.RTCPeerConnection||"removeStream"in r.RTCPeerConnection.prototype||(r.RTCPeerConnection.prototype.removeStream=function(t){En("removeStream","removeTrack"),this.getSenders().forEach(i=>{i.track&&t.getTracks().includes(i.track)&&this.removeTrack(i)})})}function qa(r){r.DataChannel&&!r.RTCDataChannel&&(r.RTCDataChannel=r.DataChannel)}function Ka(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 n=i.length>0;n&&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 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=i,a.sendEncodings=i,this.setParametersPromises.push(a.setParameters(o).then(()=>{delete a.sendEncodings}).catch(()=>{delete a.sendEncodings})))}return s})}function Wa(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 Ja(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 Za(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 Xa=Object.freeze(Object.defineProperty({__proto__:null,shimAddTransceiver:Ka,shimCreateAnswer:Za,shimCreateOffer:Ja,shimGetDisplayMedia:B_,shimGetParameters:Wa,shimGetUserMedia:Va,shimOnTrack:Fa,shimPeerConnection:Tn,shimRTCDataChannel:qa,shimReceiverGetStats:Ha,shimRemoveStream:$a,shimSenderGetStats:ja},Symbol.toStringTag,{value:"Module"}));function Ya(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(n=>e.call(this,n,i)),i.getVideoTracks().forEach(n=>e.call(this,n,i))},r.RTCPeerConnection.prototype.addTrack=function(i,...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 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 n=t.getTracks();this.getSenders().forEach(s=>{n.includes(s.track)&&this.removeTrack(s)})})}}function Qa(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(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=r.RTCPeerConnection.prototype.setRemoteDescription;r.RTCPeerConnection.prototype.setRemoteDescription=function(){const i=this;return this._onaddstreampoly||this.addEventListener("track",this._onaddstreampoly=function(n){n.streams.forEach(s=>{if(i._remoteStreams||(i._remoteStreams=[]),i._remoteStreams.indexOf(s)>=0)return;i._remoteStreams.push(s);const a=new Event("addstream");a.stream=s,i.dispatchEvent(a)})}),e.apply(i,arguments)}}}function ec(r){if(typeof r!="object"||!r.RTCPeerConnection)return;const e=r.RTCPeerConnection.prototype,t=e.createOffer,i=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=i.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 tc(r){const e=r&&r.navigator;if(e.mediaDevices&&e.mediaDevices.getUserMedia){const t=e.mediaDevices,i=t.getUserMedia.bind(t);e.mediaDevices.getUserMedia=n=>i(rc(n))}!e.getUserMedia&&e.mediaDevices&&e.mediaDevices.getUserMedia&&(e.getUserMedia=(function(i,n,s){e.mediaDevices.getUserMedia(i).then(n,s)}).bind(e))}function rc(r){return r&&r.video!==void 0?Object.assign({},r,{video:Aa(r.video)}):r}function ic(r){if(!r.RTCPeerConnection)return;const e=r.RTCPeerConnection;r.RTCPeerConnection=function(i,n){if(i&&i.iceServers){const s=[];for(let a=0;a<i.iceServers.length;a++){let o=i.iceServers[a];o.urls===void 0&&o.url?(En("RTCIceServer.url","RTCIceServer.urls"),o=JSON.parse(JSON.stringify(o)),o.urls=o.url,delete o.url,s.push(o)):s.push(i.iceServers[a])}i.iceServers=s}return new e(i,n)},r.RTCPeerConnection.prototype=e.prototype,"generateCertificate"in e&&Object.defineProperty(r.RTCPeerConnection,"generateCertificate",{get(){return e.generateCertificate}})}function nc(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 sc(r){const e=r.RTCPeerConnection.prototype.createOffer;r.RTCPeerConnection.prototype.createOffer=function(i){if(i){typeof i.offerToReceiveAudio<"u"&&(i.offerToReceiveAudio=!!i.offerToReceiveAudio);const n=this.getTransceivers().find(a=>a.receiver.track.kind==="audio");i.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"):i.offerToReceiveAudio===!0&&!n&&this.addTransceiver("audio",{direction:"recvonly"}),typeof i.offerToReceiveVideo<"u"&&(i.offerToReceiveVideo=!!i.offerToReceiveVideo);const s=this.getTransceivers().find(a=>a.receiver.track.kind==="video");i.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"):i.offerToReceiveVideo===!0&&!s&&this.addTransceiver("video",{direction:"recvonly"})}return e.apply(this,arguments)}}function oc(r){typeof r!="object"||r.AudioContext||(r.AudioContext=r.webkitAudioContext)}const ac=Object.freeze(Object.defineProperty({__proto__:null,shimAudioContext:oc,shimCallbacksAPI:ec,shimConstraints:rc,shimCreateOfferLegacy:sc,shimGetUserMedia:tc,shimLocalStreamsAPI:Ya,shimRTCIceServerUrls:ic,shimRemoteStreamsAPI:Qa,shimTrackEventTransceiver:nc},Symbol.toStringTag,{value:"Module"}));var zn={exports:{}},cc;function V_(){return cc||(cc=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(`
70
70
  `).map(i=>i.trim())},e.splitSections=function(t){return t.split(`
71
71
  m=`).map((n,s)=>(s>0?"m="+n:n).trim()+`\r
72
72
  `)},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(n=>n.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 n={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 s=8;s<i.length;s+=2)switch(i[s]){case"raddr":n.relatedAddress=i[s+1];break;case"rport":n.relatedPort=parseInt(i[s+1],10);break;case"tcptype":n.tcpType=i[s+1];break;case"ufrag":n.ufrag=i[s+1],n.usernameFragment=i[s+1];break;default:n[i[s]]===void 0&&(n[i[s]]=i[s+1]);break}return n},e.writeCandidate=function(t){const i=[];i.push(t.foundation);const n=t.component;n==="rtp"?i.push(1):n==="rtcp"?i.push(2):i.push(n),i.push(t.protocol.toUpperCase()),i.push(t.priority),i.push(t.address||t.ip),i.push(t.port);const s=t.type;return i.push("typ"),i.push(s),s!=="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 n={payloadType:parseInt(i.shift(),10)};return i=i[0].split("/"),n.name=i[0],n.clockRate=parseInt(i[1],10),n.channels=i.length===3?parseInt(i[2],10):1,n.numChannels=n.channels,n},e.writeRtpMap=function(t){let i=t.payloadType;t.preferredPayloadType!==void 0&&(i=t.preferredPayloadType);const n=t.channels||t.numChannels||1;return"a=rtpmap:"+i+" "+t.name+"/"+t.clockRate+(n!==1?"/"+n:"")+`\r
@@ -97,7 +97,7 @@ a=ice-pwd:`+t.password+`\r
97
97
  o=`+(n||"thisisadapterortc")+" "+s+" "+a+` IN IP4 127.0.0.1\r
98
98
  s=-\r
99
99
  t=0 0\r
100
- `},e.getDirection=function(t,i){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 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 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 i=e.splitLines(t);for(let n=0;n<i.length;n++)if(i[n].length<2||i[n].charAt(1)!=="=")return!1;return!0},r.exports=e}(zn)),zn.exports}var cc=N_();const xt=ne(cc),G_=ye({__proto__:null,default:xt},[cc]);function Qr(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 n=new e(i),s=xt.parseCandidate(i.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(i)},r.RTCIceCandidate.prototype=e.prototype,pt(r,"icecandidate",t=>(t.candidate&&Object.defineProperty(t,"candidate",{value:new r.RTCIceCandidate(t.candidate),writable:"false"}),t))}function kn(r){!r.RTCIceCandidate||r.RTCIceCandidate&&"relayProtocol"in r.RTCIceCandidate.prototype||pt(r,"icecandidate",e=>{if(e.candidate){const t=xt.parseCandidate(e.candidate.candidate);t.type==="relay"&&(e.candidate.relayProtocol={0:"tls",1:"tcp",2:"udp"}[t.priority>>24])}return e})}function ei(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 d=xt.splitSections(o.sdp);return d.shift(),d.some(c=>{const u=xt.parseMLine(c);return u&&u.kind==="application"&&u.protocol.indexOf("SCTP")!==-1})},i=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=xt.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=r.RTCPeerConnection.prototype.setRemoteDescription;r.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=i(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 ti(r){if(!(r.RTCPeerConnection&&"createDataChannel"in r.RTCPeerConnection.prototype))return;function e(i,n){const s=i.send;i.send=function(){const o=arguments[0],d=o.length||o.size||o.byteLength;if(i.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(i,arguments)}}const t=r.RTCPeerConnection.prototype.createDataChannel;r.RTCPeerConnection.prototype.createDataChannel=function(){const n=t.apply(this,arguments);return e(n,this),n},pt(r,"datachannel",i=>(e(i.channel,i.target),i))}function Rn(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=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)),i.apply(this,arguments)}})}function An(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(n){if(n&&n.sdp&&n.sdp.indexOf(`
100
+ `},e.getDirection=function(t,i){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 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 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 i=e.splitLines(t);for(let n=0;n<i.length;n++)if(i[n].length<2||i[n].charAt(1)!=="=")return!1;return!0},r.exports=e}(zn)),zn.exports}var uc=V_();const xt=ne(uc),F_=ye({__proto__:null,default:xt},[uc]);function Qr(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 n=new e(i),s=xt.parseCandidate(i.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(i)},r.RTCIceCandidate.prototype=e.prototype,pt(r,"icecandidate",t=>(t.candidate&&Object.defineProperty(t,"candidate",{value:new r.RTCIceCandidate(t.candidate),writable:"false"}),t))}function kn(r){!r.RTCIceCandidate||r.RTCIceCandidate&&"relayProtocol"in r.RTCIceCandidate.prototype||pt(r,"icecandidate",e=>{if(e.candidate){const t=xt.parseCandidate(e.candidate.candidate);t.type==="relay"&&(e.candidate.relayProtocol={0:"tls",1:"tcp",2:"udp"}[t.priority>>24])}return e})}function ei(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 d=xt.splitSections(o.sdp);return d.shift(),d.some(c=>{const u=xt.parseMLine(c);return u&&u.kind==="application"&&u.protocol.indexOf("SCTP")!==-1})},i=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=xt.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=r.RTCPeerConnection.prototype.setRemoteDescription;r.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=i(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 ti(r){if(!(r.RTCPeerConnection&&"createDataChannel"in r.RTCPeerConnection.prototype))return;function e(i,n){const s=i.send;i.send=function(){const o=arguments[0],d=o.length||o.size||o.byteLength;if(i.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(i,arguments)}}const t=r.RTCPeerConnection.prototype.createDataChannel;r.RTCPeerConnection.prototype.createDataChannel=function(){const n=t.apply(this,arguments);return e(n,this),n},pt(r,"datachannel",i=>(e(i.channel,i.target),i))}function Rn(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=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)),i.apply(this,arguments)}})}function An(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(n){if(n&&n.sdp&&n.sdp.indexOf(`
101
101
  a=extmap-allow-mixed`)!==-1){const s=n.sdp.split(`
102
102
  `).filter(a=>a.trim()!=="a=extmap-allow-mixed").join(`
103
- `);r.RTCSessionDescription&&n instanceof r.RTCSessionDescription?arguments[0]=new r.RTCSessionDescription({type:n.type,sdp:s}):n.sdp=s}return t.apply(this,arguments)}}function ri(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 ii(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 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 B_=Object.freeze(Object.defineProperty({__proto__:null,removeExtmapAllowMixed:An,shimAddIceCandidateNullOrEmpty:ri,shimConnectionState:Rn,shimMaxMessageSize:ei,shimParameterlessSetLocalDescription:ii,shimRTCIceCandidate:Qr,shimRTCIceCandidateRelayProtocol:kn,shimSendThrowTypeError:ti},Symbol.toStringTag,{value:"Module"}));function V_({window:r}={},e={shimChrome:!0,shimFirefox:!0,shimSafari:!0}){const t=za,i=L_(r),n={browserDetails:i,commonShim:B_,extractVersion:Yr,disableLog:O_,disableWarnings:M_,sdp:G_};switch(i.browser){case"chrome":if(!Ga||!wn||!e.shimChrome)return t("Chrome shim is not included in this adapter release."),n;if(i.version===null)return t("Chrome shim can not determine version, not shimming."),n;t("adapter.js shimming chrome."),n.browserShim=Ga,ri(r,i),ii(r),xa(r,i),Pa(r),wn(r,i),Ia(r),Ua(r,i),Oa(r),Ma(r),Na(r,i),Qr(r),kn(r),Rn(r),ei(r,i),ti(r),An(r,i);break;case"firefox":if(!Za||!Tn||!e.shimFirefox)return t("Firefox shim is not included in this adapter release."),n;t("adapter.js shimming firefox."),n.browserShim=Za,ri(r,i),ii(r),Ba(r,i),Tn(r,i),Va(r),Ha(r),Fa(r),ja(r),$a(r),qa(r),Ka(r),Wa(r),Ja(r),Qr(r),Rn(r),ei(r,i),ti(r);break;case"safari":if(!oc||!e.shimSafari)return t("Safari shim is not included in this adapter release."),n;t("adapter.js shimming safari."),n.browserShim=oc,ri(r,i),ii(r),rc(r),nc(r),Qa(r),Xa(r),Ya(r),ic(r),ec(r),sc(r),Qr(r),kn(r),ei(r,i),ti(r),An(r,i);break;default:t("Unsupported browser!");break}return n}V_({window:typeof window>"u"?void 0:window});function F_(){const r={hardware_concurrency:navigator.hardwareConcurrency};navigator.deviceMemory&&(r.device_memory=navigator.deviceMemory+"GB");try{const e=document.createElement("canvas"),t=e.getContext("webgl")||e.getContext("experimental-webgl");if(t){const i=t.getExtension("WEBGL_debug_renderer_info");i&&(r.gpu_vendor=t.getParameter(i.UNMASKED_VENDOR_WEBGL),r.gpu_renderer=t.getParameter(i.UNMASKED_RENDERER_WEBGL)),r.webgl_version=t.getParameter(t.VERSION),r.webgl_shading_language_version=t.getParameter(t.SHADING_LANGUAGE_VERSION),r.webgl_vendor=t.getParameter(t.VENDOR),r.webgl_renderer=t.getParameter(t.RENDERER)}}catch{}return r}class j_ extends Ve{static async isSupported(e){if(e==="webTransport")return Promise.resolve(ya.isSupported());try{return k_()||!window.RTCPeerConnection||!window.RTCPeerConnection.prototype.addTransceiver||!window.RTCPeerConnection.prototype.createDataChannel?!1:await x_()&&await D_()}catch{return!1}}constructor(e){var t,i,n,s,a,o,d,c,u,l;if(super(),this._options=e??{},this._streamManagerController=new jm(this),this._streamComposeController=new Qm(this._streamManagerController),this._streamConsumeController=new z_(this._streamComposeController,e),this._streamConsumeController.setPushConfig(e),this._observer=I_,this._bindEvent(),!(e!=null&&e.loggerConfig)||(t=e==null?void 0:e.loggerConfig)!=null&&t.enable){Vm({showLogInConsole:((i=e==null?void 0:e.loggerConfig)==null?void 0:i.showInConsole)??!1});const h=Nm((n=e==null?void 0:e.loggerConfig)==null?void 0:n.userId),p=Gm((s=e==null?void 0:e.loggerConfig)==null?void 0:s.deviceId);Fm({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}),D(x.PUSHER_INIT,{options:e,...F_()})}}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:N.Camera})}async startMicrophone(e){return await this._streamManagerController.startMicrophoneCapture(e)}stopMicrophone(e){this._streamManagerController.stopCapture({streamId:e,type:N.Microphone})}async startVideoFileCapture(e){return e?await this._streamManagerController.startVideoFileCapture(e):void 0}stopVideoFileCapture(e){this._streamManagerController.stopCapture({streamId:e,type:N.VideoFile})}async startScreenCapture(e=!1){return await this._streamManagerController.startScreenCapture(e)}stopScreenCapture(e){this._streamManagerController.stopCapture({streamId:e,type:N.Screen})}async startAudioFileCapture(e){return e?await this._streamManagerController.startAudioFileCapture(e):void 0}stopAudioFileCapture(e){this._streamManagerController.stopCapture({streamId:e,type:N.AudioFile})}async startImageCapture(e){return e?await this._streamManagerController.startImageCapture(e):void 0}stopImageCapture(e){this._streamManagerController.stopCapture({streamId:e,type:N.Image})}startCustomVideoCapture(e){return e?this._streamManagerController.startCustomVideoCapture(e):void 0}stopCustomVideoCapture(e){this._streamManagerController.stopCapture({streamId:e,type:N.CustomVideo})}startCustomAudioCapture(e){return e?this._streamManagerController.startCustomAudioCapture(e):void 0}stopCustomAudioCapture(e){this._streamManagerController.stopCapture({streamId:e,type:N.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(D(x.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){D(x.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(D(x.PUSH_AUDIO_CONTEXT_START_FAILED,{error:t}),this._options.checkAudio)throw new yt(de.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){D(x.ADD_VIDEO_STREAM,{number:X(e)?e.length:1,config:e}),X(e)?e.forEach(t=>{this._streamComposeController.addVideoStream(t)}):this._streamComposeController.addVideoStream(e)}removeVideoStream(e){D(x.DELETE_VIDEO_STREAM,{stream_id:e}),this._streamComposeController.removeVideoStream(e)}updateVideoStream(e){D(x.UPDATE_VIDEO_STREAM,{number:X(e)?e.length:1,config:e}),X(e)?this._streamComposeController.updateVideoStream(e):this._streamComposeController.updateVideoStream([e])}muteVideoStream(e){D(x.CHANGE_VIDEO_STREAM_MUTE,{stream_id:e,mute:!1}),this._streamComposeController.muteVideoStream(e)}unmuteVideoStream(e){D(x.CHANGE_VIDEO_STREAM_MUTE,{stream_id:e,mute:!0}),this._streamComposeController.unmuteVideoStream(e)}addAudioStream(e){D(x.ADD_AUDIO_STREAM,{number:X(e)?e.length:1,config:e}),X(e)?e.map(t=>this._streamComposeController.addAudioStream(t)):this._streamComposeController.addAudioStream(e)}removeAudioStream(e){D(x.DELETE_AUDIO_STREAM,{stream_id:e}),this._streamComposeController.removeAudioStream(e)}updateAudioStream(e){D(x.UPDATE_AUDIO_STREAM,{number:X(e)?e.length:1,config:e}),X(e)?this._streamComposeController.updateAudioStream(e):this._streamComposeController.updateAudioStream([e])}muteAudioStream(e){D(x.CHANGE_AUDIO_STREAM_MUTE,{stream_id:e,mute:!0}),this._streamComposeController.muteAudioStream(e)}unmuteAudioStream(e){D(x.CHANGE_AUDIO_STREAM_MUTE,{stream_id:e,mute:!1}),this._streamComposeController.unmuteAudioStream(e)}setProperty(e,t){switch(D(x.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":Tr.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(D(x.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:i,frameRate:n,bitrate:s}=bt(e,"video");this._streamManagerController.setVideoResolution({width:t,height:i}),this._streamManagerController.setVideoFps(n),this._streamComposeController.setVideoQuality({width:t,height:i,frameRate:n}),this._streamConsumeController.setBitrate(s,"video")}setAudioQuality(e){D(x.SET_AUDIO_QUALITY,{quality:e});const{sampleRate:t,bitrate:i}=bt(e,"audio");this._streamManagerController.setAudioSampleRate(t),this._streamConsumeController.setBitrate(i,"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(Ee.Error,e=>{this.observer.onError(e.code,e.message,e.ext)}),this._streamManagerController.on(Ee.Interrupted,e=>{this.observer.onCaptureInterrupted(e.id)}),this._streamConsumeController.on(W.PushStart,()=>{this.observer.onPushStart()}),this._streamConsumeController.on(W.PushStop,()=>{this.observer.onPushStop()}),this._streamConsumeController.on(W.RTCConnectStateChanged,e=>{this.observer.onPushStatusUpdate(Nn[e],e)}),this._streamConsumeController.on(W.PushError,e=>{this.observer.onError(e.code,e.message,e.ext)}),this._streamManagerController.on(Ee.DeviceStopCapture,e=>{this.observer.onStopCapture(e.id)}),this._streamConsumeController.on(W.CaptureFirstAudioFrame,()=>{this.observer.onCaptureFirstAudioFrame()}),this._streamConsumeController.on(W.CaptureFirstVideoFrame,()=>{this.observer.onCaptureFirstVideoFrame()}),this._streamConsumeController.on(W.ReconnectStateChange,(e,t)=>{this.observer.onReconnectStateChange(e,t)}),this._streamConsumeController.on(W.LiveConnectStateChange,e=>{this.observer.onLiveConnectStateChange(e)}),zu(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 j_});
103
+ `);r.RTCSessionDescription&&n instanceof r.RTCSessionDescription?arguments[0]=new r.RTCSessionDescription({type:n.type,sdp:s}):n.sdp=s}return t.apply(this,arguments)}}function ri(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 ii(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 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 j_=Object.freeze(Object.defineProperty({__proto__:null,removeExtmapAllowMixed:An,shimAddIceCandidateNullOrEmpty:ri,shimConnectionState:Rn,shimMaxMessageSize:ei,shimParameterlessSetLocalDescription:ii,shimRTCIceCandidate:Qr,shimRTCIceCandidateRelayProtocol:kn,shimSendThrowTypeError:ti},Symbol.toStringTag,{value:"Module"}));function H_({window:r}={},e={shimChrome:!0,shimFirefox:!0,shimSafari:!0}){const t=ka,i=G_(r),n={browserDetails:i,commonShim:j_,extractVersion:Yr,disableLog:U_,disableWarnings:N_,sdp:F_};switch(i.browser){case"chrome":if(!Ba||!wn||!e.shimChrome)return t("Chrome shim is not included in this adapter release."),n;if(i.version===null)return t("Chrome shim can not determine version, not shimming."),n;t("adapter.js shimming chrome."),n.browserShim=Ba,ri(r,i),ii(r),Pa(r,i),Ia(r),wn(r,i),Oa(r),Na(r,i),Ma(r),La(r),Ga(r,i),Qr(r),kn(r),Rn(r),ei(r,i),ti(r),An(r,i);break;case"firefox":if(!Xa||!Tn||!e.shimFirefox)return t("Firefox shim is not included in this adapter release."),n;t("adapter.js shimming firefox."),n.browserShim=Xa,ri(r,i),ii(r),Va(r,i),Tn(r,i),Fa(r),$a(r),ja(r),Ha(r),qa(r),Ka(r),Wa(r),Ja(r),Za(r),Qr(r),Rn(r),ei(r,i),ti(r);break;case"safari":if(!ac||!e.shimSafari)return t("Safari shim is not included in this adapter release."),n;t("adapter.js shimming safari."),n.browserShim=ac,ri(r,i),ii(r),ic(r),sc(r),ec(r),Ya(r),Qa(r),nc(r),tc(r),oc(r),Qr(r),kn(r),ei(r,i),ti(r),An(r,i);break;default:t("Unsupported browser!");break}return n}H_({window:typeof window>"u"?void 0:window});function $_(){const r={hardware_concurrency:navigator.hardwareConcurrency};navigator.deviceMemory&&(r.device_memory=navigator.deviceMemory+"GB");try{const e=document.createElement("canvas"),t=e.getContext("webgl")||e.getContext("experimental-webgl");if(t){const i=t.getExtension("WEBGL_debug_renderer_info");i&&(r.gpu_vendor=t.getParameter(i.UNMASKED_VENDOR_WEBGL),r.gpu_renderer=t.getParameter(i.UNMASKED_RENDERER_WEBGL)),r.webgl_version=t.getParameter(t.VERSION),r.webgl_shading_language_version=t.getParameter(t.SHADING_LANGUAGE_VERSION),r.webgl_vendor=t.getParameter(t.VENDOR),r.webgl_renderer=t.getParameter(t.RENDERER)}}catch{}return r}class q_ extends Ve{static async isSupported(e){if(e==="webTransport")return Promise.resolve(ba.isSupported());try{return D_()||!window.RTCPeerConnection||!window.RTCPeerConnection.prototype.addTransceiver||!window.RTCPeerConnection.prototype.createDataChannel?!1:await O_()&&await I_()}catch{return!1}}constructor(e){var t,i,n,s,a,o,d,c,u,l;if(super(),this._options=e??{},this._streamManagerController=new qm(this),this._streamComposeController=new r_(this._streamManagerController),this._streamConsumeController=new A_(this._streamComposeController,e),this._streamConsumeController.setPushConfig(e),this._observer=L_,this._bindEvent(),!(e!=null&&e.loggerConfig)||(t=e==null?void 0:e.loggerConfig)!=null&&t.enable){Fm({showLogInConsole:((i=e==null?void 0:e.loggerConfig)==null?void 0:i.showInConsole)??!1});const h=Gm((n=e==null?void 0:e.loggerConfig)==null?void 0:n.userId),p=Bm((s=e==null?void 0:e.loggerConfig)==null?void 0:s.deviceId);jm({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}),x(D.PUSHER_INIT,{options:e,...$_()}),Hm()}}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:N.Camera})}async startMicrophone(e){return await this._streamManagerController.startMicrophoneCapture(e)}stopMicrophone(e){this._streamManagerController.stopCapture({streamId:e,type:N.Microphone})}async startVideoFileCapture(e){return e?await this._streamManagerController.startVideoFileCapture(e):void 0}stopVideoFileCapture(e){this._streamManagerController.stopCapture({streamId:e,type:N.VideoFile})}async startScreenCapture(e=!1){return await this._streamManagerController.startScreenCapture(e)}stopScreenCapture(e){this._streamManagerController.stopCapture({streamId:e,type:N.Screen})}async startAudioFileCapture(e){return e?await this._streamManagerController.startAudioFileCapture(e):void 0}stopAudioFileCapture(e){this._streamManagerController.stopCapture({streamId:e,type:N.AudioFile})}async startImageCapture(e){return e?await this._streamManagerController.startImageCapture(e):void 0}stopImageCapture(e){this._streamManagerController.stopCapture({streamId:e,type:N.Image})}startCustomVideoCapture(e){return e?this._streamManagerController.startCustomVideoCapture(e):void 0}stopCustomVideoCapture(e){this._streamManagerController.stopCapture({streamId:e,type:N.CustomVideo})}startCustomAudioCapture(e){return e?this._streamManagerController.startCustomAudioCapture(e):void 0}stopCustomAudioCapture(e){this._streamManagerController.stopCapture({streamId:e,type:N.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(x(D.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){x(D.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(x(D.PUSH_AUDIO_CONTEXT_START_FAILED,{error:t}),this._options.checkAudio)throw new yt(de.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){x(D.ADD_VIDEO_STREAM,{number:X(e)?e.length:1,config:e}),X(e)?e.forEach(t=>{this._streamComposeController.addVideoStream(t)}):this._streamComposeController.addVideoStream(e)}removeVideoStream(e){x(D.DELETE_VIDEO_STREAM,{stream_id:e}),this._streamComposeController.removeVideoStream(e)}updateVideoStream(e){x(D.UPDATE_VIDEO_STREAM,{number:X(e)?e.length:1,config:e}),X(e)?this._streamComposeController.updateVideoStream(e):this._streamComposeController.updateVideoStream([e])}muteVideoStream(e){x(D.CHANGE_VIDEO_STREAM_MUTE,{stream_id:e,mute:!1}),this._streamComposeController.muteVideoStream(e)}unmuteVideoStream(e){x(D.CHANGE_VIDEO_STREAM_MUTE,{stream_id:e,mute:!0}),this._streamComposeController.unmuteVideoStream(e)}addAudioStream(e){x(D.ADD_AUDIO_STREAM,{number:X(e)?e.length:1,config:e}),X(e)?e.map(t=>this._streamComposeController.addAudioStream(t)):this._streamComposeController.addAudioStream(e)}removeAudioStream(e){x(D.DELETE_AUDIO_STREAM,{stream_id:e}),this._streamComposeController.removeAudioStream(e)}updateAudioStream(e){x(D.UPDATE_AUDIO_STREAM,{number:X(e)?e.length:1,config:e}),X(e)?this._streamComposeController.updateAudioStream(e):this._streamComposeController.updateAudioStream([e])}muteAudioStream(e){x(D.CHANGE_AUDIO_STREAM_MUTE,{stream_id:e,mute:!0}),this._streamComposeController.muteAudioStream(e)}unmuteAudioStream(e){x(D.CHANGE_AUDIO_STREAM_MUTE,{stream_id:e,mute:!1}),this._streamComposeController.unmuteAudioStream(e)}setProperty(e,t){switch(x(D.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":Tr.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(x(D.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:i,frameRate:n,bitrate:s}=bt(e,"video");this._streamManagerController.setVideoResolution({width:t,height:i}),this._streamManagerController.setVideoFps(n),this._streamComposeController.setVideoQuality({width:t,height:i,frameRate:n}),this._streamConsumeController.setBitrate(s,"video")}setAudioQuality(e){x(D.SET_AUDIO_QUALITY,{quality:e});const{sampleRate:t,bitrate:i}=bt(e,"audio");this._streamManagerController.setAudioSampleRate(t),this._streamConsumeController.setBitrate(i,"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(Ee.Error,e=>{this.observer.onError(e.code,e.message,e.ext)}),this._streamManagerController.on(Ee.Interrupted,e=>{this.observer.onCaptureInterrupted(e.id)}),this._streamConsumeController.on(W.PushStart,()=>{this.observer.onPushStart()}),this._streamConsumeController.on(W.PushStop,()=>{this.observer.onPushStop()}),this._streamConsumeController.on(W.RTCConnectStateChanged,e=>{this.observer.onPushStatusUpdate(Nn[e],e)}),this._streamConsumeController.on(W.PushError,e=>{this.observer.onError(e.code,e.message,e.ext)}),this._streamManagerController.on(Ee.DeviceStopCapture,e=>{this.observer.onStopCapture(e.id)}),this._streamConsumeController.on(W.CaptureFirstAudioFrame,()=>{this.observer.onCaptureFirstAudioFrame()}),this._streamConsumeController.on(W.CaptureFirstVideoFrame,()=>{this.observer.onCaptureFirstVideoFrame()}),this._streamConsumeController.on(W.ReconnectStateChange,(e,t)=>{this.observer.onReconnectStateChange(e,t)}),this._streamConsumeController.on(W.LiveConnectStateChange,e=>{this.observer.onLiveConnectStateChange(e)}),ku(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(),$m()}get observer(){return this._observer}get isEnableMixing(){return this._streamComposeController.isEnableMixing}get pushMode(){return this._streamConsumeController.pushMode}}return q_});