@volcengine/vepusher 2.0.4-rc.4 → 2.0.4-rc.5
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.es.d.ts +1 -0
- package/dist/index.es.js +2776 -2628
- package/dist/index.umd.js +11 -11
- package/package.json +1 -1
package/dist/index.umd.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
(function(ge,Y){typeof exports=="object"&&typeof module<"u"?module.exports=Y():typeof define=="function"&&define.amd?define(Y):(ge=typeof globalThis<"u"?globalThis:ge||self,ge.vePusher=Y())})(this,function(){"use strict";var P_=Object.defineProperty;var L_=(ge,Y,Ne)=>Y in ge?P_(ge,Y,{enumerable:!0,configurable:!0,writable:!0,value:Ne}):ge[Y]=Ne;var b=(ge,Y,Ne)=>L_(ge,typeof Y!="symbol"?Y+"":Y,Ne);var Ya,Qa,ec,tc,rc,ic;function ge(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 Y(r){return r&&r.__esModule&&Object.prototype.hasOwnProperty.call(r,"default")?r.default:r}var Ne={exports:{}},wn;function _c(){return wn||(wn=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(h,c,u){this.fn=h,this.context=c,this.once=u||!1}function s(h,c,u,l,d){if(typeof u!="function")throw new TypeError("The listener must be a function");var p=new n(u,l||h,d),f=t?t+c:c;return h._events[f]?h._events[f].fn?h._events[f]=[h._events[f],p]:h._events[f].push(p):(h._events[f]=p,h._eventsCount++),h}function a(h,c){--h._eventsCount===0?h._events=new i:delete h._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 d=0,p=l.length,f=new Array(p);d<p;d++)f[d]=l[d].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,d,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,d),!0;case 5:return m.fn.call(m.context,u,l,d,p),!0;case 6:return m.fn.call(m.context,u,l,d,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,d);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,d){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&&(!d||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||d&&!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}(Ne)),Ne.exports}var gc=_c();const Ge=Y(gc);var Tn=(r=>(r.LeftToRight="LeftToRight",r.UpToDown="UpToDown",r.All="All",r.None="None",r))(Tn||{}),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||{}),ye=(r=>(r.DeviceCaptured="deviceCaptured",r.DeviceStopCapture="deviceStopCapture",r.Error="error",r.Interrupted="interrupted",r))(ye||{}),j=(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))(j||{}),zn=(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))(zn||{}),kn=(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))(kn||{}),An=(r=>(r.STANDARD="48000x40",r.HIGH="48000x128",r))(An||{}),Ye=(r=>(r.VideoStreamChange="videoStreamChange",r.AudioStreamChange="audioStreamChange",r))(Ye||{}),Rn=(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))(Rn||{});const Dn={SizeChange:"sizeChange"};var Xr=(r=>(r.Portrait="portrait",r.Landscape="landscape",r))(Xr||{});const xn="720p-1",On="STANDARD";var de=(r=>(r[r.DISCONNECTED=0]="DISCONNECTED",r[r.CONNECTING=1]="CONNECTING",r[r.CONNECTED=2]="CONNECTED",r[r.RECONNECTING=3]="RECONNECTING",r))(de||{}),dt=(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))(dt||{}),Yr=(r=>(r[r.PushUrlInvalid=1001]="PushUrlInvalid",r[r.ReconnectTimeout=1002]="ReconnectTimeout",r))(Yr||{}),I=(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))(I||{}),B=(r=>(r.AUDIO="audio",r.VIDEO="video",r))(B||{}),Q=(r=>(r.ENDED="ended",r.MUTE="mute",r.UNMUTE="unmute",r.PLAY_FAILED="play-failed",r.SIZE_CHANGE="size-change",r))(Q||{});const Z=[];for(let r=0;r<256;++r)Z.push((r+256).toString(16).slice(1));function vc(r,e=0){return(Z[r[e+0]]+Z[r[e+1]]+Z[r[e+2]]+Z[r[e+3]]+"-"+Z[r[e+4]]+Z[r[e+5]]+"-"+Z[r[e+6]]+Z[r[e+7]]+"-"+Z[r[e+8]]+Z[r[e+9]]+"-"+Z[r[e+10]]+Z[r[e+11]]+Z[r[e+12]]+Z[r[e+13]]+Z[r[e+14]]+Z[r[e+15]]).toLowerCase()}let Qr;const yc=new Uint8Array(16);function bc(){if(!Qr){if(typeof crypto>"u"||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");Qr=crypto.getRandomValues.bind(crypto)}return Qr(yc)}const Mn={randomUUID:typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};function Qe(r,e,t){var n;if(Mn.randomUUID&&!r)return Mn.randomUUID();r=r||{};const i=r.random??((n=r.rng)==null?void 0:n.call(r))??bc();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,vc(i)}class In{constructor(){b(this,"id",Qe());b(this,"_nextNode");b(this,"_track");b(this,"_destNode")}gain(e){if(this._nextNode instanceof Pn)return this._nextNode.g=e,this._nextNode;const t=new Pn(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 Pn extends In{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 Sc extends In{constructor(t){super();b(this,"previousNode",null);b(this,"source");this.source=t}available(){return this.source.available()}destroy(){super.destroy()}}class Ec extends Sc{constructor(){super(...arguments);b(this,"_node")}createNode(t){if(this._node)return this._node;let i;if(this.source instanceof Hn){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 M 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,M.prototype)}toString(){return`VeCapture Error: ${this.code} ${this.message}`}}const Ln={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"}},Un="__debug__",Cc="[VE-CAPTURE]";function wc(){if(typeof location>"u"||typeof localStorage>"u")return!1;let r=!1;return location.href.includes(Un)&&(r=!0),localStorage.getItem(Un)&&(r=!0),r}let ne=class{constructor(e){b(this,"moduleName");this.moduleName=e}print(e,t,...i){const n=Tc();wc()&&console.log(`${n}-${Cc}%c[${Ln[e].text}]%c[${this.moduleName}][${t}]`,`background-color:${Ln[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 Tc(){const r=new Date;return`${r.toTimeString().split(" ")[0]}:${r.getMilliseconds().toString().padStart(3,"0")}`}function ei(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 Nn({width:r,height:e}){const t=document.createElement("canvas"),i=t.getContext("2d");if(!i)throw new M(I.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 ti{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 H=()=>typeof window>"u";function F(){return navigator.userAgent.toLowerCase()}function ri(r=F()){let e="none";return H()||(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 Gn=ri()==="firefox",dr=ri()==="safari";ri(),!H()&&/crios/i.test(F()),!H()&&/edg\//i.test(F()),!H()&&/edgA/i.test(F()),!H()&&/edgios/i.test(F()),!H()&&/dingtalk/i.test(F()),!H()&&/opr\//.test(F()),!H()&&/(iphone|ipod)/i.exec(F()),!H()&&(/(ipad)/i.exec(F())||/macintosh/i.test(F())&&"ontouchend"in document),!H()&&/macintosh/i.test(F()),!H()&&/micromessenger/i.test(F()),!H()&&F().includes("mobile"),!H()&&/sm-\w+/i.test(F());const zc=!H()&&!!/(iphone|ipad|ipod)/i.exec(F());!H()&&/android/i.test(F()),!H()&&/windows/i.test(F()),!H()&&/openharmony/i.test(F());let Bn="0";const kc=!H()&&((Ya=F().match(/version\/(\d+)/i))==null?void 0:Ya[1]);dr&&kc&&(Bn=(Qa=navigator.userAgent.match(/version\/(\d+\.\d+)/i))==null?void 0:Qa[1]),!H()&&((ec=F().match(/firefox\/(\d+)/i))==null||ec[1]);const ii=Bn;!H()&&((rc=(tc=F().match(/ ([\d_]+) like mac os x/i))==null?void 0:tc[1])==null||rc.split("_").map(r=>parseInt(r))),!H()&&((ic=F().match(/chrome\/(\d+)/i))==null||ic[1]);function Ac(){var r;return!!((r=navigator==null?void 0:navigator.permissions)!=null&&r.query)}function ni(){return!!(navigator!=null&&navigator.mediaDevices)}function Rc(){var r;return ni()&&!!((r=navigator==null?void 0:navigator.mediaDevices)!=null&&r.getUserMedia)}function Dc(){return!!Promise.withResolvers}function xc(){return!(dr&&ii==="16.1")}function Oc(){return!(dr&&ii&&["16.1","16.2","16.3"].includes(ii))}function Mc(){return!Gn}function Ic(){return typeof CanvasCaptureMediaStreamTrack<"u"}function Pc(r){return typeof r.requestFrame=="function"}function Lc(){return!!ni()&&typeof navigator.mediaDevices.ondevicechange<"u"&&typeof navigator.mediaDevices.addEventListener=="function"}const ze={permissionQuery:Ac,mediaDevices:ni,settingResolutionInGetDisplayMedia:xc,promiseWithResolvers:Dc,getUserMedia:Rc,isolateEnumerateDevices:Mc,supportIdealParamsInGetDisplayMedia:Oc,canvasCaptureMediaStreamTrack:Ic,requestFrameOnMediaStream:Pc,ondevicechange:Lc};function Uc(){if(ze.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 Vn(r={}){const{timeout:e,message:t}={timeout:0,message:new M(I.UNEXPECTED_ERROR,"unexpected timeout"),...r},{promise:i,resolve:n,reject:s}=Uc();if(e<=0)return{promise:i,resolve:n,reject:s};const a=setTimeout(()=>{s(t)},e);return{promise:i,resolve:h=>{clearTimeout(a),n(h)},reject:s}}const Nc={playsinline:"","webkit-playsinline":"","x5-playsinline":"","x5-video-player-type":"h5","x-webkit-airplay":"allow",preload:"metadata",muted:"",crossOrigin:"anonymous"},Gc={playsinline:"","webkit-playsinline":"",preload:"metadata",muted:"",crossOrigin:"anonymous"};class Rt{constructor(e,t=[]){b(this,"id",Qe());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=Bc(o),this._stream=o}else if(e.url)i=Vc(e);else throw new M(I.UNEXPECTED_TYPE,`got ${typeof e}, expected: MediaStreamTrack or constraints for creating element`);const{promise:n,resolve:s,reject:a}=Vn({timeout:2e3,message:new M(I.PLAY_FAILED,"load media timeout")});this._readyLock=n,this._releaseReadyLock=s,this._throwReadyLock=a,this._element=new ti(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 M(I.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 M(I.UNEXPECTED_TYPE,"got empty list of video tracks");return i[0]}throw new M(I.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 M(I.PLAY_FAILED,"play element failed",e)}}_bindPlayerEvent(e){e.on("loadedmetadata",()=>{this._releaseReadyLock()}),e.on("error",()=>{this._throwReadyLock(new M(I.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 Bc(r){let e="audio";r.getVideoTracks().length>0&&(e="video");const t=Fn(e==="video"?B.VIDEO:B.AUDIO);return t.srcObject=r,t}function Vc(r){const{url:e,kind:t,loop:i}=r,n=Fn(t);return n.src=e,n.loop=i,n}function Fn(r){if(r===B.VIDEO)return ei(B.VIDEO,{style:{width:"100%",height:"100%"},attributes:Nc});if(r===B.AUDIO)return ei(B.AUDIO,{style:{display:"none"},attributes:Gc});throw new M(I.UNEXPECTED_TYPE,`got ${r}, expected: audio, video`)}class si extends Ge{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 oi(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 M(I.UNEXPECTED_TYPE,"unexpected constraints type")}const ai=1e3;class jn{constructor(e){b(this,"id",Qe());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=oi(e.width),i=oi(e.height),n=oi(e.frameRate);this._config={width:t,height:i,frameRate:n};const{context:s,canvas:a}=Nn({width:t,height:i});this._context=s,this._canvas=a;const o=Fc({url:e.url,width:t,height:i});this._image=new ti(o);const{promise:h,resolve:c,reject:u}=Vn({timeout:2e3,message:new M(I.PLAY_FAILED,"load image timeout")});this._readyLock=h,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 M(I.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 M(I.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),ai/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 Fc({url:r,height:e,width:t}){const i=ei("img",{style:{width:`${t}px`,height:`${e}px`},attributes:{crossOrigin:"anonymous"}});return i.src=r,i}class ci extends si{constructor(t){super();b(this,"id",Qe());b(this,"_track");b(this,"_element");t instanceof MediaStreamTrack?(this._track=new ti(t),this._bindTrackEvent(this._track)):t instanceof Rt?(this._element=t,t.addReferenceTrack(this)):t instanceof jn&&(this._element=t)}_bindTrackEvent(t){t.on("ended",this._handleTrackEnded.bind(this)),t.on("mute",()=>{this.emit(Q.MUTE)}),t.on("unmute",()=>{this.emit(Q.UNMUTE)})}_handleTrackEnded(){this.emit(Q.ENDED),this.destroy()}handlePlayFailed(){this.emit(Q.PLAY_FAILED)}track(){if(this.logger.info("track"),!this.available())throw new M(I.TRACK_NOT_AVAILABLE,"track is not available when creating MediaStreamTrack");if(this._track)return this._track.target;if(!this._element)throw new M(I.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 M(I.TRACK_NOT_AVAILABLE,"track is not available when creating HTMLMediaElement");if(this._element)return this._element.element();if(!this._track)throw new M(I.UNEXPECTED_TYPE,"got this._track falsy");const t=new Rt(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 lr extends ci{constructor(){super(...arguments);b(this,"kind",B.AUDIO);b(this,"_node")}node(){if(this.logger.info("node",this.id),!this.available())throw new M(I.TRACK_NOT_AVAILABLE,"track is not avaiable when creating node");if(this._node)return this._node;const t=new Ec(this);return this._node=t,t}element(){if(this.logger.info("element",this.id),!this.available())throw new M(I.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 M(I.UNEXPECTED_TYPE,"source should be HTMLMediaElement");return i}if(!this._track)throw new M(I.UNEXPECTED_TYPE,"got this._track falsy");const t=new Rt(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 jc extends lr{constructor(){super(...arguments);b(this,"logger",new ne("MicrophoneAudioTrack"))}}class Hc extends lr{constructor(){super(...arguments);b(this,"logger",new ne("ScreenAudioTrack"))}}class Hn extends lr{constructor(){super(...arguments);b(this,"logger",new ne("MediaAudioTrack"))}handlePlayFailed(){this.emit(Q.PLAY_FAILED)}async play(){if(this._element){if(!(this._element instanceof Rt))throw new M(I.UNEXPECTED_TYPE,"element is not TrackMediaElement");return this._element._playElement()}}}class $c extends lr{constructor(){super(...arguments);b(this,"logger",new ne("CustomAudioTrack"))}}let Kc=1;const ui=new ne("PromiseQueue");class qc{constructor(e){b(this,"lockingPromise",Promise.resolve());b(this,"locks",0);b(this,"name","");b(this,"lockId");b(this,"closeReason");this.lockId=Kc++,e&&(this.name=e),ui.info(`lock-${this.name}-${this.lockId}`,"is created.")}get isLocked(){return this.locks>0}lock(){this.locks+=1,ui.info(`lock-${this.name}-${this.lockId}`,`locked, current queue ${this.locks}.`);let e;const t=new Promise(n=>{e=()=>{this.locks-=1,ui.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 Wc=300,Jc=3e3,be=new ne("Devices");class Zc extends si{constructor(){super();b(this,"_deviceMap",{audioinput:[],audiooutput:[],videoinput:[]});b(this,"_permissions",{[B.AUDIO]:!1,[B.VIDEO]:!1});b(this,"_changedQueue",new qc("device changed queue"));this._init()}async _init(){this._initDeviceChanged(),await this._initPermissionChanged();const t=Wn(this._permissions);t.length>0&&this._refreshDevices(t)}_initDeviceChanged(){if(be.info("_initDeviceChanged","invoked"),!ze.ondevicechange()){be.error("_initDeviceChanged","no supported, use timer instead"),setInterval(()=>{this._handleDeviceChanged()},Jc);return}ze.ondevicechange()&&navigator.mediaDevices.addEventListener("devicechange",()=>{be.info("devicechange"),setTimeout(()=>{this._handleDeviceChanged()},Wc)})}async _initPermissionChanged(){if(!ze.permissionQuery()){be.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",()=>{be.info("_initPermissionChanged","update permission for audio"),this._permissions.audio=t.state==="granted"})}catch(t){be.error("_initPermissionChanged",t)}try{const t=await navigator.permissions.query({name:"camera"});this._permissions.video=t.state==="granted",t.addEventListener("change",()=>{be.info("_initPermissionChanged","update permission for video"),this._permissions.video=t.state==="granted"})}catch(t){be.error("_initPermissionChanged",t)}}async _refreshDevices(t){if(!ze.mediaDevices())throw new M(I.NOT_SUPPORTED,"mediaDevices is not supported");if(t.length===0)throw new M(I.UNEXPECTED_TYPE,"kinds expect to containt values");let i;if(!ze.isolateEnumerateDevices()){const a={};t.forEach(o=>{a[o]=!0}),i=await navigator.mediaDevices.getUserMedia(a)}let n=await navigator.mediaDevices.enumerateDevices();i&&$n(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(!ze.getUserMedia())return{grant:!1,reason:new M(I.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),$n(s),{grant:!0}):{grant:!1,reason:new M(I.UNEXPECTED_TYPE,"get stream falsy")}}catch(n){return{grant:!1,reason:new M(I.CAPTURE_FAILED,"acquire user permission failed",n)}}}async _handleDeviceChanged(){be.info("_handleDeviceChanged",this._deviceMap,this._permissions);const t=await this._changedQueue.lock();try{const i=qn(this._deviceMap);let n=[];const s=Wn(this._permissions);s.length===0?be.warn("_handleDeviceChanged","no permission, use empty list"):(await this._refreshDevices(s),n=qn(this._deviceMap)),n.forEach(a=>{i.findIndex(h=>Kn(h,a))!==-1||this.emit("onDeviceStateChanged",{deviceInfo:a,deviceState:"active"})}),i.forEach(a=>{n.findIndex(h=>Kn(h,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 M(I.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 $n(r){r.getTracks().forEach(e=>e.stop())}function Kn(r,e){return r.deviceId===e.deviceId}function qn(r){return Array.from([...r.audioinput.values(),...r.videoinput.values(),...r.audiooutput.values()])}function Wn(r){const e=[];return r.audio&&e.push(B.AUDIO),r.video&&e.push(B.VIDEO),e}const hi=new Zc,di={LeftToRight:"LeftToRight",UpToDown:"UpToDown",All:"All"};class li{constructor(){b(this,"id",Qe())}position(e,t){return new Xc(this,{x:e,y:t})}scale(e){return new Jn(this,{s:e})}mirror(e){return new Jn(this,{mirrorType:e})}available(){var e;return((e=this.previousNode)==null?void 0:e.available())??!1}}class Xc extends li{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 Jn extends li{constructor(t,i){super();b(this,"previousNode");b(this,"_scaleParams",[1,1]);if(this.previousNode=t,i.mirrorType)switch(i.mirrorType){case di.LeftToRight:this._scaleParams=[-1,1];break;case di.UpToDown:this._scaleParams=[1,-1];break;case di.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 Yc extends li{constructor(t){super();b(this,"previousNode",null);b(this,"_source");this._source=t}available(){return this._source.available()}}class pr extends Yc{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 pr(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 Qc extends ci{constructor(){super(...arguments);b(this,"logger",new ne("PictureTrack"));b(this,"kind",B.VIDEO)}element(){const t=super.element();if(!(t instanceof HTMLImageElement))throw new M(I.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 M(I.TRACK_NOT_AVAILABLE,"track is not avaiable when creating node");const t=new pr(this);return this.logger.info("node",t),t}destroy(){this.logger.warn("destroy"),super.destroy()}}const eu=500;class fr extends ci{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(Q.SIZE_CHANGE,{width:n,height:s})},eu)})}element(){const t=super.element();if(!(t instanceof HTMLVideoElement))throw new M(I.UNEXPECTED_TYPE,"source should be HTMLVideoElement");return t}node(){if(!this.available())throw new M(I.TRACK_NOT_AVAILABLE,"track is not avaiable when creating node");return new pr(this)}destroy(){clearTimeout(this.sizeChangeTimer),super.destroy()}}class tu extends fr{constructor(t){super(t);b(this,"logger",new ne("CameraVideoTrack"));this.watchSizeChangeOnce()}height(){const{height:t}=this.track().getSettings();return t??0}width(){const{width:t}=this.track().getSettings();return t??0}}class ru extends fr{constructor(t){super(t);b(this,"logger",new ne("ScreenVideoTrack"));this.watchSizeChangeOnce()}height(){const{height:t}=this.track().getSettings();return t??0}width(){const{width:t}=this.track().getSettings();return t??0}}class iu extends fr{constructor(){super(...arguments);b(this,"logger",new ne("MediaVideoTrack"))}height(){const{videoHeight:t}=this.element();return t??0}width(){const{videoWidth:t}=this.element();return t??0}}class nu extends fr{constructor(){super(...arguments);b(this,"logger",new ne("CustomVideoTrack"))}height(){const{height:t}=this.track().getSettings();return t??0}width(){const{width:t}=this.track().getSettings();return t??0}}async function Zn(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 ke=new ne("Capture");async function su(r){return hi.enumerateDevices(r)}async function ou(r){hi.removeAllListeners("onDeviceStateChanged"),hi.on("onDeviceStateChanged",r)}async function au(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 M(I.CAPTURE_FAILED,"got error when capturing camera",n)}const i=t.getVideoTracks()[0];if(r!=null&&r.frameRate&&e&&Zn(i,r),!i)throw new M(I.UNEXPECTED_TYPE,"got falsy in track");return new tu(i)}async function cu(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),ze.settingResolutionInGetDisplayMedia()||(s=!0),!ze.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 M(I.CAPTURE_FAILED,"got error when capture screen",u)}const o=a.getVideoTracks()[0],h=a.getAudioTracks()[0];if(!o)throw new M(I.UNEXPECTED_TYPE,"got falsy in videoTrack");typeof s!="boolean"&&typeof s.frameRate=="number"&&t&&Zn(o,s);const c=[];return c.push(new ru(o)),h&&c.push(new Hc(h)),c}async function uu(r){const{url:e,audio:t,video:i,loop:n}=r,s=new Rt({url:e,kind:i?B.VIDEO:B.AUDIO,loop:n}),a=[];return t&&a.push(new Hn(s)),i&&a.push(new iu(s)),await s.isReady(),a}async function hu(r){const e=new jn(r);return await e.isReady(),new Qc(e)}async function du(r){let e;try{const i={audio:r??!0};e=await navigator.mediaDevices.getUserMedia(i)}catch(i){throw new M(I.CAPTURE_FAILED,"got error when capturing microphone",i)}const t=e.getAudioTracks()[0];if(!t)throw new M(I.UNEXPECTED_TYPE,"got falsy in track");return new jc(t)}function lu(r){if(!r||r.kind!=="video")throw new M(I.UNEXPECTED_TYPE,"error custom video track type");return new nu(r)}function pu(r){if(!r||r.kind!=="audio")throw new M(I.UNEXPECTED_TYPE,"error custom audio track type");return new $c(r)}const fu=ke.invoke(su,"enumerateInputDevices"),mu=ke.invoke(au,"createCameraTrack"),_u=ke.invoke(hu,"createPictureTrack"),Xn=ke.invoke(uu,"createMediaTracks"),gu=ke.invoke(du,"createMicrophoneTrack"),vu=ke.invoke(cu,"createScreenTracks"),yu=ke.invoke(ou,"onDeviceChanged"),bu=ke.invoke(lu,"createCustomVideoTrack"),Su=ke.invoke(pu,"createCustomAudioTrack");var pi=(r=>(r.PAUSING="pausing",r))(pi||{});const Eu={sampleRate:48e3,keepAlive:!0},Yn=new Map,Dt=new ne("Mixer");class Cu extends si{constructor(t){super();b(this,"id",Qe());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=()=>{xt(this._context).then(n)};i.forEach(a=>{t.addEventListener(a,s,!1)})});Dt.info("ctor",t),this._config={...Eu,...t},this._context=wu(this._config),this._bindContextEvent(this._context)}mix(t){Dt.info("mix",t),xt(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 Dt.info("resume"),xt(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")&&(Dt.info("_emit_",pi.PAUSING),this.emit(pi.PAUSING))}track(){if(Dt.info("track"),xt(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 wu(r){const{sampleRate:e,keepAlive:t}=r;let i=Yn.get(e);return(!i||i.state==="closed")&&(i=new AudioContext({sampleRate:e}),Yn.set(e,i)),t&&(i.onstatechange=()=>{xt(i)}),i}function xt(r){return r.state==="suspended"||r.state==="interrupted"?r.resume():Promise.resolve()}const Tu=r=>(e,t)=>(r.set(e,t),t),Qn=Number.MAX_SAFE_INTEGER===void 0?9007199254740991:Number.MAX_SAFE_INTEGER,es=536870912,ts=es*2,zu=(r,e)=>t=>{const i=e.get(t);let n=i===void 0?t.size:i<ts?i+1:0;if(!t.has(n))return r(t,n);if(t.size<es){for(;t.has(n);)n=Math.floor(Math.random()*ts);return r(t,n)}if(t.size>Qn)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()*Qn);return r(t,n)},rs=new WeakMap,ku=Tu(rs),Be=zu(ku,rs),Au=r=>r.method!==void 0&&r.method==="call",Ru=r=>typeof r.id=="number"&&typeof r.result=="boolean",is=((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(Au(c)){const{params:{timerId:u,timerType:l}}=c;if(l==="interval"){const d=e.get(u);if(typeof d===void 0)throw new Error("The timer is in an undefined state.");if(typeof d=="number"){const p=i.get(d);if(p===void 0||p.timerId!==u||p.timerType!==l)throw new Error("The timer is in an undefined state.")}else typeof d=="function"&&d()}else if(l==="timeout"){const d=t.get(u);if(typeof d===void 0)throw new Error("The timer is in an undefined state.");if(typeof d=="number"){const p=i.get(d);if(p===void 0||p.timerId!==u||p.timerType!==l)throw new Error("The timer is in an undefined state.")}else typeof d=="function"&&(d(),t.delete(u))}}else if(Ru(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:d,timerType:p}=l;i.delete(u),p==="interval"?e.delete(d):t.delete(d)}else{const{error:{message:u}}=c;throw new Error(u)}}),{clearInterval:c=>{if(typeof e.get(c)=="function"){const u=Be(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=Be(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 d=Be(e);return e.set(d,()=>{c(...l),typeof e.get(d)=="function"&&n.postMessage({id:null,method:"set",params:{delay:u,now:performance.timeOrigin+performance.now(),timerId:d,timerType:"interval"}})}),n.postMessage({id:null,method:"set",params:{delay:u,now:performance.timeOrigin+performance.now(),timerId:d,timerType:"interval"}}),d},setTimeout:(c,u=0,...l)=>{const d=Be(t);return t.set(d,()=>c(...l)),n.postMessage({id:null,method:"set",params:{delay:u,now:performance.timeOrigin+performance.now(),timerId:d,timerType:"timeout"}}),d}}},`(()=>{"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})}}))})();`),Du=r=>is().clearTimeout(r),xu=(...r)=>is().setTimeout(...r),Ou=r=>r.method!==void 0&&r.method==="call",Mu=r=>typeof r.id=="number"&&typeof r.result=="boolean",Iu=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(Ou(c)){const{params:{timerId:u,timerType:l}}=c;if(l==="interval"){const d=e.get(u);if(typeof d===void 0)throw new Error("The timer is in an undefined state.");if(typeof d=="number"){const p=i.get(d);if(p===void 0||p.timerId!==u||p.timerType!==l)throw new Error("The timer is in an undefined state.")}else typeof d=="function"&&d()}else if(l==="timeout"){const d=t.get(u);if(typeof d===void 0)throw new Error("The timer is in an undefined state.");if(typeof d=="number"){const p=i.get(d);if(p===void 0||p.timerId!==u||p.timerType!==l)throw new Error("The timer is in an undefined state.")}else typeof d=="function"&&(d(),t.delete(u))}}else if(Mu(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:d,timerType:p}=l;i.delete(u),p==="interval"?e.delete(d):t.delete(d)}else{const{error:{message:u}}=c;throw new Error(u)}}),{clearInterval:c=>{if(typeof e.get(c)=="function"){const u=Be(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=Be(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 d=Be(e);return e.set(d,()=>{c(...l),typeof e.get(d)=="function"&&n.postMessage({id:null,method:"set",params:{delay:u,now:performance.timeOrigin+performance.now(),timerId:d,timerType:"interval"}})}),n.postMessage({id:null,method:"set",params:{delay:u,now:performance.timeOrigin+performance.now(),timerId:d,timerType:"interval"}}),d},setTimeout:(c,u=0,...l)=>{const d=Be(t);return t.set(d,()=>c(...l)),n.postMessage({id:null,method:"set",params:{delay:u,now:performance.timeOrigin+performance.now(),timerId:d,timerType:"timeout"}}),d}}},Pu={width:640,height:480,frameRate:30,backgroundColor:"#000000"},mr=new ne("View");class Lu{constructor(e){b(this,"id",Qe());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,"_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)},ai/this._config.frameRate),this._raqId=requestAnimationFrame(this._paintLoop)});mr.info("ctor",e),this._config={...Pu,...e};const{context:t,canvas:i}=Nn(this._config);this._context=t,this._canvas=i,this._customSetTimeout=xu,this._customClearTimeout=Du}setWorkerTimerScriptUrl(e){if(this._workerTimerScriptUrl=e,this._workerTimerScriptUrl){const t=Iu(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+=ai/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=[]){mr.info("draw",e),this._nodeList=e}_drawOnCanvas(){if(this._shouldDraw(Date.now())){this._drawBackground();for(const e of this._nodeList){let t=e;if(t.available()){for(;t;)t.paint(this._context),t=t.previousNode;this._context.setTransform(1,0,0,1,0,0)}}}}_drawBackground(){const{backgroundColor:e,width:t,height:i}=this._config;this._context.clearRect(0,0,t,i),e&&(this._context.fillStyle=e,this._context.fillRect(0,0,t,i))}track(){if(mr.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 mr.info("element"),this._paintLoop(),this._canvas}stop(){this._stopped=!0}}function Uu(){return Math.random().toString(36).slice(-8)}const Nu=`
|
|
1
|
+
(function(ye,re){typeof exports=="object"&&typeof module<"u"?module.exports=re():typeof define=="function"&&define.amd?define(re):(ye=typeof globalThis<"u"?globalThis:ye||self,ye.vePusher=re())})(this,function(){"use strict";var G_=Object.defineProperty;var B_=(ye,re,Ge)=>re in ye?G_(ye,re,{enumerable:!0,configurable:!0,writable:!0,value:Ge}):ye[re]=Ge;var b=(ye,re,Ge)=>B_(ye,typeof re!="symbol"?re+"":re,Ge);var oc,ac,cc,uc,dc,hc;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 re(r){return r&&r.__esModule&&Object.prototype.hasOwnProperty.call(r,"default")?r.default:r}var Ge={exports:{}},Pn;function vc(){return Pn||(Pn=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}(Ge)),Ge.exports}var yc=vc();const Be=re(yc);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||{}),Se=(r=>(r.DeviceCaptured="deviceCaptured",r.DeviceStopCapture="deviceStopCapture",r.Error="error",r.Interrupted="interrupted",r))(Se||{}),$=(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))($||{}),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||{}),In=(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))(In||{}),Ln=(r=>(r.STANDARD="48000x40",r.HIGH="48000x128",r))(Ln||{}),rt=(r=>(r.VideoStreamChange="videoStreamChange",r.AudioStreamChange="audioStreamChange",r))(rt||{}),Un=(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))(Un||{});const Nn={SizeChange:"sizeChange"};var oi=(r=>(r.Portrait="portrait",r.Landscape="landscape",r))(oi||{});const Gn="720p-1",Bn="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||{}),ai=(r=>(r[r.PushUrlInvalid=1001]="PushUrlInvalid",r[r.ReconnectTimeout=1002]="ReconnectTimeout",r))(ai||{}),I=(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))(I||{}),B=(r=>(r.AUDIO="audio",r.VIDEO="video",r))(B||{}),ie=(r=>(r.ENDED="ended",r.MUTE="mute",r.UNMUTE="unmute",r.PLAY_FAILED="play-failed",r.SIZE_CHANGE="size-change",r))(ie||{});const ee=[];for(let r=0;r<256;++r)ee.push((r+256).toString(16).slice(1));function bc(r,e=0){return(ee[r[e+0]]+ee[r[e+1]]+ee[r[e+2]]+ee[r[e+3]]+"-"+ee[r[e+4]]+ee[r[e+5]]+"-"+ee[r[e+6]]+ee[r[e+7]]+"-"+ee[r[e+8]]+ee[r[e+9]]+"-"+ee[r[e+10]]+ee[r[e+11]]+ee[r[e+12]]+ee[r[e+13]]+ee[r[e+14]]+ee[r[e+15]]).toLowerCase()}let ci;const Sc=new Uint8Array(16);function Ec(){if(!ci){if(typeof crypto>"u"||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");ci=crypto.getRandomValues.bind(crypto)}return ci(Sc)}const Vn={randomUUID:typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};function it(r,e,t){var n;if(Vn.randomUUID&&!r)return Vn.randomUUID();r=r||{};const i=r.random??((n=r.rng)==null?void 0:n.call(r))??Ec();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,bc(i)}class Fn{constructor(){b(this,"id",it());b(this,"_nextNode");b(this,"_track");b(this,"_destNode")}gain(e){if(this._nextNode instanceof jn)return this._nextNode.g=e,this._nextNode;const t=new jn(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 jn extends Fn{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 Cc extends Fn{constructor(t){super();b(this,"previousNode",null);b(this,"source");this.source=t}available(){return this.source.available()}destroy(){super.destroy()}}class wc extends Cc{constructor(){super(...arguments);b(this,"_node")}createNode(t){if(this._node)return this._node;let i;if(this.source instanceof Yn){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 M 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,M.prototype)}toString(){return`VeCapture Error: ${this.code} ${this.message}`}}const Hn={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"}},$n="__debug__",Tc="[VE-CAPTURE]";function zc(){if(typeof location>"u"||typeof localStorage>"u")return!1;let r=!1;return location.href.includes($n)&&(r=!0),localStorage.getItem($n)&&(r=!0),r}let ae=class{constructor(e){b(this,"moduleName");this.moduleName=e}print(e,t,...i){const n=kc();zc()&&console.log(`${n}-${Tc}%c[${Hn[e].text}]%c[${this.moduleName}][${t}]`,`background-color:${Hn[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 kc(){const r=new Date;return`${r.toTimeString().split(" ")[0]}:${r.getMilliseconds().toString().padStart(3,"0")}`}function ui(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 qn({width:r,height:e}){const t=document.createElement("canvas"),i=t.getContext("2d");if(!i)throw new M(I.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 di{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 q=()=>typeof window>"u";function j(){return navigator.userAgent.toLowerCase()}function hi(r=j()){let e="none";return q()||(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 Kn=hi()==="firefox",vr=hi()==="safari";hi(),!q()&&/crios/i.test(j()),!q()&&/edg\//i.test(j()),!q()&&/edgA/i.test(j()),!q()&&/edgios/i.test(j()),!q()&&/dingtalk/i.test(j()),!q()&&/opr\//.test(j()),!q()&&/(iphone|ipod)/i.exec(j()),!q()&&(/(ipad)/i.exec(j())||/macintosh/i.test(j())&&"ontouchend"in document),!q()&&/macintosh/i.test(j()),!q()&&/micromessenger/i.test(j()),!q()&&j().includes("mobile"),!q()&&/sm-\w+/i.test(j());const Rc=!q()&&!!/(iphone|ipad|ipod)/i.exec(j());!q()&&/android/i.test(j()),!q()&&/windows/i.test(j()),!q()&&/openharmony/i.test(j());let Wn="0";const Ac=!q()&&((oc=j().match(/version\/(\d+)/i))==null?void 0:oc[1]);vr&&Ac&&(Wn=(ac=navigator.userAgent.match(/version\/(\d+\.\d+)/i))==null?void 0:ac[1]),!q()&&((cc=j().match(/firefox\/(\d+)/i))==null||cc[1]);const li=Wn;!q()&&((dc=(uc=j().match(/ ([\d_]+) like mac os x/i))==null?void 0:uc[1])==null||dc.split("_").map(r=>parseInt(r))),!q()&&((hc=j().match(/chrome\/(\d+)/i))==null||hc[1]);function Dc(){var r;return!!((r=navigator==null?void 0:navigator.permissions)!=null&&r.query)}function pi(){return!!(navigator!=null&&navigator.mediaDevices)}function xc(){var r;return pi()&&!!((r=navigator==null?void 0:navigator.mediaDevices)!=null&&r.getUserMedia)}function Pc(){return!!Promise.withResolvers}function Oc(){return!(vr&&li==="16.1")}function Mc(){return!(vr&&li&&["16.1","16.2","16.3"].includes(li))}function Ic(){return!Kn}function Lc(){return typeof CanvasCaptureMediaStreamTrack<"u"}function Uc(r){return typeof r.requestFrame=="function"}function Nc(){return!!pi()&&typeof navigator.mediaDevices.ondevicechange<"u"&&typeof navigator.mediaDevices.addEventListener=="function"}const Re={permissionQuery:Dc,mediaDevices:pi,settingResolutionInGetDisplayMedia:Oc,promiseWithResolvers:Pc,getUserMedia:xc,isolateEnumerateDevices:Ic,supportIdealParamsInGetDisplayMedia:Mc,canvasCaptureMediaStreamTrack:Lc,requestFrameOnMediaStream:Uc,ondevicechange:Nc};function Gc(){if(Re.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 Jn(r={}){const{timeout:e,message:t}={timeout:0,message:new M(I.UNEXPECTED_ERROR,"unexpected timeout"),...r},{promise:i,resolve:n,reject:s}=Gc();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 Bc={playsinline:"","webkit-playsinline":"","x5-playsinline":"","x5-video-player-type":"h5","x-webkit-airplay":"allow",preload:"metadata",muted:"",crossOrigin:"anonymous"},Vc={playsinline:"","webkit-playsinline":"",preload:"metadata",muted:"",crossOrigin:"anonymous"};class Pt{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=Fc(o),this._stream=o}else if(e.url)i=jc(e);else throw new M(I.UNEXPECTED_TYPE,`got ${typeof e}, expected: MediaStreamTrack or constraints for creating element`);const{promise:n,resolve:s,reject:a}=Jn({timeout:2e3,message:new M(I.PLAY_FAILED,"load media timeout")});this._readyLock=n,this._releaseReadyLock=s,this._throwReadyLock=a,this._element=new di(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 M(I.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 M(I.UNEXPECTED_TYPE,"got empty list of video tracks");return i[0]}throw new M(I.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 M(I.PLAY_FAILED,"play element failed",e)}}_bindPlayerEvent(e){e.on("loadedmetadata",()=>{this._releaseReadyLock()}),e.on("error",()=>{this._throwReadyLock(new M(I.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 Fc(r){let e="audio";r.getVideoTracks().length>0&&(e="video");const t=Zn(e==="video"?B.VIDEO:B.AUDIO);return t.srcObject=r,t}function jc(r){const{url:e,kind:t,loop:i}=r,n=Zn(t);return n.src=e,n.loop=i,n}function Zn(r){if(r===B.VIDEO)return ui(B.VIDEO,{style:{width:"100%",height:"100%"},attributes:Bc});if(r===B.AUDIO)return ui(B.AUDIO,{style:{display:"none"},attributes:Vc});throw new M(I.UNEXPECTED_TYPE,`got ${r}, expected: audio, video`)}class fi extends Be{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 mi(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 M(I.UNEXPECTED_TYPE,"unexpected constraints type")}const yr=1e3;class Xn{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=mi(e.width),i=mi(e.height),n=mi(e.frameRate);this._config={width:t,height:i,frameRate:n};const{context:s,canvas:a}=qn({width:t,height:i});this._context=s,this._canvas=a;const o=Hc({url:e.url,width:t,height:i});this._image=new di(o);const{promise:d,resolve:c,reject:u}=Jn({timeout:2e3,message:new M(I.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 M(I.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 M(I.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),yr/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 Hc({url:r,height:e,width:t}){const i=ui("img",{style:{width:`${t}px`,height:`${e}px`},attributes:{crossOrigin:"anonymous"}});return i.src=r,i}class _i extends fi{constructor(t){super();b(this,"id",it());b(this,"_track");b(this,"_element");t instanceof MediaStreamTrack?(this._track=new di(t),this._bindTrackEvent(this._track)):t instanceof Pt?(this._element=t,t.addReferenceTrack(this)):t instanceof Xn&&(this._element=t)}_bindTrackEvent(t){t.on("ended",this._handleTrackEnded.bind(this)),t.on("mute",()=>{this.emit(ie.MUTE)}),t.on("unmute",()=>{this.emit(ie.UNMUTE)})}_handleTrackEnded(){this.emit(ie.ENDED),this.destroy()}handlePlayFailed(){this.emit(ie.PLAY_FAILED)}track(){if(this.logger.info("track"),!this.available())throw new M(I.TRACK_NOT_AVAILABLE,"track is not available when creating MediaStreamTrack");if(this._track)return this._track.target;if(!this._element)throw new M(I.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 M(I.TRACK_NOT_AVAILABLE,"track is not available when creating HTMLMediaElement");if(this._element)return this._element.element();if(!this._track)throw new M(I.UNEXPECTED_TYPE,"got this._track falsy");const t=new Pt(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 br extends _i{constructor(){super(...arguments);b(this,"kind",B.AUDIO);b(this,"_node")}node(){if(this.logger.info("node",this.id),!this.available())throw new M(I.TRACK_NOT_AVAILABLE,"track is not avaiable when creating node");if(this._node)return this._node;const t=new wc(this);return this._node=t,t}element(){if(this.logger.info("element",this.id),!this.available())throw new M(I.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 M(I.UNEXPECTED_TYPE,"source should be HTMLMediaElement");return i}if(!this._track)throw new M(I.UNEXPECTED_TYPE,"got this._track falsy");const t=new Pt(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 $c extends br{constructor(){super(...arguments);b(this,"logger",new ae("MicrophoneAudioTrack"))}}class qc extends br{constructor(){super(...arguments);b(this,"logger",new ae("ScreenAudioTrack"))}}class Yn extends br{constructor(){super(...arguments);b(this,"logger",new ae("MediaAudioTrack"))}handlePlayFailed(){this.emit(ie.PLAY_FAILED)}async play(){if(this._element){if(!(this._element instanceof Pt))throw new M(I.UNEXPECTED_TYPE,"element is not TrackMediaElement");return this._element._playElement()}}}class Kc extends br{constructor(){super(...arguments);b(this,"logger",new ae("CustomAudioTrack"))}}let Wc=1;const gi=new ae("PromiseQueue");class Jc{constructor(e){b(this,"lockingPromise",Promise.resolve());b(this,"locks",0);b(this,"name","");b(this,"lockId");b(this,"closeReason");this.lockId=Wc++,e&&(this.name=e),gi.info(`lock-${this.name}-${this.lockId}`,"is created.")}get isLocked(){return this.locks>0}lock(){this.locks+=1,gi.info(`lock-${this.name}-${this.lockId}`,`locked, current queue ${this.locks}.`);let e;const t=new Promise(n=>{e=()=>{this.locks-=1,gi.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 Zc=300,Xc=3e3,Ee=new ae("Devices");class Yc extends fi{constructor(){super();b(this,"_deviceMap",{audioinput:[],audiooutput:[],videoinput:[]});b(this,"_permissions",{[B.AUDIO]:!1,[B.VIDEO]:!1});b(this,"_changedQueue",new Jc("device changed queue"));this._init()}async _init(){this._initDeviceChanged(),await this._initPermissionChanged();const t=rs(this._permissions);t.length>0&&this._refreshDevices(t)}_initDeviceChanged(){if(Ee.info("_initDeviceChanged","invoked"),!Re.ondevicechange()){Ee.error("_initDeviceChanged","no supported, use timer instead"),setInterval(()=>{this._handleDeviceChanged()},Xc);return}Re.ondevicechange()&&navigator.mediaDevices.addEventListener("devicechange",()=>{Ee.info("devicechange"),setTimeout(()=>{this._handleDeviceChanged()},Zc)})}async _initPermissionChanged(){if(!Re.permissionQuery()){Ee.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",()=>{Ee.info("_initPermissionChanged","update permission for audio"),this._permissions.audio=t.state==="granted"})}catch(t){Ee.error("_initPermissionChanged",t)}try{const t=await navigator.permissions.query({name:"camera"});this._permissions.video=t.state==="granted",t.addEventListener("change",()=>{Ee.info("_initPermissionChanged","update permission for video"),this._permissions.video=t.state==="granted"})}catch(t){Ee.error("_initPermissionChanged",t)}}async _refreshDevices(t){if(!Re.mediaDevices())throw new M(I.NOT_SUPPORTED,"mediaDevices is not supported");if(t.length===0)throw new M(I.UNEXPECTED_TYPE,"kinds expect to containt values");let i;if(!Re.isolateEnumerateDevices()){const a={};t.forEach(o=>{a[o]=!0}),i=await navigator.mediaDevices.getUserMedia(a)}let n=await navigator.mediaDevices.enumerateDevices();i&&Qn(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(!Re.getUserMedia())return{grant:!1,reason:new M(I.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),Qn(s),{grant:!0}):{grant:!1,reason:new M(I.UNEXPECTED_TYPE,"get stream falsy")}}catch(n){return{grant:!1,reason:new M(I.CAPTURE_FAILED,"acquire user permission failed",n)}}}async _handleDeviceChanged(){Ee.info("_handleDeviceChanged",this._deviceMap,this._permissions);const t=await this._changedQueue.lock();try{const i=ts(this._deviceMap);let n=[];const s=rs(this._permissions);s.length===0?Ee.warn("_handleDeviceChanged","no permission, use empty list"):(await this._refreshDevices(s),n=ts(this._deviceMap)),n.forEach(a=>{i.findIndex(d=>es(d,a))!==-1||this.emit("onDeviceStateChanged",{deviceInfo:a,deviceState:"active"})}),i.forEach(a=>{n.findIndex(d=>es(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 M(I.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 Qn(r){r.getTracks().forEach(e=>e.stop())}function es(r,e){return r.deviceId===e.deviceId}function ts(r){return Array.from([...r.audioinput.values(),...r.videoinput.values(),...r.audiooutput.values()])}function rs(r){const e=[];return r.audio&&e.push(B.AUDIO),r.video&&e.push(B.VIDEO),e}const vi=new Yc,yi={LeftToRight:"LeftToRight",UpToDown:"UpToDown",All:"All"};class bi{constructor(){b(this,"id",it())}position(e,t){return new Qc(this,{x:e,y:t})}scale(e){return new is(this,{s:e})}mirror(e){return new is(this,{mirrorType:e})}available(){var e;return((e=this.previousNode)==null?void 0:e.available())??!1}}class Qc extends bi{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 is extends bi{constructor(t,i){super();b(this,"previousNode");b(this,"_scaleParams",[1,1]);if(this.previousNode=t,i.mirrorType)switch(i.mirrorType){case yi.LeftToRight:this._scaleParams=[-1,1];break;case yi.UpToDown:this._scaleParams=[1,-1];break;case yi.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 eu extends bi{constructor(t){super();b(this,"previousNode",null);b(this,"_source");this._source=t}available(){return this._source.available()}}class Sr extends eu{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 Sr(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 tu extends _i{constructor(){super(...arguments);b(this,"logger",new ae("PictureTrack"));b(this,"kind",B.VIDEO)}element(){const t=super.element();if(!(t instanceof HTMLImageElement))throw new M(I.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 M(I.TRACK_NOT_AVAILABLE,"track is not avaiable when creating node");const t=new Sr(this);return this.logger.info("node",t),t}destroy(){this.logger.warn("destroy"),super.destroy()}}const ru=500;class Er extends _i{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(ie.SIZE_CHANGE,{width:n,height:s})},ru)})}element(){const t=super.element();if(!(t instanceof HTMLVideoElement))throw new M(I.UNEXPECTED_TYPE,"source should be HTMLVideoElement");return t}node(){if(!this.available())throw new M(I.TRACK_NOT_AVAILABLE,"track is not avaiable when creating node");return new Sr(this)}destroy(){clearTimeout(this.sizeChangeTimer),super.destroy()}}class iu extends Er{constructor(t){super(t);b(this,"logger",new ae("CameraVideoTrack"));this.watchSizeChangeOnce()}height(){const{height:t}=this.track().getSettings();return t??0}width(){const{width:t}=this.track().getSettings();return t??0}}class nu extends Er{constructor(t){super(t);b(this,"logger",new ae("ScreenVideoTrack"));this.watchSizeChangeOnce()}height(){const{height:t}=this.track().getSettings();return t??0}width(){const{width:t}=this.track().getSettings();return t??0}}class su extends Er{constructor(){super(...arguments);b(this,"logger",new ae("MediaVideoTrack"))}height(){const{videoHeight:t}=this.element();return t??0}width(){const{videoWidth:t}=this.element();return t??0}}class ou extends Er{constructor(){super(...arguments);b(this,"logger",new ae("CustomVideoTrack"))}height(){const{height:t}=this.track().getSettings();return t??0}width(){const{width:t}=this.track().getSettings();return t??0}}async function ns(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 Ae=new ae("Capture");async function au(r){return vi.enumerateDevices(r)}async function cu(r){vi.removeAllListeners("onDeviceStateChanged"),vi.on("onDeviceStateChanged",r)}async function uu(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 M(I.CAPTURE_FAILED,"got error when capturing camera",n)}const i=t.getVideoTracks()[0];if(r!=null&&r.frameRate&&e&&ns(i,r),!i)throw new M(I.UNEXPECTED_TYPE,"got falsy in track");return new iu(i)}async function du(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),Re.settingResolutionInGetDisplayMedia()||(s=!0),!Re.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 M(I.CAPTURE_FAILED,"got error when capture screen",u)}const o=a.getVideoTracks()[0],d=a.getAudioTracks()[0];if(!o)throw new M(I.UNEXPECTED_TYPE,"got falsy in videoTrack");typeof s!="boolean"&&typeof s.frameRate=="number"&&t&&ns(o,s);const c=[];return c.push(new nu(o)),d&&c.push(new qc(d)),c}async function hu(r){const{url:e,audio:t,video:i,loop:n}=r,s=new Pt({url:e,kind:i?B.VIDEO:B.AUDIO,loop:n}),a=[];return t&&a.push(new Yn(s)),i&&a.push(new su(s)),await s.isReady(),a}async function lu(r){const e=new Xn(r);return await e.isReady(),new tu(e)}async function pu(r){let e;try{const i={audio:r??!0};e=await navigator.mediaDevices.getUserMedia(i)}catch(i){throw new M(I.CAPTURE_FAILED,"got error when capturing microphone",i)}const t=e.getAudioTracks()[0];if(!t)throw new M(I.UNEXPECTED_TYPE,"got falsy in track");return new $c(t)}function fu(r){if(!r||r.kind!=="video")throw new M(I.UNEXPECTED_TYPE,"error custom video track type");return new ou(r)}function mu(r){if(!r||r.kind!=="audio")throw new M(I.UNEXPECTED_TYPE,"error custom audio track type");return new Kc(r)}const _u=Ae.invoke(au,"enumerateInputDevices"),gu=Ae.invoke(uu,"createCameraTrack"),vu=Ae.invoke(lu,"createPictureTrack"),ss=Ae.invoke(hu,"createMediaTracks"),yu=Ae.invoke(pu,"createMicrophoneTrack"),bu=Ae.invoke(du,"createScreenTracks"),Su=Ae.invoke(cu,"onDeviceChanged"),Eu=Ae.invoke(fu,"createCustomVideoTrack"),Cu=Ae.invoke(mu,"createCustomAudioTrack");var Si=(r=>(r.PAUSING="pausing",r))(Si||{});const wu={sampleRate:48e3,keepAlive:!0},os=new Map,Ot=new ae("Mixer");class Tu extends fi{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=()=>{Mt(this._context).then(n)};i.forEach(a=>{t.addEventListener(a,s,!1)})});Ot.info("ctor",t),this._config={...wu,...t},this._context=zu(this._config),this._bindContextEvent(this._context)}mix(t){Ot.info("mix",t),Mt(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 Ot.info("resume"),Mt(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")&&(Ot.info("_emit_",Si.PAUSING),this.emit(Si.PAUSING))}track(){if(Ot.info("track"),Mt(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 zu(r){const{sampleRate:e,keepAlive:t}=r;let i=os.get(e);return(!i||i.state==="closed")&&(i=new AudioContext({sampleRate:e}),os.set(e,i)),t&&(i.onstatechange=()=>{Mt(i)}),i}function Mt(r){return r.state==="suspended"||r.state==="interrupted"?r.resume():Promise.resolve()}const ku=r=>(e,t)=>(r.set(e,t),t),as=Number.MAX_SAFE_INTEGER===void 0?9007199254740991:Number.MAX_SAFE_INTEGER,cs=536870912,us=cs*2,Ru=(r,e)=>t=>{const i=e.get(t);let n=i===void 0?t.size:i<us?i+1:0;if(!t.has(n))return r(t,n);if(t.size<cs){for(;t.has(n);)n=Math.floor(Math.random()*us);return r(t,n)}if(t.size>as)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()*as);return r(t,n)},ds=new WeakMap,Au=ku(ds),Ve=Ru(Au,ds),Du=r=>r.method!==void 0&&r.method==="call",xu=r=>typeof r.id=="number"&&typeof r.result=="boolean",hs=((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(Du(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(xu(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=Ve(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=Ve(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=Ve(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=Ve(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})}}))})();`),Pu=r=>hs().clearTimeout(r),Ou=(...r)=>hs().setTimeout(...r),Mu=r=>r.method!==void 0&&r.method==="call",Iu=r=>typeof r.id=="number"&&typeof r.result=="boolean",Lu=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(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(Iu(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=Ve(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=Ve(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=Ve(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=Ve(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}}},Uu={width:640,height:480,frameRate:30,backgroundColor:"#000000"},Cr=new ae("View");class Nu{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)},yr/this._config.frameRate),this._raqId=requestAnimationFrame(this._paintLoop)});Cr.info("ctor",e),this._config={...Uu,...e};const{context:t,canvas:i}=qn(this._config);this._context=t,this._canvas=i,this._customSetTimeout=Ou,this._customClearTimeout=Pu}setWorkerTimerScriptUrl(e){if(this._workerTimerScriptUrl=e,this._workerTimerScriptUrl){const t=Lu(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+=yr/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=[]){Cr.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>=yr&&(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(Cr.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 Cr.info("element"),this._paintLoop(),this._canvas}stop(){this._stopped=!0}}function Gu(){return Math.random().toString(36).slice(-8)}const Bu=`
|
|
2
2
|
const SMOOTHING_FACTOR = 0.8;
|
|
3
3
|
const MINIMUM_VALUE = 0.00001;
|
|
4
4
|
|
|
@@ -53,20 +53,20 @@ registerProcessor('vumeter', class extends AudioWorkletProcessor {
|
|
|
53
53
|
return true;
|
|
54
54
|
}
|
|
55
55
|
});
|
|
56
|
-
`,Gu=URL.createObjectURL(new Blob([Nu],{type:"application/javascript"}));class Bu{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||Gu);const n=new MediaStream;n.addTrack(e);const s=i.createMediaStreamSource(n),a=new AudioWorkletNode(i,"vumeter");a.port.onmessage=o=>{const h=o.data.volume||0;this._volume=Math.min(h*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 _r{constructor(){this._volumeDetectScriptUrl=void 0}static get instance(){return this._instance||(this._instance=new _r),this._instance}get volumeDetectScriptUrl(){return this._volumeDetectScriptUrl}set volumeDetectScriptUrl(e){this._volumeDetectScriptUrl=e}}class ns extends Ge{constructor(e){super(),this._width=0,this._height=0,this._mediaStream=null,this._nextStream=null,this._trackMap={},this.type=e.type,this.id=Uu(),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 Bu),await this._volumeDetector.start(this.audioTrack,_r.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 lt extends ns{get isVideoStream(){return!0}get isAudioStream(){return!1}bindTrackSizeChangeEvent(e){e.on(Q.SIZE_CHANGE,({width:t,height:i})=>{this._width=t,this._height=i,this.emit(Dn.SizeChange,{width:t,height:i})})}}class gr extends ns{get isVideoStream(){return!1}get isAudioStream(){return!0}}class Vu extends lt{constructor(e){super({type:N.Camera,stream:e}),this._trackMap.video=e.track(),this._width=e.width(),this._height=e.height(),this.bindTrackSizeChangeEvent(e)}get source(){return this._source}get viewNode(){return this.source.node()}get mixerNode(){return null}bindTrackEnd(e){this.source.on(Q.ENDED,e)}destroy(){this.source.destroy()}}var ss=typeof global=="object"&&global&&global.Object===Object&&global,Fu=typeof self=="object"&&self&&self.Object===Object&&self,Ae=ss||Fu||Function("return this")(),Ve=Ae.Symbol,os=Object.prototype,ju=os.hasOwnProperty,Hu=os.toString,Ot=Ve?Ve.toStringTag:void 0;function $u(r){var e=ju.call(r,Ot),t=r[Ot];try{r[Ot]=void 0;var i=!0}catch{}var n=Hu.call(r);return i&&(e?r[Ot]=t:delete r[Ot]),n}var Ku=Object.prototype,qu=Ku.toString;function Wu(r){return qu.call(r)}var Ju="[object Null]",Zu="[object Undefined]",as=Ve?Ve.toStringTag:void 0;function pt(r){return r==null?r===void 0?Zu:Ju:as&&as in Object(r)?$u(r):Wu(r)}function ft(r){return r!=null&&typeof r=="object"}var Xu="[object Symbol]";function vr(r){return typeof r=="symbol"||ft(r)&&pt(r)==Xu}function cs(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 $=Array.isArray,us=Ve?Ve.prototype:void 0,hs=us?us.toString:void 0;function ds(r){if(typeof r=="string")return r;if($(r))return cs(r,ds)+"";if(vr(r))return hs?hs.call(r):"";var e=r+"";return e=="0"&&1/r==-1/0?"-0":e}var Yu=/\s/;function Qu(r){for(var e=r.length;e--&&Yu.test(r.charAt(e)););return e}var eh=/^\s+/;function th(r){return r&&r.slice(0,Qu(r)+1).replace(eh,"")}function Mt(r){var e=typeof r;return r!=null&&(e=="object"||e=="function")}var ls=NaN,rh=/^[-+]0x[0-9a-f]+$/i,ih=/^0b[01]+$/i,nh=/^0o[0-7]+$/i,sh=parseInt;function oh(r){if(typeof r=="number")return r;if(vr(r))return ls;if(Mt(r)){var e=typeof r.valueOf=="function"?r.valueOf():r;r=Mt(e)?e+"":e}if(typeof r!="string")return r===0?r:+r;r=th(r);var t=ih.test(r);return t||nh.test(r)?sh(r.slice(2),t?2:8):rh.test(r)?ls:+r}var ah=1/0,ch=17976931348623157e292;function uh(r){if(!r)return r===0?r:0;if(r=oh(r),r===ah||r===-1/0){var e=r<0?-1:1;return e*ch}return r===r?r:0}function hh(r){var e=uh(r),t=e%1;return e===e?t?e-t:e:0}function dh(r){return r}var lh="[object AsyncFunction]",ph="[object Function]",fh="[object GeneratorFunction]",mh="[object Proxy]";function ps(r){if(!Mt(r))return!1;var e=pt(r);return e==ph||e==fh||e==lh||e==mh}var fi=Ae["__core-js_shared__"],fs=function(){var r=/[^.]+$/.exec(fi&&fi.keys&&fi.keys.IE_PROTO||"");return r?"Symbol(src)_1."+r:""}();function _h(r){return!!fs&&fs in r}var gh=Function.prototype,vh=gh.toString;function et(r){if(r!=null){try{return vh.call(r)}catch{}try{return r+""}catch{}}return""}var yh=/[\\^$.*+?()[\]{}|]/g,bh=/^\[object .+?Constructor\]$/,Sh=Function.prototype,Eh=Object.prototype,Ch=Sh.toString,wh=Eh.hasOwnProperty,Th=RegExp("^"+Ch.call(wh).replace(yh,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function zh(r){if(!Mt(r)||_h(r))return!1;var e=ps(r)?Th:bh;return e.test(et(r))}function kh(r,e){return r==null?void 0:r[e]}function mt(r,e){var t=kh(r,e);return zh(t)?t:void 0}var mi=mt(Ae,"WeakMap");function Ah(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 Rh=9007199254740991,Dh=/^(?:0|[1-9]\d*)$/;function ms(r,e){var t=typeof r;return e=e??Rh,!!e&&(t=="number"||t!="symbol"&&Dh.test(r))&&r>-1&&r%1==0&&r<e}function _s(r,e){return r===e||r!==r&&e!==e}var xh=9007199254740991;function _i(r){return typeof r=="number"&&r>-1&&r%1==0&&r<=xh}function yr(r){return r!=null&&_i(r.length)&&!ps(r)}var Oh=Object.prototype;function gs(r){var e=r&&r.constructor,t=typeof e=="function"&&e.prototype||Oh;return r===t}function Mh(r,e){for(var t=-1,i=Array(r);++t<r;)i[t]=e(t);return i}var Ih="[object Arguments]";function vs(r){return ft(r)&&pt(r)==Ih}var ys=Object.prototype,Ph=ys.hasOwnProperty,Lh=ys.propertyIsEnumerable,gi=vs(function(){return arguments}())?vs:function(r){return ft(r)&&Ph.call(r,"callee")&&!Lh.call(r,"callee")};function Uh(){return!1}var bs=typeof exports=="object"&&exports&&!exports.nodeType&&exports,Ss=bs&&typeof module=="object"&&module&&!module.nodeType&&module,Nh=Ss&&Ss.exports===bs,Es=Nh?Ae.Buffer:void 0,Gh=Es?Es.isBuffer:void 0,br=Gh||Uh,Bh="[object Arguments]",Vh="[object Array]",Fh="[object Boolean]",jh="[object Date]",Hh="[object Error]",$h="[object Function]",Kh="[object Map]",qh="[object Number]",Wh="[object Object]",Jh="[object RegExp]",Zh="[object Set]",Xh="[object String]",Yh="[object WeakMap]",Qh="[object ArrayBuffer]",ed="[object DataView]",td="[object Float32Array]",rd="[object Float64Array]",id="[object Int8Array]",nd="[object Int16Array]",sd="[object Int32Array]",od="[object Uint8Array]",ad="[object Uint8ClampedArray]",cd="[object Uint16Array]",ud="[object Uint32Array]",V={};V[td]=V[rd]=V[id]=V[nd]=V[sd]=V[od]=V[ad]=V[cd]=V[ud]=!0,V[Bh]=V[Vh]=V[Qh]=V[Fh]=V[ed]=V[jh]=V[Hh]=V[$h]=V[Kh]=V[qh]=V[Wh]=V[Jh]=V[Zh]=V[Xh]=V[Yh]=!1;function hd(r){return ft(r)&&_i(r.length)&&!!V[pt(r)]}function dd(r){return function(e){return r(e)}}var Cs=typeof exports=="object"&&exports&&!exports.nodeType&&exports,It=Cs&&typeof module=="object"&&module&&!module.nodeType&&module,ld=It&&It.exports===Cs,vi=ld&&ss.process,ws=function(){try{var r=It&&It.require&&It.require("util").types;return r||vi&&vi.binding&&vi.binding("util")}catch{}}(),Ts=ws&&ws.isTypedArray,yi=Ts?dd(Ts):hd,pd=Object.prototype,fd=pd.hasOwnProperty;function md(r,e){var t=$(r),i=!t&&gi(r),n=!t&&!i&&br(r),s=!t&&!i&&!n&&yi(r),a=t||i||n||s,o=a?Mh(r.length,String):[],h=o.length;for(var c in r)fd.call(r,c)&&!(a&&(c=="length"||n&&(c=="offset"||c=="parent")||s&&(c=="buffer"||c=="byteLength"||c=="byteOffset")||ms(c,h)))&&o.push(c);return o}function _d(r,e){return function(t){return r(e(t))}}var gd=_d(Object.keys,Object),vd=Object.prototype,yd=vd.hasOwnProperty;function zs(r){if(!gs(r))return gd(r);var e=[];for(var t in Object(r))yd.call(r,t)&&t!="constructor"&&e.push(t);return e}function Pt(r){return yr(r)?md(r):zs(r)}var bd=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,Sd=/^\w*$/;function bi(r,e){if($(r))return!1;var t=typeof r;return t=="number"||t=="symbol"||t=="boolean"||r==null||vr(r)?!0:Sd.test(r)||!bd.test(r)||e!=null&&r in Object(e)}var Lt=mt(Object,"create");function Ed(){this.__data__=Lt?Lt(null):{},this.size=0}function Cd(r){var e=this.has(r)&&delete this.__data__[r];return this.size-=e?1:0,e}var wd="__lodash_hash_undefined__",Td=Object.prototype,zd=Td.hasOwnProperty;function kd(r){var e=this.__data__;if(Lt){var t=e[r];return t===wd?void 0:t}return zd.call(e,r)?e[r]:void 0}var Ad=Object.prototype,Rd=Ad.hasOwnProperty;function Dd(r){var e=this.__data__;return Lt?e[r]!==void 0:Rd.call(e,r)}var xd="__lodash_hash_undefined__";function Od(r,e){var t=this.__data__;return this.size+=this.has(r)?0:1,t[r]=Lt&&e===void 0?xd:e,this}function tt(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])}}tt.prototype.clear=Ed,tt.prototype.delete=Cd,tt.prototype.get=kd,tt.prototype.has=Dd,tt.prototype.set=Od;function Md(){this.__data__=[],this.size=0}function Sr(r,e){for(var t=r.length;t--;)if(_s(r[t][0],e))return t;return-1}var Id=Array.prototype,Pd=Id.splice;function Ld(r){var e=this.__data__,t=Sr(e,r);if(t<0)return!1;var i=e.length-1;return t==i?e.pop():Pd.call(e,t,1),--this.size,!0}function Ud(r){var e=this.__data__,t=Sr(e,r);return t<0?void 0:e[t][1]}function Nd(r){return Sr(this.__data__,r)>-1}function Gd(r,e){var t=this.__data__,i=Sr(t,r);return i<0?(++this.size,t.push([r,e])):t[i][1]=e,this}function Re(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])}}Re.prototype.clear=Md,Re.prototype.delete=Ld,Re.prototype.get=Ud,Re.prototype.has=Nd,Re.prototype.set=Gd;var Ut=mt(Ae,"Map");function Bd(){this.size=0,this.__data__={hash:new tt,map:new(Ut||Re),string:new tt}}function Vd(r){var e=typeof r;return e=="string"||e=="number"||e=="symbol"||e=="boolean"?r!=="__proto__":r===null}function Er(r,e){var t=r.__data__;return Vd(e)?t[typeof e=="string"?"string":"hash"]:t.map}function Fd(r){var e=Er(this,r).delete(r);return this.size-=e?1:0,e}function jd(r){return Er(this,r).get(r)}function Hd(r){return Er(this,r).has(r)}function $d(r,e){var t=Er(this,r),i=t.size;return t.set(r,e),this.size+=t.size==i?0:1,this}function De(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])}}De.prototype.clear=Bd,De.prototype.delete=Fd,De.prototype.get=jd,De.prototype.has=Hd,De.prototype.set=$d;var Kd="Expected a function";function Si(r,e){if(typeof r!="function"||e!=null&&typeof e!="function")throw new TypeError(Kd);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(Si.Cache||De),t}Si.Cache=De;var qd=500;function Wd(r){var e=Si(r,function(i){return t.size===qd&&t.clear(),i}),t=e.cache;return e}var Jd=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,Zd=/\\(\\)?/g,Xd=Wd(function(r){var e=[];return r.charCodeAt(0)===46&&e.push(""),r.replace(Jd,function(t,i,n,s){e.push(n?s.replace(Zd,"$1"):i||t)}),e});function Yd(r){return r==null?"":ds(r)}function ks(r,e){return $(r)?r:bi(r,e)?[r]:Xd(Yd(r))}function Cr(r){if(typeof r=="string"||vr(r))return r;var e=r+"";return e=="0"&&1/r==-1/0?"-0":e}function As(r,e){e=ks(e,r);for(var t=0,i=e.length;r!=null&&t<i;)r=r[Cr(e[t++])];return t&&t==i?r:void 0}function Qd(r,e,t){var i=r==null?void 0:As(r,e);return i===void 0?t:i}function el(r,e){for(var t=-1,i=e.length,n=r.length;++t<i;)r[n+t]=e[t];return r}function tl(){this.__data__=new Re,this.size=0}function rl(r){var e=this.__data__,t=e.delete(r);return this.size=e.size,t}function il(r){return this.__data__.get(r)}function nl(r){return this.__data__.has(r)}var sl=200;function ol(r,e){var t=this.__data__;if(t instanceof Re){var i=t.__data__;if(!Ut||i.length<sl-1)return i.push([r,e]),this.size=++t.size,this;t=this.__data__=new De(i)}return t.set(r,e),this.size=t.size,this}function xe(r){var e=this.__data__=new Re(r);this.size=e.size}xe.prototype.clear=tl,xe.prototype.delete=rl,xe.prototype.get=il,xe.prototype.has=nl,xe.prototype.set=ol;function Rs(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 al(){return[]}var cl=Object.prototype,ul=cl.propertyIsEnumerable,Ds=Object.getOwnPropertySymbols,hl=Ds?function(r){return r==null?[]:(r=Object(r),Rs(Ds(r),function(e){return ul.call(r,e)}))}:al;function dl(r,e,t){var i=e(r);return $(r)?i:el(i,t(r))}function xs(r){return dl(r,Pt,hl)}var Ei=mt(Ae,"DataView"),Ci=mt(Ae,"Promise"),wi=mt(Ae,"Set"),Os="[object Map]",ll="[object Object]",Ms="[object Promise]",Is="[object Set]",Ps="[object WeakMap]",Ls="[object DataView]",pl=et(Ei),fl=et(Ut),ml=et(Ci),_l=et(wi),gl=et(mi),Oe=pt;(Ei&&Oe(new Ei(new ArrayBuffer(1)))!=Ls||Ut&&Oe(new Ut)!=Os||Ci&&Oe(Ci.resolve())!=Ms||wi&&Oe(new wi)!=Is||mi&&Oe(new mi)!=Ps)&&(Oe=function(r){var e=pt(r),t=e==ll?r.constructor:void 0,i=t?et(t):"";if(i)switch(i){case pl:return Ls;case fl:return Os;case ml:return Ms;case _l:return Is;case gl:return Ps}return e});var Us=Ae.Uint8Array,vl="__lodash_hash_undefined__";function yl(r){return this.__data__.set(r,vl),this}function bl(r){return this.__data__.has(r)}function wr(r){var e=-1,t=r==null?0:r.length;for(this.__data__=new De;++e<t;)this.add(r[e])}wr.prototype.add=wr.prototype.push=yl,wr.prototype.has=bl;function Sl(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 El(r,e){return r.has(e)}var Cl=1,wl=2;function Ns(r,e,t,i,n,s){var a=t&Cl,o=r.length,h=e.length;if(o!=h&&!(a&&h>o))return!1;var c=s.get(r),u=s.get(e);if(c&&u)return c==e&&u==r;var l=-1,d=!0,p=t&wl?new wr: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;d=!1;break}if(p){if(!Sl(e,function(E,y){if(!El(p,y)&&(f===E||n(f,E,t,i,s)))return p.push(y)})){d=!1;break}}else if(!(f===v||n(f,v,t,i,s))){d=!1;break}}return s.delete(r),s.delete(e),d}function Tl(r){var e=-1,t=Array(r.size);return r.forEach(function(i,n){t[++e]=[n,i]}),t}function zl(r){var e=-1,t=Array(r.size);return r.forEach(function(i){t[++e]=i}),t}var kl=1,Al=2,Rl="[object Boolean]",Dl="[object Date]",xl="[object Error]",Ol="[object Map]",Ml="[object Number]",Il="[object RegExp]",Pl="[object Set]",Ll="[object String]",Ul="[object Symbol]",Nl="[object ArrayBuffer]",Gl="[object DataView]",Gs=Ve?Ve.prototype:void 0,Ti=Gs?Gs.valueOf:void 0;function Bl(r,e,t,i,n,s,a){switch(t){case Gl:if(r.byteLength!=e.byteLength||r.byteOffset!=e.byteOffset)return!1;r=r.buffer,e=e.buffer;case Nl:return!(r.byteLength!=e.byteLength||!s(new Us(r),new Us(e)));case Rl:case Dl:case Ml:return _s(+r,+e);case xl:return r.name==e.name&&r.message==e.message;case Il:case Ll:return r==e+"";case Ol:var o=Tl;case Pl:var h=i&kl;if(o||(o=zl),r.size!=e.size&&!h)return!1;var c=a.get(r);if(c)return c==e;i|=Al,a.set(r,e);var u=Ns(o(r),o(e),i,n,s,a);return a.delete(r),u;case Ul:if(Ti)return Ti.call(r)==Ti.call(e)}return!1}var Vl=1,Fl=Object.prototype,jl=Fl.hasOwnProperty;function Hl(r,e,t,i,n,s){var a=t&Vl,o=xs(r),h=o.length,c=xs(e),u=c.length;if(h!=u&&!a)return!1;for(var l=h;l--;){var d=o[l];if(!(a?d in e:jl.call(e,d)))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<h;){d=o[l];var E=r[d],y=e[d];if(i)var _=a?i(y,E,d,e,r,s):i(E,y,d,r,e,s);if(!(_===void 0?E===y||n(E,y,t,i,s):_)){v=!1;break}m||(m=d=="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 $l=1,Bs="[object Arguments]",Vs="[object Array]",Tr="[object Object]",Kl=Object.prototype,Fs=Kl.hasOwnProperty;function ql(r,e,t,i,n,s){var a=$(r),o=$(e),h=a?Vs:Oe(r),c=o?Vs:Oe(e);h=h==Bs?Tr:h,c=c==Bs?Tr:c;var u=h==Tr,l=c==Tr,d=h==c;if(d&&br(r)){if(!br(e))return!1;a=!0,u=!1}if(d&&!u)return s||(s=new xe),a||yi(r)?Ns(r,e,t,i,n,s):Bl(r,e,h,t,i,n,s);if(!(t&$l)){var p=u&&Fs.call(r,"__wrapped__"),f=l&&Fs.call(e,"__wrapped__");if(p||f){var v=p?r.value():r,m=f?e.value():e;return s||(s=new xe),n(v,m,t,i,s)}}return d?(s||(s=new xe),Hl(r,e,t,i,n,s)):!1}function zi(r,e,t,i,n){return r===e?!0:r==null||e==null||!ft(r)&&!ft(e)?r!==r&&e!==e:ql(r,e,t,i,zi,n)}var Wl=1,Jl=2;function Zl(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],h=r[o],c=a[1];if(a[2]){if(h===void 0&&!(o in r))return!1}else{var u=new xe,l;if(!(l===void 0?zi(c,h,Wl|Jl,i,u):l))return!1}}return!0}function js(r){return r===r&&!Mt(r)}function Xl(r){for(var e=Pt(r),t=e.length;t--;){var i=e[t],n=r[i];e[t]=[i,n,js(n)]}return e}function Hs(r,e){return function(t){return t==null?!1:t[r]===e&&(e!==void 0||r in Object(t))}}function Yl(r){var e=Xl(r);return e.length==1&&e[0][2]?Hs(e[0][0],e[0][1]):function(t){return t===r||Zl(t,r,e)}}function Ql(r,e){return r!=null&&e in Object(r)}function ep(r,e,t){e=ks(e,r);for(var i=-1,n=e.length,s=!1;++i<n;){var a=Cr(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&&_i(n)&&ms(a,n)&&($(r)||gi(r)))}function tp(r,e){return r!=null&&ep(r,e,Ql)}var rp=1,ip=2;function np(r,e){return bi(r)&&js(e)?Hs(Cr(r),e):function(t){var i=Qd(t,r);return i===void 0&&i===e?tp(t,r):zi(e,i,rp|ip)}}function sp(r){return function(e){return e==null?void 0:e[r]}}function op(r){return function(e){return As(e,r)}}function ap(r){return bi(r)?sp(Cr(r)):op(r)}function ki(r){return typeof r=="function"?r:r==null?dh:typeof r=="object"?$(r)?np(r[0],r[1]):Yl(r):ap(r)}function cp(r){return function(e,t,i){for(var n=-1,s=Object(e),a=i(e),o=a.length;o--;){var h=a[++n];if(t(s[h],h,s)===!1)break}return e}}var up=cp();function hp(r,e){return r&&up(r,e,Pt)}function dp(r,e){return function(t,i){if(t==null)return t;if(!yr(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 lp=dp(hp);function pp(r,e){var t=[];return lp(r,function(i,n,s){e(i,n,s)&&t.push(i)}),t}function $s(r,e){var t=$(r)?Rs:pp;return t(r,ki(e))}function fp(r){return function(e,t,i){var n=Object(e);if(!yr(e)){var s=ki(t);e=Pt(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 mp=Math.max;function _p(r,e,t){var i=r==null?0:r.length;if(!i)return-1;var n=t==null?0:hh(t);return n<0&&(n=mp(i+n,0)),Ah(r,ki(e),n)}var Nt=fp(_p);function gp(r,e){return cs(e,function(t){return r[t]})}function Me(r){return r==null?[]:gp(r,Pt(r))}var vp="[object Map]",yp="[object Set]",bp=Object.prototype,Sp=bp.hasOwnProperty;function Ep(r){if(r==null)return!0;if(yr(r)&&($(r)||typeof r=="string"||typeof r.splice=="function"||br(r)||yi(r)||gi(r)))return!r.length;var e=Oe(r);if(e==vp||e==yp)return!r.size;if(gs(r))return!zs(r).length;for(var t in r)if(Sp.call(r,t))return!1;return!0}function Cp(r){return r==null}class wp extends gr{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(Q.ENDED,e)}destroy(){this.source.destroy()}}class Tp extends lt{constructor(e){super({type:N.VideoFile,stream:e});const t=Nt(e,n=>n.kind===B.VIDEO),i=Nt(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(Q.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 zp extends lt{constructor(e){super({type:N.Screen,stream:e});const t=Nt(e,n=>n.kind===B.VIDEO),i=Nt(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(),this.bindTrackSizeChangeEvent(t))}get viewNode(){var e;return((e=this._videoStream)==null?void 0:e.node())??null}get mixerNode(){var e;return((e=this._audioStream)==null?void 0:e.node())??null}bindTrackEnd(e){var t;(t=this._videoStream)==null||t.on(Q.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 kp extends gr{constructor(e){super({type:N.AudioFile,stream:e});const t=Nt(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(Q.ENDED,e)}destroy(){var e;(e=this._audioStream)==null||e.destroy()}}class Ap extends lt{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(Q.ENDED,e)}destroy(){this.source.destroy()}}class Rp extends lt{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(Q.ENDED,e)}destroy(){this.source.destroy()}}class Dp extends gr{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(Q.ENDED,e)}destroy(){var e;(e=this._audioStream)==null||e.destroy()}}const xp=["user","environment"],Op=18e4,Mp=1e4,Ks=1e3;var oe=(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))(oe||{});class _t extends Error{constructor(e,t,i){super(),this.code=e,this.message=t,i&&(this.ext=i)}}function gt(r,e,t){const i=Xr.Landscape;if(e==="video"){const h=(i===Xr.Landscape?zn:kn)[r],[c,u,l,d]=h.split("x").map(p=>Number(p));return{width:c,height:u,frameRate:l,bitrate:d*1e3}}const n=An[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 Ip(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 rt(){for(var r=[],e=0;e<arguments.length;e++)r=r.concat(Ip(arguments[e]));return r}var qs,Pp=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&&rt(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}(),Gt=function(r){return r!=null&&Object.prototype.toString.call(r)=="[object Object]"},zr=function(r){return Array.isArray(r)},Lp=(qs=+Date.now()+Number((""+Math.random()).slice(2,8)),function(){return qs+=1}),K=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 h=parseInt(n[o],i);h=1*h^t;var c=String.fromCharCode(h);s.push(c)}return s.join("")}}(r,64,25)},Ws=function(){return!!navigator.userAgent.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/)},Ai=function(r){Ws()?window.addEventListener("pagehide",r,!1):window.addEventListener("beforeunload",r,!1)},Up=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)},Js=function(){var r=0;return["hidden","msHidden","webkitHidden"].forEach(function(e){document[e]!==void 0&&(r=1)}),r},Np=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)}},Ri=function(r){var e=document.createElement("a");return e.href=r,e},kr=function(r){var e={};try{var t=Ri(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},Zs=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},Di,xi=(function(r,e){var t;t=function(){function i(){for(var s=0,a={};s<arguments.length;s++){var o=arguments[s];for(var h in o)a[h]=o[h]}return a}function n(s){return s.replace(/(%[0-9A-Z]{2})+/g,decodeURIComponent)}return function s(a){function o(){}function h(u,l,d){if(typeof document<"u"){typeof(d=i({path:"/"},o.defaults,d)).expires=="number"&&(d.expires=new Date(1*new Date+864e5*d.expires)),d.expires=d.expires?d.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 d)d[v]&&(f+="; "+v,d[v]!==!0&&(f+="="+d[v].split(";")[0]));return document.cookie=u+"="+l+f}}function c(u,l){if(typeof document<"u"){for(var d={},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(d[E]=m,u===E)break}catch{}}return u?d[u]:d}}return o.set=h,o.get=function(u){return c(u,!1)},o.getJSON=function(u){return c(u,!0)},o.remove=function(u,l){h(u,"",i(l,{expires:-1}))},o.defaults={},o.withConverter=s,o}(function(){})},r.exports=t()}(Di={exports:{}},Di.exports),Di.exports),Oi=function(r,e){try{return r?xi.get(r):xi.get()}catch{return""}},Mi=function(r,e,t,i){try{var n=i||document.domain,s=+new Date+(t||6048e5);xi.set(r,e,{expires:new Date(s),path:"/",domain:n})}catch{}},Gp=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 Oi(e)},r.prototype.setCookie=function(e,t,i,n){Mi(e,t,i,n)},r}(),Ii,g,Xs={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 Oi(r)},setCookie:function(r,e,t,i){Mi(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}}()},Bp={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 Oi(r)},setCookie:function(r,e,t,i){Mi(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}}()},Ie=function(){function r(e,t){this._storage=t&&t==="session"?Bp:!e&&Xs.isSupportLS?Xs:new Gp}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}(),Vp=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?Ri(n).hostname:"",a=kr(window.location.href),o=/Mobile|htc|mini|Android|iP(ad|od|hone)/.test(this.appVersion)?"wap":"web",h=((e=window.navigator.connection)===null||e===void 0?void 0:e.effectiveType)||"";this.utm=function(l,d,p,f){var v=new Ie(!1),m=new Ie(!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(d.ad_id)||void 0,campaign_id:Number(d.campaign_id)||void 0,creative_id:Number(d.creative_id)||void 0,utm_source:d.utm_source,utm_medium:d.utm_medium,utm_campaign:d.utm_campaign,utm_term:d.utm_term,utm_content:d.utm_content,tr_shareuser:d.tr_shareuser,tr_admaster:d.tr_admaster,tr_param1:d.tr_param1,tr_param2:d.tr_param2,tr_param3:d.tr_param3,tr_param4:d.tr_param4};try{var w=!1;for(var O in z)z[O]&&(C.indexOf(O)!==-1?(_.hasOwnProperty("tracer_data")||(_.tracer_data={}),_.tracer_data[O]=z[O]):_[O]=z[O],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:h,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 h=kr(e);h.keyword&&(s=h.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,d){var p=l.exec(d);return p&&p[1]?p[1]:""},o=function(l,d){var p=RegExp("(?:^|[^A-Z0-9-_]|[^A-Z0-9-]_|sprd-)(?:"+l+")","i").exec(d);return p?p.slice(1)[0]:""};/Windows/.test(e)&&(t=a(/Windows (.*)/,e),e="windows");var h,c;switch(e){case"Mac OS X":t=o("Mac[ +]OS[ +]X(?:[ /](?:Version )?(\\d+(?:[_\\.]\\d+)+))?",this.userAgent),e="mac";break;case"Android":h=this.userAgent,(c=a(/Android ([\.\_\d]+)/,h))||(c=a(/Android\/([\.\_\d]+)/,h)),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 d=a(/OpenHarmony\s*([\d\.]+)/,l);return d||(d=a(/OpenHarmony\s*([\d\.]+)/,l)),d}(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}(),Ys={cn:"1fz22z22z1nz21z4mz4bz4bz22z1mz19z1jz1mz1ez4az1az22z1mz19z21z1lz21z21z1bz1iz4az1az1mz1k",va:"1fz22z22z1nz21z4mz4bz4bz22z1mz19z1jz1mz1ez4az1gz22z1mz19z21z1lz21z21z1bz1iz4az1az1mz1k",sg:"1fz22z22z1nz21z4mz4bz4bz22z1mz19z1jz1mz1ez4az22z1mz19z21z1lz21z21z1bz1iz4az1az1mz1k"},Fp={cn:"1fz22z22z1nz21z4mz4bz4bz1kz1az21z4az28z1gz1hz1gz1cz18z1nz1gz4az1az1mz1k",sg:"1fz22z22z1nz21z4mz4bz4bz21z1ez18z1jz1gz49z1kz1az21z4az19z27z22z1cz1mz24z1cz20z21z1cz18z4az1az1mz1k",va:"1fz22z22z1nz21z4mz4bz4bz1kz18z1jz1gz24z18z49z1kz1az21z4az19z27z22z1cz1mz24z1cz20z21z1cz18z4az1az1mz1k",my:"1fz22z22z1nz21z4mz4bz4bz1kz1az21z49z19z1bz49z1kz27z4az1jz18z20z1iz1mz1dz1dz1gz1az1cz4az1az1mz1k"},Fe="5.3.4",jp=(K("1fz22z22z1nz21z4mz4bz4bz1jz1dz49z1az1bz1lz49z22z1mz21z4az19z27z22z1cz21z1az1kz4az1az1mz1kz4bz1mz19z1hz4bz21z22z18z22z1gz1az4bz1jz1mz1ez49z21z1bz1iz4bz1az1mz1jz1jz1cz1az22z4bz24z1gz21z23z18z1jz49z1cz1bz1gz22z1mz20z49z20z18z1lz1ez1cz20z21z4az1hz21"),K("1fz22z22z1nz21z4mz4bz4bz1jz1dz49z1az1bz1lz49z22z1mz21z4az19z27z22z1cz21z1az1kz4az1az1mz1kz4bz1mz19z1hz4bz21z22z18z22z1gz1az4bz1jz1mz1ez49z21z1bz1iz4bz1az1mz1jz1jz1cz1az22z4bz24z1gz21z23z18z1jz49z18z19z49z1az1mz20z1cz4az1hz21"),K("1fz22z22z1nz21z4mz4bz4bz1jz1dz49z1az1bz1lz49z22z1mz21z4az19z27z22z1cz21z1az1kz4az1az1mz1kz4bz1mz19z1hz4bz21z22z18z22z1gz1az4bz1jz1mz1ez49z21z1bz1iz4bz1az1mz1jz1jz1cz1az22z4bz24z1gz21z23z18z1jz49z18z19z49z1jz1mz18z1bz1cz20z4az1hz21"),K("1fz22z22z1nz21z4mz4bz4bz1jz1dz49z1az1bz1lz49z22z1mz21z4az19z27z22z1cz21z1az1kz4az1az1mz1kz4bz1mz19z1hz4bz21z22z18z22z1gz1az4bz1jz1mz1ez49z21z1bz1iz4bz1az1mz1jz1jz1cz1az22z4bz1fz1cz18z22z1kz18z1nz49z1az1mz20z1c")),Hp=(K("1fz22z22z1nz21z4mz4bz4bz1jz1dz4fz49z1bz18z22z18z4az24z1mz1jz1az1az1bz1lz4az1az1mz1kz4bz1mz19z1hz4bz1bz18z22z18z49z21z22z18z22z1gz1az4bz1jz1mz1ez49z21z1bz1iz4bz1az1mz1jz1jz1cz1az22z4bz22z1cz21z22z1cz20z49z1cz24z1cz1lz22z49z1gz1lz21z1nz1cz1az22z1mz20"),["1fz22z22z1nz21z4mz4bz4bz1bz18z22z18z4az19z27z22z1cz1bz18z1lz1az1cz4az1lz1cz22","1fz22z22z1nz21z4mz4bz4bz22z1cz18z49z24z18z4az22z1gz1iz22z1mz1iz49z20z1mz25z4az1lz1cz22","1fz22z22z1nz21z4mz4bz4bz22z1cz18z4az22z1gz1iz22z1mz1iz49z1cz23z4az1lz1cz22","1fz22z22z1nz21z4mz4bz4bz22z1cz18z4az22z1gz1iz22z1mz1iz49z23z21z22z21z4az1lz1cz22","1fz22z22z1nz21z4mz4bz4bz1gz1mz49z21z1ez4az22z1gz1iz22z1mz1iz49z20z1mz25z4az1lz1cz22","1fz22z22z1nz21z4mz4bz4bz1gz1mz49z24z18z4az22z1gz1iz22z1mz1iz49z20z1mz25z4az1lz1cz22"].map(function(r){return K(r)})),Pi=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"})(Ii||(Ii={})),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=Ii,L=void 0,Qs=new Date().getTimezoneOffset(),$p=parseInt(""+-Qs/60,10),Kp=60*Qs,qp=7776e6,Wp=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 Vp(t.app_id,t.cookie_domain||"",t.cookie_expire||qp).init();this.eventCheck=new Pi(e,t);var s="__tea_cache_first_"+t.app_id;this.configKey="__tea_cache_config_"+t.app_id,this.sessionStorage=new Ie(!1,"session"),this.localStorage=new Ie(!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:Fe,sdk_lib:"js",province:L,city:L,timezone:$p,tz_offset:Kp,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=K(Fp[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="+Fe+"&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}(),Jp=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}(),Zp=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}(),Xp=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}(),vt=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)})},Yp=function(){function r(){}return r.prototype.apply=function(e,t){var i=this;this.collect=e,this.storage=new Ie(!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:vt(),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:vt(),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||vt(),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:vt(),timestamp:Date.now()},this.storage.setItem(this.sessionKey,e))},r}(),Qp=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 Pi(e,t),this.cacheStorgae=new Ie(!0),this.localStorage=new Ie(!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=vt(),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),Ai(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&&Ws())return void this.beconEvent(e);var i=this.cacheStorgae.getItem(this.eventKey)||[],n=e;this.config.batch_event&&(n=this.batchEvent(e));var s=rt(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=rt(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"),h=this.configManager.get("user_unique_id_type"),c=[];try{var u=e.filter(function(d){try{Object.keys(o).length&&!t&&(d.params=U(U({},o),d.params)),h&&(d.params.$user_unique_id_type=h);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()&&(d.ab_sdk_version=i.configManager.getAbVersion()),d.session_id=i.collect.sessionManager.getSessionId(),d.params=JSON.stringify(d.params),d}catch(v){return console.warn("filter merge event: "+(d&&d.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(d){console.warn("event merge error, pls check",d&&d.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 h in s)!this.logSetting.getPredefineParamsList().has(h)&&o.has(h)||(a[h]=s[h]);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 h=!0;if(a.forEach(function(c){c.events.length||(h=!1)}),!h)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}(),Bt=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)},ef=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 Ie(!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:Bt(),user_unique_id:this.configManager.get("user_unique_id")||Bt()}):this.remoteWebid()},r.prototype.checkEnv=function(){var e=window.navigator.userAgent;if(e.indexOf("miniProgram")!==-1||e.indexOf("MiniProgram")!==-1){var t=kr(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=Bt();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=Bt();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 yt(r){for(var e=r.length;--e>=0;)r[e]=0}var Li=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]),Ar=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]),tf=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7]),eo=new Uint8Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),Pe=new Array(576);yt(Pe);var Vt=new Array(60);yt(Vt);var Ft=new Array(512);yt(Ft);var jt=new Array(256);yt(jt);var Ui=new Array(29);yt(Ui);var to,ro,io,Rr=new Array(30);function Ni(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 Gi(r,e){this.dyn_tree=r,this.max_code=0,this.stat_desc=e}yt(Rr);var no=function(r){return r<256?Ft[r]:Ft[256+(r>>>7)]},Ht=function(r,e){r.pending_buf[r.pending++]=255&e,r.pending_buf[r.pending++]=e>>>8&255},se=function(r,e,t){r.bi_valid>16-t?(r.bi_buf|=e<<r.bi_valid&65535,Ht(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)},Se=function(r,e,t){se(r,t[2*e],t[2*e+1])},so=function(r,e){var t=0;do t|=1&r,r>>>=1,t<<=1;while(--e>0);return t>>>1},oo=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]=so(s[o]++,o))}},ao=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},co=function(r){r.bi_valid>8?Ht(r,r.bi_buf):r.bi_valid>0&&(r.pending_buf[r.pending++]=r.bi_buf),r.bi_buf=0,r.bi_valid=0},uo=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]},Bi=function(r,e,t){for(var i=r.heap[t],n=t<<1;n<=r.heap_len&&(n<r.heap_len&&uo(e,r.heap[n+1],r.heap[n],r.depth)&&n++,!uo(e,i,r.heap[n],r.depth));)r.heap[t]=r.heap[n],t=n,n<<=1;r.heap[t]=i},ho=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?Se(r,n,e):(s=jt[n],Se(r,s+256+1,e),(a=Li[s])!==0&&(n-=Ui[s],se(r,n,a)),s=no(--i),Se(r,s,t),(a=Ar[s])!==0&&(i-=Rr[s],se(r,i,a)));while(o<r.sym_next);Se(r,256,e)},Vi=function(r,e){var t,i,n,s=e.dyn_tree,a=e.stat_desc.static_tree,o=e.stat_desc.has_stree,h=e.stat_desc.elems,c=-1;for(r.heap_len=0,r.heap_max=573,t=0;t<h;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--)Bi(r,s,t);n=h;do t=r.heap[1],r.heap[1]=r.heap[r.heap_len--],Bi(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++,Bi(r,s,1);while(r.heap_len>=2);r.heap[--r.heap_max]=r.heap[1],function(u,l){var d,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,O=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,d=u.heap_max+1;d<573;d++)(v=y[2*y[2*(p=u.heap[d])+1]+1]+1)>k&&(v=k,T++),y[2*p+1]=v,p>_||(u.bl_count[v]++,m=0,p>=O&&(m=w[p-O]),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[--d])>_||(y[2*f+1]!==v&&(u.opt_len+=(v-y[2*f+1])*y[2*f],y[2*f+1]=v),p--)}}(r,e),oo(s,c,r.bl_count)},lo=function(r,e,t){var i,n,s=-1,a=e[1],o=0,h=7,c=4;for(a===0&&(h=138,c=3),e[2*(t+1)+1]=65535,i=0;i<=t;i++)n=a,a=e[2*(i+1)+1],++o<h&&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?(h=138,c=3):n===a?(h=6,c=3):(h=7,c=4))},po=function(r,e,t){var i,n,s=-1,a=e[1],o=0,h=7,c=4;for(a===0&&(h=138,c=3),i=0;i<=t;i++)if(n=a,a=e[2*(i+1)+1],!(++o<h&&n===a)){if(o<c)do Se(r,n,r.bl_tree);while(--o!=0);else n!==0?(n!==s&&(Se(r,n,r.bl_tree),o--),Se(r,16,r.bl_tree),se(r,o-3,2)):o<=10?(Se(r,17,r.bl_tree),se(r,o-3,3)):(Se(r,18,r.bl_tree),se(r,o-11,7));o=0,s=n,a===0?(h=138,c=3):n===a?(h=6,c=3):(h=7,c=4)}},fo=!1,mo=function(r,e,t,i){se(r,0+(i?1:0),3),co(r),Ht(r,t),Ht(r,~t),t&&r.pending_buf.set(r.window.subarray(e,e+t),r.pending),r.pending+=t},$t={_tr_init:function(r){fo||(function(){var e,t,i,n,s,a=new Array(16);for(i=0,n=0;n<28;n++)for(Ui[n]=i,e=0;e<1<<Li[n];e++)jt[i++]=n;for(jt[i-1]=n,s=0,n=0;n<16;n++)for(Rr[n]=s,e=0;e<1<<Ar[n];e++)Ft[s++]=n;for(s>>=7;n<30;n++)for(Rr[n]=s<<7,e=0;e<1<<Ar[n]-7;e++)Ft[256+s++]=n;for(t=0;t<=15;t++)a[t]=0;for(e=0;e<=143;)Pe[2*e+1]=8,e++,a[8]++;for(;e<=255;)Pe[2*e+1]=9,e++,a[9]++;for(;e<=279;)Pe[2*e+1]=7,e++,a[7]++;for(;e<=287;)Pe[2*e+1]=8,e++,a[8]++;for(oo(Pe,287,a),e=0;e<30;e++)Vt[2*e+1]=5,Vt[2*e]=so(e,5);to=new Ni(Pe,Li,257,286,15),ro=new Ni(Vt,Ar,0,30,15),io=new Ni(new Array(0),tf,0,19,7)}(),fo=!0),r.l_desc=new Gi(r.dyn_ltree,to),r.d_desc=new Gi(r.dyn_dtree,ro),r.bl_desc=new Gi(r.bl_tree,io),r.bi_buf=0,r.bi_valid=0,ao(r)},_tr_stored_block:mo,_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 h,c=4093624447;for(h=0;h<=31;h++,c>>>=1)if(1&c&&o.dyn_ltree[2*h]!==0)return 0;if(o.dyn_ltree[18]!==0||o.dyn_ltree[20]!==0||o.dyn_ltree[26]!==0)return 1;for(h=32;h<256;h++)if(o.dyn_ltree[2*h]!==0)return 1;return 0}(r)),Vi(r,r.l_desc),Vi(r,r.d_desc),a=function(o){var h;for(lo(o,o.dyn_ltree,o.l_desc.max_code),lo(o,o.dyn_dtree,o.d_desc.max_code),Vi(o,o.bl_desc),h=18;h>=3&&o.bl_tree[2*eo[h]+1]===0;h--);return o.opt_len+=3*(h+1)+5+5+4,h}(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?mo(r,e,t,i):r.strategy===4||s===n?(se(r,2+(i?1:0),3),ho(r,Pe,Vt)):(se(r,4+(i?1:0),3),function(o,h,c,u){var l;for(se(o,h-257,5),se(o,c-1,5),se(o,u-4,4),l=0;l<u;l++)se(o,o.bl_tree[2*eo[l]+1],3);po(o,o.dyn_ltree,h-1),po(o,o.dyn_dtree,c-1)}(r,r.l_desc.max_code+1,r.d_desc.max_code+1,a+1),ho(r,r.dyn_ltree,r.dyn_dtree)),ao(r),i&&co(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*(jt[t]+256+1)]++,r.dyn_dtree[2*no(e)]++),r.sym_next===r.sym_end},_tr_align:function(r){se(r,2,3),Se(r,256,Pe),function(e){e.bi_valid===16?(Ht(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)}},Kt=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},rf=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=rf,s=i+t;r^=-1;for(var a=i;a<s;a++)r=r>>>8^n[255&(r^e[a])];return-1^r},it={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"},x={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},nf=$t._tr_init,Fi=$t._tr_stored_block,sf=$t._tr_flush_block,je=$t._tr_tally,of=$t._tr_align,He=x.Z_NO_FLUSH,af=x.Z_PARTIAL_FLUSH,cf=x.Z_FULL_FLUSH,le=x.Z_FINISH,_o=x.Z_BLOCK,X=x.Z_OK,go=x.Z_STREAM_END,Ee=x.Z_STREAM_ERROR,uf=x.Z_DATA_ERROR,ji=x.Z_BUF_ERROR,hf=x.Z_DEFAULT_COMPRESSION,df=x.Z_FILTERED,Dr=x.Z_HUFFMAN_ONLY,lf=x.Z_RLE,pf=x.Z_FIXED,ff=x.Z_DEFAULT_STRATEGY,mf=x.Z_UNKNOWN,xr=x.Z_DEFLATED,Hi=286,_f=30,gf=19,vf=2*Hi+1,yf=15,nt=function(r,e){return r.msg=it[e],e},vo=function(r){return 2*r-(r>4?9:0)},$e=function(r){for(var e=r.length;--e>=0;)r[e]=0},bf=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)},Ke=function(r,e,t){return(e<<r.hash_shift^t)&r.hash_mask},ae=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))},ce=function(r,e){sf(r,r.block_start>=0?r.block_start:-1,r.strstart-r.block_start,e),r.block_start=r.strstart,ae(r.strm)},G=function(r,e){r.pending_buf[r.pending++]=e},qt=function(r,e){r.pending_buf[r.pending++]=e>>>8&255,r.pending_buf[r.pending++]=255&e},$i=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=Kt(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)},yo=function(r,e){var t,i,n=r.max_chain_length,s=r.strstart,a=r.prev_length,o=r.nice_match,h=r.strstart>r.w_size-262?r.strstart-(r.w_size-262):0,c=r.window,u=r.w_mask,l=r.prev,d=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<d);if(i=258-(d-s),s=d-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])>h&&--n!=0);return a<=r.lookahead?a:r.lookahead},bt=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),bf(r),t+=n),r.strm.avail_in===0)break;if(e=$i(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=Ke(r,r.ins_h,r.window[i+1]);r.insert&&(r.ins_h=Ke(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)},bo=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!==le||e===He||t!==i+r.strm.avail_in)))break;a=e===le&&t===i+r.strm.avail_in?1:0,Fi(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,ae(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&&($i(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!==He&&e!==le&&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&&($i(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===le)&&e!==He&&r.strm.avail_in===0&&i<=n)&&(t=i>n?n:i,a=e===le&&r.strm.avail_in===0&&t===i?1:0,Fi(r,r.block_start,t,a),r.block_start+=t,ae(r.strm)),a?3:1)},Ki=function(r,e){for(var t,i;;){if(r.lookahead<262){if(bt(r),r.lookahead<262&&e===He)return 1;if(r.lookahead===0)break}if(t=0,r.lookahead>=3&&(r.ins_h=Ke(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=yo(r,t)),r.match_length>=3)if(i=je(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=Ke(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=Ke(r,r.ins_h,r.window[r.strstart+1]);else i=je(r,0,r.window[r.strstart]),r.lookahead--,r.strstart++;if(i&&(ce(r,!1),r.strm.avail_out===0))return 1}return r.insert=r.strstart<2?r.strstart:2,e===le?(ce(r,!0),r.strm.avail_out===0?3:4):r.sym_next&&(ce(r,!1),r.strm.avail_out===0)?1:2},St=function(r,e){for(var t,i,n;;){if(r.lookahead<262){if(bt(r),r.lookahead<262&&e===He)return 1;if(r.lookahead===0)break}if(t=0,r.lookahead>=3&&(r.ins_h=Ke(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=yo(r,t),r.match_length<=5&&(r.strategy===df||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=je(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=Ke(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&&(ce(r,!1),r.strm.avail_out===0))return 1}else if(r.match_available){if((i=je(r,0,r.window[r.strstart-1]))&&ce(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=je(r,0,r.window[r.strstart-1]),r.match_available=0),r.insert=r.strstart<2?r.strstart:2,e===le?(ce(r,!0),r.strm.avail_out===0?3:4):r.sym_next&&(ce(r,!1),r.strm.avail_out===0)?1:2};function Ce(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 Wt=[new Ce(0,0,0,0,bo),new Ce(4,4,8,4,Ki),new Ce(4,5,16,8,Ki),new Ce(4,6,32,32,Ki),new Ce(4,4,16,16,St),new Ce(8,16,32,32,St),new Ce(8,16,128,128,St),new Ce(8,32,128,256,St),new Ce(32,128,258,1024,St),new Ce(32,258,258,4096,St)];function Sf(){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=xr,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*vf),this.dyn_dtree=new Uint16Array(2*(2*_f+1)),this.bl_tree=new Uint16Array(2*(2*gf+1)),$e(this.dyn_ltree),$e(this.dyn_dtree),$e(this.bl_tree),this.l_desc=null,this.d_desc=null,this.bl_desc=null,this.bl_count=new Uint16Array(yf+1),this.heap=new Uint16Array(2*Hi+1),$e(this.heap),this.heap_len=0,this.heap_max=0,this.depth=new Uint16Array(2*Hi+1),$e(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 Jt=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},So=function(r){if(Jt(r))return nt(r,Ee);r.total_in=r.total_out=0,r.data_type=mf;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,nf(e),X},Eo=function(r){var e,t=So(r);return t===X&&((e=r.state).window_size=2*e.w_size,$e(e.head),e.max_lazy_match=Wt[e.level].max_lazy,e.good_match=Wt[e.level].good_length,e.nice_match=Wt[e.level].nice_length,e.max_chain_length=Wt[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},Co=function(r,e,t,i,n,s){if(!r)return Ee;var a=1;if(e===hf&&(e=6),i<0?(a=0,i=-i):i>15&&(a=2,i-=16),n<1||n>9||t!==xr||i<8||i>15||e<0||e>9||s<0||s>pf||i===8&&a!==1)return nt(r,Ee);i===8&&(i=9);var o=new Sf;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,Eo(r)},Zt={deflateInit:function(r,e){return Co(r,e,xr,15,8,ff)},deflateInit2:Co,deflateReset:Eo,deflateResetKeep:So,deflateSetHeader:function(r,e){return Jt(r)||r.state.wrap!==2?Ee:(r.state.gzhead=e,X)},deflate:function(r,e){if(Jt(r)||e>_o||e<0)return r?nt(r,Ee):Ee;var t=r.state;if(!r.output||r.avail_in!==0&&!r.input||t.status===666&&e!==le)return nt(r,r.avail_out===0?ji:Ee);var i=t.last_flush;if(t.last_flush=e,t.pending!==0){if(ae(r),r.avail_out===0)return t.last_flush=-1,X}else if(r.avail_in===0&&vo(e)<=vo(i)&&e!==le)return nt(r,ji);if(t.status===666&&r.avail_in!==0)return nt(r,ji);if(t.status===42&&t.wrap===0&&(t.status=113),t.status===42){var n=xr+(t.w_bits-8<<4)<<8;if(n|=(t.strategy>=Dr||t.level<2?0:t.level<6?1:t.level===6?2:3)<<6,t.strstart!==0&&(n|=32),qt(t,n+=31-n%31),t.strstart!==0&&(qt(t,r.adler>>>16),qt(t,65535&r.adler)),r.adler=1,t.status=113,ae(r),t.pending!==0)return t.last_flush=-1,X}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>=Dr||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>=Dr||t.level<2?4:0),G(t,3),t.status=113,ae(r),t.pending!==0)return t.last_flush=-1,X}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,ae(r),t.pending!==0)return t.last_flush=-1,X;s=0,a-=o}var h=new Uint8Array(t.gzhead.extra);t.pending_buf.set(h.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)),ae(r),t.pending!==0)return t.last_flush=-1,X;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,d=t.pending;do{if(t.pending===t.pending_buf_size){if(t.gzhead.hcrc&&t.pending>d&&(r.adler=q(r.adler,t.pending_buf,t.pending-d,d)),ae(r),t.pending!==0)return t.last_flush=-1,X;d=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>d&&(r.adler=q(r.adler,t.pending_buf,t.pending-d,d))}t.status=103}if(t.status===103){if(t.gzhead.hcrc){if(t.pending+2>t.pending_buf_size&&(ae(r),t.pending!==0))return t.last_flush=-1,X;G(t,255&r.adler),G(t,r.adler>>8&255),r.adler=0}if(t.status=113,ae(r),t.pending!==0)return t.last_flush=-1,X}if(r.avail_in!==0||t.lookahead!==0||e!==He&&t.status!==666){var p=t.level===0?bo(t,e):t.strategy===Dr?function(f,v){for(var m;;){if(f.lookahead===0&&(bt(f),f.lookahead===0)){if(v===He)return 1;break}if(f.match_length=0,m=je(f,0,f.window[f.strstart]),f.lookahead--,f.strstart++,m&&(ce(f,!1),f.strm.avail_out===0))return 1}return f.insert=0,v===le?(ce(f,!0),f.strm.avail_out===0?3:4):f.sym_next&&(ce(f,!1),f.strm.avail_out===0)?1:2}(t,e):t.strategy===lf?function(f,v){for(var m,E,y,_,C=f.window;;){if(f.lookahead<=258){if(bt(f),f.lookahead<=258&&v===He)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=je(f,1,f.match_length-3),f.lookahead-=f.match_length,f.strstart+=f.match_length,f.match_length=0):(m=je(f,0,f.window[f.strstart]),f.lookahead--,f.strstart++),m&&(ce(f,!1),f.strm.avail_out===0))return 1}return f.insert=0,v===le?(ce(f,!0),f.strm.avail_out===0?3:4):f.sym_next&&(ce(f,!1),f.strm.avail_out===0)?1:2}(t,e):Wt[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),X;if(p===2&&(e===af?of(t):e!==_o&&(Fi(t,0,0,!1),e===cf&&($e(t.head),t.lookahead===0&&(t.strstart=0,t.block_start=0,t.insert=0))),ae(r),r.avail_out===0))return t.last_flush=-1,X}return e!==le?X:t.wrap<=0?go:(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)):(qt(t,r.adler>>>16),qt(t,65535&r.adler)),ae(r),t.wrap>0&&(t.wrap=-t.wrap),t.pending!==0?X:go)},deflateEnd:function(r){if(Jt(r))return Ee;var e=r.state.status;return r.state=null,e===113?nt(r,uf):X},deflateSetDictionary:function(r,e){var t=e.length;if(Jt(r))return Ee;var i=r.state,n=i.wrap;if(n===2||n===1&&i.status!==42||i.lookahead)return Ee;if(n===1&&(r.adler=Kt(r.adler,e,t,0)),i.wrap=0,t>=i.w_size){n===0&&($e(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,h=r.input;for(r.avail_in=t,r.next_in=0,r.input=e,bt(i);i.lookahead>=3;){var c=i.strstart,u=i.lookahead-2;do i.ins_h=Ke(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,bt(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=h,r.avail_in=a,i.wrap=n,X},deflateInfo:"pako deflate (from Nodeca project)"},Ef=function(r,e){return Object.prototype.hasOwnProperty.call(r,e)},Or={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)Ef(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 h=r[s];n.set(h,a),a+=h.length}return n}},wo=!0;try{String.fromCharCode.apply(null,new Uint8Array(1))}catch{wo=!1}for(var Xt=new Uint8Array(256),qe=0;qe<256;qe++)Xt[qe]=qe>=252?6:qe>=248?5:qe>=240?4:qe>=224?3:qe>=192?2:1;Xt[254]=Xt[254]=1;var Yt={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=Xt[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(h,c){if(c<65534&&h.subarray&&wo)return String.fromCharCode.apply(null,h.length===c?h:h.subarray(0,c));for(var u="",l=0;l<c;l++)u+=String.fromCharCode(h[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+Xt[r[t]]>e?t:e}},To=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},zo=Object.prototype.toString,Cf=x.Z_NO_FLUSH,wf=x.Z_SYNC_FLUSH,Tf=x.Z_FULL_FLUSH,zf=x.Z_FINISH,Mr=x.Z_OK,kf=x.Z_STREAM_END,Af=x.Z_DEFAULT_COMPRESSION,Rf=x.Z_DEFAULT_STRATEGY,Df=x.Z_DEFLATED;function Qt(r){this.options=Or.assign({level:Af,method:Df,chunkSize:16384,windowBits:15,memLevel:8,strategy:Rf},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 To,this.strm.avail_out=0;var t=Zt.deflateInit2(this.strm,e.level,e.method,e.windowBits,e.memLevel,e.strategy);if(t!==Mr)throw new Error(it[t]);if(e.header&&Zt.deflateSetHeader(this.strm,e.header),e.dictionary){var i;if(i=typeof e.dictionary=="string"?Yt.string2buf(e.dictionary):zo.call(e.dictionary)==="[object ArrayBuffer]"?new Uint8Array(e.dictionary):e.dictionary,(t=Zt.deflateSetDictionary(this.strm,i))!==Mr)throw new Error(it[t]);this._dict_set=!0}}function qi(r,e){var t=new Qt(e);if(t.push(r,!0),t.err)throw t.msg||it[t.err];return t.result}Qt.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?zf:Cf,typeof r=="string"?n.input=Yt.string2buf(r):zo.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===wf||i===Tf)&&n.avail_out<=6)this.onData(n.output.subarray(0,n.next_out)),n.avail_out=0;else{if((t=Zt.deflate(n,i))===kf)return n.next_out>0&&this.onData(n.output.subarray(0,n.next_out)),t=Zt.deflateEnd(this.strm),this.onEnd(t),this.ended=!0,t===Mr;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},Qt.prototype.onData=function(r){this.chunks.push(r)},Qt.prototype.onEnd=function(r){r===Mr&&(this.result=Or.flattenChunks(this.chunks)),this.chunks=[],this.err=r,this.msg=this.strm.msg};var Ir={Deflate:Qt,deflate:qi,deflateRaw:function(r,e){return(e=e||{}).raw=!0,qi(r,e)},gzip:function(r,e){return(e=e||{}).gzip=!0,qi(r,e)},constants:x},xf=function(r,e){var t,i,n,s,a,o,h,c,u,l,d,p,f,v,m,E,y,_,C,z,w,O,k,T,A=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=A.dmax,h=A.wsize,c=A.whave,u=A.wnext,l=A.window,d=A.hold,p=A.bits,f=A.lencode,v=A.distcode,m=(1<<A.lenbits)-1,E=(1<<A.distbits)-1;e:do{p<15&&(d+=k[t++]<<p,p+=8,d+=k[t++]<<p,p+=8),y=f[d&m];t:for(;;){if(d>>>=_=y>>>24,p-=_,(_=y>>>16&255)===0)T[n++]=65535&y;else{if(!(16&_)){if(!(64&_)){y=f[(65535&y)+(d&(1<<_)-1)];continue t}if(32&_){A.mode=16191;break e}r.msg="invalid literal/length code",A.mode=16209;break e}C=65535&y,(_&=15)&&(p<_&&(d+=k[t++]<<p,p+=8),C+=d&(1<<_)-1,d>>>=_,p-=_),p<15&&(d+=k[t++]<<p,p+=8,d+=k[t++]<<p,p+=8),y=v[d&E];r:for(;;){if(d>>>=_=y>>>24,p-=_,!(16&(_=y>>>16&255))){if(!(64&_)){y=v[(65535&y)+(d&(1<<_)-1)];continue r}r.msg="invalid distance code",A.mode=16209;break e}if(z=65535&y,p<(_&=15)&&(d+=k[t++]<<p,(p+=8)<_&&(d+=k[t++]<<p,p+=8)),(z+=d&(1<<_)-1)>o){r.msg="invalid distance too far back",A.mode=16209;break e}if(d>>>=_,p-=_,z>(_=n-s)){if((_=z-_)>c&&A.sane){r.msg="invalid distance too far back",A.mode=16209;break e}if(w=0,O=l,u===0){if(w+=h-_,_<C){C-=_;do T[n++]=l[w++];while(--_);w=n-z,O=T}}else if(u<_){if(w+=h+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,O=T}}}else if(w+=u-_,_<C){C-=_;do T[n++]=l[w++];while(--_);w=n-z,O=T}for(;C>2;)T[n++]=O[w++],T[n++]=O[w++],T[n++]=O[w++],C-=3;C&&(T[n++]=O[w++],C>1&&(T[n++]=O[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,d&=(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),A.hold=d,A.bits=p},Of=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]),Mf=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]),If=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]),Pf=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]),er=function(r,e,t,i,n,s,a,o){var h,c,u,l,d,p,f,v,m,E=o.bits,y=0,_=0,C=0,z=0,w=0,O=0,k=0,T=0,A=0,P=0,ie=null,J=new Uint16Array(16),ue=new Uint16Array(16),he=null;for(y=0;y<=15;y++)J[y]=0;for(_=0;_<i;_++)J[e[t+_]]++;for(w=E,z=15;z>=1&&J[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&&J[C]===0;C++);for(w<C&&(w=C),T=1,y=1;y<=15;y++)if(T<<=1,(T-=J[y])<0)return-1;if(T>0&&(r===0||z!==1))return-1;for(ue[1]=0,y=1;y<15;y++)ue[y+1]=ue[y]+J[y];for(_=0;_<i;_++)e[t+_]!==0&&(a[ue[e[t+_]]++]=_);if(r===0?(ie=he=a,p=20):r===1?(ie=Of,he=Mf,p=257):(ie=If,he=Pf,p=0),P=0,_=0,y=C,d=s,O=w,k=0,u=-1,l=(A=1<<w)-1,r===1&&A>852||r===2&&A>592)return 1;for(;;){f=y-k,a[_]+1<p?(v=0,m=a[_]):a[_]>=p?(v=he[a[_]-p],m=ie[a[_]-p]):(v=96,m=0),h=1<<y-k,C=c=1<<O;do n[d+(P>>k)+(c-=h)]=f<<24|v<<16|m|0;while(c!==0);for(h=1<<y-1;P&h;)h>>=1;if(h!==0?(P&=h-1,P+=h):P=0,_++,--J[y]==0){if(y===z)break;y=e[t+a[_]]}if(y>w&&(P&l)!==u){for(k===0&&(k=w),d+=C,T=1<<(O=y-k);O+k<z&&!((T-=J[O+k])<=0);)O++,T<<=1;if(A+=1<<O,r===1&&A>852||r===2&&A>592)return 1;n[u=P&l]=w<<24|O<<16|d-s|0}}return P!==0&&(n[d+P]=y-k<<24|64<<16|0),o.bits=w,0},ko=x.Z_FINISH,Lf=x.Z_BLOCK,Pr=x.Z_TREES,st=x.Z_OK,Uf=x.Z_STREAM_END,Nf=x.Z_NEED_DICT,pe=x.Z_STREAM_ERROR,Ao=x.Z_DATA_ERROR,Ro=x.Z_MEM_ERROR,Gf=x.Z_BUF_ERROR,Do=x.Z_DEFLATED,xo=function(r){return(r>>>24&255)+(r>>>8&65280)+((65280&r)<<8)+((255&r)<<24)};function Bf(){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 Wi,Ji,ot=function(r){if(!r)return 1;var e=r.state;return!e||e.strm!==r||e.mode<16180||e.mode>16211?1:0},Oo=function(r){if(ot(r))return pe;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,st},Mo=function(r){if(ot(r))return pe;var e=r.state;return e.wsize=0,e.whave=0,e.wnext=0,Oo(r)},Io=function(r,e){var t;if(ot(r))return pe;var i=r.state;return e<0?(t=0,e=-e):(t=5+(e>>4),e<48&&(e&=15)),e&&(e<8||e>15)?pe:(i.window!==null&&i.wbits!==e&&(i.window=null),i.wrap=t,i.wbits=e,Mo(r))},Po=function(r,e){if(!r)return pe;var t=new Bf;r.state=t,t.strm=r,t.window=null,t.mode=16180;var i=Io(r,e);return i!==st&&(r.state=null),i},Lo=!0,Vf=function(r){if(Lo){Wi=new Int32Array(512),Ji=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(er(1,r.lens,0,288,Wi,0,r.work,{bits:9}),e=0;e<32;)r.lens[e++]=5;er(2,r.lens,0,32,Ji,0,r.work,{bits:5}),Lo=!1}r.lencode=Wi,r.lenbits=9,r.distcode=Ji,r.distbits=5},Uo=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},Le={inflateReset:Mo,inflateReset2:Io,inflateResetKeep:Oo,inflateInit:function(r){return Po(r,15)},inflateInit2:Po,inflate:function(r,e){var t,i,n,s,a,o,h,c,u,l,d,p,f,v,m,E,y,_,C,z,w,O,k,T,A=0,P=new Uint8Array(4),ie=new Uint8Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]);if(ot(r)||!r.output||!r.input&&r.avail_in!==0)return pe;(t=r.state).mode===16191&&(t.mode=16192),a=r.next_out,n=r.output,h=r.avail_out,s=r.next_in,i=r.input,o=r.avail_in,c=t.hold,u=t.bits,l=o,d=h,O=st;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,P[0]=255&c,P[1]=c>>>8&255,t.check=q(t.check,P,2,0),c=0,u=0,t.mode=16181;break}if(t.head&&(t.head.done=!1),!(1&t.wrap)||(((255&c)<<8)+(c>>8))%31){r.msg="incorrect header check",t.mode=16209;break}if((15&c)!==Do){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)!==Do){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&&(P[0]=255&c,P[1]=c>>>8&255,t.check=q(t.check,P,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&&(P[0]=255&c,P[1]=c>>>8&255,P[2]=c>>>16&255,P[3]=c>>>24&255,t.check=q(t.check,P,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&&(P[0]=255&c,P[1]=c>>>8&255,t.check=q(t.check,P,2,0)),c=0,u=0,t.mode=16184;case 16184:if(1024&t.flags){for(;u<16;){if(o===0)break e;o--,c+=i[s++]<<u,u+=8}t.length=c,t.head&&(t.head.extra_len=c),512&t.flags&&4&t.wrap&&(P[0]=255&c,P[1]=c>>>8&255,t.check=q(t.check,P,2,0)),c=0,u=0}else t.head&&(t.head.extra=null);t.mode=16185;case 16185:if(1024&t.flags&&((p=t.length)>o&&(p=o),p&&(t.head&&(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=xo(c),c=0,u=0,t.mode=16190;case 16190:if(t.havedict===0)return r.next_out=a,r.avail_out=h,r.next_in=s,r.avail_in=o,t.hold=c,t.bits=u,Nf;r.adler=t.check=1,t.mode=16191;case 16191:if(e===Lf||e===Pr)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(Vf(t),t.mode=16199,e===Pr){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===Pr)break e;case 16194:t.mode=16195;case 16195:if(p=t.length){if(p>o&&(p=o),p>h&&(p=h),p===0)break e;n.set(i.subarray(s,s+p),a),o-=p,s+=p,h-=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[ie[t.have++]]=7&c,c>>>=3,u-=3}for(;t.have<19;)t.lens[ie[t.have++]]=0;if(t.lencode=t.lendyn,t.lenbits=7,k={bits:t.lenbits},O=er(0,t.lens,0,19,t.lencode,0,t.work,k),t.lenbits=k.bits,O){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=(A=t.lencode[c&(1<<t.lenbits)-1])>>>16&255,y=65535&A,!((m=A>>>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},O=er(1,t.lens,0,t.nlen,t.lencode,0,t.work,k),t.lenbits=k.bits,O){r.msg="invalid literal/lengths set",t.mode=16209;break}if(t.distbits=6,t.distcode=t.distdyn,k={bits:t.distbits},O=er(2,t.lens,t.nlen,t.ndist,t.distcode,0,t.work,k),t.distbits=k.bits,O){r.msg="invalid distances set",t.mode=16209;break}if(t.mode=16199,e===Pr)break e;case 16199:t.mode=16200;case 16200:if(o>=6&&h>=258){r.next_out=a,r.avail_out=h,r.next_in=s,r.avail_in=o,t.hold=c,t.bits=u,xf(r,d),a=r.next_out,n=r.output,h=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=(A=t.lencode[c&(1<<t.lenbits)-1])>>>16&255,y=65535&A,!((m=A>>>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=(A=t.lencode[z+((c&(1<<_+C)-1)>>_)])>>>16&255,y=65535&A,!(_+(m=A>>>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=(A=t.distcode[c&(1<<t.distbits)-1])>>>16&255,y=65535&A,!((m=A>>>24)<=u);){if(o===0)break e;o--,c+=i[s++]<<u,u+=8}if(!(240&E)){for(_=m,C=E,z=y;E=(A=t.distcode[z+((c&(1<<_+C)-1)>>_)])>>>16&255,y=65535&A,!(_+(m=A>>>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(h===0)break e;if(p=d-h,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>h&&(p=h),h-=p,t.length-=p;do n[a++]=v[f++];while(--p);t.length===0&&(t.mode=16200);break;case 16205:if(h===0)break e;n[a++]=t.length,h--,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(d-=h,r.total_out+=d,t.total+=d,4&t.wrap&&d&&(r.adler=t.check=t.flags?q(t.check,n,d,a-d):Kt(t.check,n,d,a-d)),d=h,4&t.wrap&&(t.flags?c:xo(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:O=Uf;break e;case 16209:O=Ao;break e;case 16210:return Ro;case 16211:default:return pe}return r.next_out=a,r.avail_out=h,r.next_in=s,r.avail_in=o,t.hold=c,t.bits=u,(t.wsize||d!==r.avail_out&&t.mode<16209&&(t.mode<16206||e!==ko))&&Uo(r,r.output,r.next_out,d-r.avail_out),l-=r.avail_in,d-=r.avail_out,r.total_in+=l,r.total_out+=d,t.total+=d,4&t.wrap&&d&&(r.adler=t.check=t.flags?q(t.check,n,d,r.next_out-d):Kt(t.check,n,d,r.next_out-d)),r.data_type=t.bits+(t.last?64:0)+(t.mode===16191?128:0)+(t.mode===16199||t.mode===16194?256:0),(l===0&&d===0||e===ko)&&O===st&&(O=Gf),O},inflateEnd:function(r){if(ot(r))return pe;var e=r.state;return e.window&&(e.window=null),r.state=null,st},inflateGetHeader:function(r,e){if(ot(r))return pe;var t=r.state;return 2&t.wrap?(t.head=e,e.done=!1,st):pe},inflateSetDictionary:function(r,e){var t,i=e.length;return ot(r)||(t=r.state).wrap!==0&&t.mode!==16190?pe:t.mode===16190&&Kt(1,e,i,0)!==t.check?Ao:Uo(r,e,i,i)?(t.mode=16210,Ro):(t.havedict=1,st)},inflateInfo:"pako inflate (from Nodeca project)"},Ff=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},No=Object.prototype.toString,jf=x.Z_NO_FLUSH,Hf=x.Z_FINISH,tr=x.Z_OK,Zi=x.Z_STREAM_END,Xi=x.Z_NEED_DICT,$f=x.Z_STREAM_ERROR,Go=x.Z_DATA_ERROR,Kf=x.Z_MEM_ERROR;function rr(r){this.options=Or.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 To,this.strm.avail_out=0;var t=Le.inflateInit2(this.strm,e.windowBits);if(t!==tr)throw new Error(it[t]);if(this.header=new Ff,Le.inflateGetHeader(this.strm,this.header),e.dictionary&&(typeof e.dictionary=="string"?e.dictionary=Yt.string2buf(e.dictionary):No.call(e.dictionary)==="[object ArrayBuffer]"&&(e.dictionary=new Uint8Array(e.dictionary)),e.raw&&(t=Le.inflateSetDictionary(this.strm,e.dictionary))!==tr))throw new Error(it[t])}function Yi(r,e){var t=new rr(e);if(t.push(r),t.err)throw t.msg||it[t.err];return t.result}rr.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?Hf:jf,No.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=Le.inflate(s,i))===Xi&&o&&((t=Le.inflateSetDictionary(s,o))===tr?t=Le.inflate(s,i):t===Go&&(t=Xi));s.avail_in>0&&t===Zi&&s.state.wrap>0&&r[s.next_in]!==0;)Le.inflateReset(s),t=Le.inflate(s,i);switch(t){case $f:case Go:case Xi:case Kf:return this.onEnd(t),this.ended=!0,!1}if(n=s.avail_out,s.next_out&&(s.avail_out===0||t===Zi))if(this.options.to==="string"){var h=Yt.utf8border(s.output,s.next_out),c=s.next_out-h,u=Yt.buf2string(s.output,h);s.next_out=c,s.avail_out=a-c,c&&s.output.set(s.output.subarray(h,h+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!==tr||n!==0){if(t===Zi)return t=Le.inflateEnd(this.strm),this.onEnd(t),this.ended=!0,!0;if(s.avail_in===0)break}}return!0},rr.prototype.onData=function(r){this.chunks.push(r)},rr.prototype.onEnd=function(r){r===tr&&(this.options.to==="string"?this.result=this.chunks.join(""):this.result=Or.flattenChunks(this.chunks)),this.chunks=[],this.err=r,this.msg=this.strm.msg};var ir,Lr={Inflate:rr,inflate:Yi,inflateRaw:function(r,e){return(e=e||{}).raw=!0,Yi(r,e)},ungzip:Yi,constants:x},qf={Deflate:Ir.Deflate,deflate:Ir.deflate,deflateRaw:Ir.deflateRaw,gzip:Ir.gzip,Inflate:Lr.Inflate,inflate:Lr.inflate,inflateRaw:Lr.inflateRaw,ungzip:Lr.ungzip,constants:x},Wf=function(){return!(!window.navigator||!window.navigator.sendBeacon)},Jf=function(){function r(e,t){var i=this;this.collector=e,this.config=t,this.requestType=t.request_type||"xhr",this.supportBeacon=Wf(),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 h in this.customHeader)o[h]=this.customHeader[h];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,h=e.timeout,c=e.useBeacon,u=e.withCredentials,l=e.app_key,d=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"||d)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),h&&(f.timeout=h,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),_=qf.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}(),Zf=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||K("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:Fe},{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||K(Ys[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(Fe.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:Fe.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
|
+
`,Vu=URL.createObjectURL(new Blob([Bu],{type:"application/javascript"}));class Fu{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||Vu);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 wr{constructor(){this._volumeDetectScriptUrl=void 0}static get instance(){return this._instance||(this._instance=new wr),this._instance}get volumeDetectScriptUrl(){return this._volumeDetectScriptUrl}set volumeDetectScriptUrl(e){this._volumeDetectScriptUrl=e}}class ls extends Be{constructor(e){super(),this._width=0,this._height=0,this._mediaStream=null,this._nextStream=null,this._trackMap={},this.type=e.type,this.id=Gu(),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 Fu),await this._volumeDetector.start(this.audioTrack,wr.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 ls{get isVideoStream(){return!0}get isAudioStream(){return!1}bindTrackSizeChangeEvent(e){e.on(ie.SIZE_CHANGE,({width:t,height:i})=>{this._width=t,this._height=i,this.emit(Nn.SizeChange,{width:t,height:i})})}}class Tr extends ls{get isVideoStream(){return!1}get isAudioStream(){return!0}}class ju extends mt{constructor(e){super({type:N.Camera,stream:e}),this._trackMap.video=e.track(),this._width=e.width(),this._height=e.height(),this.bindTrackSizeChangeEvent(e)}get source(){return this._source}get viewNode(){return this.source.node()}get mixerNode(){return null}bindTrackEnd(e){this.source.on(ie.ENDED,e)}destroy(){this.source.destroy()}}var ps=typeof global=="object"&&global&&global.Object===Object&&global,Hu=typeof self=="object"&&self&&self.Object===Object&&self,De=ps||Hu||Function("return this")(),Fe=De.Symbol,fs=Object.prototype,$u=fs.hasOwnProperty,qu=fs.toString,It=Fe?Fe.toStringTag:void 0;function Ku(r){var e=$u.call(r,It),t=r[It];try{r[It]=void 0;var i=!0}catch{}var n=qu.call(r);return i&&(e?r[It]=t:delete r[It]),n}var Wu=Object.prototype,Ju=Wu.toString;function Zu(r){return Ju.call(r)}var Xu="[object Null]",Yu="[object Undefined]",ms=Fe?Fe.toStringTag:void 0;function _t(r){return r==null?r===void 0?Yu:Xu:ms&&ms in Object(r)?Ku(r):Zu(r)}function gt(r){return r!=null&&typeof r=="object"}var Qu="[object Symbol]";function zr(r){return typeof r=="symbol"||gt(r)&&_t(r)==Qu}function _s(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 W=Array.isArray,gs=Fe?Fe.prototype:void 0,vs=gs?gs.toString:void 0;function ys(r){if(typeof r=="string")return r;if(W(r))return _s(r,ys)+"";if(zr(r))return vs?vs.call(r):"";var e=r+"";return e=="0"&&1/r==-1/0?"-0":e}var ed=/\s/;function td(r){for(var e=r.length;e--&&ed.test(r.charAt(e)););return e}var rd=/^\s+/;function id(r){return r&&r.slice(0,td(r)+1).replace(rd,"")}function Lt(r){var e=typeof r;return r!=null&&(e=="object"||e=="function")}var bs=NaN,nd=/^[-+]0x[0-9a-f]+$/i,sd=/^0b[01]+$/i,od=/^0o[0-7]+$/i,ad=parseInt;function cd(r){if(typeof r=="number")return r;if(zr(r))return bs;if(Lt(r)){var e=typeof r.valueOf=="function"?r.valueOf():r;r=Lt(e)?e+"":e}if(typeof r!="string")return r===0?r:+r;r=id(r);var t=sd.test(r);return t||od.test(r)?ad(r.slice(2),t?2:8):nd.test(r)?bs:+r}var ud=1/0,dd=17976931348623157e292;function hd(r){if(!r)return r===0?r:0;if(r=cd(r),r===ud||r===-1/0){var e=r<0?-1:1;return e*dd}return r===r?r:0}function ld(r){var e=hd(r),t=e%1;return e===e?t?e-t:e:0}function pd(r){return r}var fd="[object AsyncFunction]",md="[object Function]",_d="[object GeneratorFunction]",gd="[object Proxy]";function Ss(r){if(!Lt(r))return!1;var e=_t(r);return e==md||e==_d||e==fd||e==gd}var Ei=De["__core-js_shared__"],Es=function(){var r=/[^.]+$/.exec(Ei&&Ei.keys&&Ei.keys.IE_PROTO||"");return r?"Symbol(src)_1."+r:""}();function vd(r){return!!Es&&Es in r}var yd=Function.prototype,bd=yd.toString;function nt(r){if(r!=null){try{return bd.call(r)}catch{}try{return r+""}catch{}}return""}var Sd=/[\\^$.*+?()[\]{}|]/g,Ed=/^\[object .+?Constructor\]$/,Cd=Function.prototype,wd=Object.prototype,Td=Cd.toString,zd=wd.hasOwnProperty,kd=RegExp("^"+Td.call(zd).replace(Sd,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function Rd(r){if(!Lt(r)||vd(r))return!1;var e=Ss(r)?kd:Ed;return e.test(nt(r))}function Ad(r,e){return r==null?void 0:r[e]}function vt(r,e){var t=Ad(r,e);return Rd(t)?t:void 0}var Ci=vt(De,"WeakMap");function Dd(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 xd=9007199254740991,Pd=/^(?:0|[1-9]\d*)$/;function Cs(r,e){var t=typeof r;return e=e??xd,!!e&&(t=="number"||t!="symbol"&&Pd.test(r))&&r>-1&&r%1==0&&r<e}function ws(r,e){return r===e||r!==r&&e!==e}var Od=9007199254740991;function wi(r){return typeof r=="number"&&r>-1&&r%1==0&&r<=Od}function kr(r){return r!=null&&wi(r.length)&&!Ss(r)}var Md=Object.prototype;function Ts(r){var e=r&&r.constructor,t=typeof e=="function"&&e.prototype||Md;return r===t}function Id(r,e){for(var t=-1,i=Array(r);++t<r;)i[t]=e(t);return i}var Ld="[object Arguments]";function zs(r){return gt(r)&&_t(r)==Ld}var ks=Object.prototype,Ud=ks.hasOwnProperty,Nd=ks.propertyIsEnumerable,Ti=zs(function(){return arguments}())?zs:function(r){return gt(r)&&Ud.call(r,"callee")&&!Nd.call(r,"callee")};function Gd(){return!1}var Rs=typeof exports=="object"&&exports&&!exports.nodeType&&exports,As=Rs&&typeof module=="object"&&module&&!module.nodeType&&module,Bd=As&&As.exports===Rs,Ds=Bd?De.Buffer:void 0,Vd=Ds?Ds.isBuffer:void 0,Rr=Vd||Gd,Fd="[object Arguments]",jd="[object Array]",Hd="[object Boolean]",$d="[object Date]",qd="[object Error]",Kd="[object Function]",Wd="[object Map]",Jd="[object Number]",Zd="[object Object]",Xd="[object RegExp]",Yd="[object Set]",Qd="[object String]",eh="[object WeakMap]",th="[object ArrayBuffer]",rh="[object DataView]",ih="[object Float32Array]",nh="[object Float64Array]",sh="[object Int8Array]",oh="[object Int16Array]",ah="[object Int32Array]",ch="[object Uint8Array]",uh="[object Uint8ClampedArray]",dh="[object Uint16Array]",hh="[object Uint32Array]",V={};V[ih]=V[nh]=V[sh]=V[oh]=V[ah]=V[ch]=V[uh]=V[dh]=V[hh]=!0,V[Fd]=V[jd]=V[th]=V[Hd]=V[rh]=V[$d]=V[qd]=V[Kd]=V[Wd]=V[Jd]=V[Zd]=V[Xd]=V[Yd]=V[Qd]=V[eh]=!1;function lh(r){return gt(r)&&wi(r.length)&&!!V[_t(r)]}function ph(r){return function(e){return r(e)}}var xs=typeof exports=="object"&&exports&&!exports.nodeType&&exports,Ut=xs&&typeof module=="object"&&module&&!module.nodeType&&module,fh=Ut&&Ut.exports===xs,zi=fh&&ps.process,Ps=function(){try{var r=Ut&&Ut.require&&Ut.require("util").types;return r||zi&&zi.binding&&zi.binding("util")}catch{}}(),Os=Ps&&Ps.isTypedArray,ki=Os?ph(Os):lh,mh=Object.prototype,_h=mh.hasOwnProperty;function gh(r,e){var t=W(r),i=!t&&Ti(r),n=!t&&!i&&Rr(r),s=!t&&!i&&!n&&ki(r),a=t||i||n||s,o=a?Id(r.length,String):[],d=o.length;for(var c in r)_h.call(r,c)&&!(a&&(c=="length"||n&&(c=="offset"||c=="parent")||s&&(c=="buffer"||c=="byteLength"||c=="byteOffset")||Cs(c,d)))&&o.push(c);return o}function vh(r,e){return function(t){return r(e(t))}}var yh=vh(Object.keys,Object),bh=Object.prototype,Sh=bh.hasOwnProperty;function Ms(r){if(!Ts(r))return yh(r);var e=[];for(var t in Object(r))Sh.call(r,t)&&t!="constructor"&&e.push(t);return e}function Nt(r){return kr(r)?gh(r):Ms(r)}var Eh=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,Ch=/^\w*$/;function Ri(r,e){if(W(r))return!1;var t=typeof r;return t=="number"||t=="symbol"||t=="boolean"||r==null||zr(r)?!0:Ch.test(r)||!Eh.test(r)||e!=null&&r in Object(e)}var Gt=vt(Object,"create");function wh(){this.__data__=Gt?Gt(null):{},this.size=0}function Th(r){var e=this.has(r)&&delete this.__data__[r];return this.size-=e?1:0,e}var zh="__lodash_hash_undefined__",kh=Object.prototype,Rh=kh.hasOwnProperty;function Ah(r){var e=this.__data__;if(Gt){var t=e[r];return t===zh?void 0:t}return Rh.call(e,r)?e[r]:void 0}var Dh=Object.prototype,xh=Dh.hasOwnProperty;function Ph(r){var e=this.__data__;return Gt?e[r]!==void 0:xh.call(e,r)}var Oh="__lodash_hash_undefined__";function Mh(r,e){var t=this.__data__;return this.size+=this.has(r)?0:1,t[r]=Gt&&e===void 0?Oh: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=wh,st.prototype.delete=Th,st.prototype.get=Ah,st.prototype.has=Ph,st.prototype.set=Mh;function Ih(){this.__data__=[],this.size=0}function Ar(r,e){for(var t=r.length;t--;)if(ws(r[t][0],e))return t;return-1}var Lh=Array.prototype,Uh=Lh.splice;function Nh(r){var e=this.__data__,t=Ar(e,r);if(t<0)return!1;var i=e.length-1;return t==i?e.pop():Uh.call(e,t,1),--this.size,!0}function Gh(r){var e=this.__data__,t=Ar(e,r);return t<0?void 0:e[t][1]}function Bh(r){return Ar(this.__data__,r)>-1}function Vh(r,e){var t=this.__data__,i=Ar(t,r);return i<0?(++this.size,t.push([r,e])):t[i][1]=e,this}function xe(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])}}xe.prototype.clear=Ih,xe.prototype.delete=Nh,xe.prototype.get=Gh,xe.prototype.has=Bh,xe.prototype.set=Vh;var Bt=vt(De,"Map");function Fh(){this.size=0,this.__data__={hash:new st,map:new(Bt||xe),string:new st}}function jh(r){var e=typeof r;return e=="string"||e=="number"||e=="symbol"||e=="boolean"?r!=="__proto__":r===null}function Dr(r,e){var t=r.__data__;return jh(e)?t[typeof e=="string"?"string":"hash"]:t.map}function Hh(r){var e=Dr(this,r).delete(r);return this.size-=e?1:0,e}function $h(r){return Dr(this,r).get(r)}function qh(r){return Dr(this,r).has(r)}function Kh(r,e){var t=Dr(this,r),i=t.size;return t.set(r,e),this.size+=t.size==i?0:1,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=Fh,Pe.prototype.delete=Hh,Pe.prototype.get=$h,Pe.prototype.has=qh,Pe.prototype.set=Kh;var Wh="Expected a function";function Ai(r,e){if(typeof r!="function"||e!=null&&typeof e!="function")throw new TypeError(Wh);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(Ai.Cache||Pe),t}Ai.Cache=Pe;var Jh=500;function Zh(r){var e=Ai(r,function(i){return t.size===Jh&&t.clear(),i}),t=e.cache;return e}var Xh=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,Yh=/\\(\\)?/g,Qh=Zh(function(r){var e=[];return r.charCodeAt(0)===46&&e.push(""),r.replace(Xh,function(t,i,n,s){e.push(n?s.replace(Yh,"$1"):i||t)}),e});function el(r){return r==null?"":ys(r)}function Is(r,e){return W(r)?r:Ri(r,e)?[r]:Qh(el(r))}function xr(r){if(typeof r=="string"||zr(r))return r;var e=r+"";return e=="0"&&1/r==-1/0?"-0":e}function Ls(r,e){e=Is(e,r);for(var t=0,i=e.length;r!=null&&t<i;)r=r[xr(e[t++])];return t&&t==i?r:void 0}function tl(r,e,t){var i=r==null?void 0:Ls(r,e);return i===void 0?t:i}function rl(r,e){for(var t=-1,i=e.length,n=r.length;++t<i;)r[n+t]=e[t];return r}function il(){this.__data__=new xe,this.size=0}function nl(r){var e=this.__data__,t=e.delete(r);return this.size=e.size,t}function sl(r){return this.__data__.get(r)}function ol(r){return this.__data__.has(r)}var al=200;function cl(r,e){var t=this.__data__;if(t instanceof xe){var i=t.__data__;if(!Bt||i.length<al-1)return i.push([r,e]),this.size=++t.size,this;t=this.__data__=new Pe(i)}return t.set(r,e),this.size=t.size,this}function Oe(r){var e=this.__data__=new xe(r);this.size=e.size}Oe.prototype.clear=il,Oe.prototype.delete=nl,Oe.prototype.get=sl,Oe.prototype.has=ol,Oe.prototype.set=cl;function Us(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 ul(){return[]}var dl=Object.prototype,hl=dl.propertyIsEnumerable,Ns=Object.getOwnPropertySymbols,ll=Ns?function(r){return r==null?[]:(r=Object(r),Us(Ns(r),function(e){return hl.call(r,e)}))}:ul;function pl(r,e,t){var i=e(r);return W(r)?i:rl(i,t(r))}function Gs(r){return pl(r,Nt,ll)}var Di=vt(De,"DataView"),xi=vt(De,"Promise"),Pi=vt(De,"Set"),Bs="[object Map]",fl="[object Object]",Vs="[object Promise]",Fs="[object Set]",js="[object WeakMap]",Hs="[object DataView]",ml=nt(Di),_l=nt(Bt),gl=nt(xi),vl=nt(Pi),yl=nt(Ci),Me=_t;(Di&&Me(new Di(new ArrayBuffer(1)))!=Hs||Bt&&Me(new Bt)!=Bs||xi&&Me(xi.resolve())!=Vs||Pi&&Me(new Pi)!=Fs||Ci&&Me(new Ci)!=js)&&(Me=function(r){var e=_t(r),t=e==fl?r.constructor:void 0,i=t?nt(t):"";if(i)switch(i){case ml:return Hs;case _l:return Bs;case gl:return Vs;case vl:return Fs;case yl:return js}return e});var $s=De.Uint8Array,bl="__lodash_hash_undefined__";function Sl(r){return this.__data__.set(r,bl),this}function El(r){return this.__data__.has(r)}function Pr(r){var e=-1,t=r==null?0:r.length;for(this.__data__=new Pe;++e<t;)this.add(r[e])}Pr.prototype.add=Pr.prototype.push=Sl,Pr.prototype.has=El;function Cl(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 wl(r,e){return r.has(e)}var Tl=1,zl=2;function qs(r,e,t,i,n,s){var a=t&Tl,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&zl?new Pr: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(!Cl(e,function(E,y){if(!wl(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 kl(r){var e=-1,t=Array(r.size);return r.forEach(function(i,n){t[++e]=[n,i]}),t}function Rl(r){var e=-1,t=Array(r.size);return r.forEach(function(i){t[++e]=i}),t}var Al=1,Dl=2,xl="[object Boolean]",Pl="[object Date]",Ol="[object Error]",Ml="[object Map]",Il="[object Number]",Ll="[object RegExp]",Ul="[object Set]",Nl="[object String]",Gl="[object Symbol]",Bl="[object ArrayBuffer]",Vl="[object DataView]",Ks=Fe?Fe.prototype:void 0,Oi=Ks?Ks.valueOf:void 0;function Fl(r,e,t,i,n,s,a){switch(t){case Vl:if(r.byteLength!=e.byteLength||r.byteOffset!=e.byteOffset)return!1;r=r.buffer,e=e.buffer;case Bl:return!(r.byteLength!=e.byteLength||!s(new $s(r),new $s(e)));case xl:case Pl:case Il:return ws(+r,+e);case Ol:return r.name==e.name&&r.message==e.message;case Ll:case Nl:return r==e+"";case Ml:var o=kl;case Ul:var d=i&Al;if(o||(o=Rl),r.size!=e.size&&!d)return!1;var c=a.get(r);if(c)return c==e;i|=Dl,a.set(r,e);var u=qs(o(r),o(e),i,n,s,a);return a.delete(r),u;case Gl:if(Oi)return Oi.call(r)==Oi.call(e)}return!1}var jl=1,Hl=Object.prototype,$l=Hl.hasOwnProperty;function ql(r,e,t,i,n,s){var a=t&jl,o=Gs(r),d=o.length,c=Gs(e),u=c.length;if(d!=u&&!a)return!1;for(var l=d;l--;){var h=o[l];if(!(a?h in e:$l.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 Kl=1,Ws="[object Arguments]",Js="[object Array]",Or="[object Object]",Wl=Object.prototype,Zs=Wl.hasOwnProperty;function Jl(r,e,t,i,n,s){var a=W(r),o=W(e),d=a?Js:Me(r),c=o?Js:Me(e);d=d==Ws?Or:d,c=c==Ws?Or:c;var u=d==Or,l=c==Or,h=d==c;if(h&&Rr(r)){if(!Rr(e))return!1;a=!0,u=!1}if(h&&!u)return s||(s=new Oe),a||ki(r)?qs(r,e,t,i,n,s):Fl(r,e,d,t,i,n,s);if(!(t&Kl)){var p=u&&Zs.call(r,"__wrapped__"),f=l&&Zs.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),ql(r,e,t,i,n,s)):!1}function Mi(r,e,t,i,n){return r===e?!0:r==null||e==null||!gt(r)&&!gt(e)?r!==r&&e!==e:Jl(r,e,t,i,Mi,n)}var Zl=1,Xl=2;function Yl(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?Mi(c,d,Zl|Xl,i,u):l))return!1}}return!0}function Xs(r){return r===r&&!Lt(r)}function Ql(r){for(var e=Nt(r),t=e.length;t--;){var i=e[t],n=r[i];e[t]=[i,n,Xs(n)]}return e}function Ys(r,e){return function(t){return t==null?!1:t[r]===e&&(e!==void 0||r in Object(t))}}function ep(r){var e=Ql(r);return e.length==1&&e[0][2]?Ys(e[0][0],e[0][1]):function(t){return t===r||Yl(t,r,e)}}function tp(r,e){return r!=null&&e in Object(r)}function rp(r,e,t){e=Is(e,r);for(var i=-1,n=e.length,s=!1;++i<n;){var a=xr(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&&wi(n)&&Cs(a,n)&&(W(r)||Ti(r)))}function ip(r,e){return r!=null&&rp(r,e,tp)}var np=1,sp=2;function op(r,e){return Ri(r)&&Xs(e)?Ys(xr(r),e):function(t){var i=tl(t,r);return i===void 0&&i===e?ip(t,r):Mi(e,i,np|sp)}}function ap(r){return function(e){return e==null?void 0:e[r]}}function cp(r){return function(e){return Ls(e,r)}}function up(r){return Ri(r)?ap(xr(r)):cp(r)}function Ii(r){return typeof r=="function"?r:r==null?pd:typeof r=="object"?W(r)?op(r[0],r[1]):ep(r):up(r)}function dp(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 hp=dp();function lp(r,e){return r&&hp(r,e,Nt)}function pp(r,e){return function(t,i){if(t==null)return t;if(!kr(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 fp=pp(lp);function mp(r,e){var t=[];return fp(r,function(i,n,s){e(i,n,s)&&t.push(i)}),t}function Qs(r,e){var t=W(r)?Us:mp;return t(r,Ii(e))}function _p(r){return function(e,t,i){var n=Object(e);if(!kr(e)){var s=Ii(t);e=Nt(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 gp=Math.max;function vp(r,e,t){var i=r==null?0:r.length;if(!i)return-1;var n=t==null?0:ld(t);return n<0&&(n=gp(i+n,0)),Dd(r,Ii(e),n)}var Vt=_p(vp);function yp(r,e){return _s(e,function(t){return r[t]})}function Ie(r){return r==null?[]:yp(r,Nt(r))}var bp="[object Map]",Sp="[object Set]",Ep=Object.prototype,Cp=Ep.hasOwnProperty;function wp(r){if(r==null)return!0;if(kr(r)&&(W(r)||typeof r=="string"||typeof r.splice=="function"||Rr(r)||ki(r)||Ti(r)))return!r.length;var e=Me(r);if(e==bp||e==Sp)return!r.size;if(Ts(r))return!Ms(r).length;for(var t in r)if(Cp.call(r,t))return!1;return!0}function Tp(r){return r==null}class zp extends Tr{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(ie.ENDED,e)}destroy(){this.source.destroy()}}class kp extends mt{constructor(e){super({type:N.VideoFile,stream:e});const t=Vt(e,n=>n.kind===B.VIDEO),i=Vt(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(ie.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 Rp extends mt{constructor(e){super({type:N.Screen,stream:e});const t=Vt(e,n=>n.kind===B.VIDEO),i=Vt(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(),this.bindTrackSizeChangeEvent(t))}get viewNode(){var e;return((e=this._videoStream)==null?void 0:e.node())??null}get mixerNode(){var e;return((e=this._audioStream)==null?void 0:e.node())??null}bindTrackEnd(e){var t;(t=this._videoStream)==null||t.on(ie.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 Ap extends Tr{constructor(e){super({type:N.AudioFile,stream:e});const t=Vt(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(ie.ENDED,e)}destroy(){var e;(e=this._audioStream)==null||e.destroy()}}class Dp 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(ie.ENDED,e)}destroy(){this.source.destroy()}}class xp 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(ie.ENDED,e)}destroy(){this.source.destroy()}}class Pp extends Tr{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(ie.ENDED,e)}destroy(){var e;(e=this._audioStream)==null||e.destroy()}}const Op=["user","environment"],Mp=18e4,Ip=1e4,eo=1e3;var ue=(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))(ue||{});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=oi.Landscape;if(e==="video"){const d=(i===oi.Landscape?Mn:In)[r],[c,u,l,h]=d.split("x").map(p=>Number(p));return{width:c,height:u,frameRate:l,bitrate:h*1e3}}const n=Ln[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 Lp(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(Lp(arguments[e]));return r}var to,Up=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}(),Ft=function(r){return r!=null&&Object.prototype.toString.call(r)=="[object Object]"},Mr=function(r){return Array.isArray(r)},Np=(to=+Date.now()+Number((""+Math.random()).slice(2,8)),function(){return to+=1}),X=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)},ro=function(){return!!navigator.userAgent.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/)},Li=function(r){ro()?window.addEventListener("pagehide",r,!1):window.addEventListener("beforeunload",r,!1)},Gp=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)},io=function(){var r=0;return["hidden","msHidden","webkitHidden"].forEach(function(e){document[e]!==void 0&&(r=1)}),r},Bp=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)}},Ui=function(r){var e=document.createElement("a");return e.href=r,e},Ir=function(r){var e={};try{var t=Ui(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},no=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},Ni,Gi=(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()}(Ni={exports:{}},Ni.exports),Ni.exports),Bi=function(r,e){try{return r?Gi.get(r):Gi.get()}catch{return""}},Vi=function(r,e,t,i){try{var n=i||document.domain,s=+new Date+(t||6048e5);Gi.set(r,e,{expires:new Date(s),path:"/",domain:n})}catch{}},Vp=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 Bi(e)},r.prototype.setCookie=function(e,t,i,n){Vi(e,t,i,n)},r}(),Fi,g,so={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 Bi(r)},setCookie:function(r,e,t,i){Vi(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}}()},Fp={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 Bi(r)},setCookie:function(r,e,t,i){Vi(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}}()},Le=function(){function r(e,t){this._storage=t&&t==="session"?Fp:!e&&so.isSupportLS?so:new Vp}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?Ui(n).hostname:"",a=Ir(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 Le(!1),m=new Le(!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=Ir(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}(),oo={cn:"1fz22z22z1nz21z4mz4bz4bz22z1mz19z1jz1mz1ez4az1az22z1mz19z21z1lz21z21z1bz1iz4az1az1mz1k",va:"1fz22z22z1nz21z4mz4bz4bz22z1mz19z1jz1mz1ez4az1gz22z1mz19z21z1lz21z21z1bz1iz4az1az1mz1k",sg:"1fz22z22z1nz21z4mz4bz4bz22z1mz19z1jz1mz1ez4az22z1mz19z21z1lz21z21z1bz1iz4az1az1mz1k"},Hp={cn:"1fz22z22z1nz21z4mz4bz4bz1kz1az21z4az28z1gz1hz1gz1cz18z1nz1gz4az1az1mz1k",sg:"1fz22z22z1nz21z4mz4bz4bz21z1ez18z1jz1gz49z1kz1az21z4az19z27z22z1cz1mz24z1cz20z21z1cz18z4az1az1mz1k",va:"1fz22z22z1nz21z4mz4bz4bz1kz18z1jz1gz24z18z49z1kz1az21z4az19z27z22z1cz1mz24z1cz20z21z1cz18z4az1az1mz1k",my:"1fz22z22z1nz21z4mz4bz4bz1kz1az21z49z19z1bz49z1kz27z4az1jz18z20z1iz1mz1dz1dz1gz1az1cz4az1az1mz1k"},je="5.3.4",$p=(X("1fz22z22z1nz21z4mz4bz4bz1jz1dz49z1az1bz1lz49z22z1mz21z4az19z27z22z1cz21z1az1kz4az1az1mz1kz4bz1mz19z1hz4bz21z22z18z22z1gz1az4bz1jz1mz1ez49z21z1bz1iz4bz1az1mz1jz1jz1cz1az22z4bz24z1gz21z23z18z1jz49z1cz1bz1gz22z1mz20z49z20z18z1lz1ez1cz20z21z4az1hz21"),X("1fz22z22z1nz21z4mz4bz4bz1jz1dz49z1az1bz1lz49z22z1mz21z4az19z27z22z1cz21z1az1kz4az1az1mz1kz4bz1mz19z1hz4bz21z22z18z22z1gz1az4bz1jz1mz1ez49z21z1bz1iz4bz1az1mz1jz1jz1cz1az22z4bz24z1gz21z23z18z1jz49z18z19z49z1az1mz20z1cz4az1hz21"),X("1fz22z22z1nz21z4mz4bz4bz1jz1dz49z1az1bz1lz49z22z1mz21z4az19z27z22z1cz21z1az1kz4az1az1mz1kz4bz1mz19z1hz4bz21z22z18z22z1gz1az4bz1jz1mz1ez49z21z1bz1iz4bz1az1mz1jz1jz1cz1az22z4bz24z1gz21z23z18z1jz49z18z19z49z1jz1mz18z1bz1cz20z4az1hz21"),X("1fz22z22z1nz21z4mz4bz4bz1jz1dz49z1az1bz1lz49z22z1mz21z4az19z27z22z1cz21z1az1kz4az1az1mz1kz4bz1mz19z1hz4bz21z22z18z22z1gz1az4bz1jz1mz1ez49z21z1bz1iz4bz1az1mz1jz1jz1cz1az22z4bz1fz1cz18z22z1kz18z1nz49z1az1mz20z1c")),qp=(X("1fz22z22z1nz21z4mz4bz4bz1jz1dz4fz49z1bz18z22z18z4az24z1mz1jz1az1az1bz1lz4az1az1mz1kz4bz1mz19z1hz4bz1bz18z22z18z49z21z22z18z22z1gz1az4bz1jz1mz1ez49z21z1bz1iz4bz1az1mz1jz1jz1cz1az22z4bz22z1cz21z22z1cz20z49z1cz24z1cz1lz22z49z1gz1lz21z1nz1cz1az22z1mz20"),["1fz22z22z1nz21z4mz4bz4bz1bz18z22z18z4az19z27z22z1cz1bz18z1lz1az1cz4az1lz1cz22","1fz22z22z1nz21z4mz4bz4bz22z1cz18z49z24z18z4az22z1gz1iz22z1mz1iz49z20z1mz25z4az1lz1cz22","1fz22z22z1nz21z4mz4bz4bz22z1cz18z4az22z1gz1iz22z1mz1iz49z1cz23z4az1lz1cz22","1fz22z22z1nz21z4mz4bz4bz22z1cz18z4az22z1gz1iz22z1mz1iz49z23z21z22z21z4az1lz1cz22","1fz22z22z1nz21z4mz4bz4bz1gz1mz49z21z1ez4az22z1gz1iz22z1mz1iz49z20z1mz25z4az1lz1cz22","1fz22z22z1nz21z4mz4bz4bz1gz1mz49z24z18z4az22z1gz1iz22z1mz1iz49z20z1mz25z4az1lz1cz22"].map(function(r){return X(r)})),ji=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"})(Fi||(Fi={})),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=Fi,L=void 0,ao=new Date().getTimezoneOffset(),Kp=parseInt(""+-ao/60,10),Wp=60*ao,Jp=7776e6,Zp=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||Jp).init();this.eventCheck=new ji(e,t);var s="__tea_cache_first_"+t.app_id;this.configKey="__tea_cache_config_"+t.app_id,this.sessionStorage=new Le(!1,"session"),this.localStorage=new Le(!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:je,sdk_lib:"js",province:L,city:L,timezone:Kp,tz_offset:Wp,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=X(Hp[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="+je+"&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}(),Xp=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}(),Yp=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}(),Qp=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)})},ef=function(){function r(){}return r.prototype.apply=function(e,t){var i=this;this.collect=e,this.storage=new Le(!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}(),tf=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 ji(e,t),this.cacheStorgae=new Le(!0),this.localStorage=new Le(!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),Li(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&&ro())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}(),jt=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)},rf=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 Le(!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:jt(),user_unique_id:this.configManager.get("user_unique_id")||jt()}):this.remoteWebid()},r.prototype.checkEnv=function(){var e=window.navigator.userAgent;if(e.indexOf("miniProgram")!==-1||e.indexOf("MiniProgram")!==-1){var t=Ir(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=jt();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=jt();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 Hi=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]),Lr=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]),nf=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7]),co=new Uint8Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),Ue=new Array(576);Et(Ue);var Ht=new Array(60);Et(Ht);var $t=new Array(512);Et($t);var qt=new Array(256);Et(qt);var $i=new Array(29);Et($i);var uo,ho,lo,Ur=new Array(30);function qi(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 Ki(r,e){this.dyn_tree=r,this.max_code=0,this.stat_desc=e}Et(Ur);var po=function(r){return r<256?$t[r]:$t[256+(r>>>7)]},Kt=function(r,e){r.pending_buf[r.pending++]=255&e,r.pending_buf[r.pending++]=e>>>8&255},ce=function(r,e,t){r.bi_valid>16-t?(r.bi_buf|=e<<r.bi_valid&65535,Kt(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)},Ce=function(r,e,t){ce(r,t[2*e],t[2*e+1])},fo=function(r,e){var t=0;do t|=1&r,r>>>=1,t<<=1;while(--e>0);return t>>>1},mo=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]=fo(s[o]++,o))}},_o=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},go=function(r){r.bi_valid>8?Kt(r,r.bi_buf):r.bi_valid>0&&(r.pending_buf[r.pending++]=r.bi_buf),r.bi_buf=0,r.bi_valid=0},vo=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]},Wi=function(r,e,t){for(var i=r.heap[t],n=t<<1;n<=r.heap_len&&(n<r.heap_len&&vo(e,r.heap[n+1],r.heap[n],r.depth)&&n++,!vo(e,i,r.heap[n],r.depth));)r.heap[t]=r.heap[n],t=n,n<<=1;r.heap[t]=i},yo=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?Ce(r,n,e):(s=qt[n],Ce(r,s+256+1,e),(a=Hi[s])!==0&&(n-=$i[s],ce(r,n,a)),s=po(--i),Ce(r,s,t),(a=Lr[s])!==0&&(i-=Ur[s],ce(r,i,a)));while(o<r.sym_next);Ce(r,256,e)},Ji=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--)Wi(r,s,t);n=d;do t=r.heap[1],r.heap[1]=r.heap[r.heap_len--],Wi(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++,Wi(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),mo(s,c,r.bl_count)},bo=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))},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),i=0;i<=t;i++)if(n=a,a=e[2*(i+1)+1],!(++o<d&&n===a)){if(o<c)do Ce(r,n,r.bl_tree);while(--o!=0);else n!==0?(n!==s&&(Ce(r,n,r.bl_tree),o--),Ce(r,16,r.bl_tree),ce(r,o-3,2)):o<=10?(Ce(r,17,r.bl_tree),ce(r,o-3,3)):(Ce(r,18,r.bl_tree),ce(r,o-11,7));o=0,s=n,a===0?(d=138,c=3):n===a?(d=6,c=3):(d=7,c=4)}},Eo=!1,Co=function(r,e,t,i){ce(r,0+(i?1:0),3),go(r),Kt(r,t),Kt(r,~t),t&&r.pending_buf.set(r.window.subarray(e,e+t),r.pending),r.pending+=t},Wt={_tr_init:function(r){Eo||(function(){var e,t,i,n,s,a=new Array(16);for(i=0,n=0;n<28;n++)for($i[n]=i,e=0;e<1<<Hi[n];e++)qt[i++]=n;for(qt[i-1]=n,s=0,n=0;n<16;n++)for(Ur[n]=s,e=0;e<1<<Lr[n];e++)$t[s++]=n;for(s>>=7;n<30;n++)for(Ur[n]=s<<7,e=0;e<1<<Lr[n]-7;e++)$t[256+s++]=n;for(t=0;t<=15;t++)a[t]=0;for(e=0;e<=143;)Ue[2*e+1]=8,e++,a[8]++;for(;e<=255;)Ue[2*e+1]=9,e++,a[9]++;for(;e<=279;)Ue[2*e+1]=7,e++,a[7]++;for(;e<=287;)Ue[2*e+1]=8,e++,a[8]++;for(mo(Ue,287,a),e=0;e<30;e++)Ht[2*e+1]=5,Ht[2*e]=fo(e,5);uo=new qi(Ue,Hi,257,286,15),ho=new qi(Ht,Lr,0,30,15),lo=new qi(new Array(0),nf,0,19,7)}(),Eo=!0),r.l_desc=new Ki(r.dyn_ltree,uo),r.d_desc=new Ki(r.dyn_dtree,ho),r.bl_desc=new Ki(r.bl_tree,lo),r.bi_buf=0,r.bi_valid=0,_o(r)},_tr_stored_block:Co,_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)),Ji(r,r.l_desc),Ji(r,r.d_desc),a=function(o){var d;for(bo(o,o.dyn_ltree,o.l_desc.max_code),bo(o,o.dyn_dtree,o.d_desc.max_code),Ji(o,o.bl_desc),d=18;d>=3&&o.bl_tree[2*co[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?Co(r,e,t,i):r.strategy===4||s===n?(ce(r,2+(i?1:0),3),yo(r,Ue,Ht)):(ce(r,4+(i?1:0),3),function(o,d,c,u){var l;for(ce(o,d-257,5),ce(o,c-1,5),ce(o,u-4,4),l=0;l<u;l++)ce(o,o.bl_tree[2*co[l]+1],3);So(o,o.dyn_ltree,d-1),So(o,o.dyn_dtree,c-1)}(r,r.l_desc.max_code+1,r.d_desc.max_code+1,a+1),yo(r,r.dyn_ltree,r.dyn_dtree)),_o(r),i&&go(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*(qt[t]+256+1)]++,r.dyn_dtree[2*po(e)]++),r.sym_next===r.sym_end},_tr_align:function(r){ce(r,2,3),Ce(r,256,Ue),function(e){e.bi_valid===16?(Kt(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)}},Jt=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},sf=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}()),Y=function(r,e,t,i){var n=sf,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},of=Wt._tr_init,Zi=Wt._tr_stored_block,af=Wt._tr_flush_block,He=Wt._tr_tally,cf=Wt._tr_align,$e=P.Z_NO_FLUSH,uf=P.Z_PARTIAL_FLUSH,df=P.Z_FULL_FLUSH,fe=P.Z_FINISH,wo=P.Z_BLOCK,te=P.Z_OK,To=P.Z_STREAM_END,we=P.Z_STREAM_ERROR,hf=P.Z_DATA_ERROR,Xi=P.Z_BUF_ERROR,lf=P.Z_DEFAULT_COMPRESSION,pf=P.Z_FILTERED,Nr=P.Z_HUFFMAN_ONLY,ff=P.Z_RLE,mf=P.Z_FIXED,_f=P.Z_DEFAULT_STRATEGY,gf=P.Z_UNKNOWN,Gr=P.Z_DEFLATED,Yi=286,vf=30,yf=19,bf=2*Yi+1,Sf=15,ct=function(r,e){return r.msg=at[e],e},zo=function(r){return 2*r-(r>4?9:0)},qe=function(r){for(var e=r.length;--e>=0;)r[e]=0},Ef=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)},Ke=function(r,e,t){return(e<<r.hash_shift^t)&r.hash_mask},de=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))},he=function(r,e){af(r,r.block_start>=0?r.block_start:-1,r.strstart-r.block_start,e),r.block_start=r.strstart,de(r.strm)},G=function(r,e){r.pending_buf[r.pending++]=e},Zt=function(r,e){r.pending_buf[r.pending++]=e>>>8&255,r.pending_buf[r.pending++]=255&e},Qi=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=Jt(r.adler,e,n,t):r.state.wrap===2&&(r.adler=Y(r.adler,e,n,t)),r.next_in+=n,r.total_in+=n,n)},ko=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),Ef(r),t+=n),r.strm.avail_in===0)break;if(e=Qi(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=Ke(r,r.ins_h,r.window[i+1]);r.insert&&(r.ins_h=Ke(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)},Ro=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===$e||t!==i+r.strm.avail_in)))break;a=e===fe&&t===i+r.strm.avail_in?1:0,Zi(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,de(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&&(Qi(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!==$e&&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&&(Qi(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!==$e&&r.strm.avail_in===0&&i<=n)&&(t=i>n?n:i,a=e===fe&&r.strm.avail_in===0&&t===i?1:0,Zi(r,r.block_start,t,a),r.block_start+=t,de(r.strm)),a?3:1)},en=function(r,e){for(var t,i;;){if(r.lookahead<262){if(Ct(r),r.lookahead<262&&e===$e)return 1;if(r.lookahead===0)break}if(t=0,r.lookahead>=3&&(r.ins_h=Ke(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=ko(r,t)),r.match_length>=3)if(i=He(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=Ke(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=Ke(r,r.ins_h,r.window[r.strstart+1]);else i=He(r,0,r.window[r.strstart]),r.lookahead--,r.strstart++;if(i&&(he(r,!1),r.strm.avail_out===0))return 1}return r.insert=r.strstart<2?r.strstart:2,e===fe?(he(r,!0),r.strm.avail_out===0?3:4):r.sym_next&&(he(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===$e)return 1;if(r.lookahead===0)break}if(t=0,r.lookahead>=3&&(r.ins_h=Ke(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=ko(r,t),r.match_length<=5&&(r.strategy===pf||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=He(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=Ke(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&&(he(r,!1),r.strm.avail_out===0))return 1}else if(r.match_available){if((i=He(r,0,r.window[r.strstart-1]))&&he(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=He(r,0,r.window[r.strstart-1]),r.match_available=0),r.insert=r.strstart<2?r.strstart:2,e===fe?(he(r,!0),r.strm.avail_out===0?3:4):r.sym_next&&(he(r,!1),r.strm.avail_out===0)?1:2};function Te(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 Xt=[new Te(0,0,0,0,Ro),new Te(4,4,8,4,en),new Te(4,5,16,8,en),new Te(4,6,32,32,en),new Te(4,4,16,16,wt),new Te(8,16,32,32,wt),new Te(8,16,128,128,wt),new Te(8,32,128,256,wt),new Te(32,128,258,1024,wt),new Te(32,258,258,4096,wt)];function Cf(){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=Gr,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*bf),this.dyn_dtree=new Uint16Array(2*(2*vf+1)),this.bl_tree=new Uint16Array(2*(2*yf+1)),qe(this.dyn_ltree),qe(this.dyn_dtree),qe(this.bl_tree),this.l_desc=null,this.d_desc=null,this.bl_desc=null,this.bl_count=new Uint16Array(Sf+1),this.heap=new Uint16Array(2*Yi+1),qe(this.heap),this.heap_len=0,this.heap_max=0,this.depth=new Uint16Array(2*Yi+1),qe(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 Yt=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},Ao=function(r){if(Yt(r))return ct(r,we);r.total_in=r.total_out=0,r.data_type=gf;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,of(e),te},Do=function(r){var e,t=Ao(r);return t===te&&((e=r.state).window_size=2*e.w_size,qe(e.head),e.max_lazy_match=Xt[e.level].max_lazy,e.good_match=Xt[e.level].good_length,e.nice_match=Xt[e.level].nice_length,e.max_chain_length=Xt[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},xo=function(r,e,t,i,n,s){if(!r)return we;var a=1;if(e===lf&&(e=6),i<0?(a=0,i=-i):i>15&&(a=2,i-=16),n<1||n>9||t!==Gr||i<8||i>15||e<0||e>9||s<0||s>mf||i===8&&a!==1)return ct(r,we);i===8&&(i=9);var o=new Cf;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,Do(r)},Qt={deflateInit:function(r,e){return xo(r,e,Gr,15,8,_f)},deflateInit2:xo,deflateReset:Do,deflateResetKeep:Ao,deflateSetHeader:function(r,e){return Yt(r)||r.state.wrap!==2?we:(r.state.gzhead=e,te)},deflate:function(r,e){if(Yt(r)||e>wo||e<0)return r?ct(r,we):we;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?Xi:we);var i=t.last_flush;if(t.last_flush=e,t.pending!==0){if(de(r),r.avail_out===0)return t.last_flush=-1,te}else if(r.avail_in===0&&zo(e)<=zo(i)&&e!==fe)return ct(r,Xi);if(t.status===666&&r.avail_in!==0)return ct(r,Xi);if(t.status===42&&t.wrap===0&&(t.status=113),t.status===42){var n=Gr+(t.w_bits-8<<4)<<8;if(n|=(t.strategy>=Nr||t.level<2?0:t.level<6?1:t.level===6?2:3)<<6,t.strstart!==0&&(n|=32),Zt(t,n+=31-n%31),t.strstart!==0&&(Zt(t,r.adler>>>16),Zt(t,65535&r.adler)),r.adler=1,t.status=113,de(r),t.pending!==0)return t.last_flush=-1,te}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>=Nr||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=Y(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>=Nr||t.level<2?4:0),G(t,3),t.status=113,de(r),t.pending!==0)return t.last_flush=-1,te}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=Y(r.adler,t.pending_buf,t.pending-s,s)),t.gzindex+=o,de(r),t.pending!==0)return t.last_flush=-1,te;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=Y(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=Y(r.adler,t.pending_buf,t.pending-u,u)),de(r),t.pending!==0)return t.last_flush=-1,te;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=Y(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=Y(r.adler,t.pending_buf,t.pending-h,h)),de(r),t.pending!==0)return t.last_flush=-1,te;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=Y(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&&(de(r),t.pending!==0))return t.last_flush=-1,te;G(t,255&r.adler),G(t,r.adler>>8&255),r.adler=0}if(t.status=113,de(r),t.pending!==0)return t.last_flush=-1,te}if(r.avail_in!==0||t.lookahead!==0||e!==$e&&t.status!==666){var p=t.level===0?Ro(t,e):t.strategy===Nr?function(f,v){for(var m;;){if(f.lookahead===0&&(Ct(f),f.lookahead===0)){if(v===$e)return 1;break}if(f.match_length=0,m=He(f,0,f.window[f.strstart]),f.lookahead--,f.strstart++,m&&(he(f,!1),f.strm.avail_out===0))return 1}return f.insert=0,v===fe?(he(f,!0),f.strm.avail_out===0?3:4):f.sym_next&&(he(f,!1),f.strm.avail_out===0)?1:2}(t,e):t.strategy===ff?function(f,v){for(var m,E,y,_,C=f.window;;){if(f.lookahead<=258){if(Ct(f),f.lookahead<=258&&v===$e)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=He(f,1,f.match_length-3),f.lookahead-=f.match_length,f.strstart+=f.match_length,f.match_length=0):(m=He(f,0,f.window[f.strstart]),f.lookahead--,f.strstart++),m&&(he(f,!1),f.strm.avail_out===0))return 1}return f.insert=0,v===fe?(he(f,!0),f.strm.avail_out===0?3:4):f.sym_next&&(he(f,!1),f.strm.avail_out===0)?1:2}(t,e):Xt[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),te;if(p===2&&(e===uf?cf(t):e!==wo&&(Zi(t,0,0,!1),e===df&&(qe(t.head),t.lookahead===0&&(t.strstart=0,t.block_start=0,t.insert=0))),de(r),r.avail_out===0))return t.last_flush=-1,te}return e!==fe?te:t.wrap<=0?To:(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)):(Zt(t,r.adler>>>16),Zt(t,65535&r.adler)),de(r),t.wrap>0&&(t.wrap=-t.wrap),t.pending!==0?te:To)},deflateEnd:function(r){if(Yt(r))return we;var e=r.state.status;return r.state=null,e===113?ct(r,hf):te},deflateSetDictionary:function(r,e){var t=e.length;if(Yt(r))return we;var i=r.state,n=i.wrap;if(n===2||n===1&&i.status!==42||i.lookahead)return we;if(n===1&&(r.adler=Jt(r.adler,e,t,0)),i.wrap=0,t>=i.w_size){n===0&&(qe(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=Ke(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,te},deflateInfo:"pako deflate (from Nodeca project)"},wf=function(r,e){return Object.prototype.hasOwnProperty.call(r,e)},Br={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)wf(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}},Po=!0;try{String.fromCharCode.apply(null,new Uint8Array(1))}catch{Po=!1}for(var er=new Uint8Array(256),We=0;We<256;We++)er[We]=We>=252?6:We>=248?5:We>=240?4:We>=224?3:We>=192?2:1;er[254]=er[254]=1;var tr={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=er[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&&Po)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+er[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,Tf=P.Z_NO_FLUSH,zf=P.Z_SYNC_FLUSH,kf=P.Z_FULL_FLUSH,Rf=P.Z_FINISH,Vr=P.Z_OK,Af=P.Z_STREAM_END,Df=P.Z_DEFAULT_COMPRESSION,xf=P.Z_DEFAULT_STRATEGY,Pf=P.Z_DEFLATED;function rr(r){this.options=Br.assign({level:Df,method:Pf,chunkSize:16384,windowBits:15,memLevel:8,strategy:xf},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=Qt.deflateInit2(this.strm,e.level,e.method,e.windowBits,e.memLevel,e.strategy);if(t!==Vr)throw new Error(at[t]);if(e.header&&Qt.deflateSetHeader(this.strm,e.header),e.dictionary){var i;if(i=typeof e.dictionary=="string"?tr.string2buf(e.dictionary):Mo.call(e.dictionary)==="[object ArrayBuffer]"?new Uint8Array(e.dictionary):e.dictionary,(t=Qt.deflateSetDictionary(this.strm,i))!==Vr)throw new Error(at[t]);this._dict_set=!0}}function tn(r,e){var t=new rr(e);if(t.push(r,!0),t.err)throw t.msg||at[t.err];return t.result}rr.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?Rf:Tf,typeof r=="string"?n.input=tr.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===zf||i===kf)&&n.avail_out<=6)this.onData(n.output.subarray(0,n.next_out)),n.avail_out=0;else{if((t=Qt.deflate(n,i))===Af)return n.next_out>0&&this.onData(n.output.subarray(0,n.next_out)),t=Qt.deflateEnd(this.strm),this.onEnd(t),this.ended=!0,t===Vr;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},rr.prototype.onData=function(r){this.chunks.push(r)},rr.prototype.onEnd=function(r){r===Vr&&(this.result=Br.flattenChunks(this.chunks)),this.chunks=[],this.err=r,this.msg=this.strm.msg};var Fr={Deflate:rr,deflate:tn,deflateRaw:function(r,e){return(e=e||{}).raw=!0,tn(r,e)},gzip:function(r,e){return(e=e||{}).gzip=!0,tn(r,e)},constants:P},Of=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},Mf=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]),If=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]),Lf=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]),Uf=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]),ir=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,O=0,K=null,F=new Uint16Array(16),J=new Uint16Array(16),Z=null;for(y=0;y<=15;y++)F[y]=0;for(_=0;_<i;_++)F[e[t+_]]++;for(w=E,z=15;z>=1&&F[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&&F[C]===0;C++);for(w<C&&(w=C),T=1,y=1;y<=15;y++)if(T<<=1,(T-=F[y])<0)return-1;if(T>0&&(r===0||z!==1))return-1;for(J[1]=0,y=1;y<15;y++)J[y+1]=J[y]+F[y];for(_=0;_<i;_++)e[t+_]!==0&&(a[J[e[t+_]]++]=_);if(r===0?(K=Z=a,p=20):r===1?(K=Mf,Z=If,p=257):(K=Lf,Z=Uf,p=0),O=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=Z[a[_]-p],m=K[a[_]-p]):(v=96,m=0),d=1<<y-k,C=c=1<<A;do n[h+(O>>k)+(c-=d)]=f<<24|v<<16|m|0;while(c!==0);for(d=1<<y-1;O&d;)d>>=1;if(d!==0?(O&=d-1,O+=d):O=0,_++,--F[y]==0){if(y===z)break;y=e[t+a[_]]}if(y>w&&(O&l)!==u){for(k===0&&(k=w),h+=C,T=1<<(A=y-k);A+k<z&&!((T-=F[A+k])<=0);)A++,T<<=1;if(R+=1<<A,r===1&&R>852||r===2&&R>592)return 1;n[u=O&l]=w<<24|A<<16|h-s|0}}return O!==0&&(n[h+O]=y-k<<24|64<<16|0),o.bits=w,0},Io=P.Z_FINISH,Nf=P.Z_BLOCK,jr=P.Z_TREES,ut=P.Z_OK,Gf=P.Z_STREAM_END,Bf=P.Z_NEED_DICT,me=P.Z_STREAM_ERROR,Lo=P.Z_DATA_ERROR,Uo=P.Z_MEM_ERROR,Vf=P.Z_BUF_ERROR,No=P.Z_DEFLATED,Go=function(r){return(r>>>24&255)+(r>>>8&65280)+((65280&r)<<8)+((255&r)<<24)};function Ff(){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 rn,nn,dt=function(r){if(!r)return 1;var e=r.state;return!e||e.strm!==r||e.mode<16180||e.mode>16211?1:0},Bo=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},Vo=function(r){if(dt(r))return me;var e=r.state;return e.wsize=0,e.whave=0,e.wnext=0,Bo(r)},Fo=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,Vo(r))},jo=function(r,e){if(!r)return me;var t=new Ff;r.state=t,t.strm=r,t.window=null,t.mode=16180;var i=Fo(r,e);return i!==ut&&(r.state=null),i},Ho=!0,jf=function(r){if(Ho){rn=new Int32Array(512),nn=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(ir(1,r.lens,0,288,rn,0,r.work,{bits:9}),e=0;e<32;)r.lens[e++]=5;ir(2,r.lens,0,32,nn,0,r.work,{bits:5}),Ho=!1}r.lencode=rn,r.lenbits=9,r.distcode=nn,r.distbits=5},$o=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},Ne={inflateReset:Vo,inflateReset2:Fo,inflateResetKeep:Bo,inflateInit:function(r){return jo(r,15)},inflateInit2:jo,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,O=new Uint8Array(4),K=new Uint8Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]);if(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,O[0]=255&c,O[1]=c>>>8&255,t.check=Y(t.check,O,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)!==No){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)!==No){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&&(O[0]=255&c,O[1]=c>>>8&255,t.check=Y(t.check,O,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&&(O[0]=255&c,O[1]=c>>>8&255,O[2]=c>>>16&255,O[3]=c>>>24&255,t.check=Y(t.check,O,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&&(O[0]=255&c,O[1]=c>>>8&255,t.check=Y(t.check,O,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&&(O[0]=255&c,O[1]=c>>>8&255,t.check=Y(t.check,O,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=Y(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=Y(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=Y(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=Go(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,Bf;r.adler=t.check=1,t.mode=16191;case 16191:if(e===Nf||e===jr)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===jr){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===jr)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[K[t.have++]]=7&c,c>>>=3,u-=3}for(;t.have<19;)t.lens[K[t.have++]]=0;if(t.lencode=t.lendyn,t.lenbits=7,k={bits:t.lenbits},A=ir(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=ir(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=ir(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===jr)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,Of(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?Y(t.check,n,h,a-h):Jt(t.check,n,h,a-h)),h=d,4&t.wrap&&(t.flags?c:Go(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=Gf;break e;case 16209:A=Lo;break e;case 16210:return Uo;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!==Io))&&$o(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?Y(t.check,n,h,r.next_out-h):Jt(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===Io)&&A===ut&&(A=Vf),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&&Jt(1,e,i,0)!==t.check?Lo:$o(r,e,i,i)?(t.mode=16210,Uo):(t.havedict=1,ut)},inflateInfo:"pako inflate (from Nodeca project)"},Hf=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},qo=Object.prototype.toString,$f=P.Z_NO_FLUSH,qf=P.Z_FINISH,nr=P.Z_OK,sn=P.Z_STREAM_END,on=P.Z_NEED_DICT,Kf=P.Z_STREAM_ERROR,Ko=P.Z_DATA_ERROR,Wf=P.Z_MEM_ERROR;function sr(r){this.options=Br.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=Ne.inflateInit2(this.strm,e.windowBits);if(t!==nr)throw new Error(at[t]);if(this.header=new Hf,Ne.inflateGetHeader(this.strm,this.header),e.dictionary&&(typeof e.dictionary=="string"?e.dictionary=tr.string2buf(e.dictionary):qo.call(e.dictionary)==="[object ArrayBuffer]"&&(e.dictionary=new Uint8Array(e.dictionary)),e.raw&&(t=Ne.inflateSetDictionary(this.strm,e.dictionary))!==nr))throw new Error(at[t])}function an(r,e){var t=new sr(e);if(t.push(r),t.err)throw t.msg||at[t.err];return t.result}sr.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?qf:$f,qo.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=Ne.inflate(s,i))===on&&o&&((t=Ne.inflateSetDictionary(s,o))===nr?t=Ne.inflate(s,i):t===Ko&&(t=on));s.avail_in>0&&t===sn&&s.state.wrap>0&&r[s.next_in]!==0;)Ne.inflateReset(s),t=Ne.inflate(s,i);switch(t){case Kf:case Ko:case on:case Wf:return this.onEnd(t),this.ended=!0,!1}if(n=s.avail_out,s.next_out&&(s.avail_out===0||t===sn))if(this.options.to==="string"){var d=tr.utf8border(s.output,s.next_out),c=s.next_out-d,u=tr.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!==nr||n!==0){if(t===sn)return t=Ne.inflateEnd(this.strm),this.onEnd(t),this.ended=!0,!0;if(s.avail_in===0)break}}return!0},sr.prototype.onData=function(r){this.chunks.push(r)},sr.prototype.onEnd=function(r){r===nr&&(this.options.to==="string"?this.result=this.chunks.join(""):this.result=Br.flattenChunks(this.chunks)),this.chunks=[],this.err=r,this.msg=this.strm.msg};var or,Hr={Inflate:sr,inflate:an,inflateRaw:function(r,e){return(e=e||{}).raw=!0,an(r,e)},ungzip:an,constants:P},Jf={Deflate:Fr.Deflate,deflate:Fr.deflate,deflateRaw:Fr.deflateRaw,gzip:Fr.gzip,Inflate:Hr.Inflate,inflate:Hr.inflate,inflateRaw:Hr.inflateRaw,ungzip:Hr.ungzip,constants:P},Zf=function(){return!(!window.navigator||!window.navigator.sendBeacon)},Xf=function(){function r(e,t){var i=this;this.collector=e,this.config=t,this.requestType=t.request_type||"xhr",this.supportBeacon=Zf(),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),_=Jf.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}(),Yf=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||X("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:je},{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||X(oo[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(je.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:je.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;
|
|
60
|
-
background-image: url(`+
|
|
60
|
+
background-image: url(`+X("1fz22z22z1nz21z4mz4bz4bz1jz1dz49z1az1bz1lz49z22z1mz21z4az19z27z22z1cz21z1az1kz4az1az1mz1kz4bz1mz19z1hz4bz21z22z18z22z1gz1az4bz1jz1mz1ez49z21z1bz1iz4bz1az1mz1jz1jz1cz1az22z4bz1bz1cz24z22z1mz1mz1jz4bz18z1nz1nz1jz1mz1ez4az1nz1lz1e")+`);
|
|
61
61
|
bottom: 5%;
|
|
62
62
|
right: 10%;
|
|
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}(),Qi={autotrack:{src:{cn:K("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:K("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:K("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:K("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:K("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:K("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:K("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"}},Xf=["ab","autotrack","Stay","store","et","profile","cep","heartbeat","monitor","route","tracer"],fe=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 Pp,this.remotePlugin=new Map,this.Types=S,this.adapters.storage=Ie,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"&&Xf.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 Jp(this.name,e.log),this.inited?this.logger.warn("[instance: "+this.name+"], every instance's api: init, can be call only one time!"):e&&Gt(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 Zp,this.spider.checkSpider(e)?this.logger.warn("your env may be a spider, can not report!"):(this.appBridge=new Xp(this,e.enable_native),this.requestManager=new Jf(this,e),this.bridgeReport=this.appBridge.bridgeInject(),this.configManager=new Wp(this,e),this.debugger=new Zf(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 Qp,this.tokenManager=new ef,this.sessionManager=new Yp,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,h=Object.assign(i.initConfig,o),c=new a;return c.apply(i,h),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 "+Fe+", 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||!Gt(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 h={};for(var c in a)Object.prototype.hasOwnProperty.call(a,c)&&o.indexOf(c)<0&&(h[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&&(h[c[u]]=a[c[u]])}return h}(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,h=a.params;i.appBridge.onEventV3(o,JSON.stringify(h))}):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=Lp();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=Zs(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=Zs(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 vt()},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 h=i.configManager.get().user;return o&&(h.tobid=o,h["diss".split("").reverse().join("")]=o),e(U({},h))}},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}(),en="__rangers_ab_style__";(function(r){r[r.Var=0]="Var",r[r.All=1]="All"})(ir||(ir={}));var Yf=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,h=t.ab_cookie_domain,c=t.ab_timeout,u=s||K(Ys[t.channel||"cn"]),l=e.adapters.storage,d=this.collect.Types;this.types=d,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=h||"",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(d.TokenChange,function(p){p==="uuid"&&i.readyStatus&&(i.clearCache(),i.fetchAB())}),this.collect.on(d.TokenReset,function(p){p==="uuid"&&i.readyStatus&&(i.clearCache(),i.fetchAB())}),this.collect.on(d.AbVar,function(p){var f=p.name,v=p.defaultValue,m=p.callback;i.getVar(f,v,m)}),this.collect.on(d.AbAllVars,function(p){i.getAllVars(p)}),this.collect.on(d.AbConfig,function(p){var f=p.params,v=p.callback;i.getABconfig(f,v)}),this.collect.on(d.AbExternalVersion,function(p){i.setExternalAbVersion(p)}),this.collect.on(d.AbOpenLayer,function(){i.openOverlayer()}),this.collect.on(d.AbCloseLayer,function(){i.closeOverlayer()}),this.collect.on(d.AbVersionChangeOn,function(p){i.changeListener.set(p,p)}),this.collect.on(d.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(d.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=kr(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:ir.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&&Gt(o)){var h=a[i].vid;return t==="$ab_url"?this.mulilinkVersions.includes(h)||this.mulilinkVersions.push(h):this.versions.includes(h)||this.versions.push(h),this.updateVersions(),this.fechEvent(h,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:ir.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,h=a.user,c=this.getABCache(),u=h[this.ab_user_mode]||h.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 d={events:[l],user:h,header:o};this.reportExposure(d,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(en)){var n="body { opacity: 0 !important; }",s=document.head||document.getElementsByTagName("head")[0],a=document.createElement("style");a.id=en,a.type="text/css",a.styleSheet?a.styleSheet.cssText=n:a.appendChild(document.createTextNode(n)),s.appendChild(a)}}(),e)var i=setTimeout(function(){t.closeOverlayer(),clearTimeout(i)},e)},r.prototype.closeOverlayer=function(){var e;(e=document.getElementById(en))&&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 h=a.val,c=a.vid;h&&c&&this.getVar("$ab_url",h,function(){i.editMode||(h!==window.location.href?setTimeout(function(){if(!i.collect.destroy){var u=""+h;u=u.indexOf("http")===-1?"https://"+u:u,Ri(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===ir.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}(),Qf=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 Ur(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 Bo=function(r,e){return!!tm(r,e)};function tn(r,e){for(var t=r;t&&!Ur(t,"container",e.container_attr||"");){if(t.nodeName==="HTML"||t.nodeName==="BODY")return r;t=t.parentElement}return t||r}var em=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 Vo(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 Nr=function(r,e){return r.hasAttribute?r.hasAttribute(e):r.attributes?!(!r.attributes[e]||!r.attributes[e].specified):void 0},tm=function(r,e){if(typeof e=="string")return Nr(r,e);if(zr(e)){for(var t=!1,i=0;i<e.length;i++)if(Nr(r,e[i])){t=!0;break}return t}},Fo=function(r,e){var t={};if(typeof e=="string")Nr(r,e)&&(t[e]=r.getAttribute(e));else if(zr(e))for(var i=0;i<e.length;i++)Nr(r,e[i])&&(t[e[i]]=r.getAttribute(e[i]));return t};function jo(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(h){if(h===null)return{str:"",index:0};var c=0,u=h.parentElement;if(u)for(var l=u.children,d=0;d<l.length&&l[d]!==h;d++)l[d].nodeName===h.nodeName&&c++;return{str:[h.nodeName.toLowerCase(),Ur(h,"list")?"[]":""].join(""),index:c}}(n),a=s.str,o=s.index;t.unshift(a),i.unshift(o)}),{element_path:"/"+t.join("/"),positions:i}}var rm=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,Gt(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:Js(),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=jo(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}(),im=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(),Gt(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:Js(),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}(),nm=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 rm(e,t),this.pageClose=new im(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,h=s.url;i.resetStayDuration(a,o,h)}),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,h=s.url;i.setStayParmas(a,o,h)}),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}(),sm=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 Pi(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(h){var c=i.cache[h];return t?!c:!(c&&i.compare(c.val,e[h])&&o-c.timestamp<i.duration)}).reduce(function(h,c){return h[c]=n[c],h},{})}catch(h){this.collect.emit(g.DEBUGGER_MESSAGE,{type:g.DEBUGGER_MESSAGE_SDK,info:"发生了异常",level:"error",time:Date.now(),data:h.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}(),om=function(){function r(){var e=this;this.setInterval=function(){e.clearIntervalFunc=Np(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}(),am=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,h=n.response;s==="f_data"&&i.sdkError(a,o,h)}),this.collect.on(e.Types.SDKInnerError,function(n){var s=n.type,a=n.eventData,o=n.errorCode,h=n.msg;i.sdkInnerError(s,a,o,h)}))},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,h=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:h},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,h=[];e.forEach(function(u){u.events.forEach(function(l){h.push(l)})});var c={events:h.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,h=a.header,c=[];t.forEach(function(l){l.events.forEach(function(d){c.push(d)})});var u={events:c.map(function(l){return{event:"on_error",params:JSON.stringify({type:e,error_code:i,app_id:h.app_id,app_name:h.app_name||"",error_event:l.event,sdk_version:h.sdk_version,local_time_ms:l.local_time_ms,tea_event_index:Date.now(),params:l.params,header:h,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}(),cm=function(r){if(r.children.length){var e=r.children;return![].slice.call(e).some(function(t){return t.children.length>0})}return!0},um=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 hm(r,e){if(r.nodeType!==1||!e.svg&&um(r)||["HTML","BODY"].includes(r.tagName.toUpperCase()))return!1;var t=r;return t.style.display!=="none"&&(!!Ur(t,"container",e.container_attr||"")||!!(function(i,n){for(var s=i,a=!1;s&&!Ur(s,"container",n.container_attr||"");){if(s.nodeName==="HTML"||s.nodeName==="BODY")return a;s=s.parentElement}return a=!0}(t,e)||cm(t)||e.svg))}var dm=function(){function r(e,t,i){var n=this;this.statistics=!1,this.pageView=!1,this.clickEvent=function(s){hm(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&&(zr(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],d=l.renderTime||l.loadTime;t.statistics||(t.getPageLoadEvent(d),t.statistics=!0)}).observe({entryTypes:["largest-contentful-paint"]});var h=setTimeout(function(){t.statistics||(t.getPageLoadEvent(o[0].startTime||0),t.statistics=!0,clearTimeout(h))},2e3)}else this.getPageLoadEvent(0)}catch{this.getPageLoadEvent(0)}}}},r.prototype.removeListener=function(){var e=this;zr(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)),Ai(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}(),lm={eventConfig:{mode:"proxy-capturing",submit:!1,click:!0,change:!1,pv:!0,beat:!0,hashTag:!1,impr:!1},scoutConfig:{mode:"xpath"}},pm=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 fm(r,e,t,i){var n={},s=function(k){if(k){var T=k.getBoundingClientRect(),A=T.width,P=T.height;return{left:T.left,top:T.top,element_width:A,element_height:P}}}(e=tn(e,t)),a=function(k,T){k===void 0&&(k={}),T===void 0&&(T={});var A=k.clientX,P=k.clientY,ie=T.left,J=T.top,ue=A-ie>=0?A-ie:0,he=P-J>=0?P-J:0;return{touch_x:Math.floor(ue),touch_y:Math.floor(he)}}(r,s),o=s.element_width,h=s.element_height,c=a.touch_x,u=a.touch_y,l=jo(e),d=l.element_path,p=l.positions,f=function(k,T){var A=tn(k,T),P=[];return function ie(J){var ue=function(re){var Ue="";return re.nodeType===3?Ue=re.textContent.trim():re.dataset&&re.dataset.hasOwnProperty("teaTitle")||re.hasAttribute("ata-tea-title")?Ue=re.getAttribute("data-tea-title"):re.nodeName==="INPUT"&&["button","submit"].includes(re.getAttribute("type"))?Ue=re.getAttribute("value"):re.nodeName==="IMG"&&re.getAttribute("alt")&&(Ue=re.getAttribute("alt")),Ue.slice(0,200)}(J);if(ue&&P.indexOf(ue)===-1&&P.push(ue),J.childNodes.length>0)for(var he=J.childNodes,ht=0;ht<he.length;ht++)he[ht].nodeType!==8&&ie(he[ht])}(A),P}(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:d,positions:E})),n.element_path=y&&y.xpath||d,n.positions=y&&y.positions||E,i&&!i.text&&(n.texts=f,n.element_title=e.getAttribute("data-tea-title")||e.getAttribute("title")||em(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(h),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&&Bo(e,t.track_attr)){var _=Fo(e,t.track_attr);for(var C in _)n[C]=_[C]}if(t.custom_attr)try{if(Bo(e,t.custom_attr)){_=Fo(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 O=tn(e,t);return O.tagName==="A"&&(n.href=O.getAttribute("href")),e.tagName==="IMG"&&(n.src=e.getAttribute("src")),n}var Et=function(r,e,t,i,n){return U(U({event:r},fm(e,t,i,n)),{is_html:1,page_key:window.location.href,page_title:document.title})},mm=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(Vo(e.target))return null;var i="bav2b_click";switch(t){case"click":return i=e.target.getAttribute("data-applog-click-event")||this.eventName.click||"",Et(i,e,e.target,this.options,this.ignore);case"exposure":return i=e.target.getAttribute("data-applog-exposure-event")||this.eventName.exposure||"",Et(i,e,e.target||e,this.options,this.ignore);case"change":return U(U({},Et(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 Et(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(Vo(t.target))return null;var i=Et(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=Et(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}(),_m=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}(),nr={},Ho=[],gm=function(r){r.length&&r.forEach(function(e){Ho.push(e)})};function $o(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 vm(r){if(Ho.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;nr[t]&&nr[t].forEach(function(n){typeof n=="function"&&n(r,i)})}}var rn=!1;function ym(r,e){window.TEAVisualEditor=window.TEAVisualEditor||{},window.TEAVisualEditor.appId=e.app_id;var t=e.channel_domain,i="";if(gm(Hp),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 h=i.split("/5.0");i=h[0]||i}}}catch{}}(function(c,u){var l={};if(Object.keys(c).length)for(var d in c){if(d==="filter"||d==="autotrack"||d==="enable_stay_duration")break;l[d]=c[d]}var p=c.domain;(window.opener||window.parent).postMessage({type:"tea:sdk:info",config:l,version:u},p),window.addEventListener("message",vm,!1)})(e,Fe);try{(function(c,u){nr[c]=nr[c]||[],nr[c].push(u)})("tea:openHeatMapCore",function(c){var u=jp,l=c.data.app_id;l&&l!==e.app_id||function(d){var p=d.event,f=d.editorUrl,v=d.autoTrackInstance;rn||(rn=!0,Up(f,function(){$o(p,"editorScriptloadSuccess"),v.destroy()},function(){p&&$o(p,"editorScriptloadError"),rn=!1}))}({event:c,editorUrl:u+".js?query="+Date.now(),autoTrackInstance:r})})}catch{console.log("openHeatMapCore error")}}var we,bm=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"})(we||(we={}));var at,Sm=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=we.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),h=(s.target,s.isIntersecting,s.intersectionRatio);if(o.intersectionRatio=h,h<=.1&&(s.target.backStatus=!1),e.observeMap.set(a,o),h<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,h,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=Bt();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||we.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,h=window.innerHeight||document.documentElement.clientHeight;return i>=0&&n>=0&&i<=h&&n<=o?(s>o?o:s)*(h-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=we.RESUME_FORM_PAGE:this.exposureType=we.LIFECYCLE_SHOW_NEW:(e.hasExposure,e.backStatus!==!1&&(this.backStatus||this.customType||window.performance.navigation.type===2)?this.exposureType=we.RESUME_FORM_PAGE:this.exposureType=we.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=we.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 d=o.call.apply(o,rt([history,c],u));return e.lastState=c,d};var h=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 d=h.call.apply(h,rt([history,c],u));return e.lastState=c,d}}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=we.RESUME_FORM_PAGE):e.backStatus=!1}),function(){(function(c,u,l,d){c.addEventListener?c.removeEventListener(u,l,d):c.attachEven&&c.detachEven("on"+u,l)})(document,"visibilitychange",a,!1)}},r._observer_instance=null,r._observer_map=new Map,r}(),Em=function(){function r(e,t,i){t.autotrack&&t.autotrack.exposure&&(this._intersection=new Sm(e,t,i),this._observer=new bm(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"})(at||(at={}));var Ko,Cm=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,h=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&&(h=l-n,Math.abs(h)>=i.distance&&i.distance&&i.eventHandle({eventType:"dom",eventName:"scroll",event:m,params:{$direction:p,$offsetY:h,$offsetX:o}},u)):p!==3&&p!==4||v===d&&(o=d-s,Math.abs(o)>=i.distance&&i.distance&&i.eventHandle({eventType:"dom",eventName:"scroll",event:m,params:{$direction:p,$offsetY:h,$offsetX:o}},u)),n=l,s=d},100);var l=e.scrollTop,d=e.scrollLeft,p=at.NOT_SCROLL;l>n?p=at.SCROLL_DOWN:l<n?p=at.SCROLL_UP:d>s?p=at.SCROLL_LEFT:d<s&&(p=at.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}(),wm={hashTag:!1,impr:!1},Tm=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(wm,t),this.destroyed=!1,this.options=t,this.Config=new pm(lm,this.options),this.Exposure=new Em(this.collect,this.config,this.handle.bind(this)),this.Scroll=new Cm(this.config,this.handle.bind(this)),this.Listener=new dm(t,this.collect,this.Config),this.EventHandle=new mm(this.config,t),this.Request=new _m(this.collect),this.autoTrackStart=!0,this.init(),ym(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(h){console.log("handel dom event error "+JSON.stringify(h))}},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"})(Ko||(Ko={}));var qo={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"]},zm=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,h=s.errorCode,c=s.response;i.addErrorCount(o,a,h,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 h="log";for(var c in qo)if(qo[c].indexOf(o.event)!==-1){h=c;break}s.addCount(h,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:Fe};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()}),Ai(function(){e.leavePage()})},r.prototype.leavePage=function(){this.report(!0)},r}(),km=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}(),nn=typeof window<"u"?(window.LogPluginObject||(window.LogPluginObject={}),window.LogPluginObject):null,Am=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(Qi.hasOwnProperty(i)){var n=Qi[i].object,s=Qi[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;nn[t]?(this.process(e,nn[t]),console.log("已有"+e+"插件,避免重复加载~")):this.loadPlugin(e,i,function(){n.process(e,nn[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}(),Rm=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,rt([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 h=e.getPopStateChangeEventData();return e.lastLocation=location.href,e.sendPv(h,"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,rt([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 h=e.getPopStateChangeEventData();return e.lastLocation=location.href,e.sendPv(h),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}();fe.usePlugin(Am,"extend"),fe.usePlugin(Qf,"et"),fe.usePlugin(Yf,"ab"),fe.usePlugin(nm,"stay"),fe.usePlugin(Tm,"autotrack"),fe.usePlugin(sm,"profile"),fe.usePlugin(km,"retry"),fe.usePlugin(om,"heartbeat"),fe.usePlugin(am,"monitor"),fe.usePlugin(Rm,"route"),fe.usePlugin(zm,"tracer");var sr=new fe("default");const sn="VEPUSHER_DEVICE_ID",on="VEPUSHER_USER_ID",Wo=r=>Math.floor((Math.random()*9+1)*Math.pow(10,r-1)).toString();function Dm(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 xm(r){if(r)return localStorage.setItem(on,r),r;const e=localStorage.getItem(on);if(e)return e;const t=Wo(12);return localStorage.setItem(on,t),r}function Om(r){if(r)return localStorage.setItem(sn,r),r;const e=localStorage.getItem(sn);if(e)return e;const t=Wo(11);return localStorage.setItem(sn,t),t}class Mm{constructor({showLogInConsole:e=!1}){this._showLogInConsole=!1,this.markCollectTeaEventReady=()=>{this.isReady=!0,sr.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.89",...i}};sr.config(n),this.markCollectTeaEventReady()},this.isReady=!1,this.queueTeaEvent=[],sr.init({app_id:699880,channel:"cn"}),this._showLogInConsole=e}sendTeaEvent(e,t,i=!1){if(e)if(this.isReady)try{const n={...Dm(t||{})};sr.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 sr}}let or;function Im({showLogInConsole:r}){or=new Mm({showLogInConsole:r})}function R(r,e,t=!1){or&&or.sendTeaEvent(r,e,t)}function Pm(r,e){or&&or.configTea(r,e)}const D={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"}};function Ct(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 Lm extends Ge{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}=gt(xn,"video"),{sampleRate:s}=gt(On,"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(ye.DeviceCaptured,e)}_notifyStopCapture(e){this.emit(ye.DeviceStopCapture,e)}_bindStreamEvent(e){e.bindTrackEnd(()=>{this.emit(ye.Interrupted,e),this.stopCapture({streamId:e.id,type:e.type})})}_handleError(e,t){const i=new _t(t,e.message);this.emit(ye.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 fu(e?[e]:["audioinput","videoinput"]);return R(D.GET_DEVICES_RESULT,{type:e,is_success:!0,devices:t}),t}catch(t){return R(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=Me(this[i]);R(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={};xp.includes(e)?t={facingMode:e}:t={deviceId:e};const i={...t,...this._videoConstraints};try{const n=await mu(i,!this._livePusher.isEnableMixing),s=new Vu(n);return this._cameraStreams[s.id]=s,this._notifyCaptured(s),this._bindStreamEvent(s),R(D.CAMERA_CAPTURE_RESULT,{is_success:!0,stream_id:s.id,device_id:e,capture_params:i}),s.id}catch(n){throw R(D.CAMERA_CAPTURE_RESULT,{is_success:!1,device_id:e,capture_params:i,...Ct(n)}),this._handleError(n,oe.OPEN_CAMERA_FAILED),n}}async startMicrophoneCapture(e){const t={...this._audioConstraints,deviceId:e};try{const i=await gu(t),n=new wp(i);return this._microphoneStreams[n.id]=n,this._notifyCaptured(n),this._bindStreamEvent(n),R(D.MICROPHONE_CAPTURE_RESULT,{is_success:!0,stream_id:n.id,device_id:e,capture_params:t}),n.id}catch(i){throw R(D.MICROPHONE_CAPTURE_RESULT,{is_success:!1,device_id:e,capture_params:t,...Ct(i)}),this._handleError(i,oe.OPEN_MICROPHONE_FAILED),i}}async startScreenCapture(e){const t={audio:e,video:this._videoConstraints};try{const i=await vu(t,void 0,!this._livePusher.isEnableMixing),n=new zp(i);return this._screenStreams[n.id]=n,this._notifyCaptured(n),this._bindStreamEvent(n),R(D.SCREEN_CAPTURE_RESULT,{is_success:!0,stream_id:n.id,capture_params:t}),n.id}catch(i){throw R(D.SCREEN_CAPTURE_RESULT,{is_success:!1,capture_params:t,...Ct(i)}),this._handleError(i,oe.OPEN_SCREEN_FAILED),i}}async startVideoFileCapture(e){try{const t=await Xn({url:e,video:!0,audio:!0,loop:!0}),i=new Tp(t);return this._videoFileStreams[i.id]=i,this._notifyCaptured(i),this._bindStreamEvent(i),R(D.VIDEO_FILE_CAPTURE_RESULT,{is_success:!0,stream_id:i.id,file_url:e}),i.id}catch(t){throw this._handleError(t,oe.VIDEO_FILE_CAPTURE_FAILED),R(D.VIDEO_FILE_CAPTURE_RESULT,{is_success:!1,file_url:e,...Ct(t)}),t}}async startAudioFileCapture(e){try{const t=await Xn({url:e,video:!1,audio:!0,loop:!0}),i=new kp(t);return this._audioFileStreams[i.id]=i,this._notifyCaptured(i),this._bindStreamEvent(i),R(D.AUDIO_FILE_CAPTURE_RESULT,{is_success:!0,stream_id:i.id,file_url:e}),i.id}catch(t){throw R(D.AUDIO_FILE_CAPTURE_RESULT,{is_success:!1,file_url:e,...Ct(t)}),this._handleError(t,oe.AUDIO_FILE_CAPTURE_FAILED),t}}async startImageCapture(e){try{const t=await _u({url:e,width:0,height:0,frameRate:30}),i=new Ap(t);return this._imageStreams[i.id]=i,this._notifyCaptured(i),this._bindStreamEvent(i),R(D.IMAGE_FILE_CAPTURE_RESULT,{is_success:!0,stream_id:i.id,file_url:e}),i.id}catch(t){throw R(D.IMAGE_FILE_CAPTURE_RESULT,{is_success:!1,file_url:e,...Ct(t)}),this._handleError(t,oe.IMAGE_FILE_CAPTURE_FAILED),t}}startCustomVideoCapture(e){const t=bu(e);if(t){const i=new Rp(t);return this._customVideoStreams[i.id]=i,this._notifyCaptured(i),this._bindStreamEvent(i),i.id}}startCustomAudioCapture(e){const t=Su(e);if(t){const i=new Dp(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(),R(D.VOLUME_DETECTOR_START_RESULT,{is_success:!0,stream_id:t.id})}catch(i){R(D.VOLUME_DETECTOR_START_RESULT,{is_success:!1,stream_id:t.id,error_message:i.message}),this._handleError(i,oe.VOLUME_DETECT_FAILED)}}stopVolumeDetect(e){const t=this.getStreamById(e);t&&t.stopVolumeDetect()}getDefaultVideoStream(){return Me(this._cameraStreams)[0]||Me(this._screenStreams)[0]||Me(this._videoFileStreams)[0]||Me(this._imageStreams)[0]||Me(this._customVideoStreams)[0]}getDefaultAudioStream(){return Me(this._microphoneStreams)[0]||Me(this._audioFileStreams)[0]||Me(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 We=class{constructor(e){this._enabled=!1,this.group=(...t)=>{this._enabled&&console.group(`[${this._prefix}]: `,...t)},this.groupCollapsed=(...t)=>{this._enabled&&console.groupCollapsed(`[${this._prefix}]: `,...t)},this.groupEnd=()=>{this._enabled&&console.groupEnd()},this.log=(...t)=>{this._enabled&&console.log(`[${this._prefix}]: `,...t)},this.warn=(...t)=>{this._enabled&&console.warn(`[${this._prefix}]: `,...t)},this.error=(...t)=>{this._enabled&&console.error(`[${this._prefix}]: `,...t)},this.table=(...t)=>{this._enabled&&console.table(...t)},this._prefix=e;try{this._enabled=location.href.indexOf("rtmdebug")!==-1}catch{}}};class an{constructor({streamManagerController:e,composedStream:t,streamComposeController:i}){this._streamManagerController=e,this._composedStream=t,this._streamComposeController=i,this._active=!1,this.bindStreamManagerControllerEvent()}bindStreamManagerControllerEvent(){this._streamManagerController.on(ye.DeviceCaptured,e=>{this._active&&this.onStreamCapture(e)}),this._streamManagerController.on(ye.DeviceStopCapture,e=>{this._active&&this.onStreamStopCapture(e)})}getComposedStream(){return this._composedStream}enable(){this._active=!0}disable(){this._active=!1}}const Jo=new We("SingleComposer");class Um extends an{onStreamCapture(e){e.isVideoStream?this._handleVideoStreamCapture(e):this._handleAudioStreamCapture(e)}onStreamStopCapture(e){e&&(e.isVideoStream?this._handleVideoStreamStopCapture(e):this._handleAudioStreamStopCapture(e))}enable(){if(super.enable(),this._composedStream.videoStream){const e=this._streamManagerController.getDefaultVideoStream();e&&this._handleVideoStreamCapture(e)}}async setVideoQuality({width:e,height:t,frameRate: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){Jo.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):Jo.error("all video stream stop capture")}}_handleAudioStreamStopCapture(e){this._streamComposeController.removeAudioStream(e.id)}getComposedStream(){return this._composedStream}}class Nm extends Ge{constructor(e,{width:t,height:i,x:n,y:s,zOrder:a,keepRatio:o,mirrorType:h}){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=h,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,h=n;return s>a?(o=i,h=2*Math.round(i/s/2)):s<a&&(o=2*Math.round(n*s/2),h=n),{width:o,height:h}}_bindVideoTrackSizeChange(){this._stream.on(Dn.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!==Tn.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 Zo extends lt{constructor(e){super({type:N.MixVideo,stream:e}),this._trackMap.video=e}get source(){return this._source}replaceVideoTrack(e){this._trackMap.video=e,this._source=e}get viewNode(){return null}get mixerNode(){return null}bindTrackEnd(e){this.source.onended=e}destroy(){this.source.stop(),delete this._trackMap.video}}var Gm=Object.defineProperty,Bm=Object.getOwnPropertyDescriptor,ar=(r,e,t,i)=>{for(var n=Bm(e,t),s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=a(e,t,n)||n);return n&&Gm(e,t,n),n};const Xo=new We("composition-composer");function cr(r,e,t){const i=t.value;return t.value=function(...n){return this._active||Xo.error("composer is not active"),i.apply(this,n)},t}class wt extends an{constructor(e){super(e),this._compositionViewConfig={width:1080,height:720,frameRate:30,backgroundColor:"#000000"},this._sprites=[],this._videoMixer=new Lu}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 Zo(e),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=$s(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=>{Cp(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 Zo(n),this._composedStream.setVideoStream(this._mixedVideoStream),i.destroy()}}getMixingConfig(){return this._compositionViewConfig}addVideoStream(e,t){if(!e.viewNode){Xo.error("have no viewNode for composition");return}e.audioTrack&&this._streamComposeController.addAudioStream({streamId:e.id,volume:100});const i=new Nm(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}}}ar([cr],wt.prototype,"addVideoStream"),ar([cr],wt.prototype,"updateVideoStream"),ar([cr],wt.prototype,"removeVideoStream"),ar([cr],wt.prototype,"muteVideoStream"),ar([cr],wt.prototype,"unmuteVideoStream");class Vm extends Ge{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 Fm extends gr{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 jm extends an{constructor(e){super(e),this._spriteList=[],this._audioMixer=new Cu({keepAlive:!0})}onStreamCapture(e){}onStreamStopCapture(e){e&&this.removeAudioStream(e.id)}_updateSpriteToMixer(){const e=$s(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 Fm(e);this._composedStream.setAudioStream(t),this._audioMixer.mix([])}addAudioStream(e,t){const i=new Vm(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 Hm extends Ge{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(Ye.VideoStreamChange,e))}setAudioStream(e){var t;((t=this._audioStream)==null?void 0:t.id)!==e.id&&(this._audioStream=e,this.emit(Ye.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 $m=new We("streamComposeController");class Km{constructor(e){this._streamManagerController=e,this._composedStream=new Hm,this.singleComposer=new Um({streamManagerController:this._streamManagerController,composedStream:this._composedStream,streamComposeController:this}),this.compositionComposer=new wt({streamManagerController:this._streamManagerController,composedStream:this._composedStream,streamComposeController:this}),this.mixerComposer=new jm({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){$m.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()}}class Yo{constructor(e){this._hasBindComposedStreamEvent=!1,this._composedStream=e}bindComposedStreamEvent(){this._hasBindComposedStreamEvent||(this._composedStream.on(Ye.VideoStreamChange,this.handleVideoStreamChange),this._composedStream.on(Ye.AudioStreamChange,this.handleAudioStreamChange),this._hasBindComposedStreamEvent=!0)}unbindComposedStreamEvent(){this._hasBindComposedStreamEvent&&(this._composedStream.off(Ye.VideoStreamChange,this.handleVideoStreamChange),this._composedStream.off(Ye.AudioStreamChange,this.handleAudioStreamChange),this._hasBindComposedStreamEvent=!1)}}const Tt=new We("PreviewConsumer");class qm extends Yo{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(j.CaptureFirstVideoFrame),n.video=s),a&&a!==n.audio&&(this._streamConsumeController.emit(j.CaptureFirstAudioFrame),n.audio=a)}),t.appendChild(i)}startPreview(){if(Tt.log("startPreview"),!this._previewElement){Tt.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(j.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"&&(Tt.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),Tt.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")&&(Tt.log(`remove preview track ${n.label}`),i.removeTrack(n))}),i.getTracks().length===0&&(e.srcObject=null,Tt.log("set srcObject null")))}getPreviewElement(){if(this.isPreviewing)return this._previewElement}get isPreviewing(){return this._isPreviewing}}var ve={},cn={},un={exports:{}},Qo;function hn(){if(Qo)return un.exports;Qo=1;var r=un.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")})}),un.exports}var ea;function Wm(){return ea||(ea=1,function(r){var e=function(o){return String(Number(o))===o?Number(o):o},t=function(o,h,c,u){if(u&&!c)h[u]=e(o[1]);else for(var l=0;l<c.length;l+=1)o[l+1]!=null&&(h[c[l]]=e(o[l+1]))},i=function(o,h,c){var u=o.name&&o.names;o.push&&!h[o.push]?h[o.push]=[]:u&&!h[o.name]&&(h[o.name]={});var l=o.push?{}:u?h[o.name]:h;t(c.match(o.reg),l,o.names,o.name),o.push&&h[o.push].push(l)},n=hn(),s=RegExp.prototype.test.bind(/^([a-z])=(.*)/);r.parse=function(o){var h={},c=[],u=h;return o.split(/(\r\n|\r|\n)/).filter(s).forEach(function(l){var d=l[0],p=l.slice(2);d==="m"&&(c.push({rtp:[],fmtp:[]}),u=c[c.length-1]);for(var f=0;f<(n[d]||[]).length;f+=1){var v=n[d][f];if(v.reg.test(p))return i(v,u,p)}}),h.media=c,h};var a=function(o,h){var c=h.split(/=(.+)/,2);return c.length===2?o[c[0]]=e(c[1]):c.length===1&&h.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 h=[],c=o.split(" ").map(e),u=0;u<c.length;u+=3)h.push({component:c[u],ip:c[u+1],port:c[u+2]});return h},r.parseImageAttributes=function(o){return o.split(" ").map(function(h){return h.substring(1,h.length-1).split(",").reduce(a,{})})},r.parseSimulcastStreamList=function(o){return o.split(";").map(function(h){return h.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}})})}}(cn)),cn}var dn,ta;function Jm(){if(ta)return dn;ta=1;var r=hn(),e=/%[sdv%]/g,t=function(a){var o=1,h=arguments,c=h.length;return a.replace(e,function(u){if(o>=c)return u;var l=h[o];switch(o+=1,u){case"%%":return"%";case"%s":return String(l);case"%d":return Number(l);case"%v":return""}})},i=function(a,o,h){var c=o.format instanceof Function?o.format(o.push?h:h[o.name]):o.format,u=[a+"="+c];if(o.names)for(var l=0;l<o.names.length;l+=1){var d=o.names[l];o.name?u.push(h[o.name][d]):u.push(h[o.names[l]])}else u.push(h[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 dn=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 h=o.outerOrder||n,c=o.innerOrder||s,u=[];return h.forEach(function(l){r[l].forEach(function(d){d.name in a&&a[d.name]!=null?u.push(i(l,d,a)):d.push in a&&a[d.push]!=null&&a[d.push].forEach(function(p){u.push(i(l,d,p))})})}),a.media.forEach(function(l){u.push(i("m",r.m[0],l)),c.forEach(function(d){r[d].forEach(function(p){p.name in l&&l[p.name]!=null?u.push(i(d,p,l)):p.push in l&&l[p.push]!=null&&l[p.push].forEach(function(f){u.push(i(d,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}(),cn={autotrack:{src:{cn:X("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:X("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:X("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:X("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:X("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:X("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:X("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"}},Qf=["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 Up,this.remotePlugin=new Map,this.Types=S,this.adapters.storage=Le,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"&&Qf.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 Xp(this.name,e.log),this.inited?this.logger.warn("[instance: "+this.name+"], every instance's api: init, can be call only one time!"):e&&Ft(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 Yp,this.spider.checkSpider(e)?this.logger.warn("your env may be a spider, can not report!"):(this.appBridge=new Qp(this,e.enable_native),this.requestManager=new Xf(this,e),this.bridgeReport=this.appBridge.bridgeInject(),this.configManager=new Zp(this,e),this.debugger=new Yf(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 tf,this.tokenManager=new rf,this.sessionManager=new ef,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 "+je+", 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||!Ft(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=Np();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=no(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=no(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}(),un="__rangers_ab_style__";(function(r){r[r.Var=0]="Var",r[r.All=1]="All"})(or||(or={}));var em=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||X(oo[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=Ir(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:or.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&&Ft(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:or.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(un)){var n="body { opacity: 0 !important; }",s=document.head||document.getElementsByTagName("head")[0],a=document.createElement("style");a.id=un,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(un))&&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,Ui(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===or.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}(),tm=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 $r(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 Wo=function(r,e){return!!im(r,e)};function dn(r,e){for(var t=r;t&&!$r(t,"container",e.container_attr||"");){if(t.nodeName==="HTML"||t.nodeName==="BODY")return r;t=t.parentElement}return t||r}var rm=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 Jo(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 qr=function(r,e){return r.hasAttribute?r.hasAttribute(e):r.attributes?!(!r.attributes[e]||!r.attributes[e].specified):void 0},im=function(r,e){if(typeof e=="string")return qr(r,e);if(Mr(e)){for(var t=!1,i=0;i<e.length;i++)if(qr(r,e[i])){t=!0;break}return t}},Zo=function(r,e){var t={};if(typeof e=="string")qr(r,e)&&(t[e]=r.getAttribute(e));else if(Mr(e))for(var i=0;i<e.length;i++)qr(r,e[i])&&(t[e[i]]=r.getAttribute(e[i]));return t};function Xo(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(),$r(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 nm=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,Ft(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:io(),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=Xo(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}(),sm=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(),Ft(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:io(),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}(),om=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 nm(e,t),this.pageClose=new sm(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}(),am=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 ji(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}(),cm=function(){function r(){var e=this;this.setInterval=function(){e.clearIntervalFunc=Bp(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}(),um=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}(),dm=function(r){if(r.children.length){var e=r.children;return![].slice.call(e).some(function(t){return t.children.length>0})}return!0},hm=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 lm(r,e){if(r.nodeType!==1||!e.svg&&hm(r)||["HTML","BODY"].includes(r.tagName.toUpperCase()))return!1;var t=r;return t.style.display!=="none"&&(!!$r(t,"container",e.container_attr||"")||!!(function(i,n){for(var s=i,a=!1;s&&!$r(s,"container",n.container_attr||"");){if(s.nodeName==="HTML"||s.nodeName==="BODY")return a;s=s.parentElement}return a=!0}(t,e)||dm(t)||e.svg))}var pm=function(){function r(e,t,i){var n=this;this.statistics=!1,this.pageView=!1,this.clickEvent=function(s){lm(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)),Li(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}(),fm={eventConfig:{mode:"proxy-capturing",submit:!1,click:!0,change:!1,pv:!0,beat:!0,hashTag:!1,impr:!1},scoutConfig:{mode:"xpath"}},mm=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 _m(r,e,t,i){var n={},s=function(k){if(k){var T=k.getBoundingClientRect(),R=T.width,O=T.height;return{left:T.left,top:T.top,element_width:R,element_height:O}}}(e=dn(e,t)),a=function(k,T){k===void 0&&(k={}),T===void 0&&(T={});var R=k.clientX,O=k.clientY,K=T.left,F=T.top,J=R-K>=0?R-K:0,Z=O-F>=0?O-F:0;return{touch_x:Math.floor(J),touch_y:Math.floor(Z)}}(r,s),o=s.element_width,d=s.element_height,c=a.touch_x,u=a.touch_y,l=Xo(e),h=l.element_path,p=l.positions,f=function(k,T){var R=dn(k,T),O=[];return function K(F){var J=function(H){var oe="";return H.nodeType===3?oe=H.textContent.trim():H.dataset&&H.dataset.hasOwnProperty("teaTitle")||H.hasAttribute("ata-tea-title")?oe=H.getAttribute("data-tea-title"):H.nodeName==="INPUT"&&["button","submit"].includes(H.getAttribute("type"))?oe=H.getAttribute("value"):H.nodeName==="IMG"&&H.getAttribute("alt")&&(oe=H.getAttribute("alt")),oe.slice(0,200)}(F);if(J&&O.indexOf(J)===-1&&O.push(J),F.childNodes.length>0)for(var Z=F.childNodes,le=0;le<Z.length;le++)Z[le].nodeType!==8&&K(Z[le])}(R),O}(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")||rm(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&&Wo(e,t.track_attr)){var _=Zo(e,t.track_attr);for(var C in _)n[C]=_[C]}if(t.custom_attr)try{if(Wo(e,t.custom_attr)){_=Zo(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=dn(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},_m(e,t,i,n)),{is_html:1,page_key:window.location.href,page_title:document.title})},gm=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(Jo(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(Jo(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}(),vm=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}(),ar={},Yo=[],ym=function(r){r.length&&r.forEach(function(e){Yo.push(e)})};function Qo(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 bm(r){if(Yo.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;ar[t]&&ar[t].forEach(function(n){typeof n=="function"&&n(r,i)})}}var hn=!1;function Sm(r,e){window.TEAVisualEditor=window.TEAVisualEditor||{},window.TEAVisualEditor.appId=e.app_id;var t=e.channel_domain,i="";if(ym(qp),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",bm,!1)})(e,je);try{(function(c,u){ar[c]=ar[c]||[],ar[c].push(u)})("tea:openHeatMapCore",function(c){var u=$p,l=c.data.app_id;l&&l!==e.app_id||function(h){var p=h.event,f=h.editorUrl,v=h.autoTrackInstance;hn||(hn=!0,Gp(f,function(){Qo(p,"editorScriptloadSuccess"),v.destroy()},function(){p&&Qo(p,"editorScriptloadError"),hn=!1}))}({event:c,editorUrl:u+".js?query="+Date.now(),autoTrackInstance:r})})}catch{console.log("openHeatMapCore error")}}var ze,Em=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"})(ze||(ze={}));var ht,Cm=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=ze.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=jt();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||ze.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=ze.RESUME_FORM_PAGE:this.exposureType=ze.LIFECYCLE_SHOW_NEW:(e.hasExposure,e.backStatus!==!1&&(this.backStatus||this.customType||window.performance.navigation.type===2)?this.exposureType=ze.RESUME_FORM_PAGE:this.exposureType=ze.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=ze.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=ze.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}(),wm=function(){function r(e,t,i){t.autotrack&&t.autotrack.exposure&&(this._intersection=new Cm(e,t,i),this._observer=new Em(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 ea,Tm=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}(),zm={hashTag:!1,impr:!1},km=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(zm,t),this.destroyed=!1,this.options=t,this.Config=new mm(fm,this.options),this.Exposure=new wm(this.collect,this.config,this.handle.bind(this)),this.Scroll=new Tm(this.config,this.handle.bind(this)),this.Listener=new pm(t,this.collect,this.Config),this.EventHandle=new gm(this.config,t),this.Request=new vm(this.collect),this.autoTrackStart=!0,this.init(),Sm(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"})(ea||(ea={}));var ta={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"]},Rm=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 ta)if(ta[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:je};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()}),Li(function(){e.leavePage()})},r.prototype.leavePage=function(){this.report(!0)},r}(),Am=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}(),ln=typeof window<"u"?(window.LogPluginObject||(window.LogPluginObject={}),window.LogPluginObject):null,Dm=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(cn.hasOwnProperty(i)){var n=cn[i].object,s=cn[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;ln[t]?(this.process(e,ln[t]),console.log("已有"+e+"插件,避免重复加载~")):this.loadPlugin(e,i,function(){n.process(e,ln[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}(),xm=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(Dm,"extend"),_e.usePlugin(tm,"et"),_e.usePlugin(em,"ab"),_e.usePlugin(om,"stay"),_e.usePlugin(km,"autotrack"),_e.usePlugin(am,"profile"),_e.usePlugin(Am,"retry"),_e.usePlugin(cm,"heartbeat"),_e.usePlugin(um,"monitor"),_e.usePlugin(xm,"route"),_e.usePlugin(Rm,"tracer");var cr=new _e("default");const pn="VEPUSHER_DEVICE_ID",fn="VEPUSHER_USER_ID",ra=r=>Math.floor((Math.random()*9+1)*Math.pow(10,r-1)).toString();function Pm(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 Om(r){if(r)return localStorage.setItem(fn,r),r;const e=localStorage.getItem(fn);if(e)return e;const t=ra(12);return localStorage.setItem(fn,t),r}function Mm(r){if(r)return localStorage.setItem(pn,r),r;const e=localStorage.getItem(pn);if(e)return e;const t=ra(11);return localStorage.setItem(pn,t),t}class Im{constructor({showLogInConsole:e=!1}){this._showLogInConsole=!1,this.markCollectTeaEventReady=()=>{this.isReady=!0,cr.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.90",...i}};cr.config(n),this.markCollectTeaEventReady()},this.isReady=!1,this.queueTeaEvent=[],cr.init({app_id:699880,channel:"cn"}),this._showLogInConsole=e}sendTeaEvent(e,t,i=!1){if(e)if(this.isReady)try{const n={...Pm(t||{})};cr.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 cr}}let ur;function Lm({showLogInConsole:r}){ur=new Im({showLogInConsole:r})}function D(r,e,t=!1){ur&&ur.sendTeaEvent(r,e,t)}function Um(r,e){ur&&ur.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"}};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 Nm extends Be{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(Gn,"video"),{sampleRate:s}=bt(Bn,"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(Se.DeviceCaptured,e)}_notifyStopCapture(e){this.emit(Se.DeviceStopCapture,e)}_bindStreamEvent(e){e.bindTrackEnd(()=>{this.emit(Se.Interrupted,e),this.stopCapture({streamId:e.id,type:e.type})})}_handleError(e,t){const i=new yt(t,e.message);this.emit(Se.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 _u(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=Ie(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={};Op.includes(e)?t={facingMode:e}:t={deviceId:e};const i={...t,...this._videoConstraints};try{const n=await gu(i,!this._livePusher.isEnableMixing),s=new ju(n);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,ue.OPEN_CAMERA_FAILED),n}}async startMicrophoneCapture(e){const t={...this._audioConstraints,deviceId:e};try{const i=await yu(t),n=new zp(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,ue.OPEN_MICROPHONE_FAILED),i}}async startScreenCapture(e){const t={audio:e,video:this._videoConstraints};try{const i=await bu(t,void 0,!this._livePusher.isEnableMixing),n=new Rp(i);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,ue.OPEN_SCREEN_FAILED),i}}async startVideoFileCapture(e){try{const t=await ss({url:e,video:!0,audio:!0,loop:!0}),i=new kp(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,ue.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 ss({url:e,video:!1,audio:!0,loop:!0}),i=new Ap(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,ue.AUDIO_FILE_CAPTURE_FAILED),t}}async startImageCapture(e){try{const t=await vu({url:e,width:0,height:0,frameRate:30}),i=new Dp(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,ue.IMAGE_FILE_CAPTURE_FAILED),t}}startCustomVideoCapture(e){const t=Eu(e);if(t){const i=new xp(t);return this._customVideoStreams[i.id]=i,this._notifyCaptured(i),this._bindStreamEvent(i),i.id}}startCustomAudioCapture(e){const t=Cu(e);if(t){const i=new Pp(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,ue.VOLUME_DETECT_FAILED)}}stopVolumeDetect(e){const t=this.getStreamById(e);t&&t.stopVolumeDetect()}getDefaultVideoStream(){return Ie(this._cameraStreams)[0]||Ie(this._screenStreams)[0]||Ie(this._videoFileStreams)[0]||Ie(this._imageStreams)[0]||Ie(this._customVideoStreams)[0]}getDefaultAudioStream(){return Ie(this._microphoneStreams)[0]||Ie(this._audioFileStreams)[0]||Ie(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 Je=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 mn{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(Se.DeviceCaptured,e=>{this._active&&this.onStreamCapture(e)}),this._streamManagerController.on(Se.DeviceStopCapture,e=>{this._active&&this.onStreamStopCapture(e)})}getComposedStream(){return this._composedStream}enable(){this._active=!0}disable(){this._active=!1}}const ia=new Je("SingleComposer");class Gm extends mn{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){ia.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):ia.error("all video stream stop capture")}}_handleAudioStreamStopCapture(e){this._streamComposeController.removeAudioStream(e.id)}getComposedStream(){return this._composedStream}}class Bm extends Be{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(Nn.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 na extends mt{constructor(e){super({type:N.MixVideo,stream:e}),this._trackMap.video=e}get source(){return this._source}replaceVideoTrack(e){this._trackMap.video=e,this._source=e}get viewNode(){return null}get mixerNode(){return null}bindTrackEnd(e){this.source.onended=e}destroy(){this.source.stop(),delete this._trackMap.video}}var Vm=Object.defineProperty,Fm=Object.getOwnPropertyDescriptor,dr=(r,e,t,i)=>{for(var n=Fm(e,t),s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=a(e,t,n)||n);return n&&Vm(e,t,n),n};const sa=new Je("composition-composer");function hr(r,e,t){const i=t.value;return t.value=function(...n){return this._active||sa.error("composer is not active"),i.apply(this,n)},t}class kt extends mn{constructor(e){super(e),this._compositionViewConfig={width:1080,height:720,frameRate:30,backgroundColor:"#000000"},this._sprites=[],this._videoMixer=new Nu}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 na(e),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=Qs(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=>{Tp(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 na(n),this._composedStream.setVideoStream(this._mixedVideoStream),i.destroy()}}getMixingConfig(){return this._compositionViewConfig}addVideoStream(e,t){if(!e.viewNode){sa.error("have no viewNode for composition");return}e.audioTrack&&this._streamComposeController.addAudioStream({streamId:e.id,volume:100});const i=new Bm(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()}}dr([hr],kt.prototype,"addVideoStream"),dr([hr],kt.prototype,"updateVideoStream"),dr([hr],kt.prototype,"removeVideoStream"),dr([hr],kt.prototype,"muteVideoStream"),dr([hr],kt.prototype,"unmuteVideoStream");class jm extends Be{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 Hm extends Tr{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 $m extends mn{constructor(e){super(e),this._spriteList=[],this._audioMixer=new Tu({keepAlive:!0})}onStreamCapture(e){}onStreamStopCapture(e){e&&this.removeAudioStream(e.id)}_updateSpriteToMixer(){const e=Qs(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 Hm(e);this._composedStream.setAudioStream(t),this._audioMixer.mix([])}addAudioStream(e,t){const i=new jm(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 qm extends Be{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 Km=new Je("streamComposeController");class Wm{constructor(e){this._streamManagerController=e,this._composedStream=new qm,this.singleComposer=new Gm({streamManagerController:this._streamManagerController,composedStream:this._composedStream,streamComposeController:this}),this.compositionComposer=new kt({streamManagerController:this._streamManagerController,composedStream:this._composedStream,streamComposeController:this}),this.mixerComposer=new $m({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){Km.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 oa{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 Je("PreviewConsumer");class Jm extends oa{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($.CaptureFirstVideoFrame),n.video=s),a&&a!==n.audio&&(this._streamConsumeController.emit($.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($.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={},_n={},gn={exports:{}},aa;function vn(){if(aa)return gn.exports;aa=1;var r=gn.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")})}),gn.exports}var ca;function Zm(){return ca||(ca=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=vn(),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}})})}}(_n)),_n}var yn,ua;function Xm(){if(ua)return yn;ua=1;var r=vn(),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 yn=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
|
-
`},dn}var ra;function Zm(){if(ra)return ve;ra=1;var r=Wm(),e=Jm(),t=hn();return ve.grammar=t,ve.write=e,ve.parse=r.parse,ve.parseParams=r.parseParams,ve.parseFmtpConfig=r.parseFmtpConfig,ve.parsePayloads=r.parsePayloads,ve.parseRemoteCandidates=r.parseRemoteCandidates,ve.parseImageAttributes=r.parseImageAttributes,ve.parseSimulcastStreamList=r.parseSimulcastStreamList,ve}var Xm=Zm();const Gr=Y(Xm);function Br(r){return new Promise(e=>{setTimeout(e,r)})}async function Ym(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 ia(r,e={},t={}){const{timeout:i=0,retryDelay:n=0}=t;let{retryCount:s=0}=t;try{return await Ym(r,e,i)}catch(a){if(s--,t.retryCount=s,s<0)throw a;return await Br(n),await ia(r,e,t)}}const Qm=-1;function W(r,e){let t;return e.forEach(i=>{i.type===r&&(t=i)}),t}async function ln(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:W("media-source",i),codec:W("codec",i),candidatePair:W("candidate-pair",i),remoteCandidate:W("remote-candidate",i),localCandidate:W("local-candidate",i),track:W("track",i),outboundRtp:W("outbound-rtp",i),remoteInboundRtp:W("remote-inbound-rtp",i),transport:W("transport",i)}),n&&(t.video={mediaSource:W("media-source",n),codec:W("codec",n),candidatePair:W("candidate-pair",n),remoteCandidate:W("remote-candidate",n),localCandidate:W("local-candidate",n),track:W("track",n),outboundRtp:W("outbound-rtp",n),remoteInboundRtp:W("remote-inbound-rtp",n),transport:W("transport",n)}),t}async function e_(r,e,t){var u,l,d,p,f,v,m,E,y,_,C,z,w,O,k,T,A,P,ie,J,ue,he,ht,re,Ue,nc,sc,oc,ac,cc,uc,hc,dc,lc,pc,fc;const i=await ln(e,t);await Br(r);const n=await ln(e,t),{audio:s,video:a}=i,{audio:o,video:h}=n,c={};if(s!=null&&s.codec&&(o!=null&&o.codec)){const hr=((u=o.outboundRtp)==null?void 0:u.timestamp)-((l=s.outboundRtp)==null?void 0:l.timestamp),En=((d=o.outboundRtp)==null?void 0:d.bytesSent)-((p=s.outboundRtp)==null?void 0:p.bytesSent),Zr=((f=o.remoteInboundRtp)==null?void 0:f.packetsLost)-((v=s.remoteInboundRtp)==null?void 0:v.packetsLost),Cn=((m=o.outboundRtp)==null?void 0:m.packetsSent)-((E=s.outboundRtp)==null?void 0:E.packetsSent);c.audio={codec:o.codec.mimeType,channels:o.codec.channels,sendBitrate:En/hr*8e3,packetsSent:(y=o.outboundRtp)==null?void 0:y.packetsSent,nackCount:(_=o.outboundRtp)==null?void 0:_.nackCount,packetsLost:(C=o.remoteInboundRtp)==null?void 0:C.packetsLost,packetsLostPercent:Zr/Cn}}if(a!=null&&a.codec&&(h!=null&&h.codec)){const hr=((z=h.outboundRtp)==null?void 0:z.timestamp)-((w=a.outboundRtp)==null?void 0:w.timestamp),En=((O=h.outboundRtp)==null?void 0:O.bytesSent)-((k=a.outboundRtp)==null?void 0:k.bytesSent),Zr=((T=h.outboundRtp)==null?void 0:T.framesEncoded)-((A=a.outboundRtp)==null?void 0:A.framesEncoded),Cn=((P=h.outboundRtp)==null?void 0:P.totalEncodeTime)-((ie=a.outboundRtp)==null?void 0:ie.totalEncodeTime),mc=((J=h.outboundRtp)==null?void 0:J.packetsSent)-((ue=a.outboundRtp)==null?void 0:ue.packetsSent),M_=((he=h.outboundRtp)==null?void 0:he.totalPacketSendDelay)-((ht=a.outboundRtp)==null?void 0:ht.totalPacketSendDelay),I_=((re=h.remoteInboundRtp)==null?void 0:re.packetsLost)-((Ue=a.remoteInboundRtp)==null?void 0:Ue.packetsLost);c.video={codec:h.codec.mimeType,sendBitrate:En/hr*8e3,frameWidth:(nc=h.outboundRtp)==null?void 0:nc.frameWidth,frameHeight:(sc=h.outboundRtp)==null?void 0:sc.frameHeight,framesPerSecond:(oc=h.outboundRtp)==null?void 0:oc.framesPerSecond,framesEncoded:(ac=h.outboundRtp)==null?void 0:ac.framesEncoded,framesEncodedPerSecond:Zr*1e3/hr,keyFramesEncoded:(cc=h.outboundRtp)==null?void 0:cc.keyFramesEncoded,framesSent:(uc=h.outboundRtp)==null?void 0:uc.frameHeight,frameEncodeAvgTime:Cn*1e3/Zr,packetsSent:(hc=h.outboundRtp)==null?void 0:hc.packetsSent,packetSendDelay:M_*1e3/mc,nackCount:(dc=h.outboundRtp)==null?void 0:dc.nackCount,firCount:(lc=h.outboundRtp)==null?void 0:lc.firCount,pliCount:(pc=h.outboundRtp)==null?void 0:pc.pliCount,packetsLost:(fc=h.remoteInboundRtp)==null?void 0:fc.packetsLost,packetsLostPercent:I_/mc,deltaTime:hr}}return c}function ee(r,e=Qm){return r??e}function t_(r){var e,t,i,n,s,a,o,h,c,u,l,d,p,f,v,m,E,y,_,C,z;return{video_send_k_bitrate:ee((e=r.video)==null?void 0:e.sendBitrate)/1e3,video_send_frame_rate:ee((t=r.video)==null?void 0:t.framesPerSecond),video_encoder_output_frame_rate:ee((i=r.video)==null?void 0:i.framesEncodedPerSecond),video_encoded_frame_width:ee((n=r.video)==null?void 0:n.frameWidth),video_encoded_frame_height:ee((s=r.video)==null?void 0:s.frameHeight),video_encoded_key_frames:ee((a=r.video)==null?void 0:a.keyFramesEncoded),video_delta_time:ee((o=r.video)==null?void 0:o.deltaTime,2e3),video_packets_sent:ee((h=r.video)==null?void 0:h.packetsSent),video_nack_count:ee((c=r.video)==null?void 0:c.nackCount),video_fir_count:ee((u=r.video)==null?void 0:u.firCount),video_pli_count:ee((l=r.video)==null?void 0:l.pliCount),video_packets_lost:ee((d=r.video)==null?void 0:d.packetsLost),video_packets_lost_percent:(p=r.video)==null?void 0:p.packetsLostPercent,video_codec:(f=r.video)==null?void 0:f.codec,video_duration:(v=r.video)==null?void 0:v.deltaTime,audio_send_k_bitrate:ee((m=r.audio)==null?void 0:m.sendBitrate)/1e3,audio_send_channels:ee((E=r.audio)==null?void 0:E.channels),audio_packets_sent:ee((y=r.audio)==null?void 0:y.packetsSent),audio_packets_lost:ee((_=r.audio)==null?void 0:_.packetsLost),audio_packets_lost_percent:(C=r.audio)==null?void 0:C.packetsLostPercent,audio_codec:(z=r.audio)==null?void 0:z.codec}}function r_(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 i_=r=>{var t;if(!Gn)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")})},n_=r=>{r.ext&&(zc||dr)&&(r.ext=r.ext.filter(e=>{var t;return!((t=e.uri)!=null&&t.includes("video-orientation"))}))};function s_(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=100",`x-google-start-bitrate=${e}`].join(";"):r.fmtp.push({payload:i,config:`x-google-min-bitrate=100;x-google-start-bitrate=${e}`})}})}const te=new We("PCConnect");class o_{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 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(d=>(d==null?void 0:d.kind)==="audio")[0],a=e.filter(d=>(d==null?void 0:d.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]}),te.log("add track to pc,",s),this._videoTransceiver=n.addTransceiver(a||"video",{direction:"sendonly",sendEncodings:[{maxBitrate:t[1]}],streams:[this._ms]}),te.log("add track to pc,",a);const o=await n.createOffer();te.groupCollapsed("local offer"),te.log(o.sdp);const h=Gr.parse(o.sdp);h.media.forEach(d=>{d.type==="audio"?i_(d):d.type==="video"&&(n_(d),s_(d,t[1]))}),o.sdp=Gr.write(h),te.log("local offer modified"),te.log(o.sdp),await n.setLocalDescription(o);const c=await ia(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*Ks:(l=this._opts)==null?void 0:l.timeout});if((c==null?void 0:c.code)!==200)throw{code:c.code,message:c.message};te.log("remote answer:"),te.log(c.remoteSdp.sdp);const u=Gr.parse(c.remoteSdp.sdp);if(u.media.forEach(d=>{var p;(p=d.fingerprint)!=null&&p.hash&&(d.fingerprint.hash=d.fingerprint.hash.toUpperCase())}),c.remoteSdp.sdp=Gr.write(u),te.log("remote answer modified"),te.log(c.remoteSdp.sdp),te.groupEnd(),n.connectionState==="closed"){te.log("PeerConnection is closed, skipping setRemoteDescription");return}await n.setRemoteDescription(c.remoteSdp)}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)),te.log(`replace ${t} track done! ${n==null?void 0:n.label} -> ${e==null?void 0:e.label}`))}applyBitrate(e,t,i){var a,o,h;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=(h=s.encodings)!=null&&h.length?s.encodings:[{}],i?s.encodings[0].minBitrate=e:s.encodings[0].maxBitrate=e,n.setParameters(s),te.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,te.log("close pc!")}getStats(){var e,t;return ln((e=this._audioTransceiver)==null?void 0:e.sender,(t=this._videoTransceiver)==null?void 0:t.sender)}getStatsSnapshoot(e){var t,i;return e_(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",()=>{te.log("onconnectionstatechange:",e.connectionState),this._onConnectStateChange(e.connectionState)})}}var Je=(r=>(r.OnError="onerror",r.OnConnectClosed="onconnectclosed",r.OnFirstFramePushed="onfirstframepushed",r))(Je||{}),Ze=(r=>(r.Video="video",r.Audio="audio",r))(Ze||{}),me=(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))(me||{}),ct=(r=>(r.Ready="ready",r.Error="error",r.FirstFramePushed="firstframepushed",r.Flvfile="flvfile",r.STATS="stats",r.Close="close",r))(ct||{}),pn={exports:{}},na;function a_(){return na||(na=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(h,c,u){this.fn=h,this.context=c,this.once=u||!1}function s(h,c,u,l,d){if(typeof u!="function")throw new TypeError("The listener must be a function");var p=new n(u,l||h,d),f=t?t+c:c;return h._events[f]?h._events[f].fn?h._events[f]=[h._events[f],p]:h._events[f].push(p):(h._events[f]=p,h._eventsCount++),h}function a(h,c){--h._eventsCount===0?h._events=new i:delete h._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 d=0,p=l.length,f=new Array(p);d<p;d++)f[d]=l[d].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,d,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,d),!0;case 5:return m.fn.call(m.context,u,l,d,p),!0;case 6:return m.fn.call(m.context,u,l,d,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,d);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,d){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&&(!d||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||d&&!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}(pn)),pn.exports}var c_=a_();const u_=Y(c_);var Vr=(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))(Vr||{});class sa 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 oa(r,e,t){return new sa(r,e,t)}const At=class At{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 At.enable}get _enableLong(){return At.enableLong}get long(){return this._enableLong}};At.enable=!1,At.enableLong=!1;let Xe=At;const _e=new Xe("RTMP_Capture");class h_{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(_e.log(`replace ${e} track`),e===Ze.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){_e.log("no video track to capture");return}if(this.videoTrack.readyState!=="live"){_e.warn("video track not live");return}const e=new MediaStreamTrackProcessor(this.videoTrack);e.track=this.videoTrack;const t=e.readable.getReader();this._videoProcessorReader=t,_e.log("start capture video frame",this.videoTrack);let i;for(;;){i&&clearInterval(i),i=setTimeout(()=>{_e.warn("long time no capture output"),this._bridge._postMockVideoEncodeFlag()},1500);const s=await t.read();if(clearInterval(i),this._videoFirstframeCaptured||(this._videoFirstframeCaptured=!0,_e.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,_e.log("video track read done!",e.track)}async _startAudioCapture(){if(!this.audioTrack){_e.log("no audio track to capture");return}if(this.audioTrack.readyState!=="live"){_e.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,_e.log("start capture audio frame");;){const i=await t.read();if(this._audioFirstframeCaptured||(this._audioFirstframeCaptured=!0,_e.log("audio first frame captured")),i.done||!i.value)break;this._bridge._postAudioFrame(i.value,this.audioTrack.getSettings())}this._audioFirstframeCaptured=!1,this._audioProcessorReader=null,_e.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 aa='(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',ca=typeof self<"u"&&self.Blob&&new Blob([aa],{type:"text/javascript;charset=utf-8"});function d_(r){let e;try{if(e=ca&&(self.URL||self.webkitURL).createObjectURL(ca),!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(aa),{name:r==null?void 0:r.name})}finally{e&&(self.URL||self.webkitURL).revokeObjectURL(e)}}try{Xe.enable=location.href.indexOf("rtmpdebug")!==-1,Xe.enableLong=location.href.indexOf("rtmpdebug=long")!==-1}catch{}const Fr=new Xe("Bridge");class ua extends u_{constructor(){super(),this._worker=null,this._audioMsTrack=null,this._videoMsTrack=null,this._capture=new h_(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,h)=>{e=o,t=h}),n=o=>{var h;switch((h=this._worker)==null||h.removeEventListener("message",n),o.data.type){case ct.Error:t(o.data.data);break;default:this._bindWorkerEvent(),Fr.log("rtmp ready!"),e(!0)}};try{this._worker=new d_}catch(o){t(oa(Vr.RTMP_INIT_FAIL,o.message))}return(s=this._worker)==null||s.postMessage({type:me.Init,options:{logEnable:Xe.enable,logEnableLong:Xe.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 ct.Error:Fr.table(i.data.data),this.emit(Je.OnError,i.data.data);break;case ct.Flvfile:l_(i.data.buffer);break;case ct.FirstFramePushed:this.emit(Je.OnFirstFramePushed);break;case ct.Close:this.emit(Je.OnConnectClosed),this.destroy();break}}),(t=this._worker)==null||t.addEventListener("error",i=>{this.emit(Je.OnError,oa(Vr.WORKER_ERROR,i.message))})}addTrack(e){e.kind===Ze.Video&&(this._videoMsTrack=e),e.kind===Ze.Audio&&(this._audioMsTrack=e),this._setAVExist(!!this._videoMsTrack,!!this._audioMsTrack)}replaceTrack(e,t){e===Ze.Video&&(this._videoMsTrack=t),e===Ze.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,h)=>{e=o,t=h});this._worker||setTimeout(()=>{t()},0);const n=o=>{var h;switch(o.data.type){case ct.STATS:e(o.data.data),(h=this._worker)==null||h.removeEventListener("message",n);break}};return(s=this._worker)==null||s.addEventListener("message",n),(a=this._worker)==null||a.postMessage({type:me.GetStats}),i}_postVideoFrame(e,t){var i;(i=this._worker)==null||i.postMessage({type:me.VideoFrame,frame:e,setting:t},[e])}_postMockVideoEncodeFlag(){var e;(e=this._worker)==null||e.postMessage({type:me.MockVideoEncode})}_setAVExist(e,t){var i;(i=this._worker)==null||i.postMessage({type:me.AvExist,hasVideo:e,hasAudio:t})}_postAudioFrame(e,t){var i;(i=this._worker)==null||i.postMessage({type:me.AudioFrame,frame:e,setting:t},[e])}setEncodeCapacity(e){var t;(t=this._worker)==null||t.postMessage({type:me.EncodeConfig,cfg:e})}adjustBitrate(e,t){var i;(i=this._worker)==null||i.postMessage({type:me.AdjustBitrate,kind:e,bitrate:t})}publish(e){var t;Fr.log("start capture & connect"),this._capture.start(),(t=this._worker)==null||t.postMessage({type:me.Publish,url:e})}unpublish(){var e;this._capture.destroy(),(e=this._worker)==null||e.postMessage({type:me.UnPublish})}destroy(){var e;Fr.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:me.Download})}}function l_(r){const e=document.createElement("a");e.href=URL.createObjectURL(new Blob([r])),e.download=Date.now()+".flv",e.click()}const ha=new We("RTMPConnect");class p_{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 ua,this._bindEvents()}get isPushing(){return this._isPushing}get pushUrl(){return this._url}get sessionId(){return 0}_bindEvents(){this._rtmp.on(Je.OnError,e=>{this._isPushing=!1,this._onError(e)}),this._rtmp.on(Je.OnConnectClosed,()=>{this._isPushing=!1,this._onError(new sa(Vr.WTP_CONNECT_FAIL,"connect lost"))}),this._rtmp.on(Je.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(Ze.Audio,t[0]),t[1]&&this._rtmp.adjustBitrate(Ze.Video,t[1]),this._rtmp.publish(this._url)}updatePublish(e,t){ha.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 Br(e),this._rtmp.getStats()}unpublish(){ha.warn("unpublish"),this._rtmp.unpublish(),this._isPushing=!1}}class f_{constructor(e,t=Op){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,R(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:dt.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:dt.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:Yr.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:dt.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,Mp)},this.state="idle",this._pushConsumer=e,this._maxTimeout=t,this._logger=new We("ReconnectStrategy")}getNextPushUrl(){const e=this._pushConsumer.pushUrl;if(!e)return"";const t=new URL(e),i=Date.now();return t.searchParams.set("pri",i.toString()),t.href}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:dt.SUCCESS,teaParams:{reconnect_duration:s,session_id:this._pushConsumer.pushSessionId}}):(this._logger.log("Reconnect strategy stopped: ",t),this._pushConsumer.emitReconnectStateChange({state:dt.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:Yr.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 ur={ManualStop:0,ReconnectFailed:1,StartPushError:2,PushError:3},zt={PushCheck:0,PushError:1},da=new We("PushController");class m_ extends Yo{constructor(e,{config:t,streamConsumeController:i}){var n,s;if(super(e),this._connect=null,this._connectionState=de.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=gt(On,"audio").bitrate,this._videoBitrate=gt(xn,"video").bitrate,this.handleReconnectError=(a,o)=>{var h,c;R(D.STOP_PUSH_STREAM,{reason:ur.ReconnectFailed,error_message:a,session_id:this._pushSessionId,push_mode:this._pushMode,duration:this.pushDuration,reconnect_times:(h=this._reconnectStrategy)==null?void 0:h.getReconnectInfo().totalReconnectCount,reconnect_duration:(c=this._reconnectStrategy)==null?void 0:c.getReconnectInfo().totalReconnectDuration}),this.unpublish()},this.handleAudioStreamChange=a=>{this.updatePush({audioTrack:a.audioTrack})},this.handleVideoStreamChange=a=>{this.updatePush({videoTrack:a.videoTrack})},this._OnRTMPSuccess=()=>{this.setConnectState(de.CONNECTED)},this._OnRTMPError=a=>{const o=new _t(oe.PUBLISH_FAILED,`code:${a.code}, message: ${a.message}`);this._streamConsumeController.emit(j.PushError,o),R(D.STOP_PUSH_STREAM,{reason:ur.PushError,duration:this.pushDuration,session_id:this._pushSessionId,push_mode:this._pushMode,error_msg:a.message,error_code:a.code}),R(D.START_PUSH_STATUS,{is_success:!1,reason:zt.PushError,error_message:a.message,session_id:this._pushSessionId,push_mode:this._pushMode,push_url:this._pushUrl}),this.unpublish()},this._executeReconnect=()=>{var a;(a=this._reconnectStrategy)==null||a.execute(),this.setConnectState(de.RECONNECTING),this.unpublish({isReconnecting:!0})},this._OnRtcStateChange=a=>{var o;switch(this._streamConsumeController.emit(j.RTCConnectStateChanged,a),a){case"connected":this.setConnectState(de.CONNECTED);break;case"disconnected":this._reconnectStrategy&&this._executeReconnect();break;case"failed":(o=this._reconnectStrategy)!=null&&o.isActive()?this._executeReconnect():(this.connectionState===de.CONNECTED?R(D.STOP_PUSH_STREAM,{reason:ur.PushError,error_message:"peerconnection failed",duration:this.pushDuration,session_id:this._pushSessionId,push_mode:this._pushMode}):R(D.START_PUSH_STATUS,{is_success:!1,reason:zt.PushError,error_message:"peerconnection failed",session_id:this._pushSessionId,push_mode:this._pushMode,push_url:this._pushUrl}),this.unpublish(),this._streamConsumeController.emit(j.PushError,new _t(oe.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),(n=t==null?void 0:t.reconnectConfig)!=null&&n.enable||!(t!=null&&t.reconnectConfig)){const a=(s=t==null?void 0:t.reconnectConfig)!=null&&s.maxTimeout?t.reconnectConfig.maxTimeout*Ks:void 0;this._reconnectStrategy=new f_(this,a),this._reconnectStrategy.onReconnectError=this.handleReconnectError}}get isPushing(){return this._connectionState===de.CONNECTED||this._connectionState===de.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(j.LiveConnectStateChange,e),e){case de.CONNECTED:(t=this._reconnectStrategy)!=null&&t.isActive()?this._reconnectStrategy.stop({isSuccess:!0}):(this._streamConsumeController.emit(j.PushStart),this.setPushStatsInterval(),R(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,h;if(t.isReconnect||(this._pushSessionId=Date.now(),R(D.START_PUSH,{push_url:e,session_id:this._pushSessionId})),!e)throw R(D.START_PUSH_STATUS,{is_success:!1,session_id:this._pushSessionId,reason:zt.PushCheck,push_url:this._pushUrl}),new Error("lack publish url");if(this._connect)return;this.start(),this._pushUrl=e,this._pushEncodeConfig=t.cfg;const i=this._composedStream.videoTrack,n=this._composedStream.audioTrack;if(this._needCheckAudioTrack&&(!i||!n)){R(D.START_PUSH_STATUS,{is_success:!1,reason:zt.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){R(D.START_PUSH_STATUS,{is_success:!1,reason:zt.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 o_(e,this._pushConfig,this._OnRtcStateChange):s=new p_(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(de.CONNECTING),await s.publish([n,i],[this._audioBitrate,this._videoBitrate],{cfg:t.cfg,isReconnect:t.isReconnect}),t.isReconnect||(da.log("startPush begin"),this._connectionStartDate=Date.now())}catch(c){const u=new _t(oe.PUBLISH_FAILED,c.message,c);if(da.groupEnd(),(h=this._reconnectStrategy)!=null&&h.isActive())throw this.unpublish({isReconnecting:!0}),u;this._streamConsumeController.emit(j.PushError,u),R(D.STOP_PUSH_STREAM,{reason:ur.PushError,error_message:u.message,enable_reconnect:!1,push_mode:this._pushMode,session_id:this._pushSessionId,duration:this.pushDuration}),R(D.START_PUSH_STATUS,{is_success:!1,push_url:this._pushUrl,reason:zt.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;if((t=this._connect)!=null&&t.isPushing){const s=Date.now(),a=await((i=this._connect)==null?void 0:i.getStatsSnapshoot(2e3)),h=Date.now()-s;Ep(a)?this._prevStats=void 0:this._prevStats=a;const c=this.pushMode==="rtm"?t_(a):r_(a);R(D.PUSH_STATS,{...c,stats:a,push_url:this._pushUrl,push_mode:this._pushMode,session_id:this._pushSessionId,duration:c.video_duration||h,video_duration:c.video_duration||h,is_push:!0},!0)}else await Br(2e3),R(D.PUSH_STATS,{push_url:this._pushUrl,push_mode:this._pushMode,session_id:this._pushSessionId,duration:2e3,is_push:!1,is_reconnecting:((n=this._reconnectStrategy)==null?void 0:n.isActive())??!1},!0);this.connectionState!==de.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 _t(oe.UPDATE_PUBLISH_FAILED,`${i.name}, code:${i.code}`);this._streamConsumeController.emit(j.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&&(R(D.STOP_PUSH_STREAM,{reason:ur.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(de.DISCONNECTED),(a=this._reconnectStrategy)==null||a.stop({quiet:!0}),this._streamConsumeController.emit(j.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}){R(D.PUSH_RECONNECT_STATUS,{status:e,...t,...i}),this._streamConsumeController.emit(j.ReconnectStateChange,e,t)}}class __ extends Ge{constructor(e,t){super(),this._previewConsumer=new qm(e.getComposedStream(),{streamConsumeController:this}),this._pushConsumer=new m_(e.getComposedStream(),{streamConsumeController:this,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 g_=()=>typeof window>"u",Te={},jr=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 la(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 v_=async()=>{let r=await jr("sendonly");return navigator.userAgent.includes("VivoBrowser")&&(r=await jr("sendonly")),Te.h264encode=la(r),Te.vp8encode=r.indexOf("vp8")>-1,Te},y_=async()=>{let r=await jr("recvonly");return navigator.userAgent.includes("VivoBrowser")&&(r=await jr("recvonly")),Te.h264decode=la(r),Te.vp8decode=r.indexOf("vp8")>-1,Te},b_=async()=>{if(typeof Te.h264encode>"u")try{await v_()}catch{return!1}return Te.h264encode||!1},S_=async()=>{if(typeof Te.h264decode>"u")try{await y_()}catch{return!1}return Te.h264decode||!1};class E_{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 C_=new E_;let pa=!0,fa=!0;function Hr(r,e,t){const i=r.match(e);return i&&i.length>=t&&parseInt(i[t],10)}function ut(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 h=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,h),n.apply(this,[a,h])};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 h=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,h])},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 w_(r){return typeof r!="boolean"?new Error("Argument type: "+typeof r+". Please use a boolean."):(pa=r,r?"adapter.js logging disabled":"adapter.js logging enabled")}function T_(r){return typeof r!="boolean"?new Error("Argument type: "+typeof r+". Please use a boolean."):(fa=!r,"adapter.js deprecation warnings "+(r?"disabled":"enabled"))}function ma(){if(typeof window=="object"){if(pa)return;typeof console<"u"&&typeof console.log=="function"&&console.log.apply(console,arguments)}}function fn(r,e){fa&&console.warn(r+" is deprecated, please use "+e+" instead.")}function z_(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=Hr(t.userAgent,/Firefox\/(\d+)\./,1);else if(t.webkitGetUserMedia||r.isSecureContext===!1&&r.webkitRTCPeerConnection)e.browser="chrome",e.version=Hr(t.userAgent,/Chrom(e|ium)\/(\d+)\./,2);else if(r.RTCPeerConnection&&t.userAgent.match(/AppleWebKit\/(\d+)\./))e.browser="safari",e.version=Hr(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 _a(r){return Object.prototype.toString.call(r)==="[object Object]"}function ga(r){return _a(r)?Object.keys(r).reduce(function(e,t){const i=_a(r[t]),n=i?ga(r[t]):r[t],s=i&&!Object.keys(n).length;return n===void 0||s?e:Object.assign(e,{[t]:n})},{}):r}function mn(r,e,t){!e||t.has(e.id)||(t.set(e.id,e),Object.keys(e).forEach(i=>{i.endsWith("Id")?mn(r,r.get(e[i]),t):i.endsWith("Ids")&&e[i].forEach(n=>{mn(r,r.get(n),t)})}))}function va(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&&mn(r,o,n)})}),n}const ya=ma;function ba(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 h={};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(d,p){return d?d+p.charAt(0).toUpperCase()+p.slice(1):p==="deviceId"?"sourceId":p};if(u.ideal!==void 0){h.optional=h.optional||[];let d={};typeof u.ideal=="number"?(d[l("min",c)]=u.ideal,h.optional.push(d),d={},d[l("max",c)]=u.ideal,h.optional.push(d)):(d[l("",c)]=u.ideal,h.optional.push(d))}u.exact!==void 0&&typeof u.exact!="number"?(h.mandatory=h.mandatory||{},h.mandatory[l("",c)]=u.exact):["min","max"].forEach(d=>{u[d]!==void 0&&(h.mandatory=h.mandatory||{},h.mandatory[l(d,c)]=u[d])})}),o.advanced&&(h.optional=(h.optional||[]).concat(o.advanced)),h},n=function(o,h){if(e.version>=61)return h(o);if(o=JSON.parse(JSON.stringify(o)),o&&typeof o.audio=="object"){const c=function(u,l,d){l in u&&!(d in u)&&(u[d]=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(d=>{d=d.filter(f=>f.kind==="videoinput");let p=d.find(f=>l.some(v=>f.label.toLowerCase().includes(v)));return!p&&d.length&&l.includes("back")&&(p=d[d.length-1]),p&&(o.video.deviceId=c.exact?{exact:p.deviceId}:{ideal:p.deviceId}),o.video=i(o.video),ya("chrome: "+JSON.stringify(o)),h(o)})}o.video=i(o.video)}return ya("chrome: "+JSON.stringify(o)),h(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,h,c){n(o,u=>{t.webkitGetUserMedia(u,h,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(h){return n(h,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 Sa(r){r.MediaStream=r.MediaStream||r.webkitMediaStream}function Ea(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 ut(r,"track",e=>(e.transceiver||Object.defineProperty(e,"transceiver",{value:{receiver:e.receiver}}),e))}function Ca(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,h){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 h=this._senders.indexOf(o);h!==-1&&this._senders.splice(h,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(h=>h.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 wa(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=>va(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}),ut(r,"track",i=>(i.receiver._pc=i.srcElement,i)),r.RTCRtpReceiver.prototype.getStats=function(){const n=this;return this._pc.getStats().then(s=>va(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 Ta(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 h=e.apply(this,arguments);return this._shimmedLocalStreams[o.id]?this._shimmedLocalStreams[o.id].indexOf(h)===-1&&this._shimmedLocalStreams[o.id].push(h):this._shimmedLocalStreams[o.id]=[o,h],h};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 h=this.getSenders().filter(c=>o.indexOf(c)===-1);this._shimmedLocalStreams[a.id]=[a].concat(h)};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 h=this._shimmedLocalStreams[o].indexOf(a);h!==-1&&this._shimmedLocalStreams[o].splice(h,1),this._shimmedLocalStreams[o].length===1&&delete this._shimmedLocalStreams[o]}),n.apply(this,arguments)}}function za(r,e){if(!r.RTCPeerConnection)return;if(r.RTCPeerConnection.prototype.addTrack&&e.version>=65)return Ta(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 d=[].slice.call(arguments,1);if(d.length!==1||!d[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(d=>{const p=c._reverseStreams[d],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(d=>{const p=c._reverseStreams[d],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 d=arguments;return arguments.length&&typeof arguments[0]=="function"?u.apply(this,[f=>{const v=s(this,f);d[0].apply(null,[v])},f=>{d[1]&&d[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 h=Object.getOwnPropertyDescriptor(r.RTCPeerConnection.prototype,"localDescription");Object.defineProperty(r.RTCPeerConnection.prototype,"localDescription",{get(){const c=h.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 d;Object.keys(this._streams).forEach(p=>{this._streams[p].getTracks().find(v=>u.track===v)&&(d=this._streams[p])}),d&&(d.getTracks().length===1?this.removeStream(this._reverseStreams[d.id]):d.removeTrack(u.track),this.dispatchEvent(new Event("negotiationneeded")))}}function _n(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 ka(r,e){ut(r,"negotiationneeded",t=>{const i=t.target;if(!((e.version<72||i.getConfiguration&&i.getConfiguration().sdpSemantics==="plan-b")&&i.signalingState!=="stable"))return t})}const Aa=Object.freeze(Object.defineProperty({__proto__:null,fixNegotiationNeeded:ka,shimAddTrackRemoveTrack:za,shimAddTrackRemoveTrackWithNative:Ta,shimGetSendersWithDtmf:Ca,shimGetUserMedia:ba,shimMediaStream:Sa,shimOnTrack:Ea,shimPeerConnection:_n,shimSenderReceiverGetStats:wa},Symbol.toStringTag,{value:"Module"}));function Ra(r,e){const t=r&&r.navigator,i=r&&r.MediaStreamTrack;if(t.getUserMedia=function(n,s,a){fn("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,h){o in a&&!(h in a)&&(a[h]=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 k_(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 Da(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 gn(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(h=>{if(e.version<53&&!a)try{h.forEach(c=>{c.type=t[c.type]||c.type})}catch(c){if(c.name!=="TypeError")throw c;h.forEach((u,l)=>{h.set(l,Object.assign({},u,{type:t[u.type]||u.type}))})}return h}).then(a,o)}}function xa(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 Oa(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}),ut(r,"track",t=>(t.receiver._pc=t.srcElement,t)),r.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track)}}function Ma(r){!r.RTCPeerConnection||"removeStream"in r.RTCPeerConnection.prototype||(r.RTCPeerConnection.prototype.removeStream=function(t){fn("removeStream","removeTrack"),this.getSenders().forEach(i=>{i.track&&t.getTracks().includes(i.track)&&this.removeTrack(i)})})}function Ia(r){r.DataChannel&&!r.RTCDataChannel&&(r.RTCDataChannel=r.DataChannel)}function Pa(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 La(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 Ua(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 Na(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 Ga=Object.freeze(Object.defineProperty({__proto__:null,shimAddTransceiver:Pa,shimCreateAnswer:Na,shimCreateOffer:Ua,shimGetDisplayMedia:k_,shimGetParameters:La,shimGetUserMedia:Ra,shimOnTrack:Da,shimPeerConnection:gn,shimRTCDataChannel:Ia,shimReceiverGetStats:Oa,shimRemoveStream:Ma,shimSenderGetStats:xa},Symbol.toStringTag,{value:"Module"}));function Ba(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 Va(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 Fa(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],d=t.apply(this,[l]);return u?(d.then(c,u),Promise.resolve()):d},e.createAnswer=function(c,u){const l=arguments.length>=2?arguments[2]:arguments[0],d=i.apply(this,[l]);return u?(d.then(c,u),Promise.resolve()):d};let o=function(h,c,u){const l=n.apply(this,[h]);return u?(l.then(c,u),Promise.resolve()):l};e.setLocalDescription=o,o=function(h,c,u){const l=s.apply(this,[h]);return u?(l.then(c,u),Promise.resolve()):l},e.setRemoteDescription=o,o=function(h,c,u){const l=a.apply(this,[h]);return u?(l.then(c,u),Promise.resolve()):l},e.addIceCandidate=o}function ja(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(Ha(n))}!e.getUserMedia&&e.mediaDevices&&e.mediaDevices.getUserMedia&&(e.getUserMedia=(function(i,n,s){e.mediaDevices.getUserMedia(i).then(n,s)}).bind(e))}function Ha(r){return r&&r.video!==void 0?Object.assign({},r,{video:ga(r.video)}):r}function $a(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?(fn("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 Ka(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 qa(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 Wa(r){typeof r!="object"||r.AudioContext||(r.AudioContext=r.webkitAudioContext)}const Ja=Object.freeze(Object.defineProperty({__proto__:null,shimAudioContext:Wa,shimCallbacksAPI:Fa,shimConstraints:Ha,shimCreateOfferLegacy:qa,shimGetUserMedia:ja,shimLocalStreamsAPI:Ba,shimRTCIceServerUrls:$a,shimRemoteStreamsAPI:Va,shimTrackEventTransceiver:Ka},Symbol.toStringTag,{value:"Module"}));var vn={exports:{}},Za;function A_(){return Za||(Za=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
|
+
`},yn}var da;function Ym(){if(da)return be;da=1;var r=Zm(),e=Xm(),t=vn();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 Qm=Ym();const Kr=re(Qm);function Wr(r){return new Promise(e=>{setTimeout(e,r)})}async function e_(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 ha(r,e={},t={}){const{timeout:i=0,retryDelay:n=0}=t;let{retryCount:s=0}=t;try{return await e_(r,e,i)}catch(a){if(s--,t.retryCount=s,s<0)throw a;return await Wr(n),await ha(r,e,t)}}const t_=-1;function Q(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:Q("media-source",i),codec:Q("codec",i),candidatePair:Q("candidate-pair",i),remoteCandidate:Q("remote-candidate",i),localCandidate:Q("local-candidate",i),track:Q("track",i),outboundRtp:Q("outbound-rtp",i),remoteInboundRtp:Q("remote-inbound-rtp",i),transport:Q("transport",i)}),n&&(t.video={mediaSource:Q("media-source",n),codec:Q("codec",n),candidatePair:Q("candidate-pair",n),remoteCandidate:Q("remote-candidate",n),localCandidate:Q("local-candidate",n),track:Q("track",n),outboundRtp:Q("outbound-rtp",n),remoteInboundRtp:Q("remote-inbound-rtp",n),transport:Q("transport",n)}),t}async function r_(r,e,t){var u,l,h,p,f,v,m,E,y,_,C,z,w,A,k,T,R,O,K,F,J,Z,le,H,oe,Qe,et,tt,pr,fr,mr,_r,lc,pc,fc,mc,_c,gc;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 gr=((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),si=(((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/gr*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:si}}if(a!=null&&a.codec&&(d!=null&&d.codec)){const gr=((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=((O=d.outboundRtp)==null?void 0:O.framesEncoded)-((K=a.outboundRtp)==null?void 0:K.framesEncoded),xn=((F=d.outboundRtp)==null?void 0:F.totalEncodeTime)-((J=a.outboundRtp)==null?void 0:J.totalEncodeTime),si=((Z=d.outboundRtp)==null?void 0:Z.packetsSent)-((le=a.outboundRtp)==null?void 0:le.packetsSent),U_=((H=d.outboundRtp)==null?void 0:H.totalPacketSendDelay)-((oe=a.outboundRtp)==null?void 0:oe.totalPacketSendDelay),N_=((Qe=d.remoteInboundRtp)==null?void 0:Qe.packetsLost)-((et=a.remoteInboundRtp)==null?void 0:et.packetsLost);c.video={codec:d.codec.mimeType,sendBitrate:Dn/gr*8e3,frameWidth:(tt=d.outboundRtp)==null?void 0:tt.frameWidth,frameHeight:(pr=d.outboundRtp)==null?void 0:pr.frameHeight,framesPerSecond:(fr=d.outboundRtp)==null?void 0:fr.framesPerSecond,framesEncoded:(mr=d.outboundRtp)==null?void 0:mr.framesEncoded,framesEncodedPerSecond:ni*1e3/gr,keyFramesEncoded:(_r=d.outboundRtp)==null?void 0:_r.keyFramesEncoded,framesSent:(lc=d.outboundRtp)==null?void 0:lc.frameHeight,frameEncodeAvgTime:xn*1e3/ni,packetsSent:(pc=d.outboundRtp)==null?void 0:pc.packetsSent,packetSendDelay:U_*1e3/si,nackCount:(fc=d.outboundRtp)==null?void 0:fc.nackCount,firCount:(mc=d.outboundRtp)==null?void 0:mc.firCount,pliCount:(_c=d.outboundRtp)==null?void 0:_c.pliCount,packetsLost:(gc=d.remoteInboundRtp)==null?void 0:gc.packetsLost,packetsLostPercent:N_/si,deltaTime:gr}}return{stats:c,originStats:{audio:o,video:d}}}function ne(r,e=t_){return r??e}function i_(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,O,K,F,J,Z,le,H,oe,Qe,et,tt,pr,fr,mr,_r;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:(O=r.candidatePair)==null?void 0:O.responsesReceived,audio_sent_ping_requests_before_first_response:(K=r.candidatePair)==null?void 0:K.requestsSent,audio_sent_ping_requests_total:(((F=r.candidatePair)==null?void 0:F.requestsSent)??0)+(((J=r.candidatePair)==null?void 0:J.consentRequestsSent)??0),audio_sent_ping_responses:(Z=r.candidatePair)==null?void 0:Z.responsesSent,audio_local_candidate_type:(le=r.localCandidate)==null?void 0:le.candidateType,audio_local_ip:((H=r.localCandidate)==null?void 0:H.ip)||((oe=r.localCandidate)==null?void 0:oe.address),audio_local_network_type:(Qe=r.localCandidate)==null?void 0:Qe.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:(pr=r.remoteCandidate)==null?void 0:pr.candidateType,audio_remote_ip:((fr=r.remoteCandidate)==null?void 0:fr.ip)||((mr=r.remoteCandidate)==null?void 0:mr.address),audio_remote_port:(_r=r.remoteCandidate)==null?void 0:_r.port}}function n_(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,O,K,F,J,Z,le,H,oe,Qe,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)||((O=r.localCandidate)==null?void 0:O.address),video_local_network_type:(K=r.localCandidate)==null?void 0:K.networkType,video_local_port:(F=r.localCandidate)==null?void 0:F.port,video_local_protocol:(J=r.localCandidate)==null?void 0:J.protocol,video_remote_candidate_type:(Z=r.remoteCandidate)==null?void 0:Z.candidateType,video_remote_ip:((le=r.remoteCandidate)==null?void 0:le.ip)||((H=r.remoteCandidate)==null?void 0:H.address),video_remote_port:(oe=r.remoteCandidate)==null?void 0:oe.port,video_input_frame_rate:(Qe=r.mediaSource)==null?void 0:Qe.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 s_(r,e){var t,i,n,s,a,o,d,c,u,l,h,p,f,v,m,E,y,_,C,z,w,A;return{...n_(e.video??{}),video_send_k_bitrate:ne((t=r.video)==null?void 0:t.sendBitrate)/1e3,video_send_frame_rate:ne((i=r.video)==null?void 0:i.framesPerSecond),video_encoder_output_frame_rate:ne((n=r.video)==null?void 0:n.framesEncodedPerSecond),video_encoded_frame_width:ne((s=r.video)==null?void 0:s.frameWidth),video_encoded_frame_height:ne((a=r.video)==null?void 0:a.frameHeight),video_encoded_key_frames:ne((o=r.video)==null?void 0:o.keyFramesEncoded),video_delta_time:ne((d=r.video)==null?void 0:d.deltaTime,2e3),video_packets_sent:ne((c=r.video)==null?void 0:c.packetsSent),video_nack_count:ne((u=r.video)==null?void 0:u.nackCount),video_fir_count:ne((l=r.video)==null?void 0:l.firCount),video_pli_count:ne((h=r.video)==null?void 0:h.pliCount),video_packets_lost:ne((p=r.video)==null?void 0:p.packetsLost),video_packets_lost_percent:(f=r.video)==null?void 0:f.packetsLostPercent,video_codec:(v=r.video)==null?void 0:v.codec,video_duration:(m=r.video)==null?void 0:m.deltaTime,...i_(e.audio??{}),audio_send_k_bitrate:ne((E=r.audio)==null?void 0:E.sendBitrate)/1e3,audio_send_channels:ne((y=r.audio)==null?void 0:y.channels),audio_packets_sent:ne((_=r.audio)==null?void 0:_.packetsSent),audio_packets_lost:ne((C=r.audio)==null?void 0:C.packetsLost),audio_packets_lost_percent:(z=r.audio)==null?void 0:z.packetsLostPercent,audio_codec:(w=r.audio)==null?void 0:w.codec,audio_delta_energy:(A=r.audio)==null?void 0:A.deltaAudioEnergy}}function o_(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 a_=r=>{var t;if(!Kn)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")})},c_=r=>{r.ext&&(Rc||vr)&&(r.ext=r.ext.filter(e=>{var t;return!((t=e.uri)!=null&&t.includes("video-orientation"))}))};function u_(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=100",`x-google-start-bitrate=${e}`].join(";"):r.fmtp.push({payload:i,config:`x-google-min-bitrate=100;x-google-start-bitrate=${e}`})}})}const se=new Je("PCConnect");class d_{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]}),se.log("add track to pc,",s),this._videoTransceiver=n.addTransceiver(a||"video",{direction:"sendonly",sendEncodings:[{maxBitrate:t[1]}],streams:[this._ms]}),se.log("add track to pc,",a);const o=await n.createOffer();se.groupCollapsed("local offer"),se.log(o.sdp);const d=Kr.parse(o.sdp);d.media.forEach(h=>{h.type==="audio"?a_(h):h.type==="video"&&(c_(h),u_(h,t[1]))}),o.sdp=Kr.write(d),se.log("local offer modified"),se.log(o.sdp),await n.setLocalDescription(o);const c=await ha(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*eo:(l=this._opts)==null?void 0:l.timeout});if((c==null?void 0:c.code)!==200)throw{code:c.code,message:c.message};se.log("remote answer:"),se.log(c.remoteSdp.sdp);const u=Kr.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=Kr.write(u),se.log("remote answer modified"),se.log(c.remoteSdp.sdp),se.groupEnd(),n.connectionState==="closed"){se.log("PeerConnection is closed, skipping setRemoteDescription");return}await n.setRemoteDescription(c.remoteSdp)}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)),se.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),se.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,se.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 r_(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",()=>{se.log("onconnectionstatechange:",e.connectionState),this._onConnectStateChange(e.connectionState)})}}var Ze=(r=>(r.OnError="onerror",r.OnConnectClosed="onconnectclosed",r.OnFirstFramePushed="onfirstframepushed",r))(Ze||{}),Xe=(r=>(r.Video="video",r.Audio="audio",r))(Xe||{}),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:{}},la;function h_(){return la||(la=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 l_=h_();const p_=re(l_);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 pa 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 fa(r,e,t){return new pa(r,e,t)}const xt=class xt{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 xt.enable}get _enableLong(){return xt.enableLong}get long(){return this._enableLong}};xt.enable=!1,xt.enableLong=!1;let Ye=xt;const ve=new Ye("RTMP_Capture");class f_{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===Xe.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 ma='(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',_a=typeof self<"u"&&self.Blob&&new Blob([ma],{type:"text/javascript;charset=utf-8"});function m_(r){let e;try{if(e=_a&&(self.URL||self.webkitURL).createObjectURL(_a),!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(ma),{name:r==null?void 0:r.name})}finally{e&&(self.URL||self.webkitURL).revokeObjectURL(e)}}try{Ye.enable=location.href.indexOf("rtmpdebug")!==-1,Ye.enableLong=location.href.indexOf("rtmpdebug=long")!==-1}catch{}const Zr=new Ye("Bridge");class ga extends p_{constructor(){super(),this._worker=null,this._audioMsTrack=null,this._videoMsTrack=null,this._capture=new f_(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 m_}catch(o){t(fa(Jr.RTMP_INIT_FAIL,o.message))}return(s=this._worker)==null||s.postMessage({type:ge.Init,options:{logEnable:Ye.enable,logEnableLong:Ye.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(Ze.OnError,i.data.data);break;case lt.Flvfile:__(i.data.buffer);break;case lt.FirstFramePushed:this.emit(Ze.OnFirstFramePushed);break;case lt.Close:this.emit(Ze.OnConnectClosed),this.destroy();break}}),(t=this._worker)==null||t.addEventListener("error",i=>{this.emit(Ze.OnError,fa(Jr.WORKER_ERROR,i.message))})}addTrack(e){e.kind===Xe.Video&&(this._videoMsTrack=e),e.kind===Xe.Audio&&(this._audioMsTrack=e),this._setAVExist(!!this._videoMsTrack,!!this._audioMsTrack)}replaceTrack(e,t){e===Xe.Video&&(this._videoMsTrack=t),e===Xe.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 __(r){const e=document.createElement("a");e.href=URL.createObjectURL(new Blob([r])),e.download=Date.now()+".flv",e.click()}const va=new Je("RTMPConnect");class g_{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 ga,this._bindEvents()}get isPushing(){return this._isPushing}get pushUrl(){return this._url}get sessionId(){return 0}_bindEvents(){this._rtmp.on(Ze.OnError,e=>{this._isPushing=!1,this._onError(e)}),this._rtmp.on(Ze.OnConnectClosed,()=>{this._isPushing=!1,this._onError(new pa(Jr.WTP_CONNECT_FAIL,"connect lost"))}),this._rtmp.on(Ze.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(Xe.Audio,t[0]),t[1]&&this._rtmp.adjustBitrate(Xe.Video,t[1]),this._rtmp.publish(this._url)}updatePublish(e,t){va.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(){va.warn("unpublish"),this._rtmp.unpublish(),this._isPushing=!1}}class v_{constructor(e,t=Mp){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:ai.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,Ip)},this.state="idle",this._pushConsumer=e,this._maxTimeout=t,this._logger=new Je("ReconnectStrategy")}getNextPushUrl(){const e=this._pushConsumer.pushUrl;if(!e)return"";const t=new URL(e),i=Date.now();return t.searchParams.set("pri",i.toString()),t.href}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:ai.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 lr={ManualStop:0,ReconnectFailed:1,StartPushError:2,PushError:3},At={PushCheck:0,PushError:1},ya=new Je("PushController");class y_ extends oa{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(Bn,"audio").bitrate,this._videoBitrate=bt(Gn,"video").bitrate,this.handleReconnectError=(o,d)=>{var c,u;D(x.STOP_PUSH_STREAM,{reason:lr.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(ue.PUBLISH_FAILED,`code:${o.code}, message: ${o.message}`);this._streamConsumeController.emit($.PushError,d),D(x.STOP_PUSH_STREAM,{reason:lr.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:At.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($.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:lr.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:At.PushError,error_message:"peerconnection failed",session_id:this._pushSessionId,push_mode:this._pushMode,push_url:this._pushUrl}),this.unpublish(),this._streamConsumeController.emit($.PushError,new yt(ue.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*eo:void 0;this._reconnectStrategy=new v_(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($.LiveConnectStateChange,e),e){case pe.CONNECTED:(t=this._reconnectStrategy)!=null&&t.isActive()?this._reconnectStrategy.stop({isSuccess:!0}):(this._streamConsumeController.emit($.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:At.PushCheck,push_url:this._pushUrl}),new Error("lack publish url");if(this._connect)return;this.start(),this._pushUrl=e,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:At.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:At.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 d_(e,this._pushConfig,this._OnRtcStateChange):s=new g_(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||(ya.log("startPush begin"),this._connectionStartDate=Date.now())}catch(c){const u=new yt(ue.PUBLISH_FAILED,c.message,c);if(ya.groupEnd(),(d=this._reconnectStrategy)!=null&&d.isActive())throw this.unpublish({isReconnecting:!0}),u;this._streamConsumeController.emit($.PushError,u),D(x.STOP_PUSH_STREAM,{reason:lr.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:At.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;if((t=this._connect)!=null&&t.isPushing){const s=Date.now(),{stats:a,originStats:o}=await this._connect.getStatsSnapshoot(2e3),c=Date.now()-s;wp(a)?this._prevStats=void 0:this._prevStats=a;const u=this.pushMode==="rtm"?s_(a,o):o_(a),l=this.pushMode==="rtm"?(i=this._connect)==null?void 0:i.videoSenderTrackStats:{};D(x.PUSH_STATS,{...u,...l,video_draw_frame:this._streamComposedController.getCompositionDrawCountPerSecond(),stats:a,push_url:this._pushUrl,push_mode:this._pushMode,session_id:this._pushSessionId,duration:u.video_duration||c,video_duration:u.video_duration||c,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:((n=this._reconnectStrategy)==null?void 0:n.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(ue.UPDATE_PUBLISH_FAILED,`${i.name}, code:${i.code}`);this._streamConsumeController.emit($.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:lr.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($.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($.ReconnectStateChange,e,t)}}class b_ extends Be{constructor(e,t){super(),this._previewConsumer=new Jm(e.getComposedStream(),{streamConsumeController:this}),this._pushConsumer=new y_(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 S_=()=>typeof window>"u",ke={},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 ba(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 E_=async()=>{let r=await Xr("sendonly");return navigator.userAgent.includes("VivoBrowser")&&(r=await Xr("sendonly")),ke.h264encode=ba(r),ke.vp8encode=r.indexOf("vp8")>-1,ke},C_=async()=>{let r=await Xr("recvonly");return navigator.userAgent.includes("VivoBrowser")&&(r=await Xr("recvonly")),ke.h264decode=ba(r),ke.vp8decode=r.indexOf("vp8")>-1,ke},w_=async()=>{if(typeof ke.h264encode>"u")try{await E_()}catch{return!1}return ke.h264encode||!1},T_=async()=>{if(typeof ke.h264decode>"u")try{await C_()}catch{return!1}return ke.h264decode||!1};class z_{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 k_=new z_;let Sa=!0,Ea=!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 R_(r){return typeof r!="boolean"?new Error("Argument type: "+typeof r+". Please use a boolean."):(Sa=r,r?"adapter.js logging disabled":"adapter.js logging enabled")}function A_(r){return typeof r!="boolean"?new Error("Argument type: "+typeof r+". Please use a boolean."):(Ea=!r,"adapter.js deprecation warnings "+(r?"disabled":"enabled"))}function Ca(){if(typeof window=="object"){if(Sa)return;typeof console<"u"&&typeof console.log=="function"&&console.log.apply(console,arguments)}}function En(r,e){Ea&&console.warn(r+" is deprecated, please use "+e+" instead.")}function D_(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 wa(r){return Object.prototype.toString.call(r)==="[object Object]"}function Ta(r){return wa(r)?Object.keys(r).reduce(function(e,t){const i=wa(r[t]),n=i?Ta(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 za(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 ka=Ca;function Ra(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),ka("chrome: "+JSON.stringify(o)),d(o)})}o.video=i(o.video)}return ka("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 Aa(r){r.MediaStream=r.MediaStream||r.webkitMediaStream}function Da(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 xa(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 Pa(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=>za(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=>za(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 Oa(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 Ma(r,e){if(!r.RTCPeerConnection)return;if(r.RTCPeerConnection.prototype.addTrack&&e.version>=65)return Oa(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 Ia(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 La=Object.freeze(Object.defineProperty({__proto__:null,fixNegotiationNeeded:Ia,shimAddTrackRemoveTrack:Ma,shimAddTrackRemoveTrackWithNative:Oa,shimGetSendersWithDtmf:xa,shimGetUserMedia:Ra,shimMediaStream:Aa,shimOnTrack:Da,shimPeerConnection:wn,shimSenderReceiverGetStats:Pa},Symbol.toStringTag,{value:"Module"}));function Ua(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 x_(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 Na(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 Ga(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 Ba(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 Va(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 Fa(r){r.DataChannel&&!r.RTCDataChannel&&(r.RTCDataChannel=r.DataChannel)}function ja(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 Ha(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 $a(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 qa(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 Ka=Object.freeze(Object.defineProperty({__proto__:null,shimAddTransceiver:ja,shimCreateAnswer:qa,shimCreateOffer:$a,shimGetDisplayMedia:x_,shimGetParameters:Ha,shimGetUserMedia:Ua,shimOnTrack:Na,shimPeerConnection:Tn,shimRTCDataChannel:Fa,shimReceiverGetStats:Ba,shimRemoveStream:Va,shimSenderGetStats:Ga},Symbol.toStringTag,{value:"Module"}));function Wa(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 Ja(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 Za(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 Xa(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(Ya(n))}!e.getUserMedia&&e.mediaDevices&&e.mediaDevices.getUserMedia&&(e.getUserMedia=(function(i,n,s){e.mediaDevices.getUserMedia(i).then(n,s)}).bind(e))}function Ya(r){return r&&r.video!==void 0?Object.assign({},r,{video:Ta(r.video)}):r}function Qa(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 ec(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 tc(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 rc(r){typeof r!="object"||r.AudioContext||(r.AudioContext=r.webkitAudioContext)}const ic=Object.freeze(Object.defineProperty({__proto__:null,shimAudioContext:rc,shimCallbacksAPI:Za,shimConstraints:Ya,shimCreateOfferLegacy:tc,shimGetUserMedia:Xa,shimLocalStreamsAPI:Wa,shimRTCIceServerUrls:Qa,shimRemoteStreamsAPI:Ja,shimTrackEventTransceiver:ec},Symbol.toStringTag,{value:"Module"}));var zn={exports:{}},nc;function P_(){return nc||(nc=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
|
|
@@ -79,14 +79,14 @@ m=`).map((n,s)=>(s>0?"m="+n:n).trim()+`\r
|
|
|
79
79
|
`},e.parseCryptoKeyParams=function(t){if(t.indexOf("inline:")!==0)return null;const i=t.substring(7).split("|");return{keyMethod:"inline",keySalt:i[0],lifeTime:i[1],mkiValue:i[2]?i[2].split(":")[0]:void 0,mkiLength:i[2]?i[2].split(":")[1]:void 0}},e.writeCryptoKeyParams=function(t){return t.keyMethod+":"+t.keySalt+(t.lifeTime?"|"+t.lifeTime:"")+(t.mkiValue&&t.mkiLength?"|"+t.mkiValue+":"+t.mkiLength:"")},e.getCryptoParameters=function(t,i){return e.matchPrefix(t+i,"a=crypto:").map(e.parseCryptoLine)},e.getIceParameters=function(t,i){const n=e.matchPrefix(t+i,"a=ice-ufrag:")[0],s=e.matchPrefix(t+i,"a=ice-pwd:")[0];return n&&s?{usernameFragment:n.substring(12),password:s.substring(10)}:null},e.writeIceParameters=function(t){let i="a=ice-ufrag:"+t.usernameFragment+`\r
|
|
80
80
|
a=ice-pwd:`+t.password+`\r
|
|
81
81
|
`;return t.iceLite&&(i+=`a=ice-lite\r
|
|
82
|
-
`),i},e.parseRtpParameters=function(t){const i={codecs:[],headerExtensions:[],fecMechanisms:[],rtcp:[]},s=e.splitLines(t)[0].split(" ");i.profile=s[2];for(let o=3;o<s.length;o++){const
|
|
82
|
+
`),i},e.parseRtpParameters=function(t){const i={codecs:[],headerExtensions:[],fecMechanisms:[],rtcp:[]},s=e.splitLines(t)[0].split(" ");i.profile=s[2];for(let o=3;o<s.length;o++){const d=s[o],c=e.matchPrefix(t,"a=rtpmap:"+d+" ")[0];if(c){const u=e.parseRtpMap(c),l=e.matchPrefix(t,"a=fmtp:"+d+" ");switch(u.parameters=l.length?e.parseFmtp(l[0]):{},u.rtcpFeedback=e.matchPrefix(t,"a=rtcp-fb:"+d+" ").map(e.parseRtcpFb),i.codecs.push(u),u.name.toUpperCase()){case"RED":case"ULPFEC":i.fecMechanisms.push(u.name.toUpperCase());break}}}e.matchPrefix(t,"a=extmap:").forEach(o=>{i.headerExtensions.push(e.parseExtmap(o))});const a=e.matchPrefix(t,"a=rtcp-fb:* ").map(e.parseRtcpFb);return i.codecs.forEach(o=>{a.forEach(d=>{o.rtcpFeedback.find(u=>u.type===d.type&&u.parameter===d.parameter)||o.rtcpFeedback.push(d)})}),i},e.writeRtpDescription=function(t,i){let n="";n+="m="+t+" ",n+=i.codecs.length>0?"9":"0",n+=" "+(i.profile||"UDP/TLS/RTP/SAVPF")+" ",n+=i.codecs.map(a=>a.preferredPayloadType!==void 0?a.preferredPayloadType:a.payloadType).join(" ")+`\r
|
|
83
83
|
`,n+=`c=IN IP4 0.0.0.0\r
|
|
84
84
|
`,n+=`a=rtcp:9 IN IP4 0.0.0.0\r
|
|
85
85
|
`,i.codecs.forEach(a=>{n+=e.writeRtpMap(a),n+=e.writeFmtp(a),n+=e.writeRtcpFb(a)});let s=0;return i.codecs.forEach(a=>{a.maxptime>s&&(s=a.maxptime)}),s>0&&(n+="a=maxptime:"+s+`\r
|
|
86
|
-
`),i.headerExtensions&&i.headerExtensions.forEach(a=>{n+=e.writeExtmap(a)}),n},e.parseRtpEncodingParameters=function(t){const i=[],n=e.parseRtpParameters(t),s=n.fecMechanisms.indexOf("RED")!==-1,a=n.fecMechanisms.indexOf("ULPFEC")!==-1,o=e.matchPrefix(t,"a=ssrc:").map(
|
|
86
|
+
`),i.headerExtensions&&i.headerExtensions.forEach(a=>{n+=e.writeExtmap(a)}),n},e.parseRtpEncodingParameters=function(t){const i=[],n=e.parseRtpParameters(t),s=n.fecMechanisms.indexOf("RED")!==-1,a=n.fecMechanisms.indexOf("ULPFEC")!==-1,o=e.matchPrefix(t,"a=ssrc:").map(h=>e.parseSsrcMedia(h)).filter(h=>h.attribute==="cname"),d=o.length>0&&o[0].ssrc;let c;const u=e.matchPrefix(t,"a=ssrc-group:FID").map(h=>h.substring(17).split(" ").map(f=>parseInt(f,10)));u.length>0&&u[0].length>1&&u[0][0]===d&&(c=u[0][1]),n.codecs.forEach(h=>{if(h.name.toUpperCase()==="RTX"&&h.parameters.apt){let p={ssrc:d,codecPayloadType:parseInt(h.parameters.apt,10)};d&&c&&(p.rtx={ssrc:c}),i.push(p),s&&(p=JSON.parse(JSON.stringify(p)),p.fec={ssrc:d,mechanism:a?"red+ulpfec":"red"},i.push(p))}}),i.length===0&&d&&i.push({ssrc:d});let l=e.matchPrefix(t,"b=");return l.length&&(l[0].indexOf("b=TIAS:")===0?l=parseInt(l[0].substring(7),10):l[0].indexOf("b=AS:")===0?l=parseInt(l[0].substring(5),10)*1e3*.95-50*40*8:l=void 0,i.forEach(h=>{h.maxBitrate=l})),i},e.parseRtcpParameters=function(t){const i={},n=e.matchPrefix(t,"a=ssrc:").map(o=>e.parseSsrcMedia(o)).filter(o=>o.attribute==="cname")[0];n&&(i.cname=n.value,i.ssrc=n.ssrc);const s=e.matchPrefix(t,"a=rtcp-rsize");i.reducedSize=s.length>0,i.compound=s.length===0;const a=e.matchPrefix(t,"a=rtcp-mux");return i.mux=a.length>0,i},e.writeRtcpParameters=function(t){let i="";return t.reducedSize&&(i+=`a=rtcp-rsize\r
|
|
87
87
|
`),t.mux&&(i+=`a=rtcp-mux\r
|
|
88
88
|
`),t.ssrc!==void 0&&t.cname&&(i+="a=ssrc:"+t.ssrc+" cname:"+t.cname+`\r
|
|
89
|
-
`),i},e.parseMsid=function(t){let i;const n=e.matchPrefix(t,"a=msid:");if(n.length===1)return i=n[0].substring(7).split(" "),{stream:i[0],track:i[1]};const s=e.matchPrefix(t,"a=ssrc:").map(a=>e.parseSsrcMedia(a)).filter(a=>a.attribute==="msid");if(s.length>0)return i=s[0].value.split(" "),{stream:i[0],track:i[1]}},e.parseSctpDescription=function(t){const i=e.parseMLine(t),n=e.matchPrefix(t,"a=max-message-size:");let s;n.length>0&&(s=parseInt(n[0].substring(19),10)),isNaN(s)&&(s=65536);const a=e.matchPrefix(t,"a=sctp-port:");if(a.length>0)return{port:parseInt(a[0].substring(12),10),protocol:i.fmt,maxMessageSize:s};const o=e.matchPrefix(t,"a=sctpmap:");if(o.length>0){const
|
|
89
|
+
`),i},e.parseMsid=function(t){let i;const n=e.matchPrefix(t,"a=msid:");if(n.length===1)return i=n[0].substring(7).split(" "),{stream:i[0],track:i[1]};const s=e.matchPrefix(t,"a=ssrc:").map(a=>e.parseSsrcMedia(a)).filter(a=>a.attribute==="msid");if(s.length>0)return i=s[0].value.split(" "),{stream:i[0],track:i[1]}},e.parseSctpDescription=function(t){const i=e.parseMLine(t),n=e.matchPrefix(t,"a=max-message-size:");let s;n.length>0&&(s=parseInt(n[0].substring(19),10)),isNaN(s)&&(s=65536);const a=e.matchPrefix(t,"a=sctp-port:");if(a.length>0)return{port:parseInt(a[0].substring(12),10),protocol:i.fmt,maxMessageSize:s};const o=e.matchPrefix(t,"a=sctpmap:");if(o.length>0){const d=o[0].substring(10).split(" ");return{port:parseInt(d[0],10),protocol:d[1],maxMessageSize:s}}},e.writeSctpDescription=function(t,i){let n=[];return t.protocol!=="DTLS/SCTP"?n=["m="+t.kind+" 9 "+t.protocol+" "+i.protocol+`\r
|
|
90
90
|
`,`c=IN IP4 0.0.0.0\r
|
|
91
91
|
`,"a=sctp-port:"+i.port+`\r
|
|
92
92
|
`]:n=["m="+t.kind+" 9 "+t.protocol+" "+i.port+`\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}(
|
|
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 sc=P_();const Dt=re(sc),O_=ye({__proto__:null,default:Dt},[sc]);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=Dt.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=Dt.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=Dt.splitSections(o.sdp);return d.shift(),d.some(c=>{const u=Dt.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=Dt.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 Wr(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 Jr(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 D_=Object.freeze(Object.defineProperty({__proto__:null,removeExtmapAllowMixed:Sn,shimAddIceCandidateNullOrEmpty:Wr,shimConnectionState:bn,shimMaxMessageSize:Kr,shimParameterlessSetLocalDescription:Jr,shimRTCIceCandidate:$r,shimRTCIceCandidateRelayProtocol:yn,shimSendThrowTypeError:qr},Symbol.toStringTag,{value:"Module"}));function x_({window:r}={},e={shimChrome:!0,shimFirefox:!0,shimSafari:!0}){const t=ma,i=z_(r),n={browserDetails:i,commonShim:D_,extractVersion:Hr,disableLog:w_,disableWarnings:T_,sdp:R_};switch(i.browser){case"chrome":if(!Aa||!_n||!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=Aa,Wr(r,i),Jr(r),ba(r,i),Sa(r),_n(r,i),Ea(r),za(r,i),Ca(r),wa(r),ka(r,i),$r(r),yn(r),bn(r),Kr(r,i),qr(r),Sn(r,i);break;case"firefox":if(!Ga||!gn||!e.shimFirefox)return t("Firefox shim is not included in this adapter release."),n;t("adapter.js shimming firefox."),n.browserShim=Ga,Wr(r,i),Jr(r),Ra(r,i),gn(r,i),Da(r),Ma(r),xa(r),Oa(r),Ia(r),Pa(r),La(r),Ua(r),Na(r),$r(r),bn(r),Kr(r,i),qr(r);break;case"safari":if(!Ja||!e.shimSafari)return t("Safari shim is not included in this adapter release."),n;t("adapter.js shimming safari."),n.browserShim=Ja,Wr(r,i),Jr(r),$a(r),qa(r),Fa(r),Ba(r),Va(r),Ka(r),ja(r),Wa(r),$r(r),yn(r),Kr(r,i),qr(r),Sn(r,i);break;default:t("Unsupported browser!");break}return n}x_({window:typeof window>"u"?void 0:window});class O_ extends Ge{static async isSupported(e){if(e==="webTransport")return Promise.resolve(ua.isSupported());try{return g_()||!window.RTCPeerConnection||!window.RTCPeerConnection.prototype.addTransceiver||!window.RTCPeerConnection.prototype.createDataChannel?!1:await S_()&&await b_()}catch{return!1}}constructor(e){var t,i,n,s,a,o,h,c,u,l;if(super(),this._options=e??{},this._streamManagerController=new Lm(this),this._streamComposeController=new Km(this._streamManagerController),this._streamConsumeController=new __(this._streamComposeController,e),this._streamConsumeController.setPushConfig(e),this._observer=C_,this._bindEvent(),!(e!=null&&e.loggerConfig)||(t=e==null?void 0:e.loggerConfig)!=null&&t.enable){Im({showLogInConsole:((i=e==null?void 0:e.loggerConfig)==null?void 0:i.showInConsole)??!1});const d=xm((n=e==null?void 0:e.loggerConfig)==null?void 0:n.userId),p=Om((s=e==null?void 0:e.loggerConfig)==null?void 0:s.deviceId);Pm({user_unique_id:d,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:((h=e==null?void 0:e.loggerConfig)==null?void 0:h.appId)??0},{user_id:d,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}),R(D.PUSHER_INIT,e)}}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(R(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){R(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(R(D.PUSH_AUDIO_CONTEXT_START_FAILED,{error:t}),this._options.checkAudio)throw new _t(oe.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){R(D.ADD_VIDEO_STREAM,{number:$(e)?e.length:1,config:e}),$(e)?e.forEach(t=>{this._streamComposeController.addVideoStream(t)}):this._streamComposeController.addVideoStream(e)}removeVideoStream(e){R(D.DELETE_VIDEO_STREAM,{stream_id:e}),this._streamComposeController.removeVideoStream(e)}updateVideoStream(e){R(D.UPDATE_VIDEO_STREAM,{number:$(e)?e.length:1,config:e}),$(e)?this._streamComposeController.updateVideoStream(e):this._streamComposeController.updateVideoStream([e])}muteVideoStream(e){R(D.CHANGE_VIDEO_STREAM_MUTE,{stream_id:e,mute:!1}),this._streamComposeController.muteVideoStream(e)}unmuteVideoStream(e){R(D.CHANGE_VIDEO_STREAM_MUTE,{stream_id:e,mute:!0}),this._streamComposeController.unmuteVideoStream(e)}addAudioStream(e){R(D.ADD_AUDIO_STREAM,{number:$(e)?e.length:1,config:e}),$(e)?e.map(t=>this._streamComposeController.addAudioStream(t)):this._streamComposeController.addAudioStream(e)}removeAudioStream(e){R(D.DELETE_AUDIO_STREAM,{stream_id:e}),this._streamComposeController.removeAudioStream(e)}updateAudioStream(e){R(D.UPDATE_AUDIO_STREAM,{number:$(e)?e.length:1,config:e}),$(e)?this._streamComposeController.updateAudioStream(e):this._streamComposeController.updateAudioStream([e])}muteAudioStream(e){R(D.CHANGE_AUDIO_STREAM_MUTE,{stream_id:e,mute:!0}),this._streamComposeController.muteAudioStream(e)}unmuteAudioStream(e){R(D.CHANGE_AUDIO_STREAM_MUTE,{stream_id:e,mute:!1}),this._streamComposeController.unmuteAudioStream(e)}setProperty(e,t){switch(R(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":_r.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(R(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}=gt(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){R(D.SET_AUDIO_QUALITY,{quality:e});const{sampleRate:t,bitrate:i}=gt(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(ye.Error,e=>{this.observer.onError(e.code,e.message,e.ext)}),this._streamManagerController.on(ye.Interrupted,e=>{this.observer.onCaptureInterrupted(e.id)}),this._streamConsumeController.on(j.PushStart,()=>{this.observer.onPushStart()}),this._streamConsumeController.on(j.PushStop,()=>{this.observer.onPushStop()}),this._streamConsumeController.on(j.RTCConnectStateChanged,e=>{this.observer.onPushStatusUpdate(Rn[e],e)}),this._streamConsumeController.on(j.PushError,e=>{this.observer.onError(e.code,e.message,e.ext)}),this._streamManagerController.on(ye.DeviceStopCapture,e=>{this.observer.onStopCapture(e.id)}),this._streamConsumeController.on(j.CaptureFirstAudioFrame,()=>{this.observer.onCaptureFirstAudioFrame()}),this._streamConsumeController.on(j.CaptureFirstVideoFrame,()=>{this.observer.onCaptureFirstVideoFrame()}),this._streamConsumeController.on(j.ReconnectStateChange,(e,t)=>{this.observer.onReconnectStateChange(e,t)}),this._streamConsumeController.on(j.LiveConnectStateChange,e=>{this.observer.onLiveConnectStateChange(e)}),yu(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 O_});
|
|
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 M_=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 I_({window:r}={},e={shimChrome:!0,shimFirefox:!0,shimSafari:!0}){const t=Ca,i=D_(r),n={browserDetails:i,commonShim:M_,extractVersion:Yr,disableLog:R_,disableWarnings:A_,sdp:O_};switch(i.browser){case"chrome":if(!La||!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=La,ri(r,i),ii(r),Ra(r,i),Aa(r),wn(r,i),Da(r),Ma(r,i),xa(r),Pa(r),Ia(r,i),Qr(r),kn(r),Rn(r),ei(r,i),ti(r),An(r,i);break;case"firefox":if(!Ka||!Tn||!e.shimFirefox)return t("Firefox shim is not included in this adapter release."),n;t("adapter.js shimming firefox."),n.browserShim=Ka,ri(r,i),ii(r),Ua(r,i),Tn(r,i),Na(r),Va(r),Ga(r),Ba(r),Fa(r),ja(r),Ha(r),$a(r),qa(r),Qr(r),Rn(r),ei(r,i),ti(r);break;case"safari":if(!ic||!e.shimSafari)return t("Safari shim is not included in this adapter release."),n;t("adapter.js shimming safari."),n.browserShim=ic,ri(r,i),ii(r),Qa(r),tc(r),Za(r),Wa(r),Ja(r),ec(r),Xa(r),rc(r),Qr(r),kn(r),ei(r,i),ti(r),An(r,i);break;default:t("Unsupported browser!");break}return n}I_({window:typeof window>"u"?void 0:window});class L_ extends Be{static async isSupported(e){if(e==="webTransport")return Promise.resolve(ga.isSupported());try{return S_()||!window.RTCPeerConnection||!window.RTCPeerConnection.prototype.addTransceiver||!window.RTCPeerConnection.prototype.createDataChannel?!1:await T_()&&await w_()}catch{return!1}}constructor(e){var t,i,n,s,a,o,d,c,u,l;if(super(),this._options=e??{},this._streamManagerController=new Nm(this),this._streamComposeController=new Wm(this._streamManagerController),this._streamConsumeController=new b_(this._streamComposeController,e),this._streamConsumeController.setPushConfig(e),this._observer=k_,this._bindEvent(),!(e!=null&&e.loggerConfig)||(t=e==null?void 0:e.loggerConfig)!=null&&t.enable){Lm({showLogInConsole:((i=e==null?void 0:e.loggerConfig)==null?void 0:i.showInConsole)??!1});const h=Om((n=e==null?void 0:e.loggerConfig)==null?void 0:n.userId),p=Mm((s=e==null?void 0:e.loggerConfig)==null?void 0:s.deviceId);Um({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,e)}}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(ue.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:W(e)?e.length:1,config:e}),W(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:W(e)?e.length:1,config:e}),W(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:W(e)?e.length:1,config:e}),W(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:W(e)?e.length:1,config:e}),W(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":wr.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(Se.Error,e=>{this.observer.onError(e.code,e.message,e.ext)}),this._streamManagerController.on(Se.Interrupted,e=>{this.observer.onCaptureInterrupted(e.id)}),this._streamConsumeController.on($.PushStart,()=>{this.observer.onPushStart()}),this._streamConsumeController.on($.PushStop,()=>{this.observer.onPushStop()}),this._streamConsumeController.on($.RTCConnectStateChanged,e=>{this.observer.onPushStatusUpdate(Un[e],e)}),this._streamConsumeController.on($.PushError,e=>{this.observer.onError(e.code,e.message,e.ext)}),this._streamManagerController.on(Se.DeviceStopCapture,e=>{this.observer.onStopCapture(e.id)}),this._streamConsumeController.on($.CaptureFirstAudioFrame,()=>{this.observer.onCaptureFirstAudioFrame()}),this._streamConsumeController.on($.CaptureFirstVideoFrame,()=>{this.observer.onCaptureFirstVideoFrame()}),this._streamConsumeController.on($.ReconnectStateChange,(e,t)=>{this.observer.onReconnectStateChange(e,t)}),this._streamConsumeController.on($.LiveConnectStateChange,e=>{this.observer.onLiveConnectStateChange(e)}),Su(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 L_});
|