@byteplus/vepusher 2.0.4-rc.5 → 2.0.4-rc.6
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.js +2519 -2397
- package/dist/index.umd.js +8 -8
- package/package.json +1 -1
package/dist/index.umd.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
(function(Oe,fe){typeof exports=="object"&&typeof module<"u"?module.exports=fe():typeof define=="function"&&define.amd?define(fe):(Oe=typeof globalThis<"u"?globalThis:Oe||self,Oe.vePusher=fe())})(this,function(){"use strict";var gg=Object.defineProperty;var vg=(Oe,fe,nt)=>fe in Oe?gg(Oe,fe,{enumerable:!0,configurable:!0,writable:!0,value:nt}):Oe[fe]=nt;var O=(Oe,fe,nt)=>vg(Oe,typeof fe!="symbol"?fe+"":fe,nt);var Pc,Mc,Lc,Nc,Uc,Gc;function Oe(r,e){for(var t=0;t<e.length;t++){const n=e[t];if(typeof n!="string"&&!Array.isArray(n)){for(const i in n)if(i!=="default"&&!(i in r)){const s=Object.getOwnPropertyDescriptor(n,i);s&&Object.defineProperty(r,i,s.get?s:{enumerable:!0,get:()=>n[i]})}}}return Object.freeze(Object.defineProperty(r,Symbol.toStringTag,{value:"Module"}))}function fe(r){return r&&r.__esModule&&Object.prototype.hasOwnProperty.call(r,"default")?r.default:r}var nt={exports:{}},ss;function Fc(){return ss||(ss=1,function(r){var e=Object.prototype.hasOwnProperty,t="~";function n(){}Object.create&&(n.prototype=Object.create(null),new n().__proto__||(t=!1));function i(d,c,u){this.fn=d,this.context=c,this.once=u||!1}function s(d,c,u,h,l){if(typeof u!="function")throw new TypeError("The listener must be a function");var f=new i(u,h||d,l),y=t?t+c:c;return d._events[y]?d._events[y].fn?d._events[y]=[d._events[y],f]:d._events[y].push(f):(d._events[y]=f,d._eventsCount++),d}function a(d,c){--d._eventsCount===0?d._events=new n:delete d._events[c]}function o(){this._events=new n,this._eventsCount=0}o.prototype.eventNames=function(){var c=[],u,h;if(this._eventsCount===0)return c;for(h in u=this._events)e.call(u,h)&&c.push(t?h.slice(1):h);return Object.getOwnPropertySymbols?c.concat(Object.getOwnPropertySymbols(u)):c},o.prototype.listeners=function(c){var u=t?t+c:c,h=this._events[u];if(!h)return[];if(h.fn)return[h.fn];for(var l=0,f=h.length,y=new Array(f);l<f;l++)y[l]=h[l].fn;return y},o.prototype.listenerCount=function(c){var u=t?t+c:c,h=this._events[u];return h?h.fn?1:h.length:0},o.prototype.emit=function(c,u,h,l,f,y){var C=t?t+c:c;if(!this._events[C])return!1;var v=this._events[C],E=arguments.length,k,g;if(v.fn){switch(v.once&&this.removeListener(c,v.fn,void 0,!0),E){case 1:return v.fn.call(v.context),!0;case 2:return v.fn.call(v.context,u),!0;case 3:return v.fn.call(v.context,u,h),!0;case 4:return v.fn.call(v.context,u,h,l),!0;case 5:return v.fn.call(v.context,u,h,l,f),!0;case 6:return v.fn.call(v.context,u,h,l,f,y),!0}for(g=1,k=new Array(E-1);g<E;g++)k[g-1]=arguments[g];v.fn.apply(v.context,k)}else{var D=v.length,L;for(g=0;g<D;g++)switch(v[g].once&&this.removeListener(c,v[g].fn,void 0,!0),E){case 1:v[g].fn.call(v[g].context);break;case 2:v[g].fn.call(v[g].context,u);break;case 3:v[g].fn.call(v[g].context,u,h);break;case 4:v[g].fn.call(v[g].context,u,h,l);break;default:if(!k)for(L=1,k=new Array(E-1);L<E;L++)k[L-1]=arguments[L];v[g].fn.apply(v[g].context,k)}}return!0},o.prototype.on=function(c,u,h){return s(this,c,u,h,!1)},o.prototype.once=function(c,u,h){return s(this,c,u,h,!0)},o.prototype.removeListener=function(c,u,h,l){var f=t?t+c:c;if(!this._events[f])return this;if(!u)return a(this,f),this;var y=this._events[f];if(y.fn)y.fn===u&&(!l||y.once)&&(!h||y.context===h)&&a(this,f);else{for(var C=0,v=[],E=y.length;C<E;C++)(y[C].fn!==u||l&&!y[C].once||h&&y[C].context!==h)&&v.push(y[C]);v.length?this._events[f]=v.length===1?v[0]:v:a(this,f)}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 n,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}(nt)),nt.exports}var Vc=Fc();const it=fe(Vc);var os=(r=>(r.LeftToRight="LeftToRight",r.UpToDown="UpToDown",r.All="All",r.None="None",r))(os||{}),Y=(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))(Y||{}),Ge=(r=>(r.DeviceCaptured="deviceCaptured",r.DeviceStopCapture="deviceStopCapture",r.Error="error",r.Interrupted="interrupted",r))(Ge||{}),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))(se||{}),as=(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))(as||{}),cs=(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))(cs||{}),us=(r=>(r.STANDARD="48000x40",r.HIGH="48000x128",r))(us||{}),St=(r=>(r.VideoStreamChange="videoStreamChange",r.AudioStreamChange="audioStreamChange",r))(St||{}),ds=(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))(ds||{});const ls={SizeChange:"sizeChange"};var An=(r=>(r.Portrait="portrait",r.Landscape="landscape",r))(An||{});const hs="720p-1",ps="STANDARD";var Te=(r=>(r[r.DISCONNECTED=0]="DISCONNECTED",r[r.CONNECTING=1]="CONNECTING",r[r.CONNECTED=2]="CONNECTED",r[r.RECONNECTING=3]="RECONNECTING",r))(Te||{}),Lt=(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))(Lt||{}),Dn=(r=>(r[r.PushUrlInvalid=1001]="PushUrlInvalid",r[r.ReconnectTimeout=1002]="ReconnectTimeout",r))(Dn||{}),K=(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))(K||{}),te=(r=>(r.AUDIO="audio",r.VIDEO="video",r))(te||{}),me=(r=>(r.ENDED="ended",r.MUTE="mute",r.UNMUTE="unmute",r.PLAY_FAILED="play-failed",r.SIZE_CHANGE="size-change",r))(me||{});const de=[];for(let r=0;r<256;++r)de.push((r+256).toString(16).slice(1));function jc(r,e=0){return(de[r[e+0]]+de[r[e+1]]+de[r[e+2]]+de[r[e+3]]+"-"+de[r[e+4]]+de[r[e+5]]+"-"+de[r[e+6]]+de[r[e+7]]+"-"+de[r[e+8]]+de[r[e+9]]+"-"+de[r[e+10]]+de[r[e+11]]+de[r[e+12]]+de[r[e+13]]+de[r[e+14]]+de[r[e+15]]).toLowerCase()}let xn;const Hc=new Uint8Array(16);function qc(){if(!xn){if(typeof crypto>"u"||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");xn=crypto.getRandomValues.bind(crypto)}return xn(Hc)}const fs={randomUUID:typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};function bt(r,e,t){var i;if(fs.randomUUID&&!r)return fs.randomUUID();r=r||{};const n=r.random??((i=r.rng)==null?void 0:i.call(r))??qc();if(n.length<16)throw new Error("Random bytes length must be >= 16");return n[6]=n[6]&15|64,n[8]=n[8]&63|128,jc(n)}class ms{constructor(){O(this,"id",bt());O(this,"_nextNode");O(this,"_track");O(this,"_destNode")}gain(e){if(this._nextNode instanceof _s)return this._nextNode.g=e,this._nextNode;const t=new _s(this,{g:e});return this._nextNode=t,t}connect(e,t){if(!this.available())return;let{_node:n}=this;n||(n=this.createNode(e)),this._node=n,this.previousNode&&this.previousNode.connect(e,n),t&&n.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 _s extends ms{constructor(t,n){super();O(this,"previousNode");O(this,"_node");O(this,"_g");this.previousNode=t,this._g=n.g}createNode(t){return new GainNode(t,{gain:this._g})}set g(t){this._g=t,this._node&&(this._node.gain.value=t)}}class $c extends ms{constructor(t){super();O(this,"previousNode",null);O(this,"source");this.source=t}available(){return this.source.available()}destroy(){super.destroy()}}class Kc extends $c{constructor(){super(...arguments);O(this,"_node")}createNode(t){if(this._node)return this._node;let n;if(this.source instanceof Ts){const i=this.source.element();n=new MediaElementAudioSourceNode(t,{mediaElement:i}),i.muted=!1}else{const i=this.source.track();n=new MediaStreamAudioSourceNode(t,{mediaStream:new MediaStream([i])})}return n}}class $ extends Error{constructor(t,n,i){super(n);O(this,"code");O(this,"message");O(this,"error");this.code=t,this.message=n,this.error=i,Object.setPrototypeOf(this,$.prototype)}toString(){return`VeCapture Error: ${this.code} ${this.message}`}}const gs={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"}},vs="__debug__",Wc="[VE-CAPTURE]";function Jc(){if(typeof location>"u"||typeof localStorage>"u")return!1;let r=!1;return location.href.includes(vs)&&(r=!0),localStorage.getItem(vs)&&(r=!0),r}let ye=class{constructor(e){O(this,"moduleName");this.moduleName=e}print(e,t,...n){const i=Xc();Jc()&&console.log(`${i}-${Wc}%c[${gs[e].text}]%c[${this.moduleName}][${t}]`,`background-color:${gs[e].color};`,"background-color:rgba(0, 0, 0, 0)",...n)}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 n=this;return function(...s){n.info(`${t}-invoke`,...s);try{const a=e(...s);return typeof(a==null?void 0:a.then)=="function"?a.then(o=>(n.success(`${t}-result`,o),o)).catch(o=>{throw n.error(`${t}-result`,o),o}):(n.success(`${t}-result`,a),a)}catch(a){n.error(`[${t}-result`,a)}}}};function Xc(){const r=new Date;return`${r.toTimeString().split(" ")[0]}:${r.getMilliseconds().toString().padStart(3,"0")}`}function In(r,e){const t=document.createElement(r);return e.id&&(t.id=e.id),e.classList&&e.classList.forEach(n=>{t.classList.add(n)}),e.style&&Object.assign(t.style,e.style),e.attributes&&Object.entries(e.attributes).forEach(([n,i])=>{n==="muted"&&(t instanceof HTMLVideoElement||t instanceof HTMLAudioElement)?t.muted=!0:t.setAttribute(n,i)}),t}function ys({width:r,height:e}){const t=document.createElement("canvas"),n=t.getContext("2d");if(!n)throw new $(K.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:n,canvas:t}}class zn{constructor(e){O(this,"target");O(this,"_eventDict",new Map);this.target=e}on(e,t){let n=this._eventDict.get(e);n||(n=[t]),this._eventDict.set(e,n),this.target.addEventListener(e,t)}off(e,t){let n=this._eventDict.get(e);n&&(n=n.filter(i=>i!==t),this._eventDict.set(e,n),this.target.removeEventListener(e,t))}once(e,t){const n=i=>{t(i),this.off(e,n)};this.on(e,n)}clear(e){const t=this._eventDict.get(e);t&&t.forEach(n=>{this.target.removeEventListener(e,n)})}clearAll(){for(const e of this._eventDict.keys())this.clear(e)}}const oe=()=>typeof window>"u";function ie(){return navigator.userAgent.toLowerCase()}function On(r=ie()){let e="none";return oe()||(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 Ss=On()==="firefox",Fr=On()==="safari";On(),!oe()&&/crios/i.test(ie()),!oe()&&/edg\//i.test(ie()),!oe()&&/edgA/i.test(ie()),!oe()&&/edgios/i.test(ie()),!oe()&&/dingtalk/i.test(ie()),!oe()&&/opr\//.test(ie()),!oe()&&/(iphone|ipod)/i.exec(ie()),!oe()&&(/(ipad)/i.exec(ie())||/macintosh/i.test(ie())&&"ontouchend"in document),!oe()&&/macintosh/i.test(ie()),!oe()&&/micromessenger/i.test(ie()),!oe()&&ie().includes("mobile"),!oe()&&/sm-\w+/i.test(ie());const Zc=!oe()&&!!/(iphone|ipad|ipod)/i.exec(ie());!oe()&&/android/i.test(ie()),!oe()&&/windows/i.test(ie()),!oe()&&/openharmony/i.test(ie());let bs="0";const Yc=!oe()&&((Pc=ie().match(/version\/(\d+)/i))==null?void 0:Pc[1]);Fr&&Yc&&(bs=(Mc=navigator.userAgent.match(/version\/(\d+\.\d+)/i))==null?void 0:Mc[1]),!oe()&&((Lc=ie().match(/firefox\/(\d+)/i))==null||Lc[1]);const Pn=bs;!oe()&&((Uc=(Nc=ie().match(/ ([\d_]+) like mac os x/i))==null?void 0:Nc[1])==null||Uc.split("_").map(r=>parseInt(r))),!oe()&&((Gc=ie().match(/chrome\/(\d+)/i))==null||Gc[1]);function Qc(){var r;return!!((r=navigator==null?void 0:navigator.permissions)!=null&&r.query)}function Mn(){return!!(navigator!=null&&navigator.mediaDevices)}function eu(){var r;return Mn()&&!!((r=navigator==null?void 0:navigator.mediaDevices)!=null&&r.getUserMedia)}function tu(){return!!Promise.withResolvers}function ru(){return!(Fr&&Pn==="16.1")}function nu(){return!(Fr&&Pn&&["16.1","16.2","16.3"].includes(Pn))}function iu(){return!Ss}function su(){return typeof CanvasCaptureMediaStreamTrack<"u"}function ou(r){return typeof r.requestFrame=="function"}function au(){return!!Mn()&&typeof navigator.mediaDevices.ondevicechange<"u"&&typeof navigator.mediaDevices.addEventListener=="function"}const Ke={permissionQuery:Qc,mediaDevices:Mn,settingResolutionInGetDisplayMedia:ru,promiseWithResolvers:tu,getUserMedia:eu,isolateEnumerateDevices:iu,supportIdealParamsInGetDisplayMedia:nu,canvasCaptureMediaStreamTrack:su,requestFrameOnMediaStream:ou,ondevicechange:au};function cu(){if(Ke.promiseWithResolvers())return Promise.withResolvers();let r,e;const t=new Promise((n,i)=>{r=n,e=i});if(!r||!e)throw Error("resolver and rejector working unexpected");return{promise:t,resolve:r,reject:e}}function Es(r={}){const{timeout:e,message:t}={timeout:0,message:new $(K.UNEXPECTED_ERROR,"unexpected timeout"),...r},{promise:n,resolve:i,reject:s}=cu();if(e<=0)return{promise:n,resolve:i,reject:s};const a=setTimeout(()=>{s(t)},e);return{promise:n,resolve:d=>{clearTimeout(a),i(d)},reject:s}}const uu={playsinline:"","webkit-playsinline":"","x5-playsinline":"","x5-video-player-type":"h5","x-webkit-airplay":"allow",preload:"metadata",muted:"",crossOrigin:"anonymous"},du={playsinline:"","webkit-playsinline":"",preload:"metadata",muted:"",crossOrigin:"anonymous"};class Qt{constructor(e,t=[]){O(this,"id",bt());O(this,"_referenceTracks",[]);O(this,"_element");O(this,"_volumeMode",0);O(this,"_readyLock");O(this,"_releaseReadyLock");O(this,"_throwReadyLock");O(this,"_stream");let n;if(e instanceof MediaStreamTrack){const o=new MediaStream([e]);n=lu(o),this._stream=o}else if(e.url)n=hu(e);else throw new $(K.UNEXPECTED_TYPE,`got ${typeof e}, expected: MediaStreamTrack or constraints for creating element`);const{promise:i,resolve:s,reject:a}=Es({timeout:2e3,message:new $(K.PLAY_FAILED,"load media timeout")});this._readyLock=i,this._releaseReadyLock=s,this._throwReadyLock=a,this._element=new zn(n),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===te.AUDIO){this._upgradeVolumeMode(1e-4);const n=t.getAudioTracks();if(n.length<1)throw new $(K.UNEXPECTED_TYPE,"got empty list of audio tracks");return n[0]}if(e===te.VIDEO){const n=t.getVideoTracks();if(n.length<1)throw new $(K.UNEXPECTED_TYPE,"got empty list of video tracks");return n[0]}throw new $(K.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 $(K.PLAY_FAILED,"play element failed",e)}}_bindPlayerEvent(e){e.on("loadedmetadata",()=>{this._releaseReadyLock()}),e.on("error",()=>{this._throwReadyLock(new $(K.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 lu(r){let e="audio";r.getVideoTracks().length>0&&(e="video");const t=Cs(e==="video"?te.VIDEO:te.AUDIO);return t.srcObject=r,t}function hu(r){const{url:e,kind:t,loop:n}=r,i=Cs(t);return i.src=e,i.loop=n,i}function Cs(r){if(r===te.VIDEO)return In(te.VIDEO,{style:{width:"100%",height:"100%"},attributes:uu});if(r===te.AUDIO)return In(te.AUDIO,{style:{display:"none"},attributes:du});throw new $(K.UNEXPECTED_TYPE,`got ${r}, expected: audio, video`)}class Ln extends it{emit(e,...t){const n=this.listenerCount(e);return Promise.resolve().then(()=>{super.emit(e,...t)}),!!n}on(e,t,n){const i=(...s)=>{try{return t(...s)}catch(a){console.error(`[SafeEventEmitter] event listener threw an error when handling [${e}] event: `,a)}};return super.on(e,i,n)}once(e,t,n){const i=(...s)=>{try{return t(...s)}catch(a){console.error(`[SafeEventEmitter] event listener threw an error when handling [${e}] event: `,a)}};return super.once(e,i,n)}}function Nn(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 $(K.UNEXPECTED_TYPE,"unexpected constraints type")}const Vr=1e3;class ws{constructor(e){O(this,"id",bt());O(this,"_context");O(this,"_canvas");O(this,"_image");O(this,"_config");O(this,"_readyLock");O(this,"_releaseReadyLock");O(this,"_throwReadyLock");O(this,"_loopTimer");O(this,"_referenceTracks",[]);O(this,"_stream");const t=Nn(e.width),n=Nn(e.height),i=Nn(e.frameRate);this._config={width:t,height:n,frameRate:i};const{context:s,canvas:a}=ys({width:t,height:n});this._context=s,this._canvas=a;const o=pu({url:e.url,width:t,height:n});this._image=new zn(o);const{promise:d,resolve:c,reject:u}=Es({timeout:2e3,message:new $(K.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 n=t.getVideoTracks();if(n.length<1)throw new $(K.UNEXPECTED_TYPE,"got empty list of video tracks");return n[0]}element(){return this._image.target}isReady(){return this._readyLock}_bindImageEvent(e){e.on("load",()=>{this._releaseReadyLock()}),e.on("error",()=>{this._throwReadyLock(new $(K.PLAY_FAILED,"HTMLMediaElement got error when loading file"))})}async _paint(){const{width:e,height:t,frameRate:n}=this._config;this._context.drawImage(this._image.target,0,0,e,t),this._loopTimer&&clearTimeout(this._loopTimer),this._loopTimer=setTimeout(this._paint.bind(this),Vr/n)}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 pu({url:r,height:e,width:t}){const n=In("img",{style:{width:`${t}px`,height:`${e}px`},attributes:{crossOrigin:"anonymous"}});return n.src=r,n}class Un extends Ln{constructor(t){super();O(this,"id",bt());O(this,"_track");O(this,"_element");t instanceof MediaStreamTrack?(this._track=new zn(t),this._bindTrackEvent(this._track)):t instanceof Qt?(this._element=t,t.addReferenceTrack(this)):t instanceof ws&&(this._element=t)}_bindTrackEvent(t){t.on("ended",this._handleTrackEnded.bind(this)),t.on("mute",()=>{this.emit(me.MUTE)}),t.on("unmute",()=>{this.emit(me.UNMUTE)})}_handleTrackEnded(){this.emit(me.ENDED),this.destroy()}handlePlayFailed(){this.emit(me.PLAY_FAILED)}track(){if(this.logger.info("track"),!this.available())throw new $(K.TRACK_NOT_AVAILABLE,"track is not available when creating MediaStreamTrack");if(this._track)return this._track.target;if(!this._element)throw new $(K.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 $(K.TRACK_NOT_AVAILABLE,"track is not available when creating HTMLMediaElement");if(this._element)return this._element.element();if(!this._track)throw new $(K.UNEXPECTED_TYPE,"got this._track falsy");const t=new Qt(this._track.target,[this]);this._element=t;const n=t.element();return this.logger.success("element",n),n}available(){return!!(this._track||this._element)}destroy(){var t,n,i;(t=this._track)==null||t.clearAll(),(n=this._track)==null||n.target.stop(),this._track&&delete this._track,(i=this._element)==null||i.removeReference(this),delete this._element}}class jr extends Un{constructor(){super(...arguments);O(this,"kind",te.AUDIO);O(this,"_node")}node(){if(this.logger.info("node",this.id),!this.available())throw new $(K.TRACK_NOT_AVAILABLE,"track is not avaiable when creating node");if(this._node)return this._node;const t=new Kc(this);return this._node=t,t}element(){if(this.logger.info("element",this.id),!this.available())throw new $(K.TRACK_NOT_AVAILABLE,"track is not available when creating HTMLMediaElement");if(this._element){const n=this._element.element(!0);if(!(n instanceof HTMLMediaElement))throw new $(K.UNEXPECTED_TYPE,"source should be HTMLMediaElement");return n}if(!this._track)throw new $(K.UNEXPECTED_TYPE,"got this._track falsy");const t=new Qt(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 fu extends jr{constructor(){super(...arguments);O(this,"logger",new ye("MicrophoneAudioTrack"))}}class mu extends jr{constructor(){super(...arguments);O(this,"logger",new ye("ScreenAudioTrack"))}}class Ts extends jr{constructor(){super(...arguments);O(this,"logger",new ye("MediaAudioTrack"))}handlePlayFailed(){this.emit(me.PLAY_FAILED)}async play(){if(this._element){if(!(this._element instanceof Qt))throw new $(K.UNEXPECTED_TYPE,"element is not TrackMediaElement");return this._element._playElement()}}}class _u extends jr{constructor(){super(...arguments);O(this,"logger",new ye("CustomAudioTrack"))}}let gu=1;const Gn=new ye("PromiseQueue");class vu{constructor(e){O(this,"lockingPromise",Promise.resolve());O(this,"locks",0);O(this,"name","");O(this,"lockId");O(this,"closeReason");this.lockId=gu++,e&&(this.name=e),Gn.info(`lock-${this.name}-${this.lockId}`,"is created.")}get isLocked(){return this.locks>0}lock(){this.locks+=1,Gn.info(`lock-${this.name}-${this.lockId}`,`locked, current queue ${this.locks}.`);let e;const t=new Promise(i=>{e=()=>{this.locks-=1,Gn.info(`lock-${this.name}-${this.lockId}`,`unlocked, current queue ${this.locks}.`),i()}}),n=this.lockingPromise.then(()=>e);return this.lockingPromise=this.lockingPromise.then(()=>t),n}}const yu=300,Su=3e3,Be=new ye("Devices");class bu extends Ln{constructor(){super();O(this,"_deviceMap",{audioinput:[],audiooutput:[],videoinput:[]});O(this,"_permissions",{[te.AUDIO]:!1,[te.VIDEO]:!1});O(this,"_changedQueue",new vu("device changed queue"));this._init()}async _init(){this._initDeviceChanged(),await this._initPermissionChanged();const t=Ds(this._permissions);t.length>0&&this._refreshDevices(t)}_initDeviceChanged(){if(Be.info("_initDeviceChanged","invoked"),!Ke.ondevicechange()){Be.error("_initDeviceChanged","no supported, use timer instead"),setInterval(()=>{this._handleDeviceChanged()},Su);return}Ke.ondevicechange()&&navigator.mediaDevices.addEventListener("devicechange",()=>{Be.info("devicechange"),setTimeout(()=>{this._handleDeviceChanged()},yu)})}async _initPermissionChanged(){if(!Ke.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(!Ke.mediaDevices())throw new $(K.NOT_SUPPORTED,"mediaDevices is not supported");if(t.length===0)throw new $(K.UNEXPECTED_TYPE,"kinds expect to containt values");let n;if(!Ke.isolateEnumerateDevices()){const a={};t.forEach(o=>{a[o]=!0}),n=await navigator.mediaDevices.getUserMedia(a)}let i=await navigator.mediaDevices.enumerateDevices();n&&ks(n),i=i.filter(({deviceId:a})=>!!a);const s={audioinput:[],audiooutput:[],videoinput:[]};i.forEach(a=>{const{kind:o}=a;s[o].push(a)}),this._deviceMap=s}async _acquireUserPermission(t){let n=!1;if(t.forEach(i=>{n=n||!this._permissions[i]}),!n)return{grant:!0};if(!Ke.getUserMedia())return{grant:!1,reason:new $(K.NOT_SUPPORTED,"getUserMedia is not supported")};try{const i={};t.forEach(a=>{i[a]=!0});const s=await navigator.mediaDevices.getUserMedia(i);return s?(i.audio&&(this._permissions[te.AUDIO]=!0),i.video&&(this._permissions[te.VIDEO]=!0),ks(s),{grant:!0}):{grant:!1,reason:new $(K.UNEXPECTED_TYPE,"get stream falsy")}}catch(i){return{grant:!1,reason:new $(K.CAPTURE_FAILED,"acquire user permission failed",i)}}}async _handleDeviceChanged(){Be.info("_handleDeviceChanged",this._deviceMap,this._permissions);const t=await this._changedQueue.lock();try{const n=As(this._deviceMap);let i=[];const s=Ds(this._permissions);s.length===0?Be.warn("_handleDeviceChanged","no permission, use empty list"):(await this._refreshDevices(s),i=As(this._deviceMap)),i.forEach(a=>{n.findIndex(d=>Rs(d,a))!==-1||this.emit("onDeviceStateChanged",{deviceInfo:a,deviceState:"active"})}),n.forEach(a=>{i.findIndex(d=>Rs(d,a))!==-1||this.emit("onDeviceStateChanged",{deviceInfo:a,deviceState:"inactive"})})}finally{t()}}async enumerateDevices(t){const n=[];t.forEach(o=>{if(o==="audioinput"||o==="audiooutput")n.push(te.AUDIO);else if(o==="videoinput")n.push(te.VIDEO);else throw new $(K.UNEXPECTED_TYPE,"kind in kinds should be enum MediaDeviceKind")});const{grant:i,reason:s}=await this._acquireUserPermission(n);if(!i)throw s;await this._refreshDevices(n);const a=[];return t.forEach(o=>{a.push(...this._deviceMap[o])}),a}async enableDevices(t){return this._acquireUserPermission(t)}}function ks(r){r.getTracks().forEach(e=>e.stop())}function Rs(r,e){return r.deviceId===e.deviceId}function As(r){return Array.from([...r.audioinput.values(),...r.videoinput.values(),...r.audiooutput.values()])}function Ds(r){const e=[];return r.audio&&e.push(te.AUDIO),r.video&&e.push(te.VIDEO),e}const Bn=new bu,Fn={LeftToRight:"LeftToRight",UpToDown:"UpToDown",All:"All"};class Vn{constructor(){O(this,"id",bt())}position(e,t){return new Eu(this,{x:e,y:t})}scale(e){return new xs(this,{s:e})}mirror(e){return new xs(this,{mirrorType:e})}available(){var e;return((e=this.previousNode)==null?void 0:e.available())??!1}}class Eu extends Vn{constructor(t,n){super();O(this,"previousNode");O(this,"_x");O(this,"_y");this.previousNode=t,this._x=n.x,this._y=n.y}paint(t){t.translate(this._x,this._y)}}class xs extends Vn{constructor(t,n){super();O(this,"previousNode");O(this,"_scaleParams",[1,1]);if(this.previousNode=t,n.mirrorType)switch(n.mirrorType){case Fn.LeftToRight:this._scaleParams=[-1,1];break;case Fn.UpToDown:this._scaleParams=[1,-1];break;case Fn.All:this._scaleParams=[-1,-1];break;default:this._scaleParams=[1,1];break}else n.s&&(this._scaleParams=[n.s,n.s])}paint(t){t.scale(this._scaleParams[0],this._scaleParams[1])}}class Cu extends Vn{constructor(t){super();O(this,"previousNode",null);O(this,"_source");this._source=t}available(){return this._source.available()}}class Hr extends Cu{constructor(t,n){super(t);O(this,"_targetWidth");O(this,"_targetHeight");const{width:i,height:s}=n??{};this._targetWidth=i??this._source.width(),this._targetHeight=s??this._source.height()}size(t,n){return new Hr(this._source,{width:t,height:n})}paint(t){const n=this._targetWidth,i=this._targetHeight;t.drawImage(this._source.element(),-n/2,-i/2,n,i)}}class wu extends Un{constructor(){super(...arguments);O(this,"logger",new ye("PictureTrack"));O(this,"kind",te.VIDEO)}element(){const t=super.element();if(!(t instanceof HTMLImageElement))throw new $(K.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 $(K.TRACK_NOT_AVAILABLE,"track is not avaiable when creating node");const t=new Hr(this);return this.logger.info("node",t),t}destroy(){this.logger.warn("destroy"),super.destroy()}}const Tu=500;class qr extends Un{constructor(){super(...arguments);O(this,"kind",te.VIDEO);O(this,"sizeChangeTimer");O(this,"watchSizeChangeOnce",()=>{const t=this.width(),n=this.height();this.sizeChangeTimer=setTimeout(()=>{const i=this.width(),s=this.height();(n!==s||t!==i)&&this.emit(me.SIZE_CHANGE,{width:i,height:s})},Tu)})}element(){const t=super.element();if(!(t instanceof HTMLVideoElement))throw new $(K.UNEXPECTED_TYPE,"source should be HTMLVideoElement");return t}node(){if(!this.available())throw new $(K.TRACK_NOT_AVAILABLE,"track is not avaiable when creating node");return new Hr(this)}destroy(){clearTimeout(this.sizeChangeTimer),super.destroy()}}class ku extends qr{constructor(t){super(t);O(this,"logger",new ye("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 qr{constructor(t){super(t);O(this,"logger",new ye("ScreenVideoTrack"));this.watchSizeChangeOnce()}height(){const{height:t}=this.track().getSettings();return t??0}width(){const{width:t}=this.track().getSettings();return t??0}}class Au extends qr{constructor(){super(...arguments);O(this,"logger",new ye("MediaVideoTrack"))}height(){const{videoHeight:t}=this.element();return t??0}width(){const{videoWidth:t}=this.element();return t??0}}class Du extends qr{constructor(){super(...arguments);O(this,"logger",new ye("CustomVideoTrack"))}height(){const{height:t}=this.track().getSettings();return t??0}width(){const{width:t}=this.track().getSettings();return t??0}}async function Is(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(n){console.warn("[VePusher Error]: frameRate limit failed",n)}}const We=new ye("Capture");async function xu(r){return Bn.enumerateDevices(r)}async function Iu(r){Bn.removeAllListeners("onDeviceStateChanged"),Bn.on("onDeviceStateChanged",r)}async function zu(r,e){let t;try{const i={video:r??!0};typeof i.video=="object"&&i.video.facingMode&&delete i.video.deviceId,t=await navigator.mediaDevices.getUserMedia(i)}catch(i){throw new $(K.CAPTURE_FAILED,"got error when capturing camera",i)}const n=t.getVideoTracks()[0];if(r!=null&&r.frameRate&&e&&Is(n,r),!n)throw new $(K.UNEXPECTED_TYPE,"got falsy in track");return new ku(n)}async function Ou(r,e,t){const{video:n,audio:i}=r;let s=n===!0?{}:n;e!=null&&e.displaySurface&&(s.displaySurface=e.displaySurface,delete e.displaySurface),Ke.settingResolutionInGetDisplayMedia()||(s=!0),!Ke.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:i,...e})}catch(u){throw new $(K.CAPTURE_FAILED,"got error when capture screen",u)}const o=a.getVideoTracks()[0],d=a.getAudioTracks()[0];if(!o)throw new $(K.UNEXPECTED_TYPE,"got falsy in videoTrack");typeof s!="boolean"&&typeof s.frameRate=="number"&&t&&Is(o,s);const c=[];return c.push(new Ru(o)),d&&c.push(new mu(d)),c}async function Pu(r){const{url:e,audio:t,video:n,loop:i}=r,s=new Qt({url:e,kind:n?te.VIDEO:te.AUDIO,loop:i}),a=[];return t&&a.push(new Ts(s)),n&&a.push(new Au(s)),await s.isReady(),a}async function Mu(r){const e=new ws(r);return await e.isReady(),new wu(e)}async function Lu(r){let e;try{const n={audio:r??!0};e=await navigator.mediaDevices.getUserMedia(n)}catch(n){throw new $(K.CAPTURE_FAILED,"got error when capturing microphone",n)}const t=e.getAudioTracks()[0];if(!t)throw new $(K.UNEXPECTED_TYPE,"got falsy in track");return new fu(t)}function Nu(r){if(!r||r.kind!=="video")throw new $(K.UNEXPECTED_TYPE,"error custom video track type");return new Du(r)}function Uu(r){if(!r||r.kind!=="audio")throw new $(K.UNEXPECTED_TYPE,"error custom audio track type");return new _u(r)}const Gu=We.invoke(xu,"enumerateInputDevices"),Bu=We.invoke(zu,"createCameraTrack"),Fu=We.invoke(Mu,"createPictureTrack"),zs=We.invoke(Pu,"createMediaTracks"),Vu=We.invoke(Lu,"createMicrophoneTrack"),ju=We.invoke(Ou,"createScreenTracks"),Hu=We.invoke(Iu,"onDeviceChanged"),qu=We.invoke(Nu,"createCustomVideoTrack"),$u=We.invoke(Uu,"createCustomAudioTrack");var jn=(r=>(r.PAUSING="pausing",r))(jn||{});const Ku={sampleRate:48e3,keepAlive:!0},Os=new Map,er=new ye("Mixer");class Wu extends Ln{constructor(t){super();O(this,"id",bt());O(this,"_context");O(this,"_config");O(this,"_nodeList",[]);O(this,"_destNode");O(this,"_bufferNode");O(this,"_track");O(this,"unlockAudioContext",()=>{if(this._context.state!=="suspended")return;const t=document.body,n=["touchstart","touchend","mousedown","keydown"],i=()=>{n.forEach(a=>{t.removeEventListener(a,s)})},s=()=>{tr(this._context).then(i)};n.forEach(a=>{t.addEventListener(a,s,!1)})});er.info("ctor",t),this._config={...Ku,...t},this._context=Ju(this._config),this._bindContextEvent(this._context)}mix(t){er.info("mix",t),tr(this._context);for(const n of this._nodeList)t.includes(n)||n.destroy();this._nodeList=t,this._connect(t,this._destNode),this._nodeList.length===0&&this._appendSlience(this._context,this._destNode)}resume(){return er.info("resume"),tr(this._context)}_connect(t,n){for(const i of t)i.connect(this._context,n)}_appendSlience(t,n){if(!n||this._bufferNode)return;const{sampleRate:i}=t,s=new AudioBuffer({length:100,sampleRate:i}),a=new AudioBufferSourceNode(t,{buffer:s,loop:!0});a.connect(n),this._bufferNode=a}_bindContextEvent(t){t.addEventListener("statechange",this._handleContextStateChange.bind(this))}_handleContextStateChange(){const t=this._context;(t.state==="suspended"||t.state==="interrupted")&&(er.info("_emit_",jn.PAUSING),this.emit(jn.PAUSING))}track(){if(er.info("track"),tr(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 n=t.stream.getAudioTracks()[0];return this._destNode=t,this._track=n,n}}function Ju(r){const{sampleRate:e,keepAlive:t}=r;let n=Os.get(e);return(!n||n.state==="closed")&&(n=new AudioContext({sampleRate:e}),Os.set(e,n)),t&&(n.onstatechange=()=>{tr(n)}),n}function tr(r){return r.state==="suspended"||r.state==="interrupted"?r.resume():Promise.resolve()}const Xu=r=>(e,t)=>(r.set(e,t),t),Ps=Number.MAX_SAFE_INTEGER===void 0?9007199254740991:Number.MAX_SAFE_INTEGER,Ms=536870912,Ls=Ms*2,Zu=(r,e)=>t=>{const n=e.get(t);let i=n===void 0?t.size:n<Ls?n+1:0;if(!t.has(i))return r(t,i);if(t.size<Ms){for(;t.has(i);)i=Math.floor(Math.random()*Ls);return r(t,i)}if(t.size>Ps)throw new Error("Congratulations, you created a collection of unique numbers which uses all available integers!");for(;t.has(i);)i=Math.floor(Math.random()*Ps);return r(t,i)},Ns=new WeakMap,Yu=Xu(Ns),st=Zu(Yu,Ns),Qu=r=>r.method!==void 0&&r.method==="call",ed=r=>typeof r.id=="number"&&typeof r.result=="boolean",Us=((r,e)=>{let t=null;return()=>{if(t!==null)return t;const n=new Blob([e],{type:"application/javascript; charset=utf-8"}),i=URL.createObjectURL(n);return t=r(i),setTimeout(()=>URL.revokeObjectURL(i)),t}})(r=>{const e=new Map([[0,()=>{}]]),t=new Map([[0,()=>{}]]),n=new Map,i=new Worker(r);return i.addEventListener("message",({data:c})=>{if(Qu(c)){const{params:{timerId:u,timerType:h}}=c;if(h==="interval"){const l=e.get(u);if(typeof l===void 0)throw new Error("The timer is in an undefined state.");if(typeof l=="number"){const f=n.get(l);if(f===void 0||f.timerId!==u||f.timerType!==h)throw new Error("The timer is in an undefined state.")}else typeof l=="function"&&l()}else if(h==="timeout"){const l=t.get(u);if(typeof l===void 0)throw new Error("The timer is in an undefined state.");if(typeof l=="number"){const f=n.get(l);if(f===void 0||f.timerId!==u||f.timerType!==h)throw new Error("The timer is in an undefined state.")}else typeof l=="function"&&(l(),t.delete(u))}}else if(ed(c)){const{id:u}=c,h=n.get(u);if(h===void 0)throw new Error("The timer is in an undefined state.");const{timerId:l,timerType:f}=h;n.delete(u),f==="interval"?e.delete(l):t.delete(l)}else{const{error:{message:u}}=c;throw new Error(u)}}),{clearInterval:c=>{if(typeof e.get(c)=="function"){const u=st(n);n.set(u,{timerId:c,timerType:"interval"}),e.set(c,u),i.postMessage({id:u,method:"clear",params:{timerId:c,timerType:"interval"}})}},clearTimeout:c=>{if(typeof t.get(c)=="function"){const u=st(n);n.set(u,{timerId:c,timerType:"timeout"}),t.set(c,u),i.postMessage({id:u,method:"clear",params:{timerId:c,timerType:"timeout"}})}},setInterval:(c,u=0,...h)=>{const l=st(e);return e.set(l,()=>{c(...h),typeof e.get(l)=="function"&&i.postMessage({id:null,method:"set",params:{delay:u,now:performance.timeOrigin+performance.now(),timerId:l,timerType:"interval"}})}),i.postMessage({id:null,method:"set",params:{delay:u,now:performance.timeOrigin+performance.now(),timerId:l,timerType:"interval"}}),l},setTimeout:(c,u=0,...h)=>{const l=st(t);return t.set(l,()=>c(...h)),i.postMessage({id:null,method:"set",params:{delay:u,now:performance.timeOrigin+performance.now(),timerId:l,timerType:"timeout"}}),l}}},`(()=>{"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})}}))})();`),td=r=>Us().clearTimeout(r),rd=(...r)=>Us().setTimeout(...r),nd=r=>r.method!==void 0&&r.method==="call",id=r=>typeof r.id=="number"&&typeof r.result=="boolean",sd=r=>{const e=new Map([[0,()=>{}]]),t=new Map([[0,()=>{}]]),n=new Map,i=new Worker(r,{credentials:"omit"});return i.addEventListener("message",({data:c})=>{if(nd(c)){const{params:{timerId:u,timerType:h}}=c;if(h==="interval"){const l=e.get(u);if(typeof l===void 0)throw new Error("The timer is in an undefined state.");if(typeof l=="number"){const f=n.get(l);if(f===void 0||f.timerId!==u||f.timerType!==h)throw new Error("The timer is in an undefined state.")}else typeof l=="function"&&l()}else if(h==="timeout"){const l=t.get(u);if(typeof l===void 0)throw new Error("The timer is in an undefined state.");if(typeof l=="number"){const f=n.get(l);if(f===void 0||f.timerId!==u||f.timerType!==h)throw new Error("The timer is in an undefined state.")}else typeof l=="function"&&(l(),t.delete(u))}}else if(id(c)){const{id:u}=c,h=n.get(u);if(h===void 0)throw new Error("The timer is in an undefined state.");const{timerId:l,timerType:f}=h;n.delete(u),f==="interval"?e.delete(l):t.delete(l)}else{const{error:{message:u}}=c;throw new Error(u)}}),{clearInterval:c=>{if(typeof e.get(c)=="function"){const u=st(n);n.set(u,{timerId:c,timerType:"interval"}),e.set(c,u),i.postMessage({id:u,method:"clear",params:{timerId:c,timerType:"interval"}})}},clearTimeout:c=>{if(typeof t.get(c)=="function"){const u=st(n);n.set(u,{timerId:c,timerType:"timeout"}),t.set(c,u),i.postMessage({id:u,method:"clear",params:{timerId:c,timerType:"timeout"}})}},setInterval:(c,u=0,...h)=>{const l=st(e);return e.set(l,()=>{c(...h),typeof e.get(l)=="function"&&i.postMessage({id:null,method:"set",params:{delay:u,now:performance.timeOrigin+performance.now(),timerId:l,timerType:"interval"}})}),i.postMessage({id:null,method:"set",params:{delay:u,now:performance.timeOrigin+performance.now(),timerId:l,timerType:"interval"}}),l},setTimeout:(c,u=0,...h)=>{const l=st(t);return t.set(l,()=>c(...h)),i.postMessage({id:null,method:"set",params:{delay:u,now:performance.timeOrigin+performance.now(),timerId:l,timerType:"timeout"}}),l}}},od={width:640,height:480,frameRate:30,backgroundColor:"#000000"},$r=new ye("View");class ad{constructor(e){O(this,"id",bt());O(this,"_context");O(this,"_canvas");O(this,"_config");O(this,"_nodeList",[]);O(this,"_track");O(this,"_stopped",!0);O(this,"_nextTime",Date.now());O(this,"_workerTimeoutId");O(this,"_raqId");O(this,"_workerTimerScriptUrl");O(this,"_customSetTimeout");O(this,"_customClearTimeout");O(this,"_drawCount",0);O(this,"_lastSecondDrawCount",0);O(this,"_lastCountResetTime",Date.now());O(this,"_loopTimer");O(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)},Vr/this._config.frameRate),this._raqId=requestAnimationFrame(this._paintLoop)});$r.info("ctor",e),this._config={...od,...e};const{context:t,canvas:n}=ys(this._config);this._context=t,this._canvas=n,this._customSetTimeout=rd,this._customClearTimeout=td}setWorkerTimerScriptUrl(e){if(this._workerTimerScriptUrl=e,this._workerTimerScriptUrl){const t=sd(this._workerTimerScriptUrl);this._customSetTimeout=(...n)=>t.setTimeout(...n),this._customClearTimeout=n=>t.clearTimeout(n)}}_shouldDraw(e){if(e<this._nextTime)return!1;for(;e>this._nextTime;)this._nextTime+=Vr/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=[]){$r.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>=Vr&&(this._lastSecondDrawCount=this._drawCount,this._drawCount=0,this._lastCountResetTime=e)}getDrawCountPerSecond(){return this._updateDrawCountPerSecond(),this._lastSecondDrawCount}_drawBackground(){const{backgroundColor:e,width:t,height:n}=this._config;this._context.clearRect(0,0,t,n),e&&(this._context.fillStyle=e,this._context.fillRect(0,0,t,n))}track(){if($r.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,n=this._canvas.captureStream(t);return this._track=n.getVideoTracks()[0],e.stop(),this._track}else return this.track()}element(){return $r.info("element"),this._paintLoop(),this._canvas}stop(){this._stopped=!0}}function cd(){return Math.random().toString(36).slice(-8)}const ud=`
|
|
1
|
+
(function(Ne,_e){typeof exports=="object"&&typeof module<"u"?module.exports=_e():typeof define=="function"&&define.amd?define(_e):(Ne=typeof globalThis<"u"?globalThis:Ne||self,Ne.vePusher=_e())})(this,function(){"use strict";var Eg=Object.defineProperty;var Cg=(Ne,_e,it)=>_e in Ne?Eg(Ne,_e,{enumerable:!0,configurable:!0,writable:!0,value:it}):Ne[_e]=it;var P=(Ne,_e,it)=>Cg(Ne,typeof _e!="symbol"?_e+"":_e,it);var Uc,Gc,Bc,Fc,Vc,jc;function Ne(r,e){for(var t=0;t<e.length;t++){const n=e[t];if(typeof n!="string"&&!Array.isArray(n)){for(const i in n)if(i!=="default"&&!(i in r)){const s=Object.getOwnPropertyDescriptor(n,i);s&&Object.defineProperty(r,i,s.get?s:{enumerable:!0,get:()=>n[i]})}}}return Object.freeze(Object.defineProperty(r,Symbol.toStringTag,{value:"Module"}))}function _e(r){return r&&r.__esModule&&Object.prototype.hasOwnProperty.call(r,"default")?r.default:r}var it={exports:{}},as;function qc(){return as||(as=1,function(r){var e=Object.prototype.hasOwnProperty,t="~";function n(){}Object.create&&(n.prototype=Object.create(null),new n().__proto__||(t=!1));function i(d,c,u){this.fn=d,this.context=c,this.once=u||!1}function s(d,c,u,h,l){if(typeof u!="function")throw new TypeError("The listener must be a function");var f=new i(u,h||d,l),y=t?t+c:c;return d._events[y]?d._events[y].fn?d._events[y]=[d._events[y],f]:d._events[y].push(f):(d._events[y]=f,d._eventsCount++),d}function a(d,c){--d._eventsCount===0?d._events=new n:delete d._events[c]}function o(){this._events=new n,this._eventsCount=0}o.prototype.eventNames=function(){var c=[],u,h;if(this._eventsCount===0)return c;for(h in u=this._events)e.call(u,h)&&c.push(t?h.slice(1):h);return Object.getOwnPropertySymbols?c.concat(Object.getOwnPropertySymbols(u)):c},o.prototype.listeners=function(c){var u=t?t+c:c,h=this._events[u];if(!h)return[];if(h.fn)return[h.fn];for(var l=0,f=h.length,y=new Array(f);l<f;l++)y[l]=h[l].fn;return y},o.prototype.listenerCount=function(c){var u=t?t+c:c,h=this._events[u];return h?h.fn?1:h.length:0},o.prototype.emit=function(c,u,h,l,f,y){var C=t?t+c:c;if(!this._events[C])return!1;var v=this._events[C],E=arguments.length,k,g;if(v.fn){switch(v.once&&this.removeListener(c,v.fn,void 0,!0),E){case 1:return v.fn.call(v.context),!0;case 2:return v.fn.call(v.context,u),!0;case 3:return v.fn.call(v.context,u,h),!0;case 4:return v.fn.call(v.context,u,h,l),!0;case 5:return v.fn.call(v.context,u,h,l,f),!0;case 6:return v.fn.call(v.context,u,h,l,f,y),!0}for(g=1,k=new Array(E-1);g<E;g++)k[g-1]=arguments[g];v.fn.apply(v.context,k)}else{var D=v.length,L;for(g=0;g<D;g++)switch(v[g].once&&this.removeListener(c,v[g].fn,void 0,!0),E){case 1:v[g].fn.call(v[g].context);break;case 2:v[g].fn.call(v[g].context,u);break;case 3:v[g].fn.call(v[g].context,u,h);break;case 4:v[g].fn.call(v[g].context,u,h,l);break;default:if(!k)for(L=1,k=new Array(E-1);L<E;L++)k[L-1]=arguments[L];v[g].fn.apply(v[g].context,k)}}return!0},o.prototype.on=function(c,u,h){return s(this,c,u,h,!1)},o.prototype.once=function(c,u,h){return s(this,c,u,h,!0)},o.prototype.removeListener=function(c,u,h,l){var f=t?t+c:c;if(!this._events[f])return this;if(!u)return a(this,f),this;var y=this._events[f];if(y.fn)y.fn===u&&(!l||y.once)&&(!h||y.context===h)&&a(this,f);else{for(var C=0,v=[],E=y.length;C<E;C++)(y[C].fn!==u||l&&!y[C].once||h&&y[C].context!==h)&&v.push(y[C]);v.length?this._events[f]=v.length===1?v[0]:v:a(this,f)}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 n,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}(it)),it.exports}var $c=qc();const st=_e($c);var cs=(r=>(r.LeftToRight="LeftToRight",r.UpToDown="UpToDown",r.All="All",r.None="None",r))(cs||{}),Q=(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))(Q||{}),Be=(r=>(r.DeviceCaptured="deviceCaptured",r.DeviceStopCapture="deviceStopCapture",r.Error="error",r.Interrupted="interrupted",r))(Be||{}),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))(se||{}),us=(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))(us||{}),ds=(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))(ds||{}),ls=(r=>(r.STANDARD="48000x40",r.HIGH="48000x128",r))(ls||{}),vt=(r=>(r.VideoStreamChange="videoStreamChange",r.AudioStreamChange="audioStreamChange",r))(vt||{}),hs=(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))(hs||{});const ps={SizeChange:"sizeChange"};var In=(r=>(r.Portrait="portrait",r.Landscape="landscape",r))(In||{});const fs="720p-1",ms="STANDARD";var xe=(r=>(r[r.DISCONNECTED=0]="DISCONNECTED",r[r.CONNECTING=1]="CONNECTING",r[r.CONNECTED=2]="CONNECTED",r[r.RECONNECTING=3]="RECONNECTING",r))(xe||{}),Mt=(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))(Mt||{}),zn=(r=>(r[r.PushUrlInvalid=1001]="PushUrlInvalid",r[r.ReconnectTimeout=1002]="ReconnectTimeout",r))(zn||{}),K=(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))(K||{}),te=(r=>(r.AUDIO="audio",r.VIDEO="video",r))(te||{}),ge=(r=>(r.ENDED="ended",r.MUTE="mute",r.UNMUTE="unmute",r.PLAY_FAILED="play-failed",r.SIZE_CHANGE="size-change",r))(ge||{});const pe=[];for(let r=0;r<256;++r)pe.push((r+256).toString(16).slice(1));function Kc(r,e=0){return(pe[r[e+0]]+pe[r[e+1]]+pe[r[e+2]]+pe[r[e+3]]+"-"+pe[r[e+4]]+pe[r[e+5]]+"-"+pe[r[e+6]]+pe[r[e+7]]+"-"+pe[r[e+8]]+pe[r[e+9]]+"-"+pe[r[e+10]]+pe[r[e+11]]+pe[r[e+12]]+pe[r[e+13]]+pe[r[e+14]]+pe[r[e+15]]).toLowerCase()}let Pn;const Wc=new Uint8Array(16);function Jc(){if(!Pn){if(typeof crypto>"u"||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");Pn=crypto.getRandomValues.bind(crypto)}return Pn(Wc)}const _s={randomUUID:typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};function yt(r,e,t){var i;if(_s.randomUUID&&!r)return _s.randomUUID();r=r||{};const n=r.random??((i=r.rng)==null?void 0:i.call(r))??Jc();if(n.length<16)throw new Error("Random bytes length must be >= 16");return n[6]=n[6]&15|64,n[8]=n[8]&63|128,Kc(n)}class gs{constructor(){P(this,"id",yt());P(this,"_nextNode");P(this,"_track");P(this,"_destNode")}gain(e){if(this._nextNode instanceof vs)return this._nextNode.g=e,this._nextNode;const t=new vs(this,{g:e});return this._nextNode=t,t}connect(e,t){if(!this.available())return;let{_node:n}=this;n||(n=this.createNode(e)),this._node=n,this.previousNode&&this.previousNode.connect(e,n),t&&n.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 vs extends gs{constructor(t,n){super();P(this,"previousNode");P(this,"_node");P(this,"_g");this.previousNode=t,this._g=n.g}createNode(t){return new GainNode(t,{gain:this._g})}set g(t){this._g=t,this._node&&(this._node.gain.value=t)}}class Xc extends gs{constructor(t){super();P(this,"previousNode",null);P(this,"source");this.source=t}available(){return this.source.available()}destroy(){super.destroy()}}class Zc extends Xc{constructor(){super(...arguments);P(this,"_node")}createNode(t){if(this._node)return this._node;let n;if(this.source instanceof Rs){const i=this.source.element();n=new MediaElementAudioSourceNode(t,{mediaElement:i}),i.muted=!1}else{const i=this.source.track();n=new MediaStreamAudioSourceNode(t,{mediaStream:new MediaStream([i])})}return n}}class $ extends Error{constructor(t,n,i){super(n);P(this,"code");P(this,"message");P(this,"error");this.code=t,this.message=n,this.error=i,Object.setPrototypeOf(this,$.prototype)}toString(){return`VeCapture Error: ${this.code} ${this.message}`}}const ys={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"}},Ss="__debug__",Yc="[VE-CAPTURE]";function Qc(){if(typeof location>"u"||typeof localStorage>"u")return!1;let r=!1;return location.href.includes(Ss)&&(r=!0),localStorage.getItem(Ss)&&(r=!0),r}let Se=class{constructor(e){P(this,"moduleName");this.moduleName=e}print(e,t,...n){const i=eu();Qc()&&console.log(`${i}-${Yc}%c[${ys[e].text}]%c[${this.moduleName}][${t}]`,`background-color:${ys[e].color};`,"background-color:rgba(0, 0, 0, 0)",...n)}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 n=this;return function(...s){n.info(`${t}-invoke`,...s);try{const a=e(...s);return typeof(a==null?void 0:a.then)=="function"?a.then(o=>(n.success(`${t}-result`,o),o)).catch(o=>{throw n.error(`${t}-result`,o),o}):(n.success(`${t}-result`,a),a)}catch(a){n.error(`[${t}-result`,a)}}}};function eu(){const r=new Date;return`${r.toTimeString().split(" ")[0]}:${r.getMilliseconds().toString().padStart(3,"0")}`}function On(r,e){const t=document.createElement(r);return e.id&&(t.id=e.id),e.classList&&e.classList.forEach(n=>{t.classList.add(n)}),e.style&&Object.assign(t.style,e.style),e.attributes&&Object.entries(e.attributes).forEach(([n,i])=>{n==="muted"&&(t instanceof HTMLVideoElement||t instanceof HTMLAudioElement)?t.muted=!0:t.setAttribute(n,i)}),t}function bs({width:r,height:e}){const t=document.createElement("canvas"),n=t.getContext("2d");if(!n)throw new $(K.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:n,canvas:t}}class Mn{constructor(e){P(this,"target");P(this,"_eventDict",new Map);this.target=e}on(e,t){let n=this._eventDict.get(e);n||(n=[t]),this._eventDict.set(e,n),this.target.addEventListener(e,t)}off(e,t){let n=this._eventDict.get(e);n&&(n=n.filter(i=>i!==t),this._eventDict.set(e,n),this.target.removeEventListener(e,t))}once(e,t){const n=i=>{t(i),this.off(e,n)};this.on(e,n)}clear(e){const t=this._eventDict.get(e);t&&t.forEach(n=>{this.target.removeEventListener(e,n)})}clearAll(){for(const e of this._eventDict.keys())this.clear(e)}}const oe=()=>typeof window>"u";function ie(){return navigator.userAgent.toLowerCase()}function Ln(r=ie()){let e="none";return oe()||(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 Es=Ln()==="firefox",Hr=Ln()==="safari";Ln(),!oe()&&/crios/i.test(ie()),!oe()&&/edg\//i.test(ie()),!oe()&&/edgA/i.test(ie()),!oe()&&/edgios/i.test(ie()),!oe()&&/dingtalk/i.test(ie()),!oe()&&/opr\//.test(ie()),!oe()&&/(iphone|ipod)/i.exec(ie()),!oe()&&(/(ipad)/i.exec(ie())||/macintosh/i.test(ie())&&"ontouchend"in document),!oe()&&/macintosh/i.test(ie()),!oe()&&/micromessenger/i.test(ie()),!oe()&&ie().includes("mobile"),!oe()&&/sm-\w+/i.test(ie());const tu=!oe()&&!!/(iphone|ipad|ipod)/i.exec(ie());!oe()&&/android/i.test(ie()),!oe()&&/windows/i.test(ie()),!oe()&&/openharmony/i.test(ie());let Cs="0";const ru=!oe()&&((Uc=ie().match(/version\/(\d+)/i))==null?void 0:Uc[1]);Hr&&ru&&(Cs=(Gc=navigator.userAgent.match(/version\/(\d+\.\d+)/i))==null?void 0:Gc[1]),!oe()&&((Bc=ie().match(/firefox\/(\d+)/i))==null||Bc[1]);const Nn=Cs;!oe()&&((Vc=(Fc=ie().match(/ ([\d_]+) like mac os x/i))==null?void 0:Fc[1])==null||Vc.split("_").map(r=>parseInt(r))),!oe()&&((jc=ie().match(/chrome\/(\d+)/i))==null||jc[1]);function nu(){var r;return!!((r=navigator==null?void 0:navigator.permissions)!=null&&r.query)}function Un(){return!!(navigator!=null&&navigator.mediaDevices)}function iu(){var r;return Un()&&!!((r=navigator==null?void 0:navigator.mediaDevices)!=null&&r.getUserMedia)}function su(){return!!Promise.withResolvers}function ou(){return!(Hr&&Nn==="16.1")}function au(){return!(Hr&&Nn&&["16.1","16.2","16.3"].includes(Nn))}function cu(){return!Es}function uu(){return typeof CanvasCaptureMediaStreamTrack<"u"}function du(r){return typeof r.requestFrame=="function"}function lu(){return!!Un()&&typeof navigator.mediaDevices.ondevicechange<"u"&&typeof navigator.mediaDevices.addEventListener=="function"}const Ke={permissionQuery:nu,mediaDevices:Un,settingResolutionInGetDisplayMedia:ou,promiseWithResolvers:su,getUserMedia:iu,isolateEnumerateDevices:cu,supportIdealParamsInGetDisplayMedia:au,canvasCaptureMediaStreamTrack:uu,requestFrameOnMediaStream:du,ondevicechange:lu};function hu(){if(Ke.promiseWithResolvers())return Promise.withResolvers();let r,e;const t=new Promise((n,i)=>{r=n,e=i});if(!r||!e)throw Error("resolver and rejector working unexpected");return{promise:t,resolve:r,reject:e}}function ws(r={}){const{timeout:e,message:t}={timeout:0,message:new $(K.UNEXPECTED_ERROR,"unexpected timeout"),...r},{promise:n,resolve:i,reject:s}=hu();if(e<=0)return{promise:n,resolve:i,reject:s};const a=setTimeout(()=>{s(t)},e);return{promise:n,resolve:d=>{clearTimeout(a),i(d)},reject:s}}const pu={playsinline:"","webkit-playsinline":"","x5-playsinline":"","x5-video-player-type":"h5","x-webkit-airplay":"allow",preload:"metadata",muted:"",crossOrigin:"anonymous"},fu={playsinline:"","webkit-playsinline":"",preload:"metadata",muted:"",crossOrigin:"anonymous"};class Yt{constructor(e,t=[]){P(this,"id",yt());P(this,"_referenceTracks",[]);P(this,"_element");P(this,"_volumeMode",0);P(this,"_readyLock");P(this,"_releaseReadyLock");P(this,"_throwReadyLock");P(this,"_stream");let n;if(e instanceof MediaStreamTrack){const o=new MediaStream([e]);n=mu(o),this._stream=o}else if(e.url)n=_u(e);else throw new $(K.UNEXPECTED_TYPE,`got ${typeof e}, expected: MediaStreamTrack or constraints for creating element`);const{promise:i,resolve:s,reject:a}=ws({timeout:2e3,message:new $(K.PLAY_FAILED,"load media timeout")});this._readyLock=i,this._releaseReadyLock=s,this._throwReadyLock=a,this._element=new Mn(n),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===te.AUDIO){this._upgradeVolumeMode(1e-4);const n=t.getAudioTracks();if(n.length<1)throw new $(K.UNEXPECTED_TYPE,"got empty list of audio tracks");return n[0]}if(e===te.VIDEO){const n=t.getVideoTracks();if(n.length<1)throw new $(K.UNEXPECTED_TYPE,"got empty list of video tracks");return n[0]}throw new $(K.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 $(K.PLAY_FAILED,"play element failed",e)}}_bindPlayerEvent(e){e.on("loadedmetadata",()=>{this._releaseReadyLock()}),e.on("error",()=>{this._throwReadyLock(new $(K.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 mu(r){let e="audio";r.getVideoTracks().length>0&&(e="video");const t=Ts(e==="video"?te.VIDEO:te.AUDIO);return t.srcObject=r,t}function _u(r){const{url:e,kind:t,loop:n}=r,i=Ts(t);return i.src=e,i.loop=n,i}function Ts(r){if(r===te.VIDEO)return On(te.VIDEO,{style:{width:"100%",height:"100%"},attributes:pu});if(r===te.AUDIO)return On(te.AUDIO,{style:{display:"none"},attributes:fu});throw new $(K.UNEXPECTED_TYPE,`got ${r}, expected: audio, video`)}class Gn extends st{emit(e,...t){const n=this.listenerCount(e);return Promise.resolve().then(()=>{super.emit(e,...t)}),!!n}on(e,t,n){const i=(...s)=>{try{return t(...s)}catch(a){console.error(`[SafeEventEmitter] event listener threw an error when handling [${e}] event: `,a)}};return super.on(e,i,n)}once(e,t,n){const i=(...s)=>{try{return t(...s)}catch(a){console.error(`[SafeEventEmitter] event listener threw an error when handling [${e}] event: `,a)}};return super.once(e,i,n)}}function Bn(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 $(K.UNEXPECTED_TYPE,"unexpected constraints type")}const qr=1e3;class ks{constructor(e){P(this,"id",yt());P(this,"_context");P(this,"_canvas");P(this,"_image");P(this,"_config");P(this,"_readyLock");P(this,"_releaseReadyLock");P(this,"_throwReadyLock");P(this,"_loopTimer");P(this,"_referenceTracks",[]);P(this,"_stream");const t=Bn(e.width),n=Bn(e.height),i=Bn(e.frameRate);this._config={width:t,height:n,frameRate:i};const{context:s,canvas:a}=bs({width:t,height:n});this._context=s,this._canvas=a;const o=gu({url:e.url,width:t,height:n});this._image=new Mn(o);const{promise:d,resolve:c,reject:u}=ws({timeout:2e3,message:new $(K.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 n=t.getVideoTracks();if(n.length<1)throw new $(K.UNEXPECTED_TYPE,"got empty list of video tracks");return n[0]}element(){return this._image.target}isReady(){return this._readyLock}_bindImageEvent(e){e.on("load",()=>{this._releaseReadyLock()}),e.on("error",()=>{this._throwReadyLock(new $(K.PLAY_FAILED,"HTMLMediaElement got error when loading file"))})}async _paint(){const{width:e,height:t,frameRate:n}=this._config;this._context.drawImage(this._image.target,0,0,e,t),this._loopTimer&&clearTimeout(this._loopTimer),this._loopTimer=setTimeout(this._paint.bind(this),qr/n)}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 gu({url:r,height:e,width:t}){const n=On("img",{style:{width:`${t}px`,height:`${e}px`},attributes:{crossOrigin:"anonymous"}});return n.src=r,n}class Fn extends Gn{constructor(t){super();P(this,"id",yt());P(this,"_track");P(this,"_element");t instanceof MediaStreamTrack?(this._track=new Mn(t),this._bindTrackEvent(this._track)):t instanceof Yt?(this._element=t,t.addReferenceTrack(this)):t instanceof ks&&(this._element=t)}_bindTrackEvent(t){t.on("ended",this._handleTrackEnded.bind(this)),t.on("mute",()=>{this.emit(ge.MUTE)}),t.on("unmute",()=>{this.emit(ge.UNMUTE)})}_handleTrackEnded(){this.emit(ge.ENDED),this.destroy()}handlePlayFailed(){this.emit(ge.PLAY_FAILED)}track(){if(this.logger.info("track"),!this.available())throw new $(K.TRACK_NOT_AVAILABLE,"track is not available when creating MediaStreamTrack");if(this._track)return this._track.target;if(!this._element)throw new $(K.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 $(K.TRACK_NOT_AVAILABLE,"track is not available when creating HTMLMediaElement");if(this._element)return this._element.element();if(!this._track)throw new $(K.UNEXPECTED_TYPE,"got this._track falsy");const t=new Yt(this._track.target,[this]);this._element=t;const n=t.element();return this.logger.success("element",n),n}available(){return!!(this._track||this._element)}destroy(){var t,n,i;(t=this._track)==null||t.clearAll(),(n=this._track)==null||n.target.stop(),this._track&&delete this._track,(i=this._element)==null||i.removeReference(this),delete this._element}}class $r extends Fn{constructor(){super(...arguments);P(this,"kind",te.AUDIO);P(this,"_node")}node(){if(this.logger.info("node",this.id),!this.available())throw new $(K.TRACK_NOT_AVAILABLE,"track is not avaiable when creating node");if(this._node)return this._node;const t=new Zc(this);return this._node=t,t}element(){if(this.logger.info("element",this.id),!this.available())throw new $(K.TRACK_NOT_AVAILABLE,"track is not available when creating HTMLMediaElement");if(this._element){const n=this._element.element(!0);if(!(n instanceof HTMLMediaElement))throw new $(K.UNEXPECTED_TYPE,"source should be HTMLMediaElement");return n}if(!this._track)throw new $(K.UNEXPECTED_TYPE,"got this._track falsy");const t=new Yt(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 vu extends $r{constructor(){super(...arguments);P(this,"logger",new Se("MicrophoneAudioTrack"))}}class yu extends $r{constructor(){super(...arguments);P(this,"logger",new Se("ScreenAudioTrack"))}}class Rs extends $r{constructor(){super(...arguments);P(this,"logger",new Se("MediaAudioTrack"))}handlePlayFailed(){this.emit(ge.PLAY_FAILED)}async play(){if(this._element){if(!(this._element instanceof Yt))throw new $(K.UNEXPECTED_TYPE,"element is not TrackMediaElement");return this._element._playElement()}}}class Su extends $r{constructor(){super(...arguments);P(this,"logger",new Se("CustomAudioTrack"))}}let bu=1;const Vn=new Se("PromiseQueue");class Eu{constructor(e){P(this,"lockingPromise",Promise.resolve());P(this,"locks",0);P(this,"name","");P(this,"lockId");P(this,"closeReason");this.lockId=bu++,e&&(this.name=e),Vn.info(`lock-${this.name}-${this.lockId}`,"is created.")}get isLocked(){return this.locks>0}lock(){this.locks+=1,Vn.info(`lock-${this.name}-${this.lockId}`,`locked, current queue ${this.locks}.`);let e;const t=new Promise(i=>{e=()=>{this.locks-=1,Vn.info(`lock-${this.name}-${this.lockId}`,`unlocked, current queue ${this.locks}.`),i()}}),n=this.lockingPromise.then(()=>e);return this.lockingPromise=this.lockingPromise.then(()=>t),n}}const Cu=300,wu=3e3,Fe=new Se("Devices");class Tu extends Gn{constructor(){super();P(this,"_deviceMap",{audioinput:[],audiooutput:[],videoinput:[]});P(this,"_permissions",{[te.AUDIO]:!1,[te.VIDEO]:!1});P(this,"_changedQueue",new Eu("device changed queue"));this._init()}async _init(){this._initDeviceChanged(),await this._initPermissionChanged();const t=Is(this._permissions);t.length>0&&this._refreshDevices(t)}_initDeviceChanged(){if(Fe.info("_initDeviceChanged","invoked"),!Ke.ondevicechange()){Fe.error("_initDeviceChanged","no supported, use timer instead"),setInterval(()=>{this._handleDeviceChanged()},wu);return}Ke.ondevicechange()&&navigator.mediaDevices.addEventListener("devicechange",()=>{Fe.info("devicechange"),setTimeout(()=>{this._handleDeviceChanged()},Cu)})}async _initPermissionChanged(){if(!Ke.permissionQuery()){Fe.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",()=>{Fe.info("_initPermissionChanged","update permission for audio"),this._permissions.audio=t.state==="granted"})}catch(t){Fe.error("_initPermissionChanged",t)}try{const t=await navigator.permissions.query({name:"camera"});this._permissions.video=t.state==="granted",t.addEventListener("change",()=>{Fe.info("_initPermissionChanged","update permission for video"),this._permissions.video=t.state==="granted"})}catch(t){Fe.error("_initPermissionChanged",t)}}async _refreshDevices(t){if(!Ke.mediaDevices())throw new $(K.NOT_SUPPORTED,"mediaDevices is not supported");if(t.length===0)throw new $(K.UNEXPECTED_TYPE,"kinds expect to containt values");let n;if(!Ke.isolateEnumerateDevices()){const a={};t.forEach(o=>{a[o]=!0}),n=await navigator.mediaDevices.getUserMedia(a)}let i=await navigator.mediaDevices.enumerateDevices();n&&As(n),i=i.filter(({deviceId:a})=>!!a);const s={audioinput:[],audiooutput:[],videoinput:[]};i.forEach(a=>{const{kind:o}=a;s[o].push(a)}),this._deviceMap=s}async _acquireUserPermission(t){let n=!1;if(t.forEach(i=>{n=n||!this._permissions[i]}),!n)return{grant:!0};if(!Ke.getUserMedia())return{grant:!1,reason:new $(K.NOT_SUPPORTED,"getUserMedia is not supported")};try{const i={};t.forEach(a=>{i[a]=!0});const s=await navigator.mediaDevices.getUserMedia(i);return s?(i.audio&&(this._permissions[te.AUDIO]=!0),i.video&&(this._permissions[te.VIDEO]=!0),As(s),{grant:!0}):{grant:!1,reason:new $(K.UNEXPECTED_TYPE,"get stream falsy")}}catch(i){return{grant:!1,reason:new $(K.CAPTURE_FAILED,"acquire user permission failed",i)}}}async _handleDeviceChanged(){Fe.info("_handleDeviceChanged",this._deviceMap,this._permissions);const t=await this._changedQueue.lock();try{const n=xs(this._deviceMap);let i=[];const s=Is(this._permissions);s.length===0?Fe.warn("_handleDeviceChanged","no permission, use empty list"):(await this._refreshDevices(s),i=xs(this._deviceMap)),i.forEach(a=>{n.findIndex(d=>Ds(d,a))!==-1||this.emit("onDeviceStateChanged",{deviceInfo:a,deviceState:"active"})}),n.forEach(a=>{i.findIndex(d=>Ds(d,a))!==-1||this.emit("onDeviceStateChanged",{deviceInfo:a,deviceState:"inactive"})})}finally{t()}}async enumerateDevices(t){const n=[];t.forEach(o=>{if(o==="audioinput"||o==="audiooutput")n.push(te.AUDIO);else if(o==="videoinput")n.push(te.VIDEO);else throw new $(K.UNEXPECTED_TYPE,"kind in kinds should be enum MediaDeviceKind")});const{grant:i,reason:s}=await this._acquireUserPermission(n);if(!i)throw s;await this._refreshDevices(n);const a=[];return t.forEach(o=>{a.push(...this._deviceMap[o])}),a}async enableDevices(t){return this._acquireUserPermission(t)}}function As(r){r.getTracks().forEach(e=>e.stop())}function Ds(r,e){return r.deviceId===e.deviceId}function xs(r){return Array.from([...r.audioinput.values(),...r.videoinput.values(),...r.audiooutput.values()])}function Is(r){const e=[];return r.audio&&e.push(te.AUDIO),r.video&&e.push(te.VIDEO),e}const jn=new Tu,Hn={LeftToRight:"LeftToRight",UpToDown:"UpToDown",All:"All"};class qn{constructor(){P(this,"id",yt())}position(e,t){return new ku(this,{x:e,y:t})}scale(e){return new zs(this,{s:e})}mirror(e){return new zs(this,{mirrorType:e})}available(){var e;return((e=this.previousNode)==null?void 0:e.available())??!1}}class ku extends qn{constructor(t,n){super();P(this,"previousNode");P(this,"_x");P(this,"_y");this.previousNode=t,this._x=n.x,this._y=n.y}paint(t){t.translate(this._x,this._y)}}class zs extends qn{constructor(t,n){super();P(this,"previousNode");P(this,"_scaleParams",[1,1]);if(this.previousNode=t,n.mirrorType)switch(n.mirrorType){case Hn.LeftToRight:this._scaleParams=[-1,1];break;case Hn.UpToDown:this._scaleParams=[1,-1];break;case Hn.All:this._scaleParams=[-1,-1];break;default:this._scaleParams=[1,1];break}else n.s&&(this._scaleParams=[n.s,n.s])}paint(t){t.scale(this._scaleParams[0],this._scaleParams[1])}}class Ru extends qn{constructor(t){super();P(this,"previousNode",null);P(this,"_source");this._source=t}available(){return this._source.available()}}class Kr extends Ru{constructor(t,n){super(t);P(this,"_targetWidth");P(this,"_targetHeight");const{width:i,height:s}=n??{};this._targetWidth=i??this._source.width(),this._targetHeight=s??this._source.height()}size(t,n){return new Kr(this._source,{width:t,height:n})}paint(t){const n=this._targetWidth,i=this._targetHeight;t.drawImage(this._source.element(),-n/2,-i/2,n,i)}}class Au extends Fn{constructor(){super(...arguments);P(this,"logger",new Se("PictureTrack"));P(this,"kind",te.VIDEO)}element(){const t=super.element();if(!(t instanceof HTMLImageElement))throw new $(K.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 $(K.TRACK_NOT_AVAILABLE,"track is not avaiable when creating node");const t=new Kr(this);return this.logger.info("node",t),t}destroy(){this.logger.warn("destroy"),super.destroy()}}const Du=500;class Wr extends Fn{constructor(){super(...arguments);P(this,"kind",te.VIDEO);P(this,"sizeChangeTimer");P(this,"watchSizeChangeOnce",()=>{const t=this.width(),n=this.height();this.sizeChangeTimer=setTimeout(()=>{const i=this.width(),s=this.height();(n!==s||t!==i)&&this.emit(ge.SIZE_CHANGE,{width:i,height:s})},Du)})}element(){const t=super.element();if(!(t instanceof HTMLVideoElement))throw new $(K.UNEXPECTED_TYPE,"source should be HTMLVideoElement");return t}node(){if(!this.available())throw new $(K.TRACK_NOT_AVAILABLE,"track is not avaiable when creating node");return new Kr(this)}destroy(){clearTimeout(this.sizeChangeTimer),super.destroy()}}class xu extends Wr{constructor(t){super(t);P(this,"logger",new Se("CameraVideoTrack"));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 Wr{constructor(t){super(t);P(this,"logger",new Se("ScreenVideoTrack"));this.watchSizeChangeOnce()}height(){const{height:t}=this.track().getSettings();return t??0}width(){const{width:t}=this.track().getSettings();return t??0}}class zu extends Wr{constructor(){super(...arguments);P(this,"logger",new Se("MediaVideoTrack"))}height(){const{videoHeight:t}=this.element();return t??0}width(){const{videoWidth:t}=this.element();return t??0}}class Pu extends Wr{constructor(){super(...arguments);P(this,"logger",new Se("CustomVideoTrack"))}height(){const{height:t}=this.track().getSettings();return t??0}width(){const{width:t}=this.track().getSettings();return t??0}}async function Ps(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(n){console.warn("[VePusher Error]: frameRate limit failed",n)}}const We=new Se("Capture");async function Ou(r){return jn.enumerateDevices(r)}async function Mu(r){jn.removeAllListeners("onDeviceStateChanged"),jn.on("onDeviceStateChanged",r)}async function Lu(r,e){let t;try{const i={video:r??!0};typeof i.video=="object"&&i.video.facingMode&&delete i.video.deviceId,t=await navigator.mediaDevices.getUserMedia(i)}catch(i){throw new $(K.CAPTURE_FAILED,"got error when capturing camera",i)}const n=t.getVideoTracks()[0];if(r!=null&&r.frameRate&&e&&Ps(n,r),!n)throw new $(K.UNEXPECTED_TYPE,"got falsy in track");return new xu(n)}async function Nu(r,e,t){const{video:n,audio:i}=r;let s=n===!0?{}:n;e!=null&&e.displaySurface&&(s.displaySurface=e.displaySurface,delete e.displaySurface),Ke.settingResolutionInGetDisplayMedia()||(s=!0),!Ke.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:i,...e})}catch(u){throw new $(K.CAPTURE_FAILED,"got error when capture screen",u)}const o=a.getVideoTracks()[0],d=a.getAudioTracks()[0];if(!o)throw new $(K.UNEXPECTED_TYPE,"got falsy in videoTrack");typeof s!="boolean"&&typeof s.frameRate=="number"&&t&&Ps(o,s);const c=[];return c.push(new Iu(o)),d&&c.push(new yu(d)),c}async function Uu(r){const{url:e,audio:t,video:n,loop:i}=r,s=new Yt({url:e,kind:n?te.VIDEO:te.AUDIO,loop:i}),a=[];return t&&a.push(new Rs(s)),n&&a.push(new zu(s)),await s.isReady(),a}async function Gu(r){const e=new ks(r);return await e.isReady(),new Au(e)}async function Bu(r){let e;try{const n={audio:r??!0};e=await navigator.mediaDevices.getUserMedia(n)}catch(n){throw new $(K.CAPTURE_FAILED,"got error when capturing microphone",n)}const t=e.getAudioTracks()[0];if(!t)throw new $(K.UNEXPECTED_TYPE,"got falsy in track");return new vu(t)}function Fu(r){if(!r||r.kind!=="video")throw new $(K.UNEXPECTED_TYPE,"error custom video track type");return new Pu(r)}function Vu(r){if(!r||r.kind!=="audio")throw new $(K.UNEXPECTED_TYPE,"error custom audio track type");return new Su(r)}const ju=We.invoke(Ou,"enumerateInputDevices"),Hu=We.invoke(Lu,"createCameraTrack"),qu=We.invoke(Gu,"createPictureTrack"),Os=We.invoke(Uu,"createMediaTracks"),$u=We.invoke(Bu,"createMicrophoneTrack"),Ku=We.invoke(Nu,"createScreenTracks"),Wu=We.invoke(Mu,"onDeviceChanged"),Ju=We.invoke(Fu,"createCustomVideoTrack"),Xu=We.invoke(Vu,"createCustomAudioTrack");var $n=(r=>(r.PAUSING="pausing",r))($n||{});const Zu={sampleRate:48e3,keepAlive:!0},Ms=new Map,Qt=new Se("Mixer");class Yu extends Gn{constructor(t){super();P(this,"id",yt());P(this,"_context");P(this,"_config");P(this,"_nodeList",[]);P(this,"_destNode");P(this,"_bufferNode");P(this,"_track");P(this,"unlockAudioContext",()=>{if(this._context.state!=="suspended")return;const t=document.body,n=["touchstart","touchend","mousedown","keydown"],i=()=>{n.forEach(a=>{t.removeEventListener(a,s)})},s=()=>{er(this._context).then(i)};n.forEach(a=>{t.addEventListener(a,s,!1)})});Qt.info("ctor",t),this._config={...Zu,...t},this._context=Qu(this._config),this._bindContextEvent(this._context)}mix(t){Qt.info("mix",t),er(this._context);for(const n of this._nodeList)t.includes(n)||n.destroy();this._nodeList=t,this._connect(t,this._destNode),this._nodeList.length===0&&this._appendSlience(this._context,this._destNode)}resume(){return Qt.info("resume"),er(this._context)}_connect(t,n){for(const i of t)i.connect(this._context,n)}_appendSlience(t,n){if(!n||this._bufferNode)return;const{sampleRate:i}=t,s=new AudioBuffer({length:100,sampleRate:i}),a=new AudioBufferSourceNode(t,{buffer:s,loop:!0});a.connect(n),this._bufferNode=a}_bindContextEvent(t){t.addEventListener("statechange",this._handleContextStateChange.bind(this))}_handleContextStateChange(){const t=this._context;(t.state==="suspended"||t.state==="interrupted")&&(Qt.info("_emit_",$n.PAUSING),this.emit($n.PAUSING))}track(){if(Qt.info("track"),er(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 n=t.stream.getAudioTracks()[0];return this._destNode=t,this._track=n,n}}function Qu(r){const{sampleRate:e,keepAlive:t}=r;let n=Ms.get(e);return(!n||n.state==="closed")&&(n=new AudioContext({sampleRate:e}),Ms.set(e,n)),t&&(n.onstatechange=()=>{er(n)}),n}function er(r){return r.state==="suspended"||r.state==="interrupted"?r.resume():Promise.resolve()}const ed=r=>(e,t)=>(r.set(e,t),t),Ls=Number.MAX_SAFE_INTEGER===void 0?9007199254740991:Number.MAX_SAFE_INTEGER,Ns=536870912,Us=Ns*2,td=(r,e)=>t=>{const n=e.get(t);let i=n===void 0?t.size:n<Us?n+1:0;if(!t.has(i))return r(t,i);if(t.size<Ns){for(;t.has(i);)i=Math.floor(Math.random()*Us);return r(t,i)}if(t.size>Ls)throw new Error("Congratulations, you created a collection of unique numbers which uses all available integers!");for(;t.has(i);)i=Math.floor(Math.random()*Ls);return r(t,i)},Gs=new WeakMap,rd=ed(Gs),ot=td(rd,Gs),nd=r=>r.method!==void 0&&r.method==="call",id=r=>typeof r.id=="number"&&typeof r.result=="boolean",Bs=((r,e)=>{let t=null;return()=>{if(t!==null)return t;const n=new Blob([e],{type:"application/javascript; charset=utf-8"}),i=URL.createObjectURL(n);return t=r(i),setTimeout(()=>URL.revokeObjectURL(i)),t}})(r=>{const e=new Map([[0,()=>{}]]),t=new Map([[0,()=>{}]]),n=new Map,i=new Worker(r);return i.addEventListener("message",({data:c})=>{if(nd(c)){const{params:{timerId:u,timerType:h}}=c;if(h==="interval"){const l=e.get(u);if(typeof l===void 0)throw new Error("The timer is in an undefined state.");if(typeof l=="number"){const f=n.get(l);if(f===void 0||f.timerId!==u||f.timerType!==h)throw new Error("The timer is in an undefined state.")}else typeof l=="function"&&l()}else if(h==="timeout"){const l=t.get(u);if(typeof l===void 0)throw new Error("The timer is in an undefined state.");if(typeof l=="number"){const f=n.get(l);if(f===void 0||f.timerId!==u||f.timerType!==h)throw new Error("The timer is in an undefined state.")}else typeof l=="function"&&(l(),t.delete(u))}}else if(id(c)){const{id:u}=c,h=n.get(u);if(h===void 0)throw new Error("The timer is in an undefined state.");const{timerId:l,timerType:f}=h;n.delete(u),f==="interval"?e.delete(l):t.delete(l)}else{const{error:{message:u}}=c;throw new Error(u)}}),{clearInterval:c=>{if(typeof e.get(c)=="function"){const u=ot(n);n.set(u,{timerId:c,timerType:"interval"}),e.set(c,u),i.postMessage({id:u,method:"clear",params:{timerId:c,timerType:"interval"}})}},clearTimeout:c=>{if(typeof t.get(c)=="function"){const u=ot(n);n.set(u,{timerId:c,timerType:"timeout"}),t.set(c,u),i.postMessage({id:u,method:"clear",params:{timerId:c,timerType:"timeout"}})}},setInterval:(c,u=0,...h)=>{const l=ot(e);return e.set(l,()=>{c(...h),typeof e.get(l)=="function"&&i.postMessage({id:null,method:"set",params:{delay:u,now:performance.timeOrigin+performance.now(),timerId:l,timerType:"interval"}})}),i.postMessage({id:null,method:"set",params:{delay:u,now:performance.timeOrigin+performance.now(),timerId:l,timerType:"interval"}}),l},setTimeout:(c,u=0,...h)=>{const l=ot(t);return t.set(l,()=>c(...h)),i.postMessage({id:null,method:"set",params:{delay:u,now:performance.timeOrigin+performance.now(),timerId:l,timerType:"timeout"}}),l}}},`(()=>{"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})}}))})();`),sd=r=>Bs().clearTimeout(r),od=(...r)=>Bs().setTimeout(...r),ad=r=>r.method!==void 0&&r.method==="call",cd=r=>typeof r.id=="number"&&typeof r.result=="boolean",ud=r=>{const e=new Map([[0,()=>{}]]),t=new Map([[0,()=>{}]]),n=new Map,i=new Worker(r,{credentials:"omit"});return i.addEventListener("message",({data:c})=>{if(ad(c)){const{params:{timerId:u,timerType:h}}=c;if(h==="interval"){const l=e.get(u);if(typeof l===void 0)throw new Error("The timer is in an undefined state.");if(typeof l=="number"){const f=n.get(l);if(f===void 0||f.timerId!==u||f.timerType!==h)throw new Error("The timer is in an undefined state.")}else typeof l=="function"&&l()}else if(h==="timeout"){const l=t.get(u);if(typeof l===void 0)throw new Error("The timer is in an undefined state.");if(typeof l=="number"){const f=n.get(l);if(f===void 0||f.timerId!==u||f.timerType!==h)throw new Error("The timer is in an undefined state.")}else typeof l=="function"&&(l(),t.delete(u))}}else if(cd(c)){const{id:u}=c,h=n.get(u);if(h===void 0)throw new Error("The timer is in an undefined state.");const{timerId:l,timerType:f}=h;n.delete(u),f==="interval"?e.delete(l):t.delete(l)}else{const{error:{message:u}}=c;throw new Error(u)}}),{clearInterval:c=>{if(typeof e.get(c)=="function"){const u=ot(n);n.set(u,{timerId:c,timerType:"interval"}),e.set(c,u),i.postMessage({id:u,method:"clear",params:{timerId:c,timerType:"interval"}})}},clearTimeout:c=>{if(typeof t.get(c)=="function"){const u=ot(n);n.set(u,{timerId:c,timerType:"timeout"}),t.set(c,u),i.postMessage({id:u,method:"clear",params:{timerId:c,timerType:"timeout"}})}},setInterval:(c,u=0,...h)=>{const l=ot(e);return e.set(l,()=>{c(...h),typeof e.get(l)=="function"&&i.postMessage({id:null,method:"set",params:{delay:u,now:performance.timeOrigin+performance.now(),timerId:l,timerType:"interval"}})}),i.postMessage({id:null,method:"set",params:{delay:u,now:performance.timeOrigin+performance.now(),timerId:l,timerType:"interval"}}),l},setTimeout:(c,u=0,...h)=>{const l=ot(t);return t.set(l,()=>c(...h)),i.postMessage({id:null,method:"set",params:{delay:u,now:performance.timeOrigin+performance.now(),timerId:l,timerType:"timeout"}}),l}}},dd={width:640,height:480,frameRate:30,backgroundColor:"#000000"},Jr=new Se("View");class ld{constructor(e){P(this,"id",yt());P(this,"_context");P(this,"_canvas");P(this,"_config");P(this,"_nodeList",[]);P(this,"_track");P(this,"_stopped",!0);P(this,"_nextTime",Date.now());P(this,"_workerTimeoutId");P(this,"_raqId");P(this,"_workerTimerScriptUrl");P(this,"_customSetTimeout");P(this,"_customClearTimeout");P(this,"_drawCount",0);P(this,"_lastSecondDrawCount",0);P(this,"_lastCountResetTime",Date.now());P(this,"_loopTimer");P(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)},qr/this._config.frameRate),this._raqId=requestAnimationFrame(this._paintLoop)});Jr.info("ctor",e),this._config={...dd,...e};const{context:t,canvas:n}=bs(this._config);this._context=t,this._canvas=n,this._customSetTimeout=od,this._customClearTimeout=sd}setWorkerTimerScriptUrl(e){if(this._workerTimerScriptUrl=e,this._workerTimerScriptUrl){const t=ud(this._workerTimerScriptUrl);this._customSetTimeout=(...n)=>t.setTimeout(...n),this._customClearTimeout=n=>t.clearTimeout(n)}}_shouldDraw(e){if(e<this._nextTime)return!1;for(;e>this._nextTime;)this._nextTime+=qr/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=[]){Jr.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>=qr&&(this._lastSecondDrawCount=this._drawCount,this._drawCount=0,this._lastCountResetTime=e)}getDrawCountPerSecond(){return this._updateDrawCountPerSecond(),this._lastSecondDrawCount}_drawBackground(){const{backgroundColor:e,width:t,height:n}=this._config;this._context.clearRect(0,0,t,n),e&&(this._context.fillStyle=e,this._context.fillRect(0,0,t,n))}track(){if(Jr.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,n=this._canvas.captureStream(t);return this._track=n.getVideoTracks()[0],e.stop(),this._track}else return this.track()}element(){return Jr.info("element"),this._paintLoop(),this._canvas}stop(){this._stopped=!0}}function hd(){return Math.random().toString(36).slice(-8)}const pd=`
|
|
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
|
-
`,dd=URL.createObjectURL(new Blob([ud],{type:"application/javascript"}));class ld{constructor(){this._audioCtx=null,this._volume=0}get volume(){return this._volume}async start(e,t){if(this._audioCtx)return;const n=new AudioContext;await n.audioWorklet.addModule(t||dd);const i=new MediaStream;i.addTrack(e);const s=n.createMediaStreamSource(i),a=new AudioWorkletNode(n,"vumeter");a.port.onmessage=o=>{const d=o.data.volume||0;this._volume=Math.min(d*100/2,10)},s.connect(a).connect(n.destination),this._audioCtx=n}stop(){var e;(e=this._audioCtx)==null||e.close(),this._audioCtx=null}}class Kr{constructor(){this._volumeDetectScriptUrl=void 0}static get instance(){return this._instance||(this._instance=new Kr),this._instance}get volumeDetectScriptUrl(){return this._volumeDetectScriptUrl}set volumeDetectScriptUrl(e){this._volumeDetectScriptUrl=e}}class Gs extends it{constructor(e){super(),this._width=0,this._height=0,this._mediaStream=null,this._nextStream=null,this._trackMap={},this.type=e.type,this.id=cd(),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[Y.Camera,Y.Screen,Y.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 ld),await this._volumeDetector.start(this.audioTrack,Kr.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 Nt extends Gs{get isVideoStream(){return!0}get isAudioStream(){return!1}bindTrackSizeChangeEvent(e){e.on(me.SIZE_CHANGE,({width:t,height:n})=>{this._width=t,this._height=n,this.emit(ls.SizeChange,{width:t,height:n})})}}class Wr extends Gs{get isVideoStream(){return!1}get isAudioStream(){return!0}}class hd extends Nt{constructor(e){super({type:Y.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(me.ENDED,e)}destroy(){this.source.destroy()}}var Bs=typeof global=="object"&&global&&global.Object===Object&&global,pd=typeof self=="object"&&self&&self.Object===Object&&self,Je=Bs||pd||Function("return this")(),ot=Je.Symbol,Fs=Object.prototype,fd=Fs.hasOwnProperty,md=Fs.toString,rr=ot?ot.toStringTag:void 0;function _d(r){var e=fd.call(r,rr),t=r[rr];try{r[rr]=void 0;var n=!0}catch{}var i=md.call(r);return n&&(e?r[rr]=t:delete r[rr]),i}var gd=Object.prototype,vd=gd.toString;function yd(r){return vd.call(r)}var Sd="[object Null]",bd="[object Undefined]",Vs=ot?ot.toStringTag:void 0;function Ut(r){return r==null?r===void 0?bd:Sd:Vs&&Vs in Object(r)?_d(r):yd(r)}function Gt(r){return r!=null&&typeof r=="object"}var Ed="[object Symbol]";function Jr(r){return typeof r=="symbol"||Gt(r)&&Ut(r)==Ed}function js(r,e){for(var t=-1,n=r==null?0:r.length,i=Array(n);++t<n;)i[t]=e(r[t],t,r);return i}var ae=Array.isArray,Hs=ot?ot.prototype:void 0,qs=Hs?Hs.toString:void 0;function $s(r){if(typeof r=="string")return r;if(ae(r))return js(r,$s)+"";if(Jr(r))return qs?qs.call(r):"";var e=r+"";return e=="0"&&1/r==-1/0?"-0":e}var Cd=/\s/;function wd(r){for(var e=r.length;e--&&Cd.test(r.charAt(e)););return e}var Td=/^\s+/;function kd(r){return r&&r.slice(0,wd(r)+1).replace(Td,"")}function nr(r){var e=typeof r;return r!=null&&(e=="object"||e=="function")}var Ks=NaN,Rd=/^[-+]0x[0-9a-f]+$/i,Ad=/^0b[01]+$/i,Dd=/^0o[0-7]+$/i,xd=parseInt;function Id(r){if(typeof r=="number")return r;if(Jr(r))return Ks;if(nr(r)){var e=typeof r.valueOf=="function"?r.valueOf():r;r=nr(e)?e+"":e}if(typeof r!="string")return r===0?r:+r;r=kd(r);var t=Ad.test(r);return t||Dd.test(r)?xd(r.slice(2),t?2:8):Rd.test(r)?Ks:+r}var zd=1/0,Od=17976931348623157e292;function Pd(r){if(!r)return r===0?r:0;if(r=Id(r),r===zd||r===-1/0){var e=r<0?-1:1;return e*Od}return r===r?r:0}function Md(r){var e=Pd(r),t=e%1;return e===e?t?e-t:e:0}function Ld(r){return r}var Nd="[object AsyncFunction]",Ud="[object Function]",Gd="[object GeneratorFunction]",Bd="[object Proxy]";function Ws(r){if(!nr(r))return!1;var e=Ut(r);return e==Ud||e==Gd||e==Nd||e==Bd}var Hn=Je["__core-js_shared__"],Js=function(){var r=/[^.]+$/.exec(Hn&&Hn.keys&&Hn.keys.IE_PROTO||"");return r?"Symbol(src)_1."+r:""}();function Fd(r){return!!Js&&Js in r}var Vd=Function.prototype,jd=Vd.toString;function Et(r){if(r!=null){try{return jd.call(r)}catch{}try{return r+""}catch{}}return""}var Hd=/[\\^$.*+?()[\]{}|]/g,qd=/^\[object .+?Constructor\]$/,$d=Function.prototype,Kd=Object.prototype,Wd=$d.toString,Jd=Kd.hasOwnProperty,Xd=RegExp("^"+Wd.call(Jd).replace(Hd,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function Zd(r){if(!nr(r)||Fd(r))return!1;var e=Ws(r)?Xd:qd;return e.test(Et(r))}function Yd(r,e){return r==null?void 0:r[e]}function Bt(r,e){var t=Yd(r,e);return Zd(t)?t:void 0}var qn=Bt(Je,"WeakMap");function Qd(r,e,t,n){for(var i=r.length,s=t+-1;++s<i;)if(e(r[s],s,r))return s;return-1}var el=9007199254740991,tl=/^(?:0|[1-9]\d*)$/;function Xs(r,e){var t=typeof r;return e=e??el,!!e&&(t=="number"||t!="symbol"&&tl.test(r))&&r>-1&&r%1==0&&r<e}function Zs(r,e){return r===e||r!==r&&e!==e}var rl=9007199254740991;function $n(r){return typeof r=="number"&&r>-1&&r%1==0&&r<=rl}function Xr(r){return r!=null&&$n(r.length)&&!Ws(r)}var nl=Object.prototype;function Ys(r){var e=r&&r.constructor,t=typeof e=="function"&&e.prototype||nl;return r===t}function il(r,e){for(var t=-1,n=Array(r);++t<r;)n[t]=e(t);return n}var sl="[object Arguments]";function Qs(r){return Gt(r)&&Ut(r)==sl}var eo=Object.prototype,ol=eo.hasOwnProperty,al=eo.propertyIsEnumerable,Kn=Qs(function(){return arguments}())?Qs:function(r){return Gt(r)&&ol.call(r,"callee")&&!al.call(r,"callee")};function cl(){return!1}var to=typeof exports=="object"&&exports&&!exports.nodeType&&exports,ro=to&&typeof module=="object"&&module&&!module.nodeType&&module,ul=ro&&ro.exports===to,no=ul?Je.Buffer:void 0,dl=no?no.isBuffer:void 0,Zr=dl||cl,ll="[object Arguments]",hl="[object Array]",pl="[object Boolean]",fl="[object Date]",ml="[object Error]",_l="[object Function]",gl="[object Map]",vl="[object Number]",yl="[object Object]",Sl="[object RegExp]",bl="[object Set]",El="[object String]",Cl="[object WeakMap]",wl="[object ArrayBuffer]",Tl="[object DataView]",kl="[object Float32Array]",Rl="[object Float64Array]",Al="[object Int8Array]",Dl="[object Int16Array]",xl="[object Int32Array]",Il="[object Uint8Array]",zl="[object Uint8ClampedArray]",Ol="[object Uint16Array]",Pl="[object Uint32Array]",re={};re[kl]=re[Rl]=re[Al]=re[Dl]=re[xl]=re[Il]=re[zl]=re[Ol]=re[Pl]=!0,re[ll]=re[hl]=re[wl]=re[pl]=re[Tl]=re[fl]=re[ml]=re[_l]=re[gl]=re[vl]=re[yl]=re[Sl]=re[bl]=re[El]=re[Cl]=!1;function Ml(r){return Gt(r)&&$n(r.length)&&!!re[Ut(r)]}function Ll(r){return function(e){return r(e)}}var io=typeof exports=="object"&&exports&&!exports.nodeType&&exports,ir=io&&typeof module=="object"&&module&&!module.nodeType&&module,Nl=ir&&ir.exports===io,Wn=Nl&&Bs.process,so=function(){try{var r=ir&&ir.require&&ir.require("util").types;return r||Wn&&Wn.binding&&Wn.binding("util")}catch{}}(),oo=so&&so.isTypedArray,Jn=oo?Ll(oo):Ml,Ul=Object.prototype,Gl=Ul.hasOwnProperty;function Bl(r,e){var t=ae(r),n=!t&&Kn(r),i=!t&&!n&&Zr(r),s=!t&&!n&&!i&&Jn(r),a=t||n||i||s,o=a?il(r.length,String):[],d=o.length;for(var c in r)Gl.call(r,c)&&!(a&&(c=="length"||i&&(c=="offset"||c=="parent")||s&&(c=="buffer"||c=="byteLength"||c=="byteOffset")||Xs(c,d)))&&o.push(c);return o}function Fl(r,e){return function(t){return r(e(t))}}var Vl=Fl(Object.keys,Object),jl=Object.prototype,Hl=jl.hasOwnProperty;function ao(r){if(!Ys(r))return Vl(r);var e=[];for(var t in Object(r))Hl.call(r,t)&&t!="constructor"&&e.push(t);return e}function sr(r){return Xr(r)?Bl(r):ao(r)}var ql=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,$l=/^\w*$/;function Xn(r,e){if(ae(r))return!1;var t=typeof r;return t=="number"||t=="symbol"||t=="boolean"||r==null||Jr(r)?!0:$l.test(r)||!ql.test(r)||e!=null&&r in Object(e)}var or=Bt(Object,"create");function Kl(){this.__data__=or?or(null):{},this.size=0}function Wl(r){var e=this.has(r)&&delete this.__data__[r];return this.size-=e?1:0,e}var Jl="__lodash_hash_undefined__",Xl=Object.prototype,Zl=Xl.hasOwnProperty;function Yl(r){var e=this.__data__;if(or){var t=e[r];return t===Jl?void 0:t}return Zl.call(e,r)?e[r]:void 0}var Ql=Object.prototype,eh=Ql.hasOwnProperty;function th(r){var e=this.__data__;return or?e[r]!==void 0:eh.call(e,r)}var rh="__lodash_hash_undefined__";function nh(r,e){var t=this.__data__;return this.size+=this.has(r)?0:1,t[r]=or&&e===void 0?rh:e,this}function Ct(r){var e=-1,t=r==null?0:r.length;for(this.clear();++e<t;){var n=r[e];this.set(n[0],n[1])}}Ct.prototype.clear=Kl,Ct.prototype.delete=Wl,Ct.prototype.get=Yl,Ct.prototype.has=th,Ct.prototype.set=nh;function ih(){this.__data__=[],this.size=0}function Yr(r,e){for(var t=r.length;t--;)if(Zs(r[t][0],e))return t;return-1}var sh=Array.prototype,oh=sh.splice;function ah(r){var e=this.__data__,t=Yr(e,r);if(t<0)return!1;var n=e.length-1;return t==n?e.pop():oh.call(e,t,1),--this.size,!0}function ch(r){var e=this.__data__,t=Yr(e,r);return t<0?void 0:e[t][1]}function uh(r){return Yr(this.__data__,r)>-1}function dh(r,e){var t=this.__data__,n=Yr(t,r);return n<0?(++this.size,t.push([r,e])):t[n][1]=e,this}function Xe(r){var e=-1,t=r==null?0:r.length;for(this.clear();++e<t;){var n=r[e];this.set(n[0],n[1])}}Xe.prototype.clear=ih,Xe.prototype.delete=ah,Xe.prototype.get=ch,Xe.prototype.has=uh,Xe.prototype.set=dh;var ar=Bt(Je,"Map");function lh(){this.size=0,this.__data__={hash:new Ct,map:new(ar||Xe),string:new Ct}}function hh(r){var e=typeof r;return e=="string"||e=="number"||e=="symbol"||e=="boolean"?r!=="__proto__":r===null}function Qr(r,e){var t=r.__data__;return hh(e)?t[typeof e=="string"?"string":"hash"]:t.map}function ph(r){var e=Qr(this,r).delete(r);return this.size-=e?1:0,e}function fh(r){return Qr(this,r).get(r)}function mh(r){return Qr(this,r).has(r)}function _h(r,e){var t=Qr(this,r),n=t.size;return t.set(r,e),this.size+=t.size==n?0:1,this}function Ze(r){var e=-1,t=r==null?0:r.length;for(this.clear();++e<t;){var n=r[e];this.set(n[0],n[1])}}Ze.prototype.clear=lh,Ze.prototype.delete=ph,Ze.prototype.get=fh,Ze.prototype.has=mh,Ze.prototype.set=_h;var gh="Expected a function";function Zn(r,e){if(typeof r!="function"||e!=null&&typeof e!="function")throw new TypeError(gh);var t=function(){var n=arguments,i=e?e.apply(this,n):n[0],s=t.cache;if(s.has(i))return s.get(i);var a=r.apply(this,n);return t.cache=s.set(i,a)||s,a};return t.cache=new(Zn.Cache||Ze),t}Zn.Cache=Ze;var vh=500;function yh(r){var e=Zn(r,function(n){return t.size===vh&&t.clear(),n}),t=e.cache;return e}var Sh=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,bh=/\\(\\)?/g,Eh=yh(function(r){var e=[];return r.charCodeAt(0)===46&&e.push(""),r.replace(Sh,function(t,n,i,s){e.push(i?s.replace(bh,"$1"):n||t)}),e});function Ch(r){return r==null?"":$s(r)}function co(r,e){return ae(r)?r:Xn(r,e)?[r]:Eh(Ch(r))}function en(r){if(typeof r=="string"||Jr(r))return r;var e=r+"";return e=="0"&&1/r==-1/0?"-0":e}function uo(r,e){e=co(e,r);for(var t=0,n=e.length;r!=null&&t<n;)r=r[en(e[t++])];return t&&t==n?r:void 0}function wh(r,e,t){var n=r==null?void 0:uo(r,e);return n===void 0?t:n}function Th(r,e){for(var t=-1,n=e.length,i=r.length;++t<n;)r[i+t]=e[t];return r}function kh(){this.__data__=new Xe,this.size=0}function Rh(r){var e=this.__data__,t=e.delete(r);return this.size=e.size,t}function Ah(r){return this.__data__.get(r)}function Dh(r){return this.__data__.has(r)}var xh=200;function Ih(r,e){var t=this.__data__;if(t instanceof Xe){var n=t.__data__;if(!ar||n.length<xh-1)return n.push([r,e]),this.size=++t.size,this;t=this.__data__=new Ze(n)}return t.set(r,e),this.size=t.size,this}function Ye(r){var e=this.__data__=new Xe(r);this.size=e.size}Ye.prototype.clear=kh,Ye.prototype.delete=Rh,Ye.prototype.get=Ah,Ye.prototype.has=Dh,Ye.prototype.set=Ih;function lo(r,e){for(var t=-1,n=r==null?0:r.length,i=0,s=[];++t<n;){var a=r[t];e(a,t,r)&&(s[i++]=a)}return s}function zh(){return[]}var Oh=Object.prototype,Ph=Oh.propertyIsEnumerable,ho=Object.getOwnPropertySymbols,Mh=ho?function(r){return r==null?[]:(r=Object(r),lo(ho(r),function(e){return Ph.call(r,e)}))}:zh;function Lh(r,e,t){var n=e(r);return ae(r)?n:Th(n,t(r))}function po(r){return Lh(r,sr,Mh)}var Yn=Bt(Je,"DataView"),Qn=Bt(Je,"Promise"),ei=Bt(Je,"Set"),fo="[object Map]",Nh="[object Object]",mo="[object Promise]",_o="[object Set]",go="[object WeakMap]",vo="[object DataView]",Uh=Et(Yn),Gh=Et(ar),Bh=Et(Qn),Fh=Et(ei),Vh=Et(qn),Qe=Ut;(Yn&&Qe(new Yn(new ArrayBuffer(1)))!=vo||ar&&Qe(new ar)!=fo||Qn&&Qe(Qn.resolve())!=mo||ei&&Qe(new ei)!=_o||qn&&Qe(new qn)!=go)&&(Qe=function(r){var e=Ut(r),t=e==Nh?r.constructor:void 0,n=t?Et(t):"";if(n)switch(n){case Uh:return vo;case Gh:return fo;case Bh:return mo;case Fh:return _o;case Vh:return go}return e});var yo=Je.Uint8Array,jh="__lodash_hash_undefined__";function Hh(r){return this.__data__.set(r,jh),this}function qh(r){return this.__data__.has(r)}function tn(r){var e=-1,t=r==null?0:r.length;for(this.__data__=new Ze;++e<t;)this.add(r[e])}tn.prototype.add=tn.prototype.push=Hh,tn.prototype.has=qh;function $h(r,e){for(var t=-1,n=r==null?0:r.length;++t<n;)if(e(r[t],t,r))return!0;return!1}function Kh(r,e){return r.has(e)}var Wh=1,Jh=2;function So(r,e,t,n,i,s){var a=t&Wh,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 h=-1,l=!0,f=t&Jh?new tn:void 0;for(s.set(r,e),s.set(e,r);++h<o;){var y=r[h],C=e[h];if(n)var v=a?n(C,y,h,e,r,s):n(y,C,h,r,e,s);if(v!==void 0){if(v)continue;l=!1;break}if(f){if(!$h(e,function(E,k){if(!Kh(f,k)&&(y===E||i(y,E,t,n,s)))return f.push(k)})){l=!1;break}}else if(!(y===C||i(y,C,t,n,s))){l=!1;break}}return s.delete(r),s.delete(e),l}function Xh(r){var e=-1,t=Array(r.size);return r.forEach(function(n,i){t[++e]=[i,n]}),t}function Zh(r){var e=-1,t=Array(r.size);return r.forEach(function(n){t[++e]=n}),t}var Yh=1,Qh=2,ep="[object Boolean]",tp="[object Date]",rp="[object Error]",np="[object Map]",ip="[object Number]",sp="[object RegExp]",op="[object Set]",ap="[object String]",cp="[object Symbol]",up="[object ArrayBuffer]",dp="[object DataView]",bo=ot?ot.prototype:void 0,ti=bo?bo.valueOf:void 0;function lp(r,e,t,n,i,s,a){switch(t){case dp:if(r.byteLength!=e.byteLength||r.byteOffset!=e.byteOffset)return!1;r=r.buffer,e=e.buffer;case up:return!(r.byteLength!=e.byteLength||!s(new yo(r),new yo(e)));case ep:case tp:case ip:return Zs(+r,+e);case rp:return r.name==e.name&&r.message==e.message;case sp:case ap:return r==e+"";case np:var o=Xh;case op:var d=n&Yh;if(o||(o=Zh),r.size!=e.size&&!d)return!1;var c=a.get(r);if(c)return c==e;n|=Qh,a.set(r,e);var u=So(o(r),o(e),n,i,s,a);return a.delete(r),u;case cp:if(ti)return ti.call(r)==ti.call(e)}return!1}var hp=1,pp=Object.prototype,fp=pp.hasOwnProperty;function mp(r,e,t,n,i,s){var a=t&hp,o=po(r),d=o.length,c=po(e),u=c.length;if(d!=u&&!a)return!1;for(var h=d;h--;){var l=o[h];if(!(a?l in e:fp.call(e,l)))return!1}var f=s.get(r),y=s.get(e);if(f&&y)return f==e&&y==r;var C=!0;s.set(r,e),s.set(e,r);for(var v=a;++h<d;){l=o[h];var E=r[l],k=e[l];if(n)var g=a?n(k,E,l,e,r,s):n(E,k,l,r,e,s);if(!(g===void 0?E===k||i(E,k,t,n,s):g)){C=!1;break}v||(v=l=="constructor")}if(C&&!v){var D=r.constructor,L=e.constructor;D!=L&&"constructor"in r&&"constructor"in e&&!(typeof D=="function"&&D instanceof D&&typeof L=="function"&&L instanceof L)&&(C=!1)}return s.delete(r),s.delete(e),C}var _p=1,Eo="[object Arguments]",Co="[object Array]",rn="[object Object]",gp=Object.prototype,wo=gp.hasOwnProperty;function vp(r,e,t,n,i,s){var a=ae(r),o=ae(e),d=a?Co:Qe(r),c=o?Co:Qe(e);d=d==Eo?rn:d,c=c==Eo?rn:c;var u=d==rn,h=c==rn,l=d==c;if(l&&Zr(r)){if(!Zr(e))return!1;a=!0,u=!1}if(l&&!u)return s||(s=new Ye),a||Jn(r)?So(r,e,t,n,i,s):lp(r,e,d,t,n,i,s);if(!(t&_p)){var f=u&&wo.call(r,"__wrapped__"),y=h&&wo.call(e,"__wrapped__");if(f||y){var C=f?r.value():r,v=y?e.value():e;return s||(s=new Ye),i(C,v,t,n,s)}}return l?(s||(s=new Ye),mp(r,e,t,n,i,s)):!1}function ri(r,e,t,n,i){return r===e?!0:r==null||e==null||!Gt(r)&&!Gt(e)?r!==r&&e!==e:vp(r,e,t,n,ri,i)}var yp=1,Sp=2;function bp(r,e,t,n){var i=t.length,s=i;if(r==null)return!s;for(r=Object(r);i--;){var a=t[i];if(a[2]?a[1]!==r[a[0]]:!(a[0]in r))return!1}for(;++i<s;){a=t[i];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 Ye,h;if(!(h===void 0?ri(c,d,yp|Sp,n,u):h))return!1}}return!0}function To(r){return r===r&&!nr(r)}function Ep(r){for(var e=sr(r),t=e.length;t--;){var n=e[t],i=r[n];e[t]=[n,i,To(i)]}return e}function ko(r,e){return function(t){return t==null?!1:t[r]===e&&(e!==void 0||r in Object(t))}}function Cp(r){var e=Ep(r);return e.length==1&&e[0][2]?ko(e[0][0],e[0][1]):function(t){return t===r||bp(t,r,e)}}function wp(r,e){return r!=null&&e in Object(r)}function Tp(r,e,t){e=co(e,r);for(var n=-1,i=e.length,s=!1;++n<i;){var a=en(e[n]);if(!(s=r!=null&&t(r,a)))break;r=r[a]}return s||++n!=i?s:(i=r==null?0:r.length,!!i&&$n(i)&&Xs(a,i)&&(ae(r)||Kn(r)))}function kp(r,e){return r!=null&&Tp(r,e,wp)}var Rp=1,Ap=2;function Dp(r,e){return Xn(r)&&To(e)?ko(en(r),e):function(t){var n=wh(t,r);return n===void 0&&n===e?kp(t,r):ri(e,n,Rp|Ap)}}function xp(r){return function(e){return e==null?void 0:e[r]}}function Ip(r){return function(e){return uo(e,r)}}function zp(r){return Xn(r)?xp(en(r)):Ip(r)}function ni(r){return typeof r=="function"?r:r==null?Ld:typeof r=="object"?ae(r)?Dp(r[0],r[1]):Cp(r):zp(r)}function Op(r){return function(e,t,n){for(var i=-1,s=Object(e),a=n(e),o=a.length;o--;){var d=a[++i];if(t(s[d],d,s)===!1)break}return e}}var Pp=Op();function Mp(r,e){return r&&Pp(r,e,sr)}function Lp(r,e){return function(t,n){if(t==null)return t;if(!Xr(t))return r(t,n);for(var i=t.length,s=-1,a=Object(t);++s<i&&n(a[s],s,a)!==!1;);return t}}var Np=Lp(Mp);function Up(r,e){var t=[];return Np(r,function(n,i,s){e(n,i,s)&&t.push(n)}),t}function Ro(r,e){var t=ae(r)?lo:Up;return t(r,ni(e))}function Gp(r){return function(e,t,n){var i=Object(e);if(!Xr(e)){var s=ni(t);e=sr(e),t=function(o){return s(i[o],o,i)}}var a=r(e,t,n);return a>-1?i[s?e[a]:a]:void 0}}var Bp=Math.max;function Fp(r,e,t){var n=r==null?0:r.length;if(!n)return-1;var i=t==null?0:Md(t);return i<0&&(i=Bp(n+i,0)),Qd(r,ni(e),i)}var cr=Gp(Fp);function Vp(r,e){return js(e,function(t){return r[t]})}function et(r){return r==null?[]:Vp(r,sr(r))}var jp="[object Map]",Hp="[object Set]",qp=Object.prototype,$p=qp.hasOwnProperty;function Kp(r){if(r==null)return!0;if(Xr(r)&&(ae(r)||typeof r=="string"||typeof r.splice=="function"||Zr(r)||Jn(r)||Kn(r)))return!r.length;var e=Qe(r);if(e==jp||e==Hp)return!r.size;if(Ys(r))return!ao(r).length;for(var t in r)if($p.call(r,t))return!1;return!0}function Wp(r){return r==null}class Jp extends Wr{constructor(e){super({type:Y.Microphone,stream:e}),this._trackMap.audio=e.track()}get source(){return this._source}get mixerNode(){return this.source.node()}bindTrackEnd(e){this.source.on(me.ENDED,e)}destroy(){this.source.destroy()}}class Xp extends Nt{constructor(e){super({type:Y.VideoFile,stream:e});const t=cr(e,i=>i.kind===te.VIDEO),n=cr(e,i=>i.kind===te.AUDIO);this._videoStream=t,this._audioStream=n,this._trackMap.video=t==null?void 0:t.track(),this._trackMap.audio=n==null?void 0:n.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(me.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 Nt{constructor(e){super({type:Y.Screen,stream:e});const t=cr(e,i=>i.kind===te.VIDEO),n=cr(e,i=>i.kind===te.AUDIO);this._videoStream=t,this._audioStream=n,this._trackMap.video=t==null?void 0:t.track(),this._trackMap.audio=n==null?void 0:n.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(me.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 Yp extends Wr{constructor(e){super({type:Y.AudioFile,stream:e});const t=cr(e,n=>n.kind===te.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(me.ENDED,e)}destroy(){var e;(e=this._audioStream)==null||e.destroy()}}class Qp extends Nt{constructor(e){super({type:Y.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(me.ENDED,e)}destroy(){this.source.destroy()}}class ef extends Nt{constructor(e){super({type:Y.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(me.ENDED,e)}destroy(){this.source.destroy()}}class tf extends Wr{constructor(e){super({type:Y.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(me.ENDED,e)}destroy(){var e;(e=this._audioStream)==null||e.destroy()}}const rf=["user","environment"],nf=18e4,sf=1e4,Ao=1e3;var Ee=(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))(Ee||{});class Ft extends Error{constructor(e,t,n){super(),this.code=e,this.message=t,n&&(this.ext=n)}}function Vt(r,e,t){const n=An.Landscape;if(e==="video"){const d=(n===An.Landscape?as:cs)[r],[c,u,h,l]=d.split("x").map(f=>Number(f));return{width:c,height:u,frameRate:h,bitrate:l*1e3}}const i=us[r],[s,a]=i.split("x").map(o=>Number(o));return{sampleRate:s,bitrate:a*1e3}}var ne=function(){return(ne=Object.assign||function(r){for(var e,t=1,n=arguments.length;t<n;t++)for(var i in e=arguments[t])Object.prototype.hasOwnProperty.call(e,i)&&(r[i]=e[i]);return r}).apply(this,arguments)};function ii(r,e,t,n){return new(t||(t=Promise))(function(i,s){function a(c){try{d(n.next(c))}catch(u){s(u)}}function o(c){try{d(n.throw(c))}catch(u){s(u)}}function d(c){c.done?i(c.value):new t(function(u){u(c.value)}).then(a,o)}d((n=n.apply(r,[])).next())})}function si(r,e){var t,n,i,s,a={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]};return s={next:o(0),throw:o(1),return:o(2)},typeof Symbol=="function"&&(s[Symbol.iterator]=function(){return this}),s;function o(d){return function(c){return function(u){if(t)throw new TypeError("Generator is already executing.");for(;a;)try{if(t=1,n&&(i=2&u[0]?n.return:u[0]?n.throw||((i=n.return)&&i.call(n),0):n.next)&&!(i=i.call(n,u[1])).done)return i;switch(n=0,i&&(u=[2&u[0],i.value]),u[0]){case 0:case 1:i=u;break;case 4:return a.label++,{value:u[1],done:!1};case 5:a.label++,n=u[1],u=[0];continue;case 7:u=a.ops.pop(),a.trys.pop();continue;default:if(i=a.trys,!((i=i.length>0&&i[i.length-1])||u[0]!==6&&u[0]!==2)){a=0;continue}if(u[0]===3&&(!i||u[1]>i[0]&&u[1]<i[3])){a.label=u[1];break}if(u[0]===6&&a.label<i[1]){a.label=i[1],i=u;break}if(i&&a.label<i[2]){a.label=i[2],a.ops.push(u);break}i[2]&&a.ops.pop(),a.trys.pop();continue}u=e.call(r,a)}catch(h){u=[6,h],n=0}finally{t=i=0}if(5&u[0])throw u[1];return{value:u[0]?u[1]:void 0,done:!0}}([d,c])}}}function of(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n,i,s=t.call(r),a=[];try{for(;(e===void 0||e-- >0)&&!(n=s.next()).done;)a.push(n.value)}catch(o){i={error:o}}finally{try{n&&!n.done&&(t=s.return)&&t.call(s)}finally{if(i)throw i.error}}return a}function ur(){for(var r=[],e=0;e<arguments.length;e++)r=r.concat(of(arguments[e]));return r}var Do,af=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 n=this;e&&t&&typeof t=="function"&&this.on(e,function i(s){t(s),n.off(e,i)})},r.prototype.off=function(e,t){if(e&&this._hooks[e]&&this._hooks[e].length)if(t){var n=this._hooks[e].indexOf(t);n!==-1&&this._hooks[e].splice(n,1)}else this._hooks[e]=[]},r.prototype.emit=function(e,t,n){if(n){if(!e)return;this._cache.indexOf(n)!==-1?this._emit(e,t):(this._hooksCache.hasOwnProperty(n)||(this._hooksCache[n]={}),this._hooksCache[n].hasOwnProperty(e)||(this._hooksCache[n][e]=[]),this._hooksCache[n][e].push(t))}else this._emit(e,t)},r.prototype._emit=function(e,t){e&&this._hooks[e]&&this._hooks[e].length&&ur(this._hooks[e]).forEach(function(n){try{n(t)}catch{}})},r.prototype.set=function(e){e&&this._cache.indexOf(e)===-1&&this._cache.push(e)},r}(),dr=function(r){return r!=null&&Object.prototype.toString.call(r)=="[object Object]"},oi=function(r){return Array.isArray(r)},cf=(Do=+Date.now()+Number((""+Math.random()).slice(2,8)),function(){return Do+=1}),lr=function(r){return function(e,t,n){if(typeof e=="string"&&typeof n=="number"){var i,s=[];n=n<=25?n:n%25;var a=String.fromCharCode(n+97);i=e.split(a);for(var o=0;o<i.length;o++){var d=parseInt(i[o],n);d=1*d^t;var c=String.fromCharCode(d);s.push(c)}return s.join("")}}(r,64,25)},xo=function(){return!!navigator.userAgent.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/)},hr=function(r){xo()?window.addEventListener("pagehide",r,!1):window.addEventListener("beforeunload",r,!1)},Io=function(){var r=0;return["hidden","msHidden","webkitHidden"].forEach(function(e){document[e]!==void 0&&(r=1)}),r},ai=function(r){var e=document.createElement("a");return e.href=r,e},nn=function(r){var e={};try{var t=ai(r).search;(t=t.slice(1)).split("&").forEach(function(n){var i,s,a=n.split("=");a.length&&(i=a[0],s=a[1]);try{e[i]=decodeURIComponent(s===void 0?"":s)}catch{e[i]=s}})}catch{}return e},sn=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function ci(){throw new Error("Dynamic requires are not currently supported by rollup-plugin-commonjs")}function zo(r,e){return r(e={exports:{}},e.exports),e.exports}var pr=zo(function(r,e){var t;t=function(){function n(){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 i(s){return s.replace(/(%[0-9A-Z]{2})+/g,decodeURIComponent)}return function s(a){function o(){}function d(u,h,l){if(typeof document<"u"){typeof(l=n({path:"/"},o.defaults,l)).expires=="number"&&(l.expires=new Date(1*new Date+864e5*l.expires)),l.expires=l.expires?l.expires.toUTCString():"";try{var f=JSON.stringify(h);/^[\{\[]/.test(f)&&(h=f)}catch{}h=a.write?a.write(h,u):encodeURIComponent(String(h)).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 y="";for(var C in l)l[C]&&(y+="; "+C,l[C]!==!0&&(y+="="+l[C].split(";")[0]));return document.cookie=u+"="+h+y}}function c(u,h){if(typeof document<"u"){for(var l={},f=document.cookie?document.cookie.split("; "):[],y=0;y<f.length;y++){var C=f[y].split("="),v=C.slice(1).join("=");h||v.charAt(0)!=='"'||(v=v.slice(1,-1));try{var E=i(C[0]);if(v=(a.read||a)(v,E)||i(v),h)try{v=JSON.parse(v)}catch{}if(l[E]=v,u===E)break}catch{}}return u?l[u]:l}}return o.set=d,o.get=function(u){return c(u,!1)},o.getJSON=function(u){return c(u,!0)},o.remove=function(u,h){d(u,"",n(h,{expires:-1}))},o.defaults={},o.withConverter=s,o}(function(){})},r.exports=t()}),ui=zo(function(r,e){r.exports=function t(n,i,s){function a(c,u){if(!i[c]){if(!n[c]){if(!u&&ci)return ci();if(o)return o(c,!0);var h=new Error("Cannot find module '"+c+"'");throw h.code="MODULE_NOT_FOUND",h}var l=i[c]={exports:{}};n[c][0].call(l.exports,function(f){var y=n[c][1][f];return a(y||f)},l,l.exports,t,n,i,s)}return i[c].exports}for(var o=ci,d=0;d<s.length;d++)a(s[d]);return a}({1:[function(t,n,i){(function(s){var a,o,d=s.MutationObserver||s.WebKitMutationObserver;if(d){var c=0,u=new d(y),h=s.document.createTextNode("");u.observe(h,{characterData:!0}),a=function(){h.data=c=++c%2}}else if(s.setImmediate||s.MessageChannel===void 0)a="document"in s&&"onreadystatechange"in s.document.createElement("script")?function(){var C=s.document.createElement("script");C.onreadystatechange=function(){y(),C.onreadystatechange=null,C.parentNode.removeChild(C),C=null},s.document.documentElement.appendChild(C)}:function(){setTimeout(y,0)};else{var l=new s.MessageChannel;l.port1.onmessage=y,a=function(){l.port2.postMessage(0)}}var f=[];function y(){var C,v;o=!0;for(var E=f.length;E;){for(v=f,f=[],C=-1;++C<E;)v[C]();E=f.length}o=!1}n.exports=function(C){f.push(C)!==1||o||a()}}).call(this,sn!==void 0?sn:typeof self<"u"?self:typeof window<"u"?window:{})},{}],2:[function(t,n,i){var s=t(1);function a(){}var o={},d=["REJECTED"],c=["FULFILLED"],u=["PENDING"];function h(E){if(typeof E!="function")throw new TypeError("resolver must be a function");this.state=u,this.queue=[],this.outcome=void 0,E!==a&&C(this,E)}function l(E,k,g){this.promise=E,typeof k=="function"&&(this.onFulfilled=k,this.callFulfilled=this.otherCallFulfilled),typeof g=="function"&&(this.onRejected=g,this.callRejected=this.otherCallRejected)}function f(E,k,g){s(function(){var D;try{D=k(g)}catch(L){return o.reject(E,L)}D===E?o.reject(E,new TypeError("Cannot resolve promise with itself")):o.resolve(E,D)})}function y(E){var k=E&&E.then;if(E&&(typeof E=="object"||typeof E=="function")&&typeof k=="function")return function(){k.apply(E,arguments)}}function C(E,k){var g=!1;function D(M){g||(g=!0,o.reject(E,M))}function L(M){g||(g=!0,o.resolve(E,M))}var R=v(function(){k(L,D)});R.status==="error"&&D(R.value)}function v(E,k){var g={};try{g.value=E(k),g.status="success"}catch(D){g.status="error",g.value=D}return g}n.exports=h,h.prototype.catch=function(E){return this.then(null,E)},h.prototype.then=function(E,k){if(typeof E!="function"&&this.state===c||typeof k!="function"&&this.state===d)return this;var g=new this.constructor(a);return this.state!==u?f(g,this.state===c?E:k,this.outcome):this.queue.push(new l(g,E,k)),g},l.prototype.callFulfilled=function(E){o.resolve(this.promise,E)},l.prototype.otherCallFulfilled=function(E){f(this.promise,this.onFulfilled,E)},l.prototype.callRejected=function(E){o.reject(this.promise,E)},l.prototype.otherCallRejected=function(E){f(this.promise,this.onRejected,E)},o.resolve=function(E,k){var g=v(y,k);if(g.status==="error")return o.reject(E,g.value);var D=g.value;if(D)C(E,D);else{E.state=c,E.outcome=k;for(var L=-1,R=E.queue.length;++L<R;)E.queue[L].callFulfilled(k)}return E},o.reject=function(E,k){E.state=d,E.outcome=k;for(var g=-1,D=E.queue.length;++g<D;)E.queue[g].callRejected(k);return E},h.resolve=function(E){return E instanceof this?E:o.resolve(new this(a),E)},h.reject=function(E){var k=new this(a);return o.reject(k,E)},h.all=function(E){var k=this;if(Object.prototype.toString.call(E)!=="[object Array]")return this.reject(new TypeError("must be an array"));var g=E.length,D=!1;if(!g)return this.resolve([]);for(var L=new Array(g),R=0,M=-1,U=new this(a);++M<g;)G(E[M],M);return U;function G(F,q){k.resolve(F).then(function(ee){L[q]=ee,++R!==g||D||(D=!0,o.resolve(U,L))},function(ee){D||(D=!0,o.reject(U,ee))})}},h.race=function(E){var k=this;if(Object.prototype.toString.call(E)!=="[object Array]")return this.reject(new TypeError("must be an array"));var g=E.length,D=!1;if(!g)return this.resolve([]);for(var L,R=-1,M=new this(a);++R<g;)L=E[R],k.resolve(L).then(function(U){D||(D=!0,o.resolve(M,U))},function(U){D||(D=!0,o.reject(M,U))});return M}},{1:1}],3:[function(t,n,i){(function(s){typeof s.Promise!="function"&&(s.Promise=t(2))}).call(this,sn!==void 0?sn:typeof self<"u"?self:typeof window<"u"?window:{})},{2:2}],4:[function(t,n,i){var s=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(p){return typeof p}:function(p){return p&&typeof Symbol=="function"&&p.constructor===Symbol&&p!==Symbol.prototype?"symbol":typeof p},a=function(){try{if(typeof indexedDB<"u")return indexedDB;if(typeof webkitIndexedDB<"u")return webkitIndexedDB;if(typeof mozIndexedDB<"u")return mozIndexedDB;if(typeof OIndexedDB<"u")return OIndexedDB;if(typeof msIndexedDB<"u")return msIndexedDB}catch{return}}();function o(p,m){p=p||[],m=m||{};try{return new Blob(p,m)}catch(S){if(S.name!=="TypeError")throw S;for(var _=new(typeof BlobBuilder<"u"?BlobBuilder:typeof MSBlobBuilder<"u"?MSBlobBuilder:typeof MozBlobBuilder<"u"?MozBlobBuilder:WebKitBlobBuilder),w=0;w<p.length;w+=1)_.append(p[w]);return _.getBlob(m.type)}}typeof Promise>"u"&&t(3);var d=Promise;function c(p,m){m&&p.then(function(_){m(null,_)},function(_){m(_)})}function u(p,m,_){typeof m=="function"&&p.then(m),typeof _=="function"&&p.catch(_)}function h(p){return typeof p!="string"&&(console.warn(p+" used as a key, but it is not a string."),p=String(p)),p}function l(){if(arguments.length&&typeof arguments[arguments.length-1]=="function")return arguments[arguments.length-1]}var f=void 0,y={},C=Object.prototype.toString;function v(p){return typeof f=="boolean"?d.resolve(f):function(m){return new d(function(_){var w=m.transaction("local-forage-detect-blob-support","readwrite"),S=o([""]);w.objectStore("local-forage-detect-blob-support").put(S,"key"),w.onabort=function(b){b.preventDefault(),b.stopPropagation(),_(!1)},w.oncomplete=function(){var b=navigator.userAgent.match(/Chrome\/(\d+)/),A=navigator.userAgent.match(/Edge\//);_(A||!b||parseInt(b[1],10)>=43)}}).catch(function(){return!1})}(p).then(function(m){return f=m})}function E(p){var m=y[p.name],_={};_.promise=new d(function(w,S){_.resolve=w,_.reject=S}),m.deferredOperations.push(_),m.dbReady?m.dbReady=m.dbReady.then(function(){return _.promise}):m.dbReady=_.promise}function k(p){var m=y[p.name].deferredOperations.pop();if(m)return m.resolve(),m.promise}function g(p,m){var _=y[p.name].deferredOperations.pop();if(_)return _.reject(m),_.promise}function D(p,m){return new d(function(_,w){if(y[p.name]=y[p.name]||{forages:[],db:null,dbReady:null,deferredOperations:[]},p.db){if(!m)return _(p.db);E(p),p.db.close()}var S=[p.name];m&&S.push(p.version);var b=a.open.apply(a,S);m&&(b.onupgradeneeded=function(A){var I=b.result;try{I.createObjectStore(p.storeName),A.oldVersion<=1&&I.createObjectStore("local-forage-detect-blob-support")}catch(z){if(z.name!=="ConstraintError")throw z;console.warn('The database "'+p.name+'" has been upgraded from version '+A.oldVersion+" to version "+A.newVersion+', but the storage "'+p.storeName+'" already exists.')}}),b.onerror=function(A){A.preventDefault(),w(b.error)},b.onsuccess=function(){var A=b.result;A.onversionchange=function(I){I.target.close()},_(A),k(p)}})}function L(p){return D(p,!1)}function R(p){return D(p,!0)}function M(p,m){if(!p.db)return!0;var _=!p.db.objectStoreNames.contains(p.storeName),w=p.version<p.db.version,S=p.version>p.db.version;if(w&&(p.version!==m&&console.warn('The database "'+p.name+`" can't be downgraded from version `+p.db.version+" to version "+p.version+"."),p.version=p.db.version),S||_){if(_){var b=p.db.version+1;b>p.version&&(p.version=b)}return!0}return!1}function U(p){return o([function(m){for(var _=m.length,w=new ArrayBuffer(_),S=new Uint8Array(w),b=0;b<_;b++)S[b]=m.charCodeAt(b);return w}(atob(p.data))],{type:p.type})}function G(p){return p&&p.__local_forage_encoded_blob}function F(p){var m=this,_=m._initReady().then(function(){var w=y[m._dbInfo.name];if(w&&w.dbReady)return w.dbReady});return u(_,p,p),_}function q(p,m,_,w){w===void 0&&(w=1);try{var S=p.db.transaction(p.storeName,m);_(null,S)}catch(b){if(w>0&&(!p.db||b.name==="InvalidStateError"||b.name==="NotFoundError"))return d.resolve().then(function(){if(!p.db||b.name==="NotFoundError"&&!p.db.objectStoreNames.contains(p.storeName)&&p.version<=p.db.version)return p.db&&(p.version=p.db.version+1),R(p)}).then(function(){return function(A){E(A);for(var I=y[A.name],z=I.forages,P=0;P<z.length;P++){var N=z[P];N._dbInfo.db&&(N._dbInfo.db.close(),N._dbInfo.db=null)}return A.db=null,L(A).then(function(B){return A.db=B,M(A)?R(A):B}).then(function(B){A.db=I.db=B;for(var H=0;H<z.length;H++)z[H]._dbInfo.db=B}).catch(function(B){throw g(A,B),B})}(p).then(function(){q(p,m,_,w-1)})}).catch(_);_(b)}}var ee={_driver:"asyncStorage",_initStorage:function(p){var m=this,_={db:null};if(p)for(var w in p)_[w]=p[w];var S=y[_.name];S||(S={forages:[],db:null,dbReady:null,deferredOperations:[]},y[_.name]=S),S.forages.push(m),m._initReady||(m._initReady=m.ready,m.ready=F);var b=[];function A(){return d.resolve()}for(var I=0;I<S.forages.length;I++){var z=S.forages[I];z!==m&&b.push(z._initReady().catch(A))}var P=S.forages.slice(0);return d.all(b).then(function(){return _.db=S.db,L(_)}).then(function(N){return _.db=N,M(_,m._defaultConfig.version)?R(_):N}).then(function(N){_.db=S.db=N,m._dbInfo=_;for(var B=0;B<P.length;B++){var H=P[B];H!==m&&(H._dbInfo.db=_.db,H._dbInfo.version=_.version)}})},_support:function(){try{if(!a||!a.open)return!1;var p=typeof openDatabase<"u"&&/(Safari|iPhone|iPad|iPod)/.test(navigator.userAgent)&&!/Chrome/.test(navigator.userAgent)&&!/BlackBerry/.test(navigator.platform),m=typeof fetch=="function"&&fetch.toString().indexOf("[native code")!==-1;return(!p||m)&&typeof indexedDB<"u"&&typeof IDBKeyRange<"u"}catch{return!1}}(),iterate:function(p,m){var _=this,w=new d(function(S,b){_.ready().then(function(){q(_._dbInfo,"readonly",function(A,I){if(A)return b(A);try{var z=I.objectStore(_._dbInfo.storeName).openCursor(),P=1;z.onsuccess=function(){var N=z.result;if(N){var B=N.value;G(B)&&(B=U(B));var H=p(B,N.key,P++);H!==void 0?S(H):N.continue()}else S()},z.onerror=function(){b(z.error)}}catch(N){b(N)}})}).catch(b)});return c(w,m),w},getItem:function(p,m){var _=this;p=h(p);var w=new d(function(S,b){_.ready().then(function(){q(_._dbInfo,"readonly",function(A,I){if(A)return b(A);try{var z=I.objectStore(_._dbInfo.storeName).get(p);z.onsuccess=function(){var P=z.result;P===void 0&&(P=null),G(P)&&(P=U(P)),S(P)},z.onerror=function(){b(z.error)}}catch(P){b(P)}})}).catch(b)});return c(w,m),w},setItem:function(p,m,_){var w=this;p=h(p);var S=new d(function(b,A){var I;w.ready().then(function(){return I=w._dbInfo,C.call(m)==="[object Blob]"?v(I.db).then(function(z){return z?m:(P=m,new d(function(N,B){var H=new FileReader;H.onerror=B,H.onloadend=function(X){var W=btoa(X.target.result||"");N({__local_forage_encoded_blob:!0,data:W,type:P.type})},H.readAsBinaryString(P)}));var P}):m}).then(function(z){q(w._dbInfo,"readwrite",function(P,N){if(P)return A(P);try{var B=N.objectStore(w._dbInfo.storeName);z===null&&(z=void 0);var H=B.put(z,p);N.oncomplete=function(){z===void 0&&(z=null),b(z)},N.onabort=N.onerror=function(){try{var X=H.error?H.error:H.transaction.error;A(X)}catch(W){A(W)}}}catch(X){A(X)}})}).catch(A)});return c(S,_),S},removeItem:function(p,m){var _=this;p=h(p);var w=new d(function(S,b){_.ready().then(function(){q(_._dbInfo,"readwrite",function(A,I){if(A)return b(A);try{var z=I.objectStore(_._dbInfo.storeName).delete(p);I.oncomplete=function(){S()},I.onerror=function(){b(z.error)},I.onabort=function(){try{var P=z.error?z.error:z.transaction.error;b(P)}catch(N){b(N)}}}catch(P){b(P)}})}).catch(b)});return c(w,m),w},clear:function(p){var m=this,_=new d(function(w,S){m.ready().then(function(){q(m._dbInfo,"readwrite",function(b,A){if(b)return S(b);try{var I=A.objectStore(m._dbInfo.storeName).clear();A.oncomplete=function(){w()},A.onabort=A.onerror=function(){try{var z=I.error?I.error:I.transaction.error;S(z)}catch(P){S(P)}}}catch(z){S(z)}})}).catch(S)});return c(_,p),_},length:function(p){var m=this,_=new d(function(w,S){m.ready().then(function(){q(m._dbInfo,"readonly",function(b,A){if(b)return S(b);try{var I=A.objectStore(m._dbInfo.storeName).count();I.onsuccess=function(){w(I.result)},I.onerror=function(){S(I.error)}}catch(z){S(z)}})}).catch(S)});return c(_,p),_},key:function(p,m){var _=this,w=new d(function(S,b){p<0?S(null):_.ready().then(function(){q(_._dbInfo,"readonly",function(A,I){if(A)return b(A);try{var z=I.objectStore(_._dbInfo.storeName),P=!1,N=(z.openKeyCursor||z.openCursor).call(z);N.onsuccess=function(){var B=N.result;B?p===0||P?S(B.key):(P=!0,B.advance(p)):S(null)},N.onerror=function(){b(N.error)}}catch(B){b(B)}})}).catch(b)});return c(w,m),w},keys:function(p){var m=this,_=new d(function(w,S){m.ready().then(function(){q(m._dbInfo,"readonly",function(b,A){if(b)return S(b);try{var I=A.objectStore(m._dbInfo.storeName),z=(I.openKeyCursor||I.openCursor).call(I),P=[];z.onsuccess=function(){var N=z.result;N?(P.push(N.key),N.continue()):w(P)},z.onerror=function(){S(z.error)}}catch(N){S(N)}})}).catch(S)});return c(_,p),_},dropInstance:function(p,m){m=l.apply(this,arguments);var _=this.config();(p=typeof p!="function"&&p||{}).name||(p.name=p.name||_.name,p.storeName=p.storeName||_.storeName);var w,S=this;if(p.name){var b=p.name===_.name&&S._dbInfo.db,A=b?d.resolve(S._dbInfo.db):L(p).then(function(I){var z=y[p.name],P=z.forages;z.db=I;for(var N=0;N<P.length;N++)P[N]._dbInfo.db=I;return I});w=p.storeName?A.then(function(I){if(I.objectStoreNames.contains(p.storeName)){var z=I.version+1;E(p);var P=y[p.name],N=P.forages;I.close();for(var B=0;B<N.length;B++){var H=N[B];H._dbInfo.db=null,H._dbInfo.version=z}return new d(function(X,W){var pe=a.open(p.name,z);pe.onerror=function(Mt){pe.result.close(),W(Mt)},pe.onupgradeneeded=function(){pe.result.deleteObjectStore(p.storeName)},pe.onsuccess=function(){var Mt=pe.result;Mt.close(),X(Mt)}}).then(function(X){P.db=X;for(var W=0;W<N.length;W++){var pe=N[W];pe._dbInfo.db=X,k(pe._dbInfo)}}).catch(function(X){throw(g(p,X)||d.resolve()).catch(function(){}),X})}}):A.then(function(I){E(p);var z=y[p.name],P=z.forages;I.close();for(var N=0;N<P.length;N++)P[N]._dbInfo.db=null;return new d(function(B,H){var X=a.deleteDatabase(p.name);X.onerror=function(){var W=X.result;W&&W.close(),H(X.error)},X.onblocked=function(){console.warn('dropInstance blocked for database "'+p.name+'" until all open connections are closed')},X.onsuccess=function(){var W=X.result;W&&W.close(),B(W)}}).then(function(B){z.db=B;for(var H=0;H<P.length;H++)k(P[H]._dbInfo)}).catch(function(B){throw(g(p,B)||d.resolve()).catch(function(){}),B})})}else w=d.reject("Invalid arguments");return c(w,m),w}},J="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",ve=/^~~local_forage_type~([^~]+)~/,he=9,Me=he+4,Le=Object.prototype.toString;function Ne(p){var m,_,w,S,b,A=.75*p.length,I=p.length,z=0;p[p.length-1]==="="&&(A--,p[p.length-2]==="="&&A--);var P=new ArrayBuffer(A),N=new Uint8Array(P);for(m=0;m<I;m+=4)_=J.indexOf(p[m]),w=J.indexOf(p[m+1]),S=J.indexOf(p[m+2]),b=J.indexOf(p[m+3]),N[z++]=_<<2|w>>4,N[z++]=(15&w)<<4|S>>2,N[z++]=(3&S)<<6|63&b;return P}function Ie(p){var m,_=new Uint8Array(p),w="";for(m=0;m<_.length;m+=3)w+=J[_[m]>>2],w+=J[(3&_[m])<<4|_[m+1]>>4],w+=J[(15&_[m+1])<<2|_[m+2]>>6],w+=J[63&_[m+2]];return _.length%3==2?w=w.substring(0,w.length-1)+"=":_.length%3==1&&(w=w.substring(0,w.length-2)+"=="),w}var ze={serialize:function(p,m){var _="";if(p&&(_=Le.call(p)),p&&(_==="[object ArrayBuffer]"||p.buffer&&Le.call(p.buffer)==="[object ArrayBuffer]")){var w,S="__lfsc__:";p instanceof ArrayBuffer?(w=p,S+="arbf"):(w=p.buffer,_==="[object Int8Array]"?S+="si08":_==="[object Uint8Array]"?S+="ui08":_==="[object Uint8ClampedArray]"?S+="uic8":_==="[object Int16Array]"?S+="si16":_==="[object Uint16Array]"?S+="ur16":_==="[object Int32Array]"?S+="si32":_==="[object Uint32Array]"?S+="ui32":_==="[object Float32Array]"?S+="fl32":_==="[object Float64Array]"?S+="fl64":m(new Error("Failed to get type for BinaryArray"))),m(S+Ie(w))}else if(_==="[object Blob]"){var b=new FileReader;b.onload=function(){var A="~~local_forage_type~"+p.type+"~"+Ie(this.result);m("__lfsc__:blob"+A)},b.readAsArrayBuffer(p)}else try{m(JSON.stringify(p))}catch(A){console.error("Couldn't convert value into a JSON string: ",p),m(null,A)}},deserialize:function(p){if(p.substring(0,he)!=="__lfsc__:")return JSON.parse(p);var m,_=p.substring(Me),w=p.substring(he,Me);if(w==="blob"&&ve.test(_)){var S=_.match(ve);m=S[1],_=_.substring(S[0].length)}var b=Ne(_);switch(w){case"arbf":return b;case"blob":return o([b],{type:m});case"si08":return new Int8Array(b);case"ui08":return new Uint8Array(b);case"uic8":return new Uint8ClampedArray(b);case"si16":return new Int16Array(b);case"ur16":return new Uint16Array(b);case"si32":return new Int32Array(b);case"ui32":return new Uint32Array(b);case"fl32":return new Float32Array(b);case"fl64":return new Float64Array(b);default:throw new Error("Unkown type: "+w)}},stringToBuffer:Ne,bufferToString:Ie};function Ue(p,m,_,w){p.executeSql("CREATE TABLE IF NOT EXISTS "+m.storeName+" (id INTEGER PRIMARY KEY, key unique, value)",[],_,w)}function be(p,m,_,w,S,b){p.executeSql(_,w,S,function(A,I){I.code===I.SYNTAX_ERR?A.executeSql("SELECT name FROM sqlite_master WHERE type='table' AND name = ?",[m.storeName],function(z,P){P.rows.length?b(z,I):Ue(z,m,function(){z.executeSql(_,w,S,b)},b)},b):b(A,I)},b)}function mt(p,m,_,w){var S=this;p=h(p);var b=new d(function(A,I){S.ready().then(function(){m===void 0&&(m=null);var z=m,P=S._dbInfo;P.serializer.serialize(m,function(N,B){B?I(B):P.db.transaction(function(H){be(H,P,"INSERT OR REPLACE INTO "+P.storeName+" (key, value) VALUES (?, ?)",[p,N],function(){A(z)},function(X,W){I(W)})},function(H){if(H.code===H.QUOTA_ERR){if(w>0)return void A(mt.apply(S,[p,z,_,w-1]));I(H)}})})}).catch(I)});return c(b,_),b}function Ot(p){return new d(function(m,_){p.transaction(function(w){w.executeSql("SELECT name FROM sqlite_master WHERE type='table' AND name <> '__WebKitDatabaseInfoTable__'",[],function(S,b){for(var A=[],I=0;I<b.rows.length;I++)A.push(b.rows.item(I).name);m({db:p,storeNames:A})},function(S,b){_(b)})},function(w){_(w)})})}var Pt={_driver:"webSQLStorage",_initStorage:function(p){var m=this,_={db:null};if(p)for(var w in p)_[w]=typeof p[w]!="string"?p[w].toString():p[w];var S=new d(function(b,A){try{_.db=openDatabase(_.name,String(_.version),_.description,_.size)}catch(I){return A(I)}_.db.transaction(function(I){Ue(I,_,function(){m._dbInfo=_,b()},function(z,P){A(P)})},A)});return _.serializer=ze,S},_support:typeof openDatabase=="function",iterate:function(p,m){var _=this,w=new d(function(S,b){_.ready().then(function(){var A=_._dbInfo;A.db.transaction(function(I){be(I,A,"SELECT * FROM "+A.storeName,[],function(z,P){for(var N=P.rows,B=N.length,H=0;H<B;H++){var X=N.item(H),W=X.value;if(W&&(W=A.serializer.deserialize(W)),(W=p(W,X.key,H+1))!==void 0)return void S(W)}S()},function(z,P){b(P)})})}).catch(b)});return c(w,m),w},getItem:function(p,m){var _=this;p=h(p);var w=new d(function(S,b){_.ready().then(function(){var A=_._dbInfo;A.db.transaction(function(I){be(I,A,"SELECT * FROM "+A.storeName+" WHERE key = ? LIMIT 1",[p],function(z,P){var N=P.rows.length?P.rows.item(0).value:null;N&&(N=A.serializer.deserialize(N)),S(N)},function(z,P){b(P)})})}).catch(b)});return c(w,m),w},setItem:function(p,m,_){return mt.apply(this,[p,m,_,1])},removeItem:function(p,m){var _=this;p=h(p);var w=new d(function(S,b){_.ready().then(function(){var A=_._dbInfo;A.db.transaction(function(I){be(I,A,"DELETE FROM "+A.storeName+" WHERE key = ?",[p],function(){S()},function(z,P){b(P)})})}).catch(b)});return c(w,m),w},clear:function(p){var m=this,_=new d(function(w,S){m.ready().then(function(){var b=m._dbInfo;b.db.transaction(function(A){be(A,b,"DELETE FROM "+b.storeName,[],function(){w()},function(I,z){S(z)})})}).catch(S)});return c(_,p),_},length:function(p){var m=this,_=new d(function(w,S){m.ready().then(function(){var b=m._dbInfo;b.db.transaction(function(A){be(A,b,"SELECT COUNT(key) as c FROM "+b.storeName,[],function(I,z){var P=z.rows.item(0).c;w(P)},function(I,z){S(z)})})}).catch(S)});return c(_,p),_},key:function(p,m){var _=this,w=new d(function(S,b){_.ready().then(function(){var A=_._dbInfo;A.db.transaction(function(I){be(I,A,"SELECT key FROM "+A.storeName+" WHERE id = ? LIMIT 1",[p+1],function(z,P){var N=P.rows.length?P.rows.item(0).key:null;S(N)},function(z,P){b(P)})})}).catch(b)});return c(w,m),w},keys:function(p){var m=this,_=new d(function(w,S){m.ready().then(function(){var b=m._dbInfo;b.db.transaction(function(A){be(A,b,"SELECT key FROM "+b.storeName,[],function(I,z){for(var P=[],N=0;N<z.rows.length;N++)P.push(z.rows.item(N).key);w(P)},function(I,z){S(z)})})}).catch(S)});return c(_,p),_},dropInstance:function(p,m){m=l.apply(this,arguments);var _=this.config();(p=typeof p!="function"&&p||{}).name||(p.name=p.name||_.name,p.storeName=p.storeName||_.storeName);var w,S=this;return c(w=p.name?new d(function(b){var A;A=p.name===_.name?S._dbInfo.db:openDatabase(p.name,"","",0),p.storeName?b({db:A,storeNames:[p.storeName]}):b(Ot(A))}).then(function(b){return new d(function(A,I){b.db.transaction(function(z){function P(X){return new d(function(W,pe){z.executeSql("DROP TABLE IF EXISTS "+X,[],function(){W()},function(Mt,Br){pe(Br)})})}for(var N=[],B=0,H=b.storeNames.length;B<H;B++)N.push(P(b.storeNames[B]));d.all(N).then(function(){A()}).catch(function(X){I(X)})},function(z){I(z)})})}):d.reject("Invalid arguments"),m),w}};function Ur(p,m){var _=p.name+"/";return p.storeName!==m.storeName&&(_+=p.storeName+"/"),_}function Tn(){return!function(){try{return localStorage.setItem("_localforage_support_test",!0),localStorage.removeItem("_localforage_support_test"),!1}catch{return!0}}()||localStorage.length>0}var kn={_driver:"localStorageWrapper",_initStorage:function(p){var m={};if(p)for(var _ in p)m[_]=p[_];return m.keyPrefix=Ur(p,this._defaultConfig),Tn()?(this._dbInfo=m,m.serializer=ze,d.resolve()):d.reject()},_support:function(){try{return typeof localStorage<"u"&&"setItem"in localStorage&&!!localStorage.setItem}catch{return!1}}(),iterate:function(p,m){var _=this,w=_.ready().then(function(){for(var S=_._dbInfo,b=S.keyPrefix,A=b.length,I=localStorage.length,z=1,P=0;P<I;P++){var N=localStorage.key(P);if(N.indexOf(b)===0){var B=localStorage.getItem(N);if(B&&(B=S.serializer.deserialize(B)),(B=p(B,N.substring(A),z++))!==void 0)return B}}});return c(w,m),w},getItem:function(p,m){var _=this;p=h(p);var w=_.ready().then(function(){var S=_._dbInfo,b=localStorage.getItem(S.keyPrefix+p);return b&&(b=S.serializer.deserialize(b)),b});return c(w,m),w},setItem:function(p,m,_){var w=this;p=h(p);var S=w.ready().then(function(){m===void 0&&(m=null);var b=m;return new d(function(A,I){var z=w._dbInfo;z.serializer.serialize(m,function(P,N){if(N)I(N);else try{localStorage.setItem(z.keyPrefix+p,P),A(b)}catch(B){B.name!=="QuotaExceededError"&&B.name!=="NS_ERROR_DOM_QUOTA_REACHED"||I(B),I(B)}})})});return c(S,_),S},removeItem:function(p,m){var _=this;p=h(p);var w=_.ready().then(function(){var S=_._dbInfo;localStorage.removeItem(S.keyPrefix+p)});return c(w,m),w},clear:function(p){var m=this,_=m.ready().then(function(){for(var w=m._dbInfo.keyPrefix,S=localStorage.length-1;S>=0;S--){var b=localStorage.key(S);b.indexOf(w)===0&&localStorage.removeItem(b)}});return c(_,p),_},length:function(p){var m=this.keys().then(function(_){return _.length});return c(m,p),m},key:function(p,m){var _=this,w=_.ready().then(function(){var S,b=_._dbInfo;try{S=localStorage.key(p)}catch{S=null}return S&&(S=S.substring(b.keyPrefix.length)),S});return c(w,m),w},keys:function(p){var m=this,_=m.ready().then(function(){for(var w=m._dbInfo,S=localStorage.length,b=[],A=0;A<S;A++){var I=localStorage.key(A);I.indexOf(w.keyPrefix)===0&&b.push(I.substring(w.keyPrefix.length))}return b});return c(_,p),_},dropInstance:function(p,m){if(m=l.apply(this,arguments),!(p=typeof p!="function"&&p||{}).name){var _=this.config();p.name=p.name||_.name,p.storeName=p.storeName||_.storeName}var w,S=this;return c(w=p.name?new d(function(b){p.storeName?b(Ur(p,S._defaultConfig)):b(p.name+"/")}).then(function(b){for(var A=localStorage.length-1;A>=0;A--){var I=localStorage.key(A);I.indexOf(b)===0&&localStorage.removeItem(I)}}):d.reject("Invalid arguments"),m),w}},Rn=function(p,m){for(var _,w,S=p.length,b=0;b<S;){if((_=p[b])===(w=m)||typeof _=="number"&&typeof w=="number"&&isNaN(_)&&isNaN(w))return!0;b++}return!1},Gr=Array.isArray||function(p){return Object.prototype.toString.call(p)==="[object Array]"},_t={},gt={},$e={INDEXEDDB:ee,WEBSQL:Pt,LOCALSTORAGE:kn},Yt=[$e.INDEXEDDB._driver,$e.WEBSQL._driver,$e.LOCALSTORAGE._driver],vt=["dropInstance"],yt=["clear","getItem","iterate","key","keys","length","removeItem","setItem"].concat(vt),rs={description:"",driver:Yt.slice(),name:"localforage",size:4980736,storeName:"keyvaluepairs",version:1};function ns(p,m){p[m]=function(){var _=arguments;return p.ready().then(function(){return p[m].apply(p,_)})}}function is(){for(var p=1;p<arguments.length;p++){var m=arguments[p];if(m)for(var _ in m)m.hasOwnProperty(_)&&(Gr(m[_])?arguments[0][_]=m[_].slice():arguments[0][_]=m[_])}return arguments[0]}var fg=new(function(){function p(m){for(var _ in function(b,A){if(!(b instanceof A))throw new TypeError("Cannot call a class as a function")}(this,p),$e)if($e.hasOwnProperty(_)){var w=$e[_],S=w._driver;this[_]=S,_t[S]||this.defineDriver(w)}this._defaultConfig=is({},rs),this._config=is({},this._defaultConfig,m),this._driverSet=null,this._initDriver=null,this._ready=!1,this._dbInfo=null,this._wrapLibraryMethodsWithReady(),this.setDriver(this._config.driver).catch(function(){})}return p.prototype.config=function(m){if((m===void 0?"undefined":s(m))==="object"){if(this._ready)return new Error("Can't call config() after localforage has been used.");for(var _ in m){if(_==="storeName"&&(m[_]=m[_].replace(/\W/g,"_")),_==="version"&&typeof m[_]!="number")return new Error("Database version must be a number.");this._config[_]=m[_]}return!("driver"in m)||!m.driver||this.setDriver(this._config.driver)}return typeof m=="string"?this._config[m]:this._config},p.prototype.defineDriver=function(m,_,w){var S=new d(function(b,A){try{var I=m._driver,z=new Error("Custom driver not compliant; see https://mozilla.github.io/localForage/#definedriver");if(!m._driver)return void A(z);for(var P=yt.concat("_initStorage"),N=0,B=P.length;N<B;N++){var H=P[N];if((!Rn(vt,H)||m[H])&&typeof m[H]!="function")return void A(z)}(function(){for(var W=function(mg){return function(){var _g=new Error("Method "+mg+" is not implemented by the current driver"),Bc=d.reject(_g);return c(Bc,arguments[arguments.length-1]),Bc}},pe=0,Mt=vt.length;pe<Mt;pe++){var Br=vt[pe];m[Br]||(m[Br]=W(Br))}})();var X=function(W){_t[I]&&console.info("Redefining LocalForage driver: "+I),_t[I]=m,gt[I]=W,b()};"_support"in m?m._support&&typeof m._support=="function"?m._support().then(X,A):X(!!m._support):X(!0)}catch(W){A(W)}});return u(S,_,w),S},p.prototype.driver=function(){return this._driver||null},p.prototype.getDriver=function(m,_,w){var S=_t[m]?d.resolve(_t[m]):d.reject(new Error("Driver not found."));return u(S,_,w),S},p.prototype.getSerializer=function(m){var _=d.resolve(ze);return u(_,m),_},p.prototype.ready=function(m){var _=this,w=_._driverSet.then(function(){return _._ready===null&&(_._ready=_._initDriver()),_._ready});return u(w,m,m),w},p.prototype.setDriver=function(m,_,w){var S=this;Gr(m)||(m=[m]);var b=this._getSupportedDrivers(m);function A(){S._config.driver=S.driver()}function I(P){return S._extend(P),A(),S._ready=S._initStorage(S._config),S._ready}var z=this._driverSet!==null?this._driverSet.catch(function(){return d.resolve()}):d.resolve();return this._driverSet=z.then(function(){var P=b[0];return S._dbInfo=null,S._ready=null,S.getDriver(P).then(function(N){S._driver=N._driver,A(),S._wrapLibraryMethodsWithReady(),S._initDriver=function(B){return function(){var H=0;return function X(){for(;H<B.length;){var W=B[H];return H++,S._dbInfo=null,S._ready=null,S.getDriver(W).then(I).catch(X)}A();var pe=new Error("No available storage method found.");return S._driverSet=d.reject(pe),S._driverSet}()}}(b)})}).catch(function(){A();var P=new Error("No available storage method found.");return S._driverSet=d.reject(P),S._driverSet}),u(this._driverSet,_,w),this._driverSet},p.prototype.supports=function(m){return!!gt[m]},p.prototype._extend=function(m){is(this,m)},p.prototype._getSupportedDrivers=function(m){for(var _=[],w=0,S=m.length;w<S;w++){var b=m[w];this.supports(b)&&_.push(b)}return _},p.prototype._wrapLibraryMethodsWithReady=function(){for(var m=0,_=yt.length;m<_;m++)ns(this,yt[m])},p.prototype.createInstance=function(m){return new p(m)},p}());n.exports=fg},{3:3}]},{},[4])(4)}),uf=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}(),df=function(){function r(){this.support=this.isSupportLS()}return r.prototype.isSupportLS=function(){try{return localStorage.setItem("_applogtest-test-key","hi"),localStorage.getItem("_applogtest-test-key"),localStorage.removeItem("_applogtest-test-key"),!0}catch{return!1}},r.prototype.getItem=function(e){try{var t=localStorage.getItem(e),n=t;try{t&&typeof t=="string"&&(n=JSON.parse(t))}catch{}return n||{}}catch{}return{}},r.prototype.setItem=function(e,t){try{var n=typeof t=="string"?t:JSON.stringify(t);localStorage.setItem(e,n)}catch{}},r.prototype.removeItem=function(e){try{localStorage.removeItem(e)}catch{}},r}(),lf=function(){function r(){this.support=this.isSupportSession()}return r.prototype.isSupportSession=function(){try{return sessionStorage.setItem("_applogtest-test-key","hi"),sessionStorage.getItem("_applogtest-test-key"),sessionStorage.removeItem("_applogtest-test-key"),!0}catch{return!1}},r.prototype.getItem=function(e){try{var t=sessionStorage.getItem(e),n=t;try{t&&typeof t=="string"&&(n=JSON.parse(t))}catch{}return n||{}}catch{}return{}},r.prototype.setItem=function(e,t){try{var n=typeof t=="string"?t:JSON.stringify(t);sessionStorage.setItem(e,n)}catch{}},r.prototype.removeItem=function(e){try{sessionStorage.removeItem(e)}catch{}},r}(),hf=function(){function r(e,t){return this.dbStorage=ui.createInstance({driver:[ui.INDEXEDDB,ui.LOCALSTORAGE],name:e,storeName:t}),this.dbStorage}return r.prototype.getItem=function(e){return ii(this,void 0,void 0,function(){var t,n;return si(this,function(i){switch(i.label){case 0:return i.trys.push([0,2,,3]),[4,this.dbStorage.getItem(e)];case 1:t=i.sent(),n=t;try{t&&typeof t=="string"&&(n=JSON.parse(t))}catch{}return[2,n||void 0];case 2:return i.sent(),console.warn("db get storage error"),[3,3];case 3:return[2,void 0]}})})},r.prototype.setItem=function(e,t){try{this.dbStorage.setItem(e,t)}catch{console.warn("db set storage error")}},r.prototype.removeItem=function(e){try{this.dbStorage.removeItem(e)}catch{console.warn("db remove storage error")}},r}(),pf=function(){function r(){this.defaultExpireTime=6048e5,this.local=new df,this.session=new lf,this.cache=new uf}return r.prototype.getLocalItem=function(e){return this.local.getItem(e)},r.prototype.setLocalItem=function(e,t){this.local.setItem(e,t)},r.prototype.removeLocalItem=function(e){this.local.removeItem(e)},r.prototype.getSessionItem=function(e){return this.session.getItem(e)},r.prototype.setSessionItem=function(e,t){this.session.setItem(e,t)},r.prototype.removeSessionItem=function(e){this.session.removeItem(e)},r.prototype.getCacheItem=function(e){return this.cache.getItem(e)},r.prototype.setCacheItem=function(e,t){this.cache.setItem(e,t)},r.prototype.removeCacheItem=function(e){this.cache.removeItem(e)},r.prototype.getCookie=function(e,t){try{return pr.get(e)}catch{return""}},r.prototype.setCookie=function(e,t,n,i){n===void 0&&(n=this.defaultExpireTime);try{var s=i||document.domain,a=+new Date+n;pr.set(e,t,{expires:new Date(a),path:"/",domain:s})}catch{}},r.prototype.removeCookie=function(e,t){try{pr.remove(e,{path:"/",domain:t||""})}catch{}},r}(),ff=function(){function r(e,t,n){this.appid=e,this.domain=t,this.userAgent=window.navigator.userAgent,this.appVersion=window.navigator.appVersion,this.cookie_expire=n}return r.prototype.init=function(){var e,t=window.navigator.userAgent,n=window.navigator.language,i=document.referrer,s=i?ai(i).hostname:"",a=nn(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(h,l,f,y){var C=new pf,v=h?"_tea_utm_cache_"+h:"_tea_utm_cache",E=h?"_$utm_from_url_"+h:"_$utm_from_url",k={},g=["tr_shareuser","tr_admaster","tr_param1","tr_param2","tr_param3","tr_param4","$utm_from_url"],D={ad_id:Number(l.ad_id)||void 0,campaign_id:Number(l.campaign_id)||void 0,creative_id:Number(l.creative_id)||void 0,utm_source:l.utm_source,utm_medium:l.utm_medium,utm_campaign:l.utm_campaign,utm_term:l.utm_term,utm_content:l.utm_content,tr_shareuser:l.tr_shareuser,tr_admaster:l.tr_admaster,tr_param1:l.tr_param1,tr_param2:l.tr_param2,tr_param3:l.tr_param3,tr_param4:l.tr_param4};try{var L=!1;for(var R in D)D[R]&&(g.indexOf(R)!==-1?(k.hasOwnProperty("tracer_data")||(k.tracer_data={}),k.tracer_data[R]=D[R]):k[R]=D[R],L=!0);if(L)C.setSessionItem(E,"1"),C.setCookie(v,JSON.stringify(k),y,f);else{var M=C.getCookie(v,f);M&&(k=JSON.parse(M))}C.getSessionItem(E)==1&&(k.hasOwnProperty("tracer_data")||(k.tracer_data={}),k.tracer_data.$utm_from_url=1)}catch{return D}return k}(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:n,referrer:i,referrer_host:s,network_type:d,utm:this.utm,latest_data:this.last(i,s)}},r.prototype.last=function(e,t){var n="",i="",s="",a=location.hostname,o=!1;if(e&&t&&a!==t){n=e,i=t,o=!0;var d=nn(e);d.keyword&&(s=d.keyword)}return{$latest_referrer:n,$latest_referrer_host:i,$latest_search_keyword:s,isLast:o}},r.prototype.browser=function(){var e,t,n="",i=""+parseFloat(this.appVersion),s=this.userAgent;return s.indexOf("Edge")!==-1||s.indexOf("Edg")!==-1?(n="Microsoft Edge",s.indexOf("Edge")!==-1?(e=s.indexOf("Edge"),i=s.substring(e+5)):(e=s.indexOf("Edg"),i=s.substring(e+4))):(e=s.indexOf("MSIE"))!==-1?(n="Microsoft Internet Explorer",i=s.substring(e+5)):(e=s.indexOf("Lark"))!==-1?(n="Lark",i=s.substring(e+5,e+11)):s.indexOf("Chrome")!==-1?(e=s.indexOf("TTWebView"))!==-1?(n="TTWebView",i=s.substring(e+10,e+23)):((e=s.indexOf("Chrome"))!==-1||(e=s.indexOf("Chrome"))!==-1)&&(n="Chrome",i=s.substring(e+7)):s.indexOf("Safari")!==-1?(e=s.indexOf("Safari"))!==-1&&(n="Safari",i=s.substring(e+7),(e=s.indexOf("Version"))!==-1&&(i=s.substring(e+8))):(e=s.indexOf("Firefox"))!==-1&&(n="Firefox",i=s.substring(e+8)),(t=i.indexOf(";"))!==-1&&(i=i.substring(0,t)),(t=i.indexOf(" "))!==-1&&(i=i.substring(0,t)),(t=i.indexOf(")"))!==-1&&(i=i.substring(0,t)),{browser:n,browser_version:i}},r.prototype.os=function(){for(var e="",t="",n=[{s:"Windows 10",r:/(Windows 10.0|Windows NT 10.0|Windows NT 10.1)/},{s:"Windows 8.1",r:/(Windows 8.1|Windows NT 6.3)/},{s:"Windows 8",r:/(Windows 8|Windows NT 6.2)/},{s:"Windows 7",r:/(Windows 7|Windows NT 6.1)/},{s:"Android",r:/Android/},{s:"iOS",r:/(iPhone|iPad|iPod)/},{s:"Mac OS X",r:/Mac OS X/},{s:"Mac OS",r:/(MacPPC|MacIntel|Mac_PowerPC|Macintosh)/},{s:"ChromeOS",r:/CrOS/},{s:"Linux",r:/(Linux|X11)/},{s:"Sun OS",r:/SunOS/}],i=0;i<n.length;i++){var s=n[i];if(s.r.test(this.userAgent)){(e=s.s)==="Mac OS X"&&this.isNewIpad()&&(e="iOS");break}}var a=function(h,l){var f=h.exec(l);return f&&f[1]?f[1]:""},o=function(h,l){var f=RegExp("(?:^|[^A-Z0-9-_]|[^A-Z0-9-]_|sprd-)(?:"+h+")","i").exec(l);return f?f.slice(1)[0]:""};/Windows/.test(e)&&(t=a(/Windows (.*)/,e),e="windows");var d,c;switch(e){case"Mac OS X":t=o("Mac[ +]OS[ +]X(?:[ /](?:Version )?(\\d+(?:[_\\.]\\d+)+))?",this.userAgent),e="mac";break;case"Android":d=this.userAgent,(c=a(/Android ([\.\_\d]+)/,d))||(c=a(/Android\/([\.\_\d]+)/,d)),t=c,e="android";break;case"iOS":t=this.isNewIpad()?o("Mac[ +]OS[ +]X(?:[ /](?:Version )?(\\d+(?:[_\\.]\\d+)+))?",this.userAgent):(t=/OS (\d+)_(\d+)_?(\d+)?/.exec(this.appVersion))?t[1]+"."+t[2]+"."+(0|t[3]):"",e="ios";break;case"chromeOS":var u=this.userAgent.indexOf("x86_64");t=this.userAgent.substring(u+7,u+16)}return{os_name:e,os_version:t}},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 n=navigator.userAgent.replace("Mozilla/5.0 (",""),i=n.indexOf(";");t=n.slice(0,i)}}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}(),di=function(r,e){try{return pr.get(r)}catch{return""}},li=function(r,e,t,n){try{var i=n||document.domain,s=+new Date+(t||6048e5);pr.set(r,e,{expires:new Date(s),path:"/",domain:i})}catch{}},mf=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 di(e)},r.prototype.setCookie=function(e,t,n,i){li(e,t,n,i)},r}(),hi,T,Oo={getItem:function(r){try{var e=localStorage.getItem(r),t=e;try{e&&typeof e=="string"&&(t=JSON.parse(e))}catch{}return t||{}}catch{}return{}},setItem:function(r,e){try{var t=typeof e=="string"?e:JSON.stringify(e);localStorage.setItem(r,t)}catch{}},removeItem:function(r){try{localStorage.removeItem(r)}catch{}},getCookie:function(r,e){return di(r)},setCookie:function(r,e,t,n){li(r,e,t,n)},isSupportLS:function(){try{return localStorage.setItem("_ranger-test-key","hi"),localStorage.getItem("_ranger-test-key"),localStorage.removeItem("_ranger-test-key"),!0}catch{return!1}}()},_f={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 di(r)},setCookie:function(r,e,t,n){li(r,e,t,n)},isSupportSession:function(){try{return sessionStorage.setItem("_ranger-test-key","hi"),sessionStorage.getItem("_ranger-test-key"),sessionStorage.removeItem("_ranger-test-key"),!0}catch{return!1}}()},wt=function(){function r(e,t){this._storage=t&&t==="session"?_f:!e&&Oo.isSupportLS?Oo:new mf}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,n,i){this._storage.setCookie(e,t,n,i)},r.prototype.removeItem=function(e){this._storage.removeItem(e)},r}(),pi={sg_central:"1fz22z22z1nz21z4mz4bz4bz21z1ez18z1jz1gz49z1kz1az21z4az19z27z22z1cz1mz24z1cz20z21z1cz18z4az1az1mz1k",us_east:"1fz22z22z1nz21z4mz4bz4bz1kz18z1jz1gz24z18z49z1kz1az21z4az19z27z22z1cz1mz24z1cz20z21z1cz18z4az1az1mz1k",sg_central_tt:"1fz22z22z1nz21z4mz4bz4bz1kz1az21z49z21z1ez4az22z1gz1iz22z1mz1iz24z4az1az1mz1k",us_east_tt:"1fz22z22z1nz21z4mz4bz4bz1kz1az21z49z24z18z4az22z1gz1iz22z1mz1iz24z4az1az1mz1k",us_ttp:"1fz22z22z1nz21z4mz4bz4bz1kz1az21z4az22z1gz1iz22z1mz1iz24z4az23z21",us_ttp_w:"1fz22z22z1nz21z4mz4bz4bz1kz1az21z4az22z1gz1iz22z1mz1iz25z4az23z21",us_ttp2:"1fz22z22z1nz21z4mz4bz4bz1kz1az21z49z22z22z1nz4ez4az23z21z4az22z1gz1iz22z1mz1iz4az1az1mz1k",eu_ttp_gcp:"1fz22z22z1nz21z4mz4bz4bz1kz1az21z49z24z18z49z23z21z1cz18z21z22z4ez18z4az22z1gz1iz22z1mz1iz24z4az1az1mz1k",eu_central:"1fz22z22z1nz21z4mz4bz4bz18z25z21z1dz20z49z1kz1az21z4az19z27z22z1cz1gz1lz22z1jz18z1nz1gz4az1az1mz1k",eu_ttp_ie2:"1fz22z22z1nz21z4mz4bz4bz1kz1az21z49z1gz1cz4ez4az22z1gz1iz22z1mz1iz25z4az1cz23",eu_ttp2:"1fz22z22z1nz21z4mz4bz4bz1kz1az21z4dz4iz49z1lz1mz20z1kz18z1jz49z1lz1mz4dz18z4az22z1gz1iz22z1mz1iz25z4az1cz23"},Po=function(){return new Set(Object.keys(pi))},fi=function(){return Object.keys(pi)},Mo={sg:"1fz22z22z1nz21z4mz4bz4bz21z1ez18z1jz1gz49z1kz1az21z4az19z27z22z1cz1mz24z1cz20z21z1cz18z4az1az1mz1k",va:"1fz22z22z1nz21z4mz4bz4bz1kz18z1jz1gz24z18z49z1kz1az21z4az19z27z22z1cz1mz24z1cz20z21z1cz18z4az1az1mz1k",my:"1fz22z22z1nz21z4mz4bz4bz1kz1az21z49z19z1bz49z1kz27z4az1jz18z20z1iz1mz1dz1dz1gz1az1cz4az1az1mz1k"},mi={va:"1fz22z22z1nz21z4mz4bz4bz22z1mz19z1jz1mz1ez4az1gz22z1mz19z21z1lz21z21z1bz1iz4az1az1mz1k",sg:"1fz22z22z1nz21z4mz4bz4bz22z1mz19z1jz1mz1ez4az22z1mz19z21z1lz21z21z1bz1iz4az1az1mz1k",in:"1fz22z22z1nz21z4mz4bz4bz22z1mz19z1jz1mz1ez4az1gz22z1mz19z21z1lz21z21z1bz1iz4az1az1mz1k"},gf={sg:"1fz22z22z1nz21z4mz4bz4bz1kz1az21z49z21z1ez4az22z1gz1iz22z1mz1iz24z4az1az1mz1k",va:"1fz22z22z1nz21z4mz4bz4bz1kz1az21z49z24z18z4az22z1gz1iz22z1mz1iz24z4az1az1mz1k",in:"1fz22z22z1nz21z4mz4bz4bz1kz1az21z49z24z18z49z23z21z1cz18z21z22z4ez18z4az22z1gz1iz22z1mz1iz24z4az1az1mz1k",ie2:"1fz22z22z1nz21z4mz4bz4bz1kz1az21z49z1gz1cz4ez4az22z1gz1iz22z1mz1iz25z4az1cz23"},vf={sg:"1fz22z22z1nz21z4mz4bz4bz1kz1az21z4az22z1gz1iz22z1mz1iz25z4az23z21",va:"1fz22z22z1nz21z4mz4bz4bz1kz1az21z4az22z1gz1iz22z1mz1iz24z4az23z21",ie2:"1fz22z22z1nz21z4mz4bz4bz1kz1az21z49z1gz1cz4ez4az22z1gz1iz22z1mz1iz25z4az1cz23"},fr="5.3.11_oversea",yf=["1fz22z22z1nz21z4mz4bz4bz1bz18z22z18z4az19z27z22z1cz1bz18z1lz1az1cz4az1lz1cz22","1fz22z22z1nz21z4mz4bz4bz22z1cz18z49z24z18z4az22z1gz1iz22z1mz1iz49z20z1mz25z4az1lz1cz22","1fz22z22z1nz21z4mz4bz4bz22z1cz18z4az22z1gz1iz22z1mz1iz49z1cz23z4az1lz1cz22","1fz22z22z1nz21z4mz4bz4bz22z1cz18z4az22z1gz1iz22z1mz1iz49z23z21z22z21z4az1lz1cz22","1fz22z22z1nz21z4mz4bz4bz1gz1mz49z21z1ez4az22z1gz1iz22z1mz1iz49z20z1mz25z4az1lz1cz22","1fz22z22z1nz21z4mz4bz4bz1gz1mz49z24z18z4az22z1gz1iz22z1mz1iz49z20z1mz25z4az1lz1cz22"].map(function(r){return lr(r)});(function(r){r.Init="init",r.Config="config",r.Start="start",r.Ready="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-deviceid",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.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.DestoryInstance="destory-instance",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.TrackEventDuration="track-event-duration",r.TrackEventDurationStart="track-event-duration-start",r.TrackEventDurationEnd="track-event-duration-end",r.TrackEventDurationPause="track-event-duration-pause",r.TrackEventDurationResume="tracl-event-duration-resume",r.VisualCollectReady="visual-collect-ready",r.VisualApiReady="visual-api-ready",r.VisualApiUpdate="visual-api-update"})(hi||(hi={})),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"}(T||(T={}));var x=hi,Z=void 0,Lo=new Date().getTimezoneOffset(),Sf=parseInt(""+-Lo/60,10),bf=60*Lo,Ef=function(){function r(e,t){var n=this;this.is_first_time=!0,this.configPersist=!1,this.initConfig=t,this.collect=e;var i=new ff(t.app_id,t.cookie_domain||"",t.cookie_expire||6048e5).init(),s="__tea_cache_first_"+t.app_id;this.configKey="__tea_cache_config_"+t.app_id,this.sessionStorage=new wt(!1,"session"),this.localStorage=new wt(!1,"local"),this.channelUrl=this.getChannelForUrl(),this.current_env="row",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:Z,user_type:Z,user_id:Z,user_is_auth:Z,user_is_login:Z,device_id:Z,web_id:Z,ip_addr_id:Z,user_unique_id_type:Z},header:{app_id:Z,app_name:Z,app_install_id:Z,install_id:Z,app_package:Z,app_channel:Z,app_version:Z,ab_version:Z,os_name:i.os_name,os_version:i.os_version,device_model:i.device_model,ab_client:Z,traffic_type:Z,network_type:i.network_type,client_ip:Z,device_brand:Z,os_api:Z,access:Z,language:i.language,region:Z,app_language:Z,app_region:Z,creative_id:i.utm.creative_id,ad_id:i.utm.ad_id,campaign_id:i.utm.campaign_id,log_type:Z,rnd:Z,platform:i.platform,sdk_version:fr,sdk_lib:"js",province:Z,city:Z,timezone:Sf,tz_offset:bf,tz_name:Z,sim_region:Z,carrier:Z,resolution:i.screen_width+"x"+i.screen_height,browser:i.browser,browser_version:i.browser_version,referrer:i.referrer,referrer_host:i.referrer_host,width:i.screen_width,height:i.screen_height,screen_width:i.screen_width,screen_height:i.screen_height,utm_term:i.utm.utm_term,utm_content:i.utm.utm_content,utm_source:i.utm.utm_source,utm_medium:i.utm.utm_medium,utm_campaign:i.utm.utm_campaign,tracer_data:JSON.stringify(i.utm.tracer_data),custom:i.network_type?{network_type:i.network_type}:{}}},this.ab_version="",this.ab_uuid_cache={},this.evtParams={},this.reportErrorCallback=function(){},this.isLast=!1,this.setCustom(i),this.initDomain(),this.initABData(),this.collect.on("route-change",function(o){n.changeReferInfo(o.config)})}return r.prototype.initDomain=function(e){var t=this.initConfig.channel_domain;if(t)this.domain=t;else{var n=e||this.initConfig.report_channel||this.initConfig.channel,i=this.getChannelDomain(n);i||(console.warn("current channel: "+n+" is not exist, use va instead, please check!!!!"),i=Mo.sg),this.domain=lr(i),this.setCurrentEnv(this.domain)}},r.prototype.setDomain=function(e){this.customDomain=!0,this.domain=e,this.setCurrentEnv(this.domain)},r.prototype.getDomain=function(e){return this.customDomain||e&&this.initDomain(e),this.domain},r.prototype.getChannelDomain=function(e){var t,n,i=e||this.initConfig.report_channel||this.initConfig.channel;return Po().has(i)?pi[i]:((t=this.initConfig)===null||t===void 0?void 0:t.channel_type)==="tcpy"?gf[i]:((n=this.initConfig)===null||n===void 0?void 0:n.channel_type)==="ttp"?vf[i]:Mo[i]},r.prototype.getChannelForUrl=function(){return this.initConfig.channel_type?{WEBID_URL:"/v1/user/webid",TOB_URL:"",REPORT_URL:"/v1/list"}:this.initConfig.report_channel?["sg_central","us_east"].indexOf(this.initConfig.report_channel)!==-1?{WEBID_URL:"/webid",TOB_URL:"/tobid",REPORT_URL:"/list"}:{WEBID_URL:"/v1/user/webid",TOB_URL:"",REPORT_URL:"/v1/list"}:{WEBID_URL:"/webid",TOB_URL:"/tobid",REPORT_URL:"/list"}},r.prototype.setCurrentEnv=function(e){this.getDomain().includes("byteoversea")?this.current_env="row":this.current_env="other"},r.prototype.getCurrentEnv=function(){return this.current_env},r.prototype.initABData=function(){var e,t="__tea_sdk_ab_version_"+this.initConfig.app_id;e=this.localStorage.getItem(t),this.setAbCache(e)},r.prototype.setAbCache=function(e){this.ab_cache=e},r.prototype.getAbCache=function(){return this.ab_cache},r.prototype.clearAbCache=function(){this.ab_cache={},this.ab_version=""},r.prototype.setAbVersion=function(e){this.ab_version=e},r.prototype.getAbVersion=function(){return this.ab_version},r.prototype.setAbUuidCache=function(e,t){var n=t||this.envInfo.user.user_unique_id;this.ab_uuid_cache[""+n]||(this.ab_uuid_cache[""+n]=[]),this.ab_uuid_cache[""+n].indexOf(e)===-1&&this.ab_uuid_cache[""+n].push(e)},r.prototype.getAbUuidCache=function(e){return this.ab_uuid_cache[""+e]},r.prototype.getUrl=function(e){var t="";switch(e){case"event":t=this.channelUrl.REPORT_URL;break;case"webid":t=this.channelUrl.WEBID_URL;break;case"tobid":t=this.channelUrl.TOB_URL}var n="";return this.initConfig.caller&&(n="?sdk_version=5.3.11_oversea&sdk_name=web&app_id="+this.initConfig.app_id+"&caller="+this.initConfig.caller),""+this.getDomain()+t+n},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.setAppid=function(e){this.envInfo.header.app_id=e},r.prototype.changeReferInfo=function(e){var t=e;this.set({referrer:t.referrer});var n="";try{n=new URL(t.referrer).host}catch{}this.set({referrer_host:n||this.envInfo.header.referrer_host})},r.prototype.set=function(e){var t=this;Object.keys(e).forEach(function(n){if(e[n]!==void 0&&e[n]!==null||t.delete(n),n==="traffic_type"&&t.isLast&&(t.envInfo.header.custom.$latest_traffic_source_type=e[n]),n==="evtParams")t.evtParams=ne(ne({},t.evtParams||{}),e.evtParams||{});else if(n==="_staging_flag")t.evtParams=ne(ne({},t.evtParams||{}),{_staging_flag:e._staging_flag});else if(n==="reportErrorCallback"&&typeof e[n]=="function")t.reportErrorCallback=e[n];else{var i="",s="";if(n.indexOf(".")>-1){var a=n.split(".");i=a[0],s=a[1]}i?i==="user"||i==="header"?t.envInfo[i][s]=e[n]:(t.envInfo.header.custom[s]=e[n],t.collect.emit(T.DEBUGGER_MESSAGE,{type:T.DEBUGGER_MESSAGE_SDK,info:"SDK Add Custom Params",level:"info",time:Date.now(),infoType:"sdk",secType:"HEADER",common:"custom"})):Object.hasOwnProperty.call(t.envInfo.user,n)?(["user_type","ip_addr_id"].indexOf(n)>-1?t.envInfo.user[n]=e[n]?Number(e[n]):e[n]:["user_id","web_id","user_unique_id","user_unique_id_type"].indexOf(n)>-1?t.envInfo.user[n]=e[n]?String(e[n]):e[n]:["user_is_auth","user_is_login"].indexOf(n)>-1?t.envInfo.user[n]=!!e[n]:n==="device_id"&&(t.envInfo.user[n]=e[n]),t.collect.emit(T.DEBUGGER_MESSAGE,{type:T.DEBUGGER_MESSAGE_SDK,info:"SDK Set Common Params",level:"info",time:Date.now(),infoType:"sdk",secType:"USER",common:n})):Object.hasOwnProperty.call(t.envInfo.header,n)?(t.envInfo.header[n]=e[n],t.collect.emit(T.DEBUGGER_MESSAGE,{type:T.DEBUGGER_MESSAGE_SDK,info:"SDK Set Common Params",level:"info",time:Date.now(),infoType:"sdk",secType:"HEADER",common:n})):(t.envInfo.header.custom[n]=e[n],t.collect.emit(T.DEBUGGER_MESSAGE,{type:T.DEBUGGER_MESSAGE_SDK,info:"SDK Add Custom Params",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(T.DEBUGGER_MESSAGE,{type:T.DEBUGGER_MESSAGE_SDK,info:"SDK Something Error",level:"error",time:Date.now(),data:t.message,infoType:"sdk"})}},r.prototype.setStore=function(e){try{if(!this.configPersist)return;var t=this.storage.getItem(this.configKey)||{};if(t&&Object.keys(e).length){var n=Object.assign(e,t);this.storage.setItem(this.configKey,n)}}catch(i){console.log("setStore error"),this.collect.emit(T.DEBUGGER_MESSAGE,{type:T.DEBUGGER_MESSAGE_SDK,info:"SDK Something Error",level:"error",time:Date.now(),data:i.message,infoType:"sdk"})}},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(T.DEBUGGER_MESSAGE,{type:T.DEBUGGER_MESSAGE_SDK,info:"SDK Something Error",level:"error",time:Date.now(),data:t.message,infoType:"sdk"}),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(n){this.collect.emit(T.DEBUGGER_MESSAGE,{type:T.DEBUGGER_MESSAGE_SDK,info:"SDK Something Error",level:"error",time:Date.now(),data:n.message,infoType:"sdk"}),console.log("delete error")}},r}(),Cf=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;","[Tea instance: "+this.name+"] "+e)},r.prototype.warn=function(e){this.isLog&&console.warn("%c %s","color: #4D1B00;","[Tea instance: "+this.name+"] "+e)},r.prototype.error=function(e){this.isLog&&console.error("%c %s","color: #FFF; background-color: #F53F3F;","[Tea instance: "+this.name+"] "+e)},r.prototype.throw=function(e){throw this.error(this.name),new Error(e)},r}(),wf=function(){function r(){this.spiderBot=["Baiduspider","googlebot","360Spider","haosouspider","YoudaoBot","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 n=!1;return this.spiderBot.forEach(function(i){t.indexOf(i)!==-1&&(n=!0)}),n},r}(),Tf=function(){function r(t,n){this.collect=t,this.native=n}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(n,i){try{t.bridgeInject()?AppLogBridge.hasStarted(function(s){console.log("AppLogBridge is started? : "+s),s?n(!0):i(!1)}):i(!1)}catch(s){console.log("AppLogBridge, error:"+JSON.stringify(s.stack)),i(!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 n=this;try{Object.keys(t).forEach(function(i){i==="user_unique_id"?n.setUserUniqueId(t[i]):t[i]?n.addHeaderInfo(i,t[i]):n.removeHeaderInfo(i)})}catch{console.error("setConfig error")}},e.setUserUniqueId=function(t){try{AppLogBridge.setUserUniqueId(t)}catch{console.error("setUserUniqueId error")}},e.addHeaderInfo=function(t,n){try{AppLogBridge.addHeaderInfo(t,n)}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,n){try{AppLogBridge.onEventV3(t,n),this.collect.emit(DebuggerMesssge.DEBUGGER_MESSAGE,{type:DebuggerMesssge.DEBUGGER_MESSAGE_EVENT,info:"bridge report success",time:Date.now(),data:[{events:[{event:t,params:n}]}],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}(),kf=function(){function r(){this.setUrl="/service/2/web_sdk_settings/",this.expireTime=216e5}return r.prototype.apply=function(e,t){if(t.enable_logsetting){this.collect=e,this.config=t;var n=e.adapters.storage;this.setKey="applog_web_logsetting_"+t.app_id,this.uniqueKey="web_logsetting_data",this.cacheStorgae=new n(!1),this.dbStorage=new hf(this.setKey,"LOGSETTING_DATA_STORE"),this.domain=t.logsetting_domain||this.collect.configManager.getDomain(),this.check()}else e.emit(x.LogSettingReady)},r.prototype.check=function(){return ii(this,void 0,void 0,function(){var e;return si(this,function(t){switch(t.label){case 0:return t.trys.push([0,2,,3]),[4,this.getLocalData()];case 1:return(e=t.sent())&&Object.keys(e).length?(e==null?void 0:e.timestamp)<Date.now()-this.expireTime?this.fetchSetting():(this.setSettingData(e.settingConfig),this.collect.emit(x.LogSettingReady)):this.fetchSetting(),[3,3];case 2:return t.sent(),this.collect.emit(x.LogSettingReady),this.collect.emit(T.DEBUGGER_MESSAGE,{type:T.DEBUGGER_MESSAGE_SDK,info:"SDK Check LogSetting Data Error",logType:"fetch",level:"error",time:Date.now(),infoType:"sdk"}),[3,3];case 3:return[2]}})})},r.prototype.fetchSetting=function(e){var t=this;if(e)this.collect.emit(x.LogSettingReady);else{var n=this.collect.configManager.get("header");n.custom=JSON.stringify(n.custom);var i=this.collect.configManager.get("user"),s={event_filter:0,header:ne(ne({aid:this.config.app_id},n),i),options:{params_block_enable:this.config.enable_logsetting_params?1:0,header_custom_allow_enable:this.config.enable_logsetting_header_custom?1:0}};this.collect.emit(T.DEBUGGER_MESSAGE,{type:T.DEBUGGER_MESSAGE_SDK,info:"SDK Fetch LogSetting Request",logType:"fetch",level:"info",time:Date.now(),data:s,infoType:"sdk"}),this.collect.requestManager.useRequest({url:""+this.domain+this.setUrl+"?device_platform=web",data:s,timeout:5e3,success:function(a){a!=null&&a.config?(t.setLocalData(a.config),t.collect.emit(T.DEBUGGER_MESSAGE,{type:T.DEBUGGER_MESSAGE_SDK,info:"LogSetting Request Success",logType:"fetch",level:"info",time:Date.now(),data:a,infoType:"sdk"})):t.collect.emit(T.DEBUGGER_MESSAGE,{type:T.DEBUGGER_MESSAGE_SDK,info:"LogSetting Request Response No Data",logType:"fetch",level:"error",time:Date.now(),infoType:"sdk"}),t.collect.emit(x.LogSettingReady)},fail:function(){t.collect.emit(x.LogSettingReady),t.collect.emit(T.DEBUGGER_MESSAGE,{type:T.DEBUGGER_MESSAGE_SDK,info:"LogSetting Request Fail",logType:"fetch",level:"error",time:Date.now(),infoType:"sdk"})}})}},r.prototype.getLocalData=function(){return ii(this,void 0,void 0,function(){return si(this,function(e){switch(e.label){case 0:return e.trys.push([0,2,,3]),[4,this.dbStorage.getItem(this.uniqueKey)];case 1:return[2,e.sent()];case 2:return e.sent(),[2,null];case 3:return[2]}})})},r.prototype.setLocalData=function(e){try{var t={timestamp:Date.now(),settingConfig:e};this.setSettingData(e),this.dbStorage.setItem(this.uniqueKey,t),this.collect.emit(T.DEBUGGER_MESSAGE,{type:T.DEBUGGER_MESSAGE_SDK,info:"SDK Update LogSetting Cache",logType:"info",level:"info",time:Date.now(),infoType:"sdk",data:e})}catch{this.collect.emit(T.DEBUGGER_MESSAGE,{type:T.DEBUGGER_MESSAGE_SDK,info:"SDK Set LogSetting Data Error",logType:"info",level:"error",time:Date.now(),infoType:"sdk"})}},r.prototype.getSettingData=function(e){return e?this.logSettingConfig[e]:this.logSettingConfig},r.prototype.setSettingData=function(e){this.logSettingConfig=e},r.prototype.getPredefineEventList=function(){return new Set(["predefine_pageview","onload","bav2b_click","bav2b_page","bav2b_beat","bav2b_page_statistics","bav2b_exposure","predefine_page_alive","predefine_page_close","_be_active","__bav_click","__bav_page","__bav_beat","__bav_page_statistics","__bav_page_exposure"])},r.prototype.getPredefineParamsList=function(){return new Set(["event_index"])},r}(),Rf=function(){function r(){this.eventLimit=50,this.enable_ttwebid=!1,this.eventCache=[],this.beconEventCache=[]}return r.prototype.apply=function(e,t){var n=this;this.collect=e,this.config=t,this.configManager=e.configManager,this.cacheStorgae=new wt(!0),this.localStorage=new wt(!1),this.logSetting=new kf,this.maxReport=t.max_report||10,this.reportTime=t.reportTime||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.logSetting.apply(e,t),this.collect.on(x.Ready,function(){n.reportAll(!1)}),this.collect.on(x.ConfigDomain,function(){n.reportUrl=n.configManager.getUrl("event")}),this.collect.on(x.Event,function(i){n.event(i)}),this.collect.on(x.BeconEvent,function(i){n.beconEvent(i)}),this.collect.on(x.CleanEvents,function(){n.reportAll(!1)}),this.linster()},r.prototype.linster=function(){var e=this;window.addEventListener("unload",function(){e.reportAll(!0)},!1),hr(function(){e.reportAll(!0)}),document.addEventListener("visibilitychange",function(){document.visibilityState==="hidden"&&e.reportAll(!0)},!1)},r.prototype.reportAll=function(e){this.report(e),this.reportBecon()},r.prototype.event=function(e){var t=this;if(!this.collect.destroy&&!this.collect.sdkStop)try{if(this.config.enable_ios_sendbeacon&&xo())return void this.beconEvent(e);var n=ur(e,this.cacheStorgae.getItem(this.eventKey)||[]);if(this.cacheStorgae.setItem(this.eventKey,n),this.reportTimeout&&clearTimeout(this.reportTimeout),n.length>=this.maxReport)this.report(!1);else{var i=this.reportTime;this.reportTimeout=setTimeout(function(){t.report(!1),t.reportTimeout=null},i)}}catch(s){this.collect.emit(T.DEBUGGER_MESSAGE,{type:T.DEBUGGER_MESSAGE_SDK,info:"SDK Something Error",level:"error",time:Date.now(),data:s.message,infoType:"sdk"})}},r.prototype.beconEvent=function(e){if(!this.collect.destroy&&!this.collect.sdkStop){var t=ur(e,this.cacheStorgae.getItem(this.beconKey)||[]);if(this.cacheStorgae.setItem(this.beconKey,t),this.collect.tokenManager.getReady()&&this.collect.sdkReady){this.cacheStorgae.removeItem(this.beconKey);try{var n=JSON.parse(JSON.stringify(t));if(this.send(this.split(this.merge(t)),!0),this.config.event_verify_url){var i=this.split(this.merge(n,!0));this.collect.emit(x.SubmitVerify,i)}}catch{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)||[];if(e&&e.length){this.cacheStorgae.removeItem(this.beconKey);try{var t=JSON.parse(JSON.stringify(e));if(this.send(this.split(this.merge(e)),!0),this.config.event_verify_url){var n=this.split(this.merge(t,!0));this.collect.emit(x.SubmitVerify,n)}}catch{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.sliceEvent(t,e))}},r.prototype.sliceEvent=function(e,t){if(e.length>this.eventLimit)for(var n=0;n<e.length;n+=this.eventLimit){var i;i=e.slice(n,n+this.eventLimit);try{var s=JSON.parse(JSON.stringify(i));if(this.send(this.split(this.merge(i)),t),this.config.event_verify_url){var a=this.split(this.merge(s,!0));this.collect.emit(x.SubmitVerify,a)}}catch{this.send(this.split(this.merge(i)),t)}}else try{s=JSON.parse(JSON.stringify(e)),this.send(this.split(this.merge(e)),t),this.config.event_verify_url&&(a=this.split(this.merge(s,!0)),this.collect.emit(x.SubmitVerify,a))}catch{this.send(this.split(this.merge(e)),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 n=this;t===void 0&&(t=!1);var i=this.configManager.get(),s=i.header,a=i.user;s.custom=this.customAllow(s.custom,t);var o=this.configManager.get("evtParams"),d=this.configManager.get("user_unique_id_type"),c=[];try{var u=e.filter(function(l){try{Object.keys(o).length&&(l.params=ne(ne({},o),l.params)),d&&(l.params.$user_unique_id_type=d);var f=n.configManager.getAbCache(),y=a[n.config.ab_user_mode]||a.user_unique_id,C=n.configManager.getAbUuidCache(y);if(f&&f.uuid&&f.uuid===y){var v=n.configManager.getAbVersion();if(n.config.enable_ab_uuid){if(C&&C.length){var E=C.join(",");v&&v.includes(E)&&(l.ab_sdk_version=v)}}else v&&(l.ab_sdk_version=v)}return l.session_id=n.collect.sessionManager.getSessionId(),l.params=n.paramsAllow(l,t),l}catch(k){return console.warn("filter merge event: "+(l&&l.event)+" error, pls check",k&&k.message),n.collect.emit(T.DEBUGGER_MESSAGE,{type:T.DEBUGGER_MESSAGE_SDK,info:"SDK Merge Event Something Error",level:"error",time:Date.now(),data:k.message,infoType:"sdk"}),!1}}),h=JSON.parse(JSON.stringify({events:u,user:a,header:s}));h.local_time=Math.floor(Date.now()/1e3),h.user_unique_type=this.config.enable_ttwebid?this.config.user_unique_type:void 0,h.verbose=1,c.push(h)}catch(l){console.warn("event merge error, pls check",l&&l.message)}return c},r.prototype.split=function(e){return e=e.map(function(t){var n=[];return n.push(t),n})},r.prototype.blockEvent=function(e){try{var t=this.blockList;if(this.config.enable_logsetting){var n=this.blockList,i=this.logSetting.getSettingData("blocklist_events").block_event;t=n.concat(i.filter(function(s){return n.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)&&t.length)||!!this.whiteList.includes(e)}catch{return!0}},r.prototype.customAllow=function(e,t){try{if(t||!this.config.enable_logsetting||!this.config.enable_logsetting_header_custom)return JSON.stringify(e);var n=this.logSetting.getSettingData().header_custom_allow;if(n){var i={};if(n.length&&Object.keys(e).length){var s=new Set(n);for(var a in e)s.has(a)&&(i[a]=e[a])}return JSON.stringify(i)}return JSON.stringify(e)}catch(o){return this.collect.emit(T.DEBUGGER_MESSAGE,{type:T.DEBUGGER_MESSAGE_SDK,info:"SDK Execute customAllow Something Error",level:"error",time:Date.now(),data:o.message,infoType:"sdk"}),JSON.stringify(e)}},r.prototype.paramsAllow=function(e,t){try{if(t||!this.config.enable_logsetting||!this.config.enable_logsetting_params)return JSON.stringify(e.params);var n=this.logSetting.getSettingData().params_block,i=e.event,s=e.params;if(!n)return JSON.stringify(e.params);if(n[i]&&n[i].length){var a={},o=new Set(n[i]);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(T.DEBUGGER_MESSAGE,{type:T.DEBUGGER_MESSAGE_SDK,info:"SDK Execute paramsAllow Something Error",level:"error",time:Date.now(),data:c.message,infoType:"sdk"}),JSON.stringify(e.params)}},r.prototype.send=function(e,t){var n=this;e.length&&(this.config.disable_track_event||e.forEach(function(i){try{var s=JSON.parse(JSON.stringify(i));n.config.filter&&((s=n.config.filter(s))||console.warn("filter must return data !!")),n.collect.eventFilter&&s&&((s=n.collect.eventFilter(s))||console.warn("filterEvent api must return data !!"));var a=s||i,o=JSON.parse(JSON.stringify(a));if(!a.length)return;var d=!0;if(a.forEach(function(c){c.events.length||(d=!1)}),!d)return;n.collect.emit(x.SubmitBefore,a),n.collect.requestManager.useRequest({url:n.reportUrl,data:a,success:function(c,u){c&&c.e!==0?(n.collect.emit(x.SubmitError,{type:"f_data",eventData:u,errorCode:c.e,response:c}),n.collect.emit(T.DEBUGGER_MESSAGE,{type:T.DEBUGGER_MESSAGE_EVENT,info:"Event Report Fail",time:Date.now(),data:o,code:c.e,failType:"event data error",status:"fail"})):(n.collect.emit(x.SubmitScuess,{eventData:u,res:c}),n.collect.emit(T.DEBUGGER_MESSAGE,{type:T.DEBUGGER_MESSAGE_EVENT,info:"Event Report Success",time:Date.now(),data:o,code:200,status:"success"}))},fail:function(c,u){n.configManager.get("reportErrorCallback")(c,u),n.collect.emit(x.SubmitError,{type:"f_net",eventData:c,errorCode:u}),n.collect.emit(T.DEBUGGER_MESSAGE,{type:T.DEBUGGER_MESSAGE_EVENT,info:"Event Report Network Fail",time:Date.now(),data:o,code:u,failType:"network error",status:"fail"})},timeout:n.timeout,useBeacon:!n.config.disable_sendbeacon&&t,withCredentials:n.enable_ttwebid,zip:!0}),n.collect.emit(x.SubmitAfter,a)}catch(c){console.warn("something error, "+JSON.stringify(c.stack)),n.collect.emit(T.DEBUGGER_MESSAGE,{type:T.DEBUGGER_MESSAGE_SDK,info:"SDK Report Event Something Error",level:"error",time:Date.now(),data:c.message})}}))},r}(),on=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)},Af=function(){function r(){this.cacheToken={},this.enableCookie=!1,this.enable_ttwebid=!1,this.enableCustomWebid=!1}return r.prototype.apply=function(e,t){var n=this;this.collect=e,this.config=t,this.configManager=this.collect.configManager,this.storage=new wt(!1),this.tokenKey="__tea_cache_tokens_"+t.app_id,this.enable_ttwebid=t.enable_ttwebid,this.enableCustomWebid=t.enable_custom_webid,this.collect.on(x.ConfigUuid,function(i){n.setUuid(i)}),this.collect.on(x.ConfigWebId,function(i){n.setWebId(i)}),this.collect.on(x.ConfigDiD,function(i){n.setDeviceId(i)}),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;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(x.CustomWebId,function(){e.tokenReady=!0,e.collect.emit(x.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:on(),user_unique_id:this.configManager.get("user_unique_id")||on()}):this.remoteWebid()},r.prototype.checkEnv=function(){var e=window.navigator.userAgent;if(e.indexOf("miniProgram")!==-1||e.indexOf("MiniProgram")!==-1){var t=nn(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"),n={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(T.DEBUGGER_MESSAGE,{type:T.DEBUGGER_MESSAGE_SDK,info:"SDK Fetch WebID Request",logType:"fetch",level:"info",time:Date.now(),data:n});var i=on();this.collect.requestManager.useRequest({url:t,data:n,success:function(s){var a;s&&s.e===0?(a=s.web_id,e.collect.emit(T.DEBUGGER_MESSAGE,{type:T.DEBUGGER_MESSAGE_SDK,info:"Fetch WebID Request Success",logType:"fetch",level:"info",time:Date.now(),data:s})):(a=i,e.collect.configManager.set({localWebId:i}),e.collect.emit(x.TokenError),e.collect.emit(T.DEBUGGER_MESSAGE,{type:T.DEBUGGER_MESSAGE_SDK,info:"Fetch WebID Request Data Error, Use LocalId",logType:"fetch",level:"warn",time:Date.now(),data:s}),e.collect.logger.warn("appid: "+e.config.app_id+" get webid error, use local webid~")),e.complete({web_id:e.configManager.get("web_id")||a,user_unique_id:e.configManager.get("user_unique_id")||a})},fail:function(){e.complete({web_id:e.configManager.get("web_id")||i,user_unique_id:e.configManager.get("user_unique_id")||i}),e.collect.configManager.set({localWebId:i}),e.collect.emit(x.TokenError),e.collect.emit(T.DEBUGGER_MESSAGE,{type:T.DEBUGGER_MESSAGE_SDK,info:"Fetch WebID Request Network Fail, Use LocalId",logType:"fetch",level:"error",time:Date.now(),data:null}),e.collect.logger.warn("appid: "+e.config.app_id+", get webid error, use local webid~")},timeout:3e5})},r.prototype.complete=function(e){var t=e.web_id,n=e.user_unique_id,i=e.device_id;if(e.timestamp=Date.now(),this.collect.configManager.set({web_id:t,user_unique_id:n}),this.config.enable_device_id){var s=this.configManager.get("device_id")||i||t;this.collect.configManager.set({device_id:s}),e=ne(ne({},e),{device_id:s})}else delete e.device_id;this.setStorage(e),this.tokenReady=!0,this.collect.emit(T.DEBUGGER_MESSAGE,{type:T.DEBUGGER_MESSAGE_SDK,info:"SDK UserInfo Complete",logType:"info",secType:"USER",level:"info",time:Date.now(),data:{web_id:t,user_unique_id:n},infoType:"sdk"}),this.collect.emit(x.TokenComplete)},r.prototype.completeTtWid=function(e){var t=e.user_unique_id||"",n=this.configManager.get("user_unique_id");(n||t)&&this.configManager.set({user_unique_id:n||t}),this.setStorage(e),this.tokenReady=!0,this.collect.emit(x.TokenComplete)},r.prototype.setUuid=function(e){if(e&&["null","undefined","Null","None"].indexOf(e)===-1){var t=String(e),n=this.configManager.get("user_unique_id"),i=this.cacheToken&&this.cacheToken.user_unique_id;if(t===n&&t===i)return;this.configManager.set({user_unique_id:t}),this.cacheToken||(this.cacheToken={}),this.cacheToken.user_unique_id=t,this.cacheToken.timestamp=Date.now(),this.setStorage(this.cacheToken),this.collect.emit(x.TokenChange,"uuid"),this.collect.emit(x.SessionReset)}else this.clearUuid()},r.prototype.clearUuid=function(){this.config.enable_ttwebid||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(x.TokenReset))},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"),n=this.configManager.get("user_unique_id");n&&n!==t||(this.configManager.set({user_unique_id:e}),this.collect.emit(x.TokenChange,"uuid")),t!==e&&(this.configManager.set({web_id:e}),this.collect.emit(x.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.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){if(e.config.channel_type!=="tcpy"&&e.config.channel_type!=="ttp"){var n={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(T.DEBUGGER_MESSAGE,{type:T.DEBUGGER_MESSAGE_SDK,info:"SDK Fetch GetToken Request",logType:"fetch",level:"info",time:Date.now(),data:n,infoType:"sdk"}),e.collect.requestManager.useRequest({url:e.configManager.getUrl("tobid"),data:n,success:function(i){i&&i.e===0?(t(i.tobid),e.collect.emit(T.DEBUGGER_MESSAGE,{type:T.DEBUGGER_MESSAGE_SDK,info:"Fetch GetToken Request Success",logType:"fetch",level:"info",time:Date.now(),data:i,infoType:"sdk"})):(t(""),e.collect.emit(T.DEBUGGER_MESSAGE,{type:T.DEBUGGER_MESSAGE_SDK,info:"Fetch GetToken Request Fail",logType:"fetch",level:"error",time:Date.now(),data:i,infoType:"sdk"}))},fail:function(){t(""),e.collect.emit(T.DEBUGGER_MESSAGE,{type:T.DEBUGGER_MESSAGE_SDK,info:"Fetch GetToken Request Network Error",logType:"fetch",level:"error",time:Date.now(),infoType:"sdk"})},time:3e4,withCredentials:e.enable_ttwebid})}else t("")})},r}(),mr=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)})},Df=function(){function r(){}return r.prototype.apply=function(e,t){var n=this;this.collect=e,this.storage=new wt(!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(x.SessionReset,function(i){n.resetSessionId(i)}),this.collect.on(x.SessionResetTime,function(){n.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:mr(),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:mr(),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||mr(),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:mr(),timestamp:Date.now()},this.storage.setItem(this.sessionKey,e))},r}();function jt(r){let e=r.length;for(;--e>=0;)r[e]=0}const _i=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]),an=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]),xf=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7]),No=new Uint8Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),tt=new Array(576);jt(tt);const _r=new Array(60);jt(_r);const gr=new Array(512);jt(gr);const vr=new Array(256);jt(vr);const gi=new Array(29);jt(gi);const cn=new Array(30);function vi(r,e,t,n,i){this.static_tree=r,this.extra_bits=e,this.extra_base=t,this.elems=n,this.max_length=i,this.has_stree=r&&r.length}let Uo,Go,Bo;function yi(r,e){this.dyn_tree=r,this.max_code=0,this.stat_desc=e}jt(cn);const Fo=r=>r<256?gr[r]:gr[256+(r>>>7)],yr=(r,e)=>{r.pending_buf[r.pending++]=255&e,r.pending_buf[r.pending++]=e>>>8&255},Se=(r,e,t)=>{r.bi_valid>16-t?(r.bi_buf|=e<<r.bi_valid&65535,yr(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)},Fe=(r,e,t)=>{Se(r,t[2*e],t[2*e+1])},Vo=(r,e)=>{let t=0;do t|=1&r,r>>>=1,t<<=1;while(--e>0);return t>>>1},jo=(r,e,t)=>{const n=new Array(16);let i,s,a=0;for(i=1;i<=15;i++)a=a+t[i-1]<<1,n[i]=a;for(s=0;s<=e;s++){let o=r[2*s+1];o!==0&&(r[2*s]=Vo(n[o]++,o))}},Ho=r=>{let 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},qo=r=>{r.bi_valid>8?yr(r,r.bi_buf):r.bi_valid>0&&(r.pending_buf[r.pending++]=r.bi_buf),r.bi_buf=0,r.bi_valid=0},$o=(r,e,t,n)=>{const i=2*e,s=2*t;return r[i]<r[s]||r[i]===r[s]&&n[e]<=n[t]},Si=(r,e,t)=>{const n=r.heap[t];let i=t<<1;for(;i<=r.heap_len&&(i<r.heap_len&&$o(e,r.heap[i+1],r.heap[i],r.depth)&&i++,!$o(e,n,r.heap[i],r.depth));)r.heap[t]=r.heap[i],t=i,i<<=1;r.heap[t]=n},Ko=(r,e,t)=>{let n,i,s,a,o=0;if(r.sym_next!==0)do n=255&r.pending_buf[r.sym_buf+o++],n+=(255&r.pending_buf[r.sym_buf+o++])<<8,i=r.pending_buf[r.sym_buf+o++],n===0?Fe(r,i,e):(s=vr[i],Fe(r,s+256+1,e),a=_i[s],a!==0&&(i-=gi[s],Se(r,i,a)),n--,s=Fo(n),Fe(r,s,t),a=an[s],a!==0&&(n-=cn[s],Se(r,n,a)));while(o<r.sym_next);Fe(r,256,e)},bi=(r,e)=>{const t=e.dyn_tree,n=e.stat_desc.static_tree,i=e.stat_desc.has_stree,s=e.stat_desc.elems;let a,o,d,c=-1;for(r.heap_len=0,r.heap_max=573,a=0;a<s;a++)t[2*a]!==0?(r.heap[++r.heap_len]=c=a,r.depth[a]=0):t[2*a+1]=0;for(;r.heap_len<2;)d=r.heap[++r.heap_len]=c<2?++c:0,t[2*d]=1,r.depth[d]=0,r.opt_len--,i&&(r.static_len-=n[2*d+1]);for(e.max_code=c,a=r.heap_len>>1;a>=1;a--)Si(r,t,a);d=s;do a=r.heap[1],r.heap[1]=r.heap[r.heap_len--],Si(r,t,1),o=r.heap[1],r.heap[--r.heap_max]=a,r.heap[--r.heap_max]=o,t[2*d]=t[2*a]+t[2*o],r.depth[d]=(r.depth[a]>=r.depth[o]?r.depth[a]:r.depth[o])+1,t[2*a+1]=t[2*o+1]=d,r.heap[1]=d++,Si(r,t,1);while(r.heap_len>=2);r.heap[--r.heap_max]=r.heap[1],((u,h)=>{const l=h.dyn_tree,f=h.max_code,y=h.stat_desc.static_tree,C=h.stat_desc.has_stree,v=h.stat_desc.extra_bits,E=h.stat_desc.extra_base,k=h.stat_desc.max_length;let g,D,L,R,M,U,G=0;for(R=0;R<=15;R++)u.bl_count[R]=0;for(l[2*u.heap[u.heap_max]+1]=0,g=u.heap_max+1;g<573;g++)D=u.heap[g],R=l[2*l[2*D+1]+1]+1,R>k&&(R=k,G++),l[2*D+1]=R,D>f||(u.bl_count[R]++,M=0,D>=E&&(M=v[D-E]),U=l[2*D],u.opt_len+=U*(R+M),C&&(u.static_len+=U*(y[2*D+1]+M)));if(G!==0){do{for(R=k-1;u.bl_count[R]===0;)R--;u.bl_count[R]--,u.bl_count[R+1]+=2,u.bl_count[k]--,G-=2}while(G>0);for(R=k;R!==0;R--)for(D=u.bl_count[R];D!==0;)L=u.heap[--g],L>f||(l[2*L+1]!==R&&(u.opt_len+=(R-l[2*L+1])*l[2*L],l[2*L+1]=R),D--)}})(r,e),jo(t,c,r.bl_count)},Wo=(r,e,t)=>{let n,i,s=-1,a=e[1],o=0,d=7,c=4;for(a===0&&(d=138,c=3),e[2*(t+1)+1]=65535,n=0;n<=t;n++)i=a,a=e[2*(n+1)+1],++o<d&&i===a||(o<c?r.bl_tree[2*i]+=o:i!==0?(i!==s&&r.bl_tree[2*i]++,r.bl_tree[32]++):o<=10?r.bl_tree[34]++:r.bl_tree[36]++,o=0,s=i,a===0?(d=138,c=3):i===a?(d=6,c=3):(d=7,c=4))},Jo=(r,e,t)=>{let n,i,s=-1,a=e[1],o=0,d=7,c=4;for(a===0&&(d=138,c=3),n=0;n<=t;n++)if(i=a,a=e[2*(n+1)+1],!(++o<d&&i===a)){if(o<c)do Fe(r,i,r.bl_tree);while(--o!=0);else i!==0?(i!==s&&(Fe(r,i,r.bl_tree),o--),Fe(r,16,r.bl_tree),Se(r,o-3,2)):o<=10?(Fe(r,17,r.bl_tree),Se(r,o-3,3)):(Fe(r,18,r.bl_tree),Se(r,o-11,7));o=0,s=i,a===0?(d=138,c=3):i===a?(d=6,c=3):(d=7,c=4)}};let Xo=!1;const Zo=(r,e,t,n)=>{Se(r,0+(n?1:0),3),qo(r),yr(r,t),yr(r,~t),t&&r.pending_buf.set(r.window.subarray(e,e+t),r.pending),r.pending+=t};var If={_tr_init:r=>{Xo||((()=>{let e,t,n,i,s;const a=new Array(16);for(n=0,i=0;i<28;i++)for(gi[i]=n,e=0;e<1<<_i[i];e++)vr[n++]=i;for(vr[n-1]=i,s=0,i=0;i<16;i++)for(cn[i]=s,e=0;e<1<<an[i];e++)gr[s++]=i;for(s>>=7;i<30;i++)for(cn[i]=s<<7,e=0;e<1<<an[i]-7;e++)gr[256+s++]=i;for(t=0;t<=15;t++)a[t]=0;for(e=0;e<=143;)tt[2*e+1]=8,e++,a[8]++;for(;e<=255;)tt[2*e+1]=9,e++,a[9]++;for(;e<=279;)tt[2*e+1]=7,e++,a[7]++;for(;e<=287;)tt[2*e+1]=8,e++,a[8]++;for(jo(tt,287,a),e=0;e<30;e++)_r[2*e+1]=5,_r[2*e]=Vo(e,5);Uo=new vi(tt,_i,257,286,15),Go=new vi(_r,an,0,30,15),Bo=new vi(new Array(0),xf,0,19,7)})(),Xo=!0),r.l_desc=new yi(r.dyn_ltree,Uo),r.d_desc=new yi(r.dyn_dtree,Go),r.bl_desc=new yi(r.bl_tree,Bo),r.bi_buf=0,r.bi_valid=0,Ho(r)},_tr_stored_block:Zo,_tr_flush_block:(r,e,t,n)=>{let i,s,a=0;r.level>0?(r.strm.data_type===2&&(r.strm.data_type=(o=>{let 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)),bi(r,r.l_desc),bi(r,r.d_desc),a=(o=>{let d;for(Wo(o,o.dyn_ltree,o.l_desc.max_code),Wo(o,o.dyn_dtree,o.d_desc.max_code),bi(o,o.bl_desc),d=18;d>=3&&o.bl_tree[2*No[d]+1]===0;d--);return o.opt_len+=3*(d+1)+5+5+4,d})(r),i=r.opt_len+3+7>>>3,s=r.static_len+3+7>>>3,s<=i&&(i=s)):i=s=t+5,t+4<=i&&e!==-1?Zo(r,e,t,n):r.strategy===4||s===i?(Se(r,2+(n?1:0),3),Ko(r,tt,_r)):(Se(r,4+(n?1:0),3),((o,d,c,u)=>{let h;for(Se(o,d-257,5),Se(o,c-1,5),Se(o,u-4,4),h=0;h<u;h++)Se(o,o.bl_tree[2*No[h]+1],3);Jo(o,o.dyn_ltree,d-1),Jo(o,o.dyn_dtree,c-1)})(r,r.l_desc.max_code+1,r.d_desc.max_code+1,a+1),Ko(r,r.dyn_ltree,r.dyn_dtree)),Ho(r),n&&qo(r)},_tr_tally:(r,e,t)=>(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*(vr[t]+256+1)]++,r.dyn_dtree[2*Fo(e)]++),r.sym_next===r.sym_end),_tr_align:r=>{Se(r,2,3),Fe(r,256,tt),(e=>{e.bi_valid===16?(yr(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)}},Sr=(r,e,t,n)=>{let i=65535&r|0,s=r>>>16&65535|0,a=0;for(;t!==0;){a=t>2e3?2e3:t,t-=a;do i=i+e[n++]|0,s=s+i|0;while(--a);i%=65521,s%=65521}return i|s<<16|0};const zf=new Uint32Array((()=>{let r,e=[];for(var t=0;t<256;t++){r=t;for(var n=0;n<8;n++)r=1&r?3988292384^r>>>1:r>>>1;e[t]=r}return e})());var ce=(r,e,t,n)=>{const i=zf,s=n+t;r^=-1;for(let a=n;a<s;a++)r=r>>>8^i[255&(r^e[a])];return-1^r},Tt={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"},kt={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};const{_tr_init:Of,_tr_stored_block:Ei,_tr_flush_block:Pf,_tr_tally:at,_tr_align:Mf}=If,{Z_NO_FLUSH:ct,Z_PARTIAL_FLUSH:Lf,Z_FULL_FLUSH:Nf,Z_FINISH:ke,Z_BLOCK:Yo,Z_OK:le,Z_STREAM_END:Qo,Z_STREAM_ERROR:Ve,Z_DATA_ERROR:Uf,Z_BUF_ERROR:Ci,Z_DEFAULT_COMPRESSION:Gf,Z_FILTERED:Bf,Z_HUFFMAN_ONLY:un,Z_RLE:Ff,Z_FIXED:Vf,Z_DEFAULT_STRATEGY:jf,Z_UNKNOWN:Hf,Z_DEFLATED:dn}=kt,Rt=(r,e)=>(r.msg=Tt[e],e),ea=r=>2*r-(r>4?9:0),ut=r=>{let e=r.length;for(;--e>=0;)r[e]=0},qf=r=>{let e,t,n,i=r.w_size;e=r.hash_size,n=e;do t=r.head[--n],r.head[n]=t>=i?t-i:0;while(--e);e=i,n=e;do t=r.prev[--n],r.prev[n]=t>=i?t-i:0;while(--e)};let dt=(r,e,t)=>(e<<r.hash_shift^t)&r.hash_mask;const Ce=r=>{const e=r.state;let 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))},we=(r,e)=>{Pf(r,r.block_start>=0?r.block_start:-1,r.strstart-r.block_start,e),r.block_start=r.strstart,Ce(r.strm)},Q=(r,e)=>{r.pending_buf[r.pending++]=e},br=(r,e)=>{r.pending_buf[r.pending++]=e>>>8&255,r.pending_buf[r.pending++]=255&e},wi=(r,e,t,n)=>{let i=r.avail_in;return i>n&&(i=n),i===0?0:(r.avail_in-=i,e.set(r.input.subarray(r.next_in,r.next_in+i),t),r.state.wrap===1?r.adler=Sr(r.adler,e,i,t):r.state.wrap===2&&(r.adler=ce(r.adler,e,i,t)),r.next_in+=i,r.total_in+=i,i)},ta=(r,e)=>{let t,n,i=r.max_chain_length,s=r.strstart,a=r.prev_length,o=r.nice_match;const d=r.strstart>r.w_size-262?r.strstart-(r.w_size-262):0,c=r.window,u=r.w_mask,h=r.prev,l=r.strstart+258;let f=c[s+a-1],y=c[s+a];r.prev_length>=r.good_match&&(i>>=2),o>r.lookahead&&(o=r.lookahead);do if(t=e,c[t+a]===y&&c[t+a-1]===f&&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<l);if(n=258-(l-s),s=l-258,n>a){if(r.match_start=e,a=n,n>=o)break;f=c[s+a-1],y=c[s+a]}}while((e=h[e&u])>d&&--i!=0);return a<=r.lookahead?a:r.lookahead},Ht=r=>{const e=r.w_size;let t,n,i;do{if(n=r.window_size-r.lookahead-r.strstart,r.strstart>=e+(e-262)&&(r.window.set(r.window.subarray(e,e+e-n),0),r.match_start-=e,r.strstart-=e,r.block_start-=e,r.insert>r.strstart&&(r.insert=r.strstart),qf(r),n+=e),r.strm.avail_in===0)break;if(t=wi(r.strm,r.window,r.strstart+r.lookahead,n),r.lookahead+=t,r.lookahead+r.insert>=3)for(i=r.strstart-r.insert,r.ins_h=r.window[i],r.ins_h=dt(r,r.ins_h,r.window[i+1]);r.insert&&(r.ins_h=dt(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)},ra=(r,e)=>{let t,n,i,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,i=r.bi_valid+42>>3,r.strm.avail_out<i||(i=r.strm.avail_out-i,n=r.strstart-r.block_start,t>n+r.strm.avail_in&&(t=n+r.strm.avail_in),t>i&&(t=i),t<s&&(t===0&&e!==ke||e===ct||t!==n+r.strm.avail_in)))break;a=e===ke&&t===n+r.strm.avail_in?1:0,Ei(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,Ce(r.strm),n&&(n>t&&(n=t),r.strm.output.set(r.window.subarray(r.block_start,r.block_start+n),r.strm.next_out),r.strm.next_out+=n,r.strm.avail_out-=n,r.strm.total_out+=n,r.block_start+=n,t-=n),t&&(wi(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&&(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!==ct&&e!==ke&&r.strm.avail_in===0&&r.strstart===r.block_start?2:(i=r.window_size-r.strstart,r.strm.avail_in>i&&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++,i+=r.w_size,r.insert>r.strstart&&(r.insert=r.strstart)),i>r.strm.avail_in&&(i=r.strm.avail_in),i&&(wi(r.strm,r.window,r.strstart,i),r.strstart+=i,r.insert+=i>r.w_size-r.insert?r.w_size-r.insert:i),r.high_water<r.strstart&&(r.high_water=r.strstart),i=r.bi_valid+42>>3,i=r.pending_buf_size-i>65535?65535:r.pending_buf_size-i,s=i>r.w_size?r.w_size:i,n=r.strstart-r.block_start,(n>=s||(n||e===ke)&&e!==ct&&r.strm.avail_in===0&&n<=i)&&(t=n>i?i:n,a=e===ke&&r.strm.avail_in===0&&t===n?1:0,Ei(r,r.block_start,t,a),r.block_start+=t,Ce(r.strm)),a?3:1)},Ti=(r,e)=>{let t,n;for(;;){if(r.lookahead<262){if(Ht(r),r.lookahead<262&&e===ct)return 1;if(r.lookahead===0)break}if(t=0,r.lookahead>=3&&(r.ins_h=dt(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=ta(r,t)),r.match_length>=3)if(n=at(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=dt(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=dt(r,r.ins_h,r.window[r.strstart+1]);else n=at(r,0,r.window[r.strstart]),r.lookahead--,r.strstart++;if(n&&(we(r,!1),r.strm.avail_out===0))return 1}return r.insert=r.strstart<2?r.strstart:2,e===ke?(we(r,!0),r.strm.avail_out===0?3:4):r.sym_next&&(we(r,!1),r.strm.avail_out===0)?1:2},qt=(r,e)=>{let t,n,i;for(;;){if(r.lookahead<262){if(Ht(r),r.lookahead<262&&e===ct)return 1;if(r.lookahead===0)break}if(t=0,r.lookahead>=3&&(r.ins_h=dt(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=ta(r,t),r.match_length<=5&&(r.strategy===Bf||r.match_length===3&&r.strstart-r.match_start>4096)&&(r.match_length=2)),r.prev_length>=3&&r.match_length<=r.prev_length){i=r.strstart+r.lookahead-3,n=at(r,r.strstart-1-r.prev_match,r.prev_length-3),r.lookahead-=r.prev_length-1,r.prev_length-=2;do++r.strstart<=i&&(r.ins_h=dt(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++,n&&(we(r,!1),r.strm.avail_out===0))return 1}else if(r.match_available){if(n=at(r,0,r.window[r.strstart-1]),n&&we(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&&(n=at(r,0,r.window[r.strstart-1]),r.match_available=0),r.insert=r.strstart<2?r.strstart:2,e===ke?(we(r,!0),r.strm.avail_out===0?3:4):r.sym_next&&(we(r,!1),r.strm.avail_out===0)?1:2};function je(r,e,t,n,i){this.good_length=r,this.max_lazy=e,this.nice_length=t,this.max_chain=n,this.func=i}const Er=[new je(0,0,0,0,ra),new je(4,4,8,4,Ti),new je(4,5,16,8,Ti),new je(4,6,32,32,Ti),new je(4,4,16,16,qt),new je(8,16,32,32,qt),new je(8,16,128,128,qt),new je(8,32,128,256,qt),new je(32,128,258,1024,qt),new je(32,258,258,4096,qt)];function $f(){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=dn,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(1146),this.dyn_dtree=new Uint16Array(122),this.bl_tree=new Uint16Array(78),ut(this.dyn_ltree),ut(this.dyn_dtree),ut(this.bl_tree),this.l_desc=null,this.d_desc=null,this.bl_desc=null,this.bl_count=new Uint16Array(16),this.heap=new Uint16Array(573),ut(this.heap),this.heap_len=0,this.heap_max=0,this.depth=new Uint16Array(573),ut(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}const Cr=r=>{if(!r)return 1;const 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},na=r=>{if(Cr(r))return Rt(r,Ve);r.total_in=r.total_out=0,r.data_type=Hf;const 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),le},ia=r=>{const e=na(r);var t;return e===le&&((t=r.state).window_size=2*t.w_size,ut(t.head),t.max_lazy_match=Er[t.level].max_lazy,t.good_match=Er[t.level].good_length,t.nice_match=Er[t.level].nice_length,t.max_chain_length=Er[t.level].max_chain,t.strstart=0,t.block_start=0,t.lookahead=0,t.insert=0,t.match_length=t.prev_length=2,t.match_available=0,t.ins_h=0),e},sa=(r,e,t,n,i,s)=>{if(!r)return Ve;let a=1;if(e===Gf&&(e=6),n<0?(a=0,n=-n):n>15&&(a=2,n-=16),i<1||i>9||t!==dn||n<8||n>15||e<0||e>9||s<0||s>Vf||n===8&&a!==1)return Rt(r,Ve);n===8&&(n=9);const o=new $f;return r.state=o,o.strm=r,o.status=42,o.wrap=a,o.gzhead=null,o.w_bits=n,o.w_size=1<<o.w_bits,o.w_mask=o.w_size-1,o.hash_bits=i+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<<i+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,ia(r)};var wr={deflateInit:(r,e)=>sa(r,e,dn,15,8,jf),deflateInit2:sa,deflateReset:ia,deflateResetKeep:na,deflateSetHeader:(r,e)=>Cr(r)||r.state.wrap!==2?Ve:(r.state.gzhead=e,le),deflate:(r,e)=>{if(Cr(r)||e>Yo||e<0)return r?Rt(r,Ve):Ve;const t=r.state;if(!r.output||r.avail_in!==0&&!r.input||t.status===666&&e!==ke)return Rt(r,r.avail_out===0?Ci:Ve);const n=t.last_flush;if(t.last_flush=e,t.pending!==0){if(Ce(r),r.avail_out===0)return t.last_flush=-1,le}else if(r.avail_in===0&&ea(e)<=ea(n)&&e!==ke)return Rt(r,Ci);if(t.status===666&&r.avail_in!==0)return Rt(r,Ci);if(t.status===42&&t.wrap===0&&(t.status=113),t.status===42){let i=dn+(t.w_bits-8<<4)<<8,s=-1;if(s=t.strategy>=un||t.level<2?0:t.level<6?1:t.level===6?2:3,i|=s<<6,t.strstart!==0&&(i|=32),i+=31-i%31,br(t,i),t.strstart!==0&&(br(t,r.adler>>>16),br(t,65535&r.adler)),r.adler=1,t.status=113,Ce(r),t.pending!==0)return t.last_flush=-1,le}if(t.status===57){if(r.adler=0,Q(t,31),Q(t,139),Q(t,8),t.gzhead)Q(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)),Q(t,255&t.gzhead.time),Q(t,t.gzhead.time>>8&255),Q(t,t.gzhead.time>>16&255),Q(t,t.gzhead.time>>24&255),Q(t,t.level===9?2:t.strategy>=un||t.level<2?4:0),Q(t,255&t.gzhead.os),t.gzhead.extra&&t.gzhead.extra.length&&(Q(t,255&t.gzhead.extra.length),Q(t,t.gzhead.extra.length>>8&255)),t.gzhead.hcrc&&(r.adler=ce(r.adler,t.pending_buf,t.pending,0)),t.gzindex=0,t.status=69;else if(Q(t,0),Q(t,0),Q(t,0),Q(t,0),Q(t,0),Q(t,t.level===9?2:t.strategy>=un||t.level<2?4:0),Q(t,3),t.status=113,Ce(r),t.pending!==0)return t.last_flush=-1,le}if(t.status===69){if(t.gzhead.extra){let i=t.pending,s=(65535&t.gzhead.extra.length)-t.gzindex;for(;t.pending+s>t.pending_buf_size;){let 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>i&&(r.adler=ce(r.adler,t.pending_buf,t.pending-i,i)),t.gzindex+=o,Ce(r),t.pending!==0)return t.last_flush=-1,le;i=0,s-=o}let a=new Uint8Array(t.gzhead.extra);t.pending_buf.set(a.subarray(t.gzindex,t.gzindex+s),t.pending),t.pending+=s,t.gzhead.hcrc&&t.pending>i&&(r.adler=ce(r.adler,t.pending_buf,t.pending-i,i)),t.gzindex=0}t.status=73}if(t.status===73){if(t.gzhead.name){let i,s=t.pending;do{if(t.pending===t.pending_buf_size){if(t.gzhead.hcrc&&t.pending>s&&(r.adler=ce(r.adler,t.pending_buf,t.pending-s,s)),Ce(r),t.pending!==0)return t.last_flush=-1,le;s=0}i=t.gzindex<t.gzhead.name.length?255&t.gzhead.name.charCodeAt(t.gzindex++):0,Q(t,i)}while(i!==0);t.gzhead.hcrc&&t.pending>s&&(r.adler=ce(r.adler,t.pending_buf,t.pending-s,s)),t.gzindex=0}t.status=91}if(t.status===91){if(t.gzhead.comment){let i,s=t.pending;do{if(t.pending===t.pending_buf_size){if(t.gzhead.hcrc&&t.pending>s&&(r.adler=ce(r.adler,t.pending_buf,t.pending-s,s)),Ce(r),t.pending!==0)return t.last_flush=-1,le;s=0}i=t.gzindex<t.gzhead.comment.length?255&t.gzhead.comment.charCodeAt(t.gzindex++):0,Q(t,i)}while(i!==0);t.gzhead.hcrc&&t.pending>s&&(r.adler=ce(r.adler,t.pending_buf,t.pending-s,s))}t.status=103}if(t.status===103){if(t.gzhead.hcrc){if(t.pending+2>t.pending_buf_size&&(Ce(r),t.pending!==0))return t.last_flush=-1,le;Q(t,255&r.adler),Q(t,r.adler>>8&255),r.adler=0}if(t.status=113,Ce(r),t.pending!==0)return t.last_flush=-1,le}if(r.avail_in!==0||t.lookahead!==0||e!==ct&&t.status!==666){let i=t.level===0?ra(t,e):t.strategy===un?((s,a)=>{let o;for(;;){if(s.lookahead===0&&(Ht(s),s.lookahead===0)){if(a===ct)return 1;break}if(s.match_length=0,o=at(s,0,s.window[s.strstart]),s.lookahead--,s.strstart++,o&&(we(s,!1),s.strm.avail_out===0))return 1}return s.insert=0,a===ke?(we(s,!0),s.strm.avail_out===0?3:4):s.sym_next&&(we(s,!1),s.strm.avail_out===0)?1:2})(t,e):t.strategy===Ff?((s,a)=>{let o,d,c,u;const h=s.window;for(;;){if(s.lookahead<=258){if(Ht(s),s.lookahead<=258&&a===ct)return 1;if(s.lookahead===0)break}if(s.match_length=0,s.lookahead>=3&&s.strstart>0&&(c=s.strstart-1,d=h[c],d===h[++c]&&d===h[++c]&&d===h[++c])){u=s.strstart+258;do;while(d===h[++c]&&d===h[++c]&&d===h[++c]&&d===h[++c]&&d===h[++c]&&d===h[++c]&&d===h[++c]&&d===h[++c]&&c<u);s.match_length=258-(u-c),s.match_length>s.lookahead&&(s.match_length=s.lookahead)}if(s.match_length>=3?(o=at(s,1,s.match_length-3),s.lookahead-=s.match_length,s.strstart+=s.match_length,s.match_length=0):(o=at(s,0,s.window[s.strstart]),s.lookahead--,s.strstart++),o&&(we(s,!1),s.strm.avail_out===0))return 1}return s.insert=0,a===ke?(we(s,!0),s.strm.avail_out===0?3:4):s.sym_next&&(we(s,!1),s.strm.avail_out===0)?1:2})(t,e):Er[t.level].func(t,e);if(i!==3&&i!==4||(t.status=666),i===1||i===3)return r.avail_out===0&&(t.last_flush=-1),le;if(i===2&&(e===Lf?Mf(t):e!==Yo&&(Ei(t,0,0,!1),e===Nf&&(ut(t.head),t.lookahead===0&&(t.strstart=0,t.block_start=0,t.insert=0))),Ce(r),r.avail_out===0))return t.last_flush=-1,le}return e!==ke?le:t.wrap<=0?Qo:(t.wrap===2?(Q(t,255&r.adler),Q(t,r.adler>>8&255),Q(t,r.adler>>16&255),Q(t,r.adler>>24&255),Q(t,255&r.total_in),Q(t,r.total_in>>8&255),Q(t,r.total_in>>16&255),Q(t,r.total_in>>24&255)):(br(t,r.adler>>>16),br(t,65535&r.adler)),Ce(r),t.wrap>0&&(t.wrap=-t.wrap),t.pending!==0?le:Qo)},deflateEnd:r=>{if(Cr(r))return Ve;const e=r.state.status;return r.state=null,e===113?Rt(r,Uf):le},deflateSetDictionary:(r,e)=>{let t=e.length;if(Cr(r))return Ve;const n=r.state,i=n.wrap;if(i===2||i===1&&n.status!==42||n.lookahead)return Ve;if(i===1&&(r.adler=Sr(r.adler,e,t,0)),n.wrap=0,t>=n.w_size){i===0&&(ut(n.head),n.strstart=0,n.block_start=0,n.insert=0);let d=new Uint8Array(n.w_size);d.set(e.subarray(t-n.w_size,t),0),e=d,t=n.w_size}const s=r.avail_in,a=r.next_in,o=r.input;for(r.avail_in=t,r.next_in=0,r.input=e,Ht(n);n.lookahead>=3;){let d=n.strstart,c=n.lookahead-2;do n.ins_h=dt(n,n.ins_h,n.window[d+3-1]),n.prev[d&n.w_mask]=n.head[n.ins_h],n.head[n.ins_h]=d,d++;while(--c);n.strstart=d,n.lookahead=2,Ht(n)}return n.strstart+=n.lookahead,n.block_start=n.strstart,n.insert=n.lookahead,n.lookahead=0,n.match_length=n.prev_length=2,n.match_available=0,r.next_in=a,r.input=o,r.avail_in=s,n.wrap=i,le},deflateInfo:"pako deflate (from Nodeca project)"};const Kf=(r,e)=>Object.prototype.hasOwnProperty.call(r,e);var oa=function(r){const e=Array.prototype.slice.call(arguments,1);for(;e.length;){const t=e.shift();if(t){if(typeof t!="object")throw new TypeError(t+"must be non-object");for(const n in t)Kf(t,n)&&(r[n]=t[n])}}return r},aa=r=>{let e=0;for(let n=0,i=r.length;n<i;n++)e+=r[n].length;const t=new Uint8Array(e);for(let n=0,i=0,s=r.length;n<s;n++){let a=r[n];t.set(a,i),i+=a.length}return t};let ca=!0;try{String.fromCharCode.apply(null,new Uint8Array(1))}catch{ca=!1}const Tr=new Uint8Array(256);for(let r=0;r<256;r++)Tr[r]=r>=252?6:r>=248?5:r>=240?4:r>=224?3:r>=192?2:1;Tr[254]=Tr[254]=1;var ki=r=>{if(typeof TextEncoder=="function"&&TextEncoder.prototype.encode)return new TextEncoder().encode(r);let e,t,n,i,s,a=r.length,o=0;for(i=0;i<a;i++)t=r.charCodeAt(i),(64512&t)==55296&&i+1<a&&(n=r.charCodeAt(i+1),(64512&n)==56320&&(t=65536+(t-55296<<10)+(n-56320),i++)),o+=t<128?1:t<2048?2:t<65536?3:4;for(e=new Uint8Array(o),s=0,i=0;s<o;i++)t=r.charCodeAt(i),(64512&t)==55296&&i+1<a&&(n=r.charCodeAt(i+1),(64512&n)==56320&&(t=65536+(t-55296<<10)+(n-56320),i++)),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},Wf=(r,e)=>{const t=e||r.length;if(typeof TextDecoder=="function"&&TextDecoder.prototype.decode)return new TextDecoder().decode(r.subarray(0,e));let n,i;const s=new Array(2*t);for(i=0,n=0;n<t;){let a=r[n++];if(a<128){s[i++]=a;continue}let o=Tr[a];if(o>4)s[i++]=65533,n+=o-1;else{for(a&=o===2?31:o===3?15:7;o>1&&n<t;)a=a<<6|63&r[n++],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((a,o)=>{if(o<65534&&a.subarray&&ca)return String.fromCharCode.apply(null,a.length===o?a:a.subarray(0,o));let d="";for(let c=0;c<o;c++)d+=String.fromCharCode(a[c]);return d})(s,i)},Jf=(r,e)=>{(e=e||r.length)>r.length&&(e=r.length);let t=e-1;for(;t>=0&&(192&r[t])==128;)t--;return t<0||t===0?e:t+Tr[r[t]]>e?t:e},ua=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};const da=Object.prototype.toString,{Z_NO_FLUSH:Xf,Z_SYNC_FLUSH:Zf,Z_FULL_FLUSH:Yf,Z_FINISH:Qf,Z_OK:ln,Z_STREAM_END:em,Z_DEFAULT_COMPRESSION:tm,Z_DEFAULT_STRATEGY:rm,Z_DEFLATED:nm}=kt;function kr(r){this.options=oa({level:tm,method:nm,chunkSize:16384,windowBits:15,memLevel:8,strategy:rm},r||{});let 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 ua,this.strm.avail_out=0;let t=wr.deflateInit2(this.strm,e.level,e.method,e.windowBits,e.memLevel,e.strategy);if(t!==ln)throw new Error(Tt[t]);if(e.header&&wr.deflateSetHeader(this.strm,e.header),e.dictionary){let n;if(n=typeof e.dictionary=="string"?ki(e.dictionary):da.call(e.dictionary)==="[object ArrayBuffer]"?new Uint8Array(e.dictionary):e.dictionary,t=wr.deflateSetDictionary(this.strm,n),t!==ln)throw new Error(Tt[t]);this._dict_set=!0}}function Ri(r,e){const t=new kr(e);if(t.push(r,!0),t.err)throw t.msg||Tt[t.err];return t.result}kr.prototype.push=function(r,e){const t=this.strm,n=this.options.chunkSize;let i,s;if(this.ended)return!1;for(s=e===~~e?e:e===!0?Qf:Xf,typeof r=="string"?t.input=ki(r):da.call(r)==="[object ArrayBuffer]"?t.input=new Uint8Array(r):t.input=r,t.next_in=0,t.avail_in=t.input.length;;)if(t.avail_out===0&&(t.output=new Uint8Array(n),t.next_out=0,t.avail_out=n),(s===Zf||s===Yf)&&t.avail_out<=6)this.onData(t.output.subarray(0,t.next_out)),t.avail_out=0;else{if(i=wr.deflate(t,s),i===em)return t.next_out>0&&this.onData(t.output.subarray(0,t.next_out)),i=wr.deflateEnd(this.strm),this.onEnd(i),this.ended=!0,i===ln;if(t.avail_out!==0){if(s>0&&t.next_out>0)this.onData(t.output.subarray(0,t.next_out)),t.avail_out=0;else if(t.avail_in===0)break}else this.onData(t.output)}return!0},kr.prototype.onData=function(r){this.chunks.push(r)},kr.prototype.onEnd=function(r){r===ln&&(this.result=aa(this.chunks)),this.chunks=[],this.err=r,this.msg=this.strm.msg};var im={Deflate:kr,deflate:Ri,deflateRaw:function(r,e){return(e=e||{}).raw=!0,Ri(r,e)},gzip:function(r,e){return(e=e||{}).gzip=!0,Ri(r,e)},constants:kt},sm=function(r,e){let t,n,i,s,a,o,d,c,u,h,l,f,y,C,v,E,k,g,D,L,R,M,U,G;const F=r.state;t=r.next_in,U=r.input,n=t+(r.avail_in-5),i=r.next_out,G=r.output,s=i-(e-r.avail_out),a=i+(r.avail_out-257),o=F.dmax,d=F.wsize,c=F.whave,u=F.wnext,h=F.window,l=F.hold,f=F.bits,y=F.lencode,C=F.distcode,v=(1<<F.lenbits)-1,E=(1<<F.distbits)-1;e:do{f<15&&(l+=U[t++]<<f,f+=8,l+=U[t++]<<f,f+=8),k=y[l&v];t:for(;;){if(g=k>>>24,l>>>=g,f-=g,g=k>>>16&255,g===0)G[i++]=65535&k;else{if(!(16&g)){if(!(64&g)){k=y[(65535&k)+(l&(1<<g)-1)];continue t}if(32&g){F.mode=16191;break e}r.msg="invalid literal/length code",F.mode=16209;break e}D=65535&k,g&=15,g&&(f<g&&(l+=U[t++]<<f,f+=8),D+=l&(1<<g)-1,l>>>=g,f-=g),f<15&&(l+=U[t++]<<f,f+=8,l+=U[t++]<<f,f+=8),k=C[l&E];r:for(;;){if(g=k>>>24,l>>>=g,f-=g,g=k>>>16&255,!(16&g)){if(!(64&g)){k=C[(65535&k)+(l&(1<<g)-1)];continue r}r.msg="invalid distance code",F.mode=16209;break e}if(L=65535&k,g&=15,f<g&&(l+=U[t++]<<f,f+=8,f<g&&(l+=U[t++]<<f,f+=8)),L+=l&(1<<g)-1,L>o){r.msg="invalid distance too far back",F.mode=16209;break e}if(l>>>=g,f-=g,g=i-s,L>g){if(g=L-g,g>c&&F.sane){r.msg="invalid distance too far back",F.mode=16209;break e}if(R=0,M=h,u===0){if(R+=d-g,g<D){D-=g;do G[i++]=h[R++];while(--g);R=i-L,M=G}}else if(u<g){if(R+=d+u-g,g-=u,g<D){D-=g;do G[i++]=h[R++];while(--g);if(R=0,u<D){g=u,D-=g;do G[i++]=h[R++];while(--g);R=i-L,M=G}}}else if(R+=u-g,g<D){D-=g;do G[i++]=h[R++];while(--g);R=i-L,M=G}for(;D>2;)G[i++]=M[R++],G[i++]=M[R++],G[i++]=M[R++],D-=3;D&&(G[i++]=M[R++],D>1&&(G[i++]=M[R++]))}else{R=i-L;do G[i++]=G[R++],G[i++]=G[R++],G[i++]=G[R++],D-=3;while(D>2);D&&(G[i++]=G[R++],D>1&&(G[i++]=G[R++]))}break}}break}}while(t<n&&i<a);D=f>>3,t-=D,f-=D<<3,l&=(1<<f)-1,r.next_in=t,r.next_out=i,r.avail_in=t<n?n-t+5:5-(t-n),r.avail_out=i<a?a-i+257:257-(i-a),F.hold=l,F.bits=f};const om=new Uint16Array([3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258,0,0]),am=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]),cm=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]),um=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]);var Rr=(r,e,t,n,i,s,a,o)=>{const d=o.bits;let c,u,h,l,f,y,C=0,v=0,E=0,k=0,g=0,D=0,L=0,R=0,M=0,U=0,G=null;const F=new Uint16Array(16),q=new Uint16Array(16);let ee,J,ve,he=null;for(C=0;C<=15;C++)F[C]=0;for(v=0;v<n;v++)F[e[t+v]]++;for(g=d,k=15;k>=1&&F[k]===0;k--);if(g>k&&(g=k),k===0)return i[s++]=20971520,i[s++]=20971520,o.bits=1,0;for(E=1;E<k&&F[E]===0;E++);for(g<E&&(g=E),R=1,C=1;C<=15;C++)if(R<<=1,R-=F[C],R<0)return-1;if(R>0&&(r===0||k!==1))return-1;for(q[1]=0,C=1;C<15;C++)q[C+1]=q[C]+F[C];for(v=0;v<n;v++)e[t+v]!==0&&(a[q[e[t+v]]++]=v);if(r===0?(G=he=a,y=20):r===1?(G=om,he=am,y=257):(G=cm,he=um,y=0),U=0,v=0,C=E,f=s,D=g,L=0,h=-1,M=1<<g,l=M-1,r===1&&M>852||r===2&&M>592)return 1;for(;;){ee=C-L,a[v]+1<y?(J=0,ve=a[v]):a[v]>=y?(J=he[a[v]-y],ve=G[a[v]-y]):(J=96,ve=0),c=1<<C-L,u=1<<D,E=u;do u-=c,i[f+(U>>L)+u]=ee<<24|J<<16|ve|0;while(u!==0);for(c=1<<C-1;U&c;)c>>=1;if(c!==0?(U&=c-1,U+=c):U=0,v++,--F[C]==0){if(C===k)break;C=e[t+a[v]]}if(C>g&&(U&l)!==h){for(L===0&&(L=g),f+=E,D=C-L,R=1<<D;D+L<k&&(R-=F[D+L],!(R<=0));)D++,R<<=1;if(M+=1<<D,r===1&&M>852||r===2&&M>592)return 1;h=U&l,i[h]=g<<24|D<<16|f-s|0}}return U!==0&&(i[f+U]=C-L<<24|64<<16|0),o.bits=g,0};const{Z_FINISH:la,Z_BLOCK:dm,Z_TREES:hn,Z_OK:At,Z_STREAM_END:lm,Z_NEED_DICT:hm,Z_STREAM_ERROR:Re,Z_DATA_ERROR:ha,Z_MEM_ERROR:pa,Z_BUF_ERROR:pm,Z_DEFLATED:fa}=kt,ma=r=>(r>>>24&255)+(r>>>8&65280)+((65280&r)<<8)+((255&r)<<24);function fm(){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}const Dt=r=>{if(!r)return 1;const e=r.state;return!e||e.strm!==r||e.mode<16180||e.mode>16211?1:0},_a=r=>{if(Dt(r))return Re;const 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,At},ga=r=>{if(Dt(r))return Re;const e=r.state;return e.wsize=0,e.whave=0,e.wnext=0,_a(r)},va=(r,e)=>{let t;if(Dt(r))return Re;const n=r.state;return e<0?(t=0,e=-e):(t=5+(e>>4),e<48&&(e&=15)),e&&(e<8||e>15)?Re:(n.window!==null&&n.wbits!==e&&(n.window=null),n.wrap=t,n.wbits=e,ga(r))},ya=(r,e)=>{if(!r)return Re;const t=new fm;r.state=t,t.strm=r,t.window=null,t.mode=16180;const n=va(r,e);return n!==At&&(r.state=null),n};let Ai,Di,Sa=!0;const mm=r=>{if(Sa){Ai=new Int32Array(512),Di=new Int32Array(32);let e=0;for(;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(Rr(1,r.lens,0,288,Ai,0,r.work,{bits:9}),e=0;e<32;)r.lens[e++]=5;Rr(2,r.lens,0,32,Di,0,r.work,{bits:5}),Sa=!1}r.lencode=Ai,r.lenbits=9,r.distcode=Di,r.distbits=5},ba=(r,e,t,n)=>{let i;const s=r.state;return s.window===null&&(s.wsize=1<<s.wbits,s.wnext=0,s.whave=0,s.window=new Uint8Array(s.wsize)),n>=s.wsize?(s.window.set(e.subarray(t-s.wsize,t),0),s.wnext=0,s.whave=s.wsize):(i=s.wsize-s.wnext,i>n&&(i=n),s.window.set(e.subarray(t-n,t-n+i),s.wnext),(n-=i)?(s.window.set(e.subarray(t-n,t),0),s.wnext=n,s.whave=s.wsize):(s.wnext+=i,s.wnext===s.wsize&&(s.wnext=0),s.whave<s.wsize&&(s.whave+=i))),0};var rt={inflateReset:ga,inflateReset2:va,inflateResetKeep:_a,inflateInit:r=>ya(r,15),inflateInit2:ya,inflate:(r,e)=>{let t,n,i,s,a,o,d,c,u,h,l,f,y,C,v,E,k,g,D,L,R,M,U=0;const G=new Uint8Array(4);let F,q;const ee=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 Re;t=r.state,t.mode===16191&&(t.mode=16192),a=r.next_out,i=r.output,d=r.avail_out,s=r.next_in,n=r.input,o=r.avail_in,c=t.hold,u=t.bits,h=o,l=d,M=At;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+=n[s++]<<u,u+=8}if(2&t.wrap&&c===35615){t.wbits===0&&(t.wbits=15),t.check=0,G[0]=255&c,G[1]=c>>>8&255,t.check=ce(t.check,G,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)!==fa){r.msg="unknown compression method",t.mode=16209;break}if(c>>>=4,u-=4,R=8+(15&c),t.wbits===0&&(t.wbits=R),R>15||R>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+=n[s++]<<u,u+=8}if(t.flags=c,(255&t.flags)!==fa){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&&(G[0]=255&c,G[1]=c>>>8&255,t.check=ce(t.check,G,2,0)),c=0,u=0,t.mode=16182;case 16182:for(;u<32;){if(o===0)break e;o--,c+=n[s++]<<u,u+=8}t.head&&(t.head.time=c),512&t.flags&&4&t.wrap&&(G[0]=255&c,G[1]=c>>>8&255,G[2]=c>>>16&255,G[3]=c>>>24&255,t.check=ce(t.check,G,4,0)),c=0,u=0,t.mode=16183;case 16183:for(;u<16;){if(o===0)break e;o--,c+=n[s++]<<u,u+=8}t.head&&(t.head.xflags=255&c,t.head.os=c>>8),512&t.flags&&4&t.wrap&&(G[0]=255&c,G[1]=c>>>8&255,t.check=ce(t.check,G,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+=n[s++]<<u,u+=8}t.length=c,t.head&&(t.head.extra_len=c),512&t.flags&&4&t.wrap&&(G[0]=255&c,G[1]=c>>>8&255,t.check=ce(t.check,G,2,0)),c=0,u=0}else t.head&&(t.head.extra=null);t.mode=16185;case 16185:if(1024&t.flags&&(f=t.length,f>o&&(f=o),f&&(t.head&&(R=t.head.extra_len-t.length,t.head.extra||(t.head.extra=new Uint8Array(t.head.extra_len)),t.head.extra.set(n.subarray(s,s+f),R)),512&t.flags&&4&t.wrap&&(t.check=ce(t.check,n,f,s)),o-=f,s+=f,t.length-=f),t.length))break e;t.length=0,t.mode=16186;case 16186:if(2048&t.flags){if(o===0)break e;f=0;do R=n[s+f++],t.head&&R&&t.length<65536&&(t.head.name+=String.fromCharCode(R));while(R&&f<o);if(512&t.flags&&4&t.wrap&&(t.check=ce(t.check,n,f,s)),o-=f,s+=f,R)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;f=0;do R=n[s+f++],t.head&&R&&t.length<65536&&(t.head.comment+=String.fromCharCode(R));while(R&&f<o);if(512&t.flags&&4&t.wrap&&(t.check=ce(t.check,n,f,s)),o-=f,s+=f,R)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+=n[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+=n[s++]<<u,u+=8}r.adler=t.check=ma(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,hm;r.adler=t.check=1,t.mode=16191;case 16191:if(e===dm||e===hn)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+=n[s++]<<u,u+=8}switch(t.last=1&c,c>>>=1,u-=1,3&c){case 0:t.mode=16193;break;case 1:if(mm(t),t.mode=16199,e===hn){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+=n[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===hn)break e;case 16194:t.mode=16195;case 16195:if(f=t.length,f){if(f>o&&(f=o),f>d&&(f=d),f===0)break e;i.set(n.subarray(s,s+f),a),o-=f,s+=f,d-=f,a+=f,t.length-=f;break}t.mode=16191;break;case 16196:for(;u<14;){if(o===0)break e;o--,c+=n[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+=n[s++]<<u,u+=8}t.lens[ee[t.have++]]=7&c,c>>>=3,u-=3}for(;t.have<19;)t.lens[ee[t.have++]]=0;if(t.lencode=t.lendyn,t.lenbits=7,F={bits:t.lenbits},M=Rr(0,t.lens,0,19,t.lencode,0,t.work,F),t.lenbits=F.bits,M){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(;U=t.lencode[c&(1<<t.lenbits)-1],v=U>>>24,E=U>>>16&255,k=65535&U,!(v<=u);){if(o===0)break e;o--,c+=n[s++]<<u,u+=8}if(k<16)c>>>=v,u-=v,t.lens[t.have++]=k;else{if(k===16){for(q=v+2;u<q;){if(o===0)break e;o--,c+=n[s++]<<u,u+=8}if(c>>>=v,u-=v,t.have===0){r.msg="invalid bit length repeat",t.mode=16209;break}R=t.lens[t.have-1],f=3+(3&c),c>>>=2,u-=2}else if(k===17){for(q=v+3;u<q;){if(o===0)break e;o--,c+=n[s++]<<u,u+=8}c>>>=v,u-=v,R=0,f=3+(7&c),c>>>=3,u-=3}else{for(q=v+7;u<q;){if(o===0)break e;o--,c+=n[s++]<<u,u+=8}c>>>=v,u-=v,R=0,f=11+(127&c),c>>>=7,u-=7}if(t.have+f>t.nlen+t.ndist){r.msg="invalid bit length repeat",t.mode=16209;break}for(;f--;)t.lens[t.have++]=R}}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,F={bits:t.lenbits},M=Rr(1,t.lens,0,t.nlen,t.lencode,0,t.work,F),t.lenbits=F.bits,M){r.msg="invalid literal/lengths set",t.mode=16209;break}if(t.distbits=6,t.distcode=t.distdyn,F={bits:t.distbits},M=Rr(2,t.lens,t.nlen,t.ndist,t.distcode,0,t.work,F),t.distbits=F.bits,M){r.msg="invalid distances set",t.mode=16209;break}if(t.mode=16199,e===hn)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,sm(r,l),a=r.next_out,i=r.output,d=r.avail_out,s=r.next_in,n=r.input,o=r.avail_in,c=t.hold,u=t.bits,t.mode===16191&&(t.back=-1);break}for(t.back=0;U=t.lencode[c&(1<<t.lenbits)-1],v=U>>>24,E=U>>>16&255,k=65535&U,!(v<=u);){if(o===0)break e;o--,c+=n[s++]<<u,u+=8}if(E&&!(240&E)){for(g=v,D=E,L=k;U=t.lencode[L+((c&(1<<g+D)-1)>>g)],v=U>>>24,E=U>>>16&255,k=65535&U,!(g+v<=u);){if(o===0)break e;o--,c+=n[s++]<<u,u+=8}c>>>=g,u-=g,t.back+=g}if(c>>>=v,u-=v,t.back+=v,t.length=k,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(q=t.extra;u<q;){if(o===0)break e;o--,c+=n[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(;U=t.distcode[c&(1<<t.distbits)-1],v=U>>>24,E=U>>>16&255,k=65535&U,!(v<=u);){if(o===0)break e;o--,c+=n[s++]<<u,u+=8}if(!(240&E)){for(g=v,D=E,L=k;U=t.distcode[L+((c&(1<<g+D)-1)>>g)],v=U>>>24,E=U>>>16&255,k=65535&U,!(g+v<=u);){if(o===0)break e;o--,c+=n[s++]<<u,u+=8}c>>>=g,u-=g,t.back+=g}if(c>>>=v,u-=v,t.back+=v,64&E){r.msg="invalid distance code",t.mode=16209;break}t.offset=k,t.extra=15&E,t.mode=16203;case 16203:if(t.extra){for(q=t.extra;u<q;){if(o===0)break e;o--,c+=n[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(f=l-d,t.offset>f){if(f=t.offset-f,f>t.whave&&t.sane){r.msg="invalid distance too far back",t.mode=16209;break}f>t.wnext?(f-=t.wnext,y=t.wsize-f):y=t.wnext-f,f>t.length&&(f=t.length),C=t.window}else C=i,y=a-t.offset,f=t.length;f>d&&(f=d),d-=f,t.length-=f;do i[a++]=C[y++];while(--f);t.length===0&&(t.mode=16200);break;case 16205:if(d===0)break e;i[a++]=t.length,d--,t.mode=16200;break;case 16206:if(t.wrap){for(;u<32;){if(o===0)break e;o--,c|=n[s++]<<u,u+=8}if(l-=d,r.total_out+=l,t.total+=l,4&t.wrap&&l&&(r.adler=t.check=t.flags?ce(t.check,i,l,a-l):Sr(t.check,i,l,a-l)),l=d,4&t.wrap&&(t.flags?c:ma(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+=n[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:M=lm;break e;case 16209:M=ha;break e;case 16210:return pa;case 16211:default:return Re}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||l!==r.avail_out&&t.mode<16209&&(t.mode<16206||e!==la))&&ba(r,r.output,r.next_out,l-r.avail_out),h-=r.avail_in,l-=r.avail_out,r.total_in+=h,r.total_out+=l,t.total+=l,4&t.wrap&&l&&(r.adler=t.check=t.flags?ce(t.check,i,l,r.next_out-l):Sr(t.check,i,l,r.next_out-l)),r.data_type=t.bits+(t.last?64:0)+(t.mode===16191?128:0)+(t.mode===16199||t.mode===16194?256:0),(h===0&&l===0||e===la)&&M===At&&(M=pm),M},inflateEnd:r=>{if(Dt(r))return Re;let e=r.state;return e.window&&(e.window=null),r.state=null,At},inflateGetHeader:(r,e)=>{if(Dt(r))return Re;const t=r.state;return 2&t.wrap?(t.head=e,e.done=!1,At):Re},inflateSetDictionary:(r,e)=>{const t=e.length;let n,i,s;return Dt(r)?Re:(n=r.state,n.wrap!==0&&n.mode!==16190?Re:n.mode===16190&&(i=1,i=Sr(i,e,t,0),i!==n.check)?ha:(s=ba(r,e,t,t),s?(n.mode=16210,pa):(n.havedict=1,At)))},inflateInfo:"pako inflate (from Nodeca project)"},_m=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};const Ea=Object.prototype.toString,{Z_NO_FLUSH:gm,Z_FINISH:vm,Z_OK:Ar,Z_STREAM_END:xi,Z_NEED_DICT:Ii,Z_STREAM_ERROR:ym,Z_DATA_ERROR:Ca,Z_MEM_ERROR:Sm}=kt;function Dr(r){this.options=oa({chunkSize:65536,windowBits:15,to:""},r||{});const 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 ua,this.strm.avail_out=0;let t=rt.inflateInit2(this.strm,e.windowBits);if(t!==Ar)throw new Error(Tt[t]);if(this.header=new _m,rt.inflateGetHeader(this.strm,this.header),e.dictionary&&(typeof e.dictionary=="string"?e.dictionary=ki(e.dictionary):Ea.call(e.dictionary)==="[object ArrayBuffer]"&&(e.dictionary=new Uint8Array(e.dictionary)),e.raw&&(t=rt.inflateSetDictionary(this.strm,e.dictionary),t!==Ar)))throw new Error(Tt[t])}function zi(r,e){const t=new Dr(e);if(t.push(r),t.err)throw t.msg||Tt[t.err];return t.result}Dr.prototype.push=function(r,e){const t=this.strm,n=this.options.chunkSize,i=this.options.dictionary;let s,a,o;if(this.ended)return!1;for(a=e===~~e?e:e===!0?vm:gm,Ea.call(r)==="[object ArrayBuffer]"?t.input=new Uint8Array(r):t.input=r,t.next_in=0,t.avail_in=t.input.length;;){for(t.avail_out===0&&(t.output=new Uint8Array(n),t.next_out=0,t.avail_out=n),s=rt.inflate(t,a),s===Ii&&i&&(s=rt.inflateSetDictionary(t,i),s===Ar?s=rt.inflate(t,a):s===Ca&&(s=Ii));t.avail_in>0&&s===xi&&t.state.wrap>0&&r[t.next_in]!==0;)rt.inflateReset(t),s=rt.inflate(t,a);switch(s){case ym:case Ca:case Ii:case Sm:return this.onEnd(s),this.ended=!0,!1}if(o=t.avail_out,t.next_out&&(t.avail_out===0||s===xi))if(this.options.to==="string"){let d=Jf(t.output,t.next_out),c=t.next_out-d,u=Wf(t.output,d);t.next_out=c,t.avail_out=n-c,c&&t.output.set(t.output.subarray(d,d+c),0),this.onData(u)}else this.onData(t.output.length===t.next_out?t.output:t.output.subarray(0,t.next_out));if(s!==Ar||o!==0){if(s===xi)return s=rt.inflateEnd(this.strm),this.onEnd(s),this.ended=!0,!0;if(t.avail_in===0)break}}return!0},Dr.prototype.onData=function(r){this.chunks.push(r)},Dr.prototype.onEnd=function(r){r===Ar&&(this.options.to==="string"?this.result=this.chunks.join(""):this.result=aa(this.chunks)),this.chunks=[],this.err=r,this.msg=this.strm.msg};var bm={Inflate:Dr,inflate:zi,inflateRaw:function(r,e){return(e=e||{}).raw=!0,zi(r,e)},ungzip:zi,constants:kt};const{Deflate:Em,deflate:Cm,deflateRaw:wm,gzip:Tm}=im,{Inflate:km,inflate:Rm,inflateRaw:Am,ungzip:Dm}=bm;var xm={Deflate:Em,deflate:Cm,deflateRaw:wm,gzip:Tm,Inflate:km,inflate:Rm,inflateRaw:Am,ungzip:Dm,constants:kt},Im=function(){function r(e,t){this.collector=e,this.config=t,this.requestType=t.request_type,this.supportBeacon=!(!window.navigator||!window.navigator.sendBeacon),this.errorCode={NO_URL:4001,IMG_ON:4e3,IMG_CATCH:4002,BEACON_FALSE:4003,XHR_ON:500,RESPONSE:5001,TIMEOUT:5005},this.customHeader=t.custom_request_header||{}}return r.prototype.useFetch=function(e){var t=e.url,n=e.data,i=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:i||"POST",headers:o,body:JSON.stringify(n)}).then(function(c){return c.json()}).then(function(c){s&&s(c)}).catch(function(c){a&&a(n,c)}):(this.requestType="xhr",console.log("your brwoser not support fetch, use xhr"),this.useRequest({url:t,data:n,method:i,success:s,fail:a}))},r.prototype.useBeacon=function(e){var t=e.url,n=e.data,i=e.success,s=e.fail;this.requestType!=="xhr"?window.navigator.sendBeacon(t,JSON.stringify(n))?i&&i():s&&s(n,this.errorCode.BEACON_FALSE):this.useXhr(e)},r.prototype.useXhr=function(e){var t=this,n=e.url,i=e.data,s=e.method,a=e.success,o=e.fail,d=e.timeout,c=e.withCredentials,u=e.app_key,h=e.zip;try{var l=new XMLHttpRequest,f=s||"POST";if(l.open(f,""+n,!0),l.setRequestHeader("Content-Type","application/json; charset=utf-8"),u&&l.setRequestHeader("X-MCS-AppKey",""+u),Object.keys(this.customHeader).length)for(var y in this.customHeader)l.setRequestHeader(y,this.customHeader[y]);c&&(l.withCredentials=!0),d&&(l.timeout=d,l.ontimeout=function(){o&&o(i,t.errorCode.TIMEOUT)}),l.onload=function(){if(a){var g=null;if(l.responseText){try{g=JSON.parse(l.responseText)}catch{g={}}a(g,i)}}},l.onerror=function(){l.abort(),o&&o(i,t.errorCode.XHR_ON)};try{var C=JSON.stringify(i),v=this.collector.configManager.getCurrentEnv();if(this.config.need_zip&&h)if(v==="row"){var E=new TextEncoder().encode(C),k=xm.gzip(E);l.setRequestHeader("Content-Encoding","gzip"),l.send(k)}else l.send(C),this.collector.logger.warn("your channel do not support gzip, use normal data!");else l.send(C)}catch(g){l.send(JSON.stringify(i)),this.collector.emit("sdk-inner-error",{type:"sdk_error_send",eventData:i,errorCode:1e3,msg:g.message||g.stack||"sdk_error_send"})}}catch(g){this.collector.emit("sdk-inner-error",{type:"sdk_error_request",eventData:i,errorCode:1001,msg:g.message||g.stack||"sdk_error_request"})}},r.prototype.useRequest=function(e){var t=e.useBeacon,n=e.forceXhr;if(this.requestType==="xhr")this.useXhr(e);else{if(t&&this.supportBeacon)return void this.useBeacon(e);if(this.requestType==="fetch"&&!n)return void this.useFetch(e);this.useXhr(e)}},r}(),zm=function(){function r(e,t){if(this.devToolReady=!1,this.sendAlready=!1,t.enable_debug&&e.configManager.get("browser")!=="Microsoft Internet Explorer"){this.collect=e,this.config=t,this.app_id=t.app_id;var n=e.adapters.storage;this.cacheStorgae=new n(!1),this.devToolOrigin=window.location.origin,this.currentInstance=t.current_instance||"",this.loadUrl=t.devtool_url||"https://sf16-website-login.neutral.ttwstatic.com/obj/tiktok_web_login_static/log-sdk/collect/devtool/debug-web.v2.0.0.js",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(n){console.log("devTool load fail, "+n.message)}},r.prototype.parseUrl=function(){var e={};try{var t=window.location.href.split("?")[1].split("&");t.length&&t.forEach(function(n){var i=n.split("=");e[decodeURIComponent(i[0])]=decodeURIComponent(i[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||e.current_instance&&e.current_instance!==this.currentInstance)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:"BaseInfo",key:"base",type:1,content:[{name:"app_id",desc:"APPID",value:this.config.app_id},{name:"channel",desc:"CHANNEL",value:this.config.channel},{name:"domain",desc:"Domain",value:this.collect.configManager.getDomain()},{name:"sdk_version",desc:"SDK Version",value:fr},{name:"sdk_type",desc:"SDK Import Type",value:"npm"}]},{title:"UserInfo",key:"user",type:2,content:[{name:"uuid",desc:"UserUniqueId",value:this.collect.configManager.get("user").user_unique_id||""},{name:"web_id",desc:"WEB_ID",value:this.collect.configManager.get("user").web_id||""}]},{title:"CommonInfo",type:2,key:"common",content:[{name:"browser",desc:"Browser",value:this.collect.configManager.get("browser")},{name:"browser_version",desc:"Browser Version",value:this.collect.configManager.get("browser_version")},{name:"platform",desc:"Platform",value:this.collect.configManager.get("platform")},{name:"device_model",desc:"Devide Model",value:this.collect.configManager.get("device_model")},{name:"os_name",desc:"Os Name",value:this.collect.configManager.get("os_name")},{name:"os_version",desc:"Os Version",value:this.collect.configManager.get("os_version")},{name:"resolution",desc:"Screen Resolution",value:this.collect.configManager.get("resolution")},{name:"referrer",desc:"Referrer",value:this.collect.configManager.get("referrer")},{name:"custom",desc:"Custom Info",value:JSON.stringify(this.collect.configManager.get("custom"))}]},{title:"Config Info",key:"config",type:3,content:[{name:"autotrack",desc:"AutoTrackEvent",value:!!this.config.autotrack},{name:"stay",desc:"StayDuration",value:!!this.config.enable_stay_duration}]},{title:"A/B Config Info",key:"ab",type:4,content:[{name:"ab",desc:"A/BTester",value:!!this.config.enable_ab_test}]}],this.config.enable_ab_test){var e=this.getInfo("ab"),t=[{name:"ab",desc:"A/BTester",value:!!this.config.enable_ab_test},{name:"vid",desc:"A/B VID",value:this.collect.configManager.getAbVersion()},{name:"ab_domain",desc:"Domain",value:this.config.ab_channel_domain||lr(mi[this.config.channel])},{name:"all_values",desc:"A/B ALL Values",value:this.collect.configManager.getAbCache()}];e.content=t,this.setInfo("ab",e)}},r.prototype.getInfo=function(e){var t=null;return this.info.forEach(function(n){n.key===e&&(t=n)}),t},r.prototype.setInfo=function(e,t){var n=!1;this.info.forEach(function(i){i.key===e&&(n=!0,i=t)}),n||this.info.push(t)},r.prototype.getSecondInfo=function(e,t){var n=this.getInfo(e),i=null;return n.content.forEach(function(s){s.name===t&&(i=s)}),i},r.prototype.setSecondInfo=function(e,t,n){var i=this.getInfo(e),s=!1;if(i.content.forEach(function(o){o.name===t&&(o.value=n,s=!0)}),!s){var a={name:t,value:n,desc:t.toLocaleUpperCase()};i.content.push(a)}this.setInfo(e,i)},r.prototype.loadHook=function(){var e=this;this.collect.on(T.DEBUGGER_MESSAGE,function(t){switch(t.type){case T.DEBUGGER_MESSAGE_SDK:var n={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&&(n.desc={content:JSON.stringify(t.data)}),e.updateLog(n),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 i=e.collect.configManager.get(t.common);e.setSecondInfo("common",t.common,t.common==="custom"?JSON.stringify(i):i)}return void e.updateInfo();case T.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(e.devToolOrigin===t.origin){if(t&&t.data&&t.data.type==="devtool:web:ready"){if(e.devToolOrigin=t.origin,e.devToolReady=!0,e.sendAlready)return;e.sendData("devtool:web:init",{info:e.info,log:e.log,event:e.event,sdk_type:fr.includes("tob")?"tob":"inner",appId:e.app_id}),e.sendAlready=!0}t&&t.data&&t.data.type==="devtool:web:ssid"&&e.collect.getToken(function(n){e.setSecondInfo("user","sid",n.tobid),e.updateInfo()})}})},r.prototype.sendData=function(e,t){try{var n={type:e,payload:t};window&&window.postMessage(n,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
|
+
`,fd=URL.createObjectURL(new Blob([pd],{type:"application/javascript"}));class md{constructor(){this._audioCtx=null,this._volume=0}get volume(){return this._volume}async start(e,t){if(this._audioCtx)return;const n=new AudioContext;await n.audioWorklet.addModule(t||fd);const i=new MediaStream;i.addTrack(e);const s=n.createMediaStreamSource(i),a=new AudioWorkletNode(n,"vumeter");a.port.onmessage=o=>{const d=o.data.volume||0;this._volume=Math.min(d*100/2,10)},s.connect(a).connect(n.destination),this._audioCtx=n}stop(){var e;(e=this._audioCtx)==null||e.close(),this._audioCtx=null}}class Xr{constructor(){this._volumeDetectScriptUrl=void 0}static get instance(){return this._instance||(this._instance=new Xr),this._instance}get volumeDetectScriptUrl(){return this._volumeDetectScriptUrl}set volumeDetectScriptUrl(e){this._volumeDetectScriptUrl=e}}class Fs extends st{constructor(e){super(),this._width=0,this._height=0,this._mediaStream=null,this._nextStream=null,this._trackMap={},this.type=e.type,this.id=hd(),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[Q.Camera,Q.Screen,Q.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 md),await this._volumeDetector.start(this.audioTrack,Xr.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 Fs{constructor(){super(...arguments),this._frameRate=1}get isVideoStream(){return!0}get isAudioStream(){return!1}get frameRate(){return this._frameRate}bindTrackSizeChangeEvent(e){e.on(ge.SIZE_CHANGE,({width:t,height:n})=>{this._width=t,this._height=n,this.emit(ps.SizeChange,{width:t,height:n})})}}class Zr extends Fs{get isVideoStream(){return!1}get isAudioStream(){return!0}}class _d extends Lt{constructor(e,t){super({type:Q.Camera,stream:e}),this._trackMap.video=e.track(),this._width=e.width(),this._height=e.height(),this._frameRate=(t==null?void 0:t.frameRate)??1,this.bindTrackSizeChangeEvent(e)}get source(){return this._source}get viewNode(){return this.source.node()}get mixerNode(){return null}bindTrackEnd(e){this.source.on(ge.ENDED,e)}destroy(){this.source.destroy()}}var Vs=typeof global=="object"&&global&&global.Object===Object&&global,gd=typeof self=="object"&&self&&self.Object===Object&&self,Je=Vs||gd||Function("return this")(),at=Je.Symbol,js=Object.prototype,vd=js.hasOwnProperty,yd=js.toString,tr=at?at.toStringTag:void 0;function Sd(r){var e=vd.call(r,tr),t=r[tr];try{r[tr]=void 0;var n=!0}catch{}var i=yd.call(r);return n&&(e?r[tr]=t:delete r[tr]),i}var bd=Object.prototype,Ed=bd.toString;function Cd(r){return Ed.call(r)}var wd="[object Null]",Td="[object Undefined]",Hs=at?at.toStringTag:void 0;function Nt(r){return r==null?r===void 0?Td:wd:Hs&&Hs in Object(r)?Sd(r):Cd(r)}function Ut(r){return r!=null&&typeof r=="object"}var kd="[object Symbol]";function Yr(r){return typeof r=="symbol"||Ut(r)&&Nt(r)==kd}function qs(r,e){for(var t=-1,n=r==null?0:r.length,i=Array(n);++t<n;)i[t]=e(r[t],t,r);return i}var ue=Array.isArray,$s=at?at.prototype:void 0,Ks=$s?$s.toString:void 0;function Ws(r){if(typeof r=="string")return r;if(ue(r))return qs(r,Ws)+"";if(Yr(r))return Ks?Ks.call(r):"";var e=r+"";return e=="0"&&1/r==-1/0?"-0":e}var Rd=/\s/;function Ad(r){for(var e=r.length;e--&&Rd.test(r.charAt(e)););return e}var Dd=/^\s+/;function xd(r){return r&&r.slice(0,Ad(r)+1).replace(Dd,"")}function rr(r){var e=typeof r;return r!=null&&(e=="object"||e=="function")}var Js=NaN,Id=/^[-+]0x[0-9a-f]+$/i,zd=/^0b[01]+$/i,Pd=/^0o[0-7]+$/i,Od=parseInt;function Md(r){if(typeof r=="number")return r;if(Yr(r))return Js;if(rr(r)){var e=typeof r.valueOf=="function"?r.valueOf():r;r=rr(e)?e+"":e}if(typeof r!="string")return r===0?r:+r;r=xd(r);var t=zd.test(r);return t||Pd.test(r)?Od(r.slice(2),t?2:8):Id.test(r)?Js:+r}var Ld=1/0,Nd=17976931348623157e292;function Ud(r){if(!r)return r===0?r:0;if(r=Md(r),r===Ld||r===-1/0){var e=r<0?-1:1;return e*Nd}return r===r?r:0}function Gd(r){var e=Ud(r),t=e%1;return e===e?t?e-t:e:0}function Bd(r){return r}var Fd="[object AsyncFunction]",Vd="[object Function]",jd="[object GeneratorFunction]",Hd="[object Proxy]";function Xs(r){if(!rr(r))return!1;var e=Nt(r);return e==Vd||e==jd||e==Fd||e==Hd}var Kn=Je["__core-js_shared__"],Zs=function(){var r=/[^.]+$/.exec(Kn&&Kn.keys&&Kn.keys.IE_PROTO||"");return r?"Symbol(src)_1."+r:""}();function qd(r){return!!Zs&&Zs in r}var $d=Function.prototype,Kd=$d.toString;function St(r){if(r!=null){try{return Kd.call(r)}catch{}try{return r+""}catch{}}return""}var Wd=/[\\^$.*+?()[\]{}|]/g,Jd=/^\[object .+?Constructor\]$/,Xd=Function.prototype,Zd=Object.prototype,Yd=Xd.toString,Qd=Zd.hasOwnProperty,el=RegExp("^"+Yd.call(Qd).replace(Wd,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function tl(r){if(!rr(r)||qd(r))return!1;var e=Xs(r)?el:Jd;return e.test(St(r))}function rl(r,e){return r==null?void 0:r[e]}function Gt(r,e){var t=rl(r,e);return tl(t)?t:void 0}var Wn=Gt(Je,"WeakMap");function nl(r,e,t,n){for(var i=r.length,s=t+-1;++s<i;)if(e(r[s],s,r))return s;return-1}var il=9007199254740991,sl=/^(?:0|[1-9]\d*)$/;function Ys(r,e){var t=typeof r;return e=e??il,!!e&&(t=="number"||t!="symbol"&&sl.test(r))&&r>-1&&r%1==0&&r<e}function Qs(r,e){return r===e||r!==r&&e!==e}var ol=9007199254740991;function Jn(r){return typeof r=="number"&&r>-1&&r%1==0&&r<=ol}function Qr(r){return r!=null&&Jn(r.length)&&!Xs(r)}var al=Object.prototype;function eo(r){var e=r&&r.constructor,t=typeof e=="function"&&e.prototype||al;return r===t}function cl(r,e){for(var t=-1,n=Array(r);++t<r;)n[t]=e(t);return n}var ul="[object Arguments]";function to(r){return Ut(r)&&Nt(r)==ul}var ro=Object.prototype,dl=ro.hasOwnProperty,ll=ro.propertyIsEnumerable,Xn=to(function(){return arguments}())?to:function(r){return Ut(r)&&dl.call(r,"callee")&&!ll.call(r,"callee")};function hl(){return!1}var no=typeof exports=="object"&&exports&&!exports.nodeType&&exports,io=no&&typeof module=="object"&&module&&!module.nodeType&&module,pl=io&&io.exports===no,so=pl?Je.Buffer:void 0,fl=so?so.isBuffer:void 0,en=fl||hl,ml="[object Arguments]",_l="[object Array]",gl="[object Boolean]",vl="[object Date]",yl="[object Error]",Sl="[object Function]",bl="[object Map]",El="[object Number]",Cl="[object Object]",wl="[object RegExp]",Tl="[object Set]",kl="[object String]",Rl="[object WeakMap]",Al="[object ArrayBuffer]",Dl="[object DataView]",xl="[object Float32Array]",Il="[object Float64Array]",zl="[object Int8Array]",Pl="[object Int16Array]",Ol="[object Int32Array]",Ml="[object Uint8Array]",Ll="[object Uint8ClampedArray]",Nl="[object Uint16Array]",Ul="[object Uint32Array]",re={};re[xl]=re[Il]=re[zl]=re[Pl]=re[Ol]=re[Ml]=re[Ll]=re[Nl]=re[Ul]=!0,re[ml]=re[_l]=re[Al]=re[gl]=re[Dl]=re[vl]=re[yl]=re[Sl]=re[bl]=re[El]=re[Cl]=re[wl]=re[Tl]=re[kl]=re[Rl]=!1;function Gl(r){return Ut(r)&&Jn(r.length)&&!!re[Nt(r)]}function Bl(r){return function(e){return r(e)}}var oo=typeof exports=="object"&&exports&&!exports.nodeType&&exports,nr=oo&&typeof module=="object"&&module&&!module.nodeType&&module,Fl=nr&&nr.exports===oo,Zn=Fl&&Vs.process,ao=function(){try{var r=nr&&nr.require&&nr.require("util").types;return r||Zn&&Zn.binding&&Zn.binding("util")}catch{}}(),co=ao&&ao.isTypedArray,Yn=co?Bl(co):Gl,Vl=Object.prototype,jl=Vl.hasOwnProperty;function Hl(r,e){var t=ue(r),n=!t&&Xn(r),i=!t&&!n&&en(r),s=!t&&!n&&!i&&Yn(r),a=t||n||i||s,o=a?cl(r.length,String):[],d=o.length;for(var c in r)jl.call(r,c)&&!(a&&(c=="length"||i&&(c=="offset"||c=="parent")||s&&(c=="buffer"||c=="byteLength"||c=="byteOffset")||Ys(c,d)))&&o.push(c);return o}function ql(r,e){return function(t){return r(e(t))}}var $l=ql(Object.keys,Object),Kl=Object.prototype,Wl=Kl.hasOwnProperty;function uo(r){if(!eo(r))return $l(r);var e=[];for(var t in Object(r))Wl.call(r,t)&&t!="constructor"&&e.push(t);return e}function ir(r){return Qr(r)?Hl(r):uo(r)}var Jl=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,Xl=/^\w*$/;function Qn(r,e){if(ue(r))return!1;var t=typeof r;return t=="number"||t=="symbol"||t=="boolean"||r==null||Yr(r)?!0:Xl.test(r)||!Jl.test(r)||e!=null&&r in Object(e)}var sr=Gt(Object,"create");function Zl(){this.__data__=sr?sr(null):{},this.size=0}function Yl(r){var e=this.has(r)&&delete this.__data__[r];return this.size-=e?1:0,e}var Ql="__lodash_hash_undefined__",eh=Object.prototype,th=eh.hasOwnProperty;function rh(r){var e=this.__data__;if(sr){var t=e[r];return t===Ql?void 0:t}return th.call(e,r)?e[r]:void 0}var nh=Object.prototype,ih=nh.hasOwnProperty;function sh(r){var e=this.__data__;return sr?e[r]!==void 0:ih.call(e,r)}var oh="__lodash_hash_undefined__";function ah(r,e){var t=this.__data__;return this.size+=this.has(r)?0:1,t[r]=sr&&e===void 0?oh:e,this}function bt(r){var e=-1,t=r==null?0:r.length;for(this.clear();++e<t;){var n=r[e];this.set(n[0],n[1])}}bt.prototype.clear=Zl,bt.prototype.delete=Yl,bt.prototype.get=rh,bt.prototype.has=sh,bt.prototype.set=ah;function ch(){this.__data__=[],this.size=0}function tn(r,e){for(var t=r.length;t--;)if(Qs(r[t][0],e))return t;return-1}var uh=Array.prototype,dh=uh.splice;function lh(r){var e=this.__data__,t=tn(e,r);if(t<0)return!1;var n=e.length-1;return t==n?e.pop():dh.call(e,t,1),--this.size,!0}function hh(r){var e=this.__data__,t=tn(e,r);return t<0?void 0:e[t][1]}function ph(r){return tn(this.__data__,r)>-1}function fh(r,e){var t=this.__data__,n=tn(t,r);return n<0?(++this.size,t.push([r,e])):t[n][1]=e,this}function Xe(r){var e=-1,t=r==null?0:r.length;for(this.clear();++e<t;){var n=r[e];this.set(n[0],n[1])}}Xe.prototype.clear=ch,Xe.prototype.delete=lh,Xe.prototype.get=hh,Xe.prototype.has=ph,Xe.prototype.set=fh;var or=Gt(Je,"Map");function mh(){this.size=0,this.__data__={hash:new bt,map:new(or||Xe),string:new bt}}function _h(r){var e=typeof r;return e=="string"||e=="number"||e=="symbol"||e=="boolean"?r!=="__proto__":r===null}function rn(r,e){var t=r.__data__;return _h(e)?t[typeof e=="string"?"string":"hash"]:t.map}function gh(r){var e=rn(this,r).delete(r);return this.size-=e?1:0,e}function vh(r){return rn(this,r).get(r)}function yh(r){return rn(this,r).has(r)}function Sh(r,e){var t=rn(this,r),n=t.size;return t.set(r,e),this.size+=t.size==n?0:1,this}function Ze(r){var e=-1,t=r==null?0:r.length;for(this.clear();++e<t;){var n=r[e];this.set(n[0],n[1])}}Ze.prototype.clear=mh,Ze.prototype.delete=gh,Ze.prototype.get=vh,Ze.prototype.has=yh,Ze.prototype.set=Sh;var bh="Expected a function";function ei(r,e){if(typeof r!="function"||e!=null&&typeof e!="function")throw new TypeError(bh);var t=function(){var n=arguments,i=e?e.apply(this,n):n[0],s=t.cache;if(s.has(i))return s.get(i);var a=r.apply(this,n);return t.cache=s.set(i,a)||s,a};return t.cache=new(ei.Cache||Ze),t}ei.Cache=Ze;var Eh=500;function Ch(r){var e=ei(r,function(n){return t.size===Eh&&t.clear(),n}),t=e.cache;return e}var wh=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,Th=/\\(\\)?/g,kh=Ch(function(r){var e=[];return r.charCodeAt(0)===46&&e.push(""),r.replace(wh,function(t,n,i,s){e.push(i?s.replace(Th,"$1"):n||t)}),e});function Rh(r){return r==null?"":Ws(r)}function lo(r,e){return ue(r)?r:Qn(r,e)?[r]:kh(Rh(r))}function nn(r){if(typeof r=="string"||Yr(r))return r;var e=r+"";return e=="0"&&1/r==-1/0?"-0":e}function ho(r,e){e=lo(e,r);for(var t=0,n=e.length;r!=null&&t<n;)r=r[nn(e[t++])];return t&&t==n?r:void 0}function Ah(r,e,t){var n=r==null?void 0:ho(r,e);return n===void 0?t:n}function Dh(r,e){for(var t=-1,n=e.length,i=r.length;++t<n;)r[i+t]=e[t];return r}function xh(){this.__data__=new Xe,this.size=0}function Ih(r){var e=this.__data__,t=e.delete(r);return this.size=e.size,t}function zh(r){return this.__data__.get(r)}function Ph(r){return this.__data__.has(r)}var Oh=200;function Mh(r,e){var t=this.__data__;if(t instanceof Xe){var n=t.__data__;if(!or||n.length<Oh-1)return n.push([r,e]),this.size=++t.size,this;t=this.__data__=new Ze(n)}return t.set(r,e),this.size=t.size,this}function Ye(r){var e=this.__data__=new Xe(r);this.size=e.size}Ye.prototype.clear=xh,Ye.prototype.delete=Ih,Ye.prototype.get=zh,Ye.prototype.has=Ph,Ye.prototype.set=Mh;function po(r,e){for(var t=-1,n=r==null?0:r.length,i=0,s=[];++t<n;){var a=r[t];e(a,t,r)&&(s[i++]=a)}return s}function Lh(){return[]}var Nh=Object.prototype,Uh=Nh.propertyIsEnumerable,fo=Object.getOwnPropertySymbols,Gh=fo?function(r){return r==null?[]:(r=Object(r),po(fo(r),function(e){return Uh.call(r,e)}))}:Lh;function Bh(r,e,t){var n=e(r);return ue(r)?n:Dh(n,t(r))}function mo(r){return Bh(r,ir,Gh)}var ti=Gt(Je,"DataView"),ri=Gt(Je,"Promise"),ni=Gt(Je,"Set"),_o="[object Map]",Fh="[object Object]",go="[object Promise]",vo="[object Set]",yo="[object WeakMap]",So="[object DataView]",Vh=St(ti),jh=St(or),Hh=St(ri),qh=St(ni),$h=St(Wn),Qe=Nt;(ti&&Qe(new ti(new ArrayBuffer(1)))!=So||or&&Qe(new or)!=_o||ri&&Qe(ri.resolve())!=go||ni&&Qe(new ni)!=vo||Wn&&Qe(new Wn)!=yo)&&(Qe=function(r){var e=Nt(r),t=e==Fh?r.constructor:void 0,n=t?St(t):"";if(n)switch(n){case Vh:return So;case jh:return _o;case Hh:return go;case qh:return vo;case $h:return yo}return e});var bo=Je.Uint8Array,Kh="__lodash_hash_undefined__";function Wh(r){return this.__data__.set(r,Kh),this}function Jh(r){return this.__data__.has(r)}function sn(r){var e=-1,t=r==null?0:r.length;for(this.__data__=new Ze;++e<t;)this.add(r[e])}sn.prototype.add=sn.prototype.push=Wh,sn.prototype.has=Jh;function Xh(r,e){for(var t=-1,n=r==null?0:r.length;++t<n;)if(e(r[t],t,r))return!0;return!1}function Zh(r,e){return r.has(e)}var Yh=1,Qh=2;function Eo(r,e,t,n,i,s){var a=t&Yh,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 h=-1,l=!0,f=t&Qh?new sn:void 0;for(s.set(r,e),s.set(e,r);++h<o;){var y=r[h],C=e[h];if(n)var v=a?n(C,y,h,e,r,s):n(y,C,h,r,e,s);if(v!==void 0){if(v)continue;l=!1;break}if(f){if(!Xh(e,function(E,k){if(!Zh(f,k)&&(y===E||i(y,E,t,n,s)))return f.push(k)})){l=!1;break}}else if(!(y===C||i(y,C,t,n,s))){l=!1;break}}return s.delete(r),s.delete(e),l}function ep(r){var e=-1,t=Array(r.size);return r.forEach(function(n,i){t[++e]=[i,n]}),t}function tp(r){var e=-1,t=Array(r.size);return r.forEach(function(n){t[++e]=n}),t}var rp=1,np=2,ip="[object Boolean]",sp="[object Date]",op="[object Error]",ap="[object Map]",cp="[object Number]",up="[object RegExp]",dp="[object Set]",lp="[object String]",hp="[object Symbol]",pp="[object ArrayBuffer]",fp="[object DataView]",Co=at?at.prototype:void 0,ii=Co?Co.valueOf:void 0;function mp(r,e,t,n,i,s,a){switch(t){case fp:if(r.byteLength!=e.byteLength||r.byteOffset!=e.byteOffset)return!1;r=r.buffer,e=e.buffer;case pp:return!(r.byteLength!=e.byteLength||!s(new bo(r),new bo(e)));case ip:case sp:case cp:return Qs(+r,+e);case op:return r.name==e.name&&r.message==e.message;case up:case lp:return r==e+"";case ap:var o=ep;case dp:var d=n&rp;if(o||(o=tp),r.size!=e.size&&!d)return!1;var c=a.get(r);if(c)return c==e;n|=np,a.set(r,e);var u=Eo(o(r),o(e),n,i,s,a);return a.delete(r),u;case hp:if(ii)return ii.call(r)==ii.call(e)}return!1}var _p=1,gp=Object.prototype,vp=gp.hasOwnProperty;function yp(r,e,t,n,i,s){var a=t&_p,o=mo(r),d=o.length,c=mo(e),u=c.length;if(d!=u&&!a)return!1;for(var h=d;h--;){var l=o[h];if(!(a?l in e:vp.call(e,l)))return!1}var f=s.get(r),y=s.get(e);if(f&&y)return f==e&&y==r;var C=!0;s.set(r,e),s.set(e,r);for(var v=a;++h<d;){l=o[h];var E=r[l],k=e[l];if(n)var g=a?n(k,E,l,e,r,s):n(E,k,l,r,e,s);if(!(g===void 0?E===k||i(E,k,t,n,s):g)){C=!1;break}v||(v=l=="constructor")}if(C&&!v){var D=r.constructor,L=e.constructor;D!=L&&"constructor"in r&&"constructor"in e&&!(typeof D=="function"&&D instanceof D&&typeof L=="function"&&L instanceof L)&&(C=!1)}return s.delete(r),s.delete(e),C}var Sp=1,wo="[object Arguments]",To="[object Array]",on="[object Object]",bp=Object.prototype,ko=bp.hasOwnProperty;function Ep(r,e,t,n,i,s){var a=ue(r),o=ue(e),d=a?To:Qe(r),c=o?To:Qe(e);d=d==wo?on:d,c=c==wo?on:c;var u=d==on,h=c==on,l=d==c;if(l&&en(r)){if(!en(e))return!1;a=!0,u=!1}if(l&&!u)return s||(s=new Ye),a||Yn(r)?Eo(r,e,t,n,i,s):mp(r,e,d,t,n,i,s);if(!(t&Sp)){var f=u&&ko.call(r,"__wrapped__"),y=h&&ko.call(e,"__wrapped__");if(f||y){var C=f?r.value():r,v=y?e.value():e;return s||(s=new Ye),i(C,v,t,n,s)}}return l?(s||(s=new Ye),yp(r,e,t,n,i,s)):!1}function si(r,e,t,n,i){return r===e?!0:r==null||e==null||!Ut(r)&&!Ut(e)?r!==r&&e!==e:Ep(r,e,t,n,si,i)}var Cp=1,wp=2;function Tp(r,e,t,n){var i=t.length,s=i;if(r==null)return!s;for(r=Object(r);i--;){var a=t[i];if(a[2]?a[1]!==r[a[0]]:!(a[0]in r))return!1}for(;++i<s;){a=t[i];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 Ye,h;if(!(h===void 0?si(c,d,Cp|wp,n,u):h))return!1}}return!0}function Ro(r){return r===r&&!rr(r)}function kp(r){for(var e=ir(r),t=e.length;t--;){var n=e[t],i=r[n];e[t]=[n,i,Ro(i)]}return e}function Ao(r,e){return function(t){return t==null?!1:t[r]===e&&(e!==void 0||r in Object(t))}}function Rp(r){var e=kp(r);return e.length==1&&e[0][2]?Ao(e[0][0],e[0][1]):function(t){return t===r||Tp(t,r,e)}}function Ap(r,e){return r!=null&&e in Object(r)}function Dp(r,e,t){e=lo(e,r);for(var n=-1,i=e.length,s=!1;++n<i;){var a=nn(e[n]);if(!(s=r!=null&&t(r,a)))break;r=r[a]}return s||++n!=i?s:(i=r==null?0:r.length,!!i&&Jn(i)&&Ys(a,i)&&(ue(r)||Xn(r)))}function xp(r,e){return r!=null&&Dp(r,e,Ap)}var Ip=1,zp=2;function Pp(r,e){return Qn(r)&&Ro(e)?Ao(nn(r),e):function(t){var n=Ah(t,r);return n===void 0&&n===e?xp(t,r):si(e,n,Ip|zp)}}function Op(r){return function(e){return e==null?void 0:e[r]}}function Mp(r){return function(e){return ho(e,r)}}function Lp(r){return Qn(r)?Op(nn(r)):Mp(r)}function oi(r){return typeof r=="function"?r:r==null?Bd:typeof r=="object"?ue(r)?Pp(r[0],r[1]):Rp(r):Lp(r)}function Np(r){return function(e,t,n){for(var i=-1,s=Object(e),a=n(e),o=a.length;o--;){var d=a[++i];if(t(s[d],d,s)===!1)break}return e}}var Up=Np();function Gp(r,e){return r&&Up(r,e,ir)}function Bp(r,e){return function(t,n){if(t==null)return t;if(!Qr(t))return r(t,n);for(var i=t.length,s=-1,a=Object(t);++s<i&&n(a[s],s,a)!==!1;);return t}}var Fp=Bp(Gp);function Vp(r,e){var t=[];return Fp(r,function(n,i,s){e(n,i,s)&&t.push(n)}),t}function Do(r,e){var t=ue(r)?po:Vp;return t(r,oi(e))}function jp(r){return function(e,t,n){var i=Object(e);if(!Qr(e)){var s=oi(t);e=ir(e),t=function(o){return s(i[o],o,i)}}var a=r(e,t,n);return a>-1?i[s?e[a]:a]:void 0}}var Hp=Math.max;function qp(r,e,t){var n=r==null?0:r.length;if(!n)return-1;var i=t==null?0:Gd(t);return i<0&&(i=Hp(n+i,0)),nl(r,oi(e),i)}var ar=jp(qp);function $p(r,e){return qs(e,function(t){return r[t]})}function et(r){return r==null?[]:$p(r,ir(r))}var Kp="[object Map]",Wp="[object Set]",Jp=Object.prototype,Xp=Jp.hasOwnProperty;function Zp(r){if(r==null)return!0;if(Qr(r)&&(ue(r)||typeof r=="string"||typeof r.splice=="function"||en(r)||Yn(r)||Xn(r)))return!r.length;var e=Qe(r);if(e==Kp||e==Wp)return!r.size;if(eo(r))return!uo(r).length;for(var t in r)if(Xp.call(r,t))return!1;return!0}function Yp(r){return r==null}class Qp extends Zr{constructor(e){super({type:Q.Microphone,stream:e}),this._trackMap.audio=e.track()}get source(){return this._source}get mixerNode(){return this.source.node()}bindTrackEnd(e){this.source.on(ge.ENDED,e)}destroy(){this.source.destroy()}}class ef extends Lt{constructor(e){super({type:Q.VideoFile,stream:e});const t=ar(e,i=>i.kind===te.VIDEO),n=ar(e,i=>i.kind===te.AUDIO);this._videoStream=t,this._audioStream=n,this._trackMap.video=t==null?void 0:t.track(),this._trackMap.audio=n==null?void 0:n.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(ge.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 tf extends Lt{constructor(e,t){super({type:Q.Screen,stream:e});const n=ar(e,s=>s.kind===te.VIDEO),i=ar(e,s=>s.kind===te.AUDIO);this._videoStream=n,this._audioStream=i,this._frameRate=(t==null?void 0:t.frameRate)??1,this._trackMap.video=n==null?void 0:n.track(),this._trackMap.audio=i==null?void 0:i.track(),n&&(this._height=n==null?void 0:n.height(),this._width=n==null?void 0:n.width(),this.bindTrackSizeChangeEvent(n))}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(ge.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 rf extends Zr{constructor(e){super({type:Q.AudioFile,stream:e});const t=ar(e,n=>n.kind===te.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(ge.ENDED,e)}destroy(){var e;(e=this._audioStream)==null||e.destroy()}}class nf extends Lt{constructor(e){super({type:Q.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(ge.ENDED,e)}destroy(){this.source.destroy()}}class sf extends Lt{constructor(e){super({type:Q.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(ge.ENDED,e)}destroy(){this.source.destroy()}}class of extends Zr{constructor(e){super({type:Q.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(ge.ENDED,e)}destroy(){var e;(e=this._audioStream)==null||e.destroy()}}const af=["user","environment"],cf=18e4,uf=1e4,xo=1e3;var ke=(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))(ke||{});class Bt extends Error{constructor(e,t,n){super(),this.code=e,this.message=t,n&&(this.ext=n)}}function Ft(r,e,t){const n=In.Landscape;if(e==="video"){const d=(n===In.Landscape?us:ds)[r],[c,u,h,l]=d.split("x").map(f=>Number(f));return{width:c,height:u,frameRate:h,bitrate:l*1e3}}const i=ls[r],[s,a]=i.split("x").map(o=>Number(o));return{sampleRate:s,bitrate:a*1e3}}var ne=function(){return(ne=Object.assign||function(r){for(var e,t=1,n=arguments.length;t<n;t++)for(var i in e=arguments[t])Object.prototype.hasOwnProperty.call(e,i)&&(r[i]=e[i]);return r}).apply(this,arguments)};function ai(r,e,t,n){return new(t||(t=Promise))(function(i,s){function a(c){try{d(n.next(c))}catch(u){s(u)}}function o(c){try{d(n.throw(c))}catch(u){s(u)}}function d(c){c.done?i(c.value):new t(function(u){u(c.value)}).then(a,o)}d((n=n.apply(r,[])).next())})}function ci(r,e){var t,n,i,s,a={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]};return s={next:o(0),throw:o(1),return:o(2)},typeof Symbol=="function"&&(s[Symbol.iterator]=function(){return this}),s;function o(d){return function(c){return function(u){if(t)throw new TypeError("Generator is already executing.");for(;a;)try{if(t=1,n&&(i=2&u[0]?n.return:u[0]?n.throw||((i=n.return)&&i.call(n),0):n.next)&&!(i=i.call(n,u[1])).done)return i;switch(n=0,i&&(u=[2&u[0],i.value]),u[0]){case 0:case 1:i=u;break;case 4:return a.label++,{value:u[1],done:!1};case 5:a.label++,n=u[1],u=[0];continue;case 7:u=a.ops.pop(),a.trys.pop();continue;default:if(i=a.trys,!((i=i.length>0&&i[i.length-1])||u[0]!==6&&u[0]!==2)){a=0;continue}if(u[0]===3&&(!i||u[1]>i[0]&&u[1]<i[3])){a.label=u[1];break}if(u[0]===6&&a.label<i[1]){a.label=i[1],i=u;break}if(i&&a.label<i[2]){a.label=i[2],a.ops.push(u);break}i[2]&&a.ops.pop(),a.trys.pop();continue}u=e.call(r,a)}catch(h){u=[6,h],n=0}finally{t=i=0}if(5&u[0])throw u[1];return{value:u[0]?u[1]:void 0,done:!0}}([d,c])}}}function df(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n,i,s=t.call(r),a=[];try{for(;(e===void 0||e-- >0)&&!(n=s.next()).done;)a.push(n.value)}catch(o){i={error:o}}finally{try{n&&!n.done&&(t=s.return)&&t.call(s)}finally{if(i)throw i.error}}return a}function cr(){for(var r=[],e=0;e<arguments.length;e++)r=r.concat(df(arguments[e]));return r}var Io,lf=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 n=this;e&&t&&typeof t=="function"&&this.on(e,function i(s){t(s),n.off(e,i)})},r.prototype.off=function(e,t){if(e&&this._hooks[e]&&this._hooks[e].length)if(t){var n=this._hooks[e].indexOf(t);n!==-1&&this._hooks[e].splice(n,1)}else this._hooks[e]=[]},r.prototype.emit=function(e,t,n){if(n){if(!e)return;this._cache.indexOf(n)!==-1?this._emit(e,t):(this._hooksCache.hasOwnProperty(n)||(this._hooksCache[n]={}),this._hooksCache[n].hasOwnProperty(e)||(this._hooksCache[n][e]=[]),this._hooksCache[n][e].push(t))}else this._emit(e,t)},r.prototype._emit=function(e,t){e&&this._hooks[e]&&this._hooks[e].length&&cr(this._hooks[e]).forEach(function(n){try{n(t)}catch{}})},r.prototype.set=function(e){e&&this._cache.indexOf(e)===-1&&this._cache.push(e)},r}(),ur=function(r){return r!=null&&Object.prototype.toString.call(r)=="[object Object]"},ui=function(r){return Array.isArray(r)},hf=(Io=+Date.now()+Number((""+Math.random()).slice(2,8)),function(){return Io+=1}),dr=function(r){return function(e,t,n){if(typeof e=="string"&&typeof n=="number"){var i,s=[];n=n<=25?n:n%25;var a=String.fromCharCode(n+97);i=e.split(a);for(var o=0;o<i.length;o++){var d=parseInt(i[o],n);d=1*d^t;var c=String.fromCharCode(d);s.push(c)}return s.join("")}}(r,64,25)},zo=function(){return!!navigator.userAgent.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/)},lr=function(r){zo()?window.addEventListener("pagehide",r,!1):window.addEventListener("beforeunload",r,!1)},Po=function(){var r=0;return["hidden","msHidden","webkitHidden"].forEach(function(e){document[e]!==void 0&&(r=1)}),r},di=function(r){var e=document.createElement("a");return e.href=r,e},an=function(r){var e={};try{var t=di(r).search;(t=t.slice(1)).split("&").forEach(function(n){var i,s,a=n.split("=");a.length&&(i=a[0],s=a[1]);try{e[i]=decodeURIComponent(s===void 0?"":s)}catch{e[i]=s}})}catch{}return e},cn=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function li(){throw new Error("Dynamic requires are not currently supported by rollup-plugin-commonjs")}function Oo(r,e){return r(e={exports:{}},e.exports),e.exports}var hr=Oo(function(r,e){var t;t=function(){function n(){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 i(s){return s.replace(/(%[0-9A-Z]{2})+/g,decodeURIComponent)}return function s(a){function o(){}function d(u,h,l){if(typeof document<"u"){typeof(l=n({path:"/"},o.defaults,l)).expires=="number"&&(l.expires=new Date(1*new Date+864e5*l.expires)),l.expires=l.expires?l.expires.toUTCString():"";try{var f=JSON.stringify(h);/^[\{\[]/.test(f)&&(h=f)}catch{}h=a.write?a.write(h,u):encodeURIComponent(String(h)).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 y="";for(var C in l)l[C]&&(y+="; "+C,l[C]!==!0&&(y+="="+l[C].split(";")[0]));return document.cookie=u+"="+h+y}}function c(u,h){if(typeof document<"u"){for(var l={},f=document.cookie?document.cookie.split("; "):[],y=0;y<f.length;y++){var C=f[y].split("="),v=C.slice(1).join("=");h||v.charAt(0)!=='"'||(v=v.slice(1,-1));try{var E=i(C[0]);if(v=(a.read||a)(v,E)||i(v),h)try{v=JSON.parse(v)}catch{}if(l[E]=v,u===E)break}catch{}}return u?l[u]:l}}return o.set=d,o.get=function(u){return c(u,!1)},o.getJSON=function(u){return c(u,!0)},o.remove=function(u,h){d(u,"",n(h,{expires:-1}))},o.defaults={},o.withConverter=s,o}(function(){})},r.exports=t()}),hi=Oo(function(r,e){r.exports=function t(n,i,s){function a(c,u){if(!i[c]){if(!n[c]){if(!u&&li)return li();if(o)return o(c,!0);var h=new Error("Cannot find module '"+c+"'");throw h.code="MODULE_NOT_FOUND",h}var l=i[c]={exports:{}};n[c][0].call(l.exports,function(f){var y=n[c][1][f];return a(y||f)},l,l.exports,t,n,i,s)}return i[c].exports}for(var o=li,d=0;d<s.length;d++)a(s[d]);return a}({1:[function(t,n,i){(function(s){var a,o,d=s.MutationObserver||s.WebKitMutationObserver;if(d){var c=0,u=new d(y),h=s.document.createTextNode("");u.observe(h,{characterData:!0}),a=function(){h.data=c=++c%2}}else if(s.setImmediate||s.MessageChannel===void 0)a="document"in s&&"onreadystatechange"in s.document.createElement("script")?function(){var C=s.document.createElement("script");C.onreadystatechange=function(){y(),C.onreadystatechange=null,C.parentNode.removeChild(C),C=null},s.document.documentElement.appendChild(C)}:function(){setTimeout(y,0)};else{var l=new s.MessageChannel;l.port1.onmessage=y,a=function(){l.port2.postMessage(0)}}var f=[];function y(){var C,v;o=!0;for(var E=f.length;E;){for(v=f,f=[],C=-1;++C<E;)v[C]();E=f.length}o=!1}n.exports=function(C){f.push(C)!==1||o||a()}}).call(this,cn!==void 0?cn:typeof self<"u"?self:typeof window<"u"?window:{})},{}],2:[function(t,n,i){var s=t(1);function a(){}var o={},d=["REJECTED"],c=["FULFILLED"],u=["PENDING"];function h(E){if(typeof E!="function")throw new TypeError("resolver must be a function");this.state=u,this.queue=[],this.outcome=void 0,E!==a&&C(this,E)}function l(E,k,g){this.promise=E,typeof k=="function"&&(this.onFulfilled=k,this.callFulfilled=this.otherCallFulfilled),typeof g=="function"&&(this.onRejected=g,this.callRejected=this.otherCallRejected)}function f(E,k,g){s(function(){var D;try{D=k(g)}catch(L){return o.reject(E,L)}D===E?o.reject(E,new TypeError("Cannot resolve promise with itself")):o.resolve(E,D)})}function y(E){var k=E&&E.then;if(E&&(typeof E=="object"||typeof E=="function")&&typeof k=="function")return function(){k.apply(E,arguments)}}function C(E,k){var g=!1;function D(M){g||(g=!0,o.reject(E,M))}function L(M){g||(g=!0,o.resolve(E,M))}var R=v(function(){k(L,D)});R.status==="error"&&D(R.value)}function v(E,k){var g={};try{g.value=E(k),g.status="success"}catch(D){g.status="error",g.value=D}return g}n.exports=h,h.prototype.catch=function(E){return this.then(null,E)},h.prototype.then=function(E,k){if(typeof E!="function"&&this.state===c||typeof k!="function"&&this.state===d)return this;var g=new this.constructor(a);return this.state!==u?f(g,this.state===c?E:k,this.outcome):this.queue.push(new l(g,E,k)),g},l.prototype.callFulfilled=function(E){o.resolve(this.promise,E)},l.prototype.otherCallFulfilled=function(E){f(this.promise,this.onFulfilled,E)},l.prototype.callRejected=function(E){o.reject(this.promise,E)},l.prototype.otherCallRejected=function(E){f(this.promise,this.onRejected,E)},o.resolve=function(E,k){var g=v(y,k);if(g.status==="error")return o.reject(E,g.value);var D=g.value;if(D)C(E,D);else{E.state=c,E.outcome=k;for(var L=-1,R=E.queue.length;++L<R;)E.queue[L].callFulfilled(k)}return E},o.reject=function(E,k){E.state=d,E.outcome=k;for(var g=-1,D=E.queue.length;++g<D;)E.queue[g].callRejected(k);return E},h.resolve=function(E){return E instanceof this?E:o.resolve(new this(a),E)},h.reject=function(E){var k=new this(a);return o.reject(k,E)},h.all=function(E){var k=this;if(Object.prototype.toString.call(E)!=="[object Array]")return this.reject(new TypeError("must be an array"));var g=E.length,D=!1;if(!g)return this.resolve([]);for(var L=new Array(g),R=0,M=-1,N=new this(a);++M<g;)U(E[M],M);return N;function U(B,H){k.resolve(B).then(function(Y){L[H]=Y,++R!==g||D||(D=!0,o.resolve(N,L))},function(Y){D||(D=!0,o.reject(N,Y))})}},h.race=function(E){var k=this;if(Object.prototype.toString.call(E)!=="[object Array]")return this.reject(new TypeError("must be an array"));var g=E.length,D=!1;if(!g)return this.resolve([]);for(var L,R=-1,M=new this(a);++R<g;)L=E[R],k.resolve(L).then(function(N){D||(D=!0,o.resolve(M,N))},function(N){D||(D=!0,o.reject(M,N))});return M}},{1:1}],3:[function(t,n,i){(function(s){typeof s.Promise!="function"&&(s.Promise=t(2))}).call(this,cn!==void 0?cn:typeof self<"u"?self:typeof window<"u"?window:{})},{2:2}],4:[function(t,n,i){var s=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(p){return typeof p}:function(p){return p&&typeof Symbol=="function"&&p.constructor===Symbol&&p!==Symbol.prototype?"symbol":typeof p},a=function(){try{if(typeof indexedDB<"u")return indexedDB;if(typeof webkitIndexedDB<"u")return webkitIndexedDB;if(typeof mozIndexedDB<"u")return mozIndexedDB;if(typeof OIndexedDB<"u")return OIndexedDB;if(typeof msIndexedDB<"u")return msIndexedDB}catch{return}}();function o(p,m){p=p||[],m=m||{};try{return new Blob(p,m)}catch(S){if(S.name!=="TypeError")throw S;for(var _=new(typeof BlobBuilder<"u"?BlobBuilder:typeof MSBlobBuilder<"u"?MSBlobBuilder:typeof MozBlobBuilder<"u"?MozBlobBuilder:WebKitBlobBuilder),w=0;w<p.length;w+=1)_.append(p[w]);return _.getBlob(m.type)}}typeof Promise>"u"&&t(3);var d=Promise;function c(p,m){m&&p.then(function(_){m(null,_)},function(_){m(_)})}function u(p,m,_){typeof m=="function"&&p.then(m),typeof _=="function"&&p.catch(_)}function h(p){return typeof p!="string"&&(console.warn(p+" used as a key, but it is not a string."),p=String(p)),p}function l(){if(arguments.length&&typeof arguments[arguments.length-1]=="function")return arguments[arguments.length-1]}var f=void 0,y={},C=Object.prototype.toString;function v(p){return typeof f=="boolean"?d.resolve(f):function(m){return new d(function(_){var w=m.transaction("local-forage-detect-blob-support","readwrite"),S=o([""]);w.objectStore("local-forage-detect-blob-support").put(S,"key"),w.onabort=function(b){b.preventDefault(),b.stopPropagation(),_(!1)},w.oncomplete=function(){var b=navigator.userAgent.match(/Chrome\/(\d+)/),A=navigator.userAgent.match(/Edge\//);_(A||!b||parseInt(b[1],10)>=43)}}).catch(function(){return!1})}(p).then(function(m){return f=m})}function E(p){var m=y[p.name],_={};_.promise=new d(function(w,S){_.resolve=w,_.reject=S}),m.deferredOperations.push(_),m.dbReady?m.dbReady=m.dbReady.then(function(){return _.promise}):m.dbReady=_.promise}function k(p){var m=y[p.name].deferredOperations.pop();if(m)return m.resolve(),m.promise}function g(p,m){var _=y[p.name].deferredOperations.pop();if(_)return _.reject(m),_.promise}function D(p,m){return new d(function(_,w){if(y[p.name]=y[p.name]||{forages:[],db:null,dbReady:null,deferredOperations:[]},p.db){if(!m)return _(p.db);E(p),p.db.close()}var S=[p.name];m&&S.push(p.version);var b=a.open.apply(a,S);m&&(b.onupgradeneeded=function(A){var I=b.result;try{I.createObjectStore(p.storeName),A.oldVersion<=1&&I.createObjectStore("local-forage-detect-blob-support")}catch(z){if(z.name!=="ConstraintError")throw z;console.warn('The database "'+p.name+'" has been upgraded from version '+A.oldVersion+" to version "+A.newVersion+', but the storage "'+p.storeName+'" already exists.')}}),b.onerror=function(A){A.preventDefault(),w(b.error)},b.onsuccess=function(){var A=b.result;A.onversionchange=function(I){I.target.close()},_(A),k(p)}})}function L(p){return D(p,!1)}function R(p){return D(p,!0)}function M(p,m){if(!p.db)return!0;var _=!p.db.objectStoreNames.contains(p.storeName),w=p.version<p.db.version,S=p.version>p.db.version;if(w&&(p.version!==m&&console.warn('The database "'+p.name+`" can't be downgraded from version `+p.db.version+" to version "+p.version+"."),p.version=p.db.version),S||_){if(_){var b=p.db.version+1;b>p.version&&(p.version=b)}return!0}return!1}function N(p){return o([function(m){for(var _=m.length,w=new ArrayBuffer(_),S=new Uint8Array(w),b=0;b<_;b++)S[b]=m.charCodeAt(b);return w}(atob(p.data))],{type:p.type})}function U(p){return p&&p.__local_forage_encoded_blob}function B(p){var m=this,_=m._initReady().then(function(){var w=y[m._dbInfo.name];if(w&&w.dbReady)return w.dbReady});return u(_,p,p),_}function H(p,m,_,w){w===void 0&&(w=1);try{var S=p.db.transaction(p.storeName,m);_(null,S)}catch(b){if(w>0&&(!p.db||b.name==="InvalidStateError"||b.name==="NotFoundError"))return d.resolve().then(function(){if(!p.db||b.name==="NotFoundError"&&!p.db.objectStoreNames.contains(p.storeName)&&p.version<=p.db.version)return p.db&&(p.version=p.db.version+1),R(p)}).then(function(){return function(A){E(A);for(var I=y[A.name],z=I.forages,O=0;O<z.length;O++){var G=z[O];G._dbInfo.db&&(G._dbInfo.db.close(),G._dbInfo.db=null)}return A.db=null,L(A).then(function(F){return A.db=F,M(A)?R(A):F}).then(function(F){A.db=I.db=F;for(var q=0;q<z.length;q++)z[q]._dbInfo.db=F}).catch(function(F){throw g(A,F),F})}(p).then(function(){H(p,m,_,w-1)})}).catch(_);_(b)}}var Y={_driver:"asyncStorage",_initStorage:function(p){var m=this,_={db:null};if(p)for(var w in p)_[w]=p[w];var S=y[_.name];S||(S={forages:[],db:null,dbReady:null,deferredOperations:[]},y[_.name]=S),S.forages.push(m),m._initReady||(m._initReady=m.ready,m.ready=B);var b=[];function A(){return d.resolve()}for(var I=0;I<S.forages.length;I++){var z=S.forages[I];z!==m&&b.push(z._initReady().catch(A))}var O=S.forages.slice(0);return d.all(b).then(function(){return _.db=S.db,L(_)}).then(function(G){return _.db=G,M(_,m._defaultConfig.version)?R(_):G}).then(function(G){_.db=S.db=G,m._dbInfo=_;for(var F=0;F<O.length;F++){var q=O[F];q!==m&&(q._dbInfo.db=_.db,q._dbInfo.version=_.version)}})},_support:function(){try{if(!a||!a.open)return!1;var p=typeof openDatabase<"u"&&/(Safari|iPhone|iPad|iPod)/.test(navigator.userAgent)&&!/Chrome/.test(navigator.userAgent)&&!/BlackBerry/.test(navigator.platform),m=typeof fetch=="function"&&fetch.toString().indexOf("[native code")!==-1;return(!p||m)&&typeof indexedDB<"u"&&typeof IDBKeyRange<"u"}catch{return!1}}(),iterate:function(p,m){var _=this,w=new d(function(S,b){_.ready().then(function(){H(_._dbInfo,"readonly",function(A,I){if(A)return b(A);try{var z=I.objectStore(_._dbInfo.storeName).openCursor(),O=1;z.onsuccess=function(){var G=z.result;if(G){var F=G.value;U(F)&&(F=N(F));var q=p(F,G.key,O++);q!==void 0?S(q):G.continue()}else S()},z.onerror=function(){b(z.error)}}catch(G){b(G)}})}).catch(b)});return c(w,m),w},getItem:function(p,m){var _=this;p=h(p);var w=new d(function(S,b){_.ready().then(function(){H(_._dbInfo,"readonly",function(A,I){if(A)return b(A);try{var z=I.objectStore(_._dbInfo.storeName).get(p);z.onsuccess=function(){var O=z.result;O===void 0&&(O=null),U(O)&&(O=N(O)),S(O)},z.onerror=function(){b(z.error)}}catch(O){b(O)}})}).catch(b)});return c(w,m),w},setItem:function(p,m,_){var w=this;p=h(p);var S=new d(function(b,A){var I;w.ready().then(function(){return I=w._dbInfo,C.call(m)==="[object Blob]"?v(I.db).then(function(z){return z?m:(O=m,new d(function(G,F){var q=new FileReader;q.onerror=F,q.onloadend=function(X){var J=btoa(X.target.result||"");G({__local_forage_encoded_blob:!0,data:J,type:O.type})},q.readAsBinaryString(O)}));var O}):m}).then(function(z){H(w._dbInfo,"readwrite",function(O,G){if(O)return A(O);try{var F=G.objectStore(w._dbInfo.storeName);z===null&&(z=void 0);var q=F.put(z,p);G.oncomplete=function(){z===void 0&&(z=null),b(z)},G.onabort=G.onerror=function(){try{var X=q.error?q.error:q.transaction.error;A(X)}catch(J){A(J)}}}catch(X){A(X)}})}).catch(A)});return c(S,_),S},removeItem:function(p,m){var _=this;p=h(p);var w=new d(function(S,b){_.ready().then(function(){H(_._dbInfo,"readwrite",function(A,I){if(A)return b(A);try{var z=I.objectStore(_._dbInfo.storeName).delete(p);I.oncomplete=function(){S()},I.onerror=function(){b(z.error)},I.onabort=function(){try{var O=z.error?z.error:z.transaction.error;b(O)}catch(G){b(G)}}}catch(O){b(O)}})}).catch(b)});return c(w,m),w},clear:function(p){var m=this,_=new d(function(w,S){m.ready().then(function(){H(m._dbInfo,"readwrite",function(b,A){if(b)return S(b);try{var I=A.objectStore(m._dbInfo.storeName).clear();A.oncomplete=function(){w()},A.onabort=A.onerror=function(){try{var z=I.error?I.error:I.transaction.error;S(z)}catch(O){S(O)}}}catch(z){S(z)}})}).catch(S)});return c(_,p),_},length:function(p){var m=this,_=new d(function(w,S){m.ready().then(function(){H(m._dbInfo,"readonly",function(b,A){if(b)return S(b);try{var I=A.objectStore(m._dbInfo.storeName).count();I.onsuccess=function(){w(I.result)},I.onerror=function(){S(I.error)}}catch(z){S(z)}})}).catch(S)});return c(_,p),_},key:function(p,m){var _=this,w=new d(function(S,b){p<0?S(null):_.ready().then(function(){H(_._dbInfo,"readonly",function(A,I){if(A)return b(A);try{var z=I.objectStore(_._dbInfo.storeName),O=!1,G=(z.openKeyCursor||z.openCursor).call(z);G.onsuccess=function(){var F=G.result;F?p===0||O?S(F.key):(O=!0,F.advance(p)):S(null)},G.onerror=function(){b(G.error)}}catch(F){b(F)}})}).catch(b)});return c(w,m),w},keys:function(p){var m=this,_=new d(function(w,S){m.ready().then(function(){H(m._dbInfo,"readonly",function(b,A){if(b)return S(b);try{var I=A.objectStore(m._dbInfo.storeName),z=(I.openKeyCursor||I.openCursor).call(I),O=[];z.onsuccess=function(){var G=z.result;G?(O.push(G.key),G.continue()):w(O)},z.onerror=function(){S(z.error)}}catch(G){S(G)}})}).catch(S)});return c(_,p),_},dropInstance:function(p,m){m=l.apply(this,arguments);var _=this.config();(p=typeof p!="function"&&p||{}).name||(p.name=p.name||_.name,p.storeName=p.storeName||_.storeName);var w,S=this;if(p.name){var b=p.name===_.name&&S._dbInfo.db,A=b?d.resolve(S._dbInfo.db):L(p).then(function(I){var z=y[p.name],O=z.forages;z.db=I;for(var G=0;G<O.length;G++)O[G]._dbInfo.db=I;return I});w=p.storeName?A.then(function(I){if(I.objectStoreNames.contains(p.storeName)){var z=I.version+1;E(p);var O=y[p.name],G=O.forages;I.close();for(var F=0;F<G.length;F++){var q=G[F];q._dbInfo.db=null,q._dbInfo.version=z}return new d(function(X,J){var me=a.open(p.name,z);me.onerror=function(Ot){me.result.close(),J(Ot)},me.onupgradeneeded=function(){me.result.deleteObjectStore(p.storeName)},me.onsuccess=function(){var Ot=me.result;Ot.close(),X(Ot)}}).then(function(X){O.db=X;for(var J=0;J<G.length;J++){var me=G[J];me._dbInfo.db=X,k(me._dbInfo)}}).catch(function(X){throw(g(p,X)||d.resolve()).catch(function(){}),X})}}):A.then(function(I){E(p);var z=y[p.name],O=z.forages;I.close();for(var G=0;G<O.length;G++)O[G]._dbInfo.db=null;return new d(function(F,q){var X=a.deleteDatabase(p.name);X.onerror=function(){var J=X.result;J&&J.close(),q(X.error)},X.onblocked=function(){console.warn('dropInstance blocked for database "'+p.name+'" until all open connections are closed')},X.onsuccess=function(){var J=X.result;J&&J.close(),F(J)}}).then(function(F){z.db=F;for(var q=0;q<O.length;q++)k(O[q]._dbInfo)}).catch(function(F){throw(g(p,F)||d.resolve()).catch(function(){}),F})})}else w=d.reject("Invalid arguments");return c(w,m),w}},W="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",de=/^~~local_forage_type~([^~]+)~/,ce=9,Ee=ce+4,Ce=Object.prototype.toString;function we(p){var m,_,w,S,b,A=.75*p.length,I=p.length,z=0;p[p.length-1]==="="&&(A--,p[p.length-2]==="="&&A--);var O=new ArrayBuffer(A),G=new Uint8Array(O);for(m=0;m<I;m+=4)_=W.indexOf(p[m]),w=W.indexOf(p[m+1]),S=W.indexOf(p[m+2]),b=W.indexOf(p[m+3]),G[z++]=_<<2|w>>4,G[z++]=(15&w)<<4|S>>2,G[z++]=(3&S)<<6|63&b;return O}function ye(p){var m,_=new Uint8Array(p),w="";for(m=0;m<_.length;m+=3)w+=W[_[m]>>2],w+=W[(3&_[m])<<4|_[m+1]>>4],w+=W[(15&_[m+1])<<2|_[m+2]>>6],w+=W[63&_[m+2]];return _.length%3==2?w=w.substring(0,w.length-1)+"=":_.length%3==1&&(w=w.substring(0,w.length-2)+"=="),w}var Le={serialize:function(p,m){var _="";if(p&&(_=Ce.call(p)),p&&(_==="[object ArrayBuffer]"||p.buffer&&Ce.call(p.buffer)==="[object ArrayBuffer]")){var w,S="__lfsc__:";p instanceof ArrayBuffer?(w=p,S+="arbf"):(w=p.buffer,_==="[object Int8Array]"?S+="si08":_==="[object Uint8Array]"?S+="ui08":_==="[object Uint8ClampedArray]"?S+="uic8":_==="[object Int16Array]"?S+="si16":_==="[object Uint16Array]"?S+="ur16":_==="[object Int32Array]"?S+="si32":_==="[object Uint32Array]"?S+="ui32":_==="[object Float32Array]"?S+="fl32":_==="[object Float64Array]"?S+="fl64":m(new Error("Failed to get type for BinaryArray"))),m(S+ye(w))}else if(_==="[object Blob]"){var b=new FileReader;b.onload=function(){var A="~~local_forage_type~"+p.type+"~"+ye(this.result);m("__lfsc__:blob"+A)},b.readAsArrayBuffer(p)}else try{m(JSON.stringify(p))}catch(A){console.error("Couldn't convert value into a JSON string: ",p),m(null,A)}},deserialize:function(p){if(p.substring(0,ce)!=="__lfsc__:")return JSON.parse(p);var m,_=p.substring(Ee),w=p.substring(ce,Ee);if(w==="blob"&&de.test(_)){var S=_.match(de);m=S[1],_=_.substring(S[0].length)}var b=we(_);switch(w){case"arbf":return b;case"blob":return o([b],{type:m});case"si08":return new Int8Array(b);case"ui08":return new Uint8Array(b);case"uic8":return new Uint8ClampedArray(b);case"si16":return new Int16Array(b);case"ur16":return new Uint16Array(b);case"si32":return new Int32Array(b);case"ui32":return new Uint32Array(b);case"fl32":return new Float32Array(b);case"fl64":return new Float64Array(b);default:throw new Error("Unkown type: "+w)}},stringToBuffer:we,bufferToString:ye};function Ge(p,m,_,w){p.executeSql("CREATE TABLE IF NOT EXISTS "+m.storeName+" (id INTEGER PRIMARY KEY, key unique, value)",[],_,w)}function Te(p,m,_,w,S,b){p.executeSql(_,w,S,function(A,I){I.code===I.SYNTAX_ERR?A.executeSql("SELECT name FROM sqlite_master WHERE type='table' AND name = ?",[m.storeName],function(z,O){O.rows.length?b(z,I):Ge(z,m,function(){z.executeSql(_,w,S,b)},b)},b):b(A,I)},b)}function _t(p,m,_,w){var S=this;p=h(p);var b=new d(function(A,I){S.ready().then(function(){m===void 0&&(m=null);var z=m,O=S._dbInfo;O.serializer.serialize(m,function(G,F){F?I(F):O.db.transaction(function(q){Te(q,O,"INSERT OR REPLACE INTO "+O.storeName+" (key, value) VALUES (?, ?)",[p,G],function(){A(z)},function(X,J){I(J)})},function(q){if(q.code===q.QUOTA_ERR){if(w>0)return void A(_t.apply(S,[p,z,_,w-1]));I(q)}})})}).catch(I)});return c(b,_),b}function It(p){return new d(function(m,_){p.transaction(function(w){w.executeSql("SELECT name FROM sqlite_master WHERE type='table' AND name <> '__WebKitDatabaseInfoTable__'",[],function(S,b){for(var A=[],I=0;I<b.rows.length;I++)A.push(b.rows.item(I).name);m({db:p,storeNames:A})},function(S,b){_(b)})},function(w){_(w)})})}var zt={_driver:"webSQLStorage",_initStorage:function(p){var m=this,_={db:null};if(p)for(var w in p)_[w]=typeof p[w]!="string"?p[w].toString():p[w];var S=new d(function(b,A){try{_.db=openDatabase(_.name,String(_.version),_.description,_.size)}catch(I){return A(I)}_.db.transaction(function(I){Ge(I,_,function(){m._dbInfo=_,b()},function(z,O){A(O)})},A)});return _.serializer=Le,S},_support:typeof openDatabase=="function",iterate:function(p,m){var _=this,w=new d(function(S,b){_.ready().then(function(){var A=_._dbInfo;A.db.transaction(function(I){Te(I,A,"SELECT * FROM "+A.storeName,[],function(z,O){for(var G=O.rows,F=G.length,q=0;q<F;q++){var X=G.item(q),J=X.value;if(J&&(J=A.serializer.deserialize(J)),(J=p(J,X.key,q+1))!==void 0)return void S(J)}S()},function(z,O){b(O)})})}).catch(b)});return c(w,m),w},getItem:function(p,m){var _=this;p=h(p);var w=new d(function(S,b){_.ready().then(function(){var A=_._dbInfo;A.db.transaction(function(I){Te(I,A,"SELECT * FROM "+A.storeName+" WHERE key = ? LIMIT 1",[p],function(z,O){var G=O.rows.length?O.rows.item(0).value:null;G&&(G=A.serializer.deserialize(G)),S(G)},function(z,O){b(O)})})}).catch(b)});return c(w,m),w},setItem:function(p,m,_){return _t.apply(this,[p,m,_,1])},removeItem:function(p,m){var _=this;p=h(p);var w=new d(function(S,b){_.ready().then(function(){var A=_._dbInfo;A.db.transaction(function(I){Te(I,A,"DELETE FROM "+A.storeName+" WHERE key = ?",[p],function(){S()},function(z,O){b(O)})})}).catch(b)});return c(w,m),w},clear:function(p){var m=this,_=new d(function(w,S){m.ready().then(function(){var b=m._dbInfo;b.db.transaction(function(A){Te(A,b,"DELETE FROM "+b.storeName,[],function(){w()},function(I,z){S(z)})})}).catch(S)});return c(_,p),_},length:function(p){var m=this,_=new d(function(w,S){m.ready().then(function(){var b=m._dbInfo;b.db.transaction(function(A){Te(A,b,"SELECT COUNT(key) as c FROM "+b.storeName,[],function(I,z){var O=z.rows.item(0).c;w(O)},function(I,z){S(z)})})}).catch(S)});return c(_,p),_},key:function(p,m){var _=this,w=new d(function(S,b){_.ready().then(function(){var A=_._dbInfo;A.db.transaction(function(I){Te(I,A,"SELECT key FROM "+A.storeName+" WHERE id = ? LIMIT 1",[p+1],function(z,O){var G=O.rows.length?O.rows.item(0).key:null;S(G)},function(z,O){b(O)})})}).catch(b)});return c(w,m),w},keys:function(p){var m=this,_=new d(function(w,S){m.ready().then(function(){var b=m._dbInfo;b.db.transaction(function(A){Te(A,b,"SELECT key FROM "+b.storeName,[],function(I,z){for(var O=[],G=0;G<z.rows.length;G++)O.push(z.rows.item(G).key);w(O)},function(I,z){S(z)})})}).catch(S)});return c(_,p),_},dropInstance:function(p,m){m=l.apply(this,arguments);var _=this.config();(p=typeof p!="function"&&p||{}).name||(p.name=p.name||_.name,p.storeName=p.storeName||_.storeName);var w,S=this;return c(w=p.name?new d(function(b){var A;A=p.name===_.name?S._dbInfo.db:openDatabase(p.name,"","",0),p.storeName?b({db:A,storeNames:[p.storeName]}):b(It(A))}).then(function(b){return new d(function(A,I){b.db.transaction(function(z){function O(X){return new d(function(J,me){z.executeSql("DROP TABLE IF EXISTS "+X,[],function(){J()},function(Ot,jr){me(jr)})})}for(var G=[],F=0,q=b.storeNames.length;F<q;F++)G.push(O(b.storeNames[F]));d.all(G).then(function(){A()}).catch(function(X){I(X)})},function(z){I(z)})})}):d.reject("Invalid arguments"),m),w}};function Nr(p,m){var _=p.name+"/";return p.storeName!==m.storeName&&(_+=p.storeName+"/"),_}function Rn(){return!function(){try{return localStorage.setItem("_localforage_support_test",!0),localStorage.removeItem("_localforage_support_test"),!1}catch{return!0}}()||localStorage.length>0}var An={_driver:"localStorageWrapper",_initStorage:function(p){var m={};if(p)for(var _ in p)m[_]=p[_];return m.keyPrefix=Nr(p,this._defaultConfig),Rn()?(this._dbInfo=m,m.serializer=Le,d.resolve()):d.reject()},_support:function(){try{return typeof localStorage<"u"&&"setItem"in localStorage&&!!localStorage.setItem}catch{return!1}}(),iterate:function(p,m){var _=this,w=_.ready().then(function(){for(var S=_._dbInfo,b=S.keyPrefix,A=b.length,I=localStorage.length,z=1,O=0;O<I;O++){var G=localStorage.key(O);if(G.indexOf(b)===0){var F=localStorage.getItem(G);if(F&&(F=S.serializer.deserialize(F)),(F=p(F,G.substring(A),z++))!==void 0)return F}}});return c(w,m),w},getItem:function(p,m){var _=this;p=h(p);var w=_.ready().then(function(){var S=_._dbInfo,b=localStorage.getItem(S.keyPrefix+p);return b&&(b=S.serializer.deserialize(b)),b});return c(w,m),w},setItem:function(p,m,_){var w=this;p=h(p);var S=w.ready().then(function(){m===void 0&&(m=null);var b=m;return new d(function(A,I){var z=w._dbInfo;z.serializer.serialize(m,function(O,G){if(G)I(G);else try{localStorage.setItem(z.keyPrefix+p,O),A(b)}catch(F){F.name!=="QuotaExceededError"&&F.name!=="NS_ERROR_DOM_QUOTA_REACHED"||I(F),I(F)}})})});return c(S,_),S},removeItem:function(p,m){var _=this;p=h(p);var w=_.ready().then(function(){var S=_._dbInfo;localStorage.removeItem(S.keyPrefix+p)});return c(w,m),w},clear:function(p){var m=this,_=m.ready().then(function(){for(var w=m._dbInfo.keyPrefix,S=localStorage.length-1;S>=0;S--){var b=localStorage.key(S);b.indexOf(w)===0&&localStorage.removeItem(b)}});return c(_,p),_},length:function(p){var m=this.keys().then(function(_){return _.length});return c(m,p),m},key:function(p,m){var _=this,w=_.ready().then(function(){var S,b=_._dbInfo;try{S=localStorage.key(p)}catch{S=null}return S&&(S=S.substring(b.keyPrefix.length)),S});return c(w,m),w},keys:function(p){var m=this,_=m.ready().then(function(){for(var w=m._dbInfo,S=localStorage.length,b=[],A=0;A<S;A++){var I=localStorage.key(A);I.indexOf(w.keyPrefix)===0&&b.push(I.substring(w.keyPrefix.length))}return b});return c(_,p),_},dropInstance:function(p,m){if(m=l.apply(this,arguments),!(p=typeof p!="function"&&p||{}).name){var _=this.config();p.name=p.name||_.name,p.storeName=p.storeName||_.storeName}var w,S=this;return c(w=p.name?new d(function(b){p.storeName?b(Nr(p,S._defaultConfig)):b(p.name+"/")}).then(function(b){for(var A=localStorage.length-1;A>=0;A--){var I=localStorage.key(A);I.indexOf(b)===0&&localStorage.removeItem(I)}}):d.reject("Invalid arguments"),m),w}},Dn=function(p,m){for(var _,w,S=p.length,b=0;b<S;){if((_=p[b])===(w=m)||typeof _=="number"&&typeof w=="number"&&isNaN(_)&&isNaN(w))return!0;b++}return!1},Ur=Array.isArray||function(p){return Object.prototype.toString.call(p)==="[object Array]"},gt={},Gr={},De={INDEXEDDB:Y,WEBSQL:zt,LOCALSTORAGE:An},Br=[De.INDEXEDDB._driver,De.WEBSQL._driver,De.LOCALSTORAGE._driver],nt=["dropInstance"],Pt=["clear","getItem","iterate","key","keys","length","removeItem","setItem"].concat(nt),Fr={description:"",driver:Br.slice(),name:"localforage",size:4980736,storeName:"keyvaluepairs",version:1};function xn(p,m){p[m]=function(){var _=arguments;return p.ready().then(function(){return p[m].apply(p,_)})}}function Vr(){for(var p=1;p<arguments.length;p++){var m=arguments[p];if(m)for(var _ in m)m.hasOwnProperty(_)&&(Ur(m[_])?arguments[0][_]=m[_].slice():arguments[0][_]=m[_])}return arguments[0]}var os=new(function(){function p(m){for(var _ in function(b,A){if(!(b instanceof A))throw new TypeError("Cannot call a class as a function")}(this,p),De)if(De.hasOwnProperty(_)){var w=De[_],S=w._driver;this[_]=S,gt[S]||this.defineDriver(w)}this._defaultConfig=Vr({},Fr),this._config=Vr({},this._defaultConfig,m),this._driverSet=null,this._initDriver=null,this._ready=!1,this._dbInfo=null,this._wrapLibraryMethodsWithReady(),this.setDriver(this._config.driver).catch(function(){})}return p.prototype.config=function(m){if((m===void 0?"undefined":s(m))==="object"){if(this._ready)return new Error("Can't call config() after localforage has been used.");for(var _ in m){if(_==="storeName"&&(m[_]=m[_].replace(/\W/g,"_")),_==="version"&&typeof m[_]!="number")return new Error("Database version must be a number.");this._config[_]=m[_]}return!("driver"in m)||!m.driver||this.setDriver(this._config.driver)}return typeof m=="string"?this._config[m]:this._config},p.prototype.defineDriver=function(m,_,w){var S=new d(function(b,A){try{var I=m._driver,z=new Error("Custom driver not compliant; see https://mozilla.github.io/localForage/#definedriver");if(!m._driver)return void A(z);for(var O=Pt.concat("_initStorage"),G=0,F=O.length;G<F;G++){var q=O[G];if((!Dn(nt,q)||m[q])&&typeof m[q]!="function")return void A(z)}(function(){for(var J=function(Sg){return function(){var bg=new Error("Method "+Sg+" is not implemented by the current driver"),Hc=d.reject(bg);return c(Hc,arguments[arguments.length-1]),Hc}},me=0,Ot=nt.length;me<Ot;me++){var jr=nt[me];m[jr]||(m[jr]=J(jr))}})();var X=function(J){gt[I]&&console.info("Redefining LocalForage driver: "+I),gt[I]=m,Gr[I]=J,b()};"_support"in m?m._support&&typeof m._support=="function"?m._support().then(X,A):X(!!m._support):X(!0)}catch(J){A(J)}});return u(S,_,w),S},p.prototype.driver=function(){return this._driver||null},p.prototype.getDriver=function(m,_,w){var S=gt[m]?d.resolve(gt[m]):d.reject(new Error("Driver not found."));return u(S,_,w),S},p.prototype.getSerializer=function(m){var _=d.resolve(Le);return u(_,m),_},p.prototype.ready=function(m){var _=this,w=_._driverSet.then(function(){return _._ready===null&&(_._ready=_._initDriver()),_._ready});return u(w,m,m),w},p.prototype.setDriver=function(m,_,w){var S=this;Ur(m)||(m=[m]);var b=this._getSupportedDrivers(m);function A(){S._config.driver=S.driver()}function I(O){return S._extend(O),A(),S._ready=S._initStorage(S._config),S._ready}var z=this._driverSet!==null?this._driverSet.catch(function(){return d.resolve()}):d.resolve();return this._driverSet=z.then(function(){var O=b[0];return S._dbInfo=null,S._ready=null,S.getDriver(O).then(function(G){S._driver=G._driver,A(),S._wrapLibraryMethodsWithReady(),S._initDriver=function(F){return function(){var q=0;return function X(){for(;q<F.length;){var J=F[q];return q++,S._dbInfo=null,S._ready=null,S.getDriver(J).then(I).catch(X)}A();var me=new Error("No available storage method found.");return S._driverSet=d.reject(me),S._driverSet}()}}(b)})}).catch(function(){A();var O=new Error("No available storage method found.");return S._driverSet=d.reject(O),S._driverSet}),u(this._driverSet,_,w),this._driverSet},p.prototype.supports=function(m){return!!Gr[m]},p.prototype._extend=function(m){Vr(this,m)},p.prototype._getSupportedDrivers=function(m){for(var _=[],w=0,S=m.length;w<S;w++){var b=m[w];this.supports(b)&&_.push(b)}return _},p.prototype._wrapLibraryMethodsWithReady=function(){for(var m=0,_=Pt.length;m<_;m++)xn(this,Pt[m])},p.prototype.createInstance=function(m){return new p(m)},p}());n.exports=os},{3:3}]},{},[4])(4)}),pf=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}(),ff=function(){function r(){this.support=this.isSupportLS()}return r.prototype.isSupportLS=function(){try{return localStorage.setItem("_applogtest-test-key","hi"),localStorage.getItem("_applogtest-test-key"),localStorage.removeItem("_applogtest-test-key"),!0}catch{return!1}},r.prototype.getItem=function(e){try{var t=localStorage.getItem(e),n=t;try{t&&typeof t=="string"&&(n=JSON.parse(t))}catch{}return n||{}}catch{}return{}},r.prototype.setItem=function(e,t){try{var n=typeof t=="string"?t:JSON.stringify(t);localStorage.setItem(e,n)}catch{}},r.prototype.removeItem=function(e){try{localStorage.removeItem(e)}catch{}},r}(),mf=function(){function r(){this.support=this.isSupportSession()}return r.prototype.isSupportSession=function(){try{return sessionStorage.setItem("_applogtest-test-key","hi"),sessionStorage.getItem("_applogtest-test-key"),sessionStorage.removeItem("_applogtest-test-key"),!0}catch{return!1}},r.prototype.getItem=function(e){try{var t=sessionStorage.getItem(e),n=t;try{t&&typeof t=="string"&&(n=JSON.parse(t))}catch{}return n||{}}catch{}return{}},r.prototype.setItem=function(e,t){try{var n=typeof t=="string"?t:JSON.stringify(t);sessionStorage.setItem(e,n)}catch{}},r.prototype.removeItem=function(e){try{sessionStorage.removeItem(e)}catch{}},r}(),_f=function(){function r(e,t){return this.dbStorage=hi.createInstance({driver:[hi.INDEXEDDB,hi.LOCALSTORAGE],name:e,storeName:t}),this.dbStorage}return r.prototype.getItem=function(e){return ai(this,void 0,void 0,function(){var t,n;return ci(this,function(i){switch(i.label){case 0:return i.trys.push([0,2,,3]),[4,this.dbStorage.getItem(e)];case 1:t=i.sent(),n=t;try{t&&typeof t=="string"&&(n=JSON.parse(t))}catch{}return[2,n||void 0];case 2:return i.sent(),console.warn("db get storage error"),[3,3];case 3:return[2,void 0]}})})},r.prototype.setItem=function(e,t){try{this.dbStorage.setItem(e,t)}catch{console.warn("db set storage error")}},r.prototype.removeItem=function(e){try{this.dbStorage.removeItem(e)}catch{console.warn("db remove storage error")}},r}(),gf=function(){function r(){this.defaultExpireTime=6048e5,this.local=new ff,this.session=new mf,this.cache=new pf}return r.prototype.getLocalItem=function(e){return this.local.getItem(e)},r.prototype.setLocalItem=function(e,t){this.local.setItem(e,t)},r.prototype.removeLocalItem=function(e){this.local.removeItem(e)},r.prototype.getSessionItem=function(e){return this.session.getItem(e)},r.prototype.setSessionItem=function(e,t){this.session.setItem(e,t)},r.prototype.removeSessionItem=function(e){this.session.removeItem(e)},r.prototype.getCacheItem=function(e){return this.cache.getItem(e)},r.prototype.setCacheItem=function(e,t){this.cache.setItem(e,t)},r.prototype.removeCacheItem=function(e){this.cache.removeItem(e)},r.prototype.getCookie=function(e,t){try{return hr.get(e)}catch{return""}},r.prototype.setCookie=function(e,t,n,i){n===void 0&&(n=this.defaultExpireTime);try{var s=i||document.domain,a=+new Date+n;hr.set(e,t,{expires:new Date(a),path:"/",domain:s})}catch{}},r.prototype.removeCookie=function(e,t){try{hr.remove(e,{path:"/",domain:t||""})}catch{}},r}(),vf=function(){function r(e,t,n){this.appid=e,this.domain=t,this.userAgent=window.navigator.userAgent,this.appVersion=window.navigator.appVersion,this.cookie_expire=n}return r.prototype.init=function(){var e,t=window.navigator.userAgent,n=window.navigator.language,i=document.referrer,s=i?di(i).hostname:"",a=an(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(h,l,f,y){var C=new gf,v=h?"_tea_utm_cache_"+h:"_tea_utm_cache",E=h?"_$utm_from_url_"+h:"_$utm_from_url",k={},g=["tr_shareuser","tr_admaster","tr_param1","tr_param2","tr_param3","tr_param4","$utm_from_url"],D={ad_id:Number(l.ad_id)||void 0,campaign_id:Number(l.campaign_id)||void 0,creative_id:Number(l.creative_id)||void 0,utm_source:l.utm_source,utm_medium:l.utm_medium,utm_campaign:l.utm_campaign,utm_term:l.utm_term,utm_content:l.utm_content,tr_shareuser:l.tr_shareuser,tr_admaster:l.tr_admaster,tr_param1:l.tr_param1,tr_param2:l.tr_param2,tr_param3:l.tr_param3,tr_param4:l.tr_param4};try{var L=!1;for(var R in D)D[R]&&(g.indexOf(R)!==-1?(k.hasOwnProperty("tracer_data")||(k.tracer_data={}),k.tracer_data[R]=D[R]):k[R]=D[R],L=!0);if(L)C.setSessionItem(E,"1"),C.setCookie(v,JSON.stringify(k),y,f);else{var M=C.getCookie(v,f);M&&(k=JSON.parse(M))}C.getSessionItem(E)==1&&(k.hasOwnProperty("tracer_data")||(k.tracer_data={}),k.tracer_data.$utm_from_url=1)}catch{return D}return k}(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:n,referrer:i,referrer_host:s,network_type:d,utm:this.utm,latest_data:this.last(i,s)}},r.prototype.last=function(e,t){var n="",i="",s="",a=location.hostname,o=!1;if(e&&t&&a!==t){n=e,i=t,o=!0;var d=an(e);d.keyword&&(s=d.keyword)}return{$latest_referrer:n,$latest_referrer_host:i,$latest_search_keyword:s,isLast:o}},r.prototype.browser=function(){var e,t,n="",i=""+parseFloat(this.appVersion),s=this.userAgent;return s.indexOf("Edge")!==-1||s.indexOf("Edg")!==-1?(n="Microsoft Edge",s.indexOf("Edge")!==-1?(e=s.indexOf("Edge"),i=s.substring(e+5)):(e=s.indexOf("Edg"),i=s.substring(e+4))):(e=s.indexOf("MSIE"))!==-1?(n="Microsoft Internet Explorer",i=s.substring(e+5)):(e=s.indexOf("Lark"))!==-1?(n="Lark",i=s.substring(e+5,e+11)):s.indexOf("Chrome")!==-1?(e=s.indexOf("TTWebView"))!==-1?(n="TTWebView",i=s.substring(e+10,e+23)):((e=s.indexOf("Chrome"))!==-1||(e=s.indexOf("Chrome"))!==-1)&&(n="Chrome",i=s.substring(e+7)):s.indexOf("Safari")!==-1?(e=s.indexOf("Safari"))!==-1&&(n="Safari",i=s.substring(e+7),(e=s.indexOf("Version"))!==-1&&(i=s.substring(e+8))):(e=s.indexOf("Firefox"))!==-1&&(n="Firefox",i=s.substring(e+8)),(t=i.indexOf(";"))!==-1&&(i=i.substring(0,t)),(t=i.indexOf(" "))!==-1&&(i=i.substring(0,t)),(t=i.indexOf(")"))!==-1&&(i=i.substring(0,t)),{browser:n,browser_version:i}},r.prototype.os=function(){for(var e="",t="",n=[{s:"Windows 10",r:/(Windows 10.0|Windows NT 10.0|Windows NT 10.1)/},{s:"Windows 8.1",r:/(Windows 8.1|Windows NT 6.3)/},{s:"Windows 8",r:/(Windows 8|Windows NT 6.2)/},{s:"Windows 7",r:/(Windows 7|Windows NT 6.1)/},{s:"Android",r:/Android/},{s:"iOS",r:/(iPhone|iPad|iPod)/},{s:"Mac OS X",r:/Mac OS X/},{s:"Mac OS",r:/(MacPPC|MacIntel|Mac_PowerPC|Macintosh)/},{s:"ChromeOS",r:/CrOS/},{s:"Linux",r:/(Linux|X11)/},{s:"Sun OS",r:/SunOS/}],i=0;i<n.length;i++){var s=n[i];if(s.r.test(this.userAgent)){(e=s.s)==="Mac OS X"&&this.isNewIpad()&&(e="iOS");break}}var a=function(h,l){var f=h.exec(l);return f&&f[1]?f[1]:""},o=function(h,l){var f=RegExp("(?:^|[^A-Z0-9-_]|[^A-Z0-9-]_|sprd-)(?:"+h+")","i").exec(l);return f?f.slice(1)[0]:""};/Windows/.test(e)&&(t=a(/Windows (.*)/,e),e="windows");var d,c;switch(e){case"Mac OS X":t=o("Mac[ +]OS[ +]X(?:[ /](?:Version )?(\\d+(?:[_\\.]\\d+)+))?",this.userAgent),e="mac";break;case"Android":d=this.userAgent,(c=a(/Android ([\.\_\d]+)/,d))||(c=a(/Android\/([\.\_\d]+)/,d)),t=c,e="android";break;case"iOS":t=this.isNewIpad()?o("Mac[ +]OS[ +]X(?:[ /](?:Version )?(\\d+(?:[_\\.]\\d+)+))?",this.userAgent):(t=/OS (\d+)_(\d+)_?(\d+)?/.exec(this.appVersion))?t[1]+"."+t[2]+"."+(0|t[3]):"",e="ios";break;case"chromeOS":var u=this.userAgent.indexOf("x86_64");t=this.userAgent.substring(u+7,u+16)}return{os_name:e,os_version:t}},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 n=navigator.userAgent.replace("Mozilla/5.0 (",""),i=n.indexOf(";");t=n.slice(0,i)}}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}(),pi=function(r,e){try{return hr.get(r)}catch{return""}},fi=function(r,e,t,n){try{var i=n||document.domain,s=+new Date+(t||6048e5);hr.set(r,e,{expires:new Date(s),path:"/",domain:i})}catch{}},yf=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 pi(e)},r.prototype.setCookie=function(e,t,n,i){fi(e,t,n,i)},r}(),mi,T,Mo={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 pi(r)},setCookie:function(r,e,t,n){fi(r,e,t,n)},isSupportLS:function(){try{return localStorage.setItem("_ranger-test-key","hi"),localStorage.getItem("_ranger-test-key"),localStorage.removeItem("_ranger-test-key"),!0}catch{return!1}}()},Sf={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 pi(r)},setCookie:function(r,e,t,n){fi(r,e,t,n)},isSupportSession:function(){try{return sessionStorage.setItem("_ranger-test-key","hi"),sessionStorage.getItem("_ranger-test-key"),sessionStorage.removeItem("_ranger-test-key"),!0}catch{return!1}}()},Et=function(){function r(e,t){this._storage=t&&t==="session"?Sf:!e&&Mo.isSupportLS?Mo:new yf}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,n,i){this._storage.setCookie(e,t,n,i)},r.prototype.removeItem=function(e){this._storage.removeItem(e)},r}(),_i={sg_central:"1fz22z22z1nz21z4mz4bz4bz21z1ez18z1jz1gz49z1kz1az21z4az19z27z22z1cz1mz24z1cz20z21z1cz18z4az1az1mz1k",us_east:"1fz22z22z1nz21z4mz4bz4bz1kz18z1jz1gz24z18z49z1kz1az21z4az19z27z22z1cz1mz24z1cz20z21z1cz18z4az1az1mz1k",sg_central_tt:"1fz22z22z1nz21z4mz4bz4bz1kz1az21z49z21z1ez4az22z1gz1iz22z1mz1iz24z4az1az1mz1k",us_east_tt:"1fz22z22z1nz21z4mz4bz4bz1kz1az21z49z24z18z4az22z1gz1iz22z1mz1iz24z4az1az1mz1k",us_ttp:"1fz22z22z1nz21z4mz4bz4bz1kz1az21z4az22z1gz1iz22z1mz1iz24z4az23z21",us_ttp_w:"1fz22z22z1nz21z4mz4bz4bz1kz1az21z4az22z1gz1iz22z1mz1iz25z4az23z21",us_ttp2:"1fz22z22z1nz21z4mz4bz4bz1kz1az21z49z22z22z1nz4ez4az23z21z4az22z1gz1iz22z1mz1iz4az1az1mz1k",eu_ttp_gcp:"1fz22z22z1nz21z4mz4bz4bz1kz1az21z49z24z18z49z23z21z1cz18z21z22z4ez18z4az22z1gz1iz22z1mz1iz24z4az1az1mz1k",eu_central:"1fz22z22z1nz21z4mz4bz4bz18z25z21z1dz20z49z1kz1az21z4az19z27z22z1cz1gz1lz22z1jz18z1nz1gz4az1az1mz1k",eu_ttp_ie2:"1fz22z22z1nz21z4mz4bz4bz1kz1az21z49z1gz1cz4ez4az22z1gz1iz22z1mz1iz25z4az1cz23",eu_ttp2:"1fz22z22z1nz21z4mz4bz4bz1kz1az21z4dz4iz49z1lz1mz20z1kz18z1jz49z1lz1mz4dz18z4az22z1gz1iz22z1mz1iz25z4az1cz23"},Lo=function(){return new Set(Object.keys(_i))},gi=function(){return Object.keys(_i)},No={sg:"1fz22z22z1nz21z4mz4bz4bz21z1ez18z1jz1gz49z1kz1az21z4az19z27z22z1cz1mz24z1cz20z21z1cz18z4az1az1mz1k",va:"1fz22z22z1nz21z4mz4bz4bz1kz18z1jz1gz24z18z49z1kz1az21z4az19z27z22z1cz1mz24z1cz20z21z1cz18z4az1az1mz1k",my:"1fz22z22z1nz21z4mz4bz4bz1kz1az21z49z19z1bz49z1kz27z4az1jz18z20z1iz1mz1dz1dz1gz1az1cz4az1az1mz1k"},vi={va:"1fz22z22z1nz21z4mz4bz4bz22z1mz19z1jz1mz1ez4az1gz22z1mz19z21z1lz21z21z1bz1iz4az1az1mz1k",sg:"1fz22z22z1nz21z4mz4bz4bz22z1mz19z1jz1mz1ez4az22z1mz19z21z1lz21z21z1bz1iz4az1az1mz1k",in:"1fz22z22z1nz21z4mz4bz4bz22z1mz19z1jz1mz1ez4az1gz22z1mz19z21z1lz21z21z1bz1iz4az1az1mz1k"},bf={sg:"1fz22z22z1nz21z4mz4bz4bz1kz1az21z49z21z1ez4az22z1gz1iz22z1mz1iz24z4az1az1mz1k",va:"1fz22z22z1nz21z4mz4bz4bz1kz1az21z49z24z18z4az22z1gz1iz22z1mz1iz24z4az1az1mz1k",in:"1fz22z22z1nz21z4mz4bz4bz1kz1az21z49z24z18z49z23z21z1cz18z21z22z4ez18z4az22z1gz1iz22z1mz1iz24z4az1az1mz1k",ie2:"1fz22z22z1nz21z4mz4bz4bz1kz1az21z49z1gz1cz4ez4az22z1gz1iz22z1mz1iz25z4az1cz23"},Ef={sg:"1fz22z22z1nz21z4mz4bz4bz1kz1az21z4az22z1gz1iz22z1mz1iz25z4az23z21",va:"1fz22z22z1nz21z4mz4bz4bz1kz1az21z4az22z1gz1iz22z1mz1iz24z4az23z21",ie2:"1fz22z22z1nz21z4mz4bz4bz1kz1az21z49z1gz1cz4ez4az22z1gz1iz22z1mz1iz25z4az1cz23"},pr="5.3.11_oversea",Cf=["1fz22z22z1nz21z4mz4bz4bz1bz18z22z18z4az19z27z22z1cz1bz18z1lz1az1cz4az1lz1cz22","1fz22z22z1nz21z4mz4bz4bz22z1cz18z49z24z18z4az22z1gz1iz22z1mz1iz49z20z1mz25z4az1lz1cz22","1fz22z22z1nz21z4mz4bz4bz22z1cz18z4az22z1gz1iz22z1mz1iz49z1cz23z4az1lz1cz22","1fz22z22z1nz21z4mz4bz4bz22z1cz18z4az22z1gz1iz22z1mz1iz49z23z21z22z21z4az1lz1cz22","1fz22z22z1nz21z4mz4bz4bz1gz1mz49z21z1ez4az22z1gz1iz22z1mz1iz49z20z1mz25z4az1lz1cz22","1fz22z22z1nz21z4mz4bz4bz1gz1mz49z24z18z4az22z1gz1iz22z1mz1iz49z20z1mz25z4az1lz1cz22"].map(function(r){return dr(r)});(function(r){r.Init="init",r.Config="config",r.Start="start",r.Ready="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-deviceid",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.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.DestoryInstance="destory-instance",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.TrackEventDuration="track-event-duration",r.TrackEventDurationStart="track-event-duration-start",r.TrackEventDurationEnd="track-event-duration-end",r.TrackEventDurationPause="track-event-duration-pause",r.TrackEventDurationResume="tracl-event-duration-resume",r.VisualCollectReady="visual-collect-ready",r.VisualApiReady="visual-api-ready",r.VisualApiUpdate="visual-api-update"})(mi||(mi={})),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"}(T||(T={}));var x=mi,Z=void 0,Uo=new Date().getTimezoneOffset(),wf=parseInt(""+-Uo/60,10),Tf=60*Uo,kf=function(){function r(e,t){var n=this;this.is_first_time=!0,this.configPersist=!1,this.initConfig=t,this.collect=e;var i=new vf(t.app_id,t.cookie_domain||"",t.cookie_expire||6048e5).init(),s="__tea_cache_first_"+t.app_id;this.configKey="__tea_cache_config_"+t.app_id,this.sessionStorage=new Et(!1,"session"),this.localStorage=new Et(!1,"local"),this.channelUrl=this.getChannelForUrl(),this.current_env="row",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:Z,user_type:Z,user_id:Z,user_is_auth:Z,user_is_login:Z,device_id:Z,web_id:Z,ip_addr_id:Z,user_unique_id_type:Z},header:{app_id:Z,app_name:Z,app_install_id:Z,install_id:Z,app_package:Z,app_channel:Z,app_version:Z,ab_version:Z,os_name:i.os_name,os_version:i.os_version,device_model:i.device_model,ab_client:Z,traffic_type:Z,network_type:i.network_type,client_ip:Z,device_brand:Z,os_api:Z,access:Z,language:i.language,region:Z,app_language:Z,app_region:Z,creative_id:i.utm.creative_id,ad_id:i.utm.ad_id,campaign_id:i.utm.campaign_id,log_type:Z,rnd:Z,platform:i.platform,sdk_version:pr,sdk_lib:"js",province:Z,city:Z,timezone:wf,tz_offset:Tf,tz_name:Z,sim_region:Z,carrier:Z,resolution:i.screen_width+"x"+i.screen_height,browser:i.browser,browser_version:i.browser_version,referrer:i.referrer,referrer_host:i.referrer_host,width:i.screen_width,height:i.screen_height,screen_width:i.screen_width,screen_height:i.screen_height,utm_term:i.utm.utm_term,utm_content:i.utm.utm_content,utm_source:i.utm.utm_source,utm_medium:i.utm.utm_medium,utm_campaign:i.utm.utm_campaign,tracer_data:JSON.stringify(i.utm.tracer_data),custom:i.network_type?{network_type:i.network_type}:{}}},this.ab_version="",this.ab_uuid_cache={},this.evtParams={},this.reportErrorCallback=function(){},this.isLast=!1,this.setCustom(i),this.initDomain(),this.initABData(),this.collect.on("route-change",function(o){n.changeReferInfo(o.config)})}return r.prototype.initDomain=function(e){var t=this.initConfig.channel_domain;if(t)this.domain=t;else{var n=e||this.initConfig.report_channel||this.initConfig.channel,i=this.getChannelDomain(n);i||(console.warn("current channel: "+n+" is not exist, use va instead, please check!!!!"),i=No.sg),this.domain=dr(i),this.setCurrentEnv(this.domain)}},r.prototype.setDomain=function(e){this.customDomain=!0,this.domain=e,this.setCurrentEnv(this.domain)},r.prototype.getDomain=function(e){return this.customDomain||e&&this.initDomain(e),this.domain},r.prototype.getChannelDomain=function(e){var t,n,i=e||this.initConfig.report_channel||this.initConfig.channel;return Lo().has(i)?_i[i]:((t=this.initConfig)===null||t===void 0?void 0:t.channel_type)==="tcpy"?bf[i]:((n=this.initConfig)===null||n===void 0?void 0:n.channel_type)==="ttp"?Ef[i]:No[i]},r.prototype.getChannelForUrl=function(){return this.initConfig.channel_type?{WEBID_URL:"/v1/user/webid",TOB_URL:"",REPORT_URL:"/v1/list"}:this.initConfig.report_channel?["sg_central","us_east"].indexOf(this.initConfig.report_channel)!==-1?{WEBID_URL:"/webid",TOB_URL:"/tobid",REPORT_URL:"/list"}:{WEBID_URL:"/v1/user/webid",TOB_URL:"",REPORT_URL:"/v1/list"}:{WEBID_URL:"/webid",TOB_URL:"/tobid",REPORT_URL:"/list"}},r.prototype.setCurrentEnv=function(e){this.getDomain().includes("byteoversea")?this.current_env="row":this.current_env="other"},r.prototype.getCurrentEnv=function(){return this.current_env},r.prototype.initABData=function(){var e,t="__tea_sdk_ab_version_"+this.initConfig.app_id;e=this.localStorage.getItem(t),this.setAbCache(e)},r.prototype.setAbCache=function(e){this.ab_cache=e},r.prototype.getAbCache=function(){return this.ab_cache},r.prototype.clearAbCache=function(){this.ab_cache={},this.ab_version=""},r.prototype.setAbVersion=function(e){this.ab_version=e},r.prototype.getAbVersion=function(){return this.ab_version},r.prototype.setAbUuidCache=function(e,t){var n=t||this.envInfo.user.user_unique_id;this.ab_uuid_cache[""+n]||(this.ab_uuid_cache[""+n]=[]),this.ab_uuid_cache[""+n].indexOf(e)===-1&&this.ab_uuid_cache[""+n].push(e)},r.prototype.getAbUuidCache=function(e){return this.ab_uuid_cache[""+e]},r.prototype.getUrl=function(e){var t="";switch(e){case"event":t=this.channelUrl.REPORT_URL;break;case"webid":t=this.channelUrl.WEBID_URL;break;case"tobid":t=this.channelUrl.TOB_URL}var n="";return this.initConfig.caller&&(n="?sdk_version=5.3.11_oversea&sdk_name=web&app_id="+this.initConfig.app_id+"&caller="+this.initConfig.caller),""+this.getDomain()+t+n},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.setAppid=function(e){this.envInfo.header.app_id=e},r.prototype.changeReferInfo=function(e){var t=e;this.set({referrer:t.referrer});var n="";try{n=new URL(t.referrer).host}catch{}this.set({referrer_host:n||this.envInfo.header.referrer_host})},r.prototype.set=function(e){var t=this;Object.keys(e).forEach(function(n){if(e[n]!==void 0&&e[n]!==null||t.delete(n),n==="traffic_type"&&t.isLast&&(t.envInfo.header.custom.$latest_traffic_source_type=e[n]),n==="evtParams")t.evtParams=ne(ne({},t.evtParams||{}),e.evtParams||{});else if(n==="_staging_flag")t.evtParams=ne(ne({},t.evtParams||{}),{_staging_flag:e._staging_flag});else if(n==="reportErrorCallback"&&typeof e[n]=="function")t.reportErrorCallback=e[n];else{var i="",s="";if(n.indexOf(".")>-1){var a=n.split(".");i=a[0],s=a[1]}i?i==="user"||i==="header"?t.envInfo[i][s]=e[n]:(t.envInfo.header.custom[s]=e[n],t.collect.emit(T.DEBUGGER_MESSAGE,{type:T.DEBUGGER_MESSAGE_SDK,info:"SDK Add Custom Params",level:"info",time:Date.now(),infoType:"sdk",secType:"HEADER",common:"custom"})):Object.hasOwnProperty.call(t.envInfo.user,n)?(["user_type","ip_addr_id"].indexOf(n)>-1?t.envInfo.user[n]=e[n]?Number(e[n]):e[n]:["user_id","web_id","user_unique_id","user_unique_id_type"].indexOf(n)>-1?t.envInfo.user[n]=e[n]?String(e[n]):e[n]:["user_is_auth","user_is_login"].indexOf(n)>-1?t.envInfo.user[n]=!!e[n]:n==="device_id"&&(t.envInfo.user[n]=e[n]),t.collect.emit(T.DEBUGGER_MESSAGE,{type:T.DEBUGGER_MESSAGE_SDK,info:"SDK Set Common Params",level:"info",time:Date.now(),infoType:"sdk",secType:"USER",common:n})):Object.hasOwnProperty.call(t.envInfo.header,n)?(t.envInfo.header[n]=e[n],t.collect.emit(T.DEBUGGER_MESSAGE,{type:T.DEBUGGER_MESSAGE_SDK,info:"SDK Set Common Params",level:"info",time:Date.now(),infoType:"sdk",secType:"HEADER",common:n})):(t.envInfo.header.custom[n]=e[n],t.collect.emit(T.DEBUGGER_MESSAGE,{type:T.DEBUGGER_MESSAGE_SDK,info:"SDK Add Custom Params",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(T.DEBUGGER_MESSAGE,{type:T.DEBUGGER_MESSAGE_SDK,info:"SDK Something Error",level:"error",time:Date.now(),data:t.message,infoType:"sdk"})}},r.prototype.setStore=function(e){try{if(!this.configPersist)return;var t=this.storage.getItem(this.configKey)||{};if(t&&Object.keys(e).length){var n=Object.assign(e,t);this.storage.setItem(this.configKey,n)}}catch(i){console.log("setStore error"),this.collect.emit(T.DEBUGGER_MESSAGE,{type:T.DEBUGGER_MESSAGE_SDK,info:"SDK Something Error",level:"error",time:Date.now(),data:i.message,infoType:"sdk"})}},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(T.DEBUGGER_MESSAGE,{type:T.DEBUGGER_MESSAGE_SDK,info:"SDK Something Error",level:"error",time:Date.now(),data:t.message,infoType:"sdk"}),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(n){this.collect.emit(T.DEBUGGER_MESSAGE,{type:T.DEBUGGER_MESSAGE_SDK,info:"SDK Something Error",level:"error",time:Date.now(),data:n.message,infoType:"sdk"}),console.log("delete error")}},r}(),Rf=function(){function r(e,t){this.isLog=t||!1,this.name=e||""}return r.prototype.info=function(e){this.isLog&&console.log("%c %s","color: yellow; background-color: black;","[Tea instance: "+this.name+"] "+e)},r.prototype.warn=function(e){this.isLog&&console.warn("%c %s","color: #4D1B00;","[Tea instance: "+this.name+"] "+e)},r.prototype.error=function(e){this.isLog&&console.error("%c %s","color: #FFF; background-color: #F53F3F;","[Tea instance: "+this.name+"] "+e)},r.prototype.throw=function(e){throw this.error(this.name),new Error(e)},r}(),Af=function(){function r(){this.spiderBot=["Baiduspider","googlebot","360Spider","haosouspider","YoudaoBot","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 n=!1;return this.spiderBot.forEach(function(i){t.indexOf(i)!==-1&&(n=!0)}),n},r}(),Df=function(){function r(t,n){this.collect=t,this.native=n}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(n,i){try{t.bridgeInject()?AppLogBridge.hasStarted(function(s){console.log("AppLogBridge is started? : "+s),s?n(!0):i(!1)}):i(!1)}catch(s){console.log("AppLogBridge, error:"+JSON.stringify(s.stack)),i(!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 n=this;try{Object.keys(t).forEach(function(i){i==="user_unique_id"?n.setUserUniqueId(t[i]):t[i]?n.addHeaderInfo(i,t[i]):n.removeHeaderInfo(i)})}catch{console.error("setConfig error")}},e.setUserUniqueId=function(t){try{AppLogBridge.setUserUniqueId(t)}catch{console.error("setUserUniqueId error")}},e.addHeaderInfo=function(t,n){try{AppLogBridge.addHeaderInfo(t,n)}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,n){try{AppLogBridge.onEventV3(t,n),this.collect.emit(DebuggerMesssge.DEBUGGER_MESSAGE,{type:DebuggerMesssge.DEBUGGER_MESSAGE_EVENT,info:"bridge report success",time:Date.now(),data:[{events:[{event:t,params:n}]}],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}(),xf=function(){function r(){this.setUrl="/service/2/web_sdk_settings/",this.expireTime=216e5}return r.prototype.apply=function(e,t){if(t.enable_logsetting){this.collect=e,this.config=t;var n=e.adapters.storage;this.setKey="applog_web_logsetting_"+t.app_id,this.uniqueKey="web_logsetting_data",this.cacheStorgae=new n(!1),this.dbStorage=new _f(this.setKey,"LOGSETTING_DATA_STORE"),this.domain=t.logsetting_domain||this.collect.configManager.getDomain(),this.check()}else e.emit(x.LogSettingReady)},r.prototype.check=function(){return ai(this,void 0,void 0,function(){var e;return ci(this,function(t){switch(t.label){case 0:return t.trys.push([0,2,,3]),[4,this.getLocalData()];case 1:return(e=t.sent())&&Object.keys(e).length?(e==null?void 0:e.timestamp)<Date.now()-this.expireTime?this.fetchSetting():(this.setSettingData(e.settingConfig),this.collect.emit(x.LogSettingReady)):this.fetchSetting(),[3,3];case 2:return t.sent(),this.collect.emit(x.LogSettingReady),this.collect.emit(T.DEBUGGER_MESSAGE,{type:T.DEBUGGER_MESSAGE_SDK,info:"SDK Check LogSetting Data Error",logType:"fetch",level:"error",time:Date.now(),infoType:"sdk"}),[3,3];case 3:return[2]}})})},r.prototype.fetchSetting=function(e){var t=this;if(e)this.collect.emit(x.LogSettingReady);else{var n=this.collect.configManager.get("header");n.custom=JSON.stringify(n.custom);var i=this.collect.configManager.get("user"),s={event_filter:0,header:ne(ne({aid:this.config.app_id},n),i),options:{params_block_enable:this.config.enable_logsetting_params?1:0,header_custom_allow_enable:this.config.enable_logsetting_header_custom?1:0}};this.collect.emit(T.DEBUGGER_MESSAGE,{type:T.DEBUGGER_MESSAGE_SDK,info:"SDK Fetch LogSetting Request",logType:"fetch",level:"info",time:Date.now(),data:s,infoType:"sdk"}),this.collect.requestManager.useRequest({url:""+this.domain+this.setUrl+"?device_platform=web",data:s,timeout:5e3,success:function(a){a!=null&&a.config?(t.setLocalData(a.config),t.collect.emit(T.DEBUGGER_MESSAGE,{type:T.DEBUGGER_MESSAGE_SDK,info:"LogSetting Request Success",logType:"fetch",level:"info",time:Date.now(),data:a,infoType:"sdk"})):t.collect.emit(T.DEBUGGER_MESSAGE,{type:T.DEBUGGER_MESSAGE_SDK,info:"LogSetting Request Response No Data",logType:"fetch",level:"error",time:Date.now(),infoType:"sdk"}),t.collect.emit(x.LogSettingReady)},fail:function(){t.collect.emit(x.LogSettingReady),t.collect.emit(T.DEBUGGER_MESSAGE,{type:T.DEBUGGER_MESSAGE_SDK,info:"LogSetting Request Fail",logType:"fetch",level:"error",time:Date.now(),infoType:"sdk"})}})}},r.prototype.getLocalData=function(){return ai(this,void 0,void 0,function(){return ci(this,function(e){switch(e.label){case 0:return e.trys.push([0,2,,3]),[4,this.dbStorage.getItem(this.uniqueKey)];case 1:return[2,e.sent()];case 2:return e.sent(),[2,null];case 3:return[2]}})})},r.prototype.setLocalData=function(e){try{var t={timestamp:Date.now(),settingConfig:e};this.setSettingData(e),this.dbStorage.setItem(this.uniqueKey,t),this.collect.emit(T.DEBUGGER_MESSAGE,{type:T.DEBUGGER_MESSAGE_SDK,info:"SDK Update LogSetting Cache",logType:"info",level:"info",time:Date.now(),infoType:"sdk",data:e})}catch{this.collect.emit(T.DEBUGGER_MESSAGE,{type:T.DEBUGGER_MESSAGE_SDK,info:"SDK Set LogSetting Data Error",logType:"info",level:"error",time:Date.now(),infoType:"sdk"})}},r.prototype.getSettingData=function(e){return e?this.logSettingConfig[e]:this.logSettingConfig},r.prototype.setSettingData=function(e){this.logSettingConfig=e},r.prototype.getPredefineEventList=function(){return new Set(["predefine_pageview","onload","bav2b_click","bav2b_page","bav2b_beat","bav2b_page_statistics","bav2b_exposure","predefine_page_alive","predefine_page_close","_be_active","__bav_click","__bav_page","__bav_beat","__bav_page_statistics","__bav_page_exposure"])},r.prototype.getPredefineParamsList=function(){return new Set(["event_index"])},r}(),If=function(){function r(){this.eventLimit=50,this.enable_ttwebid=!1,this.eventCache=[],this.beconEventCache=[]}return r.prototype.apply=function(e,t){var n=this;this.collect=e,this.config=t,this.configManager=e.configManager,this.cacheStorgae=new Et(!0),this.localStorage=new Et(!1),this.logSetting=new xf,this.maxReport=t.max_report||10,this.reportTime=t.reportTime||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.logSetting.apply(e,t),this.collect.on(x.Ready,function(){n.reportAll(!1)}),this.collect.on(x.ConfigDomain,function(){n.reportUrl=n.configManager.getUrl("event")}),this.collect.on(x.Event,function(i){n.event(i)}),this.collect.on(x.BeconEvent,function(i){n.beconEvent(i)}),this.collect.on(x.CleanEvents,function(){n.reportAll(!1)}),this.linster()},r.prototype.linster=function(){var e=this;window.addEventListener("unload",function(){e.reportAll(!0)},!1),lr(function(){e.reportAll(!0)}),document.addEventListener("visibilitychange",function(){document.visibilityState==="hidden"&&e.reportAll(!0)},!1)},r.prototype.reportAll=function(e){this.report(e),this.reportBecon()},r.prototype.event=function(e){var t=this;if(!this.collect.destroy&&!this.collect.sdkStop)try{if(this.config.enable_ios_sendbeacon&&zo())return void this.beconEvent(e);var n=cr(e,this.cacheStorgae.getItem(this.eventKey)||[]);if(this.cacheStorgae.setItem(this.eventKey,n),this.reportTimeout&&clearTimeout(this.reportTimeout),n.length>=this.maxReport)this.report(!1);else{var i=this.reportTime;this.reportTimeout=setTimeout(function(){t.report(!1),t.reportTimeout=null},i)}}catch(s){this.collect.emit(T.DEBUGGER_MESSAGE,{type:T.DEBUGGER_MESSAGE_SDK,info:"SDK Something Error",level:"error",time:Date.now(),data:s.message,infoType:"sdk"})}},r.prototype.beconEvent=function(e){if(!this.collect.destroy&&!this.collect.sdkStop){var t=cr(e,this.cacheStorgae.getItem(this.beconKey)||[]);if(this.cacheStorgae.setItem(this.beconKey,t),this.collect.tokenManager.getReady()&&this.collect.sdkReady){this.cacheStorgae.removeItem(this.beconKey);try{var n=JSON.parse(JSON.stringify(t));if(this.send(this.split(this.merge(t)),!0),this.config.event_verify_url){var i=this.split(this.merge(n,!0));this.collect.emit(x.SubmitVerify,i)}}catch{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)||[];if(e&&e.length){this.cacheStorgae.removeItem(this.beconKey);try{var t=JSON.parse(JSON.stringify(e));if(this.send(this.split(this.merge(e)),!0),this.config.event_verify_url){var n=this.split(this.merge(t,!0));this.collect.emit(x.SubmitVerify,n)}}catch{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.sliceEvent(t,e))}},r.prototype.sliceEvent=function(e,t){if(e.length>this.eventLimit)for(var n=0;n<e.length;n+=this.eventLimit){var i;i=e.slice(n,n+this.eventLimit);try{var s=JSON.parse(JSON.stringify(i));if(this.send(this.split(this.merge(i)),t),this.config.event_verify_url){var a=this.split(this.merge(s,!0));this.collect.emit(x.SubmitVerify,a)}}catch{this.send(this.split(this.merge(i)),t)}}else try{s=JSON.parse(JSON.stringify(e)),this.send(this.split(this.merge(e)),t),this.config.event_verify_url&&(a=this.split(this.merge(s,!0)),this.collect.emit(x.SubmitVerify,a))}catch{this.send(this.split(this.merge(e)),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 n=this;t===void 0&&(t=!1);var i=this.configManager.get(),s=i.header,a=i.user;s.custom=this.customAllow(s.custom,t);var o=this.configManager.get("evtParams"),d=this.configManager.get("user_unique_id_type"),c=[];try{var u=e.filter(function(l){try{Object.keys(o).length&&(l.params=ne(ne({},o),l.params)),d&&(l.params.$user_unique_id_type=d);var f=n.configManager.getAbCache(),y=a[n.config.ab_user_mode]||a.user_unique_id,C=n.configManager.getAbUuidCache(y);if(f&&f.uuid&&f.uuid===y){var v=n.configManager.getAbVersion();if(n.config.enable_ab_uuid){if(C&&C.length){var E=C.join(",");v&&v.includes(E)&&(l.ab_sdk_version=v)}}else v&&(l.ab_sdk_version=v)}return l.session_id=n.collect.sessionManager.getSessionId(),l.params=n.paramsAllow(l,t),l}catch(k){return console.warn("filter merge event: "+(l&&l.event)+" error, pls check",k&&k.message),n.collect.emit(T.DEBUGGER_MESSAGE,{type:T.DEBUGGER_MESSAGE_SDK,info:"SDK Merge Event Something Error",level:"error",time:Date.now(),data:k.message,infoType:"sdk"}),!1}}),h=JSON.parse(JSON.stringify({events:u,user:a,header:s}));h.local_time=Math.floor(Date.now()/1e3),h.user_unique_type=this.config.enable_ttwebid?this.config.user_unique_type:void 0,h.verbose=1,c.push(h)}catch(l){console.warn("event merge error, pls check",l&&l.message)}return c},r.prototype.split=function(e){return e=e.map(function(t){var n=[];return n.push(t),n})},r.prototype.blockEvent=function(e){try{var t=this.blockList;if(this.config.enable_logsetting){var n=this.blockList,i=this.logSetting.getSettingData("blocklist_events").block_event;t=n.concat(i.filter(function(s){return n.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)&&t.length)||!!this.whiteList.includes(e)}catch{return!0}},r.prototype.customAllow=function(e,t){try{if(t||!this.config.enable_logsetting||!this.config.enable_logsetting_header_custom)return JSON.stringify(e);var n=this.logSetting.getSettingData().header_custom_allow;if(n){var i={};if(n.length&&Object.keys(e).length){var s=new Set(n);for(var a in e)s.has(a)&&(i[a]=e[a])}return JSON.stringify(i)}return JSON.stringify(e)}catch(o){return this.collect.emit(T.DEBUGGER_MESSAGE,{type:T.DEBUGGER_MESSAGE_SDK,info:"SDK Execute customAllow Something Error",level:"error",time:Date.now(),data:o.message,infoType:"sdk"}),JSON.stringify(e)}},r.prototype.paramsAllow=function(e,t){try{if(t||!this.config.enable_logsetting||!this.config.enable_logsetting_params)return JSON.stringify(e.params);var n=this.logSetting.getSettingData().params_block,i=e.event,s=e.params;if(!n)return JSON.stringify(e.params);if(n[i]&&n[i].length){var a={},o=new Set(n[i]);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(T.DEBUGGER_MESSAGE,{type:T.DEBUGGER_MESSAGE_SDK,info:"SDK Execute paramsAllow Something Error",level:"error",time:Date.now(),data:c.message,infoType:"sdk"}),JSON.stringify(e.params)}},r.prototype.send=function(e,t){var n=this;e.length&&(this.config.disable_track_event||e.forEach(function(i){try{var s=JSON.parse(JSON.stringify(i));n.config.filter&&((s=n.config.filter(s))||console.warn("filter must return data !!")),n.collect.eventFilter&&s&&((s=n.collect.eventFilter(s))||console.warn("filterEvent api must return data !!"));var a=s||i,o=JSON.parse(JSON.stringify(a));if(!a.length)return;var d=!0;if(a.forEach(function(c){c.events.length||(d=!1)}),!d)return;n.collect.emit(x.SubmitBefore,a),n.collect.requestManager.useRequest({url:n.reportUrl,data:a,success:function(c,u){c&&c.e!==0?(n.collect.emit(x.SubmitError,{type:"f_data",eventData:u,errorCode:c.e,response:c}),n.collect.emit(T.DEBUGGER_MESSAGE,{type:T.DEBUGGER_MESSAGE_EVENT,info:"Event Report Fail",time:Date.now(),data:o,code:c.e,failType:"event data error",status:"fail"})):(n.collect.emit(x.SubmitScuess,{eventData:u,res:c}),n.collect.emit(T.DEBUGGER_MESSAGE,{type:T.DEBUGGER_MESSAGE_EVENT,info:"Event Report Success",time:Date.now(),data:o,code:200,status:"success"}))},fail:function(c,u){n.configManager.get("reportErrorCallback")(c,u),n.collect.emit(x.SubmitError,{type:"f_net",eventData:c,errorCode:u}),n.collect.emit(T.DEBUGGER_MESSAGE,{type:T.DEBUGGER_MESSAGE_EVENT,info:"Event Report Network Fail",time:Date.now(),data:o,code:u,failType:"network error",status:"fail"})},timeout:n.timeout,useBeacon:!n.config.disable_sendbeacon&&t,withCredentials:n.enable_ttwebid,zip:!0}),n.collect.emit(x.SubmitAfter,a)}catch(c){console.warn("something error, "+JSON.stringify(c.stack)),n.collect.emit(T.DEBUGGER_MESSAGE,{type:T.DEBUGGER_MESSAGE_SDK,info:"SDK Report Event Something Error",level:"error",time:Date.now(),data:c.message})}}))},r}(),un=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)},zf=function(){function r(){this.cacheToken={},this.enableCookie=!1,this.enable_ttwebid=!1,this.enableCustomWebid=!1}return r.prototype.apply=function(e,t){var n=this;this.collect=e,this.config=t,this.configManager=this.collect.configManager,this.storage=new Et(!1),this.tokenKey="__tea_cache_tokens_"+t.app_id,this.enable_ttwebid=t.enable_ttwebid,this.enableCustomWebid=t.enable_custom_webid,this.collect.on(x.ConfigUuid,function(i){n.setUuid(i)}),this.collect.on(x.ConfigWebId,function(i){n.setWebId(i)}),this.collect.on(x.ConfigDiD,function(i){n.setDeviceId(i)}),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;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(x.CustomWebId,function(){e.tokenReady=!0,e.collect.emit(x.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:un(),user_unique_id:this.configManager.get("user_unique_id")||un()}):this.remoteWebid()},r.prototype.checkEnv=function(){var e=window.navigator.userAgent;if(e.indexOf("miniProgram")!==-1||e.indexOf("MiniProgram")!==-1){var t=an(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"),n={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(T.DEBUGGER_MESSAGE,{type:T.DEBUGGER_MESSAGE_SDK,info:"SDK Fetch WebID Request",logType:"fetch",level:"info",time:Date.now(),data:n});var i=un();this.collect.requestManager.useRequest({url:t,data:n,success:function(s){var a;s&&s.e===0?(a=s.web_id,e.collect.emit(T.DEBUGGER_MESSAGE,{type:T.DEBUGGER_MESSAGE_SDK,info:"Fetch WebID Request Success",logType:"fetch",level:"info",time:Date.now(),data:s})):(a=i,e.collect.configManager.set({localWebId:i}),e.collect.emit(x.TokenError),e.collect.emit(T.DEBUGGER_MESSAGE,{type:T.DEBUGGER_MESSAGE_SDK,info:"Fetch WebID Request Data Error, Use LocalId",logType:"fetch",level:"warn",time:Date.now(),data:s}),e.collect.logger.warn("appid: "+e.config.app_id+" get webid error, use local webid~")),e.complete({web_id:e.configManager.get("web_id")||a,user_unique_id:e.configManager.get("user_unique_id")||a})},fail:function(){e.complete({web_id:e.configManager.get("web_id")||i,user_unique_id:e.configManager.get("user_unique_id")||i}),e.collect.configManager.set({localWebId:i}),e.collect.emit(x.TokenError),e.collect.emit(T.DEBUGGER_MESSAGE,{type:T.DEBUGGER_MESSAGE_SDK,info:"Fetch WebID Request Network Fail, Use LocalId",logType:"fetch",level:"error",time:Date.now(),data:null}),e.collect.logger.warn("appid: "+e.config.app_id+", get webid error, use local webid~")},timeout:3e5})},r.prototype.complete=function(e){var t=e.web_id,n=e.user_unique_id,i=e.device_id;if(e.timestamp=Date.now(),this.collect.configManager.set({web_id:t,user_unique_id:n}),this.config.enable_device_id){var s=this.configManager.get("device_id")||i||t;this.collect.configManager.set({device_id:s}),e=ne(ne({},e),{device_id:s})}else delete e.device_id;this.setStorage(e),this.tokenReady=!0,this.collect.emit(T.DEBUGGER_MESSAGE,{type:T.DEBUGGER_MESSAGE_SDK,info:"SDK UserInfo Complete",logType:"info",secType:"USER",level:"info",time:Date.now(),data:{web_id:t,user_unique_id:n},infoType:"sdk"}),this.collect.emit(x.TokenComplete)},r.prototype.completeTtWid=function(e){var t=e.user_unique_id||"",n=this.configManager.get("user_unique_id");(n||t)&&this.configManager.set({user_unique_id:n||t}),this.setStorage(e),this.tokenReady=!0,this.collect.emit(x.TokenComplete)},r.prototype.setUuid=function(e){if(e&&["null","undefined","Null","None"].indexOf(e)===-1){var t=String(e),n=this.configManager.get("user_unique_id"),i=this.cacheToken&&this.cacheToken.user_unique_id;if(t===n&&t===i)return;this.configManager.set({user_unique_id:t}),this.cacheToken||(this.cacheToken={}),this.cacheToken.user_unique_id=t,this.cacheToken.timestamp=Date.now(),this.setStorage(this.cacheToken),this.collect.emit(x.TokenChange,"uuid"),this.collect.emit(x.SessionReset)}else this.clearUuid()},r.prototype.clearUuid=function(){this.config.enable_ttwebid||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(x.TokenReset))},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"),n=this.configManager.get("user_unique_id");n&&n!==t||(this.configManager.set({user_unique_id:e}),this.collect.emit(x.TokenChange,"uuid")),t!==e&&(this.configManager.set({web_id:e}),this.collect.emit(x.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.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){if(e.config.channel_type!=="tcpy"&&e.config.channel_type!=="ttp"){var n={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(T.DEBUGGER_MESSAGE,{type:T.DEBUGGER_MESSAGE_SDK,info:"SDK Fetch GetToken Request",logType:"fetch",level:"info",time:Date.now(),data:n,infoType:"sdk"}),e.collect.requestManager.useRequest({url:e.configManager.getUrl("tobid"),data:n,success:function(i){i&&i.e===0?(t(i.tobid),e.collect.emit(T.DEBUGGER_MESSAGE,{type:T.DEBUGGER_MESSAGE_SDK,info:"Fetch GetToken Request Success",logType:"fetch",level:"info",time:Date.now(),data:i,infoType:"sdk"})):(t(""),e.collect.emit(T.DEBUGGER_MESSAGE,{type:T.DEBUGGER_MESSAGE_SDK,info:"Fetch GetToken Request Fail",logType:"fetch",level:"error",time:Date.now(),data:i,infoType:"sdk"}))},fail:function(){t(""),e.collect.emit(T.DEBUGGER_MESSAGE,{type:T.DEBUGGER_MESSAGE_SDK,info:"Fetch GetToken Request Network Error",logType:"fetch",level:"error",time:Date.now(),infoType:"sdk"})},time:3e4,withCredentials:e.enable_ttwebid})}else t("")})},r}(),fr=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)})},Pf=function(){function r(){}return r.prototype.apply=function(e,t){var n=this;this.collect=e,this.storage=new Et(!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(x.SessionReset,function(i){n.resetSessionId(i)}),this.collect.on(x.SessionResetTime,function(){n.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:fr(),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:fr(),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||fr(),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:fr(),timestamp:Date.now()},this.storage.setItem(this.sessionKey,e))},r}();function Vt(r){let e=r.length;for(;--e>=0;)r[e]=0}const yi=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]),dn=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]),Of=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7]),Go=new Uint8Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),tt=new Array(576);Vt(tt);const mr=new Array(60);Vt(mr);const _r=new Array(512);Vt(_r);const gr=new Array(256);Vt(gr);const Si=new Array(29);Vt(Si);const ln=new Array(30);function bi(r,e,t,n,i){this.static_tree=r,this.extra_bits=e,this.extra_base=t,this.elems=n,this.max_length=i,this.has_stree=r&&r.length}let Bo,Fo,Vo;function Ei(r,e){this.dyn_tree=r,this.max_code=0,this.stat_desc=e}Vt(ln);const jo=r=>r<256?_r[r]:_r[256+(r>>>7)],vr=(r,e)=>{r.pending_buf[r.pending++]=255&e,r.pending_buf[r.pending++]=e>>>8&255},be=(r,e,t)=>{r.bi_valid>16-t?(r.bi_buf|=e<<r.bi_valid&65535,vr(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)},Ve=(r,e,t)=>{be(r,t[2*e],t[2*e+1])},Ho=(r,e)=>{let t=0;do t|=1&r,r>>>=1,t<<=1;while(--e>0);return t>>>1},qo=(r,e,t)=>{const n=new Array(16);let i,s,a=0;for(i=1;i<=15;i++)a=a+t[i-1]<<1,n[i]=a;for(s=0;s<=e;s++){let o=r[2*s+1];o!==0&&(r[2*s]=Ho(n[o]++,o))}},$o=r=>{let 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},Ko=r=>{r.bi_valid>8?vr(r,r.bi_buf):r.bi_valid>0&&(r.pending_buf[r.pending++]=r.bi_buf),r.bi_buf=0,r.bi_valid=0},Wo=(r,e,t,n)=>{const i=2*e,s=2*t;return r[i]<r[s]||r[i]===r[s]&&n[e]<=n[t]},Ci=(r,e,t)=>{const n=r.heap[t];let i=t<<1;for(;i<=r.heap_len&&(i<r.heap_len&&Wo(e,r.heap[i+1],r.heap[i],r.depth)&&i++,!Wo(e,n,r.heap[i],r.depth));)r.heap[t]=r.heap[i],t=i,i<<=1;r.heap[t]=n},Jo=(r,e,t)=>{let n,i,s,a,o=0;if(r.sym_next!==0)do n=255&r.pending_buf[r.sym_buf+o++],n+=(255&r.pending_buf[r.sym_buf+o++])<<8,i=r.pending_buf[r.sym_buf+o++],n===0?Ve(r,i,e):(s=gr[i],Ve(r,s+256+1,e),a=yi[s],a!==0&&(i-=Si[s],be(r,i,a)),n--,s=jo(n),Ve(r,s,t),a=dn[s],a!==0&&(n-=ln[s],be(r,n,a)));while(o<r.sym_next);Ve(r,256,e)},wi=(r,e)=>{const t=e.dyn_tree,n=e.stat_desc.static_tree,i=e.stat_desc.has_stree,s=e.stat_desc.elems;let a,o,d,c=-1;for(r.heap_len=0,r.heap_max=573,a=0;a<s;a++)t[2*a]!==0?(r.heap[++r.heap_len]=c=a,r.depth[a]=0):t[2*a+1]=0;for(;r.heap_len<2;)d=r.heap[++r.heap_len]=c<2?++c:0,t[2*d]=1,r.depth[d]=0,r.opt_len--,i&&(r.static_len-=n[2*d+1]);for(e.max_code=c,a=r.heap_len>>1;a>=1;a--)Ci(r,t,a);d=s;do a=r.heap[1],r.heap[1]=r.heap[r.heap_len--],Ci(r,t,1),o=r.heap[1],r.heap[--r.heap_max]=a,r.heap[--r.heap_max]=o,t[2*d]=t[2*a]+t[2*o],r.depth[d]=(r.depth[a]>=r.depth[o]?r.depth[a]:r.depth[o])+1,t[2*a+1]=t[2*o+1]=d,r.heap[1]=d++,Ci(r,t,1);while(r.heap_len>=2);r.heap[--r.heap_max]=r.heap[1],((u,h)=>{const l=h.dyn_tree,f=h.max_code,y=h.stat_desc.static_tree,C=h.stat_desc.has_stree,v=h.stat_desc.extra_bits,E=h.stat_desc.extra_base,k=h.stat_desc.max_length;let g,D,L,R,M,N,U=0;for(R=0;R<=15;R++)u.bl_count[R]=0;for(l[2*u.heap[u.heap_max]+1]=0,g=u.heap_max+1;g<573;g++)D=u.heap[g],R=l[2*l[2*D+1]+1]+1,R>k&&(R=k,U++),l[2*D+1]=R,D>f||(u.bl_count[R]++,M=0,D>=E&&(M=v[D-E]),N=l[2*D],u.opt_len+=N*(R+M),C&&(u.static_len+=N*(y[2*D+1]+M)));if(U!==0){do{for(R=k-1;u.bl_count[R]===0;)R--;u.bl_count[R]--,u.bl_count[R+1]+=2,u.bl_count[k]--,U-=2}while(U>0);for(R=k;R!==0;R--)for(D=u.bl_count[R];D!==0;)L=u.heap[--g],L>f||(l[2*L+1]!==R&&(u.opt_len+=(R-l[2*L+1])*l[2*L],l[2*L+1]=R),D--)}})(r,e),qo(t,c,r.bl_count)},Xo=(r,e,t)=>{let n,i,s=-1,a=e[1],o=0,d=7,c=4;for(a===0&&(d=138,c=3),e[2*(t+1)+1]=65535,n=0;n<=t;n++)i=a,a=e[2*(n+1)+1],++o<d&&i===a||(o<c?r.bl_tree[2*i]+=o:i!==0?(i!==s&&r.bl_tree[2*i]++,r.bl_tree[32]++):o<=10?r.bl_tree[34]++:r.bl_tree[36]++,o=0,s=i,a===0?(d=138,c=3):i===a?(d=6,c=3):(d=7,c=4))},Zo=(r,e,t)=>{let n,i,s=-1,a=e[1],o=0,d=7,c=4;for(a===0&&(d=138,c=3),n=0;n<=t;n++)if(i=a,a=e[2*(n+1)+1],!(++o<d&&i===a)){if(o<c)do Ve(r,i,r.bl_tree);while(--o!=0);else i!==0?(i!==s&&(Ve(r,i,r.bl_tree),o--),Ve(r,16,r.bl_tree),be(r,o-3,2)):o<=10?(Ve(r,17,r.bl_tree),be(r,o-3,3)):(Ve(r,18,r.bl_tree),be(r,o-11,7));o=0,s=i,a===0?(d=138,c=3):i===a?(d=6,c=3):(d=7,c=4)}};let Yo=!1;const Qo=(r,e,t,n)=>{be(r,0+(n?1:0),3),Ko(r),vr(r,t),vr(r,~t),t&&r.pending_buf.set(r.window.subarray(e,e+t),r.pending),r.pending+=t};var Mf={_tr_init:r=>{Yo||((()=>{let e,t,n,i,s;const a=new Array(16);for(n=0,i=0;i<28;i++)for(Si[i]=n,e=0;e<1<<yi[i];e++)gr[n++]=i;for(gr[n-1]=i,s=0,i=0;i<16;i++)for(ln[i]=s,e=0;e<1<<dn[i];e++)_r[s++]=i;for(s>>=7;i<30;i++)for(ln[i]=s<<7,e=0;e<1<<dn[i]-7;e++)_r[256+s++]=i;for(t=0;t<=15;t++)a[t]=0;for(e=0;e<=143;)tt[2*e+1]=8,e++,a[8]++;for(;e<=255;)tt[2*e+1]=9,e++,a[9]++;for(;e<=279;)tt[2*e+1]=7,e++,a[7]++;for(;e<=287;)tt[2*e+1]=8,e++,a[8]++;for(qo(tt,287,a),e=0;e<30;e++)mr[2*e+1]=5,mr[2*e]=Ho(e,5);Bo=new bi(tt,yi,257,286,15),Fo=new bi(mr,dn,0,30,15),Vo=new bi(new Array(0),Of,0,19,7)})(),Yo=!0),r.l_desc=new Ei(r.dyn_ltree,Bo),r.d_desc=new Ei(r.dyn_dtree,Fo),r.bl_desc=new Ei(r.bl_tree,Vo),r.bi_buf=0,r.bi_valid=0,$o(r)},_tr_stored_block:Qo,_tr_flush_block:(r,e,t,n)=>{let i,s,a=0;r.level>0?(r.strm.data_type===2&&(r.strm.data_type=(o=>{let d,c=4093624447;for(d=0;d<=31;d++,c>>>=1)if(1&c&&o.dyn_ltree[2*d]!==0)return 0;if(o.dyn_ltree[18]!==0||o.dyn_ltree[20]!==0||o.dyn_ltree[26]!==0)return 1;for(d=32;d<256;d++)if(o.dyn_ltree[2*d]!==0)return 1;return 0})(r)),wi(r,r.l_desc),wi(r,r.d_desc),a=(o=>{let d;for(Xo(o,o.dyn_ltree,o.l_desc.max_code),Xo(o,o.dyn_dtree,o.d_desc.max_code),wi(o,o.bl_desc),d=18;d>=3&&o.bl_tree[2*Go[d]+1]===0;d--);return o.opt_len+=3*(d+1)+5+5+4,d})(r),i=r.opt_len+3+7>>>3,s=r.static_len+3+7>>>3,s<=i&&(i=s)):i=s=t+5,t+4<=i&&e!==-1?Qo(r,e,t,n):r.strategy===4||s===i?(be(r,2+(n?1:0),3),Jo(r,tt,mr)):(be(r,4+(n?1:0),3),((o,d,c,u)=>{let h;for(be(o,d-257,5),be(o,c-1,5),be(o,u-4,4),h=0;h<u;h++)be(o,o.bl_tree[2*Go[h]+1],3);Zo(o,o.dyn_ltree,d-1),Zo(o,o.dyn_dtree,c-1)})(r,r.l_desc.max_code+1,r.d_desc.max_code+1,a+1),Jo(r,r.dyn_ltree,r.dyn_dtree)),$o(r),n&&Ko(r)},_tr_tally:(r,e,t)=>(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*(gr[t]+256+1)]++,r.dyn_dtree[2*jo(e)]++),r.sym_next===r.sym_end),_tr_align:r=>{be(r,2,3),Ve(r,256,tt),(e=>{e.bi_valid===16?(vr(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)}},yr=(r,e,t,n)=>{let i=65535&r|0,s=r>>>16&65535|0,a=0;for(;t!==0;){a=t>2e3?2e3:t,t-=a;do i=i+e[n++]|0,s=s+i|0;while(--a);i%=65521,s%=65521}return i|s<<16|0};const Lf=new Uint32Array((()=>{let r,e=[];for(var t=0;t<256;t++){r=t;for(var n=0;n<8;n++)r=1&r?3988292384^r>>>1:r>>>1;e[t]=r}return e})());var le=(r,e,t,n)=>{const i=Lf,s=n+t;r^=-1;for(let a=n;a<s;a++)r=r>>>8^i[255&(r^e[a])];return-1^r},Ct={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"},wt={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};const{_tr_init:Nf,_tr_stored_block:Ti,_tr_flush_block:Uf,_tr_tally:ct,_tr_align:Gf}=Mf,{Z_NO_FLUSH:ut,Z_PARTIAL_FLUSH:Bf,Z_FULL_FLUSH:Ff,Z_FINISH:Ie,Z_BLOCK:ea,Z_OK:fe,Z_STREAM_END:ta,Z_STREAM_ERROR:je,Z_DATA_ERROR:Vf,Z_BUF_ERROR:ki,Z_DEFAULT_COMPRESSION:jf,Z_FILTERED:Hf,Z_HUFFMAN_ONLY:hn,Z_RLE:qf,Z_FIXED:$f,Z_DEFAULT_STRATEGY:Kf,Z_UNKNOWN:Wf,Z_DEFLATED:pn}=wt,Tt=(r,e)=>(r.msg=Ct[e],e),ra=r=>2*r-(r>4?9:0),dt=r=>{let e=r.length;for(;--e>=0;)r[e]=0},Jf=r=>{let e,t,n,i=r.w_size;e=r.hash_size,n=e;do t=r.head[--n],r.head[n]=t>=i?t-i:0;while(--e);e=i,n=e;do t=r.prev[--n],r.prev[n]=t>=i?t-i:0;while(--e)};let lt=(r,e,t)=>(e<<r.hash_shift^t)&r.hash_mask;const Re=r=>{const e=r.state;let 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))},Ae=(r,e)=>{Uf(r,r.block_start>=0?r.block_start:-1,r.strstart-r.block_start,e),r.block_start=r.strstart,Re(r.strm)},ee=(r,e)=>{r.pending_buf[r.pending++]=e},Sr=(r,e)=>{r.pending_buf[r.pending++]=e>>>8&255,r.pending_buf[r.pending++]=255&e},Ri=(r,e,t,n)=>{let i=r.avail_in;return i>n&&(i=n),i===0?0:(r.avail_in-=i,e.set(r.input.subarray(r.next_in,r.next_in+i),t),r.state.wrap===1?r.adler=yr(r.adler,e,i,t):r.state.wrap===2&&(r.adler=le(r.adler,e,i,t)),r.next_in+=i,r.total_in+=i,i)},na=(r,e)=>{let t,n,i=r.max_chain_length,s=r.strstart,a=r.prev_length,o=r.nice_match;const d=r.strstart>r.w_size-262?r.strstart-(r.w_size-262):0,c=r.window,u=r.w_mask,h=r.prev,l=r.strstart+258;let f=c[s+a-1],y=c[s+a];r.prev_length>=r.good_match&&(i>>=2),o>r.lookahead&&(o=r.lookahead);do if(t=e,c[t+a]===y&&c[t+a-1]===f&&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<l);if(n=258-(l-s),s=l-258,n>a){if(r.match_start=e,a=n,n>=o)break;f=c[s+a-1],y=c[s+a]}}while((e=h[e&u])>d&&--i!=0);return a<=r.lookahead?a:r.lookahead},jt=r=>{const e=r.w_size;let t,n,i;do{if(n=r.window_size-r.lookahead-r.strstart,r.strstart>=e+(e-262)&&(r.window.set(r.window.subarray(e,e+e-n),0),r.match_start-=e,r.strstart-=e,r.block_start-=e,r.insert>r.strstart&&(r.insert=r.strstart),Jf(r),n+=e),r.strm.avail_in===0)break;if(t=Ri(r.strm,r.window,r.strstart+r.lookahead,n),r.lookahead+=t,r.lookahead+r.insert>=3)for(i=r.strstart-r.insert,r.ins_h=r.window[i],r.ins_h=lt(r,r.ins_h,r.window[i+1]);r.insert&&(r.ins_h=lt(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)},ia=(r,e)=>{let t,n,i,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,i=r.bi_valid+42>>3,r.strm.avail_out<i||(i=r.strm.avail_out-i,n=r.strstart-r.block_start,t>n+r.strm.avail_in&&(t=n+r.strm.avail_in),t>i&&(t=i),t<s&&(t===0&&e!==Ie||e===ut||t!==n+r.strm.avail_in)))break;a=e===Ie&&t===n+r.strm.avail_in?1:0,Ti(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,Re(r.strm),n&&(n>t&&(n=t),r.strm.output.set(r.window.subarray(r.block_start,r.block_start+n),r.strm.next_out),r.strm.next_out+=n,r.strm.avail_out-=n,r.strm.total_out+=n,r.block_start+=n,t-=n),t&&(Ri(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&&(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!==ut&&e!==Ie&&r.strm.avail_in===0&&r.strstart===r.block_start?2:(i=r.window_size-r.strstart,r.strm.avail_in>i&&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++,i+=r.w_size,r.insert>r.strstart&&(r.insert=r.strstart)),i>r.strm.avail_in&&(i=r.strm.avail_in),i&&(Ri(r.strm,r.window,r.strstart,i),r.strstart+=i,r.insert+=i>r.w_size-r.insert?r.w_size-r.insert:i),r.high_water<r.strstart&&(r.high_water=r.strstart),i=r.bi_valid+42>>3,i=r.pending_buf_size-i>65535?65535:r.pending_buf_size-i,s=i>r.w_size?r.w_size:i,n=r.strstart-r.block_start,(n>=s||(n||e===Ie)&&e!==ut&&r.strm.avail_in===0&&n<=i)&&(t=n>i?i:n,a=e===Ie&&r.strm.avail_in===0&&t===n?1:0,Ti(r,r.block_start,t,a),r.block_start+=t,Re(r.strm)),a?3:1)},Ai=(r,e)=>{let t,n;for(;;){if(r.lookahead<262){if(jt(r),r.lookahead<262&&e===ut)return 1;if(r.lookahead===0)break}if(t=0,r.lookahead>=3&&(r.ins_h=lt(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=na(r,t)),r.match_length>=3)if(n=ct(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=lt(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=lt(r,r.ins_h,r.window[r.strstart+1]);else n=ct(r,0,r.window[r.strstart]),r.lookahead--,r.strstart++;if(n&&(Ae(r,!1),r.strm.avail_out===0))return 1}return r.insert=r.strstart<2?r.strstart:2,e===Ie?(Ae(r,!0),r.strm.avail_out===0?3:4):r.sym_next&&(Ae(r,!1),r.strm.avail_out===0)?1:2},Ht=(r,e)=>{let t,n,i;for(;;){if(r.lookahead<262){if(jt(r),r.lookahead<262&&e===ut)return 1;if(r.lookahead===0)break}if(t=0,r.lookahead>=3&&(r.ins_h=lt(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=na(r,t),r.match_length<=5&&(r.strategy===Hf||r.match_length===3&&r.strstart-r.match_start>4096)&&(r.match_length=2)),r.prev_length>=3&&r.match_length<=r.prev_length){i=r.strstart+r.lookahead-3,n=ct(r,r.strstart-1-r.prev_match,r.prev_length-3),r.lookahead-=r.prev_length-1,r.prev_length-=2;do++r.strstart<=i&&(r.ins_h=lt(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++,n&&(Ae(r,!1),r.strm.avail_out===0))return 1}else if(r.match_available){if(n=ct(r,0,r.window[r.strstart-1]),n&&Ae(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&&(n=ct(r,0,r.window[r.strstart-1]),r.match_available=0),r.insert=r.strstart<2?r.strstart:2,e===Ie?(Ae(r,!0),r.strm.avail_out===0?3:4):r.sym_next&&(Ae(r,!1),r.strm.avail_out===0)?1:2};function He(r,e,t,n,i){this.good_length=r,this.max_lazy=e,this.nice_length=t,this.max_chain=n,this.func=i}const br=[new He(0,0,0,0,ia),new He(4,4,8,4,Ai),new He(4,5,16,8,Ai),new He(4,6,32,32,Ai),new He(4,4,16,16,Ht),new He(8,16,32,32,Ht),new He(8,16,128,128,Ht),new He(8,32,128,256,Ht),new He(32,128,258,1024,Ht),new He(32,258,258,4096,Ht)];function Xf(){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=pn,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(1146),this.dyn_dtree=new Uint16Array(122),this.bl_tree=new Uint16Array(78),dt(this.dyn_ltree),dt(this.dyn_dtree),dt(this.bl_tree),this.l_desc=null,this.d_desc=null,this.bl_desc=null,this.bl_count=new Uint16Array(16),this.heap=new Uint16Array(573),dt(this.heap),this.heap_len=0,this.heap_max=0,this.depth=new Uint16Array(573),dt(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}const Er=r=>{if(!r)return 1;const 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},sa=r=>{if(Er(r))return Tt(r,je);r.total_in=r.total_out=0,r.data_type=Wf;const 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),fe},oa=r=>{const e=sa(r);var t;return e===fe&&((t=r.state).window_size=2*t.w_size,dt(t.head),t.max_lazy_match=br[t.level].max_lazy,t.good_match=br[t.level].good_length,t.nice_match=br[t.level].nice_length,t.max_chain_length=br[t.level].max_chain,t.strstart=0,t.block_start=0,t.lookahead=0,t.insert=0,t.match_length=t.prev_length=2,t.match_available=0,t.ins_h=0),e},aa=(r,e,t,n,i,s)=>{if(!r)return je;let a=1;if(e===jf&&(e=6),n<0?(a=0,n=-n):n>15&&(a=2,n-=16),i<1||i>9||t!==pn||n<8||n>15||e<0||e>9||s<0||s>$f||n===8&&a!==1)return Tt(r,je);n===8&&(n=9);const o=new Xf;return r.state=o,o.strm=r,o.status=42,o.wrap=a,o.gzhead=null,o.w_bits=n,o.w_size=1<<o.w_bits,o.w_mask=o.w_size-1,o.hash_bits=i+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<<i+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,oa(r)};var Cr={deflateInit:(r,e)=>aa(r,e,pn,15,8,Kf),deflateInit2:aa,deflateReset:oa,deflateResetKeep:sa,deflateSetHeader:(r,e)=>Er(r)||r.state.wrap!==2?je:(r.state.gzhead=e,fe),deflate:(r,e)=>{if(Er(r)||e>ea||e<0)return r?Tt(r,je):je;const t=r.state;if(!r.output||r.avail_in!==0&&!r.input||t.status===666&&e!==Ie)return Tt(r,r.avail_out===0?ki:je);const n=t.last_flush;if(t.last_flush=e,t.pending!==0){if(Re(r),r.avail_out===0)return t.last_flush=-1,fe}else if(r.avail_in===0&&ra(e)<=ra(n)&&e!==Ie)return Tt(r,ki);if(t.status===666&&r.avail_in!==0)return Tt(r,ki);if(t.status===42&&t.wrap===0&&(t.status=113),t.status===42){let i=pn+(t.w_bits-8<<4)<<8,s=-1;if(s=t.strategy>=hn||t.level<2?0:t.level<6?1:t.level===6?2:3,i|=s<<6,t.strstart!==0&&(i|=32),i+=31-i%31,Sr(t,i),t.strstart!==0&&(Sr(t,r.adler>>>16),Sr(t,65535&r.adler)),r.adler=1,t.status=113,Re(r),t.pending!==0)return t.last_flush=-1,fe}if(t.status===57){if(r.adler=0,ee(t,31),ee(t,139),ee(t,8),t.gzhead)ee(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)),ee(t,255&t.gzhead.time),ee(t,t.gzhead.time>>8&255),ee(t,t.gzhead.time>>16&255),ee(t,t.gzhead.time>>24&255),ee(t,t.level===9?2:t.strategy>=hn||t.level<2?4:0),ee(t,255&t.gzhead.os),t.gzhead.extra&&t.gzhead.extra.length&&(ee(t,255&t.gzhead.extra.length),ee(t,t.gzhead.extra.length>>8&255)),t.gzhead.hcrc&&(r.adler=le(r.adler,t.pending_buf,t.pending,0)),t.gzindex=0,t.status=69;else if(ee(t,0),ee(t,0),ee(t,0),ee(t,0),ee(t,0),ee(t,t.level===9?2:t.strategy>=hn||t.level<2?4:0),ee(t,3),t.status=113,Re(r),t.pending!==0)return t.last_flush=-1,fe}if(t.status===69){if(t.gzhead.extra){let i=t.pending,s=(65535&t.gzhead.extra.length)-t.gzindex;for(;t.pending+s>t.pending_buf_size;){let 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>i&&(r.adler=le(r.adler,t.pending_buf,t.pending-i,i)),t.gzindex+=o,Re(r),t.pending!==0)return t.last_flush=-1,fe;i=0,s-=o}let a=new Uint8Array(t.gzhead.extra);t.pending_buf.set(a.subarray(t.gzindex,t.gzindex+s),t.pending),t.pending+=s,t.gzhead.hcrc&&t.pending>i&&(r.adler=le(r.adler,t.pending_buf,t.pending-i,i)),t.gzindex=0}t.status=73}if(t.status===73){if(t.gzhead.name){let i,s=t.pending;do{if(t.pending===t.pending_buf_size){if(t.gzhead.hcrc&&t.pending>s&&(r.adler=le(r.adler,t.pending_buf,t.pending-s,s)),Re(r),t.pending!==0)return t.last_flush=-1,fe;s=0}i=t.gzindex<t.gzhead.name.length?255&t.gzhead.name.charCodeAt(t.gzindex++):0,ee(t,i)}while(i!==0);t.gzhead.hcrc&&t.pending>s&&(r.adler=le(r.adler,t.pending_buf,t.pending-s,s)),t.gzindex=0}t.status=91}if(t.status===91){if(t.gzhead.comment){let i,s=t.pending;do{if(t.pending===t.pending_buf_size){if(t.gzhead.hcrc&&t.pending>s&&(r.adler=le(r.adler,t.pending_buf,t.pending-s,s)),Re(r),t.pending!==0)return t.last_flush=-1,fe;s=0}i=t.gzindex<t.gzhead.comment.length?255&t.gzhead.comment.charCodeAt(t.gzindex++):0,ee(t,i)}while(i!==0);t.gzhead.hcrc&&t.pending>s&&(r.adler=le(r.adler,t.pending_buf,t.pending-s,s))}t.status=103}if(t.status===103){if(t.gzhead.hcrc){if(t.pending+2>t.pending_buf_size&&(Re(r),t.pending!==0))return t.last_flush=-1,fe;ee(t,255&r.adler),ee(t,r.adler>>8&255),r.adler=0}if(t.status=113,Re(r),t.pending!==0)return t.last_flush=-1,fe}if(r.avail_in!==0||t.lookahead!==0||e!==ut&&t.status!==666){let i=t.level===0?ia(t,e):t.strategy===hn?((s,a)=>{let o;for(;;){if(s.lookahead===0&&(jt(s),s.lookahead===0)){if(a===ut)return 1;break}if(s.match_length=0,o=ct(s,0,s.window[s.strstart]),s.lookahead--,s.strstart++,o&&(Ae(s,!1),s.strm.avail_out===0))return 1}return s.insert=0,a===Ie?(Ae(s,!0),s.strm.avail_out===0?3:4):s.sym_next&&(Ae(s,!1),s.strm.avail_out===0)?1:2})(t,e):t.strategy===qf?((s,a)=>{let o,d,c,u;const h=s.window;for(;;){if(s.lookahead<=258){if(jt(s),s.lookahead<=258&&a===ut)return 1;if(s.lookahead===0)break}if(s.match_length=0,s.lookahead>=3&&s.strstart>0&&(c=s.strstart-1,d=h[c],d===h[++c]&&d===h[++c]&&d===h[++c])){u=s.strstart+258;do;while(d===h[++c]&&d===h[++c]&&d===h[++c]&&d===h[++c]&&d===h[++c]&&d===h[++c]&&d===h[++c]&&d===h[++c]&&c<u);s.match_length=258-(u-c),s.match_length>s.lookahead&&(s.match_length=s.lookahead)}if(s.match_length>=3?(o=ct(s,1,s.match_length-3),s.lookahead-=s.match_length,s.strstart+=s.match_length,s.match_length=0):(o=ct(s,0,s.window[s.strstart]),s.lookahead--,s.strstart++),o&&(Ae(s,!1),s.strm.avail_out===0))return 1}return s.insert=0,a===Ie?(Ae(s,!0),s.strm.avail_out===0?3:4):s.sym_next&&(Ae(s,!1),s.strm.avail_out===0)?1:2})(t,e):br[t.level].func(t,e);if(i!==3&&i!==4||(t.status=666),i===1||i===3)return r.avail_out===0&&(t.last_flush=-1),fe;if(i===2&&(e===Bf?Gf(t):e!==ea&&(Ti(t,0,0,!1),e===Ff&&(dt(t.head),t.lookahead===0&&(t.strstart=0,t.block_start=0,t.insert=0))),Re(r),r.avail_out===0))return t.last_flush=-1,fe}return e!==Ie?fe:t.wrap<=0?ta:(t.wrap===2?(ee(t,255&r.adler),ee(t,r.adler>>8&255),ee(t,r.adler>>16&255),ee(t,r.adler>>24&255),ee(t,255&r.total_in),ee(t,r.total_in>>8&255),ee(t,r.total_in>>16&255),ee(t,r.total_in>>24&255)):(Sr(t,r.adler>>>16),Sr(t,65535&r.adler)),Re(r),t.wrap>0&&(t.wrap=-t.wrap),t.pending!==0?fe:ta)},deflateEnd:r=>{if(Er(r))return je;const e=r.state.status;return r.state=null,e===113?Tt(r,Vf):fe},deflateSetDictionary:(r,e)=>{let t=e.length;if(Er(r))return je;const n=r.state,i=n.wrap;if(i===2||i===1&&n.status!==42||n.lookahead)return je;if(i===1&&(r.adler=yr(r.adler,e,t,0)),n.wrap=0,t>=n.w_size){i===0&&(dt(n.head),n.strstart=0,n.block_start=0,n.insert=0);let d=new Uint8Array(n.w_size);d.set(e.subarray(t-n.w_size,t),0),e=d,t=n.w_size}const s=r.avail_in,a=r.next_in,o=r.input;for(r.avail_in=t,r.next_in=0,r.input=e,jt(n);n.lookahead>=3;){let d=n.strstart,c=n.lookahead-2;do n.ins_h=lt(n,n.ins_h,n.window[d+3-1]),n.prev[d&n.w_mask]=n.head[n.ins_h],n.head[n.ins_h]=d,d++;while(--c);n.strstart=d,n.lookahead=2,jt(n)}return n.strstart+=n.lookahead,n.block_start=n.strstart,n.insert=n.lookahead,n.lookahead=0,n.match_length=n.prev_length=2,n.match_available=0,r.next_in=a,r.input=o,r.avail_in=s,n.wrap=i,fe},deflateInfo:"pako deflate (from Nodeca project)"};const Zf=(r,e)=>Object.prototype.hasOwnProperty.call(r,e);var ca=function(r){const e=Array.prototype.slice.call(arguments,1);for(;e.length;){const t=e.shift();if(t){if(typeof t!="object")throw new TypeError(t+"must be non-object");for(const n in t)Zf(t,n)&&(r[n]=t[n])}}return r},ua=r=>{let e=0;for(let n=0,i=r.length;n<i;n++)e+=r[n].length;const t=new Uint8Array(e);for(let n=0,i=0,s=r.length;n<s;n++){let a=r[n];t.set(a,i),i+=a.length}return t};let da=!0;try{String.fromCharCode.apply(null,new Uint8Array(1))}catch{da=!1}const wr=new Uint8Array(256);for(let r=0;r<256;r++)wr[r]=r>=252?6:r>=248?5:r>=240?4:r>=224?3:r>=192?2:1;wr[254]=wr[254]=1;var Di=r=>{if(typeof TextEncoder=="function"&&TextEncoder.prototype.encode)return new TextEncoder().encode(r);let e,t,n,i,s,a=r.length,o=0;for(i=0;i<a;i++)t=r.charCodeAt(i),(64512&t)==55296&&i+1<a&&(n=r.charCodeAt(i+1),(64512&n)==56320&&(t=65536+(t-55296<<10)+(n-56320),i++)),o+=t<128?1:t<2048?2:t<65536?3:4;for(e=new Uint8Array(o),s=0,i=0;s<o;i++)t=r.charCodeAt(i),(64512&t)==55296&&i+1<a&&(n=r.charCodeAt(i+1),(64512&n)==56320&&(t=65536+(t-55296<<10)+(n-56320),i++)),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},Yf=(r,e)=>{const t=e||r.length;if(typeof TextDecoder=="function"&&TextDecoder.prototype.decode)return new TextDecoder().decode(r.subarray(0,e));let n,i;const s=new Array(2*t);for(i=0,n=0;n<t;){let a=r[n++];if(a<128){s[i++]=a;continue}let o=wr[a];if(o>4)s[i++]=65533,n+=o-1;else{for(a&=o===2?31:o===3?15:7;o>1&&n<t;)a=a<<6|63&r[n++],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((a,o)=>{if(o<65534&&a.subarray&&da)return String.fromCharCode.apply(null,a.length===o?a:a.subarray(0,o));let d="";for(let c=0;c<o;c++)d+=String.fromCharCode(a[c]);return d})(s,i)},Qf=(r,e)=>{(e=e||r.length)>r.length&&(e=r.length);let t=e-1;for(;t>=0&&(192&r[t])==128;)t--;return t<0||t===0?e:t+wr[r[t]]>e?t:e},la=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};const ha=Object.prototype.toString,{Z_NO_FLUSH:em,Z_SYNC_FLUSH:tm,Z_FULL_FLUSH:rm,Z_FINISH:nm,Z_OK:fn,Z_STREAM_END:im,Z_DEFAULT_COMPRESSION:sm,Z_DEFAULT_STRATEGY:om,Z_DEFLATED:am}=wt;function Tr(r){this.options=ca({level:sm,method:am,chunkSize:16384,windowBits:15,memLevel:8,strategy:om},r||{});let 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 la,this.strm.avail_out=0;let t=Cr.deflateInit2(this.strm,e.level,e.method,e.windowBits,e.memLevel,e.strategy);if(t!==fn)throw new Error(Ct[t]);if(e.header&&Cr.deflateSetHeader(this.strm,e.header),e.dictionary){let n;if(n=typeof e.dictionary=="string"?Di(e.dictionary):ha.call(e.dictionary)==="[object ArrayBuffer]"?new Uint8Array(e.dictionary):e.dictionary,t=Cr.deflateSetDictionary(this.strm,n),t!==fn)throw new Error(Ct[t]);this._dict_set=!0}}function xi(r,e){const t=new Tr(e);if(t.push(r,!0),t.err)throw t.msg||Ct[t.err];return t.result}Tr.prototype.push=function(r,e){const t=this.strm,n=this.options.chunkSize;let i,s;if(this.ended)return!1;for(s=e===~~e?e:e===!0?nm:em,typeof r=="string"?t.input=Di(r):ha.call(r)==="[object ArrayBuffer]"?t.input=new Uint8Array(r):t.input=r,t.next_in=0,t.avail_in=t.input.length;;)if(t.avail_out===0&&(t.output=new Uint8Array(n),t.next_out=0,t.avail_out=n),(s===tm||s===rm)&&t.avail_out<=6)this.onData(t.output.subarray(0,t.next_out)),t.avail_out=0;else{if(i=Cr.deflate(t,s),i===im)return t.next_out>0&&this.onData(t.output.subarray(0,t.next_out)),i=Cr.deflateEnd(this.strm),this.onEnd(i),this.ended=!0,i===fn;if(t.avail_out!==0){if(s>0&&t.next_out>0)this.onData(t.output.subarray(0,t.next_out)),t.avail_out=0;else if(t.avail_in===0)break}else this.onData(t.output)}return!0},Tr.prototype.onData=function(r){this.chunks.push(r)},Tr.prototype.onEnd=function(r){r===fn&&(this.result=ua(this.chunks)),this.chunks=[],this.err=r,this.msg=this.strm.msg};var cm={Deflate:Tr,deflate:xi,deflateRaw:function(r,e){return(e=e||{}).raw=!0,xi(r,e)},gzip:function(r,e){return(e=e||{}).gzip=!0,xi(r,e)},constants:wt},um=function(r,e){let t,n,i,s,a,o,d,c,u,h,l,f,y,C,v,E,k,g,D,L,R,M,N,U;const B=r.state;t=r.next_in,N=r.input,n=t+(r.avail_in-5),i=r.next_out,U=r.output,s=i-(e-r.avail_out),a=i+(r.avail_out-257),o=B.dmax,d=B.wsize,c=B.whave,u=B.wnext,h=B.window,l=B.hold,f=B.bits,y=B.lencode,C=B.distcode,v=(1<<B.lenbits)-1,E=(1<<B.distbits)-1;e:do{f<15&&(l+=N[t++]<<f,f+=8,l+=N[t++]<<f,f+=8),k=y[l&v];t:for(;;){if(g=k>>>24,l>>>=g,f-=g,g=k>>>16&255,g===0)U[i++]=65535&k;else{if(!(16&g)){if(!(64&g)){k=y[(65535&k)+(l&(1<<g)-1)];continue t}if(32&g){B.mode=16191;break e}r.msg="invalid literal/length code",B.mode=16209;break e}D=65535&k,g&=15,g&&(f<g&&(l+=N[t++]<<f,f+=8),D+=l&(1<<g)-1,l>>>=g,f-=g),f<15&&(l+=N[t++]<<f,f+=8,l+=N[t++]<<f,f+=8),k=C[l&E];r:for(;;){if(g=k>>>24,l>>>=g,f-=g,g=k>>>16&255,!(16&g)){if(!(64&g)){k=C[(65535&k)+(l&(1<<g)-1)];continue r}r.msg="invalid distance code",B.mode=16209;break e}if(L=65535&k,g&=15,f<g&&(l+=N[t++]<<f,f+=8,f<g&&(l+=N[t++]<<f,f+=8)),L+=l&(1<<g)-1,L>o){r.msg="invalid distance too far back",B.mode=16209;break e}if(l>>>=g,f-=g,g=i-s,L>g){if(g=L-g,g>c&&B.sane){r.msg="invalid distance too far back",B.mode=16209;break e}if(R=0,M=h,u===0){if(R+=d-g,g<D){D-=g;do U[i++]=h[R++];while(--g);R=i-L,M=U}}else if(u<g){if(R+=d+u-g,g-=u,g<D){D-=g;do U[i++]=h[R++];while(--g);if(R=0,u<D){g=u,D-=g;do U[i++]=h[R++];while(--g);R=i-L,M=U}}}else if(R+=u-g,g<D){D-=g;do U[i++]=h[R++];while(--g);R=i-L,M=U}for(;D>2;)U[i++]=M[R++],U[i++]=M[R++],U[i++]=M[R++],D-=3;D&&(U[i++]=M[R++],D>1&&(U[i++]=M[R++]))}else{R=i-L;do U[i++]=U[R++],U[i++]=U[R++],U[i++]=U[R++],D-=3;while(D>2);D&&(U[i++]=U[R++],D>1&&(U[i++]=U[R++]))}break}}break}}while(t<n&&i<a);D=f>>3,t-=D,f-=D<<3,l&=(1<<f)-1,r.next_in=t,r.next_out=i,r.avail_in=t<n?n-t+5:5-(t-n),r.avail_out=i<a?a-i+257:257-(i-a),B.hold=l,B.bits=f};const dm=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]),lm=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]),hm=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]),pm=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]);var kr=(r,e,t,n,i,s,a,o)=>{const d=o.bits;let c,u,h,l,f,y,C=0,v=0,E=0,k=0,g=0,D=0,L=0,R=0,M=0,N=0,U=null;const B=new Uint16Array(16),H=new Uint16Array(16);let Y,W,de,ce=null;for(C=0;C<=15;C++)B[C]=0;for(v=0;v<n;v++)B[e[t+v]]++;for(g=d,k=15;k>=1&&B[k]===0;k--);if(g>k&&(g=k),k===0)return i[s++]=20971520,i[s++]=20971520,o.bits=1,0;for(E=1;E<k&&B[E]===0;E++);for(g<E&&(g=E),R=1,C=1;C<=15;C++)if(R<<=1,R-=B[C],R<0)return-1;if(R>0&&(r===0||k!==1))return-1;for(H[1]=0,C=1;C<15;C++)H[C+1]=H[C]+B[C];for(v=0;v<n;v++)e[t+v]!==0&&(a[H[e[t+v]]++]=v);if(r===0?(U=ce=a,y=20):r===1?(U=dm,ce=lm,y=257):(U=hm,ce=pm,y=0),N=0,v=0,C=E,f=s,D=g,L=0,h=-1,M=1<<g,l=M-1,r===1&&M>852||r===2&&M>592)return 1;for(;;){Y=C-L,a[v]+1<y?(W=0,de=a[v]):a[v]>=y?(W=ce[a[v]-y],de=U[a[v]-y]):(W=96,de=0),c=1<<C-L,u=1<<D,E=u;do u-=c,i[f+(N>>L)+u]=Y<<24|W<<16|de|0;while(u!==0);for(c=1<<C-1;N&c;)c>>=1;if(c!==0?(N&=c-1,N+=c):N=0,v++,--B[C]==0){if(C===k)break;C=e[t+a[v]]}if(C>g&&(N&l)!==h){for(L===0&&(L=g),f+=E,D=C-L,R=1<<D;D+L<k&&(R-=B[D+L],!(R<=0));)D++,R<<=1;if(M+=1<<D,r===1&&M>852||r===2&&M>592)return 1;h=N&l,i[h]=g<<24|D<<16|f-s|0}}return N!==0&&(i[f+N]=C-L<<24|64<<16|0),o.bits=g,0};const{Z_FINISH:pa,Z_BLOCK:fm,Z_TREES:mn,Z_OK:kt,Z_STREAM_END:mm,Z_NEED_DICT:_m,Z_STREAM_ERROR:ze,Z_DATA_ERROR:fa,Z_MEM_ERROR:ma,Z_BUF_ERROR:gm,Z_DEFLATED:_a}=wt,ga=r=>(r>>>24&255)+(r>>>8&65280)+((65280&r)<<8)+((255&r)<<24);function vm(){this.strm=null,this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new Uint16Array(320),this.work=new Uint16Array(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}const Rt=r=>{if(!r)return 1;const e=r.state;return!e||e.strm!==r||e.mode<16180||e.mode>16211?1:0},va=r=>{if(Rt(r))return ze;const 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,kt},ya=r=>{if(Rt(r))return ze;const e=r.state;return e.wsize=0,e.whave=0,e.wnext=0,va(r)},Sa=(r,e)=>{let t;if(Rt(r))return ze;const n=r.state;return e<0?(t=0,e=-e):(t=5+(e>>4),e<48&&(e&=15)),e&&(e<8||e>15)?ze:(n.window!==null&&n.wbits!==e&&(n.window=null),n.wrap=t,n.wbits=e,ya(r))},ba=(r,e)=>{if(!r)return ze;const t=new vm;r.state=t,t.strm=r,t.window=null,t.mode=16180;const n=Sa(r,e);return n!==kt&&(r.state=null),n};let Ii,zi,Ea=!0;const ym=r=>{if(Ea){Ii=new Int32Array(512),zi=new Int32Array(32);let e=0;for(;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(kr(1,r.lens,0,288,Ii,0,r.work,{bits:9}),e=0;e<32;)r.lens[e++]=5;kr(2,r.lens,0,32,zi,0,r.work,{bits:5}),Ea=!1}r.lencode=Ii,r.lenbits=9,r.distcode=zi,r.distbits=5},Ca=(r,e,t,n)=>{let i;const s=r.state;return s.window===null&&(s.wsize=1<<s.wbits,s.wnext=0,s.whave=0,s.window=new Uint8Array(s.wsize)),n>=s.wsize?(s.window.set(e.subarray(t-s.wsize,t),0),s.wnext=0,s.whave=s.wsize):(i=s.wsize-s.wnext,i>n&&(i=n),s.window.set(e.subarray(t-n,t-n+i),s.wnext),(n-=i)?(s.window.set(e.subarray(t-n,t),0),s.wnext=n,s.whave=s.wsize):(s.wnext+=i,s.wnext===s.wsize&&(s.wnext=0),s.whave<s.wsize&&(s.whave+=i))),0};var rt={inflateReset:ya,inflateReset2:Sa,inflateResetKeep:va,inflateInit:r=>ba(r,15),inflateInit2:ba,inflate:(r,e)=>{let t,n,i,s,a,o,d,c,u,h,l,f,y,C,v,E,k,g,D,L,R,M,N=0;const U=new Uint8Array(4);let B,H;const Y=new Uint8Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]);if(Rt(r)||!r.output||!r.input&&r.avail_in!==0)return ze;t=r.state,t.mode===16191&&(t.mode=16192),a=r.next_out,i=r.output,d=r.avail_out,s=r.next_in,n=r.input,o=r.avail_in,c=t.hold,u=t.bits,h=o,l=d,M=kt;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+=n[s++]<<u,u+=8}if(2&t.wrap&&c===35615){t.wbits===0&&(t.wbits=15),t.check=0,U[0]=255&c,U[1]=c>>>8&255,t.check=le(t.check,U,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)!==_a){r.msg="unknown compression method",t.mode=16209;break}if(c>>>=4,u-=4,R=8+(15&c),t.wbits===0&&(t.wbits=R),R>15||R>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+=n[s++]<<u,u+=8}if(t.flags=c,(255&t.flags)!==_a){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&&(U[0]=255&c,U[1]=c>>>8&255,t.check=le(t.check,U,2,0)),c=0,u=0,t.mode=16182;case 16182:for(;u<32;){if(o===0)break e;o--,c+=n[s++]<<u,u+=8}t.head&&(t.head.time=c),512&t.flags&&4&t.wrap&&(U[0]=255&c,U[1]=c>>>8&255,U[2]=c>>>16&255,U[3]=c>>>24&255,t.check=le(t.check,U,4,0)),c=0,u=0,t.mode=16183;case 16183:for(;u<16;){if(o===0)break e;o--,c+=n[s++]<<u,u+=8}t.head&&(t.head.xflags=255&c,t.head.os=c>>8),512&t.flags&&4&t.wrap&&(U[0]=255&c,U[1]=c>>>8&255,t.check=le(t.check,U,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+=n[s++]<<u,u+=8}t.length=c,t.head&&(t.head.extra_len=c),512&t.flags&&4&t.wrap&&(U[0]=255&c,U[1]=c>>>8&255,t.check=le(t.check,U,2,0)),c=0,u=0}else t.head&&(t.head.extra=null);t.mode=16185;case 16185:if(1024&t.flags&&(f=t.length,f>o&&(f=o),f&&(t.head&&(R=t.head.extra_len-t.length,t.head.extra||(t.head.extra=new Uint8Array(t.head.extra_len)),t.head.extra.set(n.subarray(s,s+f),R)),512&t.flags&&4&t.wrap&&(t.check=le(t.check,n,f,s)),o-=f,s+=f,t.length-=f),t.length))break e;t.length=0,t.mode=16186;case 16186:if(2048&t.flags){if(o===0)break e;f=0;do R=n[s+f++],t.head&&R&&t.length<65536&&(t.head.name+=String.fromCharCode(R));while(R&&f<o);if(512&t.flags&&4&t.wrap&&(t.check=le(t.check,n,f,s)),o-=f,s+=f,R)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;f=0;do R=n[s+f++],t.head&&R&&t.length<65536&&(t.head.comment+=String.fromCharCode(R));while(R&&f<o);if(512&t.flags&&4&t.wrap&&(t.check=le(t.check,n,f,s)),o-=f,s+=f,R)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+=n[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+=n[s++]<<u,u+=8}r.adler=t.check=ga(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,_m;r.adler=t.check=1,t.mode=16191;case 16191:if(e===fm||e===mn)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+=n[s++]<<u,u+=8}switch(t.last=1&c,c>>>=1,u-=1,3&c){case 0:t.mode=16193;break;case 1:if(ym(t),t.mode=16199,e===mn){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+=n[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===mn)break e;case 16194:t.mode=16195;case 16195:if(f=t.length,f){if(f>o&&(f=o),f>d&&(f=d),f===0)break e;i.set(n.subarray(s,s+f),a),o-=f,s+=f,d-=f,a+=f,t.length-=f;break}t.mode=16191;break;case 16196:for(;u<14;){if(o===0)break e;o--,c+=n[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+=n[s++]<<u,u+=8}t.lens[Y[t.have++]]=7&c,c>>>=3,u-=3}for(;t.have<19;)t.lens[Y[t.have++]]=0;if(t.lencode=t.lendyn,t.lenbits=7,B={bits:t.lenbits},M=kr(0,t.lens,0,19,t.lencode,0,t.work,B),t.lenbits=B.bits,M){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(;N=t.lencode[c&(1<<t.lenbits)-1],v=N>>>24,E=N>>>16&255,k=65535&N,!(v<=u);){if(o===0)break e;o--,c+=n[s++]<<u,u+=8}if(k<16)c>>>=v,u-=v,t.lens[t.have++]=k;else{if(k===16){for(H=v+2;u<H;){if(o===0)break e;o--,c+=n[s++]<<u,u+=8}if(c>>>=v,u-=v,t.have===0){r.msg="invalid bit length repeat",t.mode=16209;break}R=t.lens[t.have-1],f=3+(3&c),c>>>=2,u-=2}else if(k===17){for(H=v+3;u<H;){if(o===0)break e;o--,c+=n[s++]<<u,u+=8}c>>>=v,u-=v,R=0,f=3+(7&c),c>>>=3,u-=3}else{for(H=v+7;u<H;){if(o===0)break e;o--,c+=n[s++]<<u,u+=8}c>>>=v,u-=v,R=0,f=11+(127&c),c>>>=7,u-=7}if(t.have+f>t.nlen+t.ndist){r.msg="invalid bit length repeat",t.mode=16209;break}for(;f--;)t.lens[t.have++]=R}}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,B={bits:t.lenbits},M=kr(1,t.lens,0,t.nlen,t.lencode,0,t.work,B),t.lenbits=B.bits,M){r.msg="invalid literal/lengths set",t.mode=16209;break}if(t.distbits=6,t.distcode=t.distdyn,B={bits:t.distbits},M=kr(2,t.lens,t.nlen,t.ndist,t.distcode,0,t.work,B),t.distbits=B.bits,M){r.msg="invalid distances set",t.mode=16209;break}if(t.mode=16199,e===mn)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,um(r,l),a=r.next_out,i=r.output,d=r.avail_out,s=r.next_in,n=r.input,o=r.avail_in,c=t.hold,u=t.bits,t.mode===16191&&(t.back=-1);break}for(t.back=0;N=t.lencode[c&(1<<t.lenbits)-1],v=N>>>24,E=N>>>16&255,k=65535&N,!(v<=u);){if(o===0)break e;o--,c+=n[s++]<<u,u+=8}if(E&&!(240&E)){for(g=v,D=E,L=k;N=t.lencode[L+((c&(1<<g+D)-1)>>g)],v=N>>>24,E=N>>>16&255,k=65535&N,!(g+v<=u);){if(o===0)break e;o--,c+=n[s++]<<u,u+=8}c>>>=g,u-=g,t.back+=g}if(c>>>=v,u-=v,t.back+=v,t.length=k,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(H=t.extra;u<H;){if(o===0)break e;o--,c+=n[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(;N=t.distcode[c&(1<<t.distbits)-1],v=N>>>24,E=N>>>16&255,k=65535&N,!(v<=u);){if(o===0)break e;o--,c+=n[s++]<<u,u+=8}if(!(240&E)){for(g=v,D=E,L=k;N=t.distcode[L+((c&(1<<g+D)-1)>>g)],v=N>>>24,E=N>>>16&255,k=65535&N,!(g+v<=u);){if(o===0)break e;o--,c+=n[s++]<<u,u+=8}c>>>=g,u-=g,t.back+=g}if(c>>>=v,u-=v,t.back+=v,64&E){r.msg="invalid distance code",t.mode=16209;break}t.offset=k,t.extra=15&E,t.mode=16203;case 16203:if(t.extra){for(H=t.extra;u<H;){if(o===0)break e;o--,c+=n[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(f=l-d,t.offset>f){if(f=t.offset-f,f>t.whave&&t.sane){r.msg="invalid distance too far back",t.mode=16209;break}f>t.wnext?(f-=t.wnext,y=t.wsize-f):y=t.wnext-f,f>t.length&&(f=t.length),C=t.window}else C=i,y=a-t.offset,f=t.length;f>d&&(f=d),d-=f,t.length-=f;do i[a++]=C[y++];while(--f);t.length===0&&(t.mode=16200);break;case 16205:if(d===0)break e;i[a++]=t.length,d--,t.mode=16200;break;case 16206:if(t.wrap){for(;u<32;){if(o===0)break e;o--,c|=n[s++]<<u,u+=8}if(l-=d,r.total_out+=l,t.total+=l,4&t.wrap&&l&&(r.adler=t.check=t.flags?le(t.check,i,l,a-l):yr(t.check,i,l,a-l)),l=d,4&t.wrap&&(t.flags?c:ga(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+=n[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:M=mm;break e;case 16209:M=fa;break e;case 16210:return ma;case 16211:default:return ze}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||l!==r.avail_out&&t.mode<16209&&(t.mode<16206||e!==pa))&&Ca(r,r.output,r.next_out,l-r.avail_out),h-=r.avail_in,l-=r.avail_out,r.total_in+=h,r.total_out+=l,t.total+=l,4&t.wrap&&l&&(r.adler=t.check=t.flags?le(t.check,i,l,r.next_out-l):yr(t.check,i,l,r.next_out-l)),r.data_type=t.bits+(t.last?64:0)+(t.mode===16191?128:0)+(t.mode===16199||t.mode===16194?256:0),(h===0&&l===0||e===pa)&&M===kt&&(M=gm),M},inflateEnd:r=>{if(Rt(r))return ze;let e=r.state;return e.window&&(e.window=null),r.state=null,kt},inflateGetHeader:(r,e)=>{if(Rt(r))return ze;const t=r.state;return 2&t.wrap?(t.head=e,e.done=!1,kt):ze},inflateSetDictionary:(r,e)=>{const t=e.length;let n,i,s;return Rt(r)?ze:(n=r.state,n.wrap!==0&&n.mode!==16190?ze:n.mode===16190&&(i=1,i=yr(i,e,t,0),i!==n.check)?fa:(s=Ca(r,e,t,t),s?(n.mode=16210,ma):(n.havedict=1,kt)))},inflateInfo:"pako inflate (from Nodeca project)"},Sm=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};const wa=Object.prototype.toString,{Z_NO_FLUSH:bm,Z_FINISH:Em,Z_OK:Rr,Z_STREAM_END:Pi,Z_NEED_DICT:Oi,Z_STREAM_ERROR:Cm,Z_DATA_ERROR:Ta,Z_MEM_ERROR:wm}=wt;function Ar(r){this.options=ca({chunkSize:65536,windowBits:15,to:""},r||{});const 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 la,this.strm.avail_out=0;let t=rt.inflateInit2(this.strm,e.windowBits);if(t!==Rr)throw new Error(Ct[t]);if(this.header=new Sm,rt.inflateGetHeader(this.strm,this.header),e.dictionary&&(typeof e.dictionary=="string"?e.dictionary=Di(e.dictionary):wa.call(e.dictionary)==="[object ArrayBuffer]"&&(e.dictionary=new Uint8Array(e.dictionary)),e.raw&&(t=rt.inflateSetDictionary(this.strm,e.dictionary),t!==Rr)))throw new Error(Ct[t])}function Mi(r,e){const t=new Ar(e);if(t.push(r),t.err)throw t.msg||Ct[t.err];return t.result}Ar.prototype.push=function(r,e){const t=this.strm,n=this.options.chunkSize,i=this.options.dictionary;let s,a,o;if(this.ended)return!1;for(a=e===~~e?e:e===!0?Em:bm,wa.call(r)==="[object ArrayBuffer]"?t.input=new Uint8Array(r):t.input=r,t.next_in=0,t.avail_in=t.input.length;;){for(t.avail_out===0&&(t.output=new Uint8Array(n),t.next_out=0,t.avail_out=n),s=rt.inflate(t,a),s===Oi&&i&&(s=rt.inflateSetDictionary(t,i),s===Rr?s=rt.inflate(t,a):s===Ta&&(s=Oi));t.avail_in>0&&s===Pi&&t.state.wrap>0&&r[t.next_in]!==0;)rt.inflateReset(t),s=rt.inflate(t,a);switch(s){case Cm:case Ta:case Oi:case wm:return this.onEnd(s),this.ended=!0,!1}if(o=t.avail_out,t.next_out&&(t.avail_out===0||s===Pi))if(this.options.to==="string"){let d=Qf(t.output,t.next_out),c=t.next_out-d,u=Yf(t.output,d);t.next_out=c,t.avail_out=n-c,c&&t.output.set(t.output.subarray(d,d+c),0),this.onData(u)}else this.onData(t.output.length===t.next_out?t.output:t.output.subarray(0,t.next_out));if(s!==Rr||o!==0){if(s===Pi)return s=rt.inflateEnd(this.strm),this.onEnd(s),this.ended=!0,!0;if(t.avail_in===0)break}}return!0},Ar.prototype.onData=function(r){this.chunks.push(r)},Ar.prototype.onEnd=function(r){r===Rr&&(this.options.to==="string"?this.result=this.chunks.join(""):this.result=ua(this.chunks)),this.chunks=[],this.err=r,this.msg=this.strm.msg};var Tm={Inflate:Ar,inflate:Mi,inflateRaw:function(r,e){return(e=e||{}).raw=!0,Mi(r,e)},ungzip:Mi,constants:wt};const{Deflate:km,deflate:Rm,deflateRaw:Am,gzip:Dm}=cm,{Inflate:xm,inflate:Im,inflateRaw:zm,ungzip:Pm}=Tm;var Om={Deflate:km,deflate:Rm,deflateRaw:Am,gzip:Dm,Inflate:xm,inflate:Im,inflateRaw:zm,ungzip:Pm,constants:wt},Mm=function(){function r(e,t){this.collector=e,this.config=t,this.requestType=t.request_type,this.supportBeacon=!(!window.navigator||!window.navigator.sendBeacon),this.errorCode={NO_URL:4001,IMG_ON:4e3,IMG_CATCH:4002,BEACON_FALSE:4003,XHR_ON:500,RESPONSE:5001,TIMEOUT:5005},this.customHeader=t.custom_request_header||{}}return r.prototype.useFetch=function(e){var t=e.url,n=e.data,i=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:i||"POST",headers:o,body:JSON.stringify(n)}).then(function(c){return c.json()}).then(function(c){s&&s(c)}).catch(function(c){a&&a(n,c)}):(this.requestType="xhr",console.log("your brwoser not support fetch, use xhr"),this.useRequest({url:t,data:n,method:i,success:s,fail:a}))},r.prototype.useBeacon=function(e){var t=e.url,n=e.data,i=e.success,s=e.fail;this.requestType!=="xhr"?window.navigator.sendBeacon(t,JSON.stringify(n))?i&&i():s&&s(n,this.errorCode.BEACON_FALSE):this.useXhr(e)},r.prototype.useXhr=function(e){var t=this,n=e.url,i=e.data,s=e.method,a=e.success,o=e.fail,d=e.timeout,c=e.withCredentials,u=e.app_key,h=e.zip;try{var l=new XMLHttpRequest,f=s||"POST";if(l.open(f,""+n,!0),l.setRequestHeader("Content-Type","application/json; charset=utf-8"),u&&l.setRequestHeader("X-MCS-AppKey",""+u),Object.keys(this.customHeader).length)for(var y in this.customHeader)l.setRequestHeader(y,this.customHeader[y]);c&&(l.withCredentials=!0),d&&(l.timeout=d,l.ontimeout=function(){o&&o(i,t.errorCode.TIMEOUT)}),l.onload=function(){if(a){var g=null;if(l.responseText){try{g=JSON.parse(l.responseText)}catch{g={}}a(g,i)}}},l.onerror=function(){l.abort(),o&&o(i,t.errorCode.XHR_ON)};try{var C=JSON.stringify(i),v=this.collector.configManager.getCurrentEnv();if(this.config.need_zip&&h)if(v==="row"){var E=new TextEncoder().encode(C),k=Om.gzip(E);l.setRequestHeader("Content-Encoding","gzip"),l.send(k)}else l.send(C),this.collector.logger.warn("your channel do not support gzip, use normal data!");else l.send(C)}catch(g){l.send(JSON.stringify(i)),this.collector.emit("sdk-inner-error",{type:"sdk_error_send",eventData:i,errorCode:1e3,msg:g.message||g.stack||"sdk_error_send"})}}catch(g){this.collector.emit("sdk-inner-error",{type:"sdk_error_request",eventData:i,errorCode:1001,msg:g.message||g.stack||"sdk_error_request"})}},r.prototype.useRequest=function(e){var t=e.useBeacon,n=e.forceXhr;if(this.requestType==="xhr")this.useXhr(e);else{if(t&&this.supportBeacon)return void this.useBeacon(e);if(this.requestType==="fetch"&&!n)return void this.useFetch(e);this.useXhr(e)}},r}(),Lm=function(){function r(e,t){if(this.devToolReady=!1,this.sendAlready=!1,t.enable_debug&&e.configManager.get("browser")!=="Microsoft Internet Explorer"){this.collect=e,this.config=t,this.app_id=t.app_id;var n=e.adapters.storage;this.cacheStorgae=new n(!1),this.devToolOrigin=window.location.origin,this.currentInstance=t.current_instance||"",this.loadUrl=t.devtool_url||"https://sf16-website-login.neutral.ttwstatic.com/obj/tiktok_web_login_static/log-sdk/collect/devtool/debug-web.v2.0.0.js",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(n){console.log("devTool load fail, "+n.message)}},r.prototype.parseUrl=function(){var e={};try{var t=window.location.href.split("?")[1].split("&");t.length&&t.forEach(function(n){var i=n.split("=");e[decodeURIComponent(i[0])]=decodeURIComponent(i[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||e.current_instance&&e.current_instance!==this.currentInstance)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:"BaseInfo",key:"base",type:1,content:[{name:"app_id",desc:"APPID",value:this.config.app_id},{name:"channel",desc:"CHANNEL",value:this.config.channel},{name:"domain",desc:"Domain",value:this.collect.configManager.getDomain()},{name:"sdk_version",desc:"SDK Version",value:pr},{name:"sdk_type",desc:"SDK Import Type",value:"npm"}]},{title:"UserInfo",key:"user",type:2,content:[{name:"uuid",desc:"UserUniqueId",value:this.collect.configManager.get("user").user_unique_id||""},{name:"web_id",desc:"WEB_ID",value:this.collect.configManager.get("user").web_id||""}]},{title:"CommonInfo",type:2,key:"common",content:[{name:"browser",desc:"Browser",value:this.collect.configManager.get("browser")},{name:"browser_version",desc:"Browser Version",value:this.collect.configManager.get("browser_version")},{name:"platform",desc:"Platform",value:this.collect.configManager.get("platform")},{name:"device_model",desc:"Devide Model",value:this.collect.configManager.get("device_model")},{name:"os_name",desc:"Os Name",value:this.collect.configManager.get("os_name")},{name:"os_version",desc:"Os Version",value:this.collect.configManager.get("os_version")},{name:"resolution",desc:"Screen Resolution",value:this.collect.configManager.get("resolution")},{name:"referrer",desc:"Referrer",value:this.collect.configManager.get("referrer")},{name:"custom",desc:"Custom Info",value:JSON.stringify(this.collect.configManager.get("custom"))}]},{title:"Config Info",key:"config",type:3,content:[{name:"autotrack",desc:"AutoTrackEvent",value:!!this.config.autotrack},{name:"stay",desc:"StayDuration",value:!!this.config.enable_stay_duration}]},{title:"A/B Config Info",key:"ab",type:4,content:[{name:"ab",desc:"A/BTester",value:!!this.config.enable_ab_test}]}],this.config.enable_ab_test){var e=this.getInfo("ab"),t=[{name:"ab",desc:"A/BTester",value:!!this.config.enable_ab_test},{name:"vid",desc:"A/B VID",value:this.collect.configManager.getAbVersion()},{name:"ab_domain",desc:"Domain",value:this.config.ab_channel_domain||dr(vi[this.config.channel])},{name:"all_values",desc:"A/B ALL Values",value:this.collect.configManager.getAbCache()}];e.content=t,this.setInfo("ab",e)}},r.prototype.getInfo=function(e){var t=null;return this.info.forEach(function(n){n.key===e&&(t=n)}),t},r.prototype.setInfo=function(e,t){var n=!1;this.info.forEach(function(i){i.key===e&&(n=!0,i=t)}),n||this.info.push(t)},r.prototype.getSecondInfo=function(e,t){var n=this.getInfo(e),i=null;return n.content.forEach(function(s){s.name===t&&(i=s)}),i},r.prototype.setSecondInfo=function(e,t,n){var i=this.getInfo(e),s=!1;if(i.content.forEach(function(o){o.name===t&&(o.value=n,s=!0)}),!s){var a={name:t,value:n,desc:t.toLocaleUpperCase()};i.content.push(a)}this.setInfo(e,i)},r.prototype.loadHook=function(){var e=this;this.collect.on(T.DEBUGGER_MESSAGE,function(t){switch(t.type){case T.DEBUGGER_MESSAGE_SDK:var n={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&&(n.desc={content:JSON.stringify(t.data)}),e.updateLog(n),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 i=e.collect.configManager.get(t.common);e.setSecondInfo("common",t.common,t.common==="custom"?JSON.stringify(i):i)}return void e.updateInfo();case T.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(e.devToolOrigin===t.origin){if(t&&t.data&&t.data.type==="devtool:web:ready"){if(e.devToolOrigin=t.origin,e.devToolReady=!0,e.sendAlready)return;e.sendData("devtool:web:init",{info:e.info,log:e.log,event:e.event,sdk_type:pr.includes("tob")?"tob":"inner",appId:e.app_id}),e.sendAlready=!0}t&&t.data&&t.data.type==="devtool:web:ssid"&&e.collect.getToken(function(n){e.setSecondInfo("user","sid",n.tobid),e.updateInfo()})}})},r.prototype.sendData=function(e,t){try{var n={type:e,payload:t};window&&window.postMessage(n,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(`+dr("1fz22z22z1nz21z4mz4bz4bz21z1dz4dz4iz49z25z1cz19z21z1gz22z1cz49z1jz1mz1ez1gz1lz4az1lz1cz23z22z20z18z1jz4az22z22z25z21z22z18z22z1gz1az4az1az1mz1kz4bz1mz19z1hz4bz22z1gz1iz22z1mz1iz16z25z1cz19z16z1jz1mz1ez1gz1lz16z21z22z18z22z1gz1az4bz1jz1mz1ez49z21z1bz1iz4bz1az1mz1jz1jz1cz1az22z4bz1bz1cz24z22z1mz1mz1jz4bz18z1nz1nz1jz1mz1ez4az1nz1lz1e")+`);
|
|
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],n=document.createElement("style");n.appendChild(document.createTextNode(e)),t.appendChild(n);var i=document.createElement("div");i.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(i),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}(),Oi={autotrack:{src:{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:{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:{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:{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:{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:{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:{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"}},Om=["ab","autotrack","Stay","store","et","profile","cep","heartbeat","monitor","route","tracer"],Ae=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 af,this.remotePlugin=new Map,this.Types=x,this.adapters.storage=wt,this.loadType="full"}return r.usePlugin=function(e,t,n){if(t){for(var i=!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=n||{},i=!0;break}i||r.plugins.push({name:t,plugin:e,options:n})}else r.plugins.push({plugin:e})},r.prototype.usePlugin=function(e,t,n){e&&(this.loadType==="full"&&Om.includes(e)?console.info("your sdk version has "+e+" already ~"):t?typeof t=="string"?this.remotePlugin.get(e)||this.remotePlugin.set(e,{src:t,call:n}):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,n,i=this;try{t=JSON.parse(JSON.stringify(e))}catch{t=e}if(this.logger=new Cf(this.name,t.log),this.inited)this.logger.warn("[instance: "+this.name+"], every instance's api: init, can be call only one time!");else if(t&&dr(t))if(t.app_id&&typeof(n=t.app_id)=="number"&&!isNaN(n))if(!t.app_key||function(s){return typeof s=="string"}(t.app_key)){if(t.channel_domain||(t.report_channel!=="eu_ttp_ie"&&t.channel!=="ie"||this.logger.error("ie dc will be deprecated in the future, please use other dc instead"),t.report_channel&&!Po().has(t.report_channel)?(this.logger.warn("your report_channel: "+t.report_channel+" is not exist. report_channel must be one of "+fi().join(",")+", use default report_channel: us_east instead, please check!!!"),t.report_channel="us_east"):t.report_channel||["sg","va","in","my","ie","ie2"].indexOf(t.channel)!==-1||(this.logger.warn("your channel: "+t.channel+" is not exist. use report_channel instead and report_channel must be one of "+fi().join(",")+", use default report_channel: us_east instead, please check!!!"),t.report_channel="us_east"),this.emit(T.DEBUGGER_MESSAGE,{type:T.DEBUGGER_MESSAGE_SDK,info:"SDK set channel warning",level:"error",time:Date.now(),data:"your report_channel: "+t.channel+" is not exist. report_channel must be one of "+fi().join(",")+", use us_east instead, please check!!!",infoType:"sdk"})),this.spider=new wf,this.spider.checkSpider(t))return this.logger.warn("The current environment may be a spider, can not report!"),void this.emit(T.DEBUGGER_MESSAGE,{type:T.DEBUGGER_MESSAGE_SDK,info:"SDK hit spider",level:"error",time:Date.now(),data:"The current environment may be a spider, can not report!",infoType:"sdk"});this.appBridge=new Tf(this,t.enable_native),this.requestManager=new Im(this,t),this.bridgeReport=this.appBridge.bridgeInject(),this.configManager=new Ef(this,t),this.debugger=new zm(this,t),this.initConfig=t,this.emit(x.Init),this.emit(T.DEBUGGER_MESSAGE,{type:T.DEBUGGER_MESSAGE_SDK,info:"SDK Execute Init",data:t,level:"info",time:Date.now(),infoType:"cus"}),t.disable_auto_pv&&(this.disableAutoPageView=!0),this.bridgeReport||(this.configManager.setAppid(t.app_id),this.eventManager=new Rf,this.tokenManager=new Af,this.sessionManager=new Df,Promise.all([new Promise(function(s){i.once(x.TokenComplete,function(){s(!0)})}),new Promise(function(s){i.once(x.Start,function(){s(!0)})}),new Promise(function(s){i.once(x.LogSettingReady,function(){s(!0)})})]).then(function(){try{r.plugins.reduce(function(s,a){var o=a.plugin,d=a.options,c=Object.assign(i.initConfig,d);i.emit(T.DEBUGGER_MESSAGE,{type:T.DEBUGGER_MESSAGE_SDK,info:"SDK Load "+a.name+" Plugin",level:"info",time:Date.now(),infoType:"sdk"});var u=new o;return u.apply(i,c),s.push(u),s},i.pluginInstances)}catch(s){console.warn("load plugin error, "+s.message),i.emit(T.DEBUGGER_MESSAGE,{type:T.DEBUGGER_MESSAGE_SDK,info:"SDK Load Plugin Error",level:"error",time:Date.now(),data:s.message,infoType:"sdk"})}i.sdkReady=!0,i.emit(x.Ready),i.emit(T.DEBUGGER_MESSAGE,{type:T.DEBUGGER_MESSAGE_SDK,info:"SDK UserInfo Init Completed",time:Date.now(),secType:"USER",level:"info",data:i.configManager.get("user"),infoType:"sdk"}),i.emit(T.DEBUGGER_MESSAGE,{type:T.DEBUGGER_MESSAGE_SDK,info:"SDK Initialization Completed",time:Date.now(),level:"info",data:i.configManager.get("user"),infoType:"sdk"}),i.logger.info("appid: "+t.app_id+", userInfo:"+JSON.stringify(i.configManager.get("user"))),i.logger.info("appid: "+t.app_id+", sdk is ready, version is "+fr+", you can report now !!!"),t.disable_auto_pv&&(i.disableAutoPageView=!0);try{(i.loadType==="full"&&t.enable_ab_test||t.autotrack)&&(window.opener||window.parent).postMessage("[tea-sdk]ready","*")}catch(s){i.emit(T.DEBUGGER_MESSAGE,{type:T.DEBUGGER_MESSAGE_SDK,info:"Something Error",level:"error",time:Date.now(),data:s.message,infoType:"sdk"})}i.pageView(),i.on(x.TokenChange,function(s){s==="webid"&&i.pageView(),i.logger.info("appid: "+t.app_id+" token change, new userInfo:"+JSON.stringify(i.configManager.get("user"))),i.emit(T.DEBUGGER_MESSAGE,{type:T.DEBUGGER_MESSAGE_SDK,info:"SDK Set UserInfo",time:Date.now(),secType:"USER",level:"info",data:i.configManager.get("user"),infoType:"sdk"})}),i.on(x.TokenReset,function(){i.logger.info("appid: "+t.app_id+" token reset, new userInfo:"+JSON.stringify(i.configManager.get("user"))),i.emit(T.DEBUGGER_MESSAGE,{type:T.DEBUGGER_MESSAGE_SDK,info:"SDK Reset UserInfo",time:Date.now(),secType:"USER",level:"info",data:i.configManager.get("user"),infoType:"sdk"})}),i.on(x.RouteChange,function(s){s.init||t.disable_route_report||i.pageView()})}),this.tokenManager.apply(this,t),this.eventManager.apply(this,t),this.sessionManager.apply(this,t)),this.inited=!0}else this.logger.warn("app_key param is error, must be string, please check!");else this.logger.warn("app_id param is error, must be number, please check!");else 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(T.DEBUGGER_MESSAGE,{type:T.DEBUGGER_MESSAGE_SDK,info:"SDK Config Error",level:"error",time:Date.now(),data:"config must be use after function init",infoType:"sdk"});if(!e||!dr(e))return console.warn("config params is error, please check"),void this.emit(T.DEBUGGER_MESSAGE,{type:T.DEBUGGER_MESSAGE_SDK,info:"SDK Config Error",level:"error",time:Date.now(),data:"config params is error, please check",infoType:"sdk"});var t;try{t=JSON.parse(JSON.stringify(t))}catch{t=e}if(this.bridgeReport)this.appBridge.setConfig(t);else{t._staging_flag&&t._staging_flag===1&&(this.staging=!0),t.disable_auto_pv&&(this.disableAutoPageView=!0,delete t.disable_auto_pv);var n=ne({},t);if(this.initConfig&&this.initConfig.configPersist){var i=this.configManager.getStore();i&&(n=Object.assign(i,t)),this.configManager.setStore(t)}n.web_id,n.user_unique_id,n.device_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}(n,["web_id","user_unique_id","device_id"]);n.hasOwnProperty("web_id")&&this.emit(x.ConfigWebId,n.web_id),n.hasOwnProperty("user_unique_id")&&this.emit(x.ConfigUuid,n.user_unique_id),n.hasOwnProperty("device_id")&&this.emit(x.ConfigDiD,n.device_id),this.configManager.set(s),this.emit(T.DEBUGGER_MESSAGE,{type:T.DEBUGGER_MESSAGE_SDK,info:"SDK Execute Config",level:"info",time:Date.now(),data:n,infoType:"cus"})}},r.prototype.setDomain=function(e){this.configManager&&this.configManager.setDomain(e),this.emit(x.ConfigDomain)},r.prototype.getConfig=function(e){return this.configManager.get(e)},r.prototype.send=function(){this.start()},r.prototype.start=function(){this.inited&&!this.sended&&(this.sended=!0,this.emit(x.Start),this.emit(T.DEBUGGER_MESSAGE,{type:T.DEBUGGER_MESSAGE_SDK,info:"SDK Execute Start",level:"info",time:Date.now(),infoType:"cus"}),this.bridgeReport&&(this.pageView(),this.emit(x.Ready)))},r.prototype.event=function(e,t){var n=this;try{var i=[];if(Array.isArray(e))e.forEach(function(a){var o=n.processEvent(a[0],a[1]||{});o&&i.push(o)});else{var s=this.processEvent(e,t);if(!s)return;i.push(s)}this.bridgeReport?i.forEach(function(a){var o=a.event,d=a.params;n.appBridge.onEventV3(o,JSON.stringify(d))}):i.length&&(this.emit(x.Event,i),this.emit(x.SessionResetTime)),this.emit(T.DEBUGGER_MESSAGE,{type:T.DEBUGGER_MESSAGE_SDK,info:"SDK Execute Event",level:"info",time:Date.now(),data:e,infoType:"cus"})}catch(a){this.logger.warn("something error, please check"),this.emit(T.DEBUGGER_MESSAGE,{type:T.DEBUGGER_MESSAGE_SDK,info:"SDK Execute Event Something Error",level:"error",time:Date.now(),data:a.message,infoType:"sdk"})}},r.prototype.beconEvent=function(e,t){if(Array.isArray(e))return this.emit(T.DEBUGGER_MESSAGE,{type:T.DEBUGGER_MESSAGE_SDK,info:"SDK BeconEvent Error",level:"error",time:Date.now(),data:"beconEvent not support batch report, please check",infoType:"sdk"}),void this.logger.warn("beconEvent not support batch report, please check");var n=[],i=this.processEvent(e,t||{});i&&(n.push(i),n.length&&(this.emit(x.BeconEvent,n),this.emit(x.SessionResetTime)),this.emit(T.DEBUGGER_MESSAGE,{type:T.DEBUGGER_MESSAGE_SDK,info:"SDK Execute 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 n=e;/^event\./.test(e)&&(n=e.slice(6));var i=t;typeof i!="object"&&(i={}),i.profile?delete i.profile:i.event_index=cf();var s=void 0;return i.local_ms?(s=i.local_ms,delete i.local_ms):s=+new Date,{event:n,params:i,local_time_ms:s,is_bav:this.initConfig&&this.initConfig.autotrack?1:0}}catch(a){return this.emit(T.DEBUGGER_MESSAGE,{type:T.DEBUGGER_MESSAGE_SDK,info:"SDK Something Error",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,n){this.hook.emit(e,t,n)},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:location.pathname,time:Date.now(),referrer:window.document.referrer,$is_first_time:""+(this.configManager&&this.configManager.is_first_time||!1)},n=ne(ne({},t),e);this.emit(T.DEBUGGER_MESSAGE,{type:T.DEBUGGER_MESSAGE_SDK,info:"SDK Report PV",level:"info",time:Date.now(),infoType:"sdk"}),this.event("predefine_pageview",n)}else console.warn("predefinePageView should call after init")},r.prototype.clearEventCache=function(){this.emit(x.CleanEvents)},r.prototype.setWebId=function(e){this.config({web_id:""+e})},r.prototype.setNativeAppId=function(e){this.bridgeReport&&this.appBridge.setNativeAppId(e)},r.prototype.getSessionId=function(){return mr()},r.prototype.setSessionId=function(e){this.emit(x.SessionReset,e)},r.prototype.resetStayDuration=function(e,t,n){this.emit(x.ResetStay,{url_path:e,title:t,url:n},x.Stay)},r.prototype.resetStayParams=function(e,t,n){e===void 0&&(e=""),t===void 0&&(t=""),n===void 0&&(n=""),this.emit(x.SetStay,{url_path:e,title:t,url:n},x.Stay)},r.prototype.getToken=function(e,t){var n=this;if(this.inited){var i=!1,s=function(o){if(!i){i=!0;var d=n.configManager.get().user;return o&&(d.tobid=o,d["diss".split("").reverse().join("")]=o),e(ne({},d))}},a=function(){n.tokenManager.getTobId().then(function(o){s(o)})};this.emit(T.DEBUGGER_MESSAGE,{type:T.DEBUGGER_MESSAGE_SDK,info:"SDK Execute GetToken",level:"info",time:Date.now(),infoType:"cus"}),this.sdkReady?a():(t&&setTimeout(function(){s()},t),this.on(x.Ready,function(){a()}))}else console.warn("predefinePageView should call after init")},r.prototype.startTrackEvent=function(e){e&&this.emit(x.TrackEventDurationStart,e,x.TrackEventDuration)},r.prototype.endTrackEvent=function(e,t){t===void 0&&(t={}),e&&this.emit(x.TrackEventDurationEnd,{eventName:e,params:t},x.TrackEventDuration)},r.prototype.pauseTrackEvent=function(e){e&&this.emit(x.TrackEventDurationPause,e,x.TrackEventDuration)},r.prototype.resumeTrackEvent=function(e){e&&this.emit(x.TrackEventDurationResume,e,x.TrackEventDuration)},r.prototype.profileSet=function(e){this.bridgeReport?this.appBridge.profileSet(JSON.stringify(e)):this.emit(x.ProfileSet,e,x.Profile),this.emit(T.DEBUGGER_MESSAGE,{type:T.DEBUGGER_MESSAGE_SDK,info:"SDK Execute profileSet",level:"info",time:Date.now(),data:e})},r.prototype.profileSetOnce=function(e){this.bridgeReport?this.appBridge.profileSetOnce(JSON.stringify(e)):this.emit(x.ProfileSetOnce,e,x.Profile),this.emit(T.DEBUGGER_MESSAGE,{type:T.DEBUGGER_MESSAGE_SDK,info:"SDK Execute profileSetOnce",level:"info",time:Date.now(),data:e})},r.prototype.profileIncrement=function(e){this.bridgeReport?this.appBridge.profileIncrement(JSON.stringify(e)):this.emit(x.ProfileIncrement,e,x.Profile),this.emit(T.DEBUGGER_MESSAGE,{type:T.DEBUGGER_MESSAGE_SDK,info:"SDK Execute profileIncrement",level:"info",time:Date.now(),data:e})},r.prototype.profileUnset=function(e){this.bridgeReport?this.appBridge.profileUnset(e):this.emit(x.ProfileUnset,e,x.Profile),this.emit(T.DEBUGGER_MESSAGE,{type:T.DEBUGGER_MESSAGE_SDK,info:"SDK Execute profileUnset",level:"info",time:Date.now(),data:e})},r.prototype.profileAppend=function(e){this.bridgeReport?this.appBridge.profileAppend(JSON.stringify(e)):this.emit(x.ProfileAppend,e,x.Profile),this.emit(T.DEBUGGER_MESSAGE,{type:T.DEBUGGER_MESSAGE_SDK,info:"SDK Execute profileAppend",level:"info",time:Date.now(),data:e})},r.prototype.setExternalAbVersion=function(e){this.emit(x.AbExternalVersion,typeof e=="string"&&e?(""+e).trim():null,x.Ab)},r.prototype.getVar=function(e,t,n,i){this.emit(x.AbVar,{name:e,defaultValue:t,callback:n,uuid:i},x.Ab)},r.prototype.getABconfig=function(e,t){this.emit(x.AbConfig,{params:e,callback:t},x.Ab)},r.prototype.getABConfig=function(e,t){this.emit(x.AbConfig,{params:e,callback:t},x.Ab)},r.prototype.getAbSdkVersion=function(){return this.configManager.getAbVersion()},r.prototype.onAbSdkVersionChange=function(e){var t=this;return this.emit(x.AbVersionChangeOn,e,x.Ab),function(){t.emit(x.AbVersionChangeOff,e,x.Ab)}},r.prototype.offAbSdkVersionChange=function(e){this.emit(x.AbVersionChangeOff,e,x.Ab)},r.prototype.openOverlayer=function(){this.emit(x.AbOpenLayer,"",x.Ab)},r.prototype.closeOverlayer=function(){this.emit(x.AbCloseLayer,"",x.Ab)},r.prototype.getAllVars=function(e,t){this.emit(x.AbAllVars,{callback:e,timeout:t},x.Ab)},r.prototype.destoryInstace=function(){this.destroy||(this.destroy=!0,this.off(x.TokenComplete),this.emit(x.DestoryInstance))},r.prototype.destroyInstance=function(){this.destroy||(this.destroy=!0,this.off(x.TokenComplete),this.emit(x.DestoryInstance))},r.plugins=[],r}(),xr={},wa=[];function Ta(r,e,t,n){var i=r&&r.source||window.opener||window.parent,s=r&&r.origin||n||window.location.origin,a={type:e,payload:t};i.postMessage(JSON.stringify(a),s)}function Pm(r){if(wa.some(function(i){return r.origin.indexOf(i)>-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,n=e.payload;xr[t]&&xr[t].forEach(function(i){typeof i=="function"&&i(r,n)})}}var Ir,Pi="__rangers_ab_style__";(function(r){r[r.Var=0]="Var",r[r.All=1]="All"})(Ir||(Ir={}));var Mm=function(){function r(){this.fetchStatus="no",this.refreshFetchStatus="no",this.versions=[],this.extVersions=[],this.mulilinkVersions=[],this.enable_multilink=!1,this.enable_ab_visual=!1,this.editMode=!1,this.callbacks=[],this.data={},this.changeListener=new Map,this.readyStatus=!1,this.exposureCache=[],this.fetchQueueMap=new Map}return r.prototype.apply=function(e,t){var n=this;if(this.collect=e,this.config=t,this.config.enable_ab_test){var i=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=t.disable_auto_ab,h=mi[t.channel||"sg"]||mi.sg,l=s||lr(h),f=e.adapters.storage;this.cacheStorgae=new f(!1),this.timeout=c||3e3,this.enable_multilink=i,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=l+"/service/2/abtest_config/",this.reportUrl=this.collect.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.fetchQueueMap=new Map;var y=this.collect.Types;this.types=y,this.collect.on(y.TokenChange,function(C){C==="uuid"&&n.readyStatus&&(n.clearCache(),n.fetchAB())}),this.collect.on(y.AbVar,function(C){var v=C.name,E=C.defaultValue,k=C.callback;n.getVar(v,E,k)}),this.collect.on(y.AbAllVars,function(C){var v=C.callback,E=C.timeout;n.getAllVars(v,E)}),this.collect.on(y.AbConfig,function(C){var v=C.params,E=C.callback;n.getABconfig(v,E)}),this.collect.on(y.AbExternalVersion,function(C){n.setExternalAbVersion(C)}),this.collect.on(y.AbOpenLayer,function(){n.openOverlayer()}),this.collect.on(y.AbCloseLayer,function(){n.closeOverlayer()}),this.collect.on(y.AbVersionChangeOn,function(C){n.changeListener.set(C,C)}),this.collect.on(y.AbVersionChangeOff,function(C){n.changeListener.get(C)&&n.changeListener.delete(C)}),this.loadMode(),(this.enable_ab_visual||this.enable_multilink)&&this.openOverlayer(this.config.multilink_timeout_ms||500),this.checkLocal(),this.ready("ab"),this.readyStatus||(!u&&this.fetchAB(),this.readyStatus=!0),this.collect.emit(y.AbReady)}},r.prototype.ready=function(e){var t=this;if(this.collect.set(e),this.collect.hook._hooksCache.hasOwnProperty(e)){var n=this.collect.hook._hooksCache[e];if(!Object.keys(n).length)return;var i=function(a){n[a].length&&n[a].forEach(function(o){t.collect.hook.emit(a,o)})};for(var s in n)i(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 n=e.scenario,i=e.href;n?(this.editMode=!0,t=n):!i||i.indexOf("datatester")===-1&&i.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,n=e.ab_ext_version,i=e.ab_version_multilink,s=(e.data,this.checkFromUrl());s?this.mulilinkVersions.push(s):this.mulilinkVersions=i||[],this.extVersions=n||[],this.versions=t||[];var a=this.versions.concat(this.extVersions);this.enable_multilink&&(a=a.concat(this.mulilinkVersions))},r.prototype.checkFromUrl=function(){var e=nn(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,n,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 n!="function")throw new Error("getVar callback must be a function");var s={name:e,defaultValue:t,callback:n,type:Ir.Var};this.collect.emit(T.DEBUGGER_MESSAGE,{type:T.DEBUGGER_MESSAGE_SDK,secType:"AB",info:"SDK Execute GetVar",level:"info",time:Date.now(),data:e,infoType:"cus"}),this.fetchStatus==="complete"&&this.refreshFetchStatus==="complete"?this.getRealVar(s,e,i):this.callbackMap.set(e,s)},r.prototype.setAbUuid=function(e,t){this.collect.configManager.setAbUuidCache(e,t)},r.prototype.getRealVar=function(e,t,n){var i=e.name,s=e.defaultValue,a=e.callback,o=this.data;if(o){var d=o[i];if(d&&dr(d)){var c=d.vid;return t==="$ab_url"?this.mulilinkVersions.includes(c)||this.mulilinkVersions.push(c):this.versions.includes(c)||this.versions.push(c),this.setAbUuid(c,n),this.updateVersions(),this.fechEvent(c,t||i,s,a,d.val),void this.collect.emit(T.DEBUGGER_MESSAGE,{type:T.DEBUGGER_MESSAGE_SDK,secType:"AB",info:"SDK Execute GetVar, Exposure Experiment "+i,level:"info",time:Date.now(),data:o[i],infoType:"sdk"})}this.collect.emit(T.DEBUGGER_MESSAGE,{type:T.DEBUGGER_MESSAGE_SDK,secType:"AB",info:"SDK Execute GerVar Default Callback",level:"info",time:Date.now(),data:this.data,infoType:"sdk"}),a(s)}else a(s)},r.prototype.getAllVars=function(e,t){var n=this;if(typeof e!="function")throw new Error("getAllVars callback must be a function");var i=null,s={callback:e,type:Ir.All,timer:i};this.collect.emit(T.DEBUGGER_MESSAGE,{type:T.DEBUGGER_MESSAGE_SDK,secType:"AB",info:"SDK Execute GetAllVars",level:"info",time:Date.now(),infoType:"cus"}),t&&(i=setTimeout(function(){s.timer=null,n.getRealAllVars(s),clearTimeout(i)},t),s.timer=i),this.fetchStatus==="complete"&&this.refreshFetchStatus==="complete"?(s.timer=null,this.getRealAllVars(s),i&&clearTimeout(i)):this.callbackMap.set("allVars",s)},r.prototype.getRealAllVars=function(e,t){var n=e.callback,i=e.timer;i&&(clearTimeout(i),e.timer=null);var s=(t??this.data)||{};try{n(JSON.parse(JSON.stringify(s)))}catch{n(s)}this.collect.emit(T.DEBUGGER_MESSAGE,{type:T.DEBUGGER_MESSAGE_SDK,secType:"AB",info:"SDK Execute GetAllVars Callback",level:"info",time:Date.now(),data:this.data,infoType:"sdk"})},r.prototype.fechEvent=function(e,t,n,i,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 h={event:"abtest_exposure",ab_sdk_version:""+e,params:JSON.stringify({app_id:this.config.appId,ab_url:t==="$ab_url"?n:window.location.href,data:this.data}),local_time_ms:Date.now()};o.custom=JSON.stringify(o.custom);var l={events:[h],user:d,header:o};this.reportExposure(l,t),i&&i(s)}catch(f){this.collect.emit(T.DEBUGGER_MESSAGE,{type:T.DEBUGGER_MESSAGE_SDK,info:"SDK Something Error",level:"error",time:Date.now(),data:f.message,infoType:"sdk"})}},r.prototype.reportExposure=function(e,t){var n=this;this.exposureCache.push(e),this.reportTimeout&&clearTimeout(this.reportTimeout),this.exposureCache.length>=this.exposureLimit?this.report(t):this.reportTimeout=setTimeout(function(){n.report(t),clearTimeout(n.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(n){t.collect.emit(T.DEBUGGER_MESSAGE,{type:T.DEBUGGER_MESSAGE_EVENT,info:"SDK Report Exposure Event Success",time:Date.now(),data:[n],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 n=Object.keys(e);n&&n.length&&this.collect.configManager.set(e),this.fetchAB(t)},r.prototype.get=function(e){return this.cacheStorgae.getItem(e)},r.prototype.set=function(e,t){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(Pi)){var i="body { opacity: 0 !important; }",s=document.head||document.getElementsByTagName("head")[0],a=document.createElement("style");a.id=Pi,a.type="text/css",a.styleSheet?a.styleSheet.cssText=i:a.appendChild(document.createTextNode(i)),s.appendChild(a)}}(),e)var n=setTimeout(function(){t.closeOverlayer(),clearTimeout(n)},e)},r.prototype.closeOverlayer=function(){var e;(e=document.getElementById(Pi))&&e.parentElement.removeChild(e)},r.prototype.fetchComplete=function(e,t){var n=this;this.changeFetchQueueStatus(t);try{if(e&&Object.prototype.toString.call(e)=="[object Object]"){var i=this.collect.configManager.get().user;if(t&&t!==i.user_unique_id)return;this.data=e,this.setAbCache(t);var s=[];Object.keys(e).forEach(function(u){var h=e[u].vid;h&&s.push(h)}),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}else if(a&&this.enable_multilink){this.mulilinkVersions=this.mulilinkVersions.filter(function(u){return s.includes(u)});var d=a.val,c=a.vid;d&&c&&this.getVar("$ab_url",d,function(){n.editMode||(d!==window.location.href?setTimeout(function(){if(!n.collect.destroy){var u=""+d;u=u.indexOf("http")===-1?"https://"+u:u,ai(u).host!==location.host?u=u+"&vid="+c:window.history.replaceState("","",u),window.location.href=u}},100):n.closeOverlayer())})}this.updateVersions()}else this.closeOverlayer();this.callbackMap.forEach(function(u){u.type===Ir.Var?n.getRealVar(u,""):n.getRealAllVars(u,e)})}catch{}},r.prototype.pushFetchToQueue=function(e){var t=e,n=this.fetchQueueMap.get(t);n?n.fetchStatus="ing":n={current_user_id:t,fetchStatus:"ing"},this.fetchQueueMap.set(t,n)},r.prototype.changeFetchQueueStatus=function(e){var t=this.fetchQueueMap.get(e);t&&(t.fetchStatus="complete",this.fetchQueueMap.set(e,t))},r.prototype.checkFetchQueueStatus=function(){if(this.fetchQueueMap.size===0)return!1;var e=!0;return this.fetchQueueMap.forEach(function(t){t.fetchStatus!=="complete"&&(e=!1)}),e},r.prototype.clearFetchQueue=function(e){this.fetchQueueMap.delete(e)},r.prototype.fetchAB=function(e){var t=this,n=this.collect.configManager.get(),i={header:ne(ne(ne({aid:this.config.app_id},n.user||{}),n.header||{}),{ab_sdk_version:this.collect.configManager.getAbVersion(),ab_url:window.location.href})};this.collect.emit(T.DEBUGGER_MESSAGE,{type:T.DEBUGGER_MESSAGE_SDK,info:"SDK Fetch AB Request",level:"info",logType:"fetch",time:Date.now(),data:i,infoType:"sdk"});var s=n.user[this.ab_user_mode]||n.user.user_unique_id;this.pushFetchToQueue(s),this.collect.requestManager.useRequest({url:this.fetchUrl,data:i,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(T.DEBUGGER_MESSAGE,{type:T.DEBUGGER_MESSAGE_SDK,secType:"AB",info:"SDK Fetch AB Request Success",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(T.DEBUGGER_MESSAGE,{type:T.DEBUGGER_MESSAGE_SDK,secType:"AB",info:"SDK Fetch AB Request Network Error",level:"error",logType:"fetch",time:Date.now(),infoType:"sdk"})},timeout:this.timeout})},r.prototype.filterUrl=function(e){try{var t="";e.indexOf("&multilink=true")!==-1?t="&multilink=true[\0-ÿ]*":e.indexOf("?multilink=true")!==-1&&(t="\\?multilink=true[\0-ÿ]*");var n=new RegExp(t,"g");e=e.replace(n,"")}catch{}return e},r}(),Lm=function(){function r(){}return r.prototype.apply=function(e,t){var n=this;if(this.collect=e,this.config=t,t.event_verify_url)if(typeof t.event_verify_url=="string"){if(this.url=t.event_verify_url+"/v1/list_test",this.url){var i=e.Types;e.on(i.SubmitVerify,function(s){n.verify(s)}),e.on(i.AbVerify,function(s){n.verify(s)})}}else console.log("please use correct et_test url")},r.prototype.verify=function(e){var t=this;e.forEach(function(n){try{var i=JSON.parse(JSON.stringify(n));t.config.filter&&((i=t.config.filter(i))||console.warn("filter must return data !!")),t.collect.eventFilter&&i&&((i=t.collect.eventFilter(i))||console.warn("filterEvent api must return data !!"));var s=i||n,a=JSON.parse(JSON.stringify(s));if(!s.length)return;var o=!0;if(s.forEach(function(d){d.events.length||(o=!1)}),!o)return;t.collect.requestManager.useBeacon({url:t.url,data:s}),t.collect.emit(T.DEBUGGER_MESSAGE,{type:T.DEBUGGER_MESSAGE_EVENT,info:"SDK Report ByteIo Verify Request",time:Date.now(),data:a,code:200,status:"success",verifyType:!0})}catch(d){console.warn("something error, "+JSON.stringify(d.stack)),t.collect.emit(T.DEBUGGER_MESSAGE,{type:T.DEBUGGER_MESSAGE_SDK,info:"SDK Report ByteIo Verify Request Error",level:"error",time:Date.now(),data:d.message})}})},r}(),Nm=function(){function r(e,t){this.maxDuration=432e5,this.aliveDTime=6e4,this.options={aliveName:"predefine_page_alive",params:{}},this.focusState=!0,this.collect=e,this.config=t,this.pageStartTime=Date.now(),this.sessionStartTime=this.pageStartTime,this.timerHandler=null,dr(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()}return r.prototype.setParams=function(e,t,n){this.set_path=e,this.set_url=n,this.set_title=t},r.prototype.enable=function(e,t,n){this.url_path=e,this.url=n,this.title=t,this.disableCallback=this.enablePageAlive(),this.hard&&(this.removeMode=this.hardMode())},r.prototype.disable=function(){this.disableCallback(),this.pageStartTime=Date.now()},r.prototype.sendEvent=function(e,t){t===void 0&&(t=!1);var n=t?this.aliveDTime:Date.now()-this.sessionStartTime;n<0||n>this.aliveDTime||Date.now()-this.pageStartTime>this.maxDuration||t&&document.visibilityState==="hidden"||this.hard&&!this.focusState||(this.collect.beconEvent(this.options.aliveName,ne({url_path:this.getParams("url_path"),title:this.getParams("title"),url:this.getParams("url"),duration:n,is_support_visibility_change:Io(),startTime:this.sessionStartTime,hidden:document.visibilityState,leave:e,mode:this.hard?"hard":"normal",focusState:this.focusState},this.options.params)),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(){document.visibilityState==="hidden"?this.timerHandler&&(clearInterval(this.timerHandler),this.sendEvent(!1)):document.visibilityState==="visible"&&(this.sessionStartTime=Date.now(),this.timerHandler=this.setUpTimer())},r.prototype.beforeunload=function(){document.hidden||this.sendEvent(!0)},r.prototype.enablePageAlive=function(){var e=this;this.timerHandler=this.setUpTimer();var t=this.visibilitychange.bind(this),n=this.beforeunload.bind(this);return document.addEventListener("visibilitychange",t),hr(n),function(){e.beforeunload(),document.removeEventListener("visibilitychange",t),window.removeEventListener("beforeunload",n),window.removeEventListener("pagehide",n)}},r.prototype.hardMode=function(){var e=this,t=function(){e.timerHandler&&(clearInterval(e.timerHandler),e.sendEvent(!1)),e.focusState=!1},n=function(){e.focusState=!0,e.sessionStartTime=Date.now(),e.timerHandler=e.setUpTimer()};return window.addEventListener("blur",t),window.addEventListener("focus",n),function(){window.removeEventListener("blur",t),window.removeEventListener("focus",n)}},r}(),Um=function(){function r(e,t){var n=this;this.maxDuration=432e5,this.aliveDTime=6e4,this.options={closeName:"predefine_page_close",params:{}},this.focusState=!0,this.visibilitychange=function(){document.visibilityState==="hidden"?n.activeEndTime=Date.now():document.visibilityState==="visible"&&(n.activeEndTime&&(n.totalTime+=n.activeEndTime-n.activeStartTime,n.activeTimes+=1),n.activeEndTime=void 0,n.activeStartTime=Date.now())},this.beforeunload=function(){if(n.totalTime+=(n.activeEndTime||Date.now())-n.activeStartTime,n.config.autotrack)try{window.sessionStorage.setItem("_tea_cache_duration",JSON.stringify({duration:n.totalTime,page_title:document.title||location.pathname}))}catch{}n.sendEventPageClose()},this.collect=e,this.config=t,this.maxDuration=t.maxDuration||864e5,this.pageStartTime=Date.now(),dr(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,n){this.set_path=e,this.set_url=n,this.set_title=t},r.prototype.resetParams=function(e,t,n){this.url_path=e,this.url=n,this.title=t},r.prototype.enable=function(e,t,n){this.url_path=e,this.url=n,this.title=t,this.disableCallback=this.enablePageClose(),this.hard&&(this.removeMode=this.hardMode())},r.prototype.disable=function(){this.disableCallback()},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,ne({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),n=this.beforeunload.bind(this);return document.addEventListener("visibilitychange",t),hr(n),function(){e.beforeunload(),document.removeEventListener("visibilitychange",t),window.removeEventListener("beforeunload",n),window.removeEventListener("pagehide",n)}},r.prototype.hardMode=function(){var e=this,t=function(){e.focusState=!1},n=function(){e.focusState=!0};return window.addEventListener("blur",t),window.addEventListener("focus",n),function(){window.removeEventListener("blur",t),window.removeEventListener("focus",n)}},r}(),Gm=function(){function r(){}return r.prototype.apply=function(e,t){var n=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 Um(e,t);var i=this.collect.Types;this.collect.on(i.ResetStay,function(s){var a=s.url_path,o=s.title,d=s.url;n.resetStayDuration(a,o,d)}),this.collect.on(i.RouteChange,function(s){s.init||t.disable_route_report||n.resetStayDuration()}),this.collect.on(i.SetStay,function(s){var a=s.url_path,o=s.title,d=s.url;n.setStayParmas(a,o,d)}),this.enable(this.url_path,this.title,this.url),this.ready(i.Stay),this.collect.emit(i.StayReady)}},r.prototype.ready=function(e){var t=this;if(this.collect.set(e),this.collect.hook._hooksCache.hasOwnProperty(e)){var n=this.collect.hook._hooksCache[e];if(!Object.keys(n).length)return;var i=function(a){n[a].length&&n[a].forEach(function(o){t.collect.hook.emit(a,o)})};for(var s in n)i(s)}},r.prototype.enable=function(e,t,n){this.pageAlive.enable(e,t,n),this.pageClose.enable(e,t,n)},r.prototype.disable=function(){this.pageAlive.disable(),this.pageClose.disable()},r.prototype.setStayParmas=function(e,t,n){e===void 0&&(e=""),t===void 0&&(t=""),n===void 0&&(n=""),this.pageAlive.setParams(e,t,n),this.pageClose.setParams(e,t,n),this.collect.emit(T.DEBUGGER_MESSAGE,{type:T.DEBUGGER_MESSAGE_SDK,info:"SDK Execute resetStayParams",level:"info",time:Date.now(),data:{url_path:e,title:t,url:n}})},r.prototype.reset=function(e,t,n){this.disable(),this.enable(e,t,n)},r.prototype.resetStayDuration=function(e,t,n){this.reset(e,t,n),this.collect.emit(T.DEBUGGER_MESSAGE,{type:T.DEBUGGER_MESSAGE_SDK,info:"SDK Execute resetStayDuration",level:"info",time:Date.now(),data:{url_path:e,title:t,url:n}})},r}(),Bm=function(){function r(){var e=this;this.setInterval=function(){e.clearIntervalFunc=function(t,n){t===void 0&&(t=function(){}),n===void 0&&(n=1e3);var i,s=Date.now()+n;return i=window.setTimeout(function a(){var o=Date.now()-s;t(),s+=n,i=window.setTimeout(a,Math.max(0,n-o))},n),function(){window.clearTimeout(i)}}(function(){e.isSessionhasEvent&&e.endCurrentSession()},e.sessionInterval)},this.clearInterval=function(){e.clearIntervalFunc&&e.clearIntervalFunc()}}return r.prototype.apply=function(e,t){var n=this;if(this.collect=e,!t.disable_heartbeat){this.sessionInterval=6e4,this.startTime=0,this.lastTime=0,this.setInterval();var i=this.collect.Types;this.collect.on(i.SessionReset,function(){n.process()})}},r.prototype.endCurrentSession=function(){this.collect.event("_be_active",{start_time:this.startTime,end_time:this.lastTime,url:window.location.href,referrer:window.document.referrer,title:document.title||location.pathname}),this.isSessionhasEvent=!1,this.startTime=0},r.prototype.process=function(){this.isSessionhasEvent||(this.isSessionhasEvent=!0,this.startTime=+new Date);var e=this.lastTime||+new Date;this.lastTime=+new Date,this.lastTime-e>this.sessionInterval&&(this.clearInterval(),this.endCurrentSession(),this.setInterval())},r}(),Fm=function(){function r(){}return r.prototype.apply=function(e,t){var n=this;if(this.collect=e,this.config=t,!this.config.channel_domain&&!t.disable_track_event&&!t.disable_sdk_monitor){this.url=e.configManager.getUrl("event");var i=this.collect.Types;this.collect.on(i.Ready,function(){n.sdkOnload()}),this.collect.on(i.SubmitError,function(s){var a=s.type,o=s.eventData,d=s.errorCode,c=s.response;a==="f_data"&&n.sdkError(o,d,c)}),this.collect.on(e.Types.SDKInnerError,function(s){var a=s.type,o=s.eventData,d=s.errorCode,c=s.msg;n.sdkInnerError(a,o,d,c)})}},r.prototype.sdkOnload=function(){var e=this;try{var t=this.collect.configManager.get(),n=t.header,i=t.user,s=n.app_id,a=n.app_name,o=n.sdk_version,d=(i.web_id,{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_OVERSEA",url:location.href,is_setting:this.config.enable_logsetting||!1,enable_logsetting_params:this.config.enable_logsetting_params||!1,enable_logsetting_header_custom:this.config.enable_logsetting_header_custom||!1}),local_time_ms:Date.now()}],user:{user_unique_id:i.user_unique_id},header:{app_id:6656}});setTimeout(function(){e.collect.requestManager.useRequest({url:e.url,data:[d],timeout:3e4,forceXhr:!0})},16)}catch{}},r.prototype.sdkError=function(e,t,n){var i=this;try{var s=e[0],a=s.user,o=s.header,d=[];e.forEach(function(u){u.events.forEach(function(h){d.push(h)})});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:n.m||""}),local_time_ms:Date.now()}}),user:{user_unique_id:a.user_unique_id},header:{app_id:6656}};setTimeout(function(){i.collect.requestManager.useRequest({url:i.url,data:[c],timeout:3e4,forceXhr:!0})},16)}catch{}},r.prototype.sdkInnerError=function(e,t,n,i){var s=this;try{var a=t[0],o=a.user,d=a.header,c=[];t.forEach(function(h){h.events.forEach(function(l){c.push(l)})});var u={events:c.map(function(h){return{event:"on_error",params:JSON.stringify({type:e,error_code:n,app_id:d.app_id,app_name:d.app_name||"",error_event:h.event,sdk_version:d.sdk_version,local_time_ms:h.local_time_ms,tea_event_index:Date.now(),params:h.params,header:d,user:o,ua:window.navigator.userAgent,err_msg:i}),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}();function Mi(r,e){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"))return!0;return!1}function Li(r){for(var e=r;e&&!Mi(e,"container");){if(e.nodeName==="HTML"||e.nodeName==="BODY")return r;e=e.parentElement}return e||r}function ka(r){var e="";return r.nodeType===3?e=r.textContent.trim():r.dataset&&r.dataset.hasOwnProperty("teaTitle")||r.hasAttribute("ata-tea-title")?e=r.getAttribute("data-tea-title"):r.hasAttribute("title")?e=r.getAttribute("title"):r.nodeName==="INPUT"&&["button","submit"].includes(r.getAttribute("type"))?e=r.getAttribute("value"):r.nodeName==="IMG"&&r.getAttribute("alt")&&(e=r.getAttribute("alt")),e.slice(0,200)}function Ra(r){for(var e=r;e&&e.parentNode;){if(e.hasAttribute("data-tea-ignore"))return!0;if(e.nodeName==="HTML"||e.nodeName==="body")return!1;e=e.parentNode}return!1}var pn=function(r,e){return r.hasAttribute?r.hasAttribute(e):r.attributes?!(!r.attributes[e]||!r.attributes[e].specified):void 0},Vm=function(r,e){if(typeof e=="string")return pn(r,e);if(oi(e)){for(var t=!1,n=0;n<e.length;n++)if(pn(r,e[n])){t=!0;break}return t}},jm=function(){function r(e,t,n){var i=this;this.statistics=!1,this.pageView=!1,this.clickEvent=function(s){(function(a,o){if(a.nodeType!==1||!o.svg&&function(c){if(c.tagName.toLowerCase()==="svg")return!0;for(var u=c.parentElement,h=!1;u;)u.tagName.toLowerCase()==="svg"?(u=null,h=!0):u=u.parentElement;return h}(a)||["HTML","BODY"].includes(a.tagName.toUpperCase()))return!1;var d=a;return d.style.display!=="none"&&(!!Mi(d,"container")||!(!function(c){if(c.children.length){var u=c.children;return![].slice.call(u).some(function(h){return h.children.length>0})}return!0}(d)&&!o.svg))})(s.target,i.options)&&i.eventHandel({eventType:"dom",eventName:"click"},s)},this.changeEvent=function(s){i.eventHandel({eventType:"dom",eventName:"change"},s)},this.submitEvent=function(s){i.eventHandel({eventType:"dom",eventName:"submit"},s)},this.getPageViewEvent=function(s,a){a&&a==="pushState"&&i.eventHandel({eventType:"dom",eventName:"beat"},ne({beat_type:0},s)),i.eventHandel({eventType:"dom",eventName:"page_view"},s)},this.getPageLoadEvent=function(s){i.eventHandel({eventType:"dom",eventName:"page_statistics"},{lcp:s})},this.config=n.getConfig().eventConfig,this.collect=t,this.options=e,this.beatTime=e.beat}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&&window.document.addEventListener("click",this.clickEvent,!0),this.config.change&&window.document.addEventListener("change",this.changeEvent,!0),this.config.submit&&window.document.addEventListener("submit",this.submitEvent,!0),this.config.pv){this.collect.on("route-change",function(d){var c=d.config,u=d.name;t.getPageViewEvent(c,u),t.pageView=!0});var n=setTimeout(function(){t.pageView||(t.getPageViewEvent(t.getDefaultConfig()),t.pageView=!0,clearTimeout(n))},2e3)}if(this.config.beat){try{document.readyState==="complete"?this.beatEvent(this.beatTime):window.addEventListener("load",function(){t.beatEvent(t.beatTime)});var i=0,s=null;window.addEventListener("scroll",function(){clearTimeout(s),s=setTimeout(a,500),i=document.documentElement.scrollTop||document.body.scrollTop});var a=function(){(document.documentElement.scrollTop||document.body.scrollTop)==i&&t.eventHandel({eventType:"dom",eventName:"beat"},{beat_type:1})}}catch{}try{var o=window.performance&&window.performance.getEntriesByType("paint");o&&o.length?(new PerformanceObserver(function(d){var c=d.getEntries(),u=c[c.length-1],h=u.renderTime||u.loadTime;t.statistics||(t.getPageLoadEvent(h),t.statistics=!0)}).observe({entryTypes:["largest-contentful-paint"]}),setTimeout(function(){t.statistics||(t.getPageLoadEvent(o[0].startTime||0),t.statistics=!0)},2e3)):this.getPageLoadEvent(0)}catch{this.getPageLoadEvent(0)}}}},r.prototype.removeListener=function(){window.document.removeEventListener("click",this.clickEvent,!0),window.document.removeEventListener("change",this.changeEvent,!0),window.document.removeEventListener("submit",this.submitEvent,!0)},r.prototype.beatEvent=function(e){var t=this;try{var n;this.eventHandel({eventType:"dom",eventName:"beat"},{beat_type:3}),this.beatTime&&(n=setInterval(function(){t.eventHandel({eventType:"dom",eventName:"beat"},{beat_type:2})},e)),hr(function(){t.eventHandel({eventType:"dom",eventName:"beat",eventSend:"becon"},{beat_type:0}),t.beatTime&&clearInterval(n)})}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}(),Hm={eventConfig:{mode:"proxy-capturing",submit:!1,click:!0,change:!1,pv:!0,beat:!0,hashTag:!1,impr:!1},scoutConfig:{mode:"xpath"}},qm=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){for(var e=[];r.parentElement!==null;)e.push(r),r=r.parentElement;var t=[],n=[];return e.forEach(function(i){var s=function(d){if(d===null)return{str:"",index:0};var c=0,u=d.parentElement;if(u)for(var h=u.children,l=0;l<h.length&&h[l]!==d;l++)h[l].nodeName===d.nodeName&&c++;return{str:[d.nodeName.toLowerCase(),Mi(d,"list")?"[]":""].join(""),index:c}}(i),a=s.str,o=s.index;t.unshift(a),n.unshift(o)}),{element_path:"/"+t.join("/"),positions:n}}function Km(r,e,t,n){var i={},s=function(R){if(R){var M=R.getBoundingClientRect(),U=M.width,G=M.height;return{left:M.left,top:M.top,element_width:U,element_height:G}}}(e),a=function(R,M){R===void 0&&(R={}),M===void 0&&(M={});var U=R.clientX,G=R.clientY,F=M.left,q=M.top,ee=U-F>=0?U-F:0,J=G-q>=0?G-q:0;return{touch_x:Math.floor(ee),touch_y:Math.floor(J)}}(r,s),o=s.element_width,d=s.element_height,c=a.touch_x,u=a.touch_y,h=$m(e),l=h.element_path,f=h.positions,y=function(R){var M=Li(R),U=[];return function G(F){var q=ka(F);if(q&&U.indexOf(q)===-1&&U.push(q),F.childNodes.length>0)for(var ee=F.childNodes,J=0;J<ee.length;J++)ee[J].nodeType!==8&&G(ee[J])}(M),U}(e),C=window.performance.timing.navigationStart,v=Date.now()-C,E=f.map(function(R){return""+R}),k=null;if(window.TEAVisualEditor&&window.TEAVisualEditor.getOriginXpath&&(k=window.TEAVisualEditor.getOriginXpath({xpath:l,positions:E})),i.element_path=k&&k.xpath||l,i.positions=k&&k.positions||E,n&&!n.text&&(i.texts=y,i.element_title=function(R){var M=Li(R),U="";return function G(F){var q=ka(F);if(q&&(U+=q),F.childNodes.length>0)for(var ee=F.childNodes,J=0;J<ee.length;J++)ee[J].nodeType===3&&G(ee[J])}(M),U}(e)),i.element_id=e.getAttribute("id")||"",i.element_class_name=e.getAttribute("class")||"",i.element_type=e.nodeType,i.element_width=Math.floor(o),i.element_height=Math.floor(d),i.touch_x=c,i.touch_y=u,i.page_manual_key="",i.elememt_manual_key="",i.since_page_start_ms=v,i.page_start_ms=C,i.page_path=location.pathname,i.page_host=location.host,t.track_attr&&function(R,M){return!!Vm(R,M)}(e,t.track_attr)){var g=function(R,M){var U={};if(typeof M=="string")pn(R,M)&&(U.attrs=R.getAttribute(M));else if(oi(M))for(var G=0;G<M.length;G++)pn(R,M[G])&&(U[M[G]]=R.getAttribute(M[G]));return U}(e,t.track_attr);for(var D in g)i[D]=g[D]}var L=Li(e);return L.tagName==="A"&&(i.href=L.getAttribute("href")),e.tagName==="IMG"&&(i.src=e.getAttribute("src")),i}var zr=function(r,e,t,n,i){return ne(ne({event:r},Km(e,t,n,i)),{is_html:1,page_key:window.location.href,page_title:document.title})},Wm=function(){function r(e,t){this.ignore={text:!0},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"}:{click:"bav2b_click",page:"bav2b_page",beat:"bav2b_beat",static:"bav2b_page_statistics",exposure:"bav2b_exposure"},t&&t.text===!0&&(this.ignore.text=!1),t&&t.exposure&&t.exposure.eventName&&(this.eventName.exposure=t.exposure.eventName)}return r.prototype.handleEvent=function(e,t){try{if(Ra(e.target))return null;var n="bav2b_click";switch(t){case"click":return n=e.target.getAttribute("data-applog-click-event")||this.eventName.click,zr(n,e,e.target,this.options,this.ignore);case"change":return ne(ne({},zr(n="bav2b_change",e,e.target,this.options)),function(i,s){try{if(i==="bav2b_change")return s.hasAttribute("data-tea-track")?{value:s.value}:{}}catch{return{}}}(n,e.target));case"submit":return zr(n="bav2b_submit",e,e.target,this.options)}}catch(i){return console.error(i),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 n=JSON.parse(t);e.refer_page_duration_ms=n?n.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(i){console.log("page event error "+JSON.stringify(i))}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 n=e.lcp,i=window.performance.timing,s=i.loadEventEnd-i.navigationStart;t.page_init_cost_ms=parseInt(n||(s>0?s:0)),t.page_start_ms=i.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(Ra(t.target))return null;var n=zr(e.event||this.eventName.exposure,t,t.target||t,this.options,this.ignore);if(n.$exposure_type=e.exposureType,this.options.exposure.callback){var i=this.options.exposure.callback(n);return i||Object.keys(i).length?i:(console.warn("exposure callback must return data!"),n)}return n},r.prototype.handleScrollEvent=function(e,t){var n=zr(e.event||this.eventName.scroll,t,t.target||t,this.options,this.ignore);if(n=Object.assign(n,e.params),!this.options.scroll.callback||(n=this.options.scroll.callback(n))||Object.keys(n).length)return n;console.warn("scroll callback must return data!")},r}(),Jm=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 n=e.eventSend,i=t.event;delete t.event,n&&n==="becon"?this.collect.beconEvent(i,t):this.collect.event(i,t)},r.prototype.get=function(e,t){var n=Object.assign({headers:{"content-type":"application/json"},method:"GET"},t);fetch(e,n)},r.prototype.post=function(e,t){var n=Object.assign({headers:{"content-type":"application/json"},method:"POST"},t);fetch(e,n)},r}(),Ni=!1;function Xm(r){var e,t,n,i,s=r.event,a=r.editorUrl,o=r.autoTrackInstance;Ni||(Ni=!0,e=a,t=function(){Ta(s,"editorScriptloadSuccess"),o.destroy()},n=function(){s&&Ta(s,"editorScriptloadError"),Ni=!1},(i=document.createElement("script")).src=e,i.onerror=function(){n(e)},i.onload=function(){t()},document.getElementsByTagName("head")[0].appendChild(i))}function Zm(r,e){window.TEAVisualEditor=window.TEAVisualEditor||{},window.TEAVisualEditor.appId=e.app_id;var t,n,i,s=e.channel_domain,a="";if((t=yf).length&&t.forEach(function(l){wa.push(l)}),s){var o=void 0,d="";try{var c=window.performance.getEntriesByType("resource");if(c&&c.length&&(c.forEach(function(l){l.initiatorType==="script"&&l.name&&l.name.indexOf("collect")!==-1&&(d=l.name)}),d&&(o=d.split("/"))&&o.length)){a="https:/";for(var u=2;u<o.length&&u!==o.length-1;u++)a=a+"/"+o[u];if(a&&a.indexOf("/5.0")){var h=a.split("/5.0");a=h[0]||a}}}catch{}}window.addEventListener("message",Pm,!1);try{i=function(l){var f=l.data.app_id;f&&f!==e.app_id||Xm({event:l,editorUrl:"https://sf16-website-login.neutral.ttwstatic.com/obj/tiktok_web_login_static/log-sdk/collect/heatmap-core.js?query="+Date.now(),autoTrackInstance:r})},xr[n="tea:openHeatMapCore"]=xr[n]||[],xr[n].push(i)}catch{console.log("openHeatMapCore error")}}var He,Ym=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(n){n.forEach(function(i){i.type==="attributes"&&e.attributeChangeObserve(i),i.type==="childList"&&e.modifyNodeObserve(i)})}),!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(n){n.nodeType===1&&n.hasAttribute("data-exposure")&&t.exposureAdd(n,"intersect"),t.mapChild(n,t.exposureAdd.bind(t))}),Array.prototype.forEach.call(e.removedNodes,function(n){n.nodeType===1&&n.hasAttribute("data-exposure")&&t.exposureRemove(n),t.mapChild(n,t.exposureRemove.bind(t))})},r.prototype.mapChild=function(e,t){var n=this;e.nodeType===1&&e.children.length&&Array.prototype.forEach.call(e.children,function(i){i.nodeType===1&&i.hasAttribute("data-exposure")&&t(i),n.mapChild(i,t)})},r.prototype.exposureAdd=function(e,t){try{this._intersection&&this._intersection.exposureAdd(e,t)}catch(n){console.log("intersection error",JSON.stringify(n.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"})(He||(He={}));var xt,Qm=function(){function r(e,t,n){var i=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=He.NOT_EXPOSURE,this.eventHandle=n,this.hashMap=new Map,this.backStatus=!1,this.lastState=null,this.collect.on("re-start-sdk",function(){i.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=[],n=0;n<=1;n+=.01)t.push(n);t.push(1);try{r._observer_instance=new IntersectionObserver(function(i){i.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(h){console.log("IntersectionObserver setTimeout error,msg: "+JSON.stringify(h))}},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(i){console.log("IntersectionObserver error,msg: "+JSON.stringify(i))}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 n=t==="mutation"?e.target:e,i=n.observeId,s=on();if(i||this.observeMap.has(i)){var a=this.observeMap.get(i);if(a&&n!==a.instance)this.unobserve(n),this.observeMap.delete(i),n.observeId=s,n.visible=!1,this.observeMap.set(s,{instance:n.cloneNode(!0),isIntersecting:!1}),this.observe(n);else{if(n.visible===!0)return;this.handleBoundingExposure(n)}}else n.observeId=s,n.visible=!1,this.observeMap.set(s,{instance:n.cloneNode(!0),isIntersecting:!1}),this.observe(n)},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,n,i){if(t>=this.ratio){if(e.target.style.opacity==="0"||e.target.style.visibility==="hidden"||i.exposured===!0)return;i.startWait&&clearTimeout(i.startWait);var s=e.target.getAttribute("data-applog-exposure-event");this.eventHandle({eventType:"dom",eventName:"exposure",event:s,exposureType:this.getExposureType(e.target)},e),e.target.visible=!0,e.target.hasExposure=!0,i.startTime=Date.now(),i.exposured=!0}else i.startTime=Date.now(),i.exposured=!1;this.observeMap.set(n,i)},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||He.RESUME_FORM_BACK},e)}},r.prototype.getBoundingRatio=function(e){var t=e.getBoundingClientRect(),n=t.top,i=t.left,s=t.width,a=t.height,o=window.innerWidth||document.documentElement.clientWidth,d=window.innerHeight||document.documentElement.clientHeight;return n>=0&&i>=0&&n<=d&&i<=o?(s>o?o:s)*(d-n)/(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=He.RESUME_FORM_PAGE:this.exposureType=He.LIFECYCLE_SHOW_NEW:(e.hasExposure,e.backStatus!==!1&&(this.backStatus||this.customType||window.performance.navigation.type===2)?this.exposureType=He.RESUME_FORM_PAGE:this.exposureType=He.EXPOSURE_ONCE),this.exposureType},r.prototype.addListen=function(){var e=this;this.collect.on("set-exposure-type",function(o){e.customType=o});var t,n,i,s,a=this.visibilitychange.bind(this);return t=document,n="visibilitychange",i=a,s=!1,t.addEventListener?t.addEventListener(n,i,s):t.attachEven?t.attachEven("on"+n,i):t["on"+n]=i,window.addEventListener("hashchange",function(o){var d=e.hashMap.get(o.oldURL);d&&location.href===d.prev?(e.backStatus=!0,e.exposureType=He.RESUME_FORM_PAGE):(e.backStatus=!1,e.hashMap.set(location.href,{current:o.newURL,prev:o.oldURL}))}),this.collect.on("STATE_CHANGE",function(o){e.lastState=o}),window.addEventListener("popstate",function(o){var d=o.state;d&&d.current&&e.lastState&&e.lastState.back&&d.current===e.lastState.back?(e.backStatus=!0,e.exposureType=He.RESUME_FORM_PAGE):e.backStatus=!1}),function(){(function(o,d,c,u){o.addEventListener?o.removeEventListener(d,c,u):o.attachEven&&o.detachEven("on"+d,c)})(document,"visibilitychange",a,!1)}},r._observer_instance=null,r._observer_map=new Map,r}(),e_=function(){function r(e,t,n){t.autotrack&&t.autotrack.exposure&&(this._intersection=new Qm(e,t,n),this._observer=new Ym(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"})(xt||(xt={}));var Aa,t_=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(n){n.forEach(function(i){i.type==="childList"&&e.modifyNodeObserve(i)})});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(n){n.nodeType===1&&n.hasAttribute("data-scroll")&&t.scrollHandle(n),t.mapChild(n,t.scrollHandle.bind(t))}),Array.prototype.forEach.call(e.removedNodes,function(n){n.nodeType===1&&n.hasAttribute("data-scroll")&&t.scrollHandle(n,"remove"),t.mapChild(n,t.scrollHandle.bind(t))})},r.prototype.mapChild=function(e,t){var n=this;e.nodeType===1&&e.children.length&&Array.prototype.forEach.call(e.children,function(i){i.nodeType===1&&i.hasAttribute("data-scroll")&&t(i),n.mapChild(i,t)})},r.prototype.scrollHandle=function(e,t){var n=this;try{var i=e.scrollTop,s=e.scrollLeft,a=null,o=0,d=0,c=function(u){clearTimeout(a),a=setTimeout(function(){var y=e.scrollTop,C=e.scrollLeft,v=u.target&&u.target.getAttribute("data-scroll-event")||"";f===1||f===2?y===h&&(d=h-i,Math.abs(d)>=n.distance&&n.distance&&n.eventHandle({eventType:"dom",eventName:"scroll",event:v,params:{$direction:f,$offsetY:d,$offsetX:o}},u)):f!==3&&f!==4||C===l&&(o=l-s,Math.abs(o)>=n.distance&&n.distance&&n.eventHandle({eventType:"dom",eventName:"scroll",event:v,params:{$direction:f,$offsetY:d,$offsetX:o}},u)),i=h,s=l},100);var h=e.scrollTop,l=e.scrollLeft,f=xt.NOT_SCROLL;h>i?f=xt.SCROLL_DOWN:h<i?f=xt.SCROLL_UP:l>s?f=xt.SCROLL_LEFT:l<s&&(f=xt.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}(),r_={hashTag:!1,impr:!1},n_=function(){function r(){}return r.prototype.apply=function(e,t){if(this.autoTrackStart=!1,this.collect=e,this.config=t,t.autotrack){var n=e.Types;this.ready(n.Autotrack),this.collect.emit(n.AutotrackReady)}},r.prototype.ready=function(e){this.collect.set(e);var t=this.config.autotrack;t=typeof t=="object"?t:{},t=Object.assign(r_,t),this.destroyed=!1,this.options=t,this.Config=new qm(Hm,this.options),this.Exposure=new e_(this.collect,this.config,this.handle.bind(this)),this.Scroll=new t_(this.config,this.handle.bind(this)),this.Listener=new jm(t,this.collect,this.Config),this.EventHandle=new Wm(this.config,t),this.Request=new Jm(this.collect),this.autoTrackStart=!0,this.init(),Zm(this,this.config)},r.prototype.init=function(){this.Listener.init(this.handle.bind(this)),this.collect.loadType==="base"&&(window.opener||window.parent).postMessage("[tea-sdk]ready","*")},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 n=e.eventName;if(n==="click"||n==="change"||n==="submit")(o=this.EventHandle.handleEvent(t,n))&&this.Request.send({eventType:"custom"},o);else if(n==="page_view"||n==="page_statistics"){var i=void 0;(i=n==="page_view"?this.EventHandle.handleViewEvent(t):this.EventHandle.handleStatisticsEvent(t))&&this.Request.send({eventType:"custom"},i)}else if(n==="beat"){var s=this.EventHandle.handleBeadtEvent(t),a=e.eventSend;s&&this.Request.send({eventType:"custom",eventSend:a},s)}else if(n==="exposure")(o=this.EventHandle.handleExposureEvent(e,t))&&this.Request.send({eventType:"custom"},o);else if(n==="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"})(Aa||(Aa={}));var Da={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"]},i_=function(){function r(){}return r.prototype.apply=function(e,t){var n=this;if(this.ready=t.app_id&&t.enable_tracer&&!t.disable_track_event,this.ready){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 i=this.collect.Types;e.adapters.fetch,this.collect.on(i.Event,function(s){oi(s)?s.forEach(function(a){n.addCount("log")}):n.addCount("log")}),this.collect.on(i.SubmitError,function(s){var a=s.type,o=s.eventDate,d=s.errorCode,c=s.response;n.addErrorCount(o,a,d,c)}),this.listener(),this.collect.emit(i.TracerReady)}},r.prototype.addCount=function(e,t,n){t===void 0&&(t="net"),n===void 0&&(n=1);try{this.tracerCache||(this.tracerCache=new Map);var i=void 0;if(this.tracerCache.has(e))(s=this.tracerCache.get(e)).has(t)?(i=s.get(t).params.count,i++,s.set(t,this.processTracer(i,e,t))):(i=n,s.set(t,this.processTracer(n,e,t)));else{var s=new Map;i=n,s.set(t,this.processTracer(n,e,t)),this.tracerCache.set(e,s)}t==="net"&&i>=this.limit[e]&&this.report(!1)}catch(a){console.log(a)}},r.prototype.addErrorCount=function(e,t,n,i){var s=this;try{if(e&&e.length){var a=e[0].events;a&&a.length&&(t==="f_data"?(i&&i.hasOwnProperty("sc")?this.addCount("log",t,a.length-i.sc):this.addCount("log",t,a.length),this.errorCode[t]=n):a.forEach(function(o){var d="log";for(var c in Da)if(Da[c].indexOf(o.event)!==-1){d=c;break}s.addCount(d,t,1),s.errorCode[t]=n}))}}catch{}},r.prototype.report=function(e){if(this.tracerCache){var t=[];this.tracerCache.forEach(function(n){console.log(n),n.forEach(function(i){t.push(i)})}),t&&t.length&&this.sendTracer(t,e)}},r.prototype.sendTracer=function(e,t){try{var n=this.collect.eventManager.merge(e);this.collect.requestManager.useRequest({url:this.reportUrl,data:n,useBeacon:t}),this.tracerCache=null}catch{}},r.prototype.processTracer=function(e,t,n){try{var i={count:e,state:n,key:t,params_for_special:"applog_trace",aid:this.appid,platform:"web",_staging_flag:1,sdk_version:fr};n!=="f_net"&&n!=="f_data"||(i.errorCode=this.errorCode[n]);var s=this.collect.processEvent("applog_trace",i);if(s&&s.event)return delete s.is_bav,s}catch{console.warn("something error")}},r.prototype.listener=function(){var e=this;document.addEventListener("visibilitychange",function(){document.visibilityState==="hidden"&&e.leavePage()}),hr(function(){e.leavePage()})},r.prototype.leavePage=function(){this.report(!0)},r}(),s_=function(){function r(){this.retryWaitTime=3e3,this.retryStatus=!1,this.retryCacheStatus=!1}return r.prototype.apply=function(e,t){var n=this;if(t.enable_storage&&!t.disable_storage&&(this.collect=e,this.config=t,!this.collect.destroy)){var i=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(i.SubmitError,function(a){a.type!=="f_data"&&n.storeData(a)}),e.on(i.Ready,function(){n.checkStorage()})}},r.prototype.retryRightNow=function(e){var t=this;if(this.retryStatus)this.errorCache.push(e);else{var n=0;this.retryStatus=!0;var i=setInterval(function(){if(n===3)return t.storeData(t.errorCache),t.retryStatus=!1,void clearInterval(i);var s=e.eventData;t.fetchData(s,function(){t.retryStatus=!1,clearInterval(i),t.retryCacheStatus&&t.errorCache.splice(0,1),t.errorCache.length&&(t.retryCacheStatus=!0,t.retryRightNow(t.errorCache[0]))},function(){n++})},this.retryInterval)}},r.prototype.storeData=function(e){var t=this.storage.getItem(this.eventKey),n=e.eventData;Object.keys(t).length!==this.storageNum&&(t[Date.now()]=n,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 n={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([n],function(){var i=JSON.parse(JSON.stringify(t)),s=function(o){e.fetchData(t[o],function(){delete i[o],e.storage.setItem(e.eventKey,i)},function(){},!1)};for(var a in t)s(a)},function(){},!0)}catch{console.warn("error check storage")}},r.prototype.fetchData=function(e,t,n,i){this.collect.requestManager.useRequest({url:this.eventUrl,data:e,timeout:3e4,success:t,fail:n,app_key:i?"566f58151b0ed37e":""})},r}(),Ui=typeof window<"u"?(window.LogPluginObject||(window.LogPluginObject={}),window.LogPluginObject):null,o_=function(){function r(){}return r.prototype.apply=function(e,t){this._plugin={},this.config=t,this.collect=e,this.channel="va",this.loadExtend()},r.prototype.loadExtend=function(){var e=this;try{this.collect.remotePlugin.forEach(function(t,n){if(t==="sdk")if(Oi.hasOwnProperty(n)){var i=Oi[n].object,s=""+Oi[n].src[e.channel];e.exist(n,i,s)}else console.warn("your "+n+" is not exist,please check plugin name");else typeof t=="object"&&(t.src?e.exist(n,t.call,t.src):e.process(n,t.instance,"INSTANCE"))})}catch(t){this.collect.emit(T.DEBUGGER_MESSAGE,{type:T.DEBUGGER_MESSAGE_SDK,info:"LoadExtend Fail",level:"error",time:Date.now(),data:t.message}),console.log("load extend error")}},r.prototype.exist=function(e,t,n){var i=this;Ui[t]?(this.process(e,Ui[t]),console.log("already has "+e+" plugin~")):this.loadPlugin(e,n,function(){i.process(e,Ui[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,n){try{if(n){var i=new t;i.apply&&i.apply(this.collect,this.config),console.log("excude "+e+" success")}else t&&t(this.collect,this.config)}catch(s){this.collect.emit(T.DEBUGGER_MESSAGE,{type:T.DEBUGGER_MESSAGE_SDK,info:"Extend Process Fail",level:"error",time:Date.now(),data:s.message}),console.log("excude "+e+" error, message:"+s.message)}},r.prototype.loadPlugin=function(e,t,n,i){var s=this;try{var a=document.createElement("script");a.src=t,this._plugin[e]||(this._plugin[e]=[]),this._plugin[e].push(n),a.onerror=function(){i(t)},a.onload=function(){s._plugin[e].forEach(function(o){o()})},document.getElementsByTagName("head")[0].appendChild(a)}catch(o){this.collect.emit(T.DEBUGGER_MESSAGE,{type:T.DEBUGGER_MESSAGE_SDK,info:"Extend LoadPlugin Fail",level:"error",time:Date.now(),data:o.message})}},r}(),a_=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 n=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(n.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(i){for(var s=[],a=1;a<arguments.length;a++)s[a-1]=arguments[a];typeof history.onpushstate=="function"&&history.onpushstate({state:i});var o=t.call.apply(t,ur([history,i],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 n=history.replaceState;history.replaceState=function(i){for(var s=[],a=1;a<arguments.length;a++)s[a-1]=arguments[a];typeof history.onreplacestate=="function"&&history.onreplacestate({state:i});var o=n.call.apply(n,ur([history,i],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 n=e.getPopStateChangeEventData();e.sendPv(n)}}),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 n=e.getPopStateChangeEventData();e.sendPv(n)}})},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,n=this.storage.getItem("__tea_cache_first_"+this.appid);return t=!n||n!=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(i){return this.collect.emit(T.DEBUGGER_MESSAGE,{type:T.DEBUGGER_MESSAGE_SDK,info:"something error",level:"error",time:Date.now(),data:i.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)||{},n=this.removeQuery(e);t.refer_key=n,t.routeChange=!0,this.storage.setItem(this.cache_key,t)},r}(),c_=function(){function r(){}return r.prototype.apply=function(e,t){var n=this;this.collect=e,this.config=t;var i=e.Types;e.on(i.TrackDurationStart,function(s){n.trackEventStart(s)}),e.on(i.TrackDurationEnd,function(s){n.trackEventEnd(s)}),e.on(i.TrackDurationPause,function(s){n.trackEventPause(s)}),e.on(i.TrackDurationResume,function(s){n.trackEventResume(s)}),this.Types=i,this.TrackEventMap=new Map,this.ready(i.TrackDuration)},r.prototype.ready=function(e){var t=this;if(this.collect.set(e),this.collect.hook._hooksCache.hasOwnProperty(e)){var n=this.collect.hook._hooksCache[e];if(!Object.keys(n).length)return;var i=function(a){n[a].length&&n[a].forEach(function(o){t.collect.hook.emit(a,o)})};for(var s in n)i(s)}},r.prototype.trackEventStart=function(e){this.TrackEventMap.set(e,{startTime:Date.now(),isPause:!1,pauseTime:0,resumeTime:0})},r.prototype.trackEventEnd=function(e){var t=e.eventName,n=e.params;if(this.TrackEventMap.has(t)){var i=this.TrackEventMap.get(t),s=0;s=i.isPause?i.pauseTime-i.startTime:i.resumeTime?i.pauseTime-i.startTime+(Date.now()-i.resumeTime):Date.now()-i.startTime;var a=Object.assign(n,{event_duration:s});this.collect.event(t,a),this.cleanEventTrack(t)}},r.prototype.trackEventPause=function(e){if(this.TrackEventMap.has(e)){var t=this.TrackEventMap.get(e);t.isPause||(t.isPause=!0,t.pauseTime=Date.now(),this.TrackEventMap.set(e,t))}},r.prototype.trackEventResume=function(e){if(this.TrackEventMap.has(e)){var t=this.TrackEventMap.get(e);t.isPause&&(t.isPause=!1,t.resumeTime=Date.now(),this.TrackEventMap.set(e,t))}},r.prototype.cleanEventTrack=function(e){this.TrackEventMap.delete(e)},r}();Ae.usePlugin(o_,"extend"),Ae.usePlugin(Lm,"et"),Ae.usePlugin(s_,"retry"),Ae.usePlugin(Mm,"ab"),Ae.usePlugin(Gm,"stay"),Ae.usePlugin(n_,"autotrack"),Ae.usePlugin(c_,"trackeventduration"),Ae.usePlugin(Bm,"heartbeat"),Ae.usePlugin(Fm,"monitor"),Ae.usePlugin(a_,"route"),Ae.usePlugin(i_,"tracer");var Or=new Ae("default");const Gi="VEPUSHER_DEVICE_ID",Bi="VEPUSHER_USER_ID",xa=r=>Math.floor((Math.random()*9+1)*Math.pow(10,r-1)).toString();function u_(r){const e={};if(!(r instanceof Object))throw new Error("params type error");for(const[t,n]of Object.entries(r))if(["string","number","boolean"].includes(typeof n))e[t]=n;else try{e[t]=JSON.stringify(n)}catch(i){console.error("serialize error",i)}return e}function d_(r){if(r)return localStorage.setItem(Bi,r),r;const e=localStorage.getItem(Bi);if(e)return e;const t=xa(12);return localStorage.setItem(Bi,t),r}function l_(r){if(r)return localStorage.setItem(Gi,r),r;const e=localStorage.getItem(Gi);if(e)return e;const t=xa(11);return localStorage.setItem(Gi,t),t}class h_{constructor({showLogInConsole:e=!1}){this._showLogInConsole=!1,this.markCollectTeaEventReady=()=>{this.isReady=!0,Or.start(),this.queueTeaEvent.forEach(t=>this.sendTeaEvent(...t)),this.queueTeaEvent=[]},this.configTea=(t,n)=>{const i={...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.91",...n}};Or.config(i),this.markCollectTeaEventReady()},this.isReady=!1,this.queueTeaEvent=[],Or.init({app_id:778494,channel:"sg"}),this._showLogInConsole=e}sendTeaEvent(e,t,n=!1){if(e)if(this.isReady)try{const i={...u_(t||{})};Or.event(e,i),this._showLogInConsole&&!n&&console.log("[VePusher logger]:",e,i)}catch(i){console.error(i)}else this._showLogInConsole&&!n&&console.log("[VePusher logger]:",e,t),this.queueTeaEvent.push([e,t])}getIsReady(){return this.isReady}getRawTea(){return Or}}let Pr;function p_({showLogInConsole:r}){Pr=new h_({showLogInConsole:r})}function V(r,e,t=!1){Pr&&Pr.sendTeaEvent(r,e,t)}function f_(r,e){Pr&&Pr.configTea(r,e)}const j={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 $t(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 m_ extends it{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:n,frameRate:i}=Vt(hs,"video"),{sampleRate:s}=Vt(ps,"audio");this._videoConstraints={width:t,height:n,frameRate:i},this._audioConstraints={sampleRate:s,enableAutoGainControl:!0,enableNoiseSuppression:!0,enableEchoCancellation:!0},this._livePusher=e}_notifyCaptured(e){this.emit(Ge.DeviceCaptured,e)}_notifyStopCapture(e){this.emit(Ge.DeviceStopCapture,e)}_bindStreamEvent(e){e.bindTrackEnd(()=>{this.emit(Ge.Interrupted,e),this.stopCapture({streamId:e.id,type:e.type})})}_handleError(e,t){const n=new Ft(t,e.message);this.emit(Ge.Error,n)}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 Gu(e?[e]:["audioinput","videoinput"]);return V(j.GET_DEVICES_RESULT,{type:e,is_success:!0,devices:t}),t}catch(t){return V(j.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 n;switch(t){case Y.Camera:n="_cameraStreams";break;case Y.Screen:n="_screenStreams";break;case Y.VideoFile:n="_videoFileStreams";break;case Y.Microphone:n="_microphoneStreams";break;case Y.AudioFile:n="_audioFileStreams";break;case Y.Image:n="_imageStreams";break;case Y.CustomVideo:n="_customVideoStreams";break;case Y.CustomAudio:n="_customAudioStreams";break}if(n){let i=[];if(e){const s=this[n][e];i.push(s)}else i=et(this[n]);V(j.STOP_CAPTURE,{stream_id:e,type:t,number:i.length}),i.forEach(s=>{this._notifyStopCapture(s),s.destroy(),delete this[n][s.id]})}}async startCameraCapture(e){let t={};rf.includes(e)?t={facingMode:e}:t={deviceId:e};const n={...t,...this._videoConstraints};try{const i=await Bu(n,!this._livePusher.isEnableMixing),s=new hd(i);return this._cameraStreams[s.id]=s,this._notifyCaptured(s),this._bindStreamEvent(s),V(j.CAMERA_CAPTURE_RESULT,{is_success:!0,stream_id:s.id,device_id:e,capture_params:n}),s.id}catch(i){throw V(j.CAMERA_CAPTURE_RESULT,{is_success:!1,device_id:e,capture_params:n,...$t(i)}),this._handleError(i,Ee.OPEN_CAMERA_FAILED),i}}async startMicrophoneCapture(e){const t={...this._audioConstraints,deviceId:e};try{const n=await Vu(t),i=new Jp(n);return this._microphoneStreams[i.id]=i,this._notifyCaptured(i),this._bindStreamEvent(i),V(j.MICROPHONE_CAPTURE_RESULT,{is_success:!0,stream_id:i.id,device_id:e,capture_params:t}),i.id}catch(n){throw V(j.MICROPHONE_CAPTURE_RESULT,{is_success:!1,device_id:e,capture_params:t,...$t(n)}),this._handleError(n,Ee.OPEN_MICROPHONE_FAILED),n}}async startScreenCapture(e){const t={audio:e,video:this._videoConstraints};try{const n=await ju(t,void 0,!this._livePusher.isEnableMixing),i=new Zp(n);return this._screenStreams[i.id]=i,this._notifyCaptured(i),this._bindStreamEvent(i),V(j.SCREEN_CAPTURE_RESULT,{is_success:!0,stream_id:i.id,capture_params:t}),i.id}catch(n){throw V(j.SCREEN_CAPTURE_RESULT,{is_success:!1,capture_params:t,...$t(n)}),this._handleError(n,Ee.OPEN_SCREEN_FAILED),n}}async startVideoFileCapture(e){try{const t=await zs({url:e,video:!0,audio:!0,loop:!0}),n=new Xp(t);return this._videoFileStreams[n.id]=n,this._notifyCaptured(n),this._bindStreamEvent(n),V(j.VIDEO_FILE_CAPTURE_RESULT,{is_success:!0,stream_id:n.id,file_url:e}),n.id}catch(t){throw this._handleError(t,Ee.VIDEO_FILE_CAPTURE_FAILED),V(j.VIDEO_FILE_CAPTURE_RESULT,{is_success:!1,file_url:e,...$t(t)}),t}}async startAudioFileCapture(e){try{const t=await zs({url:e,video:!1,audio:!0,loop:!0}),n=new Yp(t);return this._audioFileStreams[n.id]=n,this._notifyCaptured(n),this._bindStreamEvent(n),V(j.AUDIO_FILE_CAPTURE_RESULT,{is_success:!0,stream_id:n.id,file_url:e}),n.id}catch(t){throw V(j.AUDIO_FILE_CAPTURE_RESULT,{is_success:!1,file_url:e,...$t(t)}),this._handleError(t,Ee.AUDIO_FILE_CAPTURE_FAILED),t}}async startImageCapture(e){try{const t=await Fu({url:e,width:0,height:0,frameRate:30}),n=new Qp(t);return this._imageStreams[n.id]=n,this._notifyCaptured(n),this._bindStreamEvent(n),V(j.IMAGE_FILE_CAPTURE_RESULT,{is_success:!0,stream_id:n.id,file_url:e}),n.id}catch(t){throw V(j.IMAGE_FILE_CAPTURE_RESULT,{is_success:!1,file_url:e,...$t(t)}),this._handleError(t,Ee.IMAGE_FILE_CAPTURE_FAILED),t}}startCustomVideoCapture(e){const t=qu(e);if(t){const n=new ef(t);return this._customVideoStreams[n.id]=n,this._notifyCaptured(n),this._bindStreamEvent(n),n.id}}startCustomAudioCapture(e){const t=$u(e);if(t){const n=new tf(t);return this._customAudioStreams[n.id]=n,this._notifyCaptured(n),this._bindStreamEvent(n),n.id}}async startVolumeDetect(e){const t=this.getStreamById(e);if(t)try{await t.startVolumeDetect(),V(j.VOLUME_DETECTOR_START_RESULT,{is_success:!0,stream_id:t.id})}catch(n){V(j.VOLUME_DETECTOR_START_RESULT,{is_success:!1,stream_id:t.id,error_message:n.message}),this._handleError(n,Ee.VOLUME_DETECT_FAILED)}}stopVolumeDetect(e){const t=this.getStreamById(e);t&&t.stopVolumeDetect()}getDefaultVideoStream(){return et(this._cameraStreams)[0]||et(this._screenStreams)[0]||et(this._videoFileStreams)[0]||et(this._imageStreams)[0]||et(this._customVideoStreams)[0]}getDefaultAudioStream(){return et(this._microphoneStreams)[0]||et(this._audioFileStreams)[0]||et(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(Y).forEach(e=>{this.stopCapture({type:e})})}}let lt=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 Fi{constructor({streamManagerController:e,composedStream:t,streamComposeController:n}){this._streamManagerController=e,this._composedStream=t,this._streamComposeController=n,this._active=!1,this.bindStreamManagerControllerEvent()}bindStreamManagerControllerEvent(){this._streamManagerController.on(Ge.DeviceCaptured,e=>{this._active&&this.onStreamCapture(e)}),this._streamManagerController.on(Ge.DeviceStopCapture,e=>{this._active&&this.onStreamStopCapture(e)})}getComposedStream(){return this._composedStream}enable(){this._active=!0}disable(){this._active=!1}}const Ia=new lt("SingleComposer");class __ extends Fi{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:n}){var i,s;if(this._active)try{await((s=(i=this._composedStream.videoStream)==null?void 0:i.videoTrack)==null?void 0:s.applyConstraints({width:{min:e,ideal:e},height:{min:t,ideal:t},frameRate:{min:n,ideal:n}}))}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(n=>{this._streamComposeController.removeAudioStream(n.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 n=this._streamManagerController.getDefaultVideoStream();n?this._handleVideoStreamCapture(n):Ia.error("all video stream stop capture")}}_handleAudioStreamStopCapture(e){this._streamComposeController.removeAudioStream(e.id)}getComposedStream(){return this._composedStream}}class g_ extends it{constructor(e,{width:t,height:n,x:i,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=n??e.height,this._rect.x=i??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 n=this._rect.width,i=this._rect.height;if(n===0&&i===0)return{width:0,height:0};if(n===0)return{height:i,width:e*(i/t)};if(i===0)return{width:n,height:t*(n/e)};const s=e/t,a=n/i;let o=n,d=i;return s>a?(o=n,d=2*Math.round(n/s/2)):s<a&&(o=2*Math.round(i*s/2),d=i),{width:o,height:d}}_bindVideoTrackSizeChange(){this._stream.on(ls.SizeChange,({width:e,height:t})=>{this.setBaseProps("sourceWidth",e),this.setBaseProps("sourceHeight",t)})}getViewNode(){var i;if(!this._stream)return;let e={width:this._rect.width,height:this._rect.height};this._rect.keepRatio&&(e=this._getPaintSize({elementWidth:this._stream.width,elementHeight:this._stream.height})),this._paintSize=e;const t=(i=this._stream.viewNode)==null?void 0:i.size(e.width,e.height);let n;return this._rect.mirrorType!==void 0&&this._rect.mirrorType!==os.None?n=t==null?void 0:t.mirror(this._rect.mirrorType):n=t,n=n==null?void 0:n.position(this._rect.x,this._rect.y),n}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 n=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}n&&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 za extends Nt{constructor(e){super({type:Y.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 v_=Object.defineProperty,y_=Object.getOwnPropertyDescriptor,Mr=(r,e,t,n)=>{for(var i=y_(e,t),s=r.length-1,a;s>=0;s--)(a=r[s])&&(i=a(e,t,i)||i);return i&&v_(e,t,i),i};const Oa=new lt("composition-composer");function Lr(r,e,t){const n=t.value;return t.value=function(...i){return this._active||Oa.error("composer is not active"),n.apply(this,i)},t}class Kt extends Fi{constructor(e){super(e),this._compositionViewConfig={width:1080,height:720,frameRate:30,backgroundColor:"#000000"},this._sprites=[],this._videoMixer=new ad}onStreamCapture(e){}onStreamStopCapture(e){e&&e.isVideoStream&&this.removeVideoStream(e.id)}enable(){var n;if(this._active)return;super.enable();const e=this._videoMixer.track(),t=this._mixedVideoStream;this._mixedVideoStream=new za(e),this._composedStream.setVideoStream(this._mixedVideoStream),t&&((n=t.videoTrack)==null?void 0:n.id)!==e.id&&t.destroy()}disable(){super.disable(),this._videoMixer.stop()}_updateSpriteToMixer(){const e=Ro(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,n)=>t.zOrder-n.zOrder),e.on("propsChange",t=>{Wp(t.zOrder)||(this._sprites=this._sprites.sort((n,i)=>n.zOrder-i.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 n=this._mixedVideoStream,i=this._videoMixer.updateFps();this._mixedVideoStream=new za(i),this._composedStream.setVideoStream(this._mixedVideoStream),n.destroy()}}getMixingConfig(){return this._compositionViewConfig}addVideoStream(e,t){if(!e.viewNode){Oa.error("have no viewNode for composition");return}e.audioTrack&&this._streamComposeController.addAudioStream({streamId:e.id,volume:100});const n=new g_(e,t);this._addSprite(n)}_updateSingleVideoStream(e){const t=e.streamId;if(!t)return;const n=this._sprites.find(i=>i.stream.id===t);n&&(n.height=e.height,n.width=e.width,n.x=e.x,n.y=e.y,n.zOrder=e.zOrder,n.keepRatio=e.keepRatio??!1,n.mirrorType=e.mirrorType)}updateVideoStream(e){e.forEach(t=>{this._updateSingleVideoStream(t)}),this._updateSpriteToMixer()}removeVideoStream(e){if(!e)return;const t=this._sprites.find(n=>n.stream.id===e);t&&this._removeSprite(t)}muteVideoStream(e){if(e){const t=this._sprites.find(n=>n.stream.id===e);t&&t.hide()}else this._sprites.forEach(t=>{t.hide()});this._updateSpriteToMixer()}unmuteVideoStream(e){if(e){const t=this._sprites.find(n=>n.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(n=>n.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()}}Mr([Lr],Kt.prototype,"addVideoStream"),Mr([Lr],Kt.prototype,"updateVideoStream"),Mr([Lr],Kt.prototype,"removeVideoStream"),Mr([Lr],Kt.prototype,"muteVideoStream"),Mr([Lr],Kt.prototype,"unmuteVideoStream");class S_ extends it{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 b_ extends Wr{constructor(e){super({type:Y.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 E_ extends Fi{constructor(e){super(e),this._spriteList=[],this._audioMixer=new Wu({keepAlive:!0})}onStreamCapture(e){}onStreamStopCapture(e){e&&this.removeAudioStream(e.id)}_updateSpriteToMixer(){const e=Ro(this._spriteList.map(t=>t.isMute?null:t.getMixerNode()));this._audioMixer.mix(e)}_updateSingleAudioStream(e){const{streamId:t,volume:n}=e,i=this._spriteList.find(s=>s.stream.id===t);i?n!==void 0&&(i.volume=n):console.error("can not find stream"+t)}enable(){super.enable();const e=this._audioMixer.track(),t=new b_(e);this._composedStream.setAudioStream(t),this._audioMixer.mix([])}addAudioStream(e,t){const n=new S_(e,t);this._spriteList.push(n),this._updateSpriteToMixer()}tryResume(){return this._audioMixer.resume()}removeAudioStream(e){const t=this._spriteList.find(n=>n.stream.id===e);t&&(this._spriteList=this._spriteList.filter(n=>n!==t),this._updateSpriteToMixer())}updateAudioStream(e){e.forEach(t=>{this._updateSingleAudioStream(t)}),this._updateSpriteToMixer()}muteAudioStream(e){if(e){const t=this._spriteList.find(n=>n.stream.id===e);t&&t.mute()}else this._spriteList.forEach(t=>{t.mute()});this._updateSpriteToMixer()}unmuteAudioStream(e){if(e){const t=this._spriteList.find(n=>n.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 C_ extends it{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(St.VideoStreamChange,e))}setAudioStream(e){var t;((t=this._audioStream)==null?void 0:t.id)!==e.id&&(this._audioStream=e,this.emit(St.AudioStreamChange,e))}get audioStream(){return this._audioStream}get videoStream(){return this._videoStream}get videoTrack(){var e;return(e=this._videoStream)==null?void 0:e.videoTrack}get audioTrack(){var e;return(e=this._audioStream)==null?void 0:e.audioTrack}}const w_=new lt("streamComposeController");class T_{constructor(e){this._streamManagerController=e,this._composedStream=new C_,this.singleComposer=new __({streamManagerController:this._streamManagerController,composedStream:this._composedStream,streamComposeController:this}),this.compositionComposer=new Kt({streamManagerController:this._streamManagerController,composedStream:this._composedStream,streamComposeController:this}),this.mixerComposer=new E_({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:n}){this.singleComposer.setVideoQuality({width:e,height:t,frameRate:n}),this.compositionComposer.setMixingConfig({width:e,height:t,frameRate:n})}setMixingConfig(e){this.compositionComposer.setMixingConfig(e)}getMixingConfig(){return this.compositionComposer.getMixingConfig()}addAudioStream(e){const t=this._streamManagerController.getStreamById(e.streamId);this.mixerComposer.addAudioStream(t,{volume:e.volume??100})}removeAudioStream(e){return this.mixerComposer.removeAudioStream(e)}updateAudioStream(e){this.mixerComposer.updateAudioStream(e)}addVideoStream(e){const t=this._streamManagerController.getVideoStream(e.streamId);if(!t){w_.error("can not find video stream"+e.streamId);return}this.compositionComposer.addVideoStream(t,e)}updateVideoStream(e){this.compositionComposer.updateVideoStream(e);const t=e.map(n=>({streamId:n.streamId,volume:n.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 Pa{constructor(e){this._hasBindComposedStreamEvent=!1,this._composedStream=e}bindComposedStreamEvent(){this._hasBindComposedStreamEvent||(this._composedStream.on(St.VideoStreamChange,this.handleVideoStreamChange),this._composedStream.on(St.AudioStreamChange,this.handleAudioStreamChange),this._hasBindComposedStreamEvent=!0)}unbindComposedStreamEvent(){this._hasBindComposedStreamEvent&&(this._composedStream.off(St.VideoStreamChange,this.handleVideoStreamChange),this._composedStream.off(St.AudioStreamChange,this.handleAudioStreamChange),this._hasBindComposedStreamEvent=!1)}}const Wt=new lt("PreviewConsumer");class k_ extends Pa{constructor(e,{streamConsumeController:t}){super(e),this._isPreviewing=!1,this._previewElement=null,this.handleAudioStreamChange=n=>{this.startPreview()},this.handleVideoStreamChange=n=>{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 n=document.createElement("video");n.style.width="100%",n.style.height="100%",n.autoplay=!0,n.playsInline=!0,n.setAttribute("webkit-playsinline",""),n.setAttribute("x5-playsinline",""),this._previewElement=n;const i={video:null,audio:null};n.addEventListener("loadeddata",()=>{const s=n.srcObject.getVideoTracks()[0],a=n.srcObject.getAudioTracks()[0];s&&s!==i.video&&(this._streamConsumeController.emit(se.CaptureFirstVideoFrame),i.video=s),a&&a!==i.audio&&(this._streamConsumeController.emit(se.CaptureFirstAudioFrame),i.audio=a)}),t.appendChild(n)}startPreview(){if(Wt.log("startPreview"),!this._previewElement){Wt.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(n=>{this._streamConsumeController.emit(se.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 n=e.srcObject||new MediaStream;n.getTracks().find(i=>i.id===t.id)||(t.kind==="audio"&&n.getTracks().forEach(i=>{i.kind==="audio"&&(Wt.log(`remove preview track, ${i.label}, readyState=${i.readyState}`),n.removeTrack(i))}),t.kind==="video"&&n.getTracks().forEach(i=>{i.kind==="video"&&(n.removeTrack(i),Wt.log(`remove preview track, ${i.label}, readyState=${i.readyState}`))}),n.addTrack(t),e.srcObject?e.load():e.srcObject=n)}_removeTrack(e,t){if(!e)return;const n=e.srcObject;n&&(n.getTracks().forEach(i=>{(i.id===(t==null?void 0:t.id)||i.readyState==="ended")&&(Wt.log(`remove preview track ${i.label}`),n.removeTrack(i))}),n.getTracks().length===0&&(e.srcObject=null,Wt.log("set srcObject null")))}getPreviewElement(){if(this.isPreviewing)return this._previewElement}get isPreviewing(){return this._isPreviewing}}var Pe={},Vi={},ji={exports:{}},Ma;function Hi(){if(Ma)return ji.exports;Ma=1;var r=ji.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(n){n.reg||(n.reg=/(.*)/),n.format||(n.format="%s")})}),ji.exports}var La;function R_(){return La||(La=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 h=0;h<c.length;h+=1)o[h+1]!=null&&(d[c[h]]=e(o[h+1]))},n=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 h=o.push?{}:u?d[o.name]:d;t(c.match(o.reg),h,o.names,o.name),o.push&&d[o.push].push(h)},i=Hi(),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(h){var l=h[0],f=h.slice(2);l==="m"&&(c.push({rtp:[],fmtp:[]}),u=c[c.length-1]);for(var y=0;y<(i[l]||[]).length;y+=1){var C=i[l][y];if(C.reg.test(f))return n(C,u,f)}}),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,h=!1;return c[0]!=="~"?u=e(c):(u=e(c.substring(1,c.length)),h=!0),{scid:u,paused:h}})})}}(Vi)),Vi}var qi,Na;function A_(){if(Na)return qi;Na=1;var r=Hi(),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 h=d[o];switch(o+=1,u){case"%%":return"%";case"%s":return String(h);case"%d":return Number(h);case"%v":return""}})},n=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 h=0;h<o.names.length;h+=1){var l=o.names[h];o.name?u.push(d[o.name][l]):u.push(d[o.names[h]])}else u.push(d[o.name]);return t.apply(null,u)},i=["v","o","s","i","u","e","p","c","b","t","r","z","a"],s=["i","c","b","a"];return qi=function(a,o){o=o||{},a.version==null&&(a.version=0),a.name==null&&(a.name=" "),a.media.forEach(function(h){h.payloads==null&&(h.payloads="")});var d=o.outerOrder||i,c=o.innerOrder||s,u=[];return d.forEach(function(h){r[h].forEach(function(l){l.name in a&&a[l.name]!=null?u.push(n(h,l,a)):l.push in a&&a[l.push]!=null&&a[l.push].forEach(function(f){u.push(n(h,l,f))})})}),a.media.forEach(function(h){u.push(n("m",r.m[0],h)),c.forEach(function(l){r[l].forEach(function(f){f.name in h&&h[f.name]!=null?u.push(n(l,f,h)):f.push in h&&h[f.push]!=null&&h[f.push].forEach(function(y){u.push(n(l,f,y))})})})}),u.join(`\r
|
|
66
|
+
}`,t=document.head||document.getElementsByTagName("head")[0],n=document.createElement("style");n.appendChild(document.createTextNode(e)),t.appendChild(n);var i=document.createElement("div");i.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(i),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}(),Li={autotrack:{src:{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:{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:{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:{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:{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:{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:{sg:"https://lf-global-static.iapplogcdn.com/obj/applog-sdk-static-sg/log-sdk/collect/5/plugin/visual.js",va:"https://lf-global-static.iapplogcdn.com/obj/applog-sdk-static-us/log-sdk/collect/5/plugin/visual.js"},object:"LogVisual"}},Nm=["ab","autotrack","Stay","store","et","profile","cep","heartbeat","monitor","route","tracer"],Pe=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 lf,this.remotePlugin=new Map,this.Types=x,this.adapters.storage=Et,this.loadType="full"}return r.usePlugin=function(e,t,n){if(t){for(var i=!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=n||{},i=!0;break}i||r.plugins.push({name:t,plugin:e,options:n})}else r.plugins.push({plugin:e})},r.prototype.usePlugin=function(e,t,n){e&&(this.loadType==="full"&&Nm.includes(e)?console.info("your sdk version has "+e+" already ~"):t?typeof t=="string"?this.remotePlugin.get(e)||this.remotePlugin.set(e,{src:t,call:n}):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,n,i=this;try{t=JSON.parse(JSON.stringify(e))}catch{t=e}if(this.logger=new Rf(this.name,t.log),this.inited)this.logger.warn("[instance: "+this.name+"], every instance's api: init, can be call only one time!");else if(t&&ur(t))if(t.app_id&&typeof(n=t.app_id)=="number"&&!isNaN(n))if(!t.app_key||function(s){return typeof s=="string"}(t.app_key)){if(t.channel_domain||(t.report_channel!=="eu_ttp_ie"&&t.channel!=="ie"||this.logger.error("ie dc will be deprecated in the future, please use other dc instead"),t.report_channel&&!Lo().has(t.report_channel)?(this.logger.warn("your report_channel: "+t.report_channel+" is not exist. report_channel must be one of "+gi().join(",")+", use default report_channel: us_east instead, please check!!!"),t.report_channel="us_east"):t.report_channel||["sg","va","in","my","ie","ie2"].indexOf(t.channel)!==-1||(this.logger.warn("your channel: "+t.channel+" is not exist. use report_channel instead and report_channel must be one of "+gi().join(",")+", use default report_channel: us_east instead, please check!!!"),t.report_channel="us_east"),this.emit(T.DEBUGGER_MESSAGE,{type:T.DEBUGGER_MESSAGE_SDK,info:"SDK set channel warning",level:"error",time:Date.now(),data:"your report_channel: "+t.channel+" is not exist. report_channel must be one of "+gi().join(",")+", use us_east instead, please check!!!",infoType:"sdk"})),this.spider=new Af,this.spider.checkSpider(t))return this.logger.warn("The current environment may be a spider, can not report!"),void this.emit(T.DEBUGGER_MESSAGE,{type:T.DEBUGGER_MESSAGE_SDK,info:"SDK hit spider",level:"error",time:Date.now(),data:"The current environment may be a spider, can not report!",infoType:"sdk"});this.appBridge=new Df(this,t.enable_native),this.requestManager=new Mm(this,t),this.bridgeReport=this.appBridge.bridgeInject(),this.configManager=new kf(this,t),this.debugger=new Lm(this,t),this.initConfig=t,this.emit(x.Init),this.emit(T.DEBUGGER_MESSAGE,{type:T.DEBUGGER_MESSAGE_SDK,info:"SDK Execute Init",data:t,level:"info",time:Date.now(),infoType:"cus"}),t.disable_auto_pv&&(this.disableAutoPageView=!0),this.bridgeReport||(this.configManager.setAppid(t.app_id),this.eventManager=new If,this.tokenManager=new zf,this.sessionManager=new Pf,Promise.all([new Promise(function(s){i.once(x.TokenComplete,function(){s(!0)})}),new Promise(function(s){i.once(x.Start,function(){s(!0)})}),new Promise(function(s){i.once(x.LogSettingReady,function(){s(!0)})})]).then(function(){try{r.plugins.reduce(function(s,a){var o=a.plugin,d=a.options,c=Object.assign(i.initConfig,d);i.emit(T.DEBUGGER_MESSAGE,{type:T.DEBUGGER_MESSAGE_SDK,info:"SDK Load "+a.name+" Plugin",level:"info",time:Date.now(),infoType:"sdk"});var u=new o;return u.apply(i,c),s.push(u),s},i.pluginInstances)}catch(s){console.warn("load plugin error, "+s.message),i.emit(T.DEBUGGER_MESSAGE,{type:T.DEBUGGER_MESSAGE_SDK,info:"SDK Load Plugin Error",level:"error",time:Date.now(),data:s.message,infoType:"sdk"})}i.sdkReady=!0,i.emit(x.Ready),i.emit(T.DEBUGGER_MESSAGE,{type:T.DEBUGGER_MESSAGE_SDK,info:"SDK UserInfo Init Completed",time:Date.now(),secType:"USER",level:"info",data:i.configManager.get("user"),infoType:"sdk"}),i.emit(T.DEBUGGER_MESSAGE,{type:T.DEBUGGER_MESSAGE_SDK,info:"SDK Initialization Completed",time:Date.now(),level:"info",data:i.configManager.get("user"),infoType:"sdk"}),i.logger.info("appid: "+t.app_id+", userInfo:"+JSON.stringify(i.configManager.get("user"))),i.logger.info("appid: "+t.app_id+", sdk is ready, version is "+pr+", you can report now !!!"),t.disable_auto_pv&&(i.disableAutoPageView=!0);try{(i.loadType==="full"&&t.enable_ab_test||t.autotrack)&&(window.opener||window.parent).postMessage("[tea-sdk]ready","*")}catch(s){i.emit(T.DEBUGGER_MESSAGE,{type:T.DEBUGGER_MESSAGE_SDK,info:"Something Error",level:"error",time:Date.now(),data:s.message,infoType:"sdk"})}i.pageView(),i.on(x.TokenChange,function(s){s==="webid"&&i.pageView(),i.logger.info("appid: "+t.app_id+" token change, new userInfo:"+JSON.stringify(i.configManager.get("user"))),i.emit(T.DEBUGGER_MESSAGE,{type:T.DEBUGGER_MESSAGE_SDK,info:"SDK Set UserInfo",time:Date.now(),secType:"USER",level:"info",data:i.configManager.get("user"),infoType:"sdk"})}),i.on(x.TokenReset,function(){i.logger.info("appid: "+t.app_id+" token reset, new userInfo:"+JSON.stringify(i.configManager.get("user"))),i.emit(T.DEBUGGER_MESSAGE,{type:T.DEBUGGER_MESSAGE_SDK,info:"SDK Reset UserInfo",time:Date.now(),secType:"USER",level:"info",data:i.configManager.get("user"),infoType:"sdk"})}),i.on(x.RouteChange,function(s){s.init||t.disable_route_report||i.pageView()})}),this.tokenManager.apply(this,t),this.eventManager.apply(this,t),this.sessionManager.apply(this,t)),this.inited=!0}else this.logger.warn("app_key param is error, must be string, please check!");else this.logger.warn("app_id param is error, must be number, please check!");else 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(T.DEBUGGER_MESSAGE,{type:T.DEBUGGER_MESSAGE_SDK,info:"SDK Config Error",level:"error",time:Date.now(),data:"config must be use after function init",infoType:"sdk"});if(!e||!ur(e))return console.warn("config params is error, please check"),void this.emit(T.DEBUGGER_MESSAGE,{type:T.DEBUGGER_MESSAGE_SDK,info:"SDK Config Error",level:"error",time:Date.now(),data:"config params is error, please check",infoType:"sdk"});var t;try{t=JSON.parse(JSON.stringify(t))}catch{t=e}if(this.bridgeReport)this.appBridge.setConfig(t);else{t._staging_flag&&t._staging_flag===1&&(this.staging=!0),t.disable_auto_pv&&(this.disableAutoPageView=!0,delete t.disable_auto_pv);var n=ne({},t);if(this.initConfig&&this.initConfig.configPersist){var i=this.configManager.getStore();i&&(n=Object.assign(i,t)),this.configManager.setStore(t)}n.web_id,n.user_unique_id,n.device_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}(n,["web_id","user_unique_id","device_id"]);n.hasOwnProperty("web_id")&&this.emit(x.ConfigWebId,n.web_id),n.hasOwnProperty("user_unique_id")&&this.emit(x.ConfigUuid,n.user_unique_id),n.hasOwnProperty("device_id")&&this.emit(x.ConfigDiD,n.device_id),this.configManager.set(s),this.emit(T.DEBUGGER_MESSAGE,{type:T.DEBUGGER_MESSAGE_SDK,info:"SDK Execute Config",level:"info",time:Date.now(),data:n,infoType:"cus"})}},r.prototype.setDomain=function(e){this.configManager&&this.configManager.setDomain(e),this.emit(x.ConfigDomain)},r.prototype.getConfig=function(e){return this.configManager.get(e)},r.prototype.send=function(){this.start()},r.prototype.start=function(){this.inited&&!this.sended&&(this.sended=!0,this.emit(x.Start),this.emit(T.DEBUGGER_MESSAGE,{type:T.DEBUGGER_MESSAGE_SDK,info:"SDK Execute Start",level:"info",time:Date.now(),infoType:"cus"}),this.bridgeReport&&(this.pageView(),this.emit(x.Ready)))},r.prototype.event=function(e,t){var n=this;try{var i=[];if(Array.isArray(e))e.forEach(function(a){var o=n.processEvent(a[0],a[1]||{});o&&i.push(o)});else{var s=this.processEvent(e,t);if(!s)return;i.push(s)}this.bridgeReport?i.forEach(function(a){var o=a.event,d=a.params;n.appBridge.onEventV3(o,JSON.stringify(d))}):i.length&&(this.emit(x.Event,i),this.emit(x.SessionResetTime)),this.emit(T.DEBUGGER_MESSAGE,{type:T.DEBUGGER_MESSAGE_SDK,info:"SDK Execute Event",level:"info",time:Date.now(),data:e,infoType:"cus"})}catch(a){this.logger.warn("something error, please check"),this.emit(T.DEBUGGER_MESSAGE,{type:T.DEBUGGER_MESSAGE_SDK,info:"SDK Execute Event Something Error",level:"error",time:Date.now(),data:a.message,infoType:"sdk"})}},r.prototype.beconEvent=function(e,t){if(Array.isArray(e))return this.emit(T.DEBUGGER_MESSAGE,{type:T.DEBUGGER_MESSAGE_SDK,info:"SDK BeconEvent Error",level:"error",time:Date.now(),data:"beconEvent not support batch report, please check",infoType:"sdk"}),void this.logger.warn("beconEvent not support batch report, please check");var n=[],i=this.processEvent(e,t||{});i&&(n.push(i),n.length&&(this.emit(x.BeconEvent,n),this.emit(x.SessionResetTime)),this.emit(T.DEBUGGER_MESSAGE,{type:T.DEBUGGER_MESSAGE_SDK,info:"SDK Execute 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 n=e;/^event\./.test(e)&&(n=e.slice(6));var i=t;typeof i!="object"&&(i={}),i.profile?delete i.profile:i.event_index=hf();var s=void 0;return i.local_ms?(s=i.local_ms,delete i.local_ms):s=+new Date,{event:n,params:i,local_time_ms:s,is_bav:this.initConfig&&this.initConfig.autotrack?1:0}}catch(a){return this.emit(T.DEBUGGER_MESSAGE,{type:T.DEBUGGER_MESSAGE_SDK,info:"SDK Something Error",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,n){this.hook.emit(e,t,n)},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:location.pathname,time:Date.now(),referrer:window.document.referrer,$is_first_time:""+(this.configManager&&this.configManager.is_first_time||!1)},n=ne(ne({},t),e);this.emit(T.DEBUGGER_MESSAGE,{type:T.DEBUGGER_MESSAGE_SDK,info:"SDK Report PV",level:"info",time:Date.now(),infoType:"sdk"}),this.event("predefine_pageview",n)}else console.warn("predefinePageView should call after init")},r.prototype.clearEventCache=function(){this.emit(x.CleanEvents)},r.prototype.setWebId=function(e){this.config({web_id:""+e})},r.prototype.setNativeAppId=function(e){this.bridgeReport&&this.appBridge.setNativeAppId(e)},r.prototype.getSessionId=function(){return fr()},r.prototype.setSessionId=function(e){this.emit(x.SessionReset,e)},r.prototype.resetStayDuration=function(e,t,n){this.emit(x.ResetStay,{url_path:e,title:t,url:n},x.Stay)},r.prototype.resetStayParams=function(e,t,n){e===void 0&&(e=""),t===void 0&&(t=""),n===void 0&&(n=""),this.emit(x.SetStay,{url_path:e,title:t,url:n},x.Stay)},r.prototype.getToken=function(e,t){var n=this;if(this.inited){var i=!1,s=function(o){if(!i){i=!0;var d=n.configManager.get().user;return o&&(d.tobid=o,d["diss".split("").reverse().join("")]=o),e(ne({},d))}},a=function(){n.tokenManager.getTobId().then(function(o){s(o)})};this.emit(T.DEBUGGER_MESSAGE,{type:T.DEBUGGER_MESSAGE_SDK,info:"SDK Execute GetToken",level:"info",time:Date.now(),infoType:"cus"}),this.sdkReady?a():(t&&setTimeout(function(){s()},t),this.on(x.Ready,function(){a()}))}else console.warn("predefinePageView should call after init")},r.prototype.startTrackEvent=function(e){e&&this.emit(x.TrackEventDurationStart,e,x.TrackEventDuration)},r.prototype.endTrackEvent=function(e,t){t===void 0&&(t={}),e&&this.emit(x.TrackEventDurationEnd,{eventName:e,params:t},x.TrackEventDuration)},r.prototype.pauseTrackEvent=function(e){e&&this.emit(x.TrackEventDurationPause,e,x.TrackEventDuration)},r.prototype.resumeTrackEvent=function(e){e&&this.emit(x.TrackEventDurationResume,e,x.TrackEventDuration)},r.prototype.profileSet=function(e){this.bridgeReport?this.appBridge.profileSet(JSON.stringify(e)):this.emit(x.ProfileSet,e,x.Profile),this.emit(T.DEBUGGER_MESSAGE,{type:T.DEBUGGER_MESSAGE_SDK,info:"SDK Execute profileSet",level:"info",time:Date.now(),data:e})},r.prototype.profileSetOnce=function(e){this.bridgeReport?this.appBridge.profileSetOnce(JSON.stringify(e)):this.emit(x.ProfileSetOnce,e,x.Profile),this.emit(T.DEBUGGER_MESSAGE,{type:T.DEBUGGER_MESSAGE_SDK,info:"SDK Execute profileSetOnce",level:"info",time:Date.now(),data:e})},r.prototype.profileIncrement=function(e){this.bridgeReport?this.appBridge.profileIncrement(JSON.stringify(e)):this.emit(x.ProfileIncrement,e,x.Profile),this.emit(T.DEBUGGER_MESSAGE,{type:T.DEBUGGER_MESSAGE_SDK,info:"SDK Execute profileIncrement",level:"info",time:Date.now(),data:e})},r.prototype.profileUnset=function(e){this.bridgeReport?this.appBridge.profileUnset(e):this.emit(x.ProfileUnset,e,x.Profile),this.emit(T.DEBUGGER_MESSAGE,{type:T.DEBUGGER_MESSAGE_SDK,info:"SDK Execute profileUnset",level:"info",time:Date.now(),data:e})},r.prototype.profileAppend=function(e){this.bridgeReport?this.appBridge.profileAppend(JSON.stringify(e)):this.emit(x.ProfileAppend,e,x.Profile),this.emit(T.DEBUGGER_MESSAGE,{type:T.DEBUGGER_MESSAGE_SDK,info:"SDK Execute profileAppend",level:"info",time:Date.now(),data:e})},r.prototype.setExternalAbVersion=function(e){this.emit(x.AbExternalVersion,typeof e=="string"&&e?(""+e).trim():null,x.Ab)},r.prototype.getVar=function(e,t,n,i){this.emit(x.AbVar,{name:e,defaultValue:t,callback:n,uuid:i},x.Ab)},r.prototype.getABconfig=function(e,t){this.emit(x.AbConfig,{params:e,callback:t},x.Ab)},r.prototype.getABConfig=function(e,t){this.emit(x.AbConfig,{params:e,callback:t},x.Ab)},r.prototype.getAbSdkVersion=function(){return this.configManager.getAbVersion()},r.prototype.onAbSdkVersionChange=function(e){var t=this;return this.emit(x.AbVersionChangeOn,e,x.Ab),function(){t.emit(x.AbVersionChangeOff,e,x.Ab)}},r.prototype.offAbSdkVersionChange=function(e){this.emit(x.AbVersionChangeOff,e,x.Ab)},r.prototype.openOverlayer=function(){this.emit(x.AbOpenLayer,"",x.Ab)},r.prototype.closeOverlayer=function(){this.emit(x.AbCloseLayer,"",x.Ab)},r.prototype.getAllVars=function(e,t){this.emit(x.AbAllVars,{callback:e,timeout:t},x.Ab)},r.prototype.destoryInstace=function(){this.destroy||(this.destroy=!0,this.off(x.TokenComplete),this.emit(x.DestoryInstance))},r.prototype.destroyInstance=function(){this.destroy||(this.destroy=!0,this.off(x.TokenComplete),this.emit(x.DestoryInstance))},r.plugins=[],r}(),Dr={},ka=[];function Ra(r,e,t,n){var i=r&&r.source||window.opener||window.parent,s=r&&r.origin||n||window.location.origin,a={type:e,payload:t};i.postMessage(JSON.stringify(a),s)}function Um(r){if(ka.some(function(i){return r.origin.indexOf(i)>-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,n=e.payload;Dr[t]&&Dr[t].forEach(function(i){typeof i=="function"&&i(r,n)})}}var xr,Ni="__rangers_ab_style__";(function(r){r[r.Var=0]="Var",r[r.All=1]="All"})(xr||(xr={}));var Gm=function(){function r(){this.fetchStatus="no",this.refreshFetchStatus="no",this.versions=[],this.extVersions=[],this.mulilinkVersions=[],this.enable_multilink=!1,this.enable_ab_visual=!1,this.editMode=!1,this.callbacks=[],this.data={},this.changeListener=new Map,this.readyStatus=!1,this.exposureCache=[],this.fetchQueueMap=new Map}return r.prototype.apply=function(e,t){var n=this;if(this.collect=e,this.config=t,this.config.enable_ab_test){var i=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=t.disable_auto_ab,h=vi[t.channel||"sg"]||vi.sg,l=s||dr(h),f=e.adapters.storage;this.cacheStorgae=new f(!1),this.timeout=c||3e3,this.enable_multilink=i,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=l+"/service/2/abtest_config/",this.reportUrl=this.collect.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.fetchQueueMap=new Map;var y=this.collect.Types;this.types=y,this.collect.on(y.TokenChange,function(C){C==="uuid"&&n.readyStatus&&(n.clearCache(),n.fetchAB())}),this.collect.on(y.AbVar,function(C){var v=C.name,E=C.defaultValue,k=C.callback;n.getVar(v,E,k)}),this.collect.on(y.AbAllVars,function(C){var v=C.callback,E=C.timeout;n.getAllVars(v,E)}),this.collect.on(y.AbConfig,function(C){var v=C.params,E=C.callback;n.getABconfig(v,E)}),this.collect.on(y.AbExternalVersion,function(C){n.setExternalAbVersion(C)}),this.collect.on(y.AbOpenLayer,function(){n.openOverlayer()}),this.collect.on(y.AbCloseLayer,function(){n.closeOverlayer()}),this.collect.on(y.AbVersionChangeOn,function(C){n.changeListener.set(C,C)}),this.collect.on(y.AbVersionChangeOff,function(C){n.changeListener.get(C)&&n.changeListener.delete(C)}),this.loadMode(),(this.enable_ab_visual||this.enable_multilink)&&this.openOverlayer(this.config.multilink_timeout_ms||500),this.checkLocal(),this.ready("ab"),this.readyStatus||(!u&&this.fetchAB(),this.readyStatus=!0),this.collect.emit(y.AbReady)}},r.prototype.ready=function(e){var t=this;if(this.collect.set(e),this.collect.hook._hooksCache.hasOwnProperty(e)){var n=this.collect.hook._hooksCache[e];if(!Object.keys(n).length)return;var i=function(a){n[a].length&&n[a].forEach(function(o){t.collect.hook.emit(a,o)})};for(var s in n)i(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 n=e.scenario,i=e.href;n?(this.editMode=!0,t=n):!i||i.indexOf("datatester")===-1&&i.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,n=e.ab_ext_version,i=e.ab_version_multilink,s=(e.data,this.checkFromUrl());s?this.mulilinkVersions.push(s):this.mulilinkVersions=i||[],this.extVersions=n||[],this.versions=t||[];var a=this.versions.concat(this.extVersions);this.enable_multilink&&(a=a.concat(this.mulilinkVersions))},r.prototype.checkFromUrl=function(){var e=an(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,n,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 n!="function")throw new Error("getVar callback must be a function");var s={name:e,defaultValue:t,callback:n,type:xr.Var};this.collect.emit(T.DEBUGGER_MESSAGE,{type:T.DEBUGGER_MESSAGE_SDK,secType:"AB",info:"SDK Execute GetVar",level:"info",time:Date.now(),data:e,infoType:"cus"}),this.fetchStatus==="complete"&&this.refreshFetchStatus==="complete"?this.getRealVar(s,e,i):this.callbackMap.set(e,s)},r.prototype.setAbUuid=function(e,t){this.collect.configManager.setAbUuidCache(e,t)},r.prototype.getRealVar=function(e,t,n){var i=e.name,s=e.defaultValue,a=e.callback,o=this.data;if(o){var d=o[i];if(d&&ur(d)){var c=d.vid;return t==="$ab_url"?this.mulilinkVersions.includes(c)||this.mulilinkVersions.push(c):this.versions.includes(c)||this.versions.push(c),this.setAbUuid(c,n),this.updateVersions(),this.fechEvent(c,t||i,s,a,d.val),void this.collect.emit(T.DEBUGGER_MESSAGE,{type:T.DEBUGGER_MESSAGE_SDK,secType:"AB",info:"SDK Execute GetVar, Exposure Experiment "+i,level:"info",time:Date.now(),data:o[i],infoType:"sdk"})}this.collect.emit(T.DEBUGGER_MESSAGE,{type:T.DEBUGGER_MESSAGE_SDK,secType:"AB",info:"SDK Execute GerVar Default Callback",level:"info",time:Date.now(),data:this.data,infoType:"sdk"}),a(s)}else a(s)},r.prototype.getAllVars=function(e,t){var n=this;if(typeof e!="function")throw new Error("getAllVars callback must be a function");var i=null,s={callback:e,type:xr.All,timer:i};this.collect.emit(T.DEBUGGER_MESSAGE,{type:T.DEBUGGER_MESSAGE_SDK,secType:"AB",info:"SDK Execute GetAllVars",level:"info",time:Date.now(),infoType:"cus"}),t&&(i=setTimeout(function(){s.timer=null,n.getRealAllVars(s),clearTimeout(i)},t),s.timer=i),this.fetchStatus==="complete"&&this.refreshFetchStatus==="complete"?(s.timer=null,this.getRealAllVars(s),i&&clearTimeout(i)):this.callbackMap.set("allVars",s)},r.prototype.getRealAllVars=function(e,t){var n=e.callback,i=e.timer;i&&(clearTimeout(i),e.timer=null);var s=(t??this.data)||{};try{n(JSON.parse(JSON.stringify(s)))}catch{n(s)}this.collect.emit(T.DEBUGGER_MESSAGE,{type:T.DEBUGGER_MESSAGE_SDK,secType:"AB",info:"SDK Execute GetAllVars Callback",level:"info",time:Date.now(),data:this.data,infoType:"sdk"})},r.prototype.fechEvent=function(e,t,n,i,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 h={event:"abtest_exposure",ab_sdk_version:""+e,params:JSON.stringify({app_id:this.config.appId,ab_url:t==="$ab_url"?n:window.location.href,data:this.data}),local_time_ms:Date.now()};o.custom=JSON.stringify(o.custom);var l={events:[h],user:d,header:o};this.reportExposure(l,t),i&&i(s)}catch(f){this.collect.emit(T.DEBUGGER_MESSAGE,{type:T.DEBUGGER_MESSAGE_SDK,info:"SDK Something Error",level:"error",time:Date.now(),data:f.message,infoType:"sdk"})}},r.prototype.reportExposure=function(e,t){var n=this;this.exposureCache.push(e),this.reportTimeout&&clearTimeout(this.reportTimeout),this.exposureCache.length>=this.exposureLimit?this.report(t):this.reportTimeout=setTimeout(function(){n.report(t),clearTimeout(n.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(n){t.collect.emit(T.DEBUGGER_MESSAGE,{type:T.DEBUGGER_MESSAGE_EVENT,info:"SDK Report Exposure Event Success",time:Date.now(),data:[n],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 n=Object.keys(e);n&&n.length&&this.collect.configManager.set(e),this.fetchAB(t)},r.prototype.get=function(e){return this.cacheStorgae.getItem(e)},r.prototype.set=function(e,t){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(Ni)){var i="body { opacity: 0 !important; }",s=document.head||document.getElementsByTagName("head")[0],a=document.createElement("style");a.id=Ni,a.type="text/css",a.styleSheet?a.styleSheet.cssText=i:a.appendChild(document.createTextNode(i)),s.appendChild(a)}}(),e)var n=setTimeout(function(){t.closeOverlayer(),clearTimeout(n)},e)},r.prototype.closeOverlayer=function(){var e;(e=document.getElementById(Ni))&&e.parentElement.removeChild(e)},r.prototype.fetchComplete=function(e,t){var n=this;this.changeFetchQueueStatus(t);try{if(e&&Object.prototype.toString.call(e)=="[object Object]"){var i=this.collect.configManager.get().user;if(t&&t!==i.user_unique_id)return;this.data=e,this.setAbCache(t);var s=[];Object.keys(e).forEach(function(u){var h=e[u].vid;h&&s.push(h)}),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}else if(a&&this.enable_multilink){this.mulilinkVersions=this.mulilinkVersions.filter(function(u){return s.includes(u)});var d=a.val,c=a.vid;d&&c&&this.getVar("$ab_url",d,function(){n.editMode||(d!==window.location.href?setTimeout(function(){if(!n.collect.destroy){var u=""+d;u=u.indexOf("http")===-1?"https://"+u:u,di(u).host!==location.host?u=u+"&vid="+c:window.history.replaceState("","",u),window.location.href=u}},100):n.closeOverlayer())})}this.updateVersions()}else this.closeOverlayer();this.callbackMap.forEach(function(u){u.type===xr.Var?n.getRealVar(u,""):n.getRealAllVars(u,e)})}catch{}},r.prototype.pushFetchToQueue=function(e){var t=e,n=this.fetchQueueMap.get(t);n?n.fetchStatus="ing":n={current_user_id:t,fetchStatus:"ing"},this.fetchQueueMap.set(t,n)},r.prototype.changeFetchQueueStatus=function(e){var t=this.fetchQueueMap.get(e);t&&(t.fetchStatus="complete",this.fetchQueueMap.set(e,t))},r.prototype.checkFetchQueueStatus=function(){if(this.fetchQueueMap.size===0)return!1;var e=!0;return this.fetchQueueMap.forEach(function(t){t.fetchStatus!=="complete"&&(e=!1)}),e},r.prototype.clearFetchQueue=function(e){this.fetchQueueMap.delete(e)},r.prototype.fetchAB=function(e){var t=this,n=this.collect.configManager.get(),i={header:ne(ne(ne({aid:this.config.app_id},n.user||{}),n.header||{}),{ab_sdk_version:this.collect.configManager.getAbVersion(),ab_url:window.location.href})};this.collect.emit(T.DEBUGGER_MESSAGE,{type:T.DEBUGGER_MESSAGE_SDK,info:"SDK Fetch AB Request",level:"info",logType:"fetch",time:Date.now(),data:i,infoType:"sdk"});var s=n.user[this.ab_user_mode]||n.user.user_unique_id;this.pushFetchToQueue(s),this.collect.requestManager.useRequest({url:this.fetchUrl,data:i,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(T.DEBUGGER_MESSAGE,{type:T.DEBUGGER_MESSAGE_SDK,secType:"AB",info:"SDK Fetch AB Request Success",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(T.DEBUGGER_MESSAGE,{type:T.DEBUGGER_MESSAGE_SDK,secType:"AB",info:"SDK Fetch AB Request Network Error",level:"error",logType:"fetch",time:Date.now(),infoType:"sdk"})},timeout:this.timeout})},r.prototype.filterUrl=function(e){try{var t="";e.indexOf("&multilink=true")!==-1?t="&multilink=true[\0-ÿ]*":e.indexOf("?multilink=true")!==-1&&(t="\\?multilink=true[\0-ÿ]*");var n=new RegExp(t,"g");e=e.replace(n,"")}catch{}return e},r}(),Bm=function(){function r(){}return r.prototype.apply=function(e,t){var n=this;if(this.collect=e,this.config=t,t.event_verify_url)if(typeof t.event_verify_url=="string"){if(this.url=t.event_verify_url+"/v1/list_test",this.url){var i=e.Types;e.on(i.SubmitVerify,function(s){n.verify(s)}),e.on(i.AbVerify,function(s){n.verify(s)})}}else console.log("please use correct et_test url")},r.prototype.verify=function(e){var t=this;e.forEach(function(n){try{var i=JSON.parse(JSON.stringify(n));t.config.filter&&((i=t.config.filter(i))||console.warn("filter must return data !!")),t.collect.eventFilter&&i&&((i=t.collect.eventFilter(i))||console.warn("filterEvent api must return data !!"));var s=i||n,a=JSON.parse(JSON.stringify(s));if(!s.length)return;var o=!0;if(s.forEach(function(d){d.events.length||(o=!1)}),!o)return;t.collect.requestManager.useBeacon({url:t.url,data:s}),t.collect.emit(T.DEBUGGER_MESSAGE,{type:T.DEBUGGER_MESSAGE_EVENT,info:"SDK Report ByteIo Verify Request",time:Date.now(),data:a,code:200,status:"success",verifyType:!0})}catch(d){console.warn("something error, "+JSON.stringify(d.stack)),t.collect.emit(T.DEBUGGER_MESSAGE,{type:T.DEBUGGER_MESSAGE_SDK,info:"SDK Report ByteIo Verify Request Error",level:"error",time:Date.now(),data:d.message})}})},r}(),Fm=function(){function r(e,t){this.maxDuration=432e5,this.aliveDTime=6e4,this.options={aliveName:"predefine_page_alive",params:{}},this.focusState=!0,this.collect=e,this.config=t,this.pageStartTime=Date.now(),this.sessionStartTime=this.pageStartTime,this.timerHandler=null,ur(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()}return r.prototype.setParams=function(e,t,n){this.set_path=e,this.set_url=n,this.set_title=t},r.prototype.enable=function(e,t,n){this.url_path=e,this.url=n,this.title=t,this.disableCallback=this.enablePageAlive(),this.hard&&(this.removeMode=this.hardMode())},r.prototype.disable=function(){this.disableCallback(),this.pageStartTime=Date.now()},r.prototype.sendEvent=function(e,t){t===void 0&&(t=!1);var n=t?this.aliveDTime:Date.now()-this.sessionStartTime;n<0||n>this.aliveDTime||Date.now()-this.pageStartTime>this.maxDuration||t&&document.visibilityState==="hidden"||this.hard&&!this.focusState||(this.collect.beconEvent(this.options.aliveName,ne({url_path:this.getParams("url_path"),title:this.getParams("title"),url:this.getParams("url"),duration:n,is_support_visibility_change:Po(),startTime:this.sessionStartTime,hidden:document.visibilityState,leave:e,mode:this.hard?"hard":"normal",focusState:this.focusState},this.options.params)),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(){document.visibilityState==="hidden"?this.timerHandler&&(clearInterval(this.timerHandler),this.sendEvent(!1)):document.visibilityState==="visible"&&(this.sessionStartTime=Date.now(),this.timerHandler=this.setUpTimer())},r.prototype.beforeunload=function(){document.hidden||this.sendEvent(!0)},r.prototype.enablePageAlive=function(){var e=this;this.timerHandler=this.setUpTimer();var t=this.visibilitychange.bind(this),n=this.beforeunload.bind(this);return document.addEventListener("visibilitychange",t),lr(n),function(){e.beforeunload(),document.removeEventListener("visibilitychange",t),window.removeEventListener("beforeunload",n),window.removeEventListener("pagehide",n)}},r.prototype.hardMode=function(){var e=this,t=function(){e.timerHandler&&(clearInterval(e.timerHandler),e.sendEvent(!1)),e.focusState=!1},n=function(){e.focusState=!0,e.sessionStartTime=Date.now(),e.timerHandler=e.setUpTimer()};return window.addEventListener("blur",t),window.addEventListener("focus",n),function(){window.removeEventListener("blur",t),window.removeEventListener("focus",n)}},r}(),Vm=function(){function r(e,t){var n=this;this.maxDuration=432e5,this.aliveDTime=6e4,this.options={closeName:"predefine_page_close",params:{}},this.focusState=!0,this.visibilitychange=function(){document.visibilityState==="hidden"?n.activeEndTime=Date.now():document.visibilityState==="visible"&&(n.activeEndTime&&(n.totalTime+=n.activeEndTime-n.activeStartTime,n.activeTimes+=1),n.activeEndTime=void 0,n.activeStartTime=Date.now())},this.beforeunload=function(){if(n.totalTime+=(n.activeEndTime||Date.now())-n.activeStartTime,n.config.autotrack)try{window.sessionStorage.setItem("_tea_cache_duration",JSON.stringify({duration:n.totalTime,page_title:document.title||location.pathname}))}catch{}n.sendEventPageClose()},this.collect=e,this.config=t,this.maxDuration=t.maxDuration||864e5,this.pageStartTime=Date.now(),ur(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,n){this.set_path=e,this.set_url=n,this.set_title=t},r.prototype.resetParams=function(e,t,n){this.url_path=e,this.url=n,this.title=t},r.prototype.enable=function(e,t,n){this.url_path=e,this.url=n,this.title=t,this.disableCallback=this.enablePageClose(),this.hard&&(this.removeMode=this.hardMode())},r.prototype.disable=function(){this.disableCallback()},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,ne({url_path:this.getParams("url_path"),title:this.getParams("title"),url:this.getParams("url"),active_times:this.activeTimes,duration:this.totalTime,total_duration:e,is_support_visibility_change:Po(),mode:this.hard?"hard":"normal",focusState:this.focusState},this.options.params)),this.pageStartTime=Date.now(),this.resetData())},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),n=this.beforeunload.bind(this);return document.addEventListener("visibilitychange",t),lr(n),function(){e.beforeunload(),document.removeEventListener("visibilitychange",t),window.removeEventListener("beforeunload",n),window.removeEventListener("pagehide",n)}},r.prototype.hardMode=function(){var e=this,t=function(){e.focusState=!1},n=function(){e.focusState=!0};return window.addEventListener("blur",t),window.addEventListener("focus",n),function(){window.removeEventListener("blur",t),window.removeEventListener("focus",n)}},r}(),jm=function(){function r(){}return r.prototype.apply=function(e,t){var n=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 Fm(e,t),this.pageClose=new Vm(e,t);var i=this.collect.Types;this.collect.on(i.ResetStay,function(s){var a=s.url_path,o=s.title,d=s.url;n.resetStayDuration(a,o,d)}),this.collect.on(i.RouteChange,function(s){s.init||t.disable_route_report||n.resetStayDuration()}),this.collect.on(i.SetStay,function(s){var a=s.url_path,o=s.title,d=s.url;n.setStayParmas(a,o,d)}),this.enable(this.url_path,this.title,this.url),this.ready(i.Stay),this.collect.emit(i.StayReady)}},r.prototype.ready=function(e){var t=this;if(this.collect.set(e),this.collect.hook._hooksCache.hasOwnProperty(e)){var n=this.collect.hook._hooksCache[e];if(!Object.keys(n).length)return;var i=function(a){n[a].length&&n[a].forEach(function(o){t.collect.hook.emit(a,o)})};for(var s in n)i(s)}},r.prototype.enable=function(e,t,n){this.pageAlive.enable(e,t,n),this.pageClose.enable(e,t,n)},r.prototype.disable=function(){this.pageAlive.disable(),this.pageClose.disable()},r.prototype.setStayParmas=function(e,t,n){e===void 0&&(e=""),t===void 0&&(t=""),n===void 0&&(n=""),this.pageAlive.setParams(e,t,n),this.pageClose.setParams(e,t,n),this.collect.emit(T.DEBUGGER_MESSAGE,{type:T.DEBUGGER_MESSAGE_SDK,info:"SDK Execute resetStayParams",level:"info",time:Date.now(),data:{url_path:e,title:t,url:n}})},r.prototype.reset=function(e,t,n){this.disable(),this.enable(e,t,n)},r.prototype.resetStayDuration=function(e,t,n){this.reset(e,t,n),this.collect.emit(T.DEBUGGER_MESSAGE,{type:T.DEBUGGER_MESSAGE_SDK,info:"SDK Execute resetStayDuration",level:"info",time:Date.now(),data:{url_path:e,title:t,url:n}})},r}(),Hm=function(){function r(){var e=this;this.setInterval=function(){e.clearIntervalFunc=function(t,n){t===void 0&&(t=function(){}),n===void 0&&(n=1e3);var i,s=Date.now()+n;return i=window.setTimeout(function a(){var o=Date.now()-s;t(),s+=n,i=window.setTimeout(a,Math.max(0,n-o))},n),function(){window.clearTimeout(i)}}(function(){e.isSessionhasEvent&&e.endCurrentSession()},e.sessionInterval)},this.clearInterval=function(){e.clearIntervalFunc&&e.clearIntervalFunc()}}return r.prototype.apply=function(e,t){var n=this;if(this.collect=e,!t.disable_heartbeat){this.sessionInterval=6e4,this.startTime=0,this.lastTime=0,this.setInterval();var i=this.collect.Types;this.collect.on(i.SessionReset,function(){n.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}(),qm=function(){function r(){}return r.prototype.apply=function(e,t){var n=this;if(this.collect=e,this.config=t,!this.config.channel_domain&&!t.disable_track_event&&!t.disable_sdk_monitor){this.url=e.configManager.getUrl("event");var i=this.collect.Types;this.collect.on(i.Ready,function(){n.sdkOnload()}),this.collect.on(i.SubmitError,function(s){var a=s.type,o=s.eventData,d=s.errorCode,c=s.response;a==="f_data"&&n.sdkError(o,d,c)}),this.collect.on(e.Types.SDKInnerError,function(s){var a=s.type,o=s.eventData,d=s.errorCode,c=s.msg;n.sdkInnerError(a,o,d,c)})}},r.prototype.sdkOnload=function(){var e=this;try{var t=this.collect.configManager.get(),n=t.header,i=t.user,s=n.app_id,a=n.app_name,o=n.sdk_version,d=(i.web_id,{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_OVERSEA",url:location.href,is_setting:this.config.enable_logsetting||!1,enable_logsetting_params:this.config.enable_logsetting_params||!1,enable_logsetting_header_custom:this.config.enable_logsetting_header_custom||!1}),local_time_ms:Date.now()}],user:{user_unique_id:i.user_unique_id},header:{app_id:6656}});setTimeout(function(){e.collect.requestManager.useRequest({url:e.url,data:[d],timeout:3e4,forceXhr:!0})},16)}catch{}},r.prototype.sdkError=function(e,t,n){var i=this;try{var s=e[0],a=s.user,o=s.header,d=[];e.forEach(function(u){u.events.forEach(function(h){d.push(h)})});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:n.m||""}),local_time_ms:Date.now()}}),user:{user_unique_id:a.user_unique_id},header:{app_id:6656}};setTimeout(function(){i.collect.requestManager.useRequest({url:i.url,data:[c],timeout:3e4,forceXhr:!0})},16)}catch{}},r.prototype.sdkInnerError=function(e,t,n,i){var s=this;try{var a=t[0],o=a.user,d=a.header,c=[];t.forEach(function(h){h.events.forEach(function(l){c.push(l)})});var u={events:c.map(function(h){return{event:"on_error",params:JSON.stringify({type:e,error_code:n,app_id:d.app_id,app_name:d.app_name||"",error_event:h.event,sdk_version:d.sdk_version,local_time_ms:h.local_time_ms,tea_event_index:Date.now(),params:h.params,header:d,user:o,ua:window.navigator.userAgent,err_msg:i}),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}();function Ui(r,e){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"))return!0;return!1}function Gi(r){for(var e=r;e&&!Ui(e,"container");){if(e.nodeName==="HTML"||e.nodeName==="BODY")return r;e=e.parentElement}return e||r}function Aa(r){var e="";return r.nodeType===3?e=r.textContent.trim():r.dataset&&r.dataset.hasOwnProperty("teaTitle")||r.hasAttribute("ata-tea-title")?e=r.getAttribute("data-tea-title"):r.hasAttribute("title")?e=r.getAttribute("title"):r.nodeName==="INPUT"&&["button","submit"].includes(r.getAttribute("type"))?e=r.getAttribute("value"):r.nodeName==="IMG"&&r.getAttribute("alt")&&(e=r.getAttribute("alt")),e.slice(0,200)}function Da(r){for(var e=r;e&&e.parentNode;){if(e.hasAttribute("data-tea-ignore"))return!0;if(e.nodeName==="HTML"||e.nodeName==="body")return!1;e=e.parentNode}return!1}var _n=function(r,e){return r.hasAttribute?r.hasAttribute(e):r.attributes?!(!r.attributes[e]||!r.attributes[e].specified):void 0},$m=function(r,e){if(typeof e=="string")return _n(r,e);if(ui(e)){for(var t=!1,n=0;n<e.length;n++)if(_n(r,e[n])){t=!0;break}return t}},Km=function(){function r(e,t,n){var i=this;this.statistics=!1,this.pageView=!1,this.clickEvent=function(s){(function(a,o){if(a.nodeType!==1||!o.svg&&function(c){if(c.tagName.toLowerCase()==="svg")return!0;for(var u=c.parentElement,h=!1;u;)u.tagName.toLowerCase()==="svg"?(u=null,h=!0):u=u.parentElement;return h}(a)||["HTML","BODY"].includes(a.tagName.toUpperCase()))return!1;var d=a;return d.style.display!=="none"&&(!!Ui(d,"container")||!(!function(c){if(c.children.length){var u=c.children;return![].slice.call(u).some(function(h){return h.children.length>0})}return!0}(d)&&!o.svg))})(s.target,i.options)&&i.eventHandel({eventType:"dom",eventName:"click"},s)},this.changeEvent=function(s){i.eventHandel({eventType:"dom",eventName:"change"},s)},this.submitEvent=function(s){i.eventHandel({eventType:"dom",eventName:"submit"},s)},this.getPageViewEvent=function(s,a){a&&a==="pushState"&&i.eventHandel({eventType:"dom",eventName:"beat"},ne({beat_type:0},s)),i.eventHandel({eventType:"dom",eventName:"page_view"},s)},this.getPageLoadEvent=function(s){i.eventHandel({eventType:"dom",eventName:"page_statistics"},{lcp:s})},this.config=n.getConfig().eventConfig,this.collect=t,this.options=e,this.beatTime=e.beat}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&&window.document.addEventListener("click",this.clickEvent,!0),this.config.change&&window.document.addEventListener("change",this.changeEvent,!0),this.config.submit&&window.document.addEventListener("submit",this.submitEvent,!0),this.config.pv){this.collect.on("route-change",function(d){var c=d.config,u=d.name;t.getPageViewEvent(c,u),t.pageView=!0});var n=setTimeout(function(){t.pageView||(t.getPageViewEvent(t.getDefaultConfig()),t.pageView=!0,clearTimeout(n))},2e3)}if(this.config.beat){try{document.readyState==="complete"?this.beatEvent(this.beatTime):window.addEventListener("load",function(){t.beatEvent(t.beatTime)});var i=0,s=null;window.addEventListener("scroll",function(){clearTimeout(s),s=setTimeout(a,500),i=document.documentElement.scrollTop||document.body.scrollTop});var a=function(){(document.documentElement.scrollTop||document.body.scrollTop)==i&&t.eventHandel({eventType:"dom",eventName:"beat"},{beat_type:1})}}catch{}try{var o=window.performance&&window.performance.getEntriesByType("paint");o&&o.length?(new PerformanceObserver(function(d){var c=d.getEntries(),u=c[c.length-1],h=u.renderTime||u.loadTime;t.statistics||(t.getPageLoadEvent(h),t.statistics=!0)}).observe({entryTypes:["largest-contentful-paint"]}),setTimeout(function(){t.statistics||(t.getPageLoadEvent(o[0].startTime||0),t.statistics=!0)},2e3)):this.getPageLoadEvent(0)}catch{this.getPageLoadEvent(0)}}}},r.prototype.removeListener=function(){window.document.removeEventListener("click",this.clickEvent,!0),window.document.removeEventListener("change",this.changeEvent,!0),window.document.removeEventListener("submit",this.submitEvent,!0)},r.prototype.beatEvent=function(e){var t=this;try{var n;this.eventHandel({eventType:"dom",eventName:"beat"},{beat_type:3}),this.beatTime&&(n=setInterval(function(){t.eventHandel({eventType:"dom",eventName:"beat"},{beat_type:2})},e)),lr(function(){t.eventHandel({eventType:"dom",eventName:"beat",eventSend:"becon"},{beat_type:0}),t.beatTime&&clearInterval(n)})}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}(),Wm={eventConfig:{mode:"proxy-capturing",submit:!1,click:!0,change:!1,pv:!0,beat:!0,hashTag:!1,impr:!1},scoutConfig:{mode:"xpath"}},Jm=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 Xm(r){for(var e=[];r.parentElement!==null;)e.push(r),r=r.parentElement;var t=[],n=[];return e.forEach(function(i){var s=function(d){if(d===null)return{str:"",index:0};var c=0,u=d.parentElement;if(u)for(var h=u.children,l=0;l<h.length&&h[l]!==d;l++)h[l].nodeName===d.nodeName&&c++;return{str:[d.nodeName.toLowerCase(),Ui(d,"list")?"[]":""].join(""),index:c}}(i),a=s.str,o=s.index;t.unshift(a),n.unshift(o)}),{element_path:"/"+t.join("/"),positions:n}}function Zm(r,e,t,n){var i={},s=function(R){if(R){var M=R.getBoundingClientRect(),N=M.width,U=M.height;return{left:M.left,top:M.top,element_width:N,element_height:U}}}(e),a=function(R,M){R===void 0&&(R={}),M===void 0&&(M={});var N=R.clientX,U=R.clientY,B=M.left,H=M.top,Y=N-B>=0?N-B:0,W=U-H>=0?U-H:0;return{touch_x:Math.floor(Y),touch_y:Math.floor(W)}}(r,s),o=s.element_width,d=s.element_height,c=a.touch_x,u=a.touch_y,h=Xm(e),l=h.element_path,f=h.positions,y=function(R){var M=Gi(R),N=[];return function U(B){var H=Aa(B);if(H&&N.indexOf(H)===-1&&N.push(H),B.childNodes.length>0)for(var Y=B.childNodes,W=0;W<Y.length;W++)Y[W].nodeType!==8&&U(Y[W])}(M),N}(e),C=window.performance.timing.navigationStart,v=Date.now()-C,E=f.map(function(R){return""+R}),k=null;if(window.TEAVisualEditor&&window.TEAVisualEditor.getOriginXpath&&(k=window.TEAVisualEditor.getOriginXpath({xpath:l,positions:E})),i.element_path=k&&k.xpath||l,i.positions=k&&k.positions||E,n&&!n.text&&(i.texts=y,i.element_title=function(R){var M=Gi(R),N="";return function U(B){var H=Aa(B);if(H&&(N+=H),B.childNodes.length>0)for(var Y=B.childNodes,W=0;W<Y.length;W++)Y[W].nodeType===3&&U(Y[W])}(M),N}(e)),i.element_id=e.getAttribute("id")||"",i.element_class_name=e.getAttribute("class")||"",i.element_type=e.nodeType,i.element_width=Math.floor(o),i.element_height=Math.floor(d),i.touch_x=c,i.touch_y=u,i.page_manual_key="",i.elememt_manual_key="",i.since_page_start_ms=v,i.page_start_ms=C,i.page_path=location.pathname,i.page_host=location.host,t.track_attr&&function(R,M){return!!$m(R,M)}(e,t.track_attr)){var g=function(R,M){var N={};if(typeof M=="string")_n(R,M)&&(N.attrs=R.getAttribute(M));else if(ui(M))for(var U=0;U<M.length;U++)_n(R,M[U])&&(N[M[U]]=R.getAttribute(M[U]));return N}(e,t.track_attr);for(var D in g)i[D]=g[D]}var L=Gi(e);return L.tagName==="A"&&(i.href=L.getAttribute("href")),e.tagName==="IMG"&&(i.src=e.getAttribute("src")),i}var Ir=function(r,e,t,n,i){return ne(ne({event:r},Zm(e,t,n,i)),{is_html:1,page_key:window.location.href,page_title:document.title})},Ym=function(){function r(e,t){this.ignore={text:!0},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"}:{click:"bav2b_click",page:"bav2b_page",beat:"bav2b_beat",static:"bav2b_page_statistics",exposure:"bav2b_exposure"},t&&t.text===!0&&(this.ignore.text=!1),t&&t.exposure&&t.exposure.eventName&&(this.eventName.exposure=t.exposure.eventName)}return r.prototype.handleEvent=function(e,t){try{if(Da(e.target))return null;var n="bav2b_click";switch(t){case"click":return n=e.target.getAttribute("data-applog-click-event")||this.eventName.click,Ir(n,e,e.target,this.options,this.ignore);case"change":return ne(ne({},Ir(n="bav2b_change",e,e.target,this.options)),function(i,s){try{if(i==="bav2b_change")return s.hasAttribute("data-tea-track")?{value:s.value}:{}}catch{return{}}}(n,e.target));case"submit":return Ir(n="bav2b_submit",e,e.target,this.options)}}catch(i){return console.error(i),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 n=JSON.parse(t);e.refer_page_duration_ms=n?n.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(i){console.log("page event error "+JSON.stringify(i))}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 n=e.lcp,i=window.performance.timing,s=i.loadEventEnd-i.navigationStart;t.page_init_cost_ms=parseInt(n||(s>0?s:0)),t.page_start_ms=i.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(Da(t.target))return null;var n=Ir(e.event||this.eventName.exposure,t,t.target||t,this.options,this.ignore);if(n.$exposure_type=e.exposureType,this.options.exposure.callback){var i=this.options.exposure.callback(n);return i||Object.keys(i).length?i:(console.warn("exposure callback must return data!"),n)}return n},r.prototype.handleScrollEvent=function(e,t){var n=Ir(e.event||this.eventName.scroll,t,t.target||t,this.options,this.ignore);if(n=Object.assign(n,e.params),!this.options.scroll.callback||(n=this.options.scroll.callback(n))||Object.keys(n).length)return n;console.warn("scroll callback must return data!")},r}(),Qm=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 n=e.eventSend,i=t.event;delete t.event,n&&n==="becon"?this.collect.beconEvent(i,t):this.collect.event(i,t)},r.prototype.get=function(e,t){var n=Object.assign({headers:{"content-type":"application/json"},method:"GET"},t);fetch(e,n)},r.prototype.post=function(e,t){var n=Object.assign({headers:{"content-type":"application/json"},method:"POST"},t);fetch(e,n)},r}(),Bi=!1;function e_(r){var e,t,n,i,s=r.event,a=r.editorUrl,o=r.autoTrackInstance;Bi||(Bi=!0,e=a,t=function(){Ra(s,"editorScriptloadSuccess"),o.destroy()},n=function(){s&&Ra(s,"editorScriptloadError"),Bi=!1},(i=document.createElement("script")).src=e,i.onerror=function(){n(e)},i.onload=function(){t()},document.getElementsByTagName("head")[0].appendChild(i))}function t_(r,e){window.TEAVisualEditor=window.TEAVisualEditor||{},window.TEAVisualEditor.appId=e.app_id;var t,n,i,s=e.channel_domain,a="";if((t=Cf).length&&t.forEach(function(l){ka.push(l)}),s){var o=void 0,d="";try{var c=window.performance.getEntriesByType("resource");if(c&&c.length&&(c.forEach(function(l){l.initiatorType==="script"&&l.name&&l.name.indexOf("collect")!==-1&&(d=l.name)}),d&&(o=d.split("/"))&&o.length)){a="https:/";for(var u=2;u<o.length&&u!==o.length-1;u++)a=a+"/"+o[u];if(a&&a.indexOf("/5.0")){var h=a.split("/5.0");a=h[0]||a}}}catch{}}window.addEventListener("message",Um,!1);try{i=function(l){var f=l.data.app_id;f&&f!==e.app_id||e_({event:l,editorUrl:"https://sf16-website-login.neutral.ttwstatic.com/obj/tiktok_web_login_static/log-sdk/collect/heatmap-core.js?query="+Date.now(),autoTrackInstance:r})},Dr[n="tea:openHeatMapCore"]=Dr[n]||[],Dr[n].push(i)}catch{console.log("openHeatMapCore error")}}var qe,r_=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(n){n.forEach(function(i){i.type==="attributes"&&e.attributeChangeObserve(i),i.type==="childList"&&e.modifyNodeObserve(i)})}),!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(n){n.nodeType===1&&n.hasAttribute("data-exposure")&&t.exposureAdd(n,"intersect"),t.mapChild(n,t.exposureAdd.bind(t))}),Array.prototype.forEach.call(e.removedNodes,function(n){n.nodeType===1&&n.hasAttribute("data-exposure")&&t.exposureRemove(n),t.mapChild(n,t.exposureRemove.bind(t))})},r.prototype.mapChild=function(e,t){var n=this;e.nodeType===1&&e.children.length&&Array.prototype.forEach.call(e.children,function(i){i.nodeType===1&&i.hasAttribute("data-exposure")&&t(i),n.mapChild(i,t)})},r.prototype.exposureAdd=function(e,t){try{this._intersection&&this._intersection.exposureAdd(e,t)}catch(n){console.log("intersection error",JSON.stringify(n.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"})(qe||(qe={}));var At,n_=function(){function r(e,t,n){var i=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=qe.NOT_EXPOSURE,this.eventHandle=n,this.hashMap=new Map,this.backStatus=!1,this.lastState=null,this.collect.on("re-start-sdk",function(){i.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=[],n=0;n<=1;n+=.01)t.push(n);t.push(1);try{r._observer_instance=new IntersectionObserver(function(i){i.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(h){console.log("IntersectionObserver setTimeout error,msg: "+JSON.stringify(h))}},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(i){console.log("IntersectionObserver error,msg: "+JSON.stringify(i))}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 n=t==="mutation"?e.target:e,i=n.observeId,s=un();if(i||this.observeMap.has(i)){var a=this.observeMap.get(i);if(a&&n!==a.instance)this.unobserve(n),this.observeMap.delete(i),n.observeId=s,n.visible=!1,this.observeMap.set(s,{instance:n.cloneNode(!0),isIntersecting:!1}),this.observe(n);else{if(n.visible===!0)return;this.handleBoundingExposure(n)}}else n.observeId=s,n.visible=!1,this.observeMap.set(s,{instance:n.cloneNode(!0),isIntersecting:!1}),this.observe(n)},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,n,i){if(t>=this.ratio){if(e.target.style.opacity==="0"||e.target.style.visibility==="hidden"||i.exposured===!0)return;i.startWait&&clearTimeout(i.startWait);var s=e.target.getAttribute("data-applog-exposure-event");this.eventHandle({eventType:"dom",eventName:"exposure",event:s,exposureType:this.getExposureType(e.target)},e),e.target.visible=!0,e.target.hasExposure=!0,i.startTime=Date.now(),i.exposured=!0}else i.startTime=Date.now(),i.exposured=!1;this.observeMap.set(n,i)},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||qe.RESUME_FORM_BACK},e)}},r.prototype.getBoundingRatio=function(e){var t=e.getBoundingClientRect(),n=t.top,i=t.left,s=t.width,a=t.height,o=window.innerWidth||document.documentElement.clientWidth,d=window.innerHeight||document.documentElement.clientHeight;return n>=0&&i>=0&&n<=d&&i<=o?(s>o?o:s)*(d-n)/(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=qe.RESUME_FORM_PAGE:this.exposureType=qe.LIFECYCLE_SHOW_NEW:(e.hasExposure,e.backStatus!==!1&&(this.backStatus||this.customType||window.performance.navigation.type===2)?this.exposureType=qe.RESUME_FORM_PAGE:this.exposureType=qe.EXPOSURE_ONCE),this.exposureType},r.prototype.addListen=function(){var e=this;this.collect.on("set-exposure-type",function(o){e.customType=o});var t,n,i,s,a=this.visibilitychange.bind(this);return t=document,n="visibilitychange",i=a,s=!1,t.addEventListener?t.addEventListener(n,i,s):t.attachEven?t.attachEven("on"+n,i):t["on"+n]=i,window.addEventListener("hashchange",function(o){var d=e.hashMap.get(o.oldURL);d&&location.href===d.prev?(e.backStatus=!0,e.exposureType=qe.RESUME_FORM_PAGE):(e.backStatus=!1,e.hashMap.set(location.href,{current:o.newURL,prev:o.oldURL}))}),this.collect.on("STATE_CHANGE",function(o){e.lastState=o}),window.addEventListener("popstate",function(o){var d=o.state;d&&d.current&&e.lastState&&e.lastState.back&&d.current===e.lastState.back?(e.backStatus=!0,e.exposureType=qe.RESUME_FORM_PAGE):e.backStatus=!1}),function(){(function(o,d,c,u){o.addEventListener?o.removeEventListener(d,c,u):o.attachEven&&o.detachEven("on"+d,c)})(document,"visibilitychange",a,!1)}},r._observer_instance=null,r._observer_map=new Map,r}(),i_=function(){function r(e,t,n){t.autotrack&&t.autotrack.exposure&&(this._intersection=new n_(e,t,n),this._observer=new r_(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 xa,s_=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(n){n.forEach(function(i){i.type==="childList"&&e.modifyNodeObserve(i)})});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(n){n.nodeType===1&&n.hasAttribute("data-scroll")&&t.scrollHandle(n),t.mapChild(n,t.scrollHandle.bind(t))}),Array.prototype.forEach.call(e.removedNodes,function(n){n.nodeType===1&&n.hasAttribute("data-scroll")&&t.scrollHandle(n,"remove"),t.mapChild(n,t.scrollHandle.bind(t))})},r.prototype.mapChild=function(e,t){var n=this;e.nodeType===1&&e.children.length&&Array.prototype.forEach.call(e.children,function(i){i.nodeType===1&&i.hasAttribute("data-scroll")&&t(i),n.mapChild(i,t)})},r.prototype.scrollHandle=function(e,t){var n=this;try{var i=e.scrollTop,s=e.scrollLeft,a=null,o=0,d=0,c=function(u){clearTimeout(a),a=setTimeout(function(){var y=e.scrollTop,C=e.scrollLeft,v=u.target&&u.target.getAttribute("data-scroll-event")||"";f===1||f===2?y===h&&(d=h-i,Math.abs(d)>=n.distance&&n.distance&&n.eventHandle({eventType:"dom",eventName:"scroll",event:v,params:{$direction:f,$offsetY:d,$offsetX:o}},u)):f!==3&&f!==4||C===l&&(o=l-s,Math.abs(o)>=n.distance&&n.distance&&n.eventHandle({eventType:"dom",eventName:"scroll",event:v,params:{$direction:f,$offsetY:d,$offsetX:o}},u)),i=h,s=l},100);var h=e.scrollTop,l=e.scrollLeft,f=At.NOT_SCROLL;h>i?f=At.SCROLL_DOWN:h<i?f=At.SCROLL_UP:l>s?f=At.SCROLL_LEFT:l<s&&(f=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}(),o_={hashTag:!1,impr:!1},a_=function(){function r(){}return r.prototype.apply=function(e,t){if(this.autoTrackStart=!1,this.collect=e,this.config=t,t.autotrack){var n=e.Types;this.ready(n.Autotrack),this.collect.emit(n.AutotrackReady)}},r.prototype.ready=function(e){this.collect.set(e);var t=this.config.autotrack;t=typeof t=="object"?t:{},t=Object.assign(o_,t),this.destroyed=!1,this.options=t,this.Config=new Jm(Wm,this.options),this.Exposure=new i_(this.collect,this.config,this.handle.bind(this)),this.Scroll=new s_(this.config,this.handle.bind(this)),this.Listener=new Km(t,this.collect,this.Config),this.EventHandle=new Ym(this.config,t),this.Request=new Qm(this.collect),this.autoTrackStart=!0,this.init(),t_(this,this.config)},r.prototype.init=function(){this.Listener.init(this.handle.bind(this)),this.collect.loadType==="base"&&(window.opener||window.parent).postMessage("[tea-sdk]ready","*")},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 n=e.eventName;if(n==="click"||n==="change"||n==="submit")(o=this.EventHandle.handleEvent(t,n))&&this.Request.send({eventType:"custom"},o);else if(n==="page_view"||n==="page_statistics"){var i=void 0;(i=n==="page_view"?this.EventHandle.handleViewEvent(t):this.EventHandle.handleStatisticsEvent(t))&&this.Request.send({eventType:"custom"},i)}else if(n==="beat"){var s=this.EventHandle.handleBeadtEvent(t),a=e.eventSend;s&&this.Request.send({eventType:"custom",eventSend:a},s)}else if(n==="exposure")(o=this.EventHandle.handleExposureEvent(e,t))&&this.Request.send({eventType:"custom"},o);else if(n==="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"})(xa||(xa={}));var Ia={pv:["predefine_pageview"],sdk:["_be_active","predefine_page_alive","predefine_page_close","__profile_set","__profile_set_once","__profile_increment","__profile_unset","__profile_append"],autotrack:["bav2b_click","bav2b_page","bav2b_beat","bav2b_page_statistics","__bav_click","__bav_page","__bav_beat","__bav_page_statistics"]},c_=function(){function r(){}return r.prototype.apply=function(e,t){var n=this;if(this.ready=t.app_id&&t.enable_tracer&&!t.disable_track_event,this.ready){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 i=this.collect.Types;e.adapters.fetch,this.collect.on(i.Event,function(s){ui(s)?s.forEach(function(a){n.addCount("log")}):n.addCount("log")}),this.collect.on(i.SubmitError,function(s){var a=s.type,o=s.eventDate,d=s.errorCode,c=s.response;n.addErrorCount(o,a,d,c)}),this.listener(),this.collect.emit(i.TracerReady)}},r.prototype.addCount=function(e,t,n){t===void 0&&(t="net"),n===void 0&&(n=1);try{this.tracerCache||(this.tracerCache=new Map);var i=void 0;if(this.tracerCache.has(e))(s=this.tracerCache.get(e)).has(t)?(i=s.get(t).params.count,i++,s.set(t,this.processTracer(i,e,t))):(i=n,s.set(t,this.processTracer(n,e,t)));else{var s=new Map;i=n,s.set(t,this.processTracer(n,e,t)),this.tracerCache.set(e,s)}t==="net"&&i>=this.limit[e]&&this.report(!1)}catch(a){console.log(a)}},r.prototype.addErrorCount=function(e,t,n,i){var s=this;try{if(e&&e.length){var a=e[0].events;a&&a.length&&(t==="f_data"?(i&&i.hasOwnProperty("sc")?this.addCount("log",t,a.length-i.sc):this.addCount("log",t,a.length),this.errorCode[t]=n):a.forEach(function(o){var d="log";for(var c in Ia)if(Ia[c].indexOf(o.event)!==-1){d=c;break}s.addCount(d,t,1),s.errorCode[t]=n}))}}catch{}},r.prototype.report=function(e){if(this.tracerCache){var t=[];this.tracerCache.forEach(function(n){console.log(n),n.forEach(function(i){t.push(i)})}),t&&t.length&&this.sendTracer(t,e)}},r.prototype.sendTracer=function(e,t){try{var n=this.collect.eventManager.merge(e);this.collect.requestManager.useRequest({url:this.reportUrl,data:n,useBeacon:t}),this.tracerCache=null}catch{}},r.prototype.processTracer=function(e,t,n){try{var i={count:e,state:n,key:t,params_for_special:"applog_trace",aid:this.appid,platform:"web",_staging_flag:1,sdk_version:pr};n!=="f_net"&&n!=="f_data"||(i.errorCode=this.errorCode[n]);var s=this.collect.processEvent("applog_trace",i);if(s&&s.event)return delete s.is_bav,s}catch{console.warn("something error")}},r.prototype.listener=function(){var e=this;document.addEventListener("visibilitychange",function(){document.visibilityState==="hidden"&&e.leavePage()}),lr(function(){e.leavePage()})},r.prototype.leavePage=function(){this.report(!0)},r}(),u_=function(){function r(){this.retryWaitTime=3e3,this.retryStatus=!1,this.retryCacheStatus=!1}return r.prototype.apply=function(e,t){var n=this;if(t.enable_storage&&!t.disable_storage&&(this.collect=e,this.config=t,!this.collect.destroy)){var i=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(i.SubmitError,function(a){a.type!=="f_data"&&n.storeData(a)}),e.on(i.Ready,function(){n.checkStorage()})}},r.prototype.retryRightNow=function(e){var t=this;if(this.retryStatus)this.errorCache.push(e);else{var n=0;this.retryStatus=!0;var i=setInterval(function(){if(n===3)return t.storeData(t.errorCache),t.retryStatus=!1,void clearInterval(i);var s=e.eventData;t.fetchData(s,function(){t.retryStatus=!1,clearInterval(i),t.retryCacheStatus&&t.errorCache.splice(0,1),t.errorCache.length&&(t.retryCacheStatus=!0,t.retryRightNow(t.errorCache[0]))},function(){n++})},this.retryInterval)}},r.prototype.storeData=function(e){var t=this.storage.getItem(this.eventKey),n=e.eventData;Object.keys(t).length!==this.storageNum&&(t[Date.now()]=n,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 n={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([n],function(){var i=JSON.parse(JSON.stringify(t)),s=function(o){e.fetchData(t[o],function(){delete i[o],e.storage.setItem(e.eventKey,i)},function(){},!1)};for(var a in t)s(a)},function(){},!0)}catch{console.warn("error check storage")}},r.prototype.fetchData=function(e,t,n,i){this.collect.requestManager.useRequest({url:this.eventUrl,data:e,timeout:3e4,success:t,fail:n,app_key:i?"566f58151b0ed37e":""})},r}(),Fi=typeof window<"u"?(window.LogPluginObject||(window.LogPluginObject={}),window.LogPluginObject):null,d_=function(){function r(){}return r.prototype.apply=function(e,t){this._plugin={},this.config=t,this.collect=e,this.channel="va",this.loadExtend()},r.prototype.loadExtend=function(){var e=this;try{this.collect.remotePlugin.forEach(function(t,n){if(t==="sdk")if(Li.hasOwnProperty(n)){var i=Li[n].object,s=""+Li[n].src[e.channel];e.exist(n,i,s)}else console.warn("your "+n+" is not exist,please check plugin name");else typeof t=="object"&&(t.src?e.exist(n,t.call,t.src):e.process(n,t.instance,"INSTANCE"))})}catch(t){this.collect.emit(T.DEBUGGER_MESSAGE,{type:T.DEBUGGER_MESSAGE_SDK,info:"LoadExtend Fail",level:"error",time:Date.now(),data:t.message}),console.log("load extend error")}},r.prototype.exist=function(e,t,n){var i=this;Fi[t]?(this.process(e,Fi[t]),console.log("already has "+e+" plugin~")):this.loadPlugin(e,n,function(){i.process(e,Fi[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,n){try{if(n){var i=new t;i.apply&&i.apply(this.collect,this.config),console.log("excude "+e+" success")}else t&&t(this.collect,this.config)}catch(s){this.collect.emit(T.DEBUGGER_MESSAGE,{type:T.DEBUGGER_MESSAGE_SDK,info:"Extend Process Fail",level:"error",time:Date.now(),data:s.message}),console.log("excude "+e+" error, message:"+s.message)}},r.prototype.loadPlugin=function(e,t,n,i){var s=this;try{var a=document.createElement("script");a.src=t,this._plugin[e]||(this._plugin[e]=[]),this._plugin[e].push(n),a.onerror=function(){i(t)},a.onload=function(){s._plugin[e].forEach(function(o){o()})},document.getElementsByTagName("head")[0].appendChild(a)}catch(o){this.collect.emit(T.DEBUGGER_MESSAGE,{type:T.DEBUGGER_MESSAGE_SDK,info:"Extend LoadPlugin Fail",level:"error",time:Date.now(),data:o.message})}},r}(),l_=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 n=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(n.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(i){for(var s=[],a=1;a<arguments.length;a++)s[a-1]=arguments[a];typeof history.onpushstate=="function"&&history.onpushstate({state:i});var o=t.call.apply(t,cr([history,i],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 n=history.replaceState;history.replaceState=function(i){for(var s=[],a=1;a<arguments.length;a++)s[a-1]=arguments[a];typeof history.onreplacestate=="function"&&history.onreplacestate({state:i});var o=n.call.apply(n,cr([history,i],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 n=e.getPopStateChangeEventData();e.sendPv(n)}}),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 n=e.getPopStateChangeEventData();e.sendPv(n)}})},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,n=this.storage.getItem("__tea_cache_first_"+this.appid);return t=!n||n!=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(i){return this.collect.emit(T.DEBUGGER_MESSAGE,{type:T.DEBUGGER_MESSAGE_SDK,info:"something error",level:"error",time:Date.now(),data:i.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)||{},n=this.removeQuery(e);t.refer_key=n,t.routeChange=!0,this.storage.setItem(this.cache_key,t)},r}(),h_=function(){function r(){}return r.prototype.apply=function(e,t){var n=this;this.collect=e,this.config=t;var i=e.Types;e.on(i.TrackDurationStart,function(s){n.trackEventStart(s)}),e.on(i.TrackDurationEnd,function(s){n.trackEventEnd(s)}),e.on(i.TrackDurationPause,function(s){n.trackEventPause(s)}),e.on(i.TrackDurationResume,function(s){n.trackEventResume(s)}),this.Types=i,this.TrackEventMap=new Map,this.ready(i.TrackDuration)},r.prototype.ready=function(e){var t=this;if(this.collect.set(e),this.collect.hook._hooksCache.hasOwnProperty(e)){var n=this.collect.hook._hooksCache[e];if(!Object.keys(n).length)return;var i=function(a){n[a].length&&n[a].forEach(function(o){t.collect.hook.emit(a,o)})};for(var s in n)i(s)}},r.prototype.trackEventStart=function(e){this.TrackEventMap.set(e,{startTime:Date.now(),isPause:!1,pauseTime:0,resumeTime:0})},r.prototype.trackEventEnd=function(e){var t=e.eventName,n=e.params;if(this.TrackEventMap.has(t)){var i=this.TrackEventMap.get(t),s=0;s=i.isPause?i.pauseTime-i.startTime:i.resumeTime?i.pauseTime-i.startTime+(Date.now()-i.resumeTime):Date.now()-i.startTime;var a=Object.assign(n,{event_duration:s});this.collect.event(t,a),this.cleanEventTrack(t)}},r.prototype.trackEventPause=function(e){if(this.TrackEventMap.has(e)){var t=this.TrackEventMap.get(e);t.isPause||(t.isPause=!0,t.pauseTime=Date.now(),this.TrackEventMap.set(e,t))}},r.prototype.trackEventResume=function(e){if(this.TrackEventMap.has(e)){var t=this.TrackEventMap.get(e);t.isPause&&(t.isPause=!1,t.resumeTime=Date.now(),this.TrackEventMap.set(e,t))}},r.prototype.cleanEventTrack=function(e){this.TrackEventMap.delete(e)},r}();Pe.usePlugin(d_,"extend"),Pe.usePlugin(Bm,"et"),Pe.usePlugin(u_,"retry"),Pe.usePlugin(Gm,"ab"),Pe.usePlugin(jm,"stay"),Pe.usePlugin(a_,"autotrack"),Pe.usePlugin(h_,"trackeventduration"),Pe.usePlugin(Hm,"heartbeat"),Pe.usePlugin(qm,"monitor"),Pe.usePlugin(l_,"route"),Pe.usePlugin(c_,"tracer");var zr=new Pe("default");const Vi="VEPUSHER_DEVICE_ID",ji="VEPUSHER_USER_ID",za=r=>Math.floor((Math.random()*9+1)*Math.pow(10,r-1)).toString();function p_(r){const e={};if(!(r instanceof Object))throw new Error("params type error");for(const[t,n]of Object.entries(r))if(["string","number","boolean"].includes(typeof n))e[t]=n;else try{e[t]=JSON.stringify(n)}catch(i){console.error("serialize error",i)}return e}function f_(r){if(r)return localStorage.setItem(ji,r),r;const e=localStorage.getItem(ji);if(e)return e;const t=za(12);return localStorage.setItem(ji,t),r}function m_(r){if(r)return localStorage.setItem(Vi,r),r;const e=localStorage.getItem(Vi);if(e)return e;const t=za(11);return localStorage.setItem(Vi,t),t}class __{constructor({showLogInConsole:e=!1}){this._showLogInConsole=!1,this.markCollectTeaEventReady=()=>{this.isReady=!0,zr.start(),this.queueTeaEvent.forEach(t=>this.sendTeaEvent(...t)),this.queueTeaEvent=[]},this.configTea=(t,n)=>{const i={...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.92",...n}};zr.config(i),this.markCollectTeaEventReady()},this.isReady=!1,this.queueTeaEvent=[],zr.init({app_id:778494,channel:"sg"}),this._showLogInConsole=e}sendTeaEvent(e,t,n=!1){if(e)if(this.isReady)try{const i={...p_(t||{})};zr.event(e,i),this._showLogInConsole&&!n&&console.log("[VePusher logger]:",e,i)}catch(i){console.error(i)}else this._showLogInConsole&&!n&&console.log("[VePusher logger]:",e,t),this.queueTeaEvent.push([e,t])}getIsReady(){return this.isReady}getRawTea(){return zr}}let Pr;function g_({showLogInConsole:r}){Pr=new __({showLogInConsole:r})}function V(r,e,t=!1){Pr&&Pr.sendTeaEvent(r,e,t)}function v_(r,e){Pr&&Pr.configTea(r,e)}const j={PUSHER_INIT:"pusher_init",SET_PROPERTY_CALL:"set_property_call",SET_VIDEO_QUALITY:"set_video_quality",SET_AUDIO_QUALITY:"set_audio_quality",...{GET_DEVICES_RESULT:"get_devices_result",CAMERA_CAPTURE_RESULT:"camera_capture_result",MICROPHONE_CAPTURE_RESULT:"microphone_capture_result",SCREEN_CAPTURE_RESULT:"screen_capture_result",VIDEO_FILE_CAPTURE_RESULT:"video_file_capture_result",AUDIO_FILE_CAPTURE_RESULT:"audio_file_capture_result",IMAGE_FILE_CAPTURE_RESULT:"image_file_capture_result",VOLUME_DETECTOR_START_RESULT:"volume_detector_start_result",STOP_CAPTURE:"stop_capture"},...{SWITCH_ENABLE_MIXING:"switch_enable_mixing",SET_MIXING_CONFIG:"set_mixing_config",ADD_VIDEO_STREAM:"add_video_stream",UPDATE_VIDEO_STREAM:"update_video_stream",DELETE_VIDEO_STREAM:"delete_video_stream",CHANGE_VIDEO_STREAM_MUTE:"change_video_stream_mute",ADD_AUDIO_STREAM:"add_audio_stream",UPDATE_AUDIO_STREAM:"update_audio_stream",DELETE_AUDIO_STREAM:"delete_audio_stream",CHANGE_AUDIO_STREAM_MUTE:"change_audio_stream_mute"},...{START_PUSH:"start_push",STOP_PUSH_STREAM:"stop_push_stream",START_PUSH_STATUS:"start_push_status",PUSH_RECONNECT_START:"push_reconnect_start",PUSH_RECONNECT_STATUS:"push_reconnect_status",PUSH_STATS:"push_stats",PUSH_AUDIO_CONTEXT_START_FAILED:"push_audio_context_start_failed",PUSH_RTC_STATE_CHANGE:"push_rtc_state_change",PUSH_SDP_INFO:"push_sdp_info"}};function qt(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 y_ extends st{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:n,frameRate:i}=Ft(fs,"video"),{sampleRate:s}=Ft(ms,"audio");this._videoConstraints={width:t,height:n,frameRate:i},this._audioConstraints={sampleRate:s,enableAutoGainControl:!0,enableNoiseSuppression:!0,enableEchoCancellation:!0},this._livePusher=e}_notifyCaptured(e){this.emit(Be.DeviceCaptured,e)}_notifyStopCapture(e){this.emit(Be.DeviceStopCapture,e)}_bindStreamEvent(e){e.bindTrackEnd(()=>{this.emit(Be.Interrupted,e),this.stopCapture({streamId:e.id,type:e.type})})}_handleError(e,t){const n=new Bt(t,e.message);this.emit(Be.Error,n)}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 ju(e?[e]:["audioinput","videoinput"]);return V(j.GET_DEVICES_RESULT,{type:e,is_success:!0,devices:t}),t}catch(t){return V(j.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 n;switch(t){case Q.Camera:n="_cameraStreams";break;case Q.Screen:n="_screenStreams";break;case Q.VideoFile:n="_videoFileStreams";break;case Q.Microphone:n="_microphoneStreams";break;case Q.AudioFile:n="_audioFileStreams";break;case Q.Image:n="_imageStreams";break;case Q.CustomVideo:n="_customVideoStreams";break;case Q.CustomAudio:n="_customAudioStreams";break}if(n){let i=[];if(e){const s=this[n][e];i.push(s)}else i=et(this[n]);V(j.STOP_CAPTURE,{stream_id:e,type:t,number:i.length}),i.forEach(s=>{this._notifyStopCapture(s),s.destroy(),delete this[n][s.id]})}}async startCameraCapture(e){let t={};af.includes(e)?t={facingMode:e}:t={deviceId:e};const n={...t,...this._videoConstraints};try{const i=await Hu(n,!this._livePusher.isEnableMixing),s=new _d(i,{frameRate:this._videoConstraints.frameRate});return this._cameraStreams[s.id]=s,this._notifyCaptured(s),this._bindStreamEvent(s),V(j.CAMERA_CAPTURE_RESULT,{is_success:!0,stream_id:s.id,device_id:e,capture_params:n}),s.id}catch(i){throw V(j.CAMERA_CAPTURE_RESULT,{is_success:!1,device_id:e,capture_params:n,...qt(i)}),this._handleError(i,ke.OPEN_CAMERA_FAILED),i}}async startMicrophoneCapture(e){const t={...this._audioConstraints,deviceId:e};try{const n=await $u(t),i=new Qp(n);return this._microphoneStreams[i.id]=i,this._notifyCaptured(i),this._bindStreamEvent(i),V(j.MICROPHONE_CAPTURE_RESULT,{is_success:!0,stream_id:i.id,device_id:e,capture_params:t}),i.id}catch(n){throw V(j.MICROPHONE_CAPTURE_RESULT,{is_success:!1,device_id:e,capture_params:t,...qt(n)}),this._handleError(n,ke.OPEN_MICROPHONE_FAILED),n}}async startScreenCapture(e){const t={audio:e,video:this._videoConstraints};try{const n=await Ku(t,void 0,!this._livePusher.isEnableMixing),i=new tf(n,{frameRate:this._videoConstraints.frameRate});return this._screenStreams[i.id]=i,this._notifyCaptured(i),this._bindStreamEvent(i),V(j.SCREEN_CAPTURE_RESULT,{is_success:!0,stream_id:i.id,capture_params:t}),i.id}catch(n){throw V(j.SCREEN_CAPTURE_RESULT,{is_success:!1,capture_params:t,...qt(n)}),this._handleError(n,ke.OPEN_SCREEN_FAILED),n}}async startVideoFileCapture(e){try{const t=await Os({url:e,video:!0,audio:!0,loop:!0}),n=new ef(t);return this._videoFileStreams[n.id]=n,this._notifyCaptured(n),this._bindStreamEvent(n),V(j.VIDEO_FILE_CAPTURE_RESULT,{is_success:!0,stream_id:n.id,file_url:e}),n.id}catch(t){throw this._handleError(t,ke.VIDEO_FILE_CAPTURE_FAILED),V(j.VIDEO_FILE_CAPTURE_RESULT,{is_success:!1,file_url:e,...qt(t)}),t}}async startAudioFileCapture(e){try{const t=await Os({url:e,video:!1,audio:!0,loop:!0}),n=new rf(t);return this._audioFileStreams[n.id]=n,this._notifyCaptured(n),this._bindStreamEvent(n),V(j.AUDIO_FILE_CAPTURE_RESULT,{is_success:!0,stream_id:n.id,file_url:e}),n.id}catch(t){throw V(j.AUDIO_FILE_CAPTURE_RESULT,{is_success:!1,file_url:e,...qt(t)}),this._handleError(t,ke.AUDIO_FILE_CAPTURE_FAILED),t}}async startImageCapture(e){try{const t=await qu({url:e,width:0,height:0,frameRate:30}),n=new nf(t);return this._imageStreams[n.id]=n,this._notifyCaptured(n),this._bindStreamEvent(n),V(j.IMAGE_FILE_CAPTURE_RESULT,{is_success:!0,stream_id:n.id,file_url:e}),n.id}catch(t){throw V(j.IMAGE_FILE_CAPTURE_RESULT,{is_success:!1,file_url:e,...qt(t)}),this._handleError(t,ke.IMAGE_FILE_CAPTURE_FAILED),t}}startCustomVideoCapture(e){const t=Ju(e);if(t){const n=new sf(t);return this._customVideoStreams[n.id]=n,this._notifyCaptured(n),this._bindStreamEvent(n),n.id}}startCustomAudioCapture(e){const t=Xu(e);if(t){const n=new of(t);return this._customAudioStreams[n.id]=n,this._notifyCaptured(n),this._bindStreamEvent(n),n.id}}async startVolumeDetect(e){const t=this.getStreamById(e);if(t)try{await t.startVolumeDetect(),V(j.VOLUME_DETECTOR_START_RESULT,{is_success:!0,stream_id:t.id})}catch(n){V(j.VOLUME_DETECTOR_START_RESULT,{is_success:!1,stream_id:t.id,error_message:n.message}),this._handleError(n,ke.VOLUME_DETECT_FAILED)}}stopVolumeDetect(e){const t=this.getStreamById(e);t&&t.stopVolumeDetect()}getDefaultVideoStream(){return et(this._cameraStreams)[0]||et(this._screenStreams)[0]||et(this._videoFileStreams)[0]||et(this._imageStreams)[0]||et(this._customVideoStreams)[0]}getDefaultAudioStream(){return et(this._microphoneStreams)[0]||et(this._audioFileStreams)[0]||et(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(Q).forEach(e=>{this.stopCapture({type:e})})}}let ht=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 Hi{constructor({streamManagerController:e,composedStream:t,streamComposeController:n}){this._streamManagerController=e,this._composedStream=t,this._streamComposeController=n,this._active=!1,this.bindStreamManagerControllerEvent()}bindStreamManagerControllerEvent(){this._streamManagerController.on(Be.DeviceCaptured,e=>{this._active&&this.onStreamCapture(e)}),this._streamManagerController.on(Be.DeviceStopCapture,e=>{this._active&&this.onStreamStopCapture(e)})}getComposedStream(){return this._composedStream}enable(){this._active=!0}disable(){this._active=!1}}const Pa=new ht("SingleComposer");class S_ extends Hi{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:n}){var i,s;if(this._active)try{await((s=(i=this._composedStream.videoStream)==null?void 0:i.videoTrack)==null?void 0:s.applyConstraints({width:{min:e,ideal:e},height:{min:t,ideal:t},frameRate:{min:n,ideal:n}}))}catch(a){Pa.error("setVideoQuality error",a)}}_handleVideoStreamCapture(e){const t=this._composedStream.videoStream;t!=null&&t.id&&this._streamComposeController.getMixerComposer().haveMixedStream(t.id)&&this._streamComposeController.removeAudioStream(t.id),e.audioTrack&&this._streamComposeController.addAudioStream({streamId:e.id,volume:100}),this._composedStream.setVideoStream(e)}_handleAudioStreamCapture(e){const t=this._streamComposeController.getMixerComposer().getMixedStreamByType(e.type);t.length>0&&t.forEach(n=>{this._streamComposeController.removeAudioStream(n.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 n=this._streamManagerController.getDefaultVideoStream();n?this._handleVideoStreamCapture(n):Pa.error("all video stream stop capture")}}_handleAudioStreamStopCapture(e){this._streamComposeController.removeAudioStream(e.id)}getComposedStream(){return this._composedStream}}class b_ extends st{constructor(e,{width:t,height:n,x:i,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=n??e.height,this._rect.x=i??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 n=this._rect.width,i=this._rect.height;if(n===0&&i===0)return{width:0,height:0};if(n===0)return{height:i,width:e*(i/t)};if(i===0)return{width:n,height:t*(n/e)};const s=e/t,a=n/i;let o=n,d=i;return s>a?(o=n,d=2*Math.round(n/s/2)):s<a&&(o=2*Math.round(i*s/2),d=i),{width:o,height:d}}_bindVideoTrackSizeChange(){this._stream.on(ps.SizeChange,({width:e,height:t})=>{this.setBaseProps("sourceWidth",e),this.setBaseProps("sourceHeight",t)})}getViewNode(){var i;if(!this._stream)return;let e={width:this._rect.width,height:this._rect.height};this._rect.keepRatio&&(e=this._getPaintSize({elementWidth:this._stream.width,elementHeight:this._stream.height})),this._paintSize=e;const t=(i=this._stream.viewNode)==null?void 0:i.size(e.width,e.height);let n;return this._rect.mirrorType!==void 0&&this._rect.mirrorType!==cs.None?n=t==null?void 0:t.mirror(this._rect.mirrorType):n=t,n=n==null?void 0:n.position(this._rect.x,this._rect.y),n}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 n=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}n&&this.emit("propsChange",{[e]:t})}show(){this._isHidden=!1}hide(){this._isHidden=!0}get stream(){return this._stream}get isHidden(){return this._isHidden}destroy(){}}class Oa extends Lt{constructor(e,t){super({type:Q.MixVideo,stream:e}),this._trackMap.video=e,this._frameRate=(t==null?void 0:t.frameRate)??1}get source(){return this._source}replaceVideoTrack(e){this._trackMap.video=e,this._source=e}get viewNode(){return null}get mixerNode(){return null}bindTrackEnd(e){this.source.onended=e}destroy(){this.source.stop(),delete this._trackMap.video}}var E_=Object.defineProperty,C_=Object.getOwnPropertyDescriptor,Or=(r,e,t,n)=>{for(var i=C_(e,t),s=r.length-1,a;s>=0;s--)(a=r[s])&&(i=a(e,t,i)||i);return i&&E_(e,t,i),i};const Ma=new ht("composition-composer");function Mr(r,e,t){const n=t.value;return t.value=function(...i){return this._active||Ma.error("composer is not active"),n.apply(this,i)},t}class $t extends Hi{constructor(e){super(e),this._compositionViewConfig={width:1080,height:720,frameRate:30,backgroundColor:"#000000"},this._sprites=[],this._videoMixer=new ld}onStreamCapture(e){}onStreamStopCapture(e){e&&e.isVideoStream&&this.removeVideoStream(e.id)}enable(){var n;if(this._active)return;super.enable();const e=this._videoMixer.track(),t=this._mixedVideoStream;this._mixedVideoStream=new Oa(e,{frameRate:this._compositionViewConfig.frameRate}),this._composedStream.setVideoStream(this._mixedVideoStream),t&&((n=t.videoTrack)==null?void 0:n.id)!==e.id&&t.destroy()}disable(){super.disable(),this._videoMixer.stop()}_updateSpriteToMixer(){const e=Do(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,n)=>t.zOrder-n.zOrder),e.on("propsChange",t=>{Yp(t.zOrder)||(this._sprites=this._sprites.sort((n,i)=>n.zOrder-i.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 n=this._mixedVideoStream,i=this._videoMixer.updateFps();this._mixedVideoStream=new Oa(i,{frameRate:this._compositionViewConfig.frameRate}),this._composedStream.setVideoStream(this._mixedVideoStream),n.destroy()}}getMixingConfig(){return this._compositionViewConfig}addVideoStream(e,t){if(!e.viewNode){Ma.error("have no viewNode for composition");return}e.audioTrack&&this._streamComposeController.addAudioStream({streamId:e.id,volume:100});const n=new b_(e,t);this._addSprite(n)}_updateSingleVideoStream(e){const t=e.streamId;if(!t)return;const n=this._sprites.find(i=>i.stream.id===t);n&&(n.height=e.height,n.width=e.width,n.x=e.x,n.y=e.y,n.zOrder=e.zOrder,n.keepRatio=e.keepRatio??!1,n.mirrorType=e.mirrorType)}updateVideoStream(e){e.forEach(t=>{this._updateSingleVideoStream(t)}),this._updateSpriteToMixer()}removeVideoStream(e){if(!e)return;const t=this._sprites.find(n=>n.stream.id===e);t&&this._removeSprite(t)}muteVideoStream(e){if(e){const t=this._sprites.find(n=>n.stream.id===e);t&&t.hide()}else this._sprites.forEach(t=>{t.hide()});this._updateSpriteToMixer()}unmuteVideoStream(e){if(e){const t=this._sprites.find(n=>n.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(n=>n.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()}}Or([Mr],$t.prototype,"addVideoStream"),Or([Mr],$t.prototype,"updateVideoStream"),Or([Mr],$t.prototype,"removeVideoStream"),Or([Mr],$t.prototype,"muteVideoStream"),Or([Mr],$t.prototype,"unmuteVideoStream");class w_ extends st{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 T_ extends Zr{constructor(e){super({type:Q.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 k_ extends Hi{constructor(e){super(e),this._spriteList=[],this._audioMixer=new Yu({keepAlive:!0})}onStreamCapture(e){}onStreamStopCapture(e){e&&this.removeAudioStream(e.id)}_updateSpriteToMixer(){const e=Do(this._spriteList.map(t=>t.isMute?null:t.getMixerNode()));this._audioMixer.mix(e)}_updateSingleAudioStream(e){const{streamId:t,volume:n}=e,i=this._spriteList.find(s=>s.stream.id===t);i?n!==void 0&&(i.volume=n):console.error("can not find stream"+t)}enable(){super.enable();const e=this._audioMixer.track(),t=new T_(e);this._composedStream.setAudioStream(t),this._audioMixer.mix([])}addAudioStream(e,t){const n=new w_(e,t);this._spriteList.push(n),this._updateSpriteToMixer()}tryResume(){return this._audioMixer.resume()}removeAudioStream(e){const t=this._spriteList.find(n=>n.stream.id===e);t&&(this._spriteList=this._spriteList.filter(n=>n!==t),this._updateSpriteToMixer())}updateAudioStream(e){e.forEach(t=>{this._updateSingleAudioStream(t)}),this._updateSpriteToMixer()}muteAudioStream(e){if(e){const t=this._spriteList.find(n=>n.stream.id===e);t&&t.mute()}else this._spriteList.forEach(t=>{t.mute()});this._updateSpriteToMixer()}unmuteAudioStream(e){if(e){const t=this._spriteList.find(n=>n.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 R_ extends st{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(vt.VideoStreamChange,e))}setAudioStream(e){var t;((t=this._audioStream)==null?void 0:t.id)!==e.id&&(this._audioStream=e,this.emit(vt.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 A_=new ht("streamComposeController");class D_{constructor(e){this._streamManagerController=e,this._composedStream=new R_,this.singleComposer=new S_({streamManagerController:this._streamManagerController,composedStream:this._composedStream,streamComposeController:this}),this.compositionComposer=new $t({streamManagerController:this._streamManagerController,composedStream:this._composedStream,streamComposeController:this}),this.mixerComposer=new k_({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:n}){this.singleComposer.setVideoQuality({width:e,height:t,frameRate:n}),this.compositionComposer.setMixingConfig({width:e,height:t,frameRate:n})}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){A_.error("can not find video stream"+e.streamId);return}this.compositionComposer.addVideoStream(t,e)}updateVideoStream(e){this.compositionComposer.updateVideoStream(e);const t=e.map(n=>({streamId:n.streamId,volume:n.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 La{constructor(e){this._hasBindComposedStreamEvent=!1,this._composedStream=e}bindComposedStreamEvent(){this._hasBindComposedStreamEvent||(this._composedStream.on(vt.VideoStreamChange,this.handleVideoStreamChange),this._composedStream.on(vt.AudioStreamChange,this.handleAudioStreamChange),this._hasBindComposedStreamEvent=!0)}unbindComposedStreamEvent(){this._hasBindComposedStreamEvent&&(this._composedStream.off(vt.VideoStreamChange,this.handleVideoStreamChange),this._composedStream.off(vt.AudioStreamChange,this.handleAudioStreamChange),this._hasBindComposedStreamEvent=!1)}}const Kt=new ht("PreviewConsumer");class x_ extends La{constructor(e,{streamConsumeController:t}){super(e),this._isPreviewing=!1,this._previewElement=null,this.handleAudioStreamChange=n=>{this.startPreview()},this.handleVideoStreamChange=n=>{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 n=document.createElement("video");n.style.width="100%",n.style.height="100%",n.autoplay=!0,n.playsInline=!0,n.setAttribute("webkit-playsinline",""),n.setAttribute("x5-playsinline",""),this._previewElement=n;const i={video:null,audio:null};n.addEventListener("loadeddata",()=>{const s=n.srcObject.getVideoTracks()[0],a=n.srcObject.getAudioTracks()[0];s&&s!==i.video&&(this._streamConsumeController.emit(se.CaptureFirstVideoFrame),i.video=s),a&&a!==i.audio&&(this._streamConsumeController.emit(se.CaptureFirstAudioFrame),i.audio=a)}),t.appendChild(n)}startPreview(){if(Kt.log("startPreview"),!this._previewElement){Kt.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(n=>{this._streamConsumeController.emit(se.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 n=e.srcObject||new MediaStream;n.getTracks().find(i=>i.id===t.id)||(t.kind==="audio"&&n.getTracks().forEach(i=>{i.kind==="audio"&&(Kt.log(`remove preview track, ${i.label}, readyState=${i.readyState}`),n.removeTrack(i))}),t.kind==="video"&&n.getTracks().forEach(i=>{i.kind==="video"&&(n.removeTrack(i),Kt.log(`remove preview track, ${i.label}, readyState=${i.readyState}`))}),n.addTrack(t),e.srcObject?e.load():e.srcObject=n)}_removeTrack(e,t){if(!e)return;const n=e.srcObject;n&&(n.getTracks().forEach(i=>{(i.id===(t==null?void 0:t.id)||i.readyState==="ended")&&(Kt.log(`remove preview track ${i.label}`),n.removeTrack(i))}),n.getTracks().length===0&&(e.srcObject=null,Kt.log("set srcObject null")))}getPreviewElement(){if(this.isPreviewing)return this._previewElement}get isPreviewing(){return this._isPreviewing}}var Ue={},qi={},$i={exports:{}},Na;function Ki(){if(Na)return $i.exports;Na=1;var r=$i.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(n){n.reg||(n.reg=/(.*)/),n.format||(n.format="%s")})}),$i.exports}var Ua;function I_(){return Ua||(Ua=1,function(r){var e=function(o){return String(Number(o))===o?Number(o):o},t=function(o,d,c,u){if(u&&!c)d[u]=e(o[1]);else for(var h=0;h<c.length;h+=1)o[h+1]!=null&&(d[c[h]]=e(o[h+1]))},n=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 h=o.push?{}:u?d[o.name]:d;t(c.match(o.reg),h,o.names,o.name),o.push&&d[o.push].push(h)},i=Ki(),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(h){var l=h[0],f=h.slice(2);l==="m"&&(c.push({rtp:[],fmtp:[]}),u=c[c.length-1]);for(var y=0;y<(i[l]||[]).length;y+=1){var C=i[l][y];if(C.reg.test(f))return n(C,u,f)}}),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,h=!1;return c[0]!=="~"?u=e(c):(u=e(c.substring(1,c.length)),h=!0),{scid:u,paused:h}})})}}(qi)),qi}var Wi,Ga;function z_(){if(Ga)return Wi;Ga=1;var r=Ki(),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 h=d[o];switch(o+=1,u){case"%%":return"%";case"%s":return String(h);case"%d":return Number(h);case"%v":return""}})},n=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 h=0;h<o.names.length;h+=1){var l=o.names[h];o.name?u.push(d[o.name][l]):u.push(d[o.names[h]])}else u.push(d[o.name]);return t.apply(null,u)},i=["v","o","s","i","u","e","p","c","b","t","r","z","a"],s=["i","c","b","a"];return Wi=function(a,o){o=o||{},a.version==null&&(a.version=0),a.name==null&&(a.name=" "),a.media.forEach(function(h){h.payloads==null&&(h.payloads="")});var d=o.outerOrder||i,c=o.innerOrder||s,u=[];return d.forEach(function(h){r[h].forEach(function(l){l.name in a&&a[l.name]!=null?u.push(n(h,l,a)):l.push in a&&a[l.push]!=null&&a[l.push].forEach(function(f){u.push(n(h,l,f))})})}),a.media.forEach(function(h){u.push(n("m",r.m[0],h)),c.forEach(function(l){r[l].forEach(function(f){f.name in h&&h[f.name]!=null?u.push(n(l,f,h)):f.push in h&&h[f.push]!=null&&h[f.push].forEach(function(y){u.push(n(l,f,y))})})})}),u.join(`\r
|
|
67
67
|
`)+`\r
|
|
68
|
-
`},qi}var Ua;function D_(){if(Ua)return Pe;Ua=1;var r=R_(),e=A_(),t=Hi();return Pe.grammar=t,Pe.write=e,Pe.parse=r.parse,Pe.parseParams=r.parseParams,Pe.parseFmtpConfig=r.parseFmtpConfig,Pe.parsePayloads=r.parsePayloads,Pe.parseRemoteCandidates=r.parseRemoteCandidates,Pe.parseImageAttributes=r.parseImageAttributes,Pe.parseSimulcastStreamList=r.parseSimulcastStreamList,Pe}var x_=D_();const fn=fe(x_);function mn(r){return new Promise(e=>{setTimeout(e,r)})}async function I_(r,e={},t=0){const n=new AbortController;let i=!1;e=Object.assign({},e,{signal:n.signal});const s=[fetch(r,e)];t&&s.push(new Promise((a,o)=>{setTimeout(()=>{i||(o({httpCode:0,message:"Timeout"}),n.abort())},t)}));try{const a=await Promise.race(s);if(i=!0,!a.ok||a.status<200||a.status>=300)throw{httpCode:a.status,message:a.statusText};return a.json()}catch(a){throw i=!0,a}}async function Ga(r,e={},t={}){const{timeout:n=0,retryDelay:i=0}=t;let{retryCount:s=0}=t;try{return await I_(r,e,n)}catch(a){if(s--,t.retryCount=s,s<0)throw a;return await mn(i),await Ga(r,e,t)}}const z_=-1;function ue(r,e){let t;return e.forEach(n=>{n.type===r&&(t=n)}),t}async function $i(r,e){const t={},n=await(r==null?void 0:r.getStats()),i=await(e==null?void 0:e.getStats());return n&&(t.audio={mediaSource:ue("media-source",n),codec:ue("codec",n),candidatePair:ue("candidate-pair",n),remoteCandidate:ue("remote-candidate",n),localCandidate:ue("local-candidate",n),track:ue("track",n),outboundRtp:ue("outbound-rtp",n),remoteInboundRtp:ue("remote-inbound-rtp",n),transport:ue("transport",n)}),i&&(t.video={mediaSource:ue("media-source",i),codec:ue("codec",i),candidatePair:ue("candidate-pair",i),remoteCandidate:ue("remote-candidate",i),localCandidate:ue("local-candidate",i),track:ue("track",i),outboundRtp:ue("outbound-rtp",i),remoteInboundRtp:ue("remote-inbound-rtp",i),transport:ue("transport",i)}),t}async function O_(r,e,t){var u,h,l,f,y,C,v,E,k,g,D,L,R,M,U,G,F,q,ee,J,ve,he,Me,Le,Ne,Ie,ze,Ue,be,mt,Ot,Pt,Ur,Tn,kn,Rn,Gr,_t;const n=await $i(e,t);await mn(r);const i=await $i(e,t),{audio:s,video:a}=n,{audio:o,video:d}=i,c={};if(s!=null&&s.codec&&(o!=null&&o.codec)){const gt=((u=o.outboundRtp)==null?void 0:u.timestamp)-((h=s.outboundRtp)==null?void 0:h.timestamp),$e=((l=o.outboundRtp)==null?void 0:l.bytesSent)-((f=s.outboundRtp)==null?void 0:f.bytesSent),Yt=((y=o.remoteInboundRtp)==null?void 0:y.packetsLost)-((C=s.remoteInboundRtp)==null?void 0:C.packetsLost),vt=((v=o.outboundRtp)==null?void 0:v.packetsSent)-((E=s.outboundRtp)==null?void 0:E.packetsSent),yt=(((k=o.mediaSource)==null?void 0:k.totalAudioEnergy)??0)-(((g=s.mediaSource)==null?void 0:g.totalAudioEnergy)??0);c.audio={codec:o.codec.mimeType,channels:o.codec.channels,sendBitrate:$e/gt*8e3,packetsSent:(D=o.outboundRtp)==null?void 0:D.packetsSent,nackCount:(L=o.outboundRtp)==null?void 0:L.nackCount,packetsLost:(R=o.remoteInboundRtp)==null?void 0:R.packetsLost,packetsLostPercent:Yt/vt,deltaAudioEnergy:yt}}if(a!=null&&a.codec&&(d!=null&&d.codec)){const gt=((M=d.outboundRtp)==null?void 0:M.timestamp)-((U=a.outboundRtp)==null?void 0:U.timestamp),$e=((G=d.outboundRtp)==null?void 0:G.bytesSent)-((F=a.outboundRtp)==null?void 0:F.bytesSent),Yt=((q=d.outboundRtp)==null?void 0:q.framesEncoded)-((ee=a.outboundRtp)==null?void 0:ee.framesEncoded),vt=((J=d.outboundRtp)==null?void 0:J.totalEncodeTime)-((ve=a.outboundRtp)==null?void 0:ve.totalEncodeTime),yt=((he=d.outboundRtp)==null?void 0:he.packetsSent)-((Me=a.outboundRtp)==null?void 0:Me.packetsSent),rs=((Le=d.outboundRtp)==null?void 0:Le.totalPacketSendDelay)-((Ne=a.outboundRtp)==null?void 0:Ne.totalPacketSendDelay),ns=((Ie=d.remoteInboundRtp)==null?void 0:Ie.packetsLost)-((ze=a.remoteInboundRtp)==null?void 0:ze.packetsLost);c.video={codec:d.codec.mimeType,sendBitrate:$e/gt*8e3,frameWidth:(Ue=d.outboundRtp)==null?void 0:Ue.frameWidth,frameHeight:(be=d.outboundRtp)==null?void 0:be.frameHeight,framesPerSecond:(mt=d.outboundRtp)==null?void 0:mt.framesPerSecond,framesEncoded:(Ot=d.outboundRtp)==null?void 0:Ot.framesEncoded,framesEncodedPerSecond:Yt*1e3/gt,keyFramesEncoded:(Pt=d.outboundRtp)==null?void 0:Pt.keyFramesEncoded,framesSent:(Ur=d.outboundRtp)==null?void 0:Ur.frameHeight,frameEncodeAvgTime:vt*1e3/Yt,packetsSent:(Tn=d.outboundRtp)==null?void 0:Tn.packetsSent,packetSendDelay:rs*1e3/yt,nackCount:(kn=d.outboundRtp)==null?void 0:kn.nackCount,firCount:(Rn=d.outboundRtp)==null?void 0:Rn.firCount,pliCount:(Gr=d.outboundRtp)==null?void 0:Gr.pliCount,packetsLost:(_t=d.remoteInboundRtp)==null?void 0:_t.packetsLost,packetsLostPercent:ns/yt,deltaTime:gt}}return{stats:c,originStats:{audio:o,video:d}}}function _e(r,e=z_){return r??e}function P_(r){var e,t,n,i,s,a,o,d,c,u,h,l,f,y,C,v,E,k,g,D,L,R,M,U,G,F,q,ee,J,ve,he,Me,Le,Ne,Ie,ze,Ue,be,mt,Ot,Pt;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:(n=r.outboundRtp)==null?void 0:n.nackCount,audio_ssrc:(i=r.outboundRtp)==null?void 0:i.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)):(h=r.mediaSource)==null?void 0:h.audioLevel,audio_volume:(l=r.mediaSource)!=null&&l.audioLevel?((f=r.mediaSource)==null?void 0:f.audioLevel)*255:(y=r.mediaSource)==null?void 0:y.audioLevel,audio_total_audio_energy:(C=r.mediaSource)==null?void 0:C.totalAudioEnergy,audio_total_input_duration:(v=r.mediaSource)==null?void 0:v.totalSamplesDuration,audio_send_level:(E=r.mediaSource)==null?void 0:E.audioLevel,audio_ice_available_outgoing_bitrate:(k=r.candidatePair)==null?void 0:k.availableOutgoingBitrate,audio_ice_bytes_received:(g=r.candidatePair)==null?void 0:g.bytesReceived,audio_ice_bytes_sent:(D=r.candidatePair)==null?void 0:D.bytesSent,audio_ice_nominated:(L=r.candidatePair)==null?void 0:L.nominated,audio_ice_pair_id:(R=r.candidatePair)==null?void 0:R.id,audio_ice_pair_rtt:(M=r.candidatePair)==null?void 0:M.currentRoundTripTime,audio_ice_pair_state:(U=r.candidatePair)==null?void 0:U.state,audio_ice_pair_writable:(G=r.candidatePair)==null?void 0:G.writable,audio_recv_ping_requests:(F=r.candidatePair)==null?void 0:F.requestsReceived,audio_recv_ping_responses:(q=r.candidatePair)==null?void 0:q.responsesReceived,audio_sent_ping_requests_before_first_response:(ee=r.candidatePair)==null?void 0:ee.requestsSent,audio_sent_ping_requests_total:(((J=r.candidatePair)==null?void 0:J.requestsSent)??0)+(((ve=r.candidatePair)==null?void 0:ve.consentRequestsSent)??0),audio_sent_ping_responses:(he=r.candidatePair)==null?void 0:he.responsesSent,audio_local_candidate_type:(Me=r.localCandidate)==null?void 0:Me.candidateType,audio_local_ip:((Le=r.localCandidate)==null?void 0:Le.ip)||((Ne=r.localCandidate)==null?void 0:Ne.address),audio_local_network_type:(Ie=r.localCandidate)==null?void 0:Ie.networkType,audio_local_port:(ze=r.localCandidate)==null?void 0:ze.port,audio_local_protocol:(Ue=r.localCandidate)==null?void 0:Ue.protocol,audio_remote_candidate_type:(be=r.remoteCandidate)==null?void 0:be.candidateType,audio_remote_ip:((mt=r.remoteCandidate)==null?void 0:mt.ip)||((Ot=r.remoteCandidate)==null?void 0:Ot.address),audio_remote_port:(Pt=r.remoteCandidate)==null?void 0:Pt.port}}function M_(r){var e,t,n,i,s,a,o,d,c,u,h,l,f,y,C,v,E,k,g,D,L,R,M,U,G,F,q,ee,J,ve,he,Me,Le,Ne,Ie,ze,Ue;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:(n=r.outboundRtp)==null?void 0:n.ssrc,video_quality_limitation_reason:(i=r.outboundRtp)==null?void 0:i.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:(h=r.candidatePair)==null?void 0:h.availableOutgoingBitrate,video_ice_bytes_received:(l=r.candidatePair)==null?void 0:l.bytesReceived,video_ice_bytes_sent:(f=r.candidatePair)==null?void 0:f.bytesSent,video_ice_nominated:(y=r.candidatePair)==null?void 0:y.nominated,video_ice_pair_id:(C=r.candidatePair)==null?void 0:C.id,video_ice_pair_rtt:(v=r.candidatePair)==null?void 0:v.currentRoundTripTime,video_ice_pair_state:(E=r.candidatePair)==null?void 0:E.state,video_ice_pair_writable:(k=r.candidatePair)==null?void 0:k.writable,video_recv_ping_requests:(g=r.candidatePair)==null?void 0:g.requestsReceived,video_recv_ping_responses:(D=r.candidatePair)==null?void 0:D.responsesReceived,video_sent_ping_requests_before_first_response:(L=r.candidatePair)==null?void 0:L.requestsSent,video_sent_ping_requests_total:(((R=r.candidatePair)==null?void 0:R.requestsSent)??0)+(((M=r.candidatePair)==null?void 0:M.consentRequestsSent)??0),video_sent_ping_responses:(U=r.candidatePair)==null?void 0:U.responsesSent,video_local_candidate_type:(G=r.localCandidate)==null?void 0:G.candidateType,video_local_ip:((F=r.localCandidate)==null?void 0:F.ip)||((q=r.localCandidate)==null?void 0:q.address),video_local_network_type:(ee=r.localCandidate)==null?void 0:ee.networkType,video_local_port:(J=r.localCandidate)==null?void 0:J.port,video_local_protocol:(ve=r.localCandidate)==null?void 0:ve.protocol,video_remote_candidate_type:(he=r.remoteCandidate)==null?void 0:he.candidateType,video_remote_ip:((Me=r.remoteCandidate)==null?void 0:Me.ip)||((Le=r.remoteCandidate)==null?void 0:Le.address),video_remote_port:(Ne=r.remoteCandidate)==null?void 0:Ne.port,video_input_frame_rate:(Ie=r.mediaSource)==null?void 0:Ie.framesPerSecond,video_input_frame_width:(ze=r.mediaSource)==null?void 0:ze.width,video_input_frame_height:(Ue=r.mediaSource)==null?void 0:Ue.height}}function L_(r,e){var t,n,i,s,a,o,d,c,u,h,l,f,y,C,v,E,k,g,D,L,R,M;return{...M_(e.video??{}),video_send_k_bitrate:_e((t=r.video)==null?void 0:t.sendBitrate)/1e3,video_send_frame_rate:_e((n=r.video)==null?void 0:n.framesPerSecond),video_encoder_output_frame_rate:_e((i=r.video)==null?void 0:i.framesEncodedPerSecond),video_encoded_frame_width:_e((s=r.video)==null?void 0:s.frameWidth),video_encoded_frame_height:_e((a=r.video)==null?void 0:a.frameHeight),video_encoded_key_frames:_e((o=r.video)==null?void 0:o.keyFramesEncoded),video_delta_time:_e((d=r.video)==null?void 0:d.deltaTime,2e3),video_packets_sent:_e((c=r.video)==null?void 0:c.packetsSent),video_nack_count:_e((u=r.video)==null?void 0:u.nackCount),video_fir_count:_e((h=r.video)==null?void 0:h.firCount),video_pli_count:_e((l=r.video)==null?void 0:l.pliCount),video_packets_lost:_e((f=r.video)==null?void 0:f.packetsLost),video_packets_lost_percent:(y=r.video)==null?void 0:y.packetsLostPercent,video_codec:(C=r.video)==null?void 0:C.codec,video_duration:(v=r.video)==null?void 0:v.deltaTime,...P_(e.audio??{}),audio_send_k_bitrate:_e((E=r.audio)==null?void 0:E.sendBitrate)/1e3,audio_send_channels:_e((k=r.audio)==null?void 0:k.channels),audio_packets_sent:_e((g=r.audio)==null?void 0:g.packetsSent),audio_packets_lost:_e((D=r.audio)==null?void 0:D.packetsLost),audio_packets_lost_percent:(L=r.audio)==null?void 0:L.packetsLostPercent,audio_codec:(R=r.audio)==null?void 0:R.codec,audio_delta_energy:(M=r.audio)==null?void 0:M.deltaAudioEnergy}}function N_(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 U_=r=>{var t;if(!Ss)return;const e=(t=r.rtp.filter(n=>n.codec==="opus")[0])==null?void 0:t.payload;e&&r.fmtp.forEach(n=>{n.payload===e&&(n.config="minptime=10;useinbandfec=1")})},G_=r=>{r.ext&&(Zc||Fr)&&(r.ext=r.ext.filter(e=>{var t;return!((t=e.uri)!=null&&t.includes("video-orientation"))}))};function B_(r,e){r==null||r.rtp.forEach(({codec:t,payload:n})=>{if(["vp8","h264"].includes(t.toLocaleLowerCase())){const i=r.fmtp.find(s=>s.payload===n);i?i.config=[...i.config.split(";"),"x-google-min-bitrate=100",`x-google-start-bitrate=${e}`].join(";"):r.fmtp.push({payload:n,config:`x-google-min-bitrate=100;x-google-start-bitrate=${e}`})}})}const ge=new lt("PCConnect");class F_{constructor(e,t,n){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=n}get isPushing(){var e,t,n,i;return!!((t=(e=this._videoTransceiver)==null?void 0:e.sender)!=null&&t.track||(i=(n=this._audioTransceiver)==null?void 0:n.sender)!=null&&i.track)}get videoSenderTrackStats(){var e,t,n,i;return{track_enabled:(t=(e=this._videoTransceiver)==null?void 0:e.sender.track)==null?void 0:t.enabled,track_muted:(i=(n=this._videoTransceiver)==null?void 0:n.sender.track)==null?void 0:i.muted}}get pushUrl(){return this._signalUrl}get sessionId(){return this._sessionId}async publish(e,t,n){var h;const i=new RTCPeerConnection;this._pc=i,this._bindRTCEvent();const s=e.filter(l=>(l==null?void 0:l.kind)==="audio")[0],a=e.filter(l=>(l==null?void 0:l.kind)==="video")[0];s&&this._ms.addTrack(s),a&&this._ms.addTrack(a),this._audioTransceiver=i.addTransceiver(s||"audio",{direction:"sendonly",sendEncodings:[{maxBitrate:t[0]}],streams:[this._ms]}),ge.log("add track to pc,",s),this._videoTransceiver=i.addTransceiver(a||"video",{direction:"sendonly",sendEncodings:[{maxBitrate:t[1]}],streams:[this._ms]}),ge.log("add track to pc,",a);const o=await i.createOffer();ge.groupCollapsed("local offer"),ge.log(o.sdp);const d=fn.parse(o.sdp);d.media.forEach(l=>{l.type==="audio"?U_(l):l.type==="video"&&(G_(l),B_(l,t[1]))}),o.sdp=fn.write(d),ge.log("local offer modified"),ge.log(o.sdp),await i.setLocalDescription(o);const c=await Ga(this._signalUrl,{method:"POST",mode:"cors",body:JSON.stringify({sessionId:""+this._sessionId,version:"1.0-html",localSdp:o,metadata:{platform:"Web"}})},{...this._opts,timeout:n!=null&&n.isReconnect?10*Ao:(h=this._opts)==null?void 0:h.timeout});if((c==null?void 0:c.code)!==200)throw{code:c.code,message:c.message};ge.log("remote answer:"),ge.log(c.remoteSdp.sdp);const u=fn.parse(c.remoteSdp.sdp);if(u.media.forEach(l=>{var f;(f=l.fingerprint)!=null&&f.hash&&(l.fingerprint.hash=l.fingerprint.hash.toUpperCase())}),c.remoteSdp.sdp=fn.write(u),ge.log("remote answer modified"),ge.log(c.remoteSdp.sdp),ge.groupEnd(),i.connectionState==="closed"){ge.log("PeerConnection is closed, skipping setRemoteDescription");return}await i.setRemoteDescription(c.remoteSdp)}async updatePublish(e,t){var s,a;let n;t==="video"?n=this._videoTransceiver:n=this._audioTransceiver;const i=(s=n==null?void 0:n.sender)==null?void 0:s.track;(i==null?void 0:i.id)!==(e==null?void 0:e.id)&&(await((a=n==null?void 0:n.sender)==null?void 0:a.replaceTrack(e)),ge.log(`replace ${t} track done! ${i==null?void 0:i.label} -> ${e==null?void 0:e.label}`))}applyBitrate(e,t,n){var a,o,d;const i=t==="video"?(a=this._videoTransceiver)==null?void 0:a.sender:(o=this._audioTransceiver)==null?void 0:o.sender;if(!i)return;const s=i.getParameters();s.encodings=(d=s.encodings)!=null&&d.length?s.encodings:[{}],n?s.encodings[0].minBitrate=e:s.encodings[0].maxBitrate=e,i.setParameters(s),ge.log(`set bitrate for ${t}, ${e} bps, min:${n}`)}unpublish(){var e,t;(e=this._pc)==null||e.getSenders().forEach(n=>{var i;(i=this._pc)==null||i.removeTrack(n)}),(t=this._pc)==null||t.close(),this._audioTransceiver=null,this._videoTransceiver=null,this._pc=null,ge.log("close pc!")}getStats(){var e,t;return $i((e=this._audioTransceiver)==null?void 0:e.sender,(t=this._videoTransceiver)==null?void 0:t.sender)}getStatsSnapshoot(e){var t,n;return O_(e||100,(t=this._audioTransceiver)==null?void 0:t.sender,(n=this._videoTransceiver)==null?void 0:n.sender)}_bindRTCEvent(){const e=this._pc;e==null||e.addEventListener("connectionstatechange",()=>{ge.log("onconnectionstatechange:",e.connectionState),this._onConnectStateChange(e.connectionState)})}}var ht=(r=>(r.OnError="onerror",r.OnConnectClosed="onconnectclosed",r.OnFirstFramePushed="onfirstframepushed",r))(ht||{}),pt=(r=>(r.Video="video",r.Audio="audio",r))(pt||{}),De=(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))(De||{}),It=(r=>(r.Ready="ready",r.Error="error",r.FirstFramePushed="firstframepushed",r.Flvfile="flvfile",r.STATS="stats",r.Close="close",r))(It||{}),Ki={exports:{}},Ba;function V_(){return Ba||(Ba=1,function(r){var e=Object.prototype.hasOwnProperty,t="~";function n(){}Object.create&&(n.prototype=Object.create(null),new n().__proto__||(t=!1));function i(d,c,u){this.fn=d,this.context=c,this.once=u||!1}function s(d,c,u,h,l){if(typeof u!="function")throw new TypeError("The listener must be a function");var f=new i(u,h||d,l),y=t?t+c:c;return d._events[y]?d._events[y].fn?d._events[y]=[d._events[y],f]:d._events[y].push(f):(d._events[y]=f,d._eventsCount++),d}function a(d,c){--d._eventsCount===0?d._events=new n:delete d._events[c]}function o(){this._events=new n,this._eventsCount=0}o.prototype.eventNames=function(){var c=[],u,h;if(this._eventsCount===0)return c;for(h in u=this._events)e.call(u,h)&&c.push(t?h.slice(1):h);return Object.getOwnPropertySymbols?c.concat(Object.getOwnPropertySymbols(u)):c},o.prototype.listeners=function(c){var u=t?t+c:c,h=this._events[u];if(!h)return[];if(h.fn)return[h.fn];for(var l=0,f=h.length,y=new Array(f);l<f;l++)y[l]=h[l].fn;return y},o.prototype.listenerCount=function(c){var u=t?t+c:c,h=this._events[u];return h?h.fn?1:h.length:0},o.prototype.emit=function(c,u,h,l,f,y){var C=t?t+c:c;if(!this._events[C])return!1;var v=this._events[C],E=arguments.length,k,g;if(v.fn){switch(v.once&&this.removeListener(c,v.fn,void 0,!0),E){case 1:return v.fn.call(v.context),!0;case 2:return v.fn.call(v.context,u),!0;case 3:return v.fn.call(v.context,u,h),!0;case 4:return v.fn.call(v.context,u,h,l),!0;case 5:return v.fn.call(v.context,u,h,l,f),!0;case 6:return v.fn.call(v.context,u,h,l,f,y),!0}for(g=1,k=new Array(E-1);g<E;g++)k[g-1]=arguments[g];v.fn.apply(v.context,k)}else{var D=v.length,L;for(g=0;g<D;g++)switch(v[g].once&&this.removeListener(c,v[g].fn,void 0,!0),E){case 1:v[g].fn.call(v[g].context);break;case 2:v[g].fn.call(v[g].context,u);break;case 3:v[g].fn.call(v[g].context,u,h);break;case 4:v[g].fn.call(v[g].context,u,h,l);break;default:if(!k)for(L=1,k=new Array(E-1);L<E;L++)k[L-1]=arguments[L];v[g].fn.apply(v[g].context,k)}}return!0},o.prototype.on=function(c,u,h){return s(this,c,u,h,!1)},o.prototype.once=function(c,u,h){return s(this,c,u,h,!0)},o.prototype.removeListener=function(c,u,h,l){var f=t?t+c:c;if(!this._events[f])return this;if(!u)return a(this,f),this;var y=this._events[f];if(y.fn)y.fn===u&&(!l||y.once)&&(!h||y.context===h)&&a(this,f);else{for(var C=0,v=[],E=y.length;C<E;C++)(y[C].fn!==u||l&&!y[C].once||h&&y[C].context!==h)&&v.push(y[C]);v.length?this._events[f]=v.length===1?v[0]:v:a(this,f)}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 n,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}(Ki)),Ki.exports}var j_=V_();const H_=fe(j_);var _n=(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))(_n||{});class Fa extends Error{constructor(e,t,n){super(),this.code=e,this.message=t,n&&(this.ext=n),this.toJson=()=>({code:this.code,message:this.message,ext:this.ext})}}function Va(r,e,t){return new Fa(r,e,t)}const Zt=class Zt{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 Zt.enable}get _enableLong(){return Zt.enableLong}get long(){return this._enableLong}};Zt.enable=!1,Zt.enableLong=!1;let ft=Zt;const xe=new ft("RTMP_Capture");class q_{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(xe.log(`replace ${e} track`),e===pt.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 i;if(!this.videoTrack){xe.log("no video track to capture");return}if(this.videoTrack.readyState!=="live"){xe.warn("video track not live");return}const e=new MediaStreamTrackProcessor(this.videoTrack);e.track=this.videoTrack;const t=e.readable.getReader();this._videoProcessorReader=t,xe.log("start capture video frame",this.videoTrack);let n;for(;;){n&&clearInterval(n),n=setTimeout(()=>{xe.warn("long time no capture output"),this._bridge._postMockVideoEncodeFlag()},1500);const s=await t.read();if(clearInterval(n),this._videoFirstframeCaptured||(this._videoFirstframeCaptured=!0,xe.log("video first frame captured")),s.done||!s.value){(i=s.value)==null||i.close();break}this._bridge._postVideoFrame(s.value,this.videoTrack.getSettings())}clearInterval(n),this._videoFirstframeCaptured=!1,this._videoProcessorReader=null,xe.log("video track read done!",e.track)}async _startAudioCapture(){if(!this.audioTrack){xe.log("no audio track to capture");return}if(this.audioTrack.readyState!=="live"){xe.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,xe.log("start capture audio frame");;){const n=await t.read();if(this._audioFirstframeCaptured||(this._audioFirstframeCaptured=!0,xe.log("audio first frame captured")),n.done||!n.value)break;this._bridge._postAudioFrame(n.value,this.audioTrack.getSettings())}this._audioFirstframeCaptured=!1,this._audioProcessorReader=null,xe.log("audio track read done!",e.track)}destroy(){var e,t;(e=this._audioProcessorReader)==null||e.cancel().catch(()=>{}),(t=this._videoProcessorReader)==null||t.cancel().catch(()=>{})}}const ja='(function(){"use strict";var l=(i=>(i.OnVideoCaptured="onvideocaptured",i.OnAudioCaptured="onaudiocaptured",i.OnVideoCaptureNoOutput="onvideocapturenooutput",i.OnVideoEncoded="onvideoencoded",i.OnAudioEncoded="onaudioencoded",i.OnEncodedFrame="onencodedframe",i.OnPacketed="onpacketed",i.OnUpstreamFeedback="onupstreamfeedback",i.OnBitrateChanged="onbitratechanged",i))(l||{}),O=(i=>(i.OnError="onerror",i.OnConnectClosed="onconnectclosed",i.OnFirstFramePushed="onfirstframepushed",i))(O||{}),I=(i=>(i.Video="video",i.Audio="audio",i))(I||{}),v=(i=>(i.Init="init",i.AvExist="avexist",i.VideoFrame="videoframe",i.MockVideoEncode="mockvideoencode",i.AudioFrame="audioframe",i.AdjustBitrate="adjustbitrate",i.Publish="publish",i.UnPublish="unpublish",i.Download="download",i.GetStats="getstats",i.EncodeConfig="encodeconfig",i))(v||{}),w=(i=>(i.Ready="ready",i.Error="error",i.FirstFramePushed="firstframepushed",i.Flvfile="flvfile",i.STATS="stats",i.Close="close",i))(w||{});function $(i){return i&&i.__esModule&&Object.prototype.hasOwnProperty.call(i,"default")?i.default:i}var k={exports:{}},U;function q(){return U||(U=1,function(i){var t=Object.prototype.hasOwnProperty,e="~";function s(){}Object.create&&(s.prototype=Object.create(null),new s().__proto__||(e=!1));function r(u,a,n){this.fn=u,this.context=a,this.once=n||!1}function o(u,a,n,h,m){if(typeof n!="function")throw new TypeError("The listener must be a function");var g=new r(n,h||u,m),f=e?e+a:a;return u._events[f]?u._events[f].fn?u._events[f]=[u._events[f],g]:u._events[f].push(g):(u._events[f]=g,u._eventsCount++),u}function _(u,a){--u._eventsCount===0?u._events=new s:delete u._events[a]}function c(){this._events=new s,this._eventsCount=0}c.prototype.eventNames=function(){var a=[],n,h;if(this._eventsCount===0)return a;for(h in n=this._events)t.call(n,h)&&a.push(e?h.slice(1):h);return Object.getOwnPropertySymbols?a.concat(Object.getOwnPropertySymbols(n)):a},c.prototype.listeners=function(a){var n=e?e+a:a,h=this._events[n];if(!h)return[];if(h.fn)return[h.fn];for(var m=0,g=h.length,f=new Array(g);m<g;m++)f[m]=h[m].fn;return f},c.prototype.listenerCount=function(a){var n=e?e+a:a,h=this._events[n];return h?h.fn?1:h.length:0},c.prototype.emit=function(a,n,h,m,g,f){var F=e?e+a:a;if(!this._events[F])return!1;var d=this._events[F],C=arguments.length,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',Ha=typeof self<"u"&&self.Blob&&new Blob([ja],{type:"text/javascript;charset=utf-8"});function $_(r){let e;try{if(e=Ha&&(self.URL||self.webkitURL).createObjectURL(Ha),!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(ja),{name:r==null?void 0:r.name})}finally{e&&(self.URL||self.webkitURL).revokeObjectURL(e)}}try{ft.enable=location.href.indexOf("rtmpdebug")!==-1,ft.enableLong=location.href.indexOf("rtmpdebug=long")!==-1}catch{}const gn=new ft("Bridge");class qa extends H_{constructor(){super(),this._worker=null,this._audioMsTrack=null,this._videoMsTrack=null,this._capture=new q_(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 n=new Promise((o,d)=>{e=o,t=d}),i=o=>{var d;switch((d=this._worker)==null||d.removeEventListener("message",i),o.data.type){case It.Error:t(o.data.data);break;default:this._bindWorkerEvent(),gn.log("rtmp ready!"),e(!0)}};try{this._worker=new $_}catch(o){t(Va(_n.RTMP_INIT_FAIL,o.message))}return(s=this._worker)==null||s.postMessage({type:De.Init,options:{logEnable:ft.enable,logEnableLong:ft.enableLong}}),(a=this._worker)==null||a.addEventListener("message",i),n}_bindWorkerEvent(){var e,t;(e=this._worker)==null||e.addEventListener("message",n=>{switch(n.data.type){case It.Error:gn.table(n.data.data),this.emit(ht.OnError,n.data.data);break;case It.Flvfile:K_(n.data.buffer);break;case It.FirstFramePushed:this.emit(ht.OnFirstFramePushed);break;case It.Close:this.emit(ht.OnConnectClosed),this.destroy();break}}),(t=this._worker)==null||t.addEventListener("error",n=>{this.emit(ht.OnError,Va(_n.WORKER_ERROR,n.message))})}addTrack(e){e.kind===pt.Video&&(this._videoMsTrack=e),e.kind===pt.Audio&&(this._audioMsTrack=e),this._setAVExist(!!this._videoMsTrack,!!this._audioMsTrack)}replaceTrack(e,t){e===pt.Video&&(this._videoMsTrack=t),e===pt.Audio&&(this._audioMsTrack=t),this._setAVExist(!!this._videoMsTrack,!!this._audioMsTrack),this._capture.restartCapture(e)}async getStats(){var s,a;let e,t;const n=new Promise((o,d)=>{e=o,t=d});this._worker||setTimeout(()=>{t()},0);const i=o=>{var d;switch(o.data.type){case It.STATS:e(o.data.data),(d=this._worker)==null||d.removeEventListener("message",i);break}};return(s=this._worker)==null||s.addEventListener("message",i),(a=this._worker)==null||a.postMessage({type:De.GetStats}),n}_postVideoFrame(e,t){var n;(n=this._worker)==null||n.postMessage({type:De.VideoFrame,frame:e,setting:t},[e])}_postMockVideoEncodeFlag(){var e;(e=this._worker)==null||e.postMessage({type:De.MockVideoEncode})}_setAVExist(e,t){var n;(n=this._worker)==null||n.postMessage({type:De.AvExist,hasVideo:e,hasAudio:t})}_postAudioFrame(e,t){var n;(n=this._worker)==null||n.postMessage({type:De.AudioFrame,frame:e,setting:t},[e])}setEncodeCapacity(e){var t;(t=this._worker)==null||t.postMessage({type:De.EncodeConfig,cfg:e})}adjustBitrate(e,t){var n;(n=this._worker)==null||n.postMessage({type:De.AdjustBitrate,kind:e,bitrate:t})}publish(e){var t;gn.log("start capture & connect"),this._capture.start(),(t=this._worker)==null||t.postMessage({type:De.Publish,url:e})}unpublish(){var e;this._capture.destroy(),(e=this._worker)==null||e.postMessage({type:De.UnPublish})}destroy(){var e;gn.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:De.Download})}}function K_(r){const e=document.createElement("a");e.href=URL.createObjectURL(new Blob([r])),e.download=Date.now()+".flv",e.click()}const $a=new lt("RTMPConnect");class W_{constructor(e,t,n,i){this._opts=void 0,this._isPushing=!1,this._url=e,this._opts=t,this._onError=n,this._OnSuccess=i,this._rtmp=new qa,this._bindEvents()}get isPushing(){return this._isPushing}get pushUrl(){return this._url}get sessionId(){return 0}_bindEvents(){this._rtmp.on(ht.OnError,e=>{this._isPushing=!1,this._onError(e)}),this._rtmp.on(ht.OnConnectClosed,()=>{this._isPushing=!1,this._onError(new Fa(_n.WTP_CONNECT_FAIL,"connect lost"))}),this._rtmp.on(ht.OnFirstFramePushed,()=>{this._isPushing=!0,this._OnSuccess()})}async publish(e,t,n){await this._rtmp.ready(),n!=null&&n.cfg&&this._rtmp.setEncodeCapacity(n.cfg),e.filter(Boolean).forEach(i=>this._rtmp.addTrack(i)),t[0]&&this._rtmp.adjustBitrate(pt.Audio,t[0]),t[1]&&this._rtmp.adjustBitrate(pt.Video,t[1]),this._rtmp.publish(this._url)}updatePublish(e,t){$a.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 mn(e),{stats:await this._rtmp.getStats(),originStats:void 0}}unpublish(){$a.warn("unpublish"),this._rtmp.unpublish(),this._isPushing=!1}}class J_{constructor(e,t=nf){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=(n=!1)=>{var i;this._logger.log("start reconnect strategy"),this.state==="idle"&&(this._reconnectStartTime=Date.now(),this._totalReconnectInfo.totalReconnectCount+=1,V(j.PUSH_RECONNECT_START,{start_time:this._reconnectStartTime,session_id:this._pushConsumer.pushSessionId,max_timeout:this._maxTimeout}),this.bindOnlineEvent(),this.setStrategyState("executing"),(i=this._logger)==null||i.log("start reconnecting with max timeout: ",this._maxTimeout),this.startTimeoutTimer(this._maxTimeout),this._pushConsumer.emitReconnectStateChange({state:Lt.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(n))},this.attemptReconnect=async()=>{var n;if(this.state==="executing"){this.setStrategyState("reconnecting"),this._reconnectCount+=1;const i=this.getNextPushUrl();try{if(this._pushConsumer.emitReconnectStateChange({state:Lt.RECONNECTING,params:{retryTime:this._reconnectCount},teaParams:{retry_push_url:i,session_id:this._pushConsumer.pushSessionId}}),await this._pushConsumer.reconnect(i),!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:Dn.PushUrlInvalid,failedError:s}),(n=this._onReconnectError)==null||n.call(this,"pushError",s);else{if(!this.isActive())return;this.setStrategyState("executing"),this.execute()}}}},this.executeStrategy=(n=!1)=>{const i=n?0:this._reconnectDelay;this._pushConsumer.emitReconnectStateChange({state:Lt.WAITING,params:{waitingTime:i,retryTime:this._reconnectCount+1},teaParams:{is_online:navigator.onLine,session_id:this._pushConsumer.pushSessionId}}),this._logger.log("reconnect after delay: ",i,Date.now()),this._reconnectTimeout=window.setTimeout(this.attemptReconnect,i),this._reconnectDelay=this._reconnectDelay===0?2e3:Math.min(this._reconnectDelay*2,sf)},this.state="idle",this._pushConsumer=e,this._maxTimeout=t,this._logger=new lt("ReconnectStrategy")}getNextPushUrl(){const e=this._pushConsumer.pushUrl;if(!e)return"";const t=new URL(e),n=Date.now();return t.searchParams.set("pri",n.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:n=!1,failedError:i}){var a;if(this.state==="idle")return;const s=(Date.now()-this._reconnectStartTime)/1e3;n||(e?this._pushConsumer.emitReconnectStateChange({state:Lt.SUCCESS,teaParams:{reconnect_duration:s,session_id:this._pushConsumer.pushSessionId}}):(this._logger.log("Reconnect strategy stopped: ",t),this._pushConsumer.emitReconnectStateChange({state:Lt.FAILED,params:{failedCode:t},teaParams:{reason:t,reconnect_duration:s,error_message:i==null?void 0:i.message,http_code:(a=i==null?void 0:i.ext)==null?void 0:a.httpCode,ext:i==null?void 0:i.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:Dn.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 Nr={ManualStop:0,ReconnectFailed:1,StartPushError:2,PushError:3},Jt={PushCheck:0,PushError:1},Ka=new lt("PushController");class X_ extends Pa{constructor(e,{config:t,streamConsumeController:n,streamComposedController:i}){var s,a;if(super(e),this._connect=null,this._connectionState=Te.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=Vt(ps,"audio").bitrate,this._videoBitrate=Vt(hs,"video").bitrate,this.handleReconnectError=(o,d)=>{var c,u;V(j.STOP_PUSH_STREAM,{reason:Nr.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(Te.CONNECTED)},this._OnRTMPError=o=>{const d=new Ft(Ee.PUBLISH_FAILED,`code:${o.code}, message: ${o.message}`);this._streamConsumeController.emit(se.PushError,d),V(j.STOP_PUSH_STREAM,{reason:Nr.PushError,duration:this.pushDuration,session_id:this._pushSessionId,push_mode:this._pushMode,error_msg:o.message,error_code:o.code}),V(j.START_PUSH_STATUS,{is_success:!1,reason:Jt.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(Te.RECONNECTING),this.unpublish({isReconnecting:!0})},this._OnRtcStateChange=o=>{var d;switch(V(j.PUSH_RTC_STATE_CHANGE,{state:o,push_url:this._pushUrl,session_id:this._pushSessionId,push_mode:this._pushMode}),this._streamConsumeController.emit(se.RTCConnectStateChanged,o),o){case"connected":this.setConnectState(Te.CONNECTED);break;case"disconnected":this._reconnectStrategy&&this._executeReconnect();break;case"failed":(d=this._reconnectStrategy)!=null&&d.isActive()?this._executeReconnect():(this.connectionState===Te.CONNECTED?V(j.STOP_PUSH_STREAM,{reason:Nr.PushError,error_message:"peerconnection failed",duration:this.pushDuration,session_id:this._pushSessionId,push_mode:this._pushMode}):V(j.START_PUSH_STATUS,{is_success:!1,reason:Jt.PushError,error_message:"peerconnection failed",session_id:this._pushSessionId,push_mode:this._pushMode,push_url:this._pushUrl}),this.unpublish(),this._streamConsumeController.emit(se.PushError,new Ft(Ee.PUSH_CONNECT_FAILED,"pc failed")));break}},this._pushMode=(t==null?void 0:t.mode)||"rtm",this._streamConsumeController=n,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*Ao:void 0;this._reconnectStrategy=new J_(this,o),this._reconnectStrategy.onReconnectError=this.handleReconnectError}this._streamComposedController=i}get isPushing(){return this._connectionState===Te.CONNECTED||this._connectionState===Te.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(se.LiveConnectStateChange,e),e){case Te.CONNECTED:(t=this._reconnectStrategy)!=null&&t.isActive()?this._reconnectStrategy.stop({isSuccess:!0}):(this._streamConsumeController.emit(se.PushStart),this.setPushStatsInterval(),V(j.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(),V(j.START_PUSH,{push_url:e,session_id:this._pushSessionId})),!e)throw V(j.START_PUSH_STATUS,{is_success:!1,session_id:this._pushSessionId,reason:Jt.PushCheck,push_url:this._pushUrl}),new Error("lack publish url");if(this._connect)return;this.start(),this._pushUrl=e,this._pushEncodeConfig=t.cfg;const n=this._composedStream.videoTrack,i=this._composedStream.audioTrack;if(this._needCheckAudioTrack&&(!n||!i)){V(j.START_PUSH_STATUS,{is_success:!1,reason:Jt.PushCheck,push_url:this._pushUrl,error_message:"lack videoTrack or audioTrack",video_track_id:n==null?void 0:n.id,audio_track_id:i==null?void 0:i.id,video_track_name:n==null?void 0:n.label,audio_track_name:i==null?void 0:i.label,push_mode:this._pushMode,session_id:this._pushSessionId}),console.warn("lack videoTrack or audioTrack","videoTrack: ",n==null?void 0:n.id,"audioTrack: ",i==null?void 0:i.id);return}else if(!n&&!i){V(j.START_PUSH_STATUS,{is_success:!1,reason:Jt.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 F_(e,this._pushConfig,this._OnRtcStateChange):s=new W_(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(Te.CONNECTING),await s.publish([i,n],[this._audioBitrate,this._videoBitrate],{cfg:t.cfg,isReconnect:t.isReconnect}),t.isReconnect||(Ka.log("startPush begin"),this._connectionStartDate=Date.now())}catch(c){const u=new Ft(Ee.PUBLISH_FAILED,c.message,c);if(Ka.groupEnd(),(d=this._reconnectStrategy)!=null&&d.isActive())throw this.unpublish({isReconnecting:!0}),u;this._streamConsumeController.emit(se.PushError,u),V(j.STOP_PUSH_STREAM,{reason:Nr.PushError,error_message:u.message,enable_reconnect:!1,push_mode:this._pushMode,session_id:this._pushSessionId,duration:this.pushDuration}),V(j.START_PUSH_STATUS,{is_success:!1,push_url:this._pushUrl,reason:Jt.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,n,i;if((t=this._connect)!=null&&t.isPushing){const s=Date.now(),{stats:a,originStats:o}=await this._connect.getStatsSnapshoot(2e3),c=Date.now()-s;Kp(a)?this._prevStats=void 0:this._prevStats=a;const u=this.pushMode==="rtm"?L_(a,o):N_(a),h=this.pushMode==="rtm"?(n=this._connect)==null?void 0:n.videoSenderTrackStats:{};V(j.PUSH_STATS,{...u,...h,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 mn(2e3),V(j.PUSH_STATS,{push_url:this._pushUrl,push_mode:this._pushMode,session_id:this._pushSessionId,duration:2e3,is_push:!1,is_reconnecting:((i=this._reconnectStrategy)==null?void 0:i.isActive())??!1},!0);this.connectionState!==Te.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 n=[];e&&n.push(()=>{var i;return(i=this._connect)==null?void 0:i.updatePublish(e,"video")}),t&&n.push(()=>{var i;return(i=this._connect)==null?void 0:i.updatePublish(t,"audio")}),await Promise.all(n.map(i=>i()))}catch(n){const i=new Ft(Ee.UPDATE_PUBLISH_FAILED,`${n.name}, code:${n.code}`);this._streamConsumeController.emit(se.PushError,i)}}unpublish(e={isReconnecting:!1,isManual:!1}){var t,n,i,s,a;(t=this._connect)==null||t.unpublish(),this._connect=null,e.isManual&&(V(j.STOP_PUSH_STREAM,{reason:Nr.ManualStop,duration:this.pushDuration,session_id:this._streamConsumeController.pushSessionId,push_mode:this._pushMode,reconnect_times:(n=this._reconnectStrategy)==null?void 0:n.getReconnectInfo().totalReconnectCount,reconnect_duration:(i=this._reconnectStrategy)==null?void 0:i.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(Te.DISCONNECTED),(a=this._reconnectStrategy)==null||a.stop({quiet:!0}),this._streamConsumeController.emit(se.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,n){var i;t==="video"?this._videoBitrate=e:this._audioBitrate=e,(i=this._connect)==null||i.applyBitrate(e,t,n)}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:n}){V(j.PUSH_RECONNECT_STATUS,{status:e,...t,...n}),this._streamConsumeController.emit(se.ReconnectStateChange,e,t)}}class Z_ extends it{constructor(e,t){super(),this._previewConsumer=new k_(e.getComposedStream(),{streamConsumeController:this}),this._pushConsumer=new X_(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,n){this._pushConsumer.setBitrate(e,t,n)}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 Y_=()=>typeof window>"u",qe={},vn=async r=>{const e=new RTCPeerConnection({sdpSemantics:"unified-plan"});e.addTransceiver("video",{direction:r});const t=await e.createOffer();return e.close(),t.sdp.toLowerCase()};function Wa(r){const e=r.split(`
|
|
69
|
-
`);let t=!1;for(const n of e)if(n.includes("level-asymmetry-allowed=1")&&n.includes("packetization-mode=1")&&n.includes("profile-level-id=42e0")){t=!0;break}if(t){const n=navigator.userAgent.toLowerCase();let i=!1;const s=[/miuibrowser/,/70.*HeyTapBrowser/i];for(const a of s)a.test(n)&&(i=!0);return!i}return!1}const Q_=async()=>{let r=await vn("sendonly");return navigator.userAgent.includes("VivoBrowser")&&(r=await vn("sendonly")),qe.h264encode=Wa(r),qe.vp8encode=r.indexOf("vp8")>-1,qe},eg=async()=>{let r=await vn("recvonly");return navigator.userAgent.includes("VivoBrowser")&&(r=await vn("recvonly")),qe.h264decode=Wa(r),qe.vp8decode=r.indexOf("vp8")>-1,qe},tg=async()=>{if(typeof qe.h264encode>"u")try{await Q_()}catch{return!1}return qe.h264encode||!1},rg=async()=>{if(typeof qe.h264decode>"u")try{await eg()}catch{return!1}return qe.h264decode||!1};class ng{constructor(){this.onError=(e,t,n)=>{},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 ig=new ng;let Ja=!0,Xa=!0;function yn(r,e,t){const n=r.match(e);return n&&n.length>=t&&parseInt(n[t],10)}function zt(r,e,t){if(!r.RTCPeerConnection)return;const n=r.RTCPeerConnection.prototype,i=n.addEventListener;n.addEventListener=function(a,o){if(a!==e)return i.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),i.apply(this,[a,d])};const s=n.removeEventListener;n.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(n,"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 sg(r){return typeof r!="boolean"?new Error("Argument type: "+typeof r+". Please use a boolean."):(Ja=r,r?"adapter.js logging disabled":"adapter.js logging enabled")}function og(r){return typeof r!="boolean"?new Error("Argument type: "+typeof r+". Please use a boolean."):(Xa=!r,"adapter.js deprecation warnings "+(r?"disabled":"enabled"))}function Za(){if(typeof window=="object"){if(Ja)return;typeof console<"u"&&typeof console.log=="function"&&console.log.apply(console,arguments)}}function Wi(r,e){Xa&&console.warn(r+" is deprecated, please use "+e+" instead.")}function ag(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 n=t.userAgentData.brands.find(i=>i.brand==="Chromium");if(n)return{browser:"chrome",version:parseInt(n.version,10)}}if(t.mozGetUserMedia)e.browser="firefox",e.version=yn(t.userAgent,/Firefox\/(\d+)\./,1);else if(t.webkitGetUserMedia||r.isSecureContext===!1&&r.webkitRTCPeerConnection)e.browser="chrome",e.version=yn(t.userAgent,/Chrom(e|ium)\/(\d+)\./,2);else if(r.RTCPeerConnection&&t.userAgent.match(/AppleWebKit\/(\d+)\./))e.browser="safari",e.version=yn(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 Ya(r){return Object.prototype.toString.call(r)==="[object Object]"}function Qa(r){return Ya(r)?Object.keys(r).reduce(function(e,t){const n=Ya(r[t]),i=n?Qa(r[t]):r[t],s=n&&!Object.keys(i).length;return i===void 0||s?e:Object.assign(e,{[t]:i})},{}):r}function Ji(r,e,t){!e||t.has(e.id)||(t.set(e.id,e),Object.keys(e).forEach(n=>{n.endsWith("Id")?Ji(r,r.get(e[n]),t):n.endsWith("Ids")&&e[n].forEach(i=>{Ji(r,r.get(i),t)})}))}function ec(r,e,t){const n=t?"outbound-rtp":"inbound-rtp",i=new Map;if(e===null)return i;const s=[];return r.forEach(a=>{a.type==="track"&&a.trackIdentifier===e.id&&s.push(a)}),s.forEach(a=>{r.forEach(o=>{o.type===n&&o.trackId===a.id&&Ji(r,o,i)})}),i}const tc=Za;function rc(r,e){const t=r&&r.navigator;if(!t.mediaDevices)return;const n=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 h=function(l,f){return l?l+f.charAt(0).toUpperCase()+f.slice(1):f==="deviceId"?"sourceId":f};if(u.ideal!==void 0){d.optional=d.optional||[];let l={};typeof u.ideal=="number"?(l[h("min",c)]=u.ideal,d.optional.push(l),l={},l[h("max",c)]=u.ideal,d.optional.push(l)):(l[h("",c)]=u.ideal,d.optional.push(l))}u.exact!==void 0&&typeof u.exact!="number"?(d.mandatory=d.mandatory||{},d.mandatory[h("",c)]=u.exact):["min","max"].forEach(l=>{u[l]!==void 0&&(d.mandatory=d.mandatory||{},d.mandatory[h(l,c)]=u[l])})}),o.advanced&&(d.optional=(d.optional||[]).concat(o.advanced)),d},i=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,h,l){h in u&&!(l in u)&&(u[l]=u[h],delete u[h])};o=JSON.parse(JSON.stringify(o)),c(o.audio,"autoGainControl","googAutoGainControl"),c(o.audio,"noiseSuppression","googNoiseSuppression"),o.audio=n(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 h;if(c.exact==="environment"||c.ideal==="environment"?h=["back","rear"]:(c.exact==="user"||c.ideal==="user")&&(h=["front"]),h)return t.mediaDevices.enumerateDevices().then(l=>{l=l.filter(y=>y.kind==="videoinput");let f=l.find(y=>h.some(C=>y.label.toLowerCase().includes(C)));return!f&&l.length&&h.includes("back")&&(f=l[l.length-1]),f&&(o.video.deviceId=c.exact?{exact:f.deviceId}:{ideal:f.deviceId}),o.video=n(o.video),tc("chrome: "+JSON.stringify(o)),d(o)})}o.video=n(o.video)}return tc("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){i(o,u=>{t.webkitGetUserMedia(u,d,h=>{c&&c(s(h))})})};if(t.getUserMedia=a.bind(t),t.mediaDevices.getUserMedia){const o=t.mediaDevices.getUserMedia.bind(t.mediaDevices);t.mediaDevices.getUserMedia=function(d){return i(d,c=>o(c).then(u=>{if(c.audio&&!u.getAudioTracks().length||c.video&&!u.getVideoTracks().length)throw u.getTracks().forEach(h=>{h.stop()}),new DOMException("","NotFoundError");return u},u=>Promise.reject(s(u))))}}}function nc(r){r.MediaStream=r.MediaStream||r.webkitMediaStream}function ic(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=n=>{n.stream.addEventListener("addtrack",i=>{let s;r.RTCPeerConnection.prototype.getReceivers?s=this.getReceivers().find(o=>o.track&&o.track.id===i.track.id):s={track:i.track};const a=new Event("track");a.track=i.track,a.receiver=s,a.transceiver={receiver:s},a.streams=[n.stream],this.dispatchEvent(a)}),n.stream.getTracks().forEach(i=>{let s;r.RTCPeerConnection.prototype.getReceivers?s=this.getReceivers().find(o=>o.track&&o.track.id===i.id):s={track:i};const a=new Event("track");a.track=i,a.receiver=s,a.transceiver={receiver:s},a.streams=[n.stream],this.dispatchEvent(a)})},this.addEventListener("addstream",this._ontrackpoly)),e.apply(this,arguments)}}else zt(r,"track",e=>(e.transceiver||Object.defineProperty(e,"transceiver",{value:{receiver:e.receiver}}),e))}function sc(r){if(typeof r=="object"&&r.RTCPeerConnection&&!("getSenders"in r.RTCPeerConnection.prototype)&&"createDTMFSender"in r.RTCPeerConnection.prototype){const e=function(i,s){return{track:s,get dtmf(){return this._dtmf===void 0&&(s.kind==="audio"?this._dtmf=i.createDTMFSender(s):this._dtmf=null),this._dtmf},_pc:i}};if(!r.RTCPeerConnection.prototype.getSenders){r.RTCPeerConnection.prototype.getSenders=function(){return this._senders=this._senders||[],this._senders.slice()};const i=r.RTCPeerConnection.prototype.addTrack;r.RTCPeerConnection.prototype.addTrack=function(o,d){let c=i.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 n=r.RTCPeerConnection.prototype.removeStream;r.RTCPeerConnection.prototype.removeStream=function(s){this._senders=this._senders||[],n.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 n=e.apply(this,[]);return n.forEach(i=>i._pc=this),n},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 oc(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 n=r.RTCPeerConnection.prototype.addTrack;n&&(r.RTCPeerConnection.prototype.addTrack=function(){const s=n.apply(this,arguments);return s._pc=this,s}),r.RTCRtpSender.prototype.getStats=function(){const s=this;return this._pc.getStats().then(a=>ec(a,s.track,!0))}}if(!("getStats"in r.RTCRtpReceiver.prototype)){const t=r.RTCPeerConnection.prototype.getReceivers;t&&(r.RTCPeerConnection.prototype.getReceivers=function(){const i=t.apply(this,[]);return i.forEach(s=>s._pc=this),i}),zt(r,"track",n=>(n.receiver._pc=n.srcElement,n)),r.RTCRtpReceiver.prototype.getStats=function(){const i=this;return this._pc.getStats().then(s=>ec(s,i.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 n=arguments[0];let i,s,a;return this.getSenders().forEach(o=>{o.track===n&&(i?a=!0:i=o)}),this.getReceivers().forEach(o=>(o.track===n&&(s?a=!0:s=o),o.track===n)),a||i&&s?Promise.reject(new DOMException("There are more than one sender or receiver for the track.","InvalidAccessError")):i?i.getStats():s?s.getStats():Promise.reject(new DOMException("There is no sender or receiver for the track.","InvalidAccessError"))}return e.apply(this,arguments)}}function ac(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(h=>h.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 n=r.RTCPeerConnection.prototype.removeStream;r.RTCPeerConnection.prototype.removeStream=function(a){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},delete this._shimmedLocalStreams[a.id],n.apply(this,arguments)};const i=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]}),i.apply(this,arguments)}}function cc(r,e){if(!r.RTCPeerConnection)return;if(r.RTCPeerConnection.prototype.addTrack&&e.version>=65)return ac(r);const t=r.RTCPeerConnection.prototype.getLocalStreams;r.RTCPeerConnection.prototype.getLocalStreams=function(){const u=t.apply(this);return this._reverseStreams=this._reverseStreams||{},u.map(h=>this._reverseStreams[h.id])};const n=r.RTCPeerConnection.prototype.addStream;r.RTCPeerConnection.prototype.addStream=function(u){if(this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},u.getTracks().forEach(h=>{if(this.getSenders().find(f=>f.track===h))throw new DOMException("Track already exists.","InvalidAccessError")}),!this._reverseStreams[u.id]){const h=new r.MediaStream(u.getTracks());this._streams[u.id]=h,this._reverseStreams[h.id]=u,u=h}n.apply(this,[u])};const i=r.RTCPeerConnection.prototype.removeStream;r.RTCPeerConnection.prototype.removeStream=function(u){this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},i.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,h){if(this.signalingState==="closed")throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");const l=[].slice.call(arguments,1);if(l.length!==1||!l[0].getTracks().find(C=>C===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(C=>C.track===u))throw new DOMException("Track already exists.","InvalidAccessError");this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{};const y=this._streams[h.id];if(y)y.addTrack(u),Promise.resolve().then(()=>{this.dispatchEvent(new Event("negotiationneeded"))});else{const C=new r.MediaStream([u]);this._streams[h.id]=C,this._reverseStreams[C.id]=h,this.addStream(C)}return this.getSenders().find(C=>C.track===u)};function s(c,u){let h=u.sdp;return Object.keys(c._reverseStreams||[]).forEach(l=>{const f=c._reverseStreams[l],y=c._streams[f.id];h=h.replace(new RegExp(y.id,"g"),f.id)}),new RTCSessionDescription({type:u.type,sdp:h})}function a(c,u){let h=u.sdp;return Object.keys(c._reverseStreams||[]).forEach(l=>{const f=c._reverseStreams[l],y=c._streams[f.id];h=h.replace(new RegExp(f.id,"g"),y.id)}),new RTCSessionDescription({type:u.type,sdp:h})}["createOffer","createAnswer"].forEach(function(c){const u=r.RTCPeerConnection.prototype[c],h={[c](){const l=arguments;return arguments.length&&typeof arguments[0]=="function"?u.apply(this,[y=>{const C=s(this,y);l[0].apply(null,[C])},y=>{l[1]&&l[1].apply(null,y)},arguments[2]]):u.apply(this,arguments).then(y=>s(this,y))}};r.RTCPeerConnection.prototype[c]=h[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 l;Object.keys(this._streams).forEach(f=>{this._streams[f].getTracks().find(C=>u.track===C)&&(l=this._streams[f])}),l&&(l.getTracks().length===1?this.removeStream(this._reverseStreams[l.id]):l.removeTrack(u.track),this.dispatchEvent(new Event("negotiationneeded")))}}function Xi(r,e){!r.RTCPeerConnection&&r.webkitRTCPeerConnection&&(r.RTCPeerConnection=r.webkitRTCPeerConnection),r.RTCPeerConnection&&e.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach(function(t){const n=r.RTCPeerConnection.prototype[t],i={[t](){return arguments[0]=new(t==="addIceCandidate"?r.RTCIceCandidate:r.RTCSessionDescription)(arguments[0]),n.apply(this,arguments)}};r.RTCPeerConnection.prototype[t]=i[t]})}function uc(r,e){zt(r,"negotiationneeded",t=>{const n=t.target;if(!((e.version<72||n.getConfiguration&&n.getConfiguration().sdpSemantics==="plan-b")&&n.signalingState!=="stable"))return t})}const dc=Object.freeze(Object.defineProperty({__proto__:null,fixNegotiationNeeded:uc,shimAddTrackRemoveTrack:cc,shimAddTrackRemoveTrackWithNative:ac,shimGetSendersWithDtmf:sc,shimGetUserMedia:rc,shimMediaStream:nc,shimOnTrack:ic,shimPeerConnection:Xi,shimSenderReceiverGetStats:oc},Symbol.toStringTag,{value:"Module"}));function lc(r,e){const t=r&&r.navigator,n=r&&r.MediaStreamTrack;if(t.getUserMedia=function(i,s,a){Wi("navigator.getUserMedia","navigator.mediaDevices.getUserMedia"),t.mediaDevices.getUserMedia(i).then(s,a)},!(e.version>55&&"autoGainControl"in t.mediaDevices.getSupportedConstraints())){const i=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)),i(a.audio,"autoGainControl","mozAutoGainControl"),i(a.audio,"noiseSuppression","mozNoiseSuppression")),s(a)},n&&n.prototype.getSettings){const a=n.prototype.getSettings;n.prototype.getSettings=function(){const o=a.apply(this,arguments);return i(o,"mozAutoGainControl","autoGainControl"),i(o,"mozNoiseSuppression","noiseSuppression"),o}}if(n&&n.prototype.applyConstraints){const a=n.prototype.applyConstraints;n.prototype.applyConstraints=function(o){return this.kind==="audio"&&typeof o=="object"&&(o=JSON.parse(JSON.stringify(o)),i(o,"autoGainControl","mozAutoGainControl"),i(o,"noiseSuppression","mozNoiseSuppression")),a.apply(this,[o])}}}}function cg(r,e){r.navigator.mediaDevices&&"getDisplayMedia"in r.navigator.mediaDevices||r.navigator.mediaDevices&&(r.navigator.mediaDevices.getDisplayMedia=function(n){if(!(n&&n.video)){const i=new DOMException("getDisplayMedia without video constraints is undefined");return i.name="NotFoundError",i.code=8,Promise.reject(i)}return n.video===!0?n.video={mediaSource:e}:n.video.mediaSource=e,r.navigator.mediaDevices.getUserMedia(n)})}function hc(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 Zi(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(i){const s=r.RTCPeerConnection.prototype[i],a={[i](){return arguments[0]=new(i==="addIceCandidate"?r.RTCIceCandidate:r.RTCSessionDescription)(arguments[0]),s.apply(this,arguments)}};r.RTCPeerConnection.prototype[i]=a[i]});const t={inboundrtp:"inbound-rtp",outboundrtp:"outbound-rtp",candidatepair:"candidate-pair",localcandidate:"local-candidate",remotecandidate:"remote-candidate"},n=r.RTCPeerConnection.prototype.getStats;r.RTCPeerConnection.prototype.getStats=function(){const[s,a,o]=arguments;return n.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,h)=>{d.set(h,Object.assign({},u,{type:t[u.type]||u.type}))})}return d}).then(a,o)}}function pc(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 i=e.apply(this,[]);return i.forEach(s=>s._pc=this),i});const t=r.RTCPeerConnection.prototype.addTrack;t&&(r.RTCPeerConnection.prototype.addTrack=function(){const i=t.apply(this,arguments);return i._pc=this,i}),r.RTCRtpSender.prototype.getStats=function(){return this.track?this._pc.getStats(this.track):Promise.resolve(new Map)}}function fc(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 n=e.apply(this,[]);return n.forEach(i=>i._pc=this),n}),zt(r,"track",t=>(t.receiver._pc=t.srcElement,t)),r.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track)}}function mc(r){!r.RTCPeerConnection||"removeStream"in r.RTCPeerConnection.prototype||(r.RTCPeerConnection.prototype.removeStream=function(t){Wi("removeStream","removeTrack"),this.getSenders().forEach(n=>{n.track&&t.getTracks().includes(n.track)&&this.removeTrack(n)})})}function _c(r){r.DataChannel&&!r.RTCDataChannel&&(r.RTCDataChannel=r.DataChannel)}function gc(r){if(!(typeof r=="object"&&r.RTCPeerConnection))return;const e=r.RTCPeerConnection.prototype.addTransceiver;e&&(r.RTCPeerConnection.prototype.addTransceiver=function(){this.setParametersPromises=[];let n=arguments[1]&&arguments[1].sendEncodings;n===void 0&&(n=[]),n=[...n];const i=n.length>0;i&&n.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(i){const{sender:a}=s,o=a.getParameters();(!("encodings"in o)||o.encodings.length===1&&Object.keys(o.encodings[0]).length===0)&&(o.encodings=n,a.sendEncodings=n,this.setParametersPromises.push(a.setParameters(o).then(()=>{delete a.sendEncodings}).catch(()=>{delete a.sendEncodings})))}return s})}function vc(r){if(!(typeof r=="object"&&r.RTCRtpSender))return;const e=r.RTCRtpSender.prototype.getParameters;e&&(r.RTCRtpSender.prototype.getParameters=function(){const n=e.apply(this,arguments);return"encodings"in n||(n.encodings=[].concat(this.sendEncodings||[{}])),n})}function yc(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 Sc(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 bc=Object.freeze(Object.defineProperty({__proto__:null,shimAddTransceiver:gc,shimCreateAnswer:Sc,shimCreateOffer:yc,shimGetDisplayMedia:cg,shimGetParameters:vc,shimGetUserMedia:lc,shimOnTrack:hc,shimPeerConnection:Zi,shimRTCDataChannel:_c,shimReceiverGetStats:fc,shimRemoveStream:mc,shimSenderGetStats:pc},Symbol.toStringTag,{value:"Module"}));function Ec(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(n){this._localStreams||(this._localStreams=[]),this._localStreams.includes(n)||this._localStreams.push(n),n.getAudioTracks().forEach(i=>e.call(this,i,n)),n.getVideoTracks().forEach(i=>e.call(this,i,n))},r.RTCPeerConnection.prototype.addTrack=function(n,...i){return i&&i.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 n=this._localStreams.indexOf(t);if(n===-1)return;this._localStreams.splice(n,1);const i=t.getTracks();this.getSenders().forEach(s=>{i.includes(s.track)&&this.removeTrack(s)})})}}function Cc(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=n=>{n.streams.forEach(i=>{if(this._remoteStreams||(this._remoteStreams=[]),this._remoteStreams.includes(i))return;this._remoteStreams.push(i);const s=new Event("addstream");s.stream=i,this.dispatchEvent(s)})})}});const e=r.RTCPeerConnection.prototype.setRemoteDescription;r.RTCPeerConnection.prototype.setRemoteDescription=function(){const n=this;return this._onaddstreampoly||this.addEventListener("track",this._onaddstreampoly=function(i){i.streams.forEach(s=>{if(n._remoteStreams||(n._remoteStreams=[]),n._remoteStreams.indexOf(s)>=0)return;n._remoteStreams.push(s);const a=new Event("addstream");a.stream=s,n.dispatchEvent(a)})}),e.apply(n,arguments)}}}function wc(r){if(typeof r!="object"||!r.RTCPeerConnection)return;const e=r.RTCPeerConnection.prototype,t=e.createOffer,n=e.createAnswer,i=e.setLocalDescription,s=e.setRemoteDescription,a=e.addIceCandidate;e.createOffer=function(c,u){const h=arguments.length>=2?arguments[2]:arguments[0],l=t.apply(this,[h]);return u?(l.then(c,u),Promise.resolve()):l},e.createAnswer=function(c,u){const h=arguments.length>=2?arguments[2]:arguments[0],l=n.apply(this,[h]);return u?(l.then(c,u),Promise.resolve()):l};let o=function(d,c,u){const h=i.apply(this,[d]);return u?(h.then(c,u),Promise.resolve()):h};e.setLocalDescription=o,o=function(d,c,u){const h=s.apply(this,[d]);return u?(h.then(c,u),Promise.resolve()):h},e.setRemoteDescription=o,o=function(d,c,u){const h=a.apply(this,[d]);return u?(h.then(c,u),Promise.resolve()):h},e.addIceCandidate=o}function Tc(r){const e=r&&r.navigator;if(e.mediaDevices&&e.mediaDevices.getUserMedia){const t=e.mediaDevices,n=t.getUserMedia.bind(t);e.mediaDevices.getUserMedia=i=>n(kc(i))}!e.getUserMedia&&e.mediaDevices&&e.mediaDevices.getUserMedia&&(e.getUserMedia=(function(n,i,s){e.mediaDevices.getUserMedia(n).then(i,s)}).bind(e))}function kc(r){return r&&r.video!==void 0?Object.assign({},r,{video:Qa(r.video)}):r}function Rc(r){if(!r.RTCPeerConnection)return;const e=r.RTCPeerConnection;r.RTCPeerConnection=function(n,i){if(n&&n.iceServers){const s=[];for(let a=0;a<n.iceServers.length;a++){let o=n.iceServers[a];o.urls===void 0&&o.url?(Wi("RTCIceServer.url","RTCIceServer.urls"),o=JSON.parse(JSON.stringify(o)),o.urls=o.url,delete o.url,s.push(o)):s.push(n.iceServers[a])}n.iceServers=s}return new e(n,i)},r.RTCPeerConnection.prototype=e.prototype,"generateCertificate"in e&&Object.defineProperty(r.RTCPeerConnection,"generateCertificate",{get(){return e.generateCertificate}})}function Ac(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 Dc(r){const e=r.RTCPeerConnection.prototype.createOffer;r.RTCPeerConnection.prototype.createOffer=function(n){if(n){typeof n.offerToReceiveAudio<"u"&&(n.offerToReceiveAudio=!!n.offerToReceiveAudio);const i=this.getTransceivers().find(a=>a.receiver.track.kind==="audio");n.offerToReceiveAudio===!1&&i?i.direction==="sendrecv"?i.setDirection?i.setDirection("sendonly"):i.direction="sendonly":i.direction==="recvonly"&&(i.setDirection?i.setDirection("inactive"):i.direction="inactive"):n.offerToReceiveAudio===!0&&!i&&this.addTransceiver("audio",{direction:"recvonly"}),typeof n.offerToReceiveVideo<"u"&&(n.offerToReceiveVideo=!!n.offerToReceiveVideo);const s=this.getTransceivers().find(a=>a.receiver.track.kind==="video");n.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"):n.offerToReceiveVideo===!0&&!s&&this.addTransceiver("video",{direction:"recvonly"})}return e.apply(this,arguments)}}function xc(r){typeof r!="object"||r.AudioContext||(r.AudioContext=r.webkitAudioContext)}const Ic=Object.freeze(Object.defineProperty({__proto__:null,shimAudioContext:xc,shimCallbacksAPI:wc,shimConstraints:kc,shimCreateOfferLegacy:Dc,shimGetUserMedia:Tc,shimLocalStreamsAPI:Ec,shimRTCIceServerUrls:Rc,shimRemoteStreamsAPI:Cc,shimTrackEventTransceiver:Ac},Symbol.toStringTag,{value:"Module"}));var Yi={exports:{}},zc;function ug(){return zc||(zc=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
|
+
`},Wi}var Ba;function P_(){if(Ba)return Ue;Ba=1;var r=I_(),e=z_(),t=Ki();return Ue.grammar=t,Ue.write=e,Ue.parse=r.parse,Ue.parseParams=r.parseParams,Ue.parseFmtpConfig=r.parseFmtpConfig,Ue.parsePayloads=r.parsePayloads,Ue.parseRemoteCandidates=r.parseRemoteCandidates,Ue.parseImageAttributes=r.parseImageAttributes,Ue.parseSimulcastStreamList=r.parseSimulcastStreamList,Ue}var O_=P_();const Wt=_e(O_);function gn(r){return new Promise(e=>{setTimeout(e,r)})}async function M_(r,e={},t=0){const n=new AbortController;let i=!1;e=Object.assign({},e,{signal:n.signal});const s=[fetch(r,e)];t&&s.push(new Promise((a,o)=>{setTimeout(()=>{i||(o({httpCode:0,message:"Timeout"}),n.abort())},t)}));try{const a=await Promise.race(s);if(i=!0,!a.ok||a.status<200||a.status>=300)throw{httpCode:a.status,message:a.statusText};return a.json()}catch(a){throw i=!0,a}}async function Fa(r,e={},t={}){const{timeout:n=0,retryDelay:i=0}=t;let{retryCount:s=0}=t;try{return await M_(r,e,n)}catch(a){if(s--,t.retryCount=s,s<0)throw a;return await gn(i),await Fa(r,e,t)}}const Ji=-1;function he(r,e){let t;return e.forEach(n=>{n.type===r&&(t=n)}),t}async function Xi(r,e){const t={},n=await(r==null?void 0:r.getStats()),i=await(e==null?void 0:e.getStats());return n&&(t.audio={mediaSource:he("media-source",n),codec:he("codec",n),candidatePair:he("candidate-pair",n),remoteCandidate:he("remote-candidate",n),localCandidate:he("local-candidate",n),track:he("track",n),outboundRtp:he("outbound-rtp",n),remoteInboundRtp:he("remote-inbound-rtp",n),transport:he("transport",n)}),i&&(t.video={mediaSource:he("media-source",i),codec:he("codec",i),candidatePair:he("candidate-pair",i),remoteCandidate:he("remote-candidate",i),localCandidate:he("local-candidate",i),track:he("track",i),outboundRtp:he("outbound-rtp",i),remoteInboundRtp:he("remote-inbound-rtp",i),transport:he("transport",i)}),t}async function L_(r,e,t){var u,h,l,f,y,C,v,E,k,g,D,L,R,M,N,U,B,H,Y,W,de,ce,Ee,Ce,we,ye,Le,Ge,Te,_t,It,zt,Nr,Rn,An,Dn,Ur,gt,Gr;const n=await Xi(e,t);await gn(r);const i=await Xi(e,t),{audio:s,video:a}=n,{audio:o,video:d}=i,c={};if(s!=null&&s.codec&&(o!=null&&o.codec)){const De=((u=o.outboundRtp)==null?void 0:u.timestamp)-((h=s.outboundRtp)==null?void 0:h.timestamp),Br=((l=o.outboundRtp)==null?void 0:l.bytesSent)-((f=s.outboundRtp)==null?void 0:f.bytesSent),nt=((y=o.remoteInboundRtp)==null?void 0:y.packetsLost)-((C=s.remoteInboundRtp)==null?void 0:C.packetsLost),Pt=((v=o.outboundRtp)==null?void 0:v.packetsSent)-((E=s.outboundRtp)==null?void 0:E.packetsSent),Fr=(((k=o.mediaSource)==null?void 0:k.totalAudioEnergy)??0)-(((g=s.mediaSource)==null?void 0:g.totalAudioEnergy)??0);c.audio={codec:o.codec.mimeType,channels:o.codec.channels,sendBitrate:Br/De*8e3,packetsSent:(D=o.outboundRtp)==null?void 0:D.packetsSent,nackCount:(L=o.outboundRtp)==null?void 0:L.nackCount,packetsLost:(R=o.remoteInboundRtp)==null?void 0:R.packetsLost,packetsLostPercent:nt/Pt,deltaAudioEnergy:Fr}}if(a!=null&&a.codec&&(d!=null&&d.codec)){const De=((M=d.outboundRtp)==null?void 0:M.timestamp)-((N=a.outboundRtp)==null?void 0:N.timestamp),Br=((U=d.outboundRtp)==null?void 0:U.bytesSent)-((B=a.outboundRtp)==null?void 0:B.bytesSent),nt=((H=d.outboundRtp)==null?void 0:H.framesEncoded)-((Y=a.outboundRtp)==null?void 0:Y.framesEncoded),Pt=((W=d.outboundRtp)==null?void 0:W.totalEncodeTime)-((de=a.outboundRtp)==null?void 0:de.totalEncodeTime),Fr=((ce=d.outboundRtp)==null?void 0:ce.framesSent)-((Ee=a.outboundRtp)==null?void 0:Ee.framesSent),xn=((Ce=d.outboundRtp)==null?void 0:Ce.packetsSent)-((we=a.outboundRtp)==null?void 0:we.packetsSent),Vr=((ye=d.outboundRtp)==null?void 0:ye.totalPacketSendDelay)-((Le=a.outboundRtp)==null?void 0:Le.totalPacketSendDelay),os=((Ge=d.remoteInboundRtp)==null?void 0:Ge.packetsLost)-((Te=a.remoteInboundRtp)==null?void 0:Te.packetsLost);c.video={codec:d.codec.mimeType,sendBitrate:Br/De*8e3,frameWidth:(_t=d.outboundRtp)==null?void 0:_t.frameWidth,frameHeight:(It=d.outboundRtp)==null?void 0:It.frameHeight,framesPerSecond:Math.floor(Fr/De*1e3||0),framesEncoded:(zt=d.outboundRtp)==null?void 0:zt.framesEncoded,framesEncodedPerSecond:nt*1e3/De,keyFramesEncoded:(Nr=d.outboundRtp)==null?void 0:Nr.keyFramesEncoded,framesSent:(Rn=d.outboundRtp)==null?void 0:Rn.frameHeight,frameEncodeAvgTime:Pt*1e3/nt,packetsSent:(An=d.outboundRtp)==null?void 0:An.packetsSent,packetSendDelay:Vr*1e3/xn,nackCount:(Dn=d.outboundRtp)==null?void 0:Dn.nackCount,firCount:(Ur=d.outboundRtp)==null?void 0:Ur.firCount,pliCount:(gt=d.outboundRtp)==null?void 0:gt.pliCount,packetsLost:(Gr=d.remoteInboundRtp)==null?void 0:Gr.packetsLost,packetsLostPercent:os/xn,deltaTime:De}}return{stats:c,originStats:{audio:o,video:d}}}function ae(r,e=Ji){return r??e}function N_(r){var e,t,n,i,s,a,o,d,c,u,h,l,f,y,C,v,E,k,g,D,L,R,M,N,U,B,H,Y,W,de,ce,Ee,Ce,we,ye,Le,Ge,Te,_t,It,zt;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:(n=r.outboundRtp)==null?void 0:n.nackCount,audio_ssrc:(i=r.outboundRtp)==null?void 0:i.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)):(h=r.mediaSource)==null?void 0:h.audioLevel,audio_volume:(l=r.mediaSource)!=null&&l.audioLevel?((f=r.mediaSource)==null?void 0:f.audioLevel)*255:(y=r.mediaSource)==null?void 0:y.audioLevel,audio_total_audio_energy:(C=r.mediaSource)==null?void 0:C.totalAudioEnergy,audio_total_input_duration:(v=r.mediaSource)==null?void 0:v.totalSamplesDuration,audio_send_level:(E=r.mediaSource)==null?void 0:E.audioLevel,audio_ice_available_outgoing_bitrate:(k=r.candidatePair)==null?void 0:k.availableOutgoingBitrate,audio_ice_bytes_received:(g=r.candidatePair)==null?void 0:g.bytesReceived,audio_ice_bytes_sent:(D=r.candidatePair)==null?void 0:D.bytesSent,audio_ice_nominated:(L=r.candidatePair)==null?void 0:L.nominated,audio_ice_pair_id:(R=r.candidatePair)==null?void 0:R.id,audio_ice_pair_rtt:(M=r.candidatePair)==null?void 0:M.currentRoundTripTime,audio_ice_pair_state:(N=r.candidatePair)==null?void 0:N.state,audio_ice_pair_writable:(U=r.candidatePair)==null?void 0:U.writable,audio_recv_ping_requests:(B=r.candidatePair)==null?void 0:B.requestsReceived,audio_recv_ping_responses:(H=r.candidatePair)==null?void 0:H.responsesReceived,audio_sent_ping_requests_before_first_response:(Y=r.candidatePair)==null?void 0:Y.requestsSent,audio_sent_ping_requests_total:(((W=r.candidatePair)==null?void 0:W.requestsSent)??0)+(((de=r.candidatePair)==null?void 0:de.consentRequestsSent)??0),audio_sent_ping_responses:(ce=r.candidatePair)==null?void 0:ce.responsesSent,audio_local_candidate_type:(Ee=r.localCandidate)==null?void 0:Ee.candidateType,audio_local_ip:((Ce=r.localCandidate)==null?void 0:Ce.ip)||((we=r.localCandidate)==null?void 0:we.address),audio_local_network_type:(ye=r.localCandidate)==null?void 0:ye.networkType,audio_local_port:(Le=r.localCandidate)==null?void 0:Le.port,audio_local_protocol:(Ge=r.localCandidate)==null?void 0:Ge.protocol,audio_remote_candidate_type:(Te=r.remoteCandidate)==null?void 0:Te.candidateType,audio_remote_ip:((_t=r.remoteCandidate)==null?void 0:_t.ip)||((It=r.remoteCandidate)==null?void 0:It.address),audio_remote_port:(zt=r.remoteCandidate)==null?void 0:zt.port}}function U_(r){var e,t,n,i,s,a,o,d,c,u,h,l,f,y,C,v,E,k,g,D,L,R,M,N,U,B,H,Y,W,de,ce,Ee,Ce,we,ye,Le,Ge;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:(n=r.outboundRtp)==null?void 0:n.ssrc,video_quality_limitation_reason:(i=r.outboundRtp)==null?void 0:i.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:(h=r.candidatePair)==null?void 0:h.availableOutgoingBitrate,video_ice_bytes_received:(l=r.candidatePair)==null?void 0:l.bytesReceived,video_ice_bytes_sent:(f=r.candidatePair)==null?void 0:f.bytesSent,video_ice_nominated:(y=r.candidatePair)==null?void 0:y.nominated,video_ice_pair_id:(C=r.candidatePair)==null?void 0:C.id,video_ice_pair_rtt:(v=r.candidatePair)==null?void 0:v.currentRoundTripTime,video_ice_pair_state:(E=r.candidatePair)==null?void 0:E.state,video_ice_pair_writable:(k=r.candidatePair)==null?void 0:k.writable,video_recv_ping_requests:(g=r.candidatePair)==null?void 0:g.requestsReceived,video_recv_ping_responses:(D=r.candidatePair)==null?void 0:D.responsesReceived,video_sent_ping_requests_before_first_response:(L=r.candidatePair)==null?void 0:L.requestsSent,video_sent_ping_requests_total:(((R=r.candidatePair)==null?void 0:R.requestsSent)??0)+(((M=r.candidatePair)==null?void 0:M.consentRequestsSent)??0),video_sent_ping_responses:(N=r.candidatePair)==null?void 0:N.responsesSent,video_local_candidate_type:(U=r.localCandidate)==null?void 0:U.candidateType,video_local_ip:((B=r.localCandidate)==null?void 0:B.ip)||((H=r.localCandidate)==null?void 0:H.address),video_local_network_type:(Y=r.localCandidate)==null?void 0:Y.networkType,video_local_port:(W=r.localCandidate)==null?void 0:W.port,video_local_protocol:(de=r.localCandidate)==null?void 0:de.protocol,video_remote_candidate_type:(ce=r.remoteCandidate)==null?void 0:ce.candidateType,video_remote_ip:((Ee=r.remoteCandidate)==null?void 0:Ee.ip)||((Ce=r.remoteCandidate)==null?void 0:Ce.address),video_remote_port:(we=r.remoteCandidate)==null?void 0:we.port,video_input_frame_rate:(ye=r.mediaSource)==null?void 0:ye.framesPerSecond,video_input_frame_width:(Le=r.mediaSource)==null?void 0:Le.width,video_input_frame_height:(Ge=r.mediaSource)==null?void 0:Ge.height}}function G_(r,e,t){var c,u,h,l,f,y,C,v,E,k,g,D,L,R,M,N,U,B,H,Y,W,de,ce,Ee,Ce,we,ye;const n=U_(e.video??{}),{video_input_frame_width:i,video_input_frame_height:s}=n,a=ae((c=r.video)==null?void 0:c.frameWidth),o=ae((u=r.video)==null?void 0:u.frameHeight),d=a<Number(i)||o<Number(s);return{...n,video_send_k_bitrate:ae((h=r.video)==null?void 0:h.sendBitrate)/1e3,video_send_frame_rate:ae((l=r.video)==null?void 0:l.framesPerSecond),video_encode_avg_time:ae((f=r.video)==null?void 0:f.frameEncodeAvgTime),video_encoder_output_frame_rate:ae((y=r.video)==null?void 0:y.framesEncodedPerSecond),video_encoded_frame_width:ae((C=r.video)==null?void 0:C.frameWidth),video_encoded_frame_height:ae((v=r.video)==null?void 0:v.frameHeight),video_encoded_key_frames:ae((E=r.video)==null?void 0:E.keyFramesEncoded),video_delta_time:ae((k=r.video)==null?void 0:k.deltaTime,2e3),video_packets_sent:ae((g=r.video)==null?void 0:g.packetsSent),video_nack_count:ae((D=r.video)==null?void 0:D.nackCount),video_fir_count:ae((L=r.video)==null?void 0:L.firCount),video_pli_count:ae((R=r.video)==null?void 0:R.pliCount),video_packets_lost:ae((M=r.video)==null?void 0:M.packetsLost),video_packets_lost_percent:(N=r.video)==null?void 0:N.packetsLostPercent,video_codec:(U=r.video)==null?void 0:U.codec,video_duration:(B=r.video)==null?void 0:B.deltaTime,video_frame_rate_compliance:t!=null&&t.idealFrameRate?Math.min(ae((H=r.video)==null?void 0:H.framesPerSecond)/t.idealFrameRate,1)*100:Ji,video_bitrate_compliance:t!=null&&t.idealBitrate?Math.min(ae((Y=r.video)==null?void 0:Y.sendBitrate)/t.idealBitrate,1)*100:Ji,video_resolution_downgrade:d,...N_(e.audio??{}),audio_send_k_bitrate:ae((W=r.audio)==null?void 0:W.sendBitrate)/1e3,audio_send_channels:ae((de=r.audio)==null?void 0:de.channels),audio_packets_sent:ae((ce=r.audio)==null?void 0:ce.packetsSent),audio_packets_lost:ae((Ee=r.audio)==null?void 0:Ee.packetsLost),audio_packets_lost_percent:(Ce=r.audio)==null?void 0:Ce.packetsLostPercent,audio_codec:(we=r.audio)==null?void 0:we.codec,audio_delta_energy:(ye=r.audio)==null?void 0:ye.deltaAudioEnergy}}function B_(r){return{video_send_k_bitrate:r.video.sendBitrate/1e3,video_send_frame_rate:r.video.framesPerSecond,video_encoded_frame_width:r.video.frameWidth,video_encoded_frame_height:r.video.frameHeight,video_encoded_key_frames:r.video.keyFramesEncoded,video_send_speed:r.video.sendSpeed/1e3,video_gop_size:r.video.gopSize,video_codec:r.video.codec,video_duration:0,audio_send_k_bitrate:r.audio.sendBitrate/1e3,audio_codec:r.audio.codec,audio_send_channels:r.audio.channels,audio_send_sample_rate:r.audio.sampleRate}}const F_="42001f",V_="42e01f",j_=r=>{var t;if(!Es)return;const e=(t=r.rtp.filter(n=>n.codec==="opus")[0])==null?void 0:t.payload;e&&r.fmtp.forEach(n=>{n.payload===e&&(n.config="minptime=10;useinbandfec=1")})},H_=r=>{r.ext&&(tu||Hr)&&(r.ext=r.ext.filter(e=>{var t;return!((t=e.uri)!=null&&t.includes("video-orientation"))}))};function q_(r,e){r==null||r.rtp.forEach(({codec:t,payload:n})=>{if(["vp8","h264"].includes(t.toLocaleLowerCase())){const i=r.fmtp.find(s=>s.payload===n);i?i.config=[...i.config.split(";"),`x-google-min-bitrate=${e*.4}`,`x-google-start-bitrate=${e}`].join(";"):r.fmtp.push({payload:n,config:`x-google-min-bitrate=${e*.4};x-google-start-bitrate=${e}`})}})}function Va(r,e){if(!Array.isArray(r.fmtp)||!Array.isArray(r.rtp))return;const t=r.fmtp.find(a=>a.config&&a.config.includes(F_)),n=r.fmtp.find(a=>a.config&&a.config.includes(V_));if(!t||!n)return;const i=r.rtp.findIndex(a=>a.payload===t.payload),s=r.rtp.findIndex(a=>a.payload===n.payload);if(i!==-1&&s!==-1){if(e==="hardware"){if(s<i){const a=r.rtp[s];r.rtp[s]=r.rtp[i],r.rtp[i]=a}}else if(i<s){const a=r.rtp[i];r.rtp[i]=r.rtp[s],r.rtp[s]=a}}r.payloads=r.rtp.map(a=>a.payload).join(" ")}const ve=new ht("PCConnect");class $_{constructor(e,t,n){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=n}get isPushing(){var e,t,n,i;return!!((t=(e=this._videoTransceiver)==null?void 0:e.sender)!=null&&t.track||(i=(n=this._audioTransceiver)==null?void 0:n.sender)!=null&&i.track)}get videoSenderTrackStats(){var e,t,n,i;return{track_enabled:(t=(e=this._videoTransceiver)==null?void 0:e.sender.track)==null?void 0:t.enabled,track_muted:(i=(n=this._videoTransceiver)==null?void 0:n.sender.track)==null?void 0:i.muted}}get pushUrl(){return this._signalUrl}get sessionId(){return this._sessionId}async publish(e,t,n){var h;const i=new RTCPeerConnection;this._pc=i,this._bindRTCEvent();const s=e.filter(l=>(l==null?void 0:l.kind)==="audio")[0],a=e.filter(l=>(l==null?void 0:l.kind)==="video")[0];s&&this._ms.addTrack(s),a&&this._ms.addTrack(a),this._audioTransceiver=i.addTransceiver(s||"audio",{direction:"sendonly",sendEncodings:[{maxBitrate:t[0]}],streams:[this._ms]}),ve.log("add track to pc,",s),this._videoTransceiver=i.addTransceiver(a||"video",{direction:"sendonly",sendEncodings:[{maxBitrate:t[1]}],streams:[this._ms]}),ve.log("add track to pc,",a);const o=await i.createOffer();ve.groupCollapsed("local offer"),ve.log(o.sdp);const d=Wt.parse(o.sdp);d.media.forEach(l=>{l.type==="audio"?j_(l):l.type==="video"&&(H_(l),Va(l,"software"),q_(l,t[1]))}),o.sdp=Wt.write(d),ve.log("local offer modified"),ve.log(o.sdp),await i.setLocalDescription(o);const c=await Fa(this._signalUrl,{method:"POST",mode:"cors",body:JSON.stringify({sessionId:""+this._sessionId,version:"1.0-html",localSdp:o,metadata:{platform:"Web"}})},{...this._opts,timeout:n!=null&&n.isReconnect?10*xo:(h=this._opts)==null?void 0:h.timeout});if((c==null?void 0:c.code)!==200)throw{code:c.code,message:c.message};ve.log("remote answer:"),ve.log(c.remoteSdp.sdp);const u=Wt.parse(c.remoteSdp.sdp);if(u.media.forEach(l=>{var f;(f=l.fingerprint)!=null&&f.hash&&(l.fingerprint.hash=l.fingerprint.hash.toUpperCase())}),c.remoteSdp.sdp=Wt.write(u),ve.log("remote answer modified"),ve.log(c.remoteSdp.sdp),ve.groupEnd(),i.connectionState==="closed"){ve.log("PeerConnection is closed, skipping setRemoteDescription");return}V(j.PUSH_SDP_INFO,{offer_sdp:o.sdp,answer_sdp:c.remoteSdp.sdp}),await i.setRemoteDescription(c.remoteSdp)}updateVideoEncodeType(e){var s,a;const t=this._pc,n=(s=t==null?void 0:t.localDescription)==null?void 0:s.sdp,i=(a=t==null?void 0:t.remoteDescription)==null?void 0:a.sdp;if(n&&i){const o=Wt.parse(i);o.media.forEach(d=>{d.type==="video"&&Va(d,e)}),t.setLocalDescription(t.localDescription),t.setRemoteDescription({type:"answer",sdp:Wt.write(o)})}}async updatePublish(e,t){var s,a;let n;t==="video"?n=this._videoTransceiver:n=this._audioTransceiver;const i=(s=n==null?void 0:n.sender)==null?void 0:s.track;(i==null?void 0:i.id)!==(e==null?void 0:e.id)&&(await((a=n==null?void 0:n.sender)==null?void 0:a.replaceTrack(e)),ve.log(`replace ${t} track done! ${i==null?void 0:i.label} -> ${e==null?void 0:e.label}`))}applyBitrate(e,t,n){var a,o,d;const i=t==="video"?(a=this._videoTransceiver)==null?void 0:a.sender:(o=this._audioTransceiver)==null?void 0:o.sender;if(!i)return;const s=i.getParameters();s.encodings=(d=s.encodings)!=null&&d.length?s.encodings:[{}],n?s.encodings[0].minBitrate=e:s.encodings[0].maxBitrate=e,i.setParameters(s),ve.log(`set bitrate for ${t}, ${e} bps, min:${n}`)}unpublish(){var e,t;(e=this._pc)==null||e.getSenders().forEach(n=>{var i;(i=this._pc)==null||i.removeTrack(n)}),(t=this._pc)==null||t.close(),this._audioTransceiver=null,this._videoTransceiver=null,this._pc=null,ve.log("close pc!")}getStats(){var e,t;return Xi((e=this._audioTransceiver)==null?void 0:e.sender,(t=this._videoTransceiver)==null?void 0:t.sender)}getStatsSnapshoot(e){var t,n;return L_(e||100,(t=this._audioTransceiver)==null?void 0:t.sender,(n=this._videoTransceiver)==null?void 0:n.sender)}_bindRTCEvent(){const e=this._pc;e==null||e.addEventListener("connectionstatechange",()=>{ve.log("onconnectionstatechange:",e.connectionState),this._onConnectStateChange(e.connectionState)})}}var pt=(r=>(r.OnError="onerror",r.OnConnectClosed="onconnectclosed",r.OnFirstFramePushed="onfirstframepushed",r))(pt||{}),ft=(r=>(r.Video="video",r.Audio="audio",r))(ft||{}),Oe=(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))(Oe||{}),Dt=(r=>(r.Ready="ready",r.Error="error",r.FirstFramePushed="firstframepushed",r.Flvfile="flvfile",r.STATS="stats",r.Close="close",r))(Dt||{}),Zi={exports:{}},ja;function K_(){return ja||(ja=1,function(r){var e=Object.prototype.hasOwnProperty,t="~";function n(){}Object.create&&(n.prototype=Object.create(null),new n().__proto__||(t=!1));function i(d,c,u){this.fn=d,this.context=c,this.once=u||!1}function s(d,c,u,h,l){if(typeof u!="function")throw new TypeError("The listener must be a function");var f=new i(u,h||d,l),y=t?t+c:c;return d._events[y]?d._events[y].fn?d._events[y]=[d._events[y],f]:d._events[y].push(f):(d._events[y]=f,d._eventsCount++),d}function a(d,c){--d._eventsCount===0?d._events=new n:delete d._events[c]}function o(){this._events=new n,this._eventsCount=0}o.prototype.eventNames=function(){var c=[],u,h;if(this._eventsCount===0)return c;for(h in u=this._events)e.call(u,h)&&c.push(t?h.slice(1):h);return Object.getOwnPropertySymbols?c.concat(Object.getOwnPropertySymbols(u)):c},o.prototype.listeners=function(c){var u=t?t+c:c,h=this._events[u];if(!h)return[];if(h.fn)return[h.fn];for(var l=0,f=h.length,y=new Array(f);l<f;l++)y[l]=h[l].fn;return y},o.prototype.listenerCount=function(c){var u=t?t+c:c,h=this._events[u];return h?h.fn?1:h.length:0},o.prototype.emit=function(c,u,h,l,f,y){var C=t?t+c:c;if(!this._events[C])return!1;var v=this._events[C],E=arguments.length,k,g;if(v.fn){switch(v.once&&this.removeListener(c,v.fn,void 0,!0),E){case 1:return v.fn.call(v.context),!0;case 2:return v.fn.call(v.context,u),!0;case 3:return v.fn.call(v.context,u,h),!0;case 4:return v.fn.call(v.context,u,h,l),!0;case 5:return v.fn.call(v.context,u,h,l,f),!0;case 6:return v.fn.call(v.context,u,h,l,f,y),!0}for(g=1,k=new Array(E-1);g<E;g++)k[g-1]=arguments[g];v.fn.apply(v.context,k)}else{var D=v.length,L;for(g=0;g<D;g++)switch(v[g].once&&this.removeListener(c,v[g].fn,void 0,!0),E){case 1:v[g].fn.call(v[g].context);break;case 2:v[g].fn.call(v[g].context,u);break;case 3:v[g].fn.call(v[g].context,u,h);break;case 4:v[g].fn.call(v[g].context,u,h,l);break;default:if(!k)for(L=1,k=new Array(E-1);L<E;L++)k[L-1]=arguments[L];v[g].fn.apply(v[g].context,k)}}return!0},o.prototype.on=function(c,u,h){return s(this,c,u,h,!1)},o.prototype.once=function(c,u,h){return s(this,c,u,h,!0)},o.prototype.removeListener=function(c,u,h,l){var f=t?t+c:c;if(!this._events[f])return this;if(!u)return a(this,f),this;var y=this._events[f];if(y.fn)y.fn===u&&(!l||y.once)&&(!h||y.context===h)&&a(this,f);else{for(var C=0,v=[],E=y.length;C<E;C++)(y[C].fn!==u||l&&!y[C].once||h&&y[C].context!==h)&&v.push(y[C]);v.length?this._events[f]=v.length===1?v[0]:v:a(this,f)}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 n,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}(Zi)),Zi.exports}var W_=K_();const J_=_e(W_);var vn=(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))(vn||{});class Ha extends Error{constructor(e,t,n){super(),this.code=e,this.message=t,n&&(this.ext=n),this.toJson=()=>({code:this.code,message:this.message,ext:this.ext})}}function qa(r,e,t){return new Ha(r,e,t)}const Zt=class Zt{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 Zt.enable}get _enableLong(){return Zt.enableLong}get long(){return this._enableLong}};Zt.enable=!1,Zt.enableLong=!1;let mt=Zt;const Me=new mt("RTMP_Capture");class X_{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(Me.log(`replace ${e} track`),e===ft.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 i;if(!this.videoTrack){Me.log("no video track to capture");return}if(this.videoTrack.readyState!=="live"){Me.warn("video track not live");return}const e=new MediaStreamTrackProcessor(this.videoTrack);e.track=this.videoTrack;const t=e.readable.getReader();this._videoProcessorReader=t,Me.log("start capture video frame",this.videoTrack);let n;for(;;){n&&clearInterval(n),n=setTimeout(()=>{Me.warn("long time no capture output"),this._bridge._postMockVideoEncodeFlag()},1500);const s=await t.read();if(clearInterval(n),this._videoFirstframeCaptured||(this._videoFirstframeCaptured=!0,Me.log("video first frame captured")),s.done||!s.value){(i=s.value)==null||i.close();break}this._bridge._postVideoFrame(s.value,this.videoTrack.getSettings())}clearInterval(n),this._videoFirstframeCaptured=!1,this._videoProcessorReader=null,Me.log("video track read done!",e.track)}async _startAudioCapture(){if(!this.audioTrack){Me.log("no audio track to capture");return}if(this.audioTrack.readyState!=="live"){Me.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,Me.log("start capture audio frame");;){const n=await t.read();if(this._audioFirstframeCaptured||(this._audioFirstframeCaptured=!0,Me.log("audio first frame captured")),n.done||!n.value)break;this._bridge._postAudioFrame(n.value,this.audioTrack.getSettings())}this._audioFirstframeCaptured=!1,this._audioProcessorReader=null,Me.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 $a='(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',Ka=typeof self<"u"&&self.Blob&&new Blob([$a],{type:"text/javascript;charset=utf-8"});function Z_(r){let e;try{if(e=Ka&&(self.URL||self.webkitURL).createObjectURL(Ka),!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($a),{name:r==null?void 0:r.name})}finally{e&&(self.URL||self.webkitURL).revokeObjectURL(e)}}try{mt.enable=location.href.indexOf("rtmpdebug")!==-1,mt.enableLong=location.href.indexOf("rtmpdebug=long")!==-1}catch{}const yn=new mt("Bridge");class Wa extends J_{constructor(){super(),this._worker=null,this._audioMsTrack=null,this._videoMsTrack=null,this._capture=new X_(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 n=new Promise((o,d)=>{e=o,t=d}),i=o=>{var d;switch((d=this._worker)==null||d.removeEventListener("message",i),o.data.type){case Dt.Error:t(o.data.data);break;default:this._bindWorkerEvent(),yn.log("rtmp ready!"),e(!0)}};try{this._worker=new Z_}catch(o){t(qa(vn.RTMP_INIT_FAIL,o.message))}return(s=this._worker)==null||s.postMessage({type:Oe.Init,options:{logEnable:mt.enable,logEnableLong:mt.enableLong}}),(a=this._worker)==null||a.addEventListener("message",i),n}_bindWorkerEvent(){var e,t;(e=this._worker)==null||e.addEventListener("message",n=>{switch(n.data.type){case Dt.Error:yn.table(n.data.data),this.emit(pt.OnError,n.data.data);break;case Dt.Flvfile:Y_(n.data.buffer);break;case Dt.FirstFramePushed:this.emit(pt.OnFirstFramePushed);break;case Dt.Close:this.emit(pt.OnConnectClosed),this.destroy();break}}),(t=this._worker)==null||t.addEventListener("error",n=>{this.emit(pt.OnError,qa(vn.WORKER_ERROR,n.message))})}addTrack(e){e.kind===ft.Video&&(this._videoMsTrack=e),e.kind===ft.Audio&&(this._audioMsTrack=e),this._setAVExist(!!this._videoMsTrack,!!this._audioMsTrack)}replaceTrack(e,t){e===ft.Video&&(this._videoMsTrack=t),e===ft.Audio&&(this._audioMsTrack=t),this._setAVExist(!!this._videoMsTrack,!!this._audioMsTrack),this._capture.restartCapture(e)}async getStats(){var s,a;let e,t;const n=new Promise((o,d)=>{e=o,t=d});this._worker||setTimeout(()=>{t()},0);const i=o=>{var d;switch(o.data.type){case Dt.STATS:e(o.data.data),(d=this._worker)==null||d.removeEventListener("message",i);break}};return(s=this._worker)==null||s.addEventListener("message",i),(a=this._worker)==null||a.postMessage({type:Oe.GetStats}),n}_postVideoFrame(e,t){var n;(n=this._worker)==null||n.postMessage({type:Oe.VideoFrame,frame:e,setting:t},[e])}_postMockVideoEncodeFlag(){var e;(e=this._worker)==null||e.postMessage({type:Oe.MockVideoEncode})}_setAVExist(e,t){var n;(n=this._worker)==null||n.postMessage({type:Oe.AvExist,hasVideo:e,hasAudio:t})}_postAudioFrame(e,t){var n;(n=this._worker)==null||n.postMessage({type:Oe.AudioFrame,frame:e,setting:t},[e])}setEncodeCapacity(e){var t;(t=this._worker)==null||t.postMessage({type:Oe.EncodeConfig,cfg:e})}adjustBitrate(e,t){var n;(n=this._worker)==null||n.postMessage({type:Oe.AdjustBitrate,kind:e,bitrate:t})}publish(e){var t;yn.log("start capture & connect"),this._capture.start(),(t=this._worker)==null||t.postMessage({type:Oe.Publish,url:e})}unpublish(){var e;this._capture.destroy(),(e=this._worker)==null||e.postMessage({type:Oe.UnPublish})}destroy(){var e;yn.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:Oe.Download})}}function Y_(r){const e=document.createElement("a");e.href=URL.createObjectURL(new Blob([r])),e.download=Date.now()+".flv",e.click()}const Ja=new ht("RTMPConnect");class Q_{constructor(e,t,n,i){this._opts=void 0,this._isPushing=!1,this._url=e,this._opts=t,this._onError=n,this._OnSuccess=i,this._rtmp=new Wa,this._bindEvents()}get isPushing(){return this._isPushing}get pushUrl(){return this._url}get sessionId(){return 0}_bindEvents(){this._rtmp.on(pt.OnError,e=>{this._isPushing=!1,this._onError(e)}),this._rtmp.on(pt.OnConnectClosed,()=>{this._isPushing=!1,this._onError(new Ha(vn.WTP_CONNECT_FAIL,"connect lost"))}),this._rtmp.on(pt.OnFirstFramePushed,()=>{this._isPushing=!0,this._OnSuccess()})}async publish(e,t,n){await this._rtmp.ready(),n!=null&&n.cfg&&this._rtmp.setEncodeCapacity(n.cfg),e.filter(Boolean).forEach(i=>this._rtmp.addTrack(i)),t[0]&&this._rtmp.adjustBitrate(ft.Audio,t[0]),t[1]&&this._rtmp.adjustBitrate(ft.Video,t[1]),this._rtmp.publish(this._url)}updatePublish(e,t){Ja.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 gn(e),{stats:await this._rtmp.getStats(),originStats:void 0}}unpublish(){Ja.warn("unpublish"),this._rtmp.unpublish(),this._isPushing=!1}}function Xa({pushUrl:r,addPri:e=!1,disableTCC:t=!1}){const n=new URL(r),i=Date.now();return e&&n.searchParams.set("pri",i.toString()),t&&n.searchParams.set("tcc","false"),n.href}class eg{constructor(e,t=cf){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=(n=!1)=>{var i;this._logger.log("start reconnect strategy"),this.state==="idle"&&(this._reconnectStartTime=Date.now(),this._totalReconnectInfo.totalReconnectCount+=1,V(j.PUSH_RECONNECT_START,{start_time:this._reconnectStartTime,session_id:this._pushConsumer.pushSessionId,max_timeout:this._maxTimeout}),this.bindOnlineEvent(),this.setStrategyState("executing"),(i=this._logger)==null||i.log("start reconnecting with max timeout: ",this._maxTimeout),this.startTimeoutTimer(this._maxTimeout),this._pushConsumer.emitReconnectStateChange({state:Mt.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(n))},this.attemptReconnect=async()=>{var n;if(this.state==="executing"){this.setStrategyState("reconnecting"),this._reconnectCount+=1;const i=this.getNextPushUrl();try{if(this._pushConsumer.emitReconnectStateChange({state:Mt.RECONNECTING,params:{retryTime:this._reconnectCount},teaParams:{retry_push_url:i,session_id:this._pushConsumer.pushSessionId}}),await this._pushConsumer.reconnect(i),!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:zn.PushUrlInvalid,failedError:s}),(n=this._onReconnectError)==null||n.call(this,"pushError",s);else{if(!this.isActive())return;this.setStrategyState("executing"),this.execute()}}}},this.executeStrategy=(n=!1)=>{const i=n?0:this._reconnectDelay;this._pushConsumer.emitReconnectStateChange({state:Mt.WAITING,params:{waitingTime:i,retryTime:this._reconnectCount+1},teaParams:{is_online:navigator.onLine,session_id:this._pushConsumer.pushSessionId}}),this._logger.log("reconnect after delay: ",i,Date.now()),this._reconnectTimeout=window.setTimeout(this.attemptReconnect,i),this._reconnectDelay=this._reconnectDelay===0?2e3:Math.min(this._reconnectDelay*2,uf)},this.state="idle",this._pushConsumer=e,this._maxTimeout=t,this._logger=new ht("ReconnectStrategy")}getNextPushUrl(){const e=this._pushConsumer.pushUrl;return e?Xa({pushUrl:e,addPri:!0}):""}set onReconnectError(e){this._onReconnectError=e}bindOnlineEvent(){window.addEventListener("online",this.handleOnlineReconnect)}unbindOnlineEvent(){window.removeEventListener("online",this.handleOnlineReconnect)}setStrategyState(e){this._logger.log("reconnect state change to: ",e),this.state=e}stop({isSuccess:e,reason:t,quiet:n=!1,failedError:i}){var a;if(this.state==="idle")return;const s=(Date.now()-this._reconnectStartTime)/1e3;n||(e?this._pushConsumer.emitReconnectStateChange({state:Mt.SUCCESS,teaParams:{reconnect_duration:s,session_id:this._pushConsumer.pushSessionId}}):(this._logger.log("Reconnect strategy stopped: ",t),this._pushConsumer.emitReconnectStateChange({state:Mt.FAILED,params:{failedCode:t},teaParams:{reason:t,reconnect_duration:s,error_message:i==null?void 0:i.message,http_code:(a=i==null?void 0:i.ext)==null?void 0:a.httpCode,ext:i==null?void 0:i.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:zn.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},Jt={PushCheck:0,PushError:1},Za=new ht("PushController");class tg extends La{constructor(e,{config:t,streamConsumeController:n,streamComposedController:i}){var s,a;if(super(e),this._connect=null,this._connectionState=xe.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=Ft(ms,"audio").bitrate,this._videoBitrate=Ft(fs,"video").bitrate,this.handleReconnectError=(o,d)=>{var c,u;V(j.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(xe.CONNECTED)},this._OnRTMPError=o=>{const d=new Bt(ke.PUBLISH_FAILED,`code:${o.code}, message: ${o.message}`);this._streamConsumeController.emit(se.PushError,d),V(j.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}),V(j.START_PUSH_STATUS,{is_success:!1,reason:Jt.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(xe.RECONNECTING),this.unpublish({isReconnecting:!0})},this._OnRtcStateChange=o=>{var d;switch(V(j.PUSH_RTC_STATE_CHANGE,{state:o,push_url:this._pushUrl,session_id:this._pushSessionId,push_mode:this._pushMode}),this._streamConsumeController.emit(se.RTCConnectStateChanged,o),o){case"connected":this.setConnectState(xe.CONNECTED);break;case"disconnected":this._reconnectStrategy&&this._executeReconnect();break;case"failed":(d=this._reconnectStrategy)!=null&&d.isActive()?this._executeReconnect():(this.connectionState===xe.CONNECTED?V(j.STOP_PUSH_STREAM,{reason:Lr.PushError,error_message:"peerconnection failed",duration:this.pushDuration,session_id:this._pushSessionId,push_mode:this._pushMode}):V(j.START_PUSH_STATUS,{is_success:!1,reason:Jt.PushError,error_message:"peerconnection failed",session_id:this._pushSessionId,push_mode:this._pushMode,push_url:this._pushUrl}),this.unpublish(),this._streamConsumeController.emit(se.PushError,new Bt(ke.PUSH_CONNECT_FAILED,"pc failed")));break}},this._pushMode=(t==null?void 0:t.mode)||"rtm",this._streamConsumeController=n,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*xo:void 0;this._reconnectStrategy=new eg(this,o),this._reconnectStrategy.onReconnectError=this.handleReconnectError}this._streamComposedController=i}get isPushing(){return this._connectionState===xe.CONNECTED||this._connectionState===xe.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(se.LiveConnectStateChange,e),e){case xe.CONNECTED:(t=this._reconnectStrategy)!=null&&t.isActive()?this._reconnectStrategy.stop({isSuccess:!0}):(this._streamConsumeController.emit(se.PushStart),this.setPushStatsInterval(),V(j.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(),V(j.START_PUSH,{push_url:e,session_id:this._pushSessionId})),!e)throw V(j.START_PUSH_STATUS,{is_success:!1,session_id:this._pushSessionId,reason:Jt.PushCheck,push_url:this._pushUrl}),new Error("lack publish url");if(this._connect)return;this.start(),this._pushUrl=Xa({pushUrl:e,disableTCC:!0}),this._pushEncodeConfig=t.cfg;const n=this._composedStream.videoTrack,i=this._composedStream.audioTrack;if(this._needCheckAudioTrack&&(!n||!i)){V(j.START_PUSH_STATUS,{is_success:!1,reason:Jt.PushCheck,push_url:this._pushUrl,error_message:"lack videoTrack or audioTrack",video_track_id:n==null?void 0:n.id,audio_track_id:i==null?void 0:i.id,video_track_name:n==null?void 0:n.label,audio_track_name:i==null?void 0:i.label,push_mode:this._pushMode,session_id:this._pushSessionId}),console.warn("lack videoTrack or audioTrack","videoTrack: ",n==null?void 0:n.id,"audioTrack: ",i==null?void 0:i.id);return}else if(!n&&!i){V(j.START_PUSH_STATUS,{is_success:!1,reason:Jt.PushCheck,push_url:this._pushUrl,error_message:"lack videoTrack and audioTrack",push_mode:this._pushMode,session_id:this._pushSessionId});return}let s;this._pushMode==="rtm"?s=new $_(this._pushUrl,this._pushConfig,this._OnRtcStateChange):s=new Q_(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(xe.CONNECTING),await s.publish([i,n],[this._audioBitrate,this._videoBitrate],{cfg:t.cfg,isReconnect:t.isReconnect}),t.isReconnect||(Za.log("startPush begin"),this._connectionStartDate=Date.now())}catch(c){const u=new Bt(ke.PUBLISH_FAILED,c.message,c);if(Za.groupEnd(),(d=this._reconnectStrategy)!=null&&d.isActive())throw this.unpublish({isReconnecting:!0}),u;this._streamConsumeController.emit(se.PushError,u),V(j.STOP_PUSH_STREAM,{reason:Lr.PushError,error_message:u.message,enable_reconnect:!1,push_mode:this._pushMode,session_id:this._pushSessionId,duration:this.pushDuration}),V(j.START_PUSH_STATUS,{is_success:!1,push_url:this._pushUrl,reason:Jt.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,n,i,s;if((t=this._connect)!=null&&t.isPushing){const a=Date.now(),{stats:o,originStats:d}=await this._connect.getStatsSnapshoot(2e3),u=Date.now()-a;Zp(o)?this._prevStats=void 0:this._prevStats=o;const h=this.pushMode==="rtm"?G_(o,d,{idealFrameRate:(n=this._composedStream._videoStream)==null?void 0:n.frameRate,idealBitrate:this._videoBitrate}):B_(o),l=this.pushMode==="rtm"?(i=this._connect)==null?void 0:i.videoSenderTrackStats:{};V(j.PUSH_STATS,{...h,...l,video_draw_frame:this._streamComposedController.getCompositionDrawCountPerSecond(),stats:o,push_url:this._pushUrl,push_mode:this._pushMode,session_id:this._pushSessionId,duration:h.video_duration||u,video_duration:h.video_duration||u,is_push:!0},!0)}else await gn(2e3),V(j.PUSH_STATS,{push_url:this._pushUrl,push_mode:this._pushMode,session_id:this._pushSessionId,duration:2e3,is_push:!1,is_reconnecting:((s=this._reconnectStrategy)==null?void 0:s.isActive())??!1},!0);this.connectionState!==xe.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 n=[];e&&n.push(()=>{var i;return(i=this._connect)==null?void 0:i.updatePublish(e,"video")}),t&&n.push(()=>{var i;return(i=this._connect)==null?void 0:i.updatePublish(t,"audio")}),await Promise.all(n.map(i=>i()))}catch(n){const i=new Bt(ke.UPDATE_PUBLISH_FAILED,`${n.name}, code:${n.code}`);this._streamConsumeController.emit(se.PushError,i)}}unpublish(e={isReconnecting:!1,isManual:!1}){var t,n,i,s,a;(t=this._connect)==null||t.unpublish(),this._connect=null,e.isManual&&(V(j.STOP_PUSH_STREAM,{reason:Lr.ManualStop,duration:this.pushDuration,session_id:this._streamConsumeController.pushSessionId,push_mode:this._pushMode,reconnect_times:(n=this._reconnectStrategy)==null?void 0:n.getReconnectInfo().totalReconnectCount,reconnect_duration:(i=this._reconnectStrategy)==null?void 0:i.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(xe.DISCONNECTED),(a=this._reconnectStrategy)==null||a.stop({quiet:!0}),this._streamConsumeController.emit(se.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,n){var i;t==="video"?this._videoBitrate=e:this._audioBitrate=e,(i=this._connect)==null||i.applyBitrate(e,t,n)}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:n}){V(j.PUSH_RECONNECT_STATUS,{status:e,...t,...n}),this._streamConsumeController.emit(se.ReconnectStateChange,e,t)}}class rg extends st{constructor(e,t){super(),this._previewConsumer=new x_(e.getComposedStream(),{streamConsumeController:this}),this._pushConsumer=new tg(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,n){this._pushConsumer.setBitrate(e,t,n)}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 ng=()=>typeof window>"u",$e={},Sn=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 Ya(r){const e=r.split(`
|
|
69
|
+
`);let t=!1;for(const n of e)if(n.includes("level-asymmetry-allowed=1")&&n.includes("packetization-mode=1")&&n.includes("profile-level-id=42e0")){t=!0;break}if(t){const n=navigator.userAgent.toLowerCase();let i=!1;const s=[/miuibrowser/,/70.*HeyTapBrowser/i];for(const a of s)a.test(n)&&(i=!0);return!i}return!1}const ig=async()=>{let r=await Sn("sendonly");return navigator.userAgent.includes("VivoBrowser")&&(r=await Sn("sendonly")),$e.h264encode=Ya(r),$e.vp8encode=r.indexOf("vp8")>-1,$e},sg=async()=>{let r=await Sn("recvonly");return navigator.userAgent.includes("VivoBrowser")&&(r=await Sn("recvonly")),$e.h264decode=Ya(r),$e.vp8decode=r.indexOf("vp8")>-1,$e},og=async()=>{if(typeof $e.h264encode>"u")try{await ig()}catch{return!1}return $e.h264encode||!1},ag=async()=>{if(typeof $e.h264decode>"u")try{await sg()}catch{return!1}return $e.h264decode||!1};class cg{constructor(){this.onError=(e,t,n)=>{},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 ug=new cg;let Qa=!0,ec=!0;function bn(r,e,t){const n=r.match(e);return n&&n.length>=t&&parseInt(n[t],10)}function xt(r,e,t){if(!r.RTCPeerConnection)return;const n=r.RTCPeerConnection.prototype,i=n.addEventListener;n.addEventListener=function(a,o){if(a!==e)return i.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),i.apply(this,[a,d])};const s=n.removeEventListener;n.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(n,"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 dg(r){return typeof r!="boolean"?new Error("Argument type: "+typeof r+". Please use a boolean."):(Qa=r,r?"adapter.js logging disabled":"adapter.js logging enabled")}function lg(r){return typeof r!="boolean"?new Error("Argument type: "+typeof r+". Please use a boolean."):(ec=!r,"adapter.js deprecation warnings "+(r?"disabled":"enabled"))}function tc(){if(typeof window=="object"){if(Qa)return;typeof console<"u"&&typeof console.log=="function"&&console.log.apply(console,arguments)}}function Yi(r,e){ec&&console.warn(r+" is deprecated, please use "+e+" instead.")}function hg(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 n=t.userAgentData.brands.find(i=>i.brand==="Chromium");if(n)return{browser:"chrome",version:parseInt(n.version,10)}}if(t.mozGetUserMedia)e.browser="firefox",e.version=bn(t.userAgent,/Firefox\/(\d+)\./,1);else if(t.webkitGetUserMedia||r.isSecureContext===!1&&r.webkitRTCPeerConnection)e.browser="chrome",e.version=bn(t.userAgent,/Chrom(e|ium)\/(\d+)\./,2);else if(r.RTCPeerConnection&&t.userAgent.match(/AppleWebKit\/(\d+)\./))e.browser="safari",e.version=bn(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 rc(r){return Object.prototype.toString.call(r)==="[object Object]"}function nc(r){return rc(r)?Object.keys(r).reduce(function(e,t){const n=rc(r[t]),i=n?nc(r[t]):r[t],s=n&&!Object.keys(i).length;return i===void 0||s?e:Object.assign(e,{[t]:i})},{}):r}function Qi(r,e,t){!e||t.has(e.id)||(t.set(e.id,e),Object.keys(e).forEach(n=>{n.endsWith("Id")?Qi(r,r.get(e[n]),t):n.endsWith("Ids")&&e[n].forEach(i=>{Qi(r,r.get(i),t)})}))}function ic(r,e,t){const n=t?"outbound-rtp":"inbound-rtp",i=new Map;if(e===null)return i;const s=[];return r.forEach(a=>{a.type==="track"&&a.trackIdentifier===e.id&&s.push(a)}),s.forEach(a=>{r.forEach(o=>{o.type===n&&o.trackId===a.id&&Qi(r,o,i)})}),i}const sc=tc;function oc(r,e){const t=r&&r.navigator;if(!t.mediaDevices)return;const n=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 h=function(l,f){return l?l+f.charAt(0).toUpperCase()+f.slice(1):f==="deviceId"?"sourceId":f};if(u.ideal!==void 0){d.optional=d.optional||[];let l={};typeof u.ideal=="number"?(l[h("min",c)]=u.ideal,d.optional.push(l),l={},l[h("max",c)]=u.ideal,d.optional.push(l)):(l[h("",c)]=u.ideal,d.optional.push(l))}u.exact!==void 0&&typeof u.exact!="number"?(d.mandatory=d.mandatory||{},d.mandatory[h("",c)]=u.exact):["min","max"].forEach(l=>{u[l]!==void 0&&(d.mandatory=d.mandatory||{},d.mandatory[h(l,c)]=u[l])})}),o.advanced&&(d.optional=(d.optional||[]).concat(o.advanced)),d},i=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,h,l){h in u&&!(l in u)&&(u[l]=u[h],delete u[h])};o=JSON.parse(JSON.stringify(o)),c(o.audio,"autoGainControl","googAutoGainControl"),c(o.audio,"noiseSuppression","googNoiseSuppression"),o.audio=n(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 h;if(c.exact==="environment"||c.ideal==="environment"?h=["back","rear"]:(c.exact==="user"||c.ideal==="user")&&(h=["front"]),h)return t.mediaDevices.enumerateDevices().then(l=>{l=l.filter(y=>y.kind==="videoinput");let f=l.find(y=>h.some(C=>y.label.toLowerCase().includes(C)));return!f&&l.length&&h.includes("back")&&(f=l[l.length-1]),f&&(o.video.deviceId=c.exact?{exact:f.deviceId}:{ideal:f.deviceId}),o.video=n(o.video),sc("chrome: "+JSON.stringify(o)),d(o)})}o.video=n(o.video)}return sc("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){i(o,u=>{t.webkitGetUserMedia(u,d,h=>{c&&c(s(h))})})};if(t.getUserMedia=a.bind(t),t.mediaDevices.getUserMedia){const o=t.mediaDevices.getUserMedia.bind(t.mediaDevices);t.mediaDevices.getUserMedia=function(d){return i(d,c=>o(c).then(u=>{if(c.audio&&!u.getAudioTracks().length||c.video&&!u.getVideoTracks().length)throw u.getTracks().forEach(h=>{h.stop()}),new DOMException("","NotFoundError");return u},u=>Promise.reject(s(u))))}}}function ac(r){r.MediaStream=r.MediaStream||r.webkitMediaStream}function cc(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=n=>{n.stream.addEventListener("addtrack",i=>{let s;r.RTCPeerConnection.prototype.getReceivers?s=this.getReceivers().find(o=>o.track&&o.track.id===i.track.id):s={track:i.track};const a=new Event("track");a.track=i.track,a.receiver=s,a.transceiver={receiver:s},a.streams=[n.stream],this.dispatchEvent(a)}),n.stream.getTracks().forEach(i=>{let s;r.RTCPeerConnection.prototype.getReceivers?s=this.getReceivers().find(o=>o.track&&o.track.id===i.id):s={track:i};const a=new Event("track");a.track=i,a.receiver=s,a.transceiver={receiver:s},a.streams=[n.stream],this.dispatchEvent(a)})},this.addEventListener("addstream",this._ontrackpoly)),e.apply(this,arguments)}}else xt(r,"track",e=>(e.transceiver||Object.defineProperty(e,"transceiver",{value:{receiver:e.receiver}}),e))}function uc(r){if(typeof r=="object"&&r.RTCPeerConnection&&!("getSenders"in r.RTCPeerConnection.prototype)&&"createDTMFSender"in r.RTCPeerConnection.prototype){const e=function(i,s){return{track:s,get dtmf(){return this._dtmf===void 0&&(s.kind==="audio"?this._dtmf=i.createDTMFSender(s):this._dtmf=null),this._dtmf},_pc:i}};if(!r.RTCPeerConnection.prototype.getSenders){r.RTCPeerConnection.prototype.getSenders=function(){return this._senders=this._senders||[],this._senders.slice()};const i=r.RTCPeerConnection.prototype.addTrack;r.RTCPeerConnection.prototype.addTrack=function(o,d){let c=i.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 n=r.RTCPeerConnection.prototype.removeStream;r.RTCPeerConnection.prototype.removeStream=function(s){this._senders=this._senders||[],n.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 n=e.apply(this,[]);return n.forEach(i=>i._pc=this),n},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 dc(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 n=r.RTCPeerConnection.prototype.addTrack;n&&(r.RTCPeerConnection.prototype.addTrack=function(){const s=n.apply(this,arguments);return s._pc=this,s}),r.RTCRtpSender.prototype.getStats=function(){const s=this;return this._pc.getStats().then(a=>ic(a,s.track,!0))}}if(!("getStats"in r.RTCRtpReceiver.prototype)){const t=r.RTCPeerConnection.prototype.getReceivers;t&&(r.RTCPeerConnection.prototype.getReceivers=function(){const i=t.apply(this,[]);return i.forEach(s=>s._pc=this),i}),xt(r,"track",n=>(n.receiver._pc=n.srcElement,n)),r.RTCRtpReceiver.prototype.getStats=function(){const i=this;return this._pc.getStats().then(s=>ic(s,i.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 n=arguments[0];let i,s,a;return this.getSenders().forEach(o=>{o.track===n&&(i?a=!0:i=o)}),this.getReceivers().forEach(o=>(o.track===n&&(s?a=!0:s=o),o.track===n)),a||i&&s?Promise.reject(new DOMException("There are more than one sender or receiver for the track.","InvalidAccessError")):i?i.getStats():s?s.getStats():Promise.reject(new DOMException("There is no sender or receiver for the track.","InvalidAccessError"))}return e.apply(this,arguments)}}function lc(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(h=>h.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 n=r.RTCPeerConnection.prototype.removeStream;r.RTCPeerConnection.prototype.removeStream=function(a){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},delete this._shimmedLocalStreams[a.id],n.apply(this,arguments)};const i=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]}),i.apply(this,arguments)}}function hc(r,e){if(!r.RTCPeerConnection)return;if(r.RTCPeerConnection.prototype.addTrack&&e.version>=65)return lc(r);const t=r.RTCPeerConnection.prototype.getLocalStreams;r.RTCPeerConnection.prototype.getLocalStreams=function(){const u=t.apply(this);return this._reverseStreams=this._reverseStreams||{},u.map(h=>this._reverseStreams[h.id])};const n=r.RTCPeerConnection.prototype.addStream;r.RTCPeerConnection.prototype.addStream=function(u){if(this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},u.getTracks().forEach(h=>{if(this.getSenders().find(f=>f.track===h))throw new DOMException("Track already exists.","InvalidAccessError")}),!this._reverseStreams[u.id]){const h=new r.MediaStream(u.getTracks());this._streams[u.id]=h,this._reverseStreams[h.id]=u,u=h}n.apply(this,[u])};const i=r.RTCPeerConnection.prototype.removeStream;r.RTCPeerConnection.prototype.removeStream=function(u){this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},i.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,h){if(this.signalingState==="closed")throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");const l=[].slice.call(arguments,1);if(l.length!==1||!l[0].getTracks().find(C=>C===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(C=>C.track===u))throw new DOMException("Track already exists.","InvalidAccessError");this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{};const y=this._streams[h.id];if(y)y.addTrack(u),Promise.resolve().then(()=>{this.dispatchEvent(new Event("negotiationneeded"))});else{const C=new r.MediaStream([u]);this._streams[h.id]=C,this._reverseStreams[C.id]=h,this.addStream(C)}return this.getSenders().find(C=>C.track===u)};function s(c,u){let h=u.sdp;return Object.keys(c._reverseStreams||[]).forEach(l=>{const f=c._reverseStreams[l],y=c._streams[f.id];h=h.replace(new RegExp(y.id,"g"),f.id)}),new RTCSessionDescription({type:u.type,sdp:h})}function a(c,u){let h=u.sdp;return Object.keys(c._reverseStreams||[]).forEach(l=>{const f=c._reverseStreams[l],y=c._streams[f.id];h=h.replace(new RegExp(f.id,"g"),y.id)}),new RTCSessionDescription({type:u.type,sdp:h})}["createOffer","createAnswer"].forEach(function(c){const u=r.RTCPeerConnection.prototype[c],h={[c](){const l=arguments;return arguments.length&&typeof arguments[0]=="function"?u.apply(this,[y=>{const C=s(this,y);l[0].apply(null,[C])},y=>{l[1]&&l[1].apply(null,y)},arguments[2]]):u.apply(this,arguments).then(y=>s(this,y))}};r.RTCPeerConnection.prototype[c]=h[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 l;Object.keys(this._streams).forEach(f=>{this._streams[f].getTracks().find(C=>u.track===C)&&(l=this._streams[f])}),l&&(l.getTracks().length===1?this.removeStream(this._reverseStreams[l.id]):l.removeTrack(u.track),this.dispatchEvent(new Event("negotiationneeded")))}}function es(r,e){!r.RTCPeerConnection&&r.webkitRTCPeerConnection&&(r.RTCPeerConnection=r.webkitRTCPeerConnection),r.RTCPeerConnection&&e.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach(function(t){const n=r.RTCPeerConnection.prototype[t],i={[t](){return arguments[0]=new(t==="addIceCandidate"?r.RTCIceCandidate:r.RTCSessionDescription)(arguments[0]),n.apply(this,arguments)}};r.RTCPeerConnection.prototype[t]=i[t]})}function pc(r,e){xt(r,"negotiationneeded",t=>{const n=t.target;if(!((e.version<72||n.getConfiguration&&n.getConfiguration().sdpSemantics==="plan-b")&&n.signalingState!=="stable"))return t})}const fc=Object.freeze(Object.defineProperty({__proto__:null,fixNegotiationNeeded:pc,shimAddTrackRemoveTrack:hc,shimAddTrackRemoveTrackWithNative:lc,shimGetSendersWithDtmf:uc,shimGetUserMedia:oc,shimMediaStream:ac,shimOnTrack:cc,shimPeerConnection:es,shimSenderReceiverGetStats:dc},Symbol.toStringTag,{value:"Module"}));function mc(r,e){const t=r&&r.navigator,n=r&&r.MediaStreamTrack;if(t.getUserMedia=function(i,s,a){Yi("navigator.getUserMedia","navigator.mediaDevices.getUserMedia"),t.mediaDevices.getUserMedia(i).then(s,a)},!(e.version>55&&"autoGainControl"in t.mediaDevices.getSupportedConstraints())){const i=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)),i(a.audio,"autoGainControl","mozAutoGainControl"),i(a.audio,"noiseSuppression","mozNoiseSuppression")),s(a)},n&&n.prototype.getSettings){const a=n.prototype.getSettings;n.prototype.getSettings=function(){const o=a.apply(this,arguments);return i(o,"mozAutoGainControl","autoGainControl"),i(o,"mozNoiseSuppression","noiseSuppression"),o}}if(n&&n.prototype.applyConstraints){const a=n.prototype.applyConstraints;n.prototype.applyConstraints=function(o){return this.kind==="audio"&&typeof o=="object"&&(o=JSON.parse(JSON.stringify(o)),i(o,"autoGainControl","mozAutoGainControl"),i(o,"noiseSuppression","mozNoiseSuppression")),a.apply(this,[o])}}}}function pg(r,e){r.navigator.mediaDevices&&"getDisplayMedia"in r.navigator.mediaDevices||r.navigator.mediaDevices&&(r.navigator.mediaDevices.getDisplayMedia=function(n){if(!(n&&n.video)){const i=new DOMException("getDisplayMedia without video constraints is undefined");return i.name="NotFoundError",i.code=8,Promise.reject(i)}return n.video===!0?n.video={mediaSource:e}:n.video.mediaSource=e,r.navigator.mediaDevices.getUserMedia(n)})}function _c(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 ts(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(i){const s=r.RTCPeerConnection.prototype[i],a={[i](){return arguments[0]=new(i==="addIceCandidate"?r.RTCIceCandidate:r.RTCSessionDescription)(arguments[0]),s.apply(this,arguments)}};r.RTCPeerConnection.prototype[i]=a[i]});const t={inboundrtp:"inbound-rtp",outboundrtp:"outbound-rtp",candidatepair:"candidate-pair",localcandidate:"local-candidate",remotecandidate:"remote-candidate"},n=r.RTCPeerConnection.prototype.getStats;r.RTCPeerConnection.prototype.getStats=function(){const[s,a,o]=arguments;return n.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,h)=>{d.set(h,Object.assign({},u,{type:t[u.type]||u.type}))})}return d}).then(a,o)}}function gc(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 i=e.apply(this,[]);return i.forEach(s=>s._pc=this),i});const t=r.RTCPeerConnection.prototype.addTrack;t&&(r.RTCPeerConnection.prototype.addTrack=function(){const i=t.apply(this,arguments);return i._pc=this,i}),r.RTCRtpSender.prototype.getStats=function(){return this.track?this._pc.getStats(this.track):Promise.resolve(new Map)}}function vc(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 n=e.apply(this,[]);return n.forEach(i=>i._pc=this),n}),xt(r,"track",t=>(t.receiver._pc=t.srcElement,t)),r.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track)}}function yc(r){!r.RTCPeerConnection||"removeStream"in r.RTCPeerConnection.prototype||(r.RTCPeerConnection.prototype.removeStream=function(t){Yi("removeStream","removeTrack"),this.getSenders().forEach(n=>{n.track&&t.getTracks().includes(n.track)&&this.removeTrack(n)})})}function Sc(r){r.DataChannel&&!r.RTCDataChannel&&(r.RTCDataChannel=r.DataChannel)}function bc(r){if(!(typeof r=="object"&&r.RTCPeerConnection))return;const e=r.RTCPeerConnection.prototype.addTransceiver;e&&(r.RTCPeerConnection.prototype.addTransceiver=function(){this.setParametersPromises=[];let n=arguments[1]&&arguments[1].sendEncodings;n===void 0&&(n=[]),n=[...n];const i=n.length>0;i&&n.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(i){const{sender:a}=s,o=a.getParameters();(!("encodings"in o)||o.encodings.length===1&&Object.keys(o.encodings[0]).length===0)&&(o.encodings=n,a.sendEncodings=n,this.setParametersPromises.push(a.setParameters(o).then(()=>{delete a.sendEncodings}).catch(()=>{delete a.sendEncodings})))}return s})}function Ec(r){if(!(typeof r=="object"&&r.RTCRtpSender))return;const e=r.RTCRtpSender.prototype.getParameters;e&&(r.RTCRtpSender.prototype.getParameters=function(){const n=e.apply(this,arguments);return"encodings"in n||(n.encodings=[].concat(this.sendEncodings||[{}])),n})}function Cc(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 wc(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 Tc=Object.freeze(Object.defineProperty({__proto__:null,shimAddTransceiver:bc,shimCreateAnswer:wc,shimCreateOffer:Cc,shimGetDisplayMedia:pg,shimGetParameters:Ec,shimGetUserMedia:mc,shimOnTrack:_c,shimPeerConnection:ts,shimRTCDataChannel:Sc,shimReceiverGetStats:vc,shimRemoveStream:yc,shimSenderGetStats:gc},Symbol.toStringTag,{value:"Module"}));function kc(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(n){this._localStreams||(this._localStreams=[]),this._localStreams.includes(n)||this._localStreams.push(n),n.getAudioTracks().forEach(i=>e.call(this,i,n)),n.getVideoTracks().forEach(i=>e.call(this,i,n))},r.RTCPeerConnection.prototype.addTrack=function(n,...i){return i&&i.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 n=this._localStreams.indexOf(t);if(n===-1)return;this._localStreams.splice(n,1);const i=t.getTracks();this.getSenders().forEach(s=>{i.includes(s.track)&&this.removeTrack(s)})})}}function Rc(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=n=>{n.streams.forEach(i=>{if(this._remoteStreams||(this._remoteStreams=[]),this._remoteStreams.includes(i))return;this._remoteStreams.push(i);const s=new Event("addstream");s.stream=i,this.dispatchEvent(s)})})}});const e=r.RTCPeerConnection.prototype.setRemoteDescription;r.RTCPeerConnection.prototype.setRemoteDescription=function(){const n=this;return this._onaddstreampoly||this.addEventListener("track",this._onaddstreampoly=function(i){i.streams.forEach(s=>{if(n._remoteStreams||(n._remoteStreams=[]),n._remoteStreams.indexOf(s)>=0)return;n._remoteStreams.push(s);const a=new Event("addstream");a.stream=s,n.dispatchEvent(a)})}),e.apply(n,arguments)}}}function Ac(r){if(typeof r!="object"||!r.RTCPeerConnection)return;const e=r.RTCPeerConnection.prototype,t=e.createOffer,n=e.createAnswer,i=e.setLocalDescription,s=e.setRemoteDescription,a=e.addIceCandidate;e.createOffer=function(c,u){const h=arguments.length>=2?arguments[2]:arguments[0],l=t.apply(this,[h]);return u?(l.then(c,u),Promise.resolve()):l},e.createAnswer=function(c,u){const h=arguments.length>=2?arguments[2]:arguments[0],l=n.apply(this,[h]);return u?(l.then(c,u),Promise.resolve()):l};let o=function(d,c,u){const h=i.apply(this,[d]);return u?(h.then(c,u),Promise.resolve()):h};e.setLocalDescription=o,o=function(d,c,u){const h=s.apply(this,[d]);return u?(h.then(c,u),Promise.resolve()):h},e.setRemoteDescription=o,o=function(d,c,u){const h=a.apply(this,[d]);return u?(h.then(c,u),Promise.resolve()):h},e.addIceCandidate=o}function Dc(r){const e=r&&r.navigator;if(e.mediaDevices&&e.mediaDevices.getUserMedia){const t=e.mediaDevices,n=t.getUserMedia.bind(t);e.mediaDevices.getUserMedia=i=>n(xc(i))}!e.getUserMedia&&e.mediaDevices&&e.mediaDevices.getUserMedia&&(e.getUserMedia=(function(n,i,s){e.mediaDevices.getUserMedia(n).then(i,s)}).bind(e))}function xc(r){return r&&r.video!==void 0?Object.assign({},r,{video:nc(r.video)}):r}function Ic(r){if(!r.RTCPeerConnection)return;const e=r.RTCPeerConnection;r.RTCPeerConnection=function(n,i){if(n&&n.iceServers){const s=[];for(let a=0;a<n.iceServers.length;a++){let o=n.iceServers[a];o.urls===void 0&&o.url?(Yi("RTCIceServer.url","RTCIceServer.urls"),o=JSON.parse(JSON.stringify(o)),o.urls=o.url,delete o.url,s.push(o)):s.push(n.iceServers[a])}n.iceServers=s}return new e(n,i)},r.RTCPeerConnection.prototype=e.prototype,"generateCertificate"in e&&Object.defineProperty(r.RTCPeerConnection,"generateCertificate",{get(){return e.generateCertificate}})}function zc(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 Pc(r){const e=r.RTCPeerConnection.prototype.createOffer;r.RTCPeerConnection.prototype.createOffer=function(n){if(n){typeof n.offerToReceiveAudio<"u"&&(n.offerToReceiveAudio=!!n.offerToReceiveAudio);const i=this.getTransceivers().find(a=>a.receiver.track.kind==="audio");n.offerToReceiveAudio===!1&&i?i.direction==="sendrecv"?i.setDirection?i.setDirection("sendonly"):i.direction="sendonly":i.direction==="recvonly"&&(i.setDirection?i.setDirection("inactive"):i.direction="inactive"):n.offerToReceiveAudio===!0&&!i&&this.addTransceiver("audio",{direction:"recvonly"}),typeof n.offerToReceiveVideo<"u"&&(n.offerToReceiveVideo=!!n.offerToReceiveVideo);const s=this.getTransceivers().find(a=>a.receiver.track.kind==="video");n.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"):n.offerToReceiveVideo===!0&&!s&&this.addTransceiver("video",{direction:"recvonly"})}return e.apply(this,arguments)}}function Oc(r){typeof r!="object"||r.AudioContext||(r.AudioContext=r.webkitAudioContext)}const Mc=Object.freeze(Object.defineProperty({__proto__:null,shimAudioContext:Oc,shimCallbacksAPI:Ac,shimConstraints:xc,shimCreateOfferLegacy:Pc,shimGetUserMedia:Dc,shimLocalStreamsAPI:kc,shimRTCIceServerUrls:Ic,shimRemoteStreamsAPI:Rc,shimTrackEventTransceiver:zc},Symbol.toStringTag,{value:"Module"}));var rs={exports:{}},Lc;function fg(){return Lc||(Lc=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(n=>n.trim())},e.splitSections=function(t){return t.split(`
|
|
71
71
|
m=`).map((i,s)=>(s>0?"m="+i:i).trim()+`\r
|
|
72
72
|
`)},e.getDescription=function(t){const n=e.splitSections(t);return n&&n[0]},e.getMediaSections=function(t){const n=e.splitSections(t);return n.shift(),n},e.matchPrefix=function(t,n){return e.splitLines(t).filter(i=>i.indexOf(n)===0)},e.parseCandidate=function(t){let n;t.indexOf("a=candidate:")===0?n=t.substring(12).split(" "):n=t.substring(10).split(" ");const i={foundation:n[0],component:{1:"rtp",2:"rtcp"}[n[1]]||n[1],protocol:n[2].toLowerCase(),priority:parseInt(n[3],10),ip:n[4],address:n[4],port:parseInt(n[5],10),type:n[7]};for(let s=8;s<n.length;s+=2)switch(n[s]){case"raddr":i.relatedAddress=n[s+1];break;case"rport":i.relatedPort=parseInt(n[s+1],10);break;case"tcptype":i.tcpType=n[s+1];break;case"ufrag":i.ufrag=n[s+1],i.usernameFragment=n[s+1];break;default:i[n[s]]===void 0&&(i[n[s]]=n[s+1]);break}return i},e.writeCandidate=function(t){const n=[];n.push(t.foundation);const i=t.component;i==="rtp"?n.push(1):i==="rtcp"?n.push(2):n.push(i),n.push(t.protocol.toUpperCase()),n.push(t.priority),n.push(t.address||t.ip),n.push(t.port);const s=t.type;return n.push("typ"),n.push(s),s!=="host"&&t.relatedAddress&&t.relatedPort&&(n.push("raddr"),n.push(t.relatedAddress),n.push("rport"),n.push(t.relatedPort)),t.tcpType&&t.protocol.toLowerCase()==="tcp"&&(n.push("tcptype"),n.push(t.tcpType)),(t.usernameFragment||t.ufrag)&&(n.push("ufrag"),n.push(t.usernameFragment||t.ufrag)),"candidate:"+n.join(" ")},e.parseIceOptions=function(t){return t.substring(14).split(" ")},e.parseRtpMap=function(t){let n=t.substring(9).split(" ");const i={payloadType:parseInt(n.shift(),10)};return n=n[0].split("/"),i.name=n[0],i.clockRate=parseInt(n[1],10),i.channels=n.length===3?parseInt(n[2],10):1,i.numChannels=i.channels,i},e.writeRtpMap=function(t){let n=t.payloadType;t.preferredPayloadType!==void 0&&(n=t.preferredPayloadType);const i=t.channels||t.numChannels||1;return"a=rtpmap:"+n+" "+t.name+"/"+t.clockRate+(i!==1?"/"+i:"")+`\r
|
|
@@ -97,7 +97,7 @@ a=ice-pwd:`+t.password+`\r
|
|
|
97
97
|
o=`+(i||"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,n){const i=e.splitLines(t);for(let s=0;s<i.length;s++)switch(i[s]){case"a=sendrecv":case"a=sendonly":case"a=recvonly":case"a=inactive":return i[s].substring(2)}return n?e.getDirection(n):"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 i=e.splitLines(t)[0].substring(2).split(" ");return{kind:i[0],port:parseInt(i[1],10),protocol:i[2],fmt:i.slice(3).join(" ")}},e.parseOLine=function(t){const i=e.matchPrefix(t,"o=")[0].substring(2).split(" ");return{username:i[0],sessionId:i[1],sessionVersion:parseInt(i[2],10),netType:i[3],addressType:i[4],address:i[5]}},e.isValidSDP=function(t){if(typeof t!="string"||t.length===0)return!1;const n=e.splitLines(t);for(let i=0;i<n.length;i++)if(n[i].length<2||n[i].charAt(1)!=="=")return!1;return!0},r.exports=e}(
|
|
100
|
+
`},e.getDirection=function(t,n){const i=e.splitLines(t);for(let s=0;s<i.length;s++)switch(i[s]){case"a=sendrecv":case"a=sendonly":case"a=recvonly":case"a=inactive":return i[s].substring(2)}return n?e.getDirection(n):"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 i=e.splitLines(t)[0].substring(2).split(" ");return{kind:i[0],port:parseInt(i[1],10),protocol:i[2],fmt:i.slice(3).join(" ")}},e.parseOLine=function(t){const i=e.matchPrefix(t,"o=")[0].substring(2).split(" ");return{username:i[0],sessionId:i[1],sessionVersion:parseInt(i[2],10),netType:i[3],addressType:i[4],address:i[5]}},e.isValidSDP=function(t){if(typeof t!="string"||t.length===0)return!1;const n=e.splitLines(t);for(let i=0;i<n.length;i++)if(n[i].length<2||n[i].charAt(1)!=="=")return!1;return!0},r.exports=e}(rs)),rs.exports}var Nc=fg();const Xt=_e(Nc),mg=Ne({__proto__:null,default:Xt},[Nc]);function En(r){if(!r.RTCIceCandidate||r.RTCIceCandidate&&"foundation"in r.RTCIceCandidate.prototype)return;const e=r.RTCIceCandidate;r.RTCIceCandidate=function(n){if(typeof n=="object"&&n.candidate&&n.candidate.indexOf("a=")===0&&(n=JSON.parse(JSON.stringify(n)),n.candidate=n.candidate.substring(2)),n.candidate&&n.candidate.length){const i=new e(n),s=Xt.parseCandidate(n.candidate);for(const a in s)a in i||Object.defineProperty(i,a,{value:s[a]});return i.toJSON=function(){return{candidate:i.candidate,sdpMid:i.sdpMid,sdpMLineIndex:i.sdpMLineIndex,usernameFragment:i.usernameFragment}},i}return new e(n)},r.RTCIceCandidate.prototype=e.prototype,xt(r,"icecandidate",t=>(t.candidate&&Object.defineProperty(t,"candidate",{value:new r.RTCIceCandidate(t.candidate),writable:"false"}),t))}function ns(r){!r.RTCIceCandidate||r.RTCIceCandidate&&"relayProtocol"in r.RTCIceCandidate.prototype||xt(r,"icecandidate",e=>{if(e.candidate){const t=Xt.parseCandidate(e.candidate.candidate);t.type==="relay"&&(e.candidate.relayProtocol={0:"tls",1:"tcp",2:"udp"}[t.priority>>24])}return e})}function Cn(r,e){if(!r.RTCPeerConnection)return;"sctp"in r.RTCPeerConnection.prototype||Object.defineProperty(r.RTCPeerConnection.prototype,"sctp",{get(){return typeof this._sctp>"u"?null:this._sctp}});const t=function(o){if(!o||!o.sdp)return!1;const d=Xt.splitSections(o.sdp);return d.shift(),d.some(c=>{const u=Xt.parseMLine(c);return u&&u.kind==="application"&&u.protocol.indexOf("SCTP")!==-1})},n=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},i=function(o){let d=65536;return e.browser==="firefox"&&(e.version<57?o===-1?d=16384:d=2147483637:e.version<60?d=e.version===57?65535:65536:d=2147483637),d},s=function(o,d){let c=65536;e.browser==="firefox"&&e.version===57&&(c=65535);const u=Xt.matchPrefix(o.sdp,"a=max-message-size:");return u.length>0?c=parseInt(u[0].substring(19),10):e.browser==="firefox"&&d!==-1&&(c=2147483637),c},a=r.RTCPeerConnection.prototype.setRemoteDescription;r.RTCPeerConnection.prototype.setRemoteDescription=function(){if(this._sctp=null,e.browser==="chrome"&&e.version>=76){const{sdpSemantics:d}=this.getConfiguration();d==="plan-b"&&Object.defineProperty(this,"sctp",{get(){return typeof this._sctp>"u"?null:this._sctp},enumerable:!0,configurable:!0})}if(t(arguments[0])){const d=n(arguments[0]),c=i(d),u=s(arguments[0],d);let h;c===0&&u===0?h=Number.POSITIVE_INFINITY:c===0||u===0?h=Math.max(c,u):h=Math.min(c,u);const l={};Object.defineProperty(l,"maxMessageSize",{get(){return h}}),this._sctp=l}return a.apply(this,arguments)}}function wn(r){if(!(r.RTCPeerConnection&&"createDataChannel"in r.RTCPeerConnection.prototype))return;function e(n,i){const s=n.send;n.send=function(){const o=arguments[0],d=o.length||o.size||o.byteLength;if(n.readyState==="open"&&i.sctp&&d>i.sctp.maxMessageSize)throw new TypeError("Message too large (can send a maximum of "+i.sctp.maxMessageSize+" bytes)");return s.apply(n,arguments)}}const t=r.RTCPeerConnection.prototype.createDataChannel;r.RTCPeerConnection.prototype.createDataChannel=function(){const i=t.apply(this,arguments);return e(i,this),i},xt(r,"datachannel",n=>(e(n.channel,n.target),n))}function is(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 n=e[t];e[t]=function(){return this._connectionstatechangepoly||(this._connectionstatechangepoly=i=>{const s=i.target;if(s._lastConnectionState!==s.connectionState){s._lastConnectionState=s.connectionState;const a=new Event("connectionstatechange",i);s.dispatchEvent(a)}return i},this.addEventListener("iceconnectionstatechange",this._connectionstatechangepoly)),n.apply(this,arguments)}})}function ss(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(i){if(i&&i.sdp&&i.sdp.indexOf(`
|
|
101
101
|
a=extmap-allow-mixed`)!==-1){const s=i.sdp.split(`
|
|
102
102
|
`).filter(a=>a.trim()!=="a=extmap-allow-mixed").join(`
|
|
103
|
-
`);r.RTCSessionDescription&&i instanceof r.RTCSessionDescription?arguments[0]=new r.RTCSessionDescription({type:i.type,sdp:s}):i.sdp=s}return t.apply(this,arguments)}}function Cn(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 wn(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 i=arguments[0]||{};if(typeof i!="object"||i.type&&i.sdp)return t.apply(this,arguments);if(i={type:i.type,sdp:i.sdp},!i.type)switch(this.signalingState){case"stable":case"have-local-offer":case"have-remote-pranswer":i.type="offer";break;default:i.type="answer";break}return i.sdp||i.type!=="offer"&&i.type!=="answer"?t.apply(this,[i]):(i.type==="offer"?this.createOffer:this.createAnswer).apply(this).then(a=>t.apply(this,[a]))})}const lg=Object.freeze(Object.defineProperty({__proto__:null,removeExtmapAllowMixed:ts,shimAddIceCandidateNullOrEmpty:Cn,shimConnectionState:es,shimMaxMessageSize:bn,shimParameterlessSetLocalDescription:wn,shimRTCIceCandidate:Sn,shimRTCIceCandidateRelayProtocol:Qi,shimSendThrowTypeError:En},Symbol.toStringTag,{value:"Module"}));function hg({window:r}={},e={shimChrome:!0,shimFirefox:!0,shimSafari:!0}){const t=Za,n=ag(r),i={browserDetails:n,commonShim:lg,extractVersion:yn,disableLog:sg,disableWarnings:og,sdp:dg};switch(n.browser){case"chrome":if(!dc||!Xi||!e.shimChrome)return t("Chrome shim is not included in this adapter release."),i;if(n.version===null)return t("Chrome shim can not determine version, not shimming."),i;t("adapter.js shimming chrome."),i.browserShim=dc,Cn(r,n),wn(r),rc(r,n),nc(r),Xi(r,n),ic(r),cc(r,n),sc(r),oc(r),uc(r,n),Sn(r),Qi(r),es(r),bn(r,n),En(r),ts(r,n);break;case"firefox":if(!bc||!Zi||!e.shimFirefox)return t("Firefox shim is not included in this adapter release."),i;t("adapter.js shimming firefox."),i.browserShim=bc,Cn(r,n),wn(r),lc(r,n),Zi(r,n),hc(r),mc(r),pc(r),fc(r),_c(r),gc(r),vc(r),yc(r),Sc(r),Sn(r),es(r),bn(r,n),En(r);break;case"safari":if(!Ic||!e.shimSafari)return t("Safari shim is not included in this adapter release."),i;t("adapter.js shimming safari."),i.browserShim=Ic,Cn(r,n),wn(r),Rc(r),Dc(r),wc(r),Ec(r),Cc(r),Ac(r),Tc(r),xc(r),Sn(r),Qi(r),bn(r,n),En(r),ts(r,n);break;default:t("Unsupported browser!");break}return i}hg({window:typeof window>"u"?void 0:window});class pg extends it{static async isSupported(e){if(e==="webTransport")return Promise.resolve(qa.isSupported());try{return Y_()||!window.RTCPeerConnection||!window.RTCPeerConnection.prototype.addTransceiver||!window.RTCPeerConnection.prototype.createDataChannel?!1:await rg()&&await tg()}catch{return!1}}constructor(e){var t,n,i,s,a,o,d,c,u,h;if(super(),this._options=e??{},this._streamManagerController=new m_(this),this._streamComposeController=new T_(this._streamManagerController),this._streamConsumeController=new Z_(this._streamComposeController,e),this._streamConsumeController.setPushConfig(e),this._observer=ig,this._bindEvent(),!(e!=null&&e.loggerConfig)||(t=e==null?void 0:e.loggerConfig)!=null&&t.enable){p_({showLogInConsole:((n=e==null?void 0:e.loggerConfig)==null?void 0:n.showInConsole)??!1});const l=d_((i=e==null?void 0:e.loggerConfig)==null?void 0:i.userId),f=l_((s=e==null?void 0:e.loggerConfig)==null?void 0:s.deviceId);f_({user_unique_id:l,device_id:f,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:l,device_id:f,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:((h=e==null?void 0:e.loggerConfig)==null?void 0:h.appId)??0}),V(j.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:Y.Camera})}async startMicrophone(e){return await this._streamManagerController.startMicrophoneCapture(e)}stopMicrophone(e){this._streamManagerController.stopCapture({streamId:e,type:Y.Microphone})}async startVideoFileCapture(e){return e?await this._streamManagerController.startVideoFileCapture(e):void 0}stopVideoFileCapture(e){this._streamManagerController.stopCapture({streamId:e,type:Y.VideoFile})}async startScreenCapture(e=!1){return await this._streamManagerController.startScreenCapture(e)}stopScreenCapture(e){this._streamManagerController.stopCapture({streamId:e,type:Y.Screen})}async startAudioFileCapture(e){return e?await this._streamManagerController.startAudioFileCapture(e):void 0}stopAudioFileCapture(e){this._streamManagerController.stopCapture({streamId:e,type:Y.AudioFile})}async startImageCapture(e){return e?await this._streamManagerController.startImageCapture(e):void 0}stopImageCapture(e){this._streamManagerController.stopCapture({streamId:e,type:Y.Image})}startCustomVideoCapture(e){return e?this._streamManagerController.startCustomVideoCapture(e):void 0}stopCustomVideoCapture(e){this._streamManagerController.stopCapture({streamId:e,type:Y.CustomVideo})}startCustomAudioCapture(e){return e?this._streamManagerController.startCustomAudioCapture(e):void 0}stopCustomAudioCapture(e){this._streamManagerController.stopCapture({streamId:e,type:Y.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(V(j.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){V(j.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(V(j.PUSH_AUDIO_CONTEXT_START_FAILED,{error:t}),this._options.checkAudio)throw new Ft(Ee.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){V(j.ADD_VIDEO_STREAM,{number:ae(e)?e.length:1,config:e}),ae(e)?e.forEach(t=>{this._streamComposeController.addVideoStream(t)}):this._streamComposeController.addVideoStream(e)}removeVideoStream(e){V(j.DELETE_VIDEO_STREAM,{stream_id:e}),this._streamComposeController.removeVideoStream(e)}updateVideoStream(e){V(j.UPDATE_VIDEO_STREAM,{number:ae(e)?e.length:1,config:e}),ae(e)?this._streamComposeController.updateVideoStream(e):this._streamComposeController.updateVideoStream([e])}muteVideoStream(e){V(j.CHANGE_VIDEO_STREAM_MUTE,{stream_id:e,mute:!1}),this._streamComposeController.muteVideoStream(e)}unmuteVideoStream(e){V(j.CHANGE_VIDEO_STREAM_MUTE,{stream_id:e,mute:!0}),this._streamComposeController.unmuteVideoStream(e)}addAudioStream(e){V(j.ADD_AUDIO_STREAM,{number:ae(e)?e.length:1,config:e}),ae(e)?e.map(t=>this._streamComposeController.addAudioStream(t)):this._streamComposeController.addAudioStream(e)}removeAudioStream(e){V(j.DELETE_AUDIO_STREAM,{stream_id:e}),this._streamComposeController.removeAudioStream(e)}updateAudioStream(e){V(j.UPDATE_AUDIO_STREAM,{number:ae(e)?e.length:1,config:e}),ae(e)?this._streamComposeController.updateAudioStream(e):this._streamComposeController.updateAudioStream([e])}muteAudioStream(e){V(j.CHANGE_AUDIO_STREAM_MUTE,{stream_id:e,mute:!0}),this._streamComposeController.muteAudioStream(e)}unmuteAudioStream(e){V(j.CHANGE_AUDIO_STREAM_MUTE,{stream_id:e,mute:!1}),this._streamComposeController.unmuteAudioStream(e)}setProperty(e,t){switch(V(j.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":Kr.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(V(j.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:n,frameRate:i,bitrate:s}=Vt(e,"video");this._streamManagerController.setVideoResolution({width:t,height:n}),this._streamManagerController.setVideoFps(i),this._streamComposeController.setVideoQuality({width:t,height:n,frameRate:i}),this._streamConsumeController.setBitrate(s,"video")}setAudioQuality(e){V(j.SET_AUDIO_QUALITY,{quality:e});const{sampleRate:t,bitrate:n}=Vt(e,"audio");this._streamManagerController.setAudioSampleRate(t),this._streamConsumeController.setBitrate(n,"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(Ge.Error,e=>{this.observer.onError(e.code,e.message,e.ext)}),this._streamManagerController.on(Ge.Interrupted,e=>{this.observer.onCaptureInterrupted(e.id)}),this._streamConsumeController.on(se.PushStart,()=>{this.observer.onPushStart()}),this._streamConsumeController.on(se.PushStop,()=>{this.observer.onPushStop()}),this._streamConsumeController.on(se.RTCConnectStateChanged,e=>{this.observer.onPushStatusUpdate(ds[e],e)}),this._streamConsumeController.on(se.PushError,e=>{this.observer.onError(e.code,e.message,e.ext)}),this._streamManagerController.on(Ge.DeviceStopCapture,e=>{this.observer.onStopCapture(e.id)}),this._streamConsumeController.on(se.CaptureFirstAudioFrame,()=>{this.observer.onCaptureFirstAudioFrame()}),this._streamConsumeController.on(se.CaptureFirstVideoFrame,()=>{this.observer.onCaptureFirstVideoFrame()}),this._streamConsumeController.on(se.ReconnectStateChange,(e,t)=>{this.observer.onReconnectStateChange(e,t)}),this._streamConsumeController.on(se.LiveConnectStateChange,e=>{this.observer.onLiveConnectStateChange(e)}),Hu(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 pg});
|
|
103
|
+
`);r.RTCSessionDescription&&i instanceof r.RTCSessionDescription?arguments[0]=new r.RTCSessionDescription({type:i.type,sdp:s}):i.sdp=s}return t.apply(this,arguments)}}function Tn(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 kn(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 i=arguments[0]||{};if(typeof i!="object"||i.type&&i.sdp)return t.apply(this,arguments);if(i={type:i.type,sdp:i.sdp},!i.type)switch(this.signalingState){case"stable":case"have-local-offer":case"have-remote-pranswer":i.type="offer";break;default:i.type="answer";break}return i.sdp||i.type!=="offer"&&i.type!=="answer"?t.apply(this,[i]):(i.type==="offer"?this.createOffer:this.createAnswer).apply(this).then(a=>t.apply(this,[a]))})}const _g=Object.freeze(Object.defineProperty({__proto__:null,removeExtmapAllowMixed:ss,shimAddIceCandidateNullOrEmpty:Tn,shimConnectionState:is,shimMaxMessageSize:Cn,shimParameterlessSetLocalDescription:kn,shimRTCIceCandidate:En,shimRTCIceCandidateRelayProtocol:ns,shimSendThrowTypeError:wn},Symbol.toStringTag,{value:"Module"}));function gg({window:r}={},e={shimChrome:!0,shimFirefox:!0,shimSafari:!0}){const t=tc,n=hg(r),i={browserDetails:n,commonShim:_g,extractVersion:bn,disableLog:dg,disableWarnings:lg,sdp:mg};switch(n.browser){case"chrome":if(!fc||!es||!e.shimChrome)return t("Chrome shim is not included in this adapter release."),i;if(n.version===null)return t("Chrome shim can not determine version, not shimming."),i;t("adapter.js shimming chrome."),i.browserShim=fc,Tn(r,n),kn(r),oc(r,n),ac(r),es(r,n),cc(r),hc(r,n),uc(r),dc(r),pc(r,n),En(r),ns(r),is(r),Cn(r,n),wn(r),ss(r,n);break;case"firefox":if(!Tc||!ts||!e.shimFirefox)return t("Firefox shim is not included in this adapter release."),i;t("adapter.js shimming firefox."),i.browserShim=Tc,Tn(r,n),kn(r),mc(r,n),ts(r,n),_c(r),yc(r),gc(r),vc(r),Sc(r),bc(r),Ec(r),Cc(r),wc(r),En(r),is(r),Cn(r,n),wn(r);break;case"safari":if(!Mc||!e.shimSafari)return t("Safari shim is not included in this adapter release."),i;t("adapter.js shimming safari."),i.browserShim=Mc,Tn(r,n),kn(r),Ic(r),Pc(r),Ac(r),kc(r),Rc(r),zc(r),Dc(r),Oc(r),En(r),ns(r),Cn(r,n),wn(r),ss(r,n);break;default:t("Unsupported browser!");break}return i}gg({window:typeof window>"u"?void 0:window});function vg(){const r={hardware_concurrency:navigator.hardwareConcurrency};navigator.deviceMemory&&(r.device_memory=navigator.deviceMemory+"GB");try{const e=document.createElement("canvas"),t=e.getContext("webgl")||e.getContext("experimental-webgl");if(t){const n=t.getExtension("WEBGL_debug_renderer_info");n&&(r.gpu_vendor=t.getParameter(n.UNMASKED_VENDOR_WEBGL),r.gpu_renderer=t.getParameter(n.UNMASKED_RENDERER_WEBGL)),r.webgl_version=t.getParameter(t.VERSION),r.webgl_shading_language_version=t.getParameter(t.SHADING_LANGUAGE_VERSION),r.webgl_vendor=t.getParameter(t.VENDOR),r.webgl_renderer=t.getParameter(t.RENDERER)}}catch{}return r}class yg extends st{static async isSupported(e){if(e==="webTransport")return Promise.resolve(Wa.isSupported());try{return ng()||!window.RTCPeerConnection||!window.RTCPeerConnection.prototype.addTransceiver||!window.RTCPeerConnection.prototype.createDataChannel?!1:await ag()&&await og()}catch{return!1}}constructor(e){var t,n,i,s,a,o,d,c,u,h;if(super(),this._options=e??{},this._streamManagerController=new y_(this),this._streamComposeController=new D_(this._streamManagerController),this._streamConsumeController=new rg(this._streamComposeController,e),this._streamConsumeController.setPushConfig(e),this._observer=ug,this._bindEvent(),!(e!=null&&e.loggerConfig)||(t=e==null?void 0:e.loggerConfig)!=null&&t.enable){g_({showLogInConsole:((n=e==null?void 0:e.loggerConfig)==null?void 0:n.showInConsole)??!1});const l=f_((i=e==null?void 0:e.loggerConfig)==null?void 0:i.userId),f=m_((s=e==null?void 0:e.loggerConfig)==null?void 0:s.deviceId);v_({user_unique_id:l,device_id:f,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:l,device_id:f,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:((h=e==null?void 0:e.loggerConfig)==null?void 0:h.appId)??0}),V(j.PUSHER_INIT,{options:e,...vg()})}}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:Q.Camera})}async startMicrophone(e){return await this._streamManagerController.startMicrophoneCapture(e)}stopMicrophone(e){this._streamManagerController.stopCapture({streamId:e,type:Q.Microphone})}async startVideoFileCapture(e){return e?await this._streamManagerController.startVideoFileCapture(e):void 0}stopVideoFileCapture(e){this._streamManagerController.stopCapture({streamId:e,type:Q.VideoFile})}async startScreenCapture(e=!1){return await this._streamManagerController.startScreenCapture(e)}stopScreenCapture(e){this._streamManagerController.stopCapture({streamId:e,type:Q.Screen})}async startAudioFileCapture(e){return e?await this._streamManagerController.startAudioFileCapture(e):void 0}stopAudioFileCapture(e){this._streamManagerController.stopCapture({streamId:e,type:Q.AudioFile})}async startImageCapture(e){return e?await this._streamManagerController.startImageCapture(e):void 0}stopImageCapture(e){this._streamManagerController.stopCapture({streamId:e,type:Q.Image})}startCustomVideoCapture(e){return e?this._streamManagerController.startCustomVideoCapture(e):void 0}stopCustomVideoCapture(e){this._streamManagerController.stopCapture({streamId:e,type:Q.CustomVideo})}startCustomAudioCapture(e){return e?this._streamManagerController.startCustomAudioCapture(e):void 0}stopCustomAudioCapture(e){this._streamManagerController.stopCapture({streamId:e,type:Q.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(V(j.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){V(j.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(V(j.PUSH_AUDIO_CONTEXT_START_FAILED,{error:t}),this._options.checkAudio)throw new Bt(ke.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){V(j.ADD_VIDEO_STREAM,{number:ue(e)?e.length:1,config:e}),ue(e)?e.forEach(t=>{this._streamComposeController.addVideoStream(t)}):this._streamComposeController.addVideoStream(e)}removeVideoStream(e){V(j.DELETE_VIDEO_STREAM,{stream_id:e}),this._streamComposeController.removeVideoStream(e)}updateVideoStream(e){V(j.UPDATE_VIDEO_STREAM,{number:ue(e)?e.length:1,config:e}),ue(e)?this._streamComposeController.updateVideoStream(e):this._streamComposeController.updateVideoStream([e])}muteVideoStream(e){V(j.CHANGE_VIDEO_STREAM_MUTE,{stream_id:e,mute:!1}),this._streamComposeController.muteVideoStream(e)}unmuteVideoStream(e){V(j.CHANGE_VIDEO_STREAM_MUTE,{stream_id:e,mute:!0}),this._streamComposeController.unmuteVideoStream(e)}addAudioStream(e){V(j.ADD_AUDIO_STREAM,{number:ue(e)?e.length:1,config:e}),ue(e)?e.map(t=>this._streamComposeController.addAudioStream(t)):this._streamComposeController.addAudioStream(e)}removeAudioStream(e){V(j.DELETE_AUDIO_STREAM,{stream_id:e}),this._streamComposeController.removeAudioStream(e)}updateAudioStream(e){V(j.UPDATE_AUDIO_STREAM,{number:ue(e)?e.length:1,config:e}),ue(e)?this._streamComposeController.updateAudioStream(e):this._streamComposeController.updateAudioStream([e])}muteAudioStream(e){V(j.CHANGE_AUDIO_STREAM_MUTE,{stream_id:e,mute:!0}),this._streamComposeController.muteAudioStream(e)}unmuteAudioStream(e){V(j.CHANGE_AUDIO_STREAM_MUTE,{stream_id:e,mute:!1}),this._streamComposeController.unmuteAudioStream(e)}setProperty(e,t){switch(V(j.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":Xr.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(V(j.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:n,frameRate:i,bitrate:s}=Ft(e,"video");this._streamManagerController.setVideoResolution({width:t,height:n}),this._streamManagerController.setVideoFps(i),this._streamComposeController.setVideoQuality({width:t,height:n,frameRate:i}),this._streamConsumeController.setBitrate(s,"video")}setAudioQuality(e){V(j.SET_AUDIO_QUALITY,{quality:e});const{sampleRate:t,bitrate:n}=Ft(e,"audio");this._streamManagerController.setAudioSampleRate(t),this._streamConsumeController.setBitrate(n,"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(Be.Error,e=>{this.observer.onError(e.code,e.message,e.ext)}),this._streamManagerController.on(Be.Interrupted,e=>{this.observer.onCaptureInterrupted(e.id)}),this._streamConsumeController.on(se.PushStart,()=>{this.observer.onPushStart()}),this._streamConsumeController.on(se.PushStop,()=>{this.observer.onPushStop()}),this._streamConsumeController.on(se.RTCConnectStateChanged,e=>{this.observer.onPushStatusUpdate(hs[e],e)}),this._streamConsumeController.on(se.PushError,e=>{this.observer.onError(e.code,e.message,e.ext)}),this._streamManagerController.on(Be.DeviceStopCapture,e=>{this.observer.onStopCapture(e.id)}),this._streamConsumeController.on(se.CaptureFirstAudioFrame,()=>{this.observer.onCaptureFirstAudioFrame()}),this._streamConsumeController.on(se.CaptureFirstVideoFrame,()=>{this.observer.onCaptureFirstVideoFrame()}),this._streamConsumeController.on(se.ReconnectStateChange,(e,t)=>{this.observer.onReconnectStateChange(e,t)}),this._streamConsumeController.on(se.LiveConnectStateChange,e=>{this.observer.onLiveConnectStateChange(e)}),Wu(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 yg});
|