@byteplus/vepusher 2.0.4-rc.3 → 2.0.4-rc.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.es.d.ts +301 -117
- package/dist/index.es.js +9317 -2993
- package/dist/index.umd.js +42 -32
- package/package.json +1 -1
package/dist/index.umd.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
(function($,I){typeof exports=="object"&&typeof module<"u"?module.exports=I():typeof define=="function"&&define.amd?define(I):($=typeof globalThis<"u"?globalThis:$||self,$["ve-pusher"]=I())})(this,function(){"use strict";var yh=Object.defineProperty;var Sh=($,I,ee)=>I in $?yh($,I,{enumerable:!0,configurable:!0,writable:!0,value:ee}):$[I]=ee;var m=($,I,ee)=>Sh($,typeof I!="symbol"?I+"":I,ee);var As,ws,Os,Is,Ds,Ms;function $(r,e){for(var t=0;t<e.length;t++){const i=e[t];if(typeof i!="string"&&!Array.isArray(i)){for(const s in i)if(s!=="default"&&!(s in r)){const n=Object.getOwnPropertyDescriptor(i,s);n&&Object.defineProperty(r,s,n.get?n:{enumerable:!0,get:()=>i[s]})}}}return Object.freeze(Object.defineProperty(r,Symbol.toStringTag,{value:"Module"}))}function I(r){return r&&r.__esModule&&Object.prototype.hasOwnProperty.call(r,"default")?r.default:r}var ee={exports:{}},ir;function an(){return ir||(ir=1,function(r){var e=Object.prototype.hasOwnProperty,t="~";function i(){}Object.create&&(i.prototype=Object.create(null),new i().__proto__||(t=!1));function s(u,c,d){this.fn=u,this.context=c,this.once=d||!1}function n(u,c,d,h,p){if(typeof d!="function")throw new TypeError("The listener must be a function");var l=new s(d,h||u,p),f=t?t+c:c;return u._events[f]?u._events[f].fn?u._events[f]=[u._events[f],l]:u._events[f].push(l):(u._events[f]=l,u._eventsCount++),u}function a(u,c){--u._eventsCount===0?u._events=new i:delete u._events[c]}function o(){this._events=new i,this._eventsCount=0}o.prototype.eventNames=function(){var c=[],d,h;if(this._eventsCount===0)return c;for(h in d=this._events)e.call(d,h)&&c.push(t?h.slice(1):h);return Object.getOwnPropertySymbols?c.concat(Object.getOwnPropertySymbols(d)):c},o.prototype.listeners=function(c){var d=t?t+c:c,h=this._events[d];if(!h)return[];if(h.fn)return[h.fn];for(var p=0,l=h.length,f=new Array(l);p<l;p++)f[p]=h[p].fn;return f},o.prototype.listenerCount=function(c){var d=t?t+c:c,h=this._events[d];return h?h.fn?1:h.length:0},o.prototype.emit=function(c,d,h,p,l,f){var g=t?t+c:c;if(!this._events[g])return!1;var _=this._events[g],T=arguments.length,b,v;if(_.fn){switch(_.once&&this.removeListener(c,_.fn,void 0,!0),T){case 1:return _.fn.call(_.context),!0;case 2:return _.fn.call(_.context,d),!0;case 3:return _.fn.call(_.context,d,h),!0;case 4:return _.fn.call(_.context,d,h,p),!0;case 5:return _.fn.call(_.context,d,h,p,l),!0;case 6:return _.fn.call(_.context,d,h,p,l,f),!0}for(v=1,b=new Array(T-1);v<T;v++)b[v-1]=arguments[v];_.fn.apply(_.context,b)}else{var j=_.length,A;for(v=0;v<j;v++)switch(_[v].once&&this.removeListener(c,_[v].fn,void 0,!0),T){case 1:_[v].fn.call(_[v].context);break;case 2:_[v].fn.call(_[v].context,d);break;case 3:_[v].fn.call(_[v].context,d,h);break;case 4:_[v].fn.call(_[v].context,d,h,p);break;default:if(!b)for(A=1,b=new Array(T-1);A<T;A++)b[A-1]=arguments[A];_[v].fn.apply(_[v].context,b)}}return!0},o.prototype.on=function(c,d,h){return n(this,c,d,h,!1)},o.prototype.once=function(c,d,h){return n(this,c,d,h,!0)},o.prototype.removeListener=function(c,d,h,p){var l=t?t+c:c;if(!this._events[l])return this;if(!d)return a(this,l),this;var f=this._events[l];if(f.fn)f.fn===d&&(!p||f.once)&&(!h||f.context===h)&&a(this,l);else{for(var g=0,_=[],T=f.length;g<T;g++)(f[g].fn!==d||p&&!f[g].once||h&&f[g].context!==h)&&_.push(f[g]);_.length?this._events[l]=_.length===1?_[0]:_:a(this,l)}return this},o.prototype.removeAllListeners=function(c){var d;return c?(d=t?t+c:c,this._events[d]&&a(this,d)):(this._events=new i,this._eventsCount=0),this},o.prototype.off=o.prototype.removeListener,o.prototype.addListener=o.prototype.on,o.prefixed=t,o.EventEmitter=o,r.exports=o}(ee)),ee.exports}var cn=an();const te=I(cn);var sr=(r=>(r.LeftToRight="LeftToRight",r.UpToDown="UpToDown",r.All="All",r.None="None",r))(sr||{}),S=(r=>(r.Camera="camera",r.Screen="screen",r.VideoFile="videoFile",r.Microphone="microphone",r.AudioFile="audioFile",r.Image="image",r.MixAudio="mixAudio",r.MixVideo="mixVideo",r.CustomVideo="customVideo",r.CustomAudio="customAudio",r))(S||{}),z=(r=>(r.DeviceCaptured="deviceCaptured",r.DeviceStopCapture="deviceStopCapture",r.Error="error",r.Interrupted="interrupted",r))(z||{}),R=(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))(R||{}),nr=(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))(nr||{}),or=(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))(or||{}),ar=(r=>(r.STANDARD="48000x40",r.HIGH="48000x128",r))(ar||{}),de=(r=>(r.VideoStreamChange="videoStreamChange",r.AudioStreamChange="audioStreamChange",r))(de||{}),cr=(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))(cr||{});const dr={SizeChange:"sizeChange"};var ot=(r=>(r.Portrait="portrait",r.Landscape="landscape",r))(ot||{});const ur="720p-1",hr="STANDARD";var G=(r=>(r[r.DISCONNECTED=0]="DISCONNECTED",r[r.CONNECTING=1]="CONNECTING",r[r.CONNECTED=2]="CONNECTED",r[r.RECONNECTING=3]="RECONNECTING",r))(G||{}),fe=(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))(fe||{}),at=(r=>(r[r.PushUrlInvalid=1001]="PushUrlInvalid",r[r.ReconnectTimeout=1002]="ReconnectTimeout",r))(at||{}),y=(r=>(r.TRACK_NOT_AVAILABLE="track-not-available",r.UNEXPECTED_TYPE="unexpected-type",r.PLAY_FAILED="play-failed",r.CAPTURE_FAILED="capture-failed",r.NOT_SUPPORTED="not-supported",r.UNEXPECTED_ERROR="unexpected-error",r))(y||{}),E=(r=>(r.AUDIO="audio",r.VIDEO="video",r))(E||{}),D=(r=>(r.ENDED="ended",r.MUTE="mute",r.UNMUTE="unmute",r.PLAY_FAILED="play-failed",r.SIZE_CHANGE="size-change",r))(D||{});const O=[];for(let r=0;r<256;++r)O.push((r+256).toString(16).slice(1));function dn(r,e=0){return(O[r[e+0]]+O[r[e+1]]+O[r[e+2]]+O[r[e+3]]+"-"+O[r[e+4]]+O[r[e+5]]+"-"+O[r[e+6]]+O[r[e+7]]+"-"+O[r[e+8]]+O[r[e+9]]+"-"+O[r[e+10]]+O[r[e+11]]+O[r[e+12]]+O[r[e+13]]+O[r[e+14]]+O[r[e+15]]).toLowerCase()}let ct;const un=new Uint8Array(16);function hn(){if(!ct){if(typeof crypto>"u"||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");ct=crypto.getRandomValues.bind(crypto)}return ct(un)}const pr={randomUUID:typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};function ue(r,e,t){var s;if(pr.randomUUID&&!r)return pr.randomUUID();r=r||{};const i=r.random??((s=r.rng)==null?void 0:s.call(r))??hn();if(i.length<16)throw new Error("Random bytes length must be >= 16");return i[6]=i[6]&15|64,i[8]=i[8]&63|128,dn(i)}class lr{constructor(){m(this,"id",ue());m(this,"_nextNode");m(this,"_track");m(this,"_destNode")}gain(e){if(this._nextNode instanceof mr)return this._nextNode.g=e,this._nextNode;const t=new mr(this,{g:e});return this._nextNode=t,t}connect(e,t){if(!this.available())return;let{_node:i}=this;i||(i=this.createNode(e)),this._node=i,this.previousNode&&this.previousNode.connect(e,i),t&&i.connect(t)}available(){var e;return((e=this.previousNode)==null?void 0:e.available())??!1}destroy(){var e;(e=this._node)==null||e.disconnect(),delete this._node}}class mr extends lr{constructor(t,i){super();m(this,"previousNode");m(this,"_node");m(this,"_g");this.previousNode=t,this._g=i.g}createNode(t){return new GainNode(t,{gain:this._g})}set g(t){this._g=t,this._node&&(this._node.gain.value=t)}}class pn extends lr{constructor(t){super();m(this,"previousNode",null);m(this,"source");this.source=t}available(){return this.source.available()}destroy(){super.destroy()}}class ln extends pn{constructor(){super(...arguments);m(this,"_node")}createNode(t){if(this._node)return this._node;let i;if(this.source instanceof Er){const s=this.source.element();i=new MediaElementAudioSourceNode(t,{mediaElement:s}),s.muted=!1}else{const s=this.source.track();i=new MediaStreamAudioSourceNode(t,{mediaStream:new MediaStream([s])})}return i}}class C extends Error{constructor(t,i,s){super(i);m(this,"code");m(this,"message");m(this,"error");this.code=t,this.message=i,this.error=s,Object.setPrototypeOf(this,C.prototype)}toString(){return`VeCapture Error: ${this.code} ${this.message}`}}const fr={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"}},_r="__debug__",mn="[VE-CAPTURE]";function fn(){if(typeof location>"u"||typeof localStorage>"u")return!1;let r=!1;return location.href.includes(_r)&&(r=!0),localStorage.getItem(_r)&&(r=!0),r}let L=class{constructor(e){m(this,"moduleName");this.moduleName=e}print(e,t,...i){const s=_n();fn()&&console.log(`${s}-${mn}%c[${fr[e].text}]%c[${this.moduleName}][${t}]`,`background-color:${fr[e].color};`,"background-color:rgba(0, 0, 0, 0)",...i)}info(e,...t){this.print("info",e,...t)}warn(e,...t){this.print("warn",e,...t)}error(e,...t){this.print("err",e,...t)}success(e,...t){this.print("succ",e,...t)}invoke(e,t){const i=this;return function(...n){i.info(`${t}-invoke`,...n);try{const a=e(...n);return typeof(a==null?void 0:a.then)=="function"?a.then(o=>(i.success(`${t}-result`,o),o)).catch(o=>{throw i.error(`${t}-result`,o),o}):(i.success(`${t}-result`,a),a)}catch(a){i.error(`[${t}-result`,a)}}}};function _n(){const r=new Date;return`${r.toTimeString().split(" ")[0]}:${r.getMilliseconds().toString().padStart(3,"0")}`}function dt(r,e){const t=document.createElement(r);return e.id&&(t.id=e.id),e.classList&&e.classList.forEach(i=>{t.classList.add(i)}),e.style&&Object.assign(t.style,e.style),e.attributes&&Object.entries(e.attributes).forEach(([i,s])=>{i==="muted"&&(t instanceof HTMLVideoElement||t instanceof HTMLAudioElement)?t.muted=!0:t.setAttribute(i,s)}),t}function gr({width:r,height:e}){const t=document.createElement("canvas"),i=t.getContext("2d");if(!i)throw new C(y.NOT_SUPPORTED,"CanvasRenderingContext2D is not supported by user agent");return t.width=r,t.height=e,t.style.width="100%",t.style.height="100%",{context:i,canvas:t}}class ut{constructor(e){m(this,"target");m(this,"_eventDict",new Map);this.target=e}on(e,t){let i=this._eventDict.get(e);i||(i=[t]),this._eventDict.set(e,i),this.target.addEventListener(e,t)}off(e,t){let i=this._eventDict.get(e);i&&(i=i.filter(s=>s!==t),this._eventDict.set(e,i),this.target.removeEventListener(e,t))}once(e,t){const i=s=>{t(s),this.off(e,i)};this.on(e,i)}clear(e){const t=this._eventDict.get(e);t&&t.forEach(i=>{this.target.removeEventListener(e,i)})}clearAll(){for(const e of this._eventDict.keys())this.clear(e)}}const x=()=>typeof window>"u";function P(){return navigator.userAgent.toLowerCase()}function ht(r=P()){let e="none";return x()||(r.match("firefox")!==null?e="firefox":r.match("Chrome")!==null?(e="chrome",r.match("Electron")!==null&&(e="electron")):(r.match("Safari")!==null||r.match("AppleWebKit")!==null)&&(e="safari")),e}const vr=ht()==="firefox",Fe=ht()==="safari";ht(),!x()&&/crios/i.test(P()),!x()&&/edg\//i.test(P()),!x()&&/edgA/i.test(P()),!x()&&/edgios/i.test(P()),!x()&&/dingtalk/i.test(P()),!x()&&/opr\//.test(P()),!x()&&/(iphone|ipod)/i.exec(P()),!x()&&(/(ipad)/i.exec(P())||/macintosh/i.test(P())&&"ontouchend"in document),!x()&&/macintosh/i.test(P()),!x()&&/micromessenger/i.test(P()),!x()&&P().includes("mobile"),!x()&&/sm-\w+/i.test(P());const gn=!x()&&!!/(iphone|ipad|ipod)/i.exec(P());!x()&&/android/i.test(P()),!x()&&/windows/i.test(P()),!x()&&/openharmony/i.test(P());let Cr="0";const vn=!x()&&((As=P().match(/version\/(\d+)/i))==null?void 0:As[1]);Fe&&vn&&(Cr=(ws=navigator.userAgent.match(/version\/(\d+\.\d+)/i))==null?void 0:ws[1]),!x()&&((Os=P().match(/firefox\/(\d+)/i))==null||Os[1]);const pt=Cr;!x()&&((Ds=(Is=P().match(/ ([\d_]+) like mac os x/i))==null?void 0:Is[1])==null||Ds.split("_").map(r=>parseInt(r))),!x()&&((Ms=P().match(/chrome\/(\d+)/i))==null||Ms[1]);function Cn(){var r;return!!((r=navigator==null?void 0:navigator.permissions)!=null&&r.query)}function lt(){return!!(navigator!=null&&navigator.mediaDevices)}function yn(){var r;return lt()&&!!((r=navigator==null?void 0:navigator.mediaDevices)!=null&&r.getUserMedia)}function Sn(){return!!Promise.withResolvers}function Tn(){return!(Fe&&pt==="16.1")}function En(){return!(Fe&&pt&&["16.1","16.2","16.3"].includes(pt))}function bn(){return!vr}function kn(){return typeof CanvasCaptureMediaStreamTrack<"u"}function Pn(r){return typeof r.requestFrame=="function"}function Rn(){return!!lt()&&typeof navigator.mediaDevices.ondevicechange<"u"&&typeof navigator.mediaDevices.addEventListener=="function"}const W={permissionQuery:Cn,mediaDevices:lt,settingResolutionInGetDisplayMedia:Tn,promiseWithResolvers:Sn,getUserMedia:yn,isolateEnumerateDevices:bn,supportIdealParamsInGetDisplayMedia:En,canvasCaptureMediaStreamTrack:kn,requestFrameOnMediaStream:Pn,ondevicechange:Rn};function xn(){if(W.promiseWithResolvers())return Promise.withResolvers();let r,e;const t=new Promise((i,s)=>{r=i,e=s});if(!r||!e)throw Error("resolver and rejector working unexpected");return{promise:t,resolve:r,reject:e}}function yr(r={}){const{timeout:e,message:t}={timeout:0,message:new C(y.UNEXPECTED_ERROR,"unexpected timeout"),...r},{promise:i,resolve:s,reject:n}=xn();if(e<=0)return{promise:i,resolve:s,reject:n};const a=setTimeout(()=>{n(t)},e);return{promise:i,resolve:u=>{clearTimeout(a),s(u)},reject:n}}const An={playsinline:"","webkit-playsinline":"","x5-playsinline":"","x5-video-player-type":"h5","x-webkit-airplay":"allow",preload:"metadata",muted:"",crossOrigin:"anonymous"},wn={playsinline:"","webkit-playsinline":"",preload:"metadata",muted:"",crossOrigin:"anonymous"};class ke{constructor(e,t=[]){m(this,"id",ue());m(this,"_referenceTracks",[]);m(this,"_element");m(this,"_volumeMode",0);m(this,"_readyLock");m(this,"_releaseReadyLock");m(this,"_throwReadyLock");m(this,"_stream");let i;if(e instanceof MediaStreamTrack){const o=new MediaStream([e]);i=On(o),this._stream=o}else if(e.url)i=In(e);else throw new C(y.UNEXPECTED_TYPE,`got ${typeof e}, expected: MediaStreamTrack or constraints for creating element`);const{promise:s,resolve:n,reject:a}=yr({timeout:2e3,message:new C(y.PLAY_FAILED,"load media timeout")});this._readyLock=s,this._releaseReadyLock=n,this._throwReadyLock=a,this._element=new ut(i),this._bindPlayerEvent(this._element),this._referenceTracks=[...t]}addReferenceTrack(e){this._referenceTracks.push(e)}track(e){this._playElement();let t=this._stream;if((!t||!t.active)&&(t=this._element.target.captureStream(),this._stream=t),e===E.AUDIO){this._upgradeVolumeMode(1e-4);const i=t.getAudioTracks();if(i.length<1)throw new C(y.UNEXPECTED_TYPE,"got empty list of audio tracks");return i[0]}if(e===E.VIDEO){const i=t.getVideoTracks();if(i.length<1)throw new C(y.UNEXPECTED_TYPE,"got empty list of video tracks");return i[0]}throw new C(y.UNEXPECTED_TYPE,`got ${e}, expected: audio, video`)}async _playElement(){if(!(!this._element.target.muted&&this._element.target.volume===this._volumeMode&&!this._element.target.paused))try{this._element.target.muted=!1,this._element.target.volume=this._volumeMode,await this._element.target.play()}catch(e){throw this._handlePlayFailed(),new C(y.PLAY_FAILED,"play element failed",e)}}_bindPlayerEvent(e){e.on("loadedmetadata",()=>{this._releaseReadyLock()}),e.on("error",()=>{this._throwReadyLock(new C(y.PLAY_FAILED,"HTMLMediaElement got error when loading file"))})}_handlePlayFailed(){this._referenceTracks.forEach(e=>{e.handlePlayFailed()})}_upgradeVolumeMode(e){console.warn("update volume mode",e);const t=this._volumeMode>e?this._volumeMode:e;this._volumeMode=t,this._playElement()}element(e=!1){return e&&this._upgradeVolumeMode(1),this._playElement(),this._element.target}isReady(){return this._readyLock}removeReference(e){const t=this._referenceTracks.indexOf(e);this._referenceTracks.splice(t,1),this._referenceTracks.length===0&&this.destroy()}destroy(){this._element.target.srcObject=null,this._element.target.src="",this._element.target.load();const e=[...this._referenceTracks];this._referenceTracks=[],e.forEach(t=>{try{t.destroy()}catch{}})}}function On(r){let e="audio";r.getVideoTracks().length>0&&(e="video");const t=Sr(e==="video"?E.VIDEO:E.AUDIO);return t.srcObject=r,t}function In(r){const{url:e,kind:t,loop:i}=r,s=Sr(t);return s.src=e,s.loop=i,s}function Sr(r){if(r===E.VIDEO)return dt(E.VIDEO,{style:{width:"100%",height:"100%"},attributes:An});if(r===E.AUDIO)return dt(E.AUDIO,{style:{display:"none"},attributes:wn});throw new C(y.UNEXPECTED_TYPE,`got ${r}, expected: audio, video`)}class mt extends te{emit(e,...t){const i=this.listenerCount(e);return Promise.resolve().then(()=>{super.emit(e,...t)}),!!i}on(e,t,i){const s=(...n)=>{try{return t(...n)}catch(a){console.error(`[SafeEventEmitter] event listener threw an error when handling [${e}] event: `,a)}};return super.on(e,s,i)}once(e,t,i){const s=(...n)=>{try{return t(...n)}catch(a){console.error(`[SafeEventEmitter] event listener threw an error when handling [${e}] event: `,a)}};return super.once(e,s,i)}}function ft(r){if(typeof r=="number")return r;if(typeof(r==null?void 0:r.exact)=="number")return r.exact;if(typeof(r==null?void 0:r.ideal)=="number")return r.ideal;if(typeof(r==null?void 0:r.max)=="number")return r.max;if(typeof(r==null?void 0:r.min)=="number")return r.min;throw new C(y.UNEXPECTED_TYPE,"unexpected constraints type")}const _t=1e3;class Tr{constructor(e){m(this,"id",ue());m(this,"_context");m(this,"_canvas");m(this,"_image");m(this,"_config");m(this,"_readyLock");m(this,"_releaseReadyLock");m(this,"_throwReadyLock");m(this,"_loopTimer");m(this,"_referenceTracks",[]);m(this,"_stream");const t=ft(e.width),i=ft(e.height),s=ft(e.frameRate);this._config={width:t,height:i,frameRate:s};const{context:n,canvas:a}=gr({width:t,height:i});this._context=n,this._canvas=a;const o=Dn({url:e.url,width:t,height:i});this._image=new ut(o);const{promise:u,resolve:c,reject:d}=yr({timeout:2e3,message:new C(y.PLAY_FAILED,"load image timeout")});this._readyLock=u,this._releaseReadyLock=c,this._throwReadyLock=d,this._bindImageEvent(this._image)}track(){this._paint();const{frameRate:e}=this._config;let t=this._stream;(!t||!t.active)&&(t=this._canvas.captureStream(e),this._stream=t);const i=t.getVideoTracks();if(i.length<1)throw new C(y.UNEXPECTED_TYPE,"got empty list of video tracks");return i[0]}element(){return this._image.target}isReady(){return this._readyLock}_bindImageEvent(e){e.on("load",()=>{this._releaseReadyLock()}),e.on("error",()=>{this._throwReadyLock(new C(y.PLAY_FAILED,"HTMLMediaElement got error when loading file"))})}async _paint(){const{width:e,height:t,frameRate:i}=this._config;this._context.drawImage(this._image.target,0,0,e,t),this._loopTimer&&clearTimeout(this._loopTimer),this._loopTimer=setTimeout(this._paint.bind(this),_t/i)}addReferenceTrack(e){this._referenceTracks.push(e)}removeReference(e){const t=this._referenceTracks.indexOf(e);this._referenceTracks.splice(t,1),console.warn("reference length",this._referenceTracks),this._referenceTracks.length}}function Dn({url:r,height:e,width:t}){const i=dt("img",{style:{width:`${t}px`,height:`${e}px`},attributes:{crossOrigin:"anonymous"}});return i.src=r,i}class gt extends mt{constructor(t){super();m(this,"id",ue());m(this,"_track");m(this,"_element");t instanceof MediaStreamTrack?(this._track=new ut(t),this._bindTrackEvent(this._track)):t instanceof ke?(this._element=t,t.addReferenceTrack(this)):t instanceof Tr&&(this._element=t)}_bindTrackEvent(t){t.on("ended",this._handleTrackEnded.bind(this)),t.on("mute",()=>{this.emit(D.MUTE)}),t.on("unmute",()=>{this.emit(D.UNMUTE)})}_handleTrackEnded(){this.emit(D.ENDED),this.destroy()}handlePlayFailed(){this.emit(D.PLAY_FAILED)}track(){if(this.logger.info("track"),!this.available())throw new C(y.TRACK_NOT_AVAILABLE,"track is not available when creating MediaStreamTrack");if(this._track)return this._track.target;if(!this._element)throw new C(y.UNEXPECTED_TYPE,"got this._element falsy");const t=this._element.track(this.kind);return this.logger.success("track",t),t}element(){if(this.logger.info("element"),!this.available())throw new C(y.TRACK_NOT_AVAILABLE,"track is not available when creating HTMLMediaElement");if(this._element)return this._element.element();if(!this._track)throw new C(y.UNEXPECTED_TYPE,"got this._track falsy");const t=new ke(this._track.target,[this]);this._element=t;const i=t.element();return this.logger.success("element",i),i}available(){return!!(this._track||this._element)}destroy(){var t,i,s;(t=this._track)==null||t.clearAll(),(i=this._track)==null||i.target.stop(),this._track&&delete this._track,(s=this._element)==null||s.removeReference(this),delete this._element}}class Ve extends gt{constructor(){super(...arguments);m(this,"kind",E.AUDIO);m(this,"_node")}node(){if(this.logger.info("node",this.id),!this.available())throw new C(y.TRACK_NOT_AVAILABLE,"track is not avaiable when creating node");if(this._node)return this._node;const t=new ln(this);return this._node=t,t}element(){if(this.logger.info("element",this.id),!this.available())throw new C(y.TRACK_NOT_AVAILABLE,"track is not available when creating HTMLMediaElement");if(this._element){const i=this._element.element(!0);if(!(i instanceof HTMLMediaElement))throw new C(y.UNEXPECTED_TYPE,"source should be HTMLMediaElement");return i}if(!this._track)throw new C(y.UNEXPECTED_TYPE,"got this._track falsy");const t=new ke(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 Mn extends Ve{constructor(){super(...arguments);m(this,"logger",new L("MicrophoneAudioTrack"))}}class Ln extends Ve{constructor(){super(...arguments);m(this,"logger",new L("ScreenAudioTrack"))}}class Er extends Ve{constructor(){super(...arguments);m(this,"logger",new L("MediaAudioTrack"))}handlePlayFailed(){this.emit(D.PLAY_FAILED)}async play(){if(this._element){if(!(this._element instanceof ke))throw new C(y.UNEXPECTED_TYPE,"element is not TrackMediaElement");return this._element._playElement()}}}class Nn extends Ve{constructor(){super(...arguments);m(this,"logger",new L("CustomAudioTrack"))}}let Fn=1;const vt=new L("PromiseQueue");class Vn{constructor(e){m(this,"lockingPromise",Promise.resolve());m(this,"locks",0);m(this,"name","");m(this,"lockId");m(this,"closeReason");this.lockId=Fn++,e&&(this.name=e),vt.info(`lock-${this.name}-${this.lockId}`,"is created.")}get isLocked(){return this.locks>0}lock(){this.locks+=1,vt.info(`lock-${this.name}-${this.lockId}`,`locked, current queue ${this.locks}.`);let e;const t=new Promise(s=>{e=()=>{this.locks-=1,vt.info(`lock-${this.name}-${this.lockId}`,`unlocked, current queue ${this.locks}.`),s()}}),i=this.lockingPromise.then(()=>e);return this.lockingPromise=this.lockingPromise.then(()=>t),i}}const Un=300,$n=3e3,H=new L("Devices");class Bn extends mt{constructor(){super();m(this,"_deviceMap",{audioinput:[],audiooutput:[],videoinput:[]});m(this,"_permissions",{[E.AUDIO]:!1,[E.VIDEO]:!1});m(this,"_changedQueue",new Vn("device changed queue"));this._init()}async _init(){this._initDeviceChanged(),await this._initPermissionChanged();const t=Rr(this._permissions);t.length>0&&this._refreshDevices(t)}_initDeviceChanged(){if(H.info("_initDeviceChanged","invoked"),!W.ondevicechange()){H.error("_initDeviceChanged","no supported, use timer instead"),setInterval(()=>{this._handleDeviceChanged()},$n);return}W.ondevicechange()&&navigator.mediaDevices.addEventListener("devicechange",()=>{H.info("devicechange"),setTimeout(()=>{this._handleDeviceChanged()},Un)})}async _initPermissionChanged(){if(!W.permissionQuery()){H.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",()=>{H.info("_initPermissionChanged","update permission for audio"),this._permissions.audio=t.state==="granted"})}catch(t){H.error("_initPermissionChanged",t)}try{const t=await navigator.permissions.query({name:"camera"});this._permissions.video=t.state==="granted",t.addEventListener("change",()=>{H.info("_initPermissionChanged","update permission for video"),this._permissions.video=t.state==="granted"})}catch(t){H.error("_initPermissionChanged",t)}}async _refreshDevices(t){if(!W.mediaDevices())throw new C(y.NOT_SUPPORTED,"mediaDevices is not supported");if(t.length===0)throw new C(y.UNEXPECTED_TYPE,"kinds expect to containt values");let i;if(!W.isolateEnumerateDevices()){const a={};t.forEach(o=>{a[o]=!0}),i=await navigator.mediaDevices.getUserMedia(a)}let s=await navigator.mediaDevices.enumerateDevices();i&&br(i),s=s.filter(({deviceId:a})=>!!a);const n={audioinput:[],audiooutput:[],videoinput:[]};s.forEach(a=>{const{kind:o}=a;n[o].push(a)}),this._deviceMap=n}async _acquireUserPermission(t){let i=!1;if(t.forEach(s=>{i=i||!this._permissions[s]}),!i)return{grant:!0};if(!W.getUserMedia())return{grant:!1,reason:new C(y.NOT_SUPPORTED,"getUserMedia is not supported")};try{const s={};t.forEach(a=>{s[a]=!0});const n=await navigator.mediaDevices.getUserMedia(s);return n?(s.audio&&(this._permissions[E.AUDIO]=!0),s.video&&(this._permissions[E.VIDEO]=!0),br(n),{grant:!0}):{grant:!1,reason:new C(y.UNEXPECTED_TYPE,"get stream falsy")}}catch(s){return{grant:!1,reason:new C(y.CAPTURE_FAILED,"acquire user permission failed",s)}}}async _handleDeviceChanged(){H.info("_handleDeviceChanged",this._deviceMap,this._permissions);const t=await this._changedQueue.lock();try{const i=Pr(this._deviceMap);let s=[];const n=Rr(this._permissions);n.length===0?H.warn("_handleDeviceChanged","no permission, use empty list"):(await this._refreshDevices(n),s=Pr(this._deviceMap)),s.forEach(a=>{i.findIndex(u=>kr(u,a))!==-1||this.emit("onDeviceStateChanged",{deviceInfo:a,deviceState:"active"})}),i.forEach(a=>{s.findIndex(u=>kr(u,a))!==-1||this.emit("onDeviceStateChanged",{deviceInfo:a,deviceState:"inactive"})})}finally{t()}}async enumerateDevices(t){const i=[];t.forEach(o=>{if(o==="audioinput"||o==="audiooutput")i.push(E.AUDIO);else if(o==="videoinput")i.push(E.VIDEO);else throw new C(y.UNEXPECTED_TYPE,"kind in kinds should be enum MediaDeviceKind")});const{grant:s,reason:n}=await this._acquireUserPermission(i);if(!s)throw n;await this._refreshDevices(i);const a=[];return t.forEach(o=>{a.push(...this._deviceMap[o])}),a}async enableDevices(t){return this._acquireUserPermission(t)}}function br(r){r.getTracks().forEach(e=>e.stop())}function kr(r,e){return r.deviceId===e.deviceId}function Pr(r){return Array.from([...r.audioinput.values(),...r.videoinput.values(),...r.audiooutput.values()])}function Rr(r){const e=[];return r.audio&&e.push(E.AUDIO),r.video&&e.push(E.VIDEO),e}const Ct=new Bn,yt={LeftToRight:"LeftToRight",UpToDown:"UpToDown",All:"All"};class St{constructor(){m(this,"id",ue())}position(e,t){return new jn(this,{x:e,y:t})}scale(e){return new xr(this,{s:e})}mirror(e){return new xr(this,{mirrorType:e})}available(){var e;return((e=this.previousNode)==null?void 0:e.available())??!1}}class jn extends St{constructor(t,i){super();m(this,"previousNode");m(this,"_x");m(this,"_y");this.previousNode=t,this._x=i.x,this._y=i.y}paint(t){t.translate(this._x,this._y)}}class xr extends St{constructor(t,i){super();m(this,"previousNode");m(this,"_scaleParams",[1,1]);if(this.previousNode=t,i.mirrorType)switch(i.mirrorType){case yt.LeftToRight:this._scaleParams=[-1,1];break;case yt.UpToDown:this._scaleParams=[1,-1];break;case yt.All:this._scaleParams=[-1,-1];break;default:this._scaleParams=[1,1];break}else i.s&&(this._scaleParams=[i.s,i.s])}paint(t){t.scale(this._scaleParams[0],this._scaleParams[1])}}class zn extends St{constructor(t){super();m(this,"previousNode",null);m(this,"_source");this._source=t}available(){return this._source.available()}}class Ue extends zn{constructor(t,i){super(t);m(this,"_targetWidth");m(this,"_targetHeight");const{width:s,height:n}=i??{};this._targetWidth=s??this._source.width(),this._targetHeight=n??this._source.height()}size(t,i){return new Ue(this._source,{width:t,height:i})}paint(t){const i=this._targetWidth,s=this._targetHeight;t.drawImage(this._source.element(),-i/2,-s/2,i,s)}}class Gn extends gt{constructor(){super(...arguments);m(this,"logger",new L("PictureTrack"));m(this,"kind",E.VIDEO)}element(){const t=super.element();if(!(t instanceof HTMLImageElement))throw new C(y.UNEXPECTED_TYPE,"source should be HTMLVideoElement");return this.logger.info("element",t),t}height(){const{height:t}=this.element();return t??0}width(){const{width:t}=this.element();return t??0}node(){if(!this.available())throw new C(y.TRACK_NOT_AVAILABLE,"track is not avaiable when creating node");const t=new Ue(this);return this.logger.info("node",t),t}destroy(){this.logger.warn("destroy"),super.destroy()}}const Hn=500;class $e extends gt{constructor(){super(...arguments);m(this,"kind",E.VIDEO);m(this,"sizeChangeTimer");m(this,"watchSizeChangeOnce",()=>{const t=this.width(),i=this.height();this.sizeChangeTimer=setTimeout(()=>{const s=this.width(),n=this.height();(i!==n||t!==s)&&this.emit(D.SIZE_CHANGE,{width:s,height:n})},Hn)})}element(){const t=super.element();if(!(t instanceof HTMLVideoElement))throw new C(y.UNEXPECTED_TYPE,"source should be HTMLVideoElement");return t}node(){if(!this.available())throw new C(y.TRACK_NOT_AVAILABLE,"track is not avaiable when creating node");return new Ue(this)}destroy(){clearTimeout(this.sizeChangeTimer),super.destroy()}}class qn extends $e{constructor(t){super(t);m(this,"logger",new L("CameraVideoTrack"));this.watchSizeChangeOnce()}height(){const{height:t}=this.track().getSettings();return t??0}width(){const{width:t}=this.track().getSettings();return t??0}}class Wn extends $e{constructor(t){super(t);m(this,"logger",new L("ScreenVideoTrack"));this.watchSizeChangeOnce()}height(){const{height:t}=this.track().getSettings();return t??0}width(){const{width:t}=this.track().getSettings();return t??0}}class Xn extends $e{constructor(){super(...arguments);m(this,"logger",new L("MediaVideoTrack"))}height(){const{videoHeight:t}=this.element();return t??0}width(){const{videoWidth:t}=this.element();return t??0}}class Kn extends $e{constructor(){super(...arguments);m(this,"logger",new L("CustomVideoTrack"))}height(){const{height:t}=this.track().getSettings();return t??0}width(){const{width:t}=this.track().getSettings();return t??0}}function Ar(r,e){let t;if(e!=null&&e.frameRate&&typeof e.frameRate=="number"&&(t=e.frameRate),t)try{r.applyConstraints({...e,frameRate:{min:t,ideal:t}})}catch{}}const X=new L("Capture");async function Jn(r){return Ct.enumerateDevices(r)}async function Yn(r){Ct.removeAllListeners("onDeviceStateChanged"),Ct.on("onDeviceStateChanged",r)}async function Zn(r){let e;try{const i={video:r??!0};typeof i.video=="object"&&i.video.facingMode&&delete i.video.deviceId,e=await navigator.mediaDevices.getUserMedia(i)}catch(i){throw new C(y.CAPTURE_FAILED,"got error when capturing camera",i)}const t=e.getVideoTracks()[0];if(r!=null&&r.frameRate&&Ar(t,r),!t)throw new C(y.UNEXPECTED_TYPE,"got falsy in track");return new qn(t)}async function Qn(r,e){const{video:t,audio:i}=r;let s=t===!0?{}:t;e!=null&&e.displaySurface&&(s.displaySurface=e.displaySurface,delete e.displaySurface),W.settingResolutionInGetDisplayMedia()||(s=!0),!W.supportIdealParamsInGetDisplayMedia()&&typeof s!="boolean"&&(s.width&&typeof s.width=="number"&&(s.width={max:s.width}),s.height&&typeof s.height=="number"&&(s.height={max:s.height}));let n;try{n=await navigator.mediaDevices.getDisplayMedia({video:s,audio:i,...e})}catch(c){throw new C(y.CAPTURE_FAILED,"got error when capture screen",c)}const a=n.getVideoTracks()[0],o=n.getAudioTracks()[0];if(!a)throw new C(y.UNEXPECTED_TYPE,"got falsy in videoTrack");typeof s!="boolean"&&typeof s.frameRate=="number"&&Ar(a,s);const u=[];return u.push(new Wn(a)),o&&u.push(new Ln(o)),u}async function eo(r){const{url:e,audio:t,video:i,loop:s}=r,n=new ke({url:e,kind:i?E.VIDEO:E.AUDIO,loop:s}),a=[];return t&&a.push(new Er(n)),i&&a.push(new Xn(n)),await n.isReady(),a}async function to(r){const e=new Tr(r);return await e.isReady(),new Gn(e)}async function ro(r){let e;try{const i={audio:r??!0};e=await navigator.mediaDevices.getUserMedia(i)}catch(i){throw new C(y.CAPTURE_FAILED,"got error when capturing microphone",i)}const t=e.getAudioTracks()[0];if(!t)throw new C(y.UNEXPECTED_TYPE,"got falsy in track");return new Mn(t)}function io(r){if(!r||r.kind!=="video")throw new C(y.UNEXPECTED_TYPE,"error custom video track type");return new Kn(r)}function so(r){if(!r||r.kind!=="audio")throw new C(y.UNEXPECTED_TYPE,"error custom audio track type");return new Nn(r)}const no=X.invoke(Jn,"enumerateInputDevices"),oo=X.invoke(Zn,"createCameraTrack"),ao=X.invoke(to,"createPictureTrack"),wr=X.invoke(eo,"createMediaTracks"),co=X.invoke(ro,"createMicrophoneTrack"),uo=X.invoke(Qn,"createScreenTracks"),ho=X.invoke(Yn,"onDeviceChanged"),po=X.invoke(io,"createCustomVideoTrack"),lo=X.invoke(so,"createCustomAudioTrack");var Tt=(r=>(r.PAUSING="pausing",r))(Tt||{});const mo={sampleRate:48e3,keepAlive:!0},Or=new Map,Pe=new L("Mixer");class fo extends mt{constructor(t){super();m(this,"id",ue());m(this,"_context");m(this,"_config");m(this,"_nodeList",[]);m(this,"_destNode");m(this,"_bufferNode");m(this,"_track");Pe.info("ctor",t),this._config={...mo,...t},this._context=_o(this._config),this._bindContextEvent(this._context)}mix(t){Pe.info("mix",t),Et(this._context);for(const i of this._nodeList)t.includes(i)||i.destroy();this._nodeList=t,this._connect(t,this._destNode),this._nodeList.length===0&&this._appendSlience(this._context,this._destNode)}resume(){return Pe.info("resume"),this._context.resume()}_connect(t,i){for(const s of t)s.connect(this._context,i)}_appendSlience(t,i){if(!i||this._bufferNode)return;const{sampleRate:s}=t,n=new AudioBuffer({length:100,sampleRate:s}),a=new AudioBufferSourceNode(t,{buffer:n,loop:!0});a.connect(i),this._bufferNode=a}_bindContextEvent(t){t.addEventListener("statechange",this._handleContextStateChange.bind(this))}_handleContextStateChange(){const t=this._context;(t.state==="suspended"||t.state==="interrupted")&&(Pe.info("_emit_",Tt.PAUSING),this.emit(Tt.PAUSING))}track(){if(Pe.info("track"),Et(this._context),this._track)return this._track;let t=this._destNode;t||(t=new MediaStreamAudioDestinationNode(this._context)),this._nodeList.length===0&&this._appendSlience(this._context,t),this._connect(this._nodeList,t);const i=t.stream.getAudioTracks()[0];return this._destNode=t,this._track=i,i}}function _o(r){const{sampleRate:e,keepAlive:t}=r;let i=Or.get(e);return(!i||i.state==="closed")&&(i=new AudioContext({sampleRate:e}),Or.set(e,i)),t&&(i.onstatechange=()=>{Et(i)}),i}function Et(r){if(r.state==="suspended"||r.state==="interrupted")return r.resume()}const go=r=>(e,t)=>(r.set(e,t),t),Ir=Number.MAX_SAFE_INTEGER===void 0?9007199254740991:Number.MAX_SAFE_INTEGER,Dr=536870912,Mr=Dr*2,vo=(r,e)=>t=>{const i=e.get(t);let s=i===void 0?t.size:i<Mr?i+1:0;if(!t.has(s))return r(t,s);if(t.size<Dr){for(;t.has(s);)s=Math.floor(Math.random()*Mr);return r(t,s)}if(t.size>Ir)throw new Error("Congratulations, you created a collection of unique numbers which uses all available integers!");for(;t.has(s);)s=Math.floor(Math.random()*Ir);return r(t,s)},Lr=new WeakMap,Co=go(Lr),re=vo(Co,Lr),yo=r=>r.method!==void 0&&r.method==="call",So=r=>typeof r.id=="number"&&typeof r.result=="boolean",Nr=((r,e)=>{let t=null;return()=>{if(t!==null)return t;const i=new Blob([e],{type:"application/javascript; charset=utf-8"}),s=URL.createObjectURL(i);return t=r(s),setTimeout(()=>URL.revokeObjectURL(s)),t}})(r=>{const e=new Map([[0,()=>{}]]),t=new Map([[0,()=>{}]]),i=new Map,s=new Worker(r);return s.addEventListener("message",({data:c})=>{if(yo(c)){const{params:{timerId:d,timerType:h}}=c;if(h==="interval"){const p=e.get(d);if(typeof p===void 0)throw new Error("The timer is in an undefined state.");if(typeof p=="number"){const l=i.get(p);if(l===void 0||l.timerId!==d||l.timerType!==h)throw new Error("The timer is in an undefined state.")}else typeof p=="function"&&p()}else if(h==="timeout"){const p=t.get(d);if(typeof p===void 0)throw new Error("The timer is in an undefined state.");if(typeof p=="number"){const l=i.get(p);if(l===void 0||l.timerId!==d||l.timerType!==h)throw new Error("The timer is in an undefined state.")}else typeof p=="function"&&(p(),t.delete(d))}}else if(So(c)){const{id:d}=c,h=i.get(d);if(h===void 0)throw new Error("The timer is in an undefined state.");const{timerId:p,timerType:l}=h;i.delete(d),l==="interval"?e.delete(p):t.delete(p)}else{const{error:{message:d}}=c;throw new Error(d)}}),{clearInterval:c=>{if(typeof e.get(c)=="function"){const d=re(i);i.set(d,{timerId:c,timerType:"interval"}),e.set(c,d),s.postMessage({id:d,method:"clear",params:{timerId:c,timerType:"interval"}})}},clearTimeout:c=>{if(typeof t.get(c)=="function"){const d=re(i);i.set(d,{timerId:c,timerType:"timeout"}),t.set(c,d),s.postMessage({id:d,method:"clear",params:{timerId:c,timerType:"timeout"}})}},setInterval:(c,d=0,...h)=>{const p=re(e);return e.set(p,()=>{c(...h),typeof e.get(p)=="function"&&s.postMessage({id:null,method:"set",params:{delay:d,now:performance.timeOrigin+performance.now(),timerId:p,timerType:"interval"}})}),s.postMessage({id:null,method:"set",params:{delay:d,now:performance.timeOrigin+performance.now(),timerId:p,timerType:"interval"}}),p},setTimeout:(c,d=0,...h)=>{const p=re(t);return t.set(p,()=>c(...h)),s.postMessage({id:null,method:"set",params:{delay:d,now:performance.timeOrigin+performance.now(),timerId:p,timerType:"timeout"}}),p}}},`(()=>{"use strict";const e=new Map,t=new Map,r=t=>{const r=e.get(t);return void 0!==r&&(clearTimeout(r),e.delete(t),!0)},s=e=>{const r=t.get(e);return void 0!==r&&(clearTimeout(r),t.delete(e),!0)},o=(e,t)=>{const r=performance.now(),s=e+t-r-performance.timeOrigin;return{expected:r+s,remainingDelay:s}},i=(e,t,r,s)=>{const o=r-performance.now();o>0?e.set(t,setTimeout(i,o,e,t,r,s)):(e.delete(t),postMessage({id:null,method:"call",params:{timerId:t,timerType:s}}))};addEventListener("message",(({data:n})=>{try{if("clear"===n.method){const{id:e,params:{timerId:t,timerType:o}}=n;if("interval"===o)postMessage({id:e,result:r(t)});else{if("timeout"!==o)throw new Error('The given type "'.concat(o,'" is not supported'));postMessage({id:e,result:s(t)})}}else{if("set"!==n.method)throw new Error('The given method "'.concat(n.method,'" is not supported'));{const{params:{delay:r,now:s,timerId:a,timerType:m}}=n;if("interval"===m)((t,r,s)=>{const{expected:n,remainingDelay:a}=o(t,s);e.set(r,setTimeout(i,a,e,r,n,"interval"))})(r,a,s);else{if("timeout"!==m)throw new Error('The given type "'.concat(m,'" is not supported'));((e,r,s)=>{const{expected:n,remainingDelay:a}=o(e,s);t.set(r,setTimeout(i,a,t,r,n,"timeout"))})(r,a,s)}}}}catch(e){postMessage({error:{message:e.message},id:n.id,result:null})}}))})();`),To=r=>Nr().clearTimeout(r),Eo=(...r)=>Nr().setTimeout(...r),bo=r=>r.method!==void 0&&r.method==="call",ko=r=>typeof r.id=="number"&&typeof r.result=="boolean",Po=r=>{const e=new Map([[0,()=>{}]]),t=new Map([[0,()=>{}]]),i=new Map,s=new Worker(r,{credentials:"omit"});return s.addEventListener("message",({data:c})=>{if(bo(c)){const{params:{timerId:d,timerType:h}}=c;if(h==="interval"){const p=e.get(d);if(typeof p===void 0)throw new Error("The timer is in an undefined state.");if(typeof p=="number"){const l=i.get(p);if(l===void 0||l.timerId!==d||l.timerType!==h)throw new Error("The timer is in an undefined state.")}else typeof p=="function"&&p()}else if(h==="timeout"){const p=t.get(d);if(typeof p===void 0)throw new Error("The timer is in an undefined state.");if(typeof p=="number"){const l=i.get(p);if(l===void 0||l.timerId!==d||l.timerType!==h)throw new Error("The timer is in an undefined state.")}else typeof p=="function"&&(p(),t.delete(d))}}else if(ko(c)){const{id:d}=c,h=i.get(d);if(h===void 0)throw new Error("The timer is in an undefined state.");const{timerId:p,timerType:l}=h;i.delete(d),l==="interval"?e.delete(p):t.delete(p)}else{const{error:{message:d}}=c;throw new Error(d)}}),{clearInterval:c=>{if(typeof e.get(c)=="function"){const d=re(i);i.set(d,{timerId:c,timerType:"interval"}),e.set(c,d),s.postMessage({id:d,method:"clear",params:{timerId:c,timerType:"interval"}})}},clearTimeout:c=>{if(typeof t.get(c)=="function"){const d=re(i);i.set(d,{timerId:c,timerType:"timeout"}),t.set(c,d),s.postMessage({id:d,method:"clear",params:{timerId:c,timerType:"timeout"}})}},setInterval:(c,d=0,...h)=>{const p=re(e);return e.set(p,()=>{c(...h),typeof e.get(p)=="function"&&s.postMessage({id:null,method:"set",params:{delay:d,now:performance.timeOrigin+performance.now(),timerId:p,timerType:"interval"}})}),s.postMessage({id:null,method:"set",params:{delay:d,now:performance.timeOrigin+performance.now(),timerId:p,timerType:"interval"}}),p},setTimeout:(c,d=0,...h)=>{const p=re(t);return t.set(p,()=>c(...h)),s.postMessage({id:null,method:"set",params:{delay:d,now:performance.timeOrigin+performance.now(),timerId:p,timerType:"timeout"}}),p}}},Ro={width:640,height:480,frameRate:30,backgroundColor:"#000000"},Be=new L("View");class xo{constructor(e){m(this,"id",ue());m(this,"_context");m(this,"_canvas");m(this,"_config");m(this,"_nodeList",[]);m(this,"_track");m(this,"_stopped",!0);m(this,"_nextTime",Date.now());m(this,"_workerTimeoutId");m(this,"_raqId");m(this,"_workerTimerScriptUrl");m(this,"_customSetTimeout");m(this,"_customClearTimeout");m(this,"_loopTimer");m(this,"_paintLoop",()=>{if(this._stopped){this._workerTimeoutId&&(this._customClearTimeout(this._workerTimeoutId),this._workerTimeoutId=void 0);return}this._drawOnCanvas(),this._workerTimeoutId&&this._customClearTimeout(this._workerTimeoutId),this._workerTimeoutId=this._customSetTimeout(()=>{this._paintLoop(),this._raqId&&(cancelAnimationFrame(this._raqId),this._raqId=void 0)},_t/this._config.frameRate),this._raqId=requestAnimationFrame(this._paintLoop)});Be.info("ctor",e),this._config={...Ro,...e};const{context:t,canvas:i}=gr(this._config);this._context=t,this._canvas=i,this._customSetTimeout=Eo,this._customClearTimeout=To}setWorkerTimerScriptUrl(e){if(this._workerTimerScriptUrl=e,this._workerTimerScriptUrl){const t=Po(this._workerTimerScriptUrl);this._customSetTimeout=(...i)=>t.setTimeout(...i),this._customClearTimeout=i=>t.clearTimeout(i)}}_shouldDraw(e){if(e<this._nextTime)return!1;for(;e>this._nextTime;)this._nextTime+=_t/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=[]){Be.info("draw",e),this._nodeList=e}_drawOnCanvas(){if(this._shouldDraw(Date.now())){this._drawBackground();for(const e of this._nodeList){let t=e;if(t.available()){for(;t;)t.paint(this._context),t=t.previousNode;this._context.setTransform(1,0,0,1,0,0)}}}}_drawBackground(){const{backgroundColor:e,width:t,height:i}=this._config;this._context.clearRect(0,0,t,i),e&&(this._context.fillStyle=e,this._context.fillRect(0,0,t,i))}track(){if(Be.info("track"),this._stopped&&(this._stopped=!1,this._paintLoop()),this._track)return this._track;const{frameRate:e}=this._config,t=this._canvas.captureStream(e);return this._track=t.getVideoTracks()[0],this._track}updateFps(){if(this._track){const e=this._track,{frameRate:t}=this._config,i=this._canvas.captureStream(t);return this._track=i.getVideoTracks()[0],e.stop(),this._track}else return this.track()}element(){return Be.info("element"),this._paintLoop(),this._canvas}stop(){this._stopped=!0}}function Ao(){return Math.random().toString(36).slice(-8)}const wo=`
|
|
1
|
+
(function(Ae,pe){typeof exports=="object"&&typeof module<"u"?module.exports=pe():typeof define=="function"&&define.amd?define(pe):(Ae=typeof globalThis<"u"?globalThis:Ae||self,Ae.vePusher=pe())})(this,function(){"use strict";var mg=Object.defineProperty;var _g=(Ae,pe,Ye)=>pe in Ae?mg(Ae,pe,{enumerable:!0,configurable:!0,writable:!0,value:Ye}):Ae[pe]=Ye;var M=(Ae,pe,Ye)=>_g(Ae,typeof pe!="symbol"?pe+"":pe,Ye);var zc,Oc,Mc,Pc,Lc,Nc;function Ae(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 pe(r){return r&&r.__esModule&&Object.prototype.hasOwnProperty.call(r,"default")?r.default:r}var Ye={exports:{}},ns;function Gc(){return ns||(ns=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(l,c,u){this.fn=l,this.context=c,this.once=u||!1}function s(l,c,u,d,h){if(typeof u!="function")throw new TypeError("The listener must be a function");var f=new i(u,d||l,h),b=t?t+c:c;return l._events[b]?l._events[b].fn?l._events[b]=[l._events[b],f]:l._events[b].push(f):(l._events[b]=f,l._eventsCount++),l}function a(l,c){--l._eventsCount===0?l._events=new n:delete l._events[c]}function o(){this._events=new n,this._eventsCount=0}o.prototype.eventNames=function(){var c=[],u,d;if(this._eventsCount===0)return c;for(d in u=this._events)e.call(u,d)&&c.push(t?d.slice(1):d);return Object.getOwnPropertySymbols?c.concat(Object.getOwnPropertySymbols(u)):c},o.prototype.listeners=function(c){var u=t?t+c:c,d=this._events[u];if(!d)return[];if(d.fn)return[d.fn];for(var h=0,f=d.length,b=new Array(f);h<f;h++)b[h]=d[h].fn;return b},o.prototype.listenerCount=function(c){var u=t?t+c:c,d=this._events[u];return d?d.fn?1:d.length:0},o.prototype.emit=function(c,u,d,h,f,b){var T=t?t+c:c;if(!this._events[T])return!1;var v=this._events[T],C=arguments.length,k,g;if(v.fn){switch(v.once&&this.removeListener(c,v.fn,void 0,!0),C){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,d),!0;case 4:return v.fn.call(v.context,u,d,h),!0;case 5:return v.fn.call(v.context,u,d,h,f),!0;case 6:return v.fn.call(v.context,u,d,h,f,b),!0}for(g=1,k=new Array(C-1);g<C;g++)k[g-1]=arguments[g];v.fn.apply(v.context,k)}else{var z=v.length,N;for(g=0;g<z;g++)switch(v[g].once&&this.removeListener(c,v[g].fn,void 0,!0),C){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,d);break;case 4:v[g].fn.call(v[g].context,u,d,h);break;default:if(!k)for(N=1,k=new Array(C-1);N<C;N++)k[N-1]=arguments[N];v[g].fn.apply(v[g].context,k)}}return!0},o.prototype.on=function(c,u,d){return s(this,c,u,d,!1)},o.prototype.once=function(c,u,d){return s(this,c,u,d,!0)},o.prototype.removeListener=function(c,u,d,h){var f=t?t+c:c;if(!this._events[f])return this;if(!u)return a(this,f),this;var b=this._events[f];if(b.fn)b.fn===u&&(!h||b.once)&&(!d||b.context===d)&&a(this,f);else{for(var T=0,v=[],C=b.length;T<C;T++)(b[T].fn!==u||h&&!b[T].once||d&&b[T].context!==d)&&v.push(b[T]);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}(Ye)),Ye.exports}var Bc=Gc();const Qe=pe(Bc);var is=(r=>(r.LeftToRight="LeftToRight",r.UpToDown="UpToDown",r.All="All",r.None="None",r))(is||{}),Z=(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))(Z||{}),ze=(r=>(r.DeviceCaptured="deviceCaptured",r.DeviceStopCapture="deviceStopCapture",r.Error="error",r.Interrupted="interrupted",r))(ze||{}),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||{}),ss=(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))(ss||{}),os=(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))(os||{}),as=(r=>(r.STANDARD="48000x40",r.HIGH="48000x128",r))(as||{}),ht=(r=>(r.VideoStreamChange="videoStreamChange",r.AudioStreamChange="audioStreamChange",r))(ht||{}),cs=(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))(cs||{});const us={SizeChange:"sizeChange"};var Rn=(r=>(r.Portrait="portrait",r.Landscape="landscape",r))(Rn||{});const ls="720p-1",hs="STANDARD";var Ee=(r=>(r[r.DISCONNECTED=0]="DISCONNECTED",r[r.CONNECTING=1]="CONNECTING",r[r.CONNECTED=2]="CONNECTED",r[r.RECONNECTING=3]="RECONNECTING",r))(Ee||{}),kt=(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))(kt||{}),An=(r=>(r[r.PushUrlInvalid=1001]="PushUrlInvalid",r[r.ReconnectTimeout=1002]="ReconnectTimeout",r))(An||{}),$=(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))($||{}),ee=(r=>(r.AUDIO="audio",r.VIDEO="video",r))(ee||{}),fe=(r=>(r.ENDED="ended",r.MUTE="mute",r.UNMUTE="unmute",r.PLAY_FAILED="play-failed",r.SIZE_CHANGE="size-change",r))(fe||{});const le=[];for(let r=0;r<256;++r)le.push((r+256).toString(16).slice(1));function Fc(r,e=0){return(le[r[e+0]]+le[r[e+1]]+le[r[e+2]]+le[r[e+3]]+"-"+le[r[e+4]]+le[r[e+5]]+"-"+le[r[e+6]]+le[r[e+7]]+"-"+le[r[e+8]]+le[r[e+9]]+"-"+le[r[e+10]]+le[r[e+11]]+le[r[e+12]]+le[r[e+13]]+le[r[e+14]]+le[r[e+15]]).toLowerCase()}let Dn;const Vc=new Uint8Array(16);function jc(){if(!Dn){if(typeof crypto>"u"||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");Dn=crypto.getRandomValues.bind(crypto)}return Dn(Vc)}const ds={randomUUID:typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};function dt(r,e,t){var i;if(ds.randomUUID&&!r)return ds.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,Fc(n)}class ps{constructor(){M(this,"id",dt());M(this,"_nextNode");M(this,"_track");M(this,"_destNode")}gain(e){if(this._nextNode instanceof fs)return this._nextNode.g=e,this._nextNode;const t=new fs(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 fs extends ps{constructor(t,n){super();M(this,"previousNode");M(this,"_node");M(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 Hc extends ps{constructor(t){super();M(this,"previousNode",null);M(this,"source");this.source=t}available(){return this.source.available()}destroy(){super.destroy()}}class qc extends Hc{constructor(){super(...arguments);M(this,"_node")}createNode(t){if(this._node)return this._node;let n;if(this.source instanceof Cs){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 q extends Error{constructor(t,n,i){super(n);M(this,"code");M(this,"message");M(this,"error");this.code=t,this.message=n,this.error=i,Object.setPrototypeOf(this,q.prototype)}toString(){return`VeCapture Error: ${this.code} ${this.message}`}}const ms={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"}},_s="__debug__",$c="[VE-CAPTURE]";function Kc(){if(typeof location>"u"||typeof localStorage>"u")return!1;let r=!1;return location.href.includes(_s)&&(r=!0),localStorage.getItem(_s)&&(r=!0),r}let ge=class{constructor(e){M(this,"moduleName");this.moduleName=e}print(e,t,...n){const i=Wc();Kc()&&console.log(`${i}-${$c}%c[${ms[e].text}]%c[${this.moduleName}][${t}]`,`background-color:${ms[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 Wc(){const r=new Date;return`${r.toTimeString().split(" ")[0]}:${r.getMilliseconds().toString().padStart(3,"0")}`}function xn(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 gs({width:r,height:e}){const t=document.createElement("canvas"),n=t.getContext("2d");if(!n)throw new q($.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 In{constructor(e){M(this,"target");M(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 zn(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 vs=zn()==="firefox",Ur=zn()==="safari";zn(),!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 Jc=!oe()&&!!/(iphone|ipad|ipod)/i.exec(ie());!oe()&&/android/i.test(ie()),!oe()&&/windows/i.test(ie()),!oe()&&/openharmony/i.test(ie());let ys="0";const Xc=!oe()&&((zc=ie().match(/version\/(\d+)/i))==null?void 0:zc[1]);Ur&&Xc&&(ys=(Oc=navigator.userAgent.match(/version\/(\d+\.\d+)/i))==null?void 0:Oc[1]),!oe()&&((Mc=ie().match(/firefox\/(\d+)/i))==null||Mc[1]);const On=ys;!oe()&&((Lc=(Pc=ie().match(/ ([\d_]+) like mac os x/i))==null?void 0:Pc[1])==null||Lc.split("_").map(r=>parseInt(r))),!oe()&&((Nc=ie().match(/chrome\/(\d+)/i))==null||Nc[1]);function Zc(){var r;return!!((r=navigator==null?void 0:navigator.permissions)!=null&&r.query)}function Mn(){return!!(navigator!=null&&navigator.mediaDevices)}function Yc(){var r;return Mn()&&!!((r=navigator==null?void 0:navigator.mediaDevices)!=null&&r.getUserMedia)}function Qc(){return!!Promise.withResolvers}function eu(){return!(Ur&&On==="16.1")}function tu(){return!(Ur&&On&&["16.1","16.2","16.3"].includes(On))}function ru(){return!vs}function nu(){return typeof CanvasCaptureMediaStreamTrack<"u"}function iu(r){return typeof r.requestFrame=="function"}function su(){return!!Mn()&&typeof navigator.mediaDevices.ondevicechange<"u"&&typeof navigator.mediaDevices.addEventListener=="function"}const Fe={permissionQuery:Zc,mediaDevices:Mn,settingResolutionInGetDisplayMedia:eu,promiseWithResolvers:Qc,getUserMedia:Yc,isolateEnumerateDevices:ru,supportIdealParamsInGetDisplayMedia:tu,canvasCaptureMediaStreamTrack:nu,requestFrameOnMediaStream:iu,ondevicechange:su};function ou(){if(Fe.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 Ss(r={}){const{timeout:e,message:t}={timeout:0,message:new q($.UNEXPECTED_ERROR,"unexpected timeout"),...r},{promise:n,resolve:i,reject:s}=ou();if(e<=0)return{promise:n,resolve:i,reject:s};const a=setTimeout(()=>{s(t)},e);return{promise:n,resolve:l=>{clearTimeout(a),i(l)},reject:s}}const au={playsinline:"","webkit-playsinline":"","x5-playsinline":"","x5-video-player-type":"h5","x-webkit-airplay":"allow",preload:"metadata",muted:"",crossOrigin:"anonymous"},cu={playsinline:"","webkit-playsinline":"",preload:"metadata",muted:"",crossOrigin:"anonymous"};class qt{constructor(e,t=[]){M(this,"id",dt());M(this,"_referenceTracks",[]);M(this,"_element");M(this,"_volumeMode",0);M(this,"_readyLock");M(this,"_releaseReadyLock");M(this,"_throwReadyLock");M(this,"_stream");let n;if(e instanceof MediaStreamTrack){const o=new MediaStream([e]);n=uu(o),this._stream=o}else if(e.url)n=lu(e);else throw new q($.UNEXPECTED_TYPE,`got ${typeof e}, expected: MediaStreamTrack or constraints for creating element`);const{promise:i,resolve:s,reject:a}=Ss({timeout:2e3,message:new q($.PLAY_FAILED,"load media timeout")});this._readyLock=i,this._releaseReadyLock=s,this._throwReadyLock=a,this._element=new In(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===ee.AUDIO){this._upgradeVolumeMode(1e-4);const n=t.getAudioTracks();if(n.length<1)throw new q($.UNEXPECTED_TYPE,"got empty list of audio tracks");return n[0]}if(e===ee.VIDEO){const n=t.getVideoTracks();if(n.length<1)throw new q($.UNEXPECTED_TYPE,"got empty list of video tracks");return n[0]}throw new q($.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 q($.PLAY_FAILED,"play element failed",e)}}_bindPlayerEvent(e){e.on("loadedmetadata",()=>{this._releaseReadyLock()}),e.on("error",()=>{this._throwReadyLock(new q($.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 uu(r){let e="audio";r.getVideoTracks().length>0&&(e="video");const t=bs(e==="video"?ee.VIDEO:ee.AUDIO);return t.srcObject=r,t}function lu(r){const{url:e,kind:t,loop:n}=r,i=bs(t);return i.src=e,i.loop=n,i}function bs(r){if(r===ee.VIDEO)return xn(ee.VIDEO,{style:{width:"100%",height:"100%"},attributes:au});if(r===ee.AUDIO)return xn(ee.AUDIO,{style:{display:"none"},attributes:cu});throw new q($.UNEXPECTED_TYPE,`got ${r}, expected: audio, video`)}class Pn extends Qe{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 Ln(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 q($.UNEXPECTED_TYPE,"unexpected constraints type")}const Nn=1e3;class Es{constructor(e){M(this,"id",dt());M(this,"_context");M(this,"_canvas");M(this,"_image");M(this,"_config");M(this,"_readyLock");M(this,"_releaseReadyLock");M(this,"_throwReadyLock");M(this,"_loopTimer");M(this,"_referenceTracks",[]);M(this,"_stream");const t=Ln(e.width),n=Ln(e.height),i=Ln(e.frameRate);this._config={width:t,height:n,frameRate:i};const{context:s,canvas:a}=gs({width:t,height:n});this._context=s,this._canvas=a;const o=hu({url:e.url,width:t,height:n});this._image=new In(o);const{promise:l,resolve:c,reject:u}=Ss({timeout:2e3,message:new q($.PLAY_FAILED,"load image timeout")});this._readyLock=l,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 q($.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 q($.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),Nn/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 hu({url:r,height:e,width:t}){const n=xn("img",{style:{width:`${t}px`,height:`${e}px`},attributes:{crossOrigin:"anonymous"}});return n.src=r,n}class Un extends Pn{constructor(t){super();M(this,"id",dt());M(this,"_track");M(this,"_element");t instanceof MediaStreamTrack?(this._track=new In(t),this._bindTrackEvent(this._track)):t instanceof qt?(this._element=t,t.addReferenceTrack(this)):t instanceof Es&&(this._element=t)}_bindTrackEvent(t){t.on("ended",this._handleTrackEnded.bind(this)),t.on("mute",()=>{this.emit(fe.MUTE)}),t.on("unmute",()=>{this.emit(fe.UNMUTE)})}_handleTrackEnded(){this.emit(fe.ENDED),this.destroy()}handlePlayFailed(){this.emit(fe.PLAY_FAILED)}track(){if(this.logger.info("track"),!this.available())throw new q($.TRACK_NOT_AVAILABLE,"track is not available when creating MediaStreamTrack");if(this._track)return this._track.target;if(!this._element)throw new q($.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 q($.TRACK_NOT_AVAILABLE,"track is not available when creating HTMLMediaElement");if(this._element)return this._element.element();if(!this._track)throw new q($.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 Gr extends Un{constructor(){super(...arguments);M(this,"kind",ee.AUDIO);M(this,"_node")}node(){if(this.logger.info("node",this.id),!this.available())throw new q($.TRACK_NOT_AVAILABLE,"track is not avaiable when creating node");if(this._node)return this._node;const t=new qc(this);return this._node=t,t}element(){if(this.logger.info("element",this.id),!this.available())throw new q($.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 q($.UNEXPECTED_TYPE,"source should be HTMLMediaElement");return n}if(!this._track)throw new q($.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 du extends Gr{constructor(){super(...arguments);M(this,"logger",new ge("MicrophoneAudioTrack"))}}class pu extends Gr{constructor(){super(...arguments);M(this,"logger",new ge("ScreenAudioTrack"))}}class Cs extends Gr{constructor(){super(...arguments);M(this,"logger",new ge("MediaAudioTrack"))}handlePlayFailed(){this.emit(fe.PLAY_FAILED)}async play(){if(this._element){if(!(this._element instanceof qt))throw new q($.UNEXPECTED_TYPE,"element is not TrackMediaElement");return this._element._playElement()}}}class fu extends Gr{constructor(){super(...arguments);M(this,"logger",new ge("CustomAudioTrack"))}}let mu=1;const Gn=new ge("PromiseQueue");class _u{constructor(e){M(this,"lockingPromise",Promise.resolve());M(this,"locks",0);M(this,"name","");M(this,"lockId");M(this,"closeReason");this.lockId=mu++,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 gu=300,vu=3e3,Oe=new ge("Devices");class yu extends Pn{constructor(){super();M(this,"_deviceMap",{audioinput:[],audiooutput:[],videoinput:[]});M(this,"_permissions",{[ee.AUDIO]:!1,[ee.VIDEO]:!1});M(this,"_changedQueue",new _u("device changed queue"));this._init()}async _init(){this._initDeviceChanged(),await this._initPermissionChanged();const t=Rs(this._permissions);t.length>0&&this._refreshDevices(t)}_initDeviceChanged(){if(Oe.info("_initDeviceChanged","invoked"),!Fe.ondevicechange()){Oe.error("_initDeviceChanged","no supported, use timer instead"),setInterval(()=>{this._handleDeviceChanged()},vu);return}Fe.ondevicechange()&&navigator.mediaDevices.addEventListener("devicechange",()=>{Oe.info("devicechange"),setTimeout(()=>{this._handleDeviceChanged()},gu)})}async _initPermissionChanged(){if(!Fe.permissionQuery()){Oe.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",()=>{Oe.info("_initPermissionChanged","update permission for audio"),this._permissions.audio=t.state==="granted"})}catch(t){Oe.error("_initPermissionChanged",t)}try{const t=await navigator.permissions.query({name:"camera"});this._permissions.video=t.state==="granted",t.addEventListener("change",()=>{Oe.info("_initPermissionChanged","update permission for video"),this._permissions.video=t.state==="granted"})}catch(t){Oe.error("_initPermissionChanged",t)}}async _refreshDevices(t){if(!Fe.mediaDevices())throw new q($.NOT_SUPPORTED,"mediaDevices is not supported");if(t.length===0)throw new q($.UNEXPECTED_TYPE,"kinds expect to containt values");let n;if(!Fe.isolateEnumerateDevices()){const a={};t.forEach(o=>{a[o]=!0}),n=await navigator.mediaDevices.getUserMedia(a)}let i=await navigator.mediaDevices.enumerateDevices();n&&ws(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(!Fe.getUserMedia())return{grant:!1,reason:new q($.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[ee.AUDIO]=!0),i.video&&(this._permissions[ee.VIDEO]=!0),ws(s),{grant:!0}):{grant:!1,reason:new q($.UNEXPECTED_TYPE,"get stream falsy")}}catch(i){return{grant:!1,reason:new q($.CAPTURE_FAILED,"acquire user permission failed",i)}}}async _handleDeviceChanged(){Oe.info("_handleDeviceChanged",this._deviceMap,this._permissions);const t=await this._changedQueue.lock();try{const n=ks(this._deviceMap);let i=[];const s=Rs(this._permissions);s.length===0?Oe.warn("_handleDeviceChanged","no permission, use empty list"):(await this._refreshDevices(s),i=ks(this._deviceMap)),i.forEach(a=>{n.findIndex(l=>Ts(l,a))!==-1||this.emit("onDeviceStateChanged",{deviceInfo:a,deviceState:"active"})}),n.forEach(a=>{i.findIndex(l=>Ts(l,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(ee.AUDIO);else if(o==="videoinput")n.push(ee.VIDEO);else throw new q($.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 ws(r){r.getTracks().forEach(e=>e.stop())}function Ts(r,e){return r.deviceId===e.deviceId}function ks(r){return Array.from([...r.audioinput.values(),...r.videoinput.values(),...r.audiooutput.values()])}function Rs(r){const e=[];return r.audio&&e.push(ee.AUDIO),r.video&&e.push(ee.VIDEO),e}const Bn=new yu,Fn={LeftToRight:"LeftToRight",UpToDown:"UpToDown",All:"All"};class Vn{constructor(){M(this,"id",dt())}position(e,t){return new Su(this,{x:e,y:t})}scale(e){return new As(this,{s:e})}mirror(e){return new As(this,{mirrorType:e})}available(){var e;return((e=this.previousNode)==null?void 0:e.available())??!1}}class Su extends Vn{constructor(t,n){super();M(this,"previousNode");M(this,"_x");M(this,"_y");this.previousNode=t,this._x=n.x,this._y=n.y}paint(t){t.translate(this._x,this._y)}}class As extends Vn{constructor(t,n){super();M(this,"previousNode");M(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 bu extends Vn{constructor(t){super();M(this,"previousNode",null);M(this,"_source");this._source=t}available(){return this._source.available()}}class Br extends bu{constructor(t,n){super(t);M(this,"_targetWidth");M(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 Br(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 Eu extends Un{constructor(){super(...arguments);M(this,"logger",new ge("PictureTrack"));M(this,"kind",ee.VIDEO)}element(){const t=super.element();if(!(t instanceof HTMLImageElement))throw new q($.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 q($.TRACK_NOT_AVAILABLE,"track is not avaiable when creating node");const t=new Br(this);return this.logger.info("node",t),t}destroy(){this.logger.warn("destroy"),super.destroy()}}const Cu=500;class Fr extends Un{constructor(){super(...arguments);M(this,"kind",ee.VIDEO);M(this,"sizeChangeTimer");M(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(fe.SIZE_CHANGE,{width:i,height:s})},Cu)})}element(){const t=super.element();if(!(t instanceof HTMLVideoElement))throw new q($.UNEXPECTED_TYPE,"source should be HTMLVideoElement");return t}node(){if(!this.available())throw new q($.TRACK_NOT_AVAILABLE,"track is not avaiable when creating node");return new Br(this)}destroy(){clearTimeout(this.sizeChangeTimer),super.destroy()}}class wu extends Fr{constructor(t){super(t);M(this,"logger",new ge("CameraVideoTrack"));this.watchSizeChangeOnce()}height(){const{height:t}=this.track().getSettings();return t??0}width(){const{width:t}=this.track().getSettings();return t??0}}class Tu extends Fr{constructor(t){super(t);M(this,"logger",new ge("ScreenVideoTrack"));this.watchSizeChangeOnce()}height(){const{height:t}=this.track().getSettings();return t??0}width(){const{width:t}=this.track().getSettings();return t??0}}class ku extends Fr{constructor(){super(...arguments);M(this,"logger",new ge("MediaVideoTrack"))}height(){const{videoHeight:t}=this.element();return t??0}width(){const{videoWidth:t}=this.element();return t??0}}class Ru extends Fr{constructor(){super(...arguments);M(this,"logger",new ge("CustomVideoTrack"))}height(){const{height:t}=this.track().getSettings();return t??0}width(){const{width:t}=this.track().getSettings();return t??0}}async function Ds(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 Ve=new ge("Capture");async function Au(r){return Bn.enumerateDevices(r)}async function Du(r){Bn.removeAllListeners("onDeviceStateChanged"),Bn.on("onDeviceStateChanged",r)}async function xu(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 q($.CAPTURE_FAILED,"got error when capturing camera",i)}const n=t.getVideoTracks()[0];if(r!=null&&r.frameRate&&e&&Ds(n,r),!n)throw new q($.UNEXPECTED_TYPE,"got falsy in track");return new wu(n)}async function Iu(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),Fe.settingResolutionInGetDisplayMedia()||(s=!0),!Fe.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 q($.CAPTURE_FAILED,"got error when capture screen",u)}const o=a.getVideoTracks()[0],l=a.getAudioTracks()[0];if(!o)throw new q($.UNEXPECTED_TYPE,"got falsy in videoTrack");typeof s!="boolean"&&typeof s.frameRate=="number"&&t&&Ds(o,s);const c=[];return c.push(new Tu(o)),l&&c.push(new pu(l)),c}async function zu(r){const{url:e,audio:t,video:n,loop:i}=r,s=new qt({url:e,kind:n?ee.VIDEO:ee.AUDIO,loop:i}),a=[];return t&&a.push(new Cs(s)),n&&a.push(new ku(s)),await s.isReady(),a}async function Ou(r){const e=new Es(r);return await e.isReady(),new Eu(e)}async function Mu(r){let e;try{const n={audio:r??!0};e=await navigator.mediaDevices.getUserMedia(n)}catch(n){throw new q($.CAPTURE_FAILED,"got error when capturing microphone",n)}const t=e.getAudioTracks()[0];if(!t)throw new q($.UNEXPECTED_TYPE,"got falsy in track");return new du(t)}function Pu(r){if(!r||r.kind!=="video")throw new q($.UNEXPECTED_TYPE,"error custom video track type");return new Ru(r)}function Lu(r){if(!r||r.kind!=="audio")throw new q($.UNEXPECTED_TYPE,"error custom audio track type");return new fu(r)}const Nu=Ve.invoke(Au,"enumerateInputDevices"),Uu=Ve.invoke(xu,"createCameraTrack"),Gu=Ve.invoke(Ou,"createPictureTrack"),xs=Ve.invoke(zu,"createMediaTracks"),Bu=Ve.invoke(Mu,"createMicrophoneTrack"),Fu=Ve.invoke(Iu,"createScreenTracks"),Vu=Ve.invoke(Du,"onDeviceChanged"),ju=Ve.invoke(Pu,"createCustomVideoTrack"),Hu=Ve.invoke(Lu,"createCustomAudioTrack");var jn=(r=>(r.PAUSING="pausing",r))(jn||{});const qu={sampleRate:48e3,keepAlive:!0},Is=new Map,$t=new ge("Mixer");class $u extends Pn{constructor(t){super();M(this,"id",dt());M(this,"_context");M(this,"_config");M(this,"_nodeList",[]);M(this,"_destNode");M(this,"_bufferNode");M(this,"_track");M(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=()=>{Kt(this._context).then(i)};n.forEach(a=>{t.addEventListener(a,s,!1)})});$t.info("ctor",t),this._config={...qu,...t},this._context=Ku(this._config),this._bindContextEvent(this._context)}mix(t){$t.info("mix",t),Kt(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 $t.info("resume"),Kt(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")&&($t.info("_emit_",jn.PAUSING),this.emit(jn.PAUSING))}track(){if($t.info("track"),Kt(this._context),this.unlockAudioContext(),this._track)return this._track;let t=this._destNode;t||(t=new MediaStreamAudioDestinationNode(this._context)),this._nodeList.length===0&&this._appendSlience(this._context,t),this._connect(this._nodeList,t);const n=t.stream.getAudioTracks()[0];return this._destNode=t,this._track=n,n}}function Ku(r){const{sampleRate:e,keepAlive:t}=r;let n=Is.get(e);return(!n||n.state==="closed")&&(n=new AudioContext({sampleRate:e}),Is.set(e,n)),t&&(n.onstatechange=()=>{Kt(n)}),n}function Kt(r){return r.state==="suspended"||r.state==="interrupted"?r.resume():Promise.resolve()}const Wu=r=>(e,t)=>(r.set(e,t),t),zs=Number.MAX_SAFE_INTEGER===void 0?9007199254740991:Number.MAX_SAFE_INTEGER,Os=536870912,Ms=Os*2,Ju=(r,e)=>t=>{const n=e.get(t);let i=n===void 0?t.size:n<Ms?n+1:0;if(!t.has(i))return r(t,i);if(t.size<Os){for(;t.has(i);)i=Math.floor(Math.random()*Ms);return r(t,i)}if(t.size>zs)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()*zs);return r(t,i)},Ps=new WeakMap,Xu=Wu(Ps),et=Ju(Xu,Ps),Zu=r=>r.method!==void 0&&r.method==="call",Yu=r=>typeof r.id=="number"&&typeof r.result=="boolean",Ls=((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(Zu(c)){const{params:{timerId:u,timerType:d}}=c;if(d==="interval"){const h=e.get(u);if(typeof h===void 0)throw new Error("The timer is in an undefined state.");if(typeof h=="number"){const f=n.get(h);if(f===void 0||f.timerId!==u||f.timerType!==d)throw new Error("The timer is in an undefined state.")}else typeof h=="function"&&h()}else if(d==="timeout"){const h=t.get(u);if(typeof h===void 0)throw new Error("The timer is in an undefined state.");if(typeof h=="number"){const f=n.get(h);if(f===void 0||f.timerId!==u||f.timerType!==d)throw new Error("The timer is in an undefined state.")}else typeof h=="function"&&(h(),t.delete(u))}}else if(Yu(c)){const{id:u}=c,d=n.get(u);if(d===void 0)throw new Error("The timer is in an undefined state.");const{timerId:h,timerType:f}=d;n.delete(u),f==="interval"?e.delete(h):t.delete(h)}else{const{error:{message:u}}=c;throw new Error(u)}}),{clearInterval:c=>{if(typeof e.get(c)=="function"){const u=et(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=et(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,...d)=>{const h=et(e);return e.set(h,()=>{c(...d),typeof e.get(h)=="function"&&i.postMessage({id:null,method:"set",params:{delay:u,now:performance.timeOrigin+performance.now(),timerId:h,timerType:"interval"}})}),i.postMessage({id:null,method:"set",params:{delay:u,now:performance.timeOrigin+performance.now(),timerId:h,timerType:"interval"}}),h},setTimeout:(c,u=0,...d)=>{const h=et(t);return t.set(h,()=>c(...d)),i.postMessage({id:null,method:"set",params:{delay:u,now:performance.timeOrigin+performance.now(),timerId:h,timerType:"timeout"}}),h}}},`(()=>{"use strict";const e=new Map,t=new Map,r=t=>{const r=e.get(t);return void 0!==r&&(clearTimeout(r),e.delete(t),!0)},s=e=>{const r=t.get(e);return void 0!==r&&(clearTimeout(r),t.delete(e),!0)},o=(e,t)=>{const r=performance.now(),s=e+t-r-performance.timeOrigin;return{expected:r+s,remainingDelay:s}},i=(e,t,r,s)=>{const o=r-performance.now();o>0?e.set(t,setTimeout(i,o,e,t,r,s)):(e.delete(t),postMessage({id:null,method:"call",params:{timerId:t,timerType:s}}))};addEventListener("message",(({data:n})=>{try{if("clear"===n.method){const{id:e,params:{timerId:t,timerType:o}}=n;if("interval"===o)postMessage({id:e,result:r(t)});else{if("timeout"!==o)throw new Error('The given type "'.concat(o,'" is not supported'));postMessage({id:e,result:s(t)})}}else{if("set"!==n.method)throw new Error('The given method "'.concat(n.method,'" is not supported'));{const{params:{delay:r,now:s,timerId:a,timerType:m}}=n;if("interval"===m)((t,r,s)=>{const{expected:n,remainingDelay:a}=o(t,s);e.set(r,setTimeout(i,a,e,r,n,"interval"))})(r,a,s);else{if("timeout"!==m)throw new Error('The given type "'.concat(m,'" is not supported'));((e,r,s)=>{const{expected:n,remainingDelay:a}=o(e,s);t.set(r,setTimeout(i,a,t,r,n,"timeout"))})(r,a,s)}}}}catch(e){postMessage({error:{message:e.message},id:n.id,result:null})}}))})();`),Qu=r=>Ls().clearTimeout(r),el=(...r)=>Ls().setTimeout(...r),tl=r=>r.method!==void 0&&r.method==="call",rl=r=>typeof r.id=="number"&&typeof r.result=="boolean",nl=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(tl(c)){const{params:{timerId:u,timerType:d}}=c;if(d==="interval"){const h=e.get(u);if(typeof h===void 0)throw new Error("The timer is in an undefined state.");if(typeof h=="number"){const f=n.get(h);if(f===void 0||f.timerId!==u||f.timerType!==d)throw new Error("The timer is in an undefined state.")}else typeof h=="function"&&h()}else if(d==="timeout"){const h=t.get(u);if(typeof h===void 0)throw new Error("The timer is in an undefined state.");if(typeof h=="number"){const f=n.get(h);if(f===void 0||f.timerId!==u||f.timerType!==d)throw new Error("The timer is in an undefined state.")}else typeof h=="function"&&(h(),t.delete(u))}}else if(rl(c)){const{id:u}=c,d=n.get(u);if(d===void 0)throw new Error("The timer is in an undefined state.");const{timerId:h,timerType:f}=d;n.delete(u),f==="interval"?e.delete(h):t.delete(h)}else{const{error:{message:u}}=c;throw new Error(u)}}),{clearInterval:c=>{if(typeof e.get(c)=="function"){const u=et(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=et(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,...d)=>{const h=et(e);return e.set(h,()=>{c(...d),typeof e.get(h)=="function"&&i.postMessage({id:null,method:"set",params:{delay:u,now:performance.timeOrigin+performance.now(),timerId:h,timerType:"interval"}})}),i.postMessage({id:null,method:"set",params:{delay:u,now:performance.timeOrigin+performance.now(),timerId:h,timerType:"interval"}}),h},setTimeout:(c,u=0,...d)=>{const h=et(t);return t.set(h,()=>c(...d)),i.postMessage({id:null,method:"set",params:{delay:u,now:performance.timeOrigin+performance.now(),timerId:h,timerType:"timeout"}}),h}}},il={width:640,height:480,frameRate:30,backgroundColor:"#000000"},Vr=new ge("View");class sl{constructor(e){M(this,"id",dt());M(this,"_context");M(this,"_canvas");M(this,"_config");M(this,"_nodeList",[]);M(this,"_track");M(this,"_stopped",!0);M(this,"_nextTime",Date.now());M(this,"_workerTimeoutId");M(this,"_raqId");M(this,"_workerTimerScriptUrl");M(this,"_customSetTimeout");M(this,"_customClearTimeout");M(this,"_loopTimer");M(this,"_paintLoop",()=>{if(this._stopped){this._workerTimeoutId&&(this._customClearTimeout(this._workerTimeoutId),this._workerTimeoutId=void 0);return}this._drawOnCanvas(),this._workerTimeoutId&&this._customClearTimeout(this._workerTimeoutId),this._workerTimeoutId=this._customSetTimeout(()=>{this._paintLoop(),this._raqId&&(cancelAnimationFrame(this._raqId),this._raqId=void 0)},Nn/this._config.frameRate),this._raqId=requestAnimationFrame(this._paintLoop)});Vr.info("ctor",e),this._config={...il,...e};const{context:t,canvas:n}=gs(this._config);this._context=t,this._canvas=n,this._customSetTimeout=el,this._customClearTimeout=Qu}setWorkerTimerScriptUrl(e){if(this._workerTimerScriptUrl=e,this._workerTimerScriptUrl){const t=nl(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+=Nn/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=[]){Vr.info("draw",e),this._nodeList=e}_drawOnCanvas(){if(this._shouldDraw(Date.now())){this._drawBackground();for(const e of this._nodeList){let t=e;if(t.available()){for(;t;)t.paint(this._context),t=t.previousNode;this._context.setTransform(1,0,0,1,0,0)}}}}_drawBackground(){const{backgroundColor:e,width:t,height:n}=this._config;this._context.clearRect(0,0,t,n),e&&(this._context.fillStyle=e,this._context.fillRect(0,0,t,n))}track(){if(Vr.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 Vr.info("element"),this._paintLoop(),this._canvas}stop(){this._stopped=!0}}function ol(){return Math.random().toString(36).slice(-8)}const al=`
|
|
2
2
|
const SMOOTHING_FACTOR = 0.8;
|
|
3
3
|
const MINIMUM_VALUE = 0.00001;
|
|
4
4
|
|
|
@@ -53,41 +53,51 @@ registerProcessor('vumeter', class extends AudioWorkletProcessor {
|
|
|
53
53
|
return true;
|
|
54
54
|
}
|
|
55
55
|
});
|
|
56
|
-
`,Oo=URL.createObjectURL(new Blob([wo],{type:"application/javascript"}));class Io{constructor(){this._audioCtx=null,this._volume=0}get volume(){return this._volume}async start(e,t){if(this._audioCtx)return;const i=new AudioContext;await i.audioWorklet.addModule(t||Oo);const s=new MediaStream;s.addTrack(e);const n=i.createMediaStreamSource(s),a=new AudioWorkletNode(i,"vumeter");a.port.onmessage=o=>{const u=o.data.volume||0;this._volume=Math.min(u*100/2,10)},n.connect(a).connect(i.destination),this._audioCtx=i}stop(){var e;(e=this._audioCtx)==null||e.close(),this._audioCtx=null}}class je{constructor(){this._volumeDetectScriptUrl=void 0}static get instance(){return this._instance||(this._instance=new je),this._instance}get volumeDetectScriptUrl(){return this._volumeDetectScriptUrl}set volumeDetectScriptUrl(e){this._volumeDetectScriptUrl=e}}class Fr extends te{constructor(e){super(),this._width=0,this._height=0,this._mediaStream=null,this._nextStream=null,this._trackMap={},this.type=e.type,this.id=Ao(),this._source=e.stream}get source(){return this._source}get videoTrack(){return this._trackMap.video}get audioTrack(){return this._trackMap.audio}get width(){return this._width}get height(){return this._height}get isVideoStream(){return[S.Camera,S.Screen,S.VideoFile].includes(this.type)}get mediaStream(){if(this._mediaStream)return this._mediaStream;const e=new MediaStream;return this._trackMap.audio&&e.addTrack(this._trackMap.audio),this._trackMap.video&&e.addTrack(this._trackMap.video),this._mediaStream=e,e}async startVolumeDetect(){this.audioTrack&&(this._volumeDetector||(this._volumeDetector=new Io),await this._volumeDetector.start(this.audioTrack,je.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 _e extends Fr{get isVideoStream(){return!0}get isAudioStream(){return!1}bindTrackSizeChangeEvent(e){e.on(D.SIZE_CHANGE,({width:t,height:i})=>{this._width=t,this._height=i,this.emit(dr.SizeChange,{width:t,height:i})})}}class ze extends Fr{get isVideoStream(){return!1}get isAudioStream(){return!0}}class Do extends _e{constructor(e){super({type:S.Camera,stream:e}),this._trackMap.video=e.track(),this._width=e.width(),this._height=e.height(),this.bindTrackSizeChangeEvent(e)}get source(){return this._source}get viewNode(){return this.source.node()}get mixerNode(){return null}bindTrackEnd(e){this.source.on(D.ENDED,e)}destroy(){this.source.destroy()}}var Vr=typeof global=="object"&&global&&global.Object===Object&&global,Mo=typeof self=="object"&&self&&self.Object===Object&&self,K=Vr||Mo||Function("return this")(),ie=K.Symbol,Ur=Object.prototype,Lo=Ur.hasOwnProperty,No=Ur.toString,Re=ie?ie.toStringTag:void 0;function Fo(r){var e=Lo.call(r,Re),t=r[Re];try{r[Re]=void 0;var i=!0}catch{}var s=No.call(r);return i&&(e?r[Re]=t:delete r[Re]),s}var Vo=Object.prototype,Uo=Vo.toString;function $o(r){return Uo.call(r)}var Bo="[object Null]",jo="[object Undefined]",$r=ie?ie.toStringTag:void 0;function ge(r){return r==null?r===void 0?jo:Bo:$r&&$r in Object(r)?Fo(r):$o(r)}function ve(r){return r!=null&&typeof r=="object"}var zo="[object Symbol]";function Ge(r){return typeof r=="symbol"||ve(r)&&ge(r)==zo}function Br(r,e){for(var t=-1,i=r==null?0:r.length,s=Array(i);++t<i;)s[t]=e(r[t],t,r);return s}var N=Array.isArray,jr=ie?ie.prototype:void 0,zr=jr?jr.toString:void 0;function Gr(r){if(typeof r=="string")return r;if(N(r))return Br(r,Gr)+"";if(Ge(r))return zr?zr.call(r):"";var e=r+"";return e=="0"&&1/r==-1/0?"-0":e}var Go=/\s/;function Ho(r){for(var e=r.length;e--&&Go.test(r.charAt(e)););return e}var qo=/^\s+/;function Wo(r){return r&&r.slice(0,Ho(r)+1).replace(qo,"")}function xe(r){var e=typeof r;return r!=null&&(e=="object"||e=="function")}var Hr=NaN,Xo=/^[-+]0x[0-9a-f]+$/i,Ko=/^0b[01]+$/i,Jo=/^0o[0-7]+$/i,Yo=parseInt;function Zo(r){if(typeof r=="number")return r;if(Ge(r))return Hr;if(xe(r)){var e=typeof r.valueOf=="function"?r.valueOf():r;r=xe(e)?e+"":e}if(typeof r!="string")return r===0?r:+r;r=Wo(r);var t=Ko.test(r);return t||Jo.test(r)?Yo(r.slice(2),t?2:8):Xo.test(r)?Hr:+r}var Qo=1/0,ea=17976931348623157e292;function ta(r){if(!r)return r===0?r:0;if(r=Zo(r),r===Qo||r===-1/0){var e=r<0?-1:1;return e*ea}return r===r?r:0}function ra(r){var e=ta(r),t=e%1;return e===e?t?e-t:e:0}function ia(r){return r}var sa="[object AsyncFunction]",na="[object Function]",oa="[object GeneratorFunction]",aa="[object Proxy]";function qr(r){if(!xe(r))return!1;var e=ge(r);return e==na||e==oa||e==sa||e==aa}var bt=K["__core-js_shared__"],Wr=function(){var r=/[^.]+$/.exec(bt&&bt.keys&&bt.keys.IE_PROTO||"");return r?"Symbol(src)_1."+r:""}();function ca(r){return!!Wr&&Wr in r}var da=Function.prototype,ua=da.toString;function he(r){if(r!=null){try{return ua.call(r)}catch{}try{return r+""}catch{}}return""}var ha=/[\\^$.*+?()[\]{}|]/g,pa=/^\[object .+?Constructor\]$/,la=Function.prototype,ma=Object.prototype,fa=la.toString,_a=ma.hasOwnProperty,ga=RegExp("^"+fa.call(_a).replace(ha,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function va(r){if(!xe(r)||ca(r))return!1;var e=qr(r)?ga:pa;return e.test(he(r))}function Ca(r,e){return r==null?void 0:r[e]}function Ce(r,e){var t=Ca(r,e);return va(t)?t:void 0}var kt=Ce(K,"WeakMap");function ya(r,e,t,i){for(var s=r.length,n=t+-1;++n<s;)if(e(r[n],n,r))return n;return-1}var Sa=9007199254740991,Ta=/^(?:0|[1-9]\d*)$/;function Xr(r,e){var t=typeof r;return e=e??Sa,!!e&&(t=="number"||t!="symbol"&&Ta.test(r))&&r>-1&&r%1==0&&r<e}function Kr(r,e){return r===e||r!==r&&e!==e}var Ea=9007199254740991;function Pt(r){return typeof r=="number"&&r>-1&&r%1==0&&r<=Ea}function Rt(r){return r!=null&&Pt(r.length)&&!qr(r)}var ba=Object.prototype;function ka(r){var e=r&&r.constructor,t=typeof e=="function"&&e.prototype||ba;return r===t}function Pa(r,e){for(var t=-1,i=Array(r);++t<r;)i[t]=e(t);return i}var Ra="[object Arguments]";function Jr(r){return ve(r)&&ge(r)==Ra}var Yr=Object.prototype,xa=Yr.hasOwnProperty,Aa=Yr.propertyIsEnumerable,Zr=Jr(function(){return arguments}())?Jr:function(r){return ve(r)&&xa.call(r,"callee")&&!Aa.call(r,"callee")};function wa(){return!1}var Qr=typeof exports=="object"&&exports&&!exports.nodeType&&exports,ei=Qr&&typeof module=="object"&&module&&!module.nodeType&&module,Oa=ei&&ei.exports===Qr,ti=Oa?K.Buffer:void 0,Ia=ti?ti.isBuffer:void 0,xt=Ia||wa,Da="[object Arguments]",Ma="[object Array]",La="[object Boolean]",Na="[object Date]",Fa="[object Error]",Va="[object Function]",Ua="[object Map]",$a="[object Number]",Ba="[object Object]",ja="[object RegExp]",za="[object Set]",Ga="[object String]",Ha="[object WeakMap]",qa="[object ArrayBuffer]",Wa="[object DataView]",Xa="[object Float32Array]",Ka="[object Float64Array]",Ja="[object Int8Array]",Ya="[object Int16Array]",Za="[object Int32Array]",Qa="[object Uint8Array]",ec="[object Uint8ClampedArray]",tc="[object Uint16Array]",rc="[object Uint32Array]",k={};k[Xa]=k[Ka]=k[Ja]=k[Ya]=k[Za]=k[Qa]=k[ec]=k[tc]=k[rc]=!0,k[Da]=k[Ma]=k[qa]=k[La]=k[Wa]=k[Na]=k[Fa]=k[Va]=k[Ua]=k[$a]=k[Ba]=k[ja]=k[za]=k[Ga]=k[Ha]=!1;function ic(r){return ve(r)&&Pt(r.length)&&!!k[ge(r)]}function sc(r){return function(e){return r(e)}}var ri=typeof exports=="object"&&exports&&!exports.nodeType&&exports,Ae=ri&&typeof module=="object"&&module&&!module.nodeType&&module,nc=Ae&&Ae.exports===ri,At=nc&&Vr.process,ii=function(){try{var r=Ae&&Ae.require&&Ae.require("util").types;return r||At&&At.binding&&At.binding("util")}catch{}}(),si=ii&&ii.isTypedArray,ni=si?sc(si):ic,oc=Object.prototype,ac=oc.hasOwnProperty;function cc(r,e){var t=N(r),i=!t&&Zr(r),s=!t&&!i&&xt(r),n=!t&&!i&&!s&&ni(r),a=t||i||s||n,o=a?Pa(r.length,String):[],u=o.length;for(var c in r)ac.call(r,c)&&!(a&&(c=="length"||s&&(c=="offset"||c=="parent")||n&&(c=="buffer"||c=="byteLength"||c=="byteOffset")||Xr(c,u)))&&o.push(c);return o}function dc(r,e){return function(t){return r(e(t))}}var uc=dc(Object.keys,Object),hc=Object.prototype,pc=hc.hasOwnProperty;function lc(r){if(!ka(r))return uc(r);var e=[];for(var t in Object(r))pc.call(r,t)&&t!="constructor"&&e.push(t);return e}function we(r){return Rt(r)?cc(r):lc(r)}var mc=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,fc=/^\w*$/;function wt(r,e){if(N(r))return!1;var t=typeof r;return t=="number"||t=="symbol"||t=="boolean"||r==null||Ge(r)?!0:fc.test(r)||!mc.test(r)||e!=null&&r in Object(e)}var Oe=Ce(Object,"create");function _c(){this.__data__=Oe?Oe(null):{},this.size=0}function gc(r){var e=this.has(r)&&delete this.__data__[r];return this.size-=e?1:0,e}var vc="__lodash_hash_undefined__",Cc=Object.prototype,yc=Cc.hasOwnProperty;function Sc(r){var e=this.__data__;if(Oe){var t=e[r];return t===vc?void 0:t}return yc.call(e,r)?e[r]:void 0}var Tc=Object.prototype,Ec=Tc.hasOwnProperty;function bc(r){var e=this.__data__;return Oe?e[r]!==void 0:Ec.call(e,r)}var kc="__lodash_hash_undefined__";function Pc(r,e){var t=this.__data__;return this.size+=this.has(r)?0:1,t[r]=Oe&&e===void 0?kc:e,this}function pe(r){var e=-1,t=r==null?0:r.length;for(this.clear();++e<t;){var i=r[e];this.set(i[0],i[1])}}pe.prototype.clear=_c,pe.prototype.delete=gc,pe.prototype.get=Sc,pe.prototype.has=bc,pe.prototype.set=Pc;function Rc(){this.__data__=[],this.size=0}function He(r,e){for(var t=r.length;t--;)if(Kr(r[t][0],e))return t;return-1}var xc=Array.prototype,Ac=xc.splice;function wc(r){var e=this.__data__,t=He(e,r);if(t<0)return!1;var i=e.length-1;return t==i?e.pop():Ac.call(e,t,1),--this.size,!0}function Oc(r){var e=this.__data__,t=He(e,r);return t<0?void 0:e[t][1]}function Ic(r){return He(this.__data__,r)>-1}function Dc(r,e){var t=this.__data__,i=He(t,r);return i<0?(++this.size,t.push([r,e])):t[i][1]=e,this}function J(r){var e=-1,t=r==null?0:r.length;for(this.clear();++e<t;){var i=r[e];this.set(i[0],i[1])}}J.prototype.clear=Rc,J.prototype.delete=wc,J.prototype.get=Oc,J.prototype.has=Ic,J.prototype.set=Dc;var Ie=Ce(K,"Map");function Mc(){this.size=0,this.__data__={hash:new pe,map:new(Ie||J),string:new pe}}function Lc(r){var e=typeof r;return e=="string"||e=="number"||e=="symbol"||e=="boolean"?r!=="__proto__":r===null}function qe(r,e){var t=r.__data__;return Lc(e)?t[typeof e=="string"?"string":"hash"]:t.map}function Nc(r){var e=qe(this,r).delete(r);return this.size-=e?1:0,e}function Fc(r){return qe(this,r).get(r)}function Vc(r){return qe(this,r).has(r)}function Uc(r,e){var t=qe(this,r),i=t.size;return t.set(r,e),this.size+=t.size==i?0:1,this}function Y(r){var e=-1,t=r==null?0:r.length;for(this.clear();++e<t;){var i=r[e];this.set(i[0],i[1])}}Y.prototype.clear=Mc,Y.prototype.delete=Nc,Y.prototype.get=Fc,Y.prototype.has=Vc,Y.prototype.set=Uc;var $c="Expected a function";function Ot(r,e){if(typeof r!="function"||e!=null&&typeof e!="function")throw new TypeError($c);var t=function(){var i=arguments,s=e?e.apply(this,i):i[0],n=t.cache;if(n.has(s))return n.get(s);var a=r.apply(this,i);return t.cache=n.set(s,a)||n,a};return t.cache=new(Ot.Cache||Y),t}Ot.Cache=Y;var Bc=500;function jc(r){var e=Ot(r,function(i){return t.size===Bc&&t.clear(),i}),t=e.cache;return e}var zc=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,Gc=/\\(\\)?/g,Hc=jc(function(r){var e=[];return r.charCodeAt(0)===46&&e.push(""),r.replace(zc,function(t,i,s,n){e.push(s?n.replace(Gc,"$1"):i||t)}),e});function qc(r){return r==null?"":Gr(r)}function oi(r,e){return N(r)?r:wt(r,e)?[r]:Hc(qc(r))}function We(r){if(typeof r=="string"||Ge(r))return r;var e=r+"";return e=="0"&&1/r==-1/0?"-0":e}function ai(r,e){e=oi(e,r);for(var t=0,i=e.length;r!=null&&t<i;)r=r[We(e[t++])];return t&&t==i?r:void 0}function Wc(r,e,t){var i=r==null?void 0:ai(r,e);return i===void 0?t:i}function Xc(r,e){for(var t=-1,i=e.length,s=r.length;++t<i;)r[s+t]=e[t];return r}function Kc(){this.__data__=new J,this.size=0}function Jc(r){var e=this.__data__,t=e.delete(r);return this.size=e.size,t}function Yc(r){return this.__data__.get(r)}function Zc(r){return this.__data__.has(r)}var Qc=200;function ed(r,e){var t=this.__data__;if(t instanceof J){var i=t.__data__;if(!Ie||i.length<Qc-1)return i.push([r,e]),this.size=++t.size,this;t=this.__data__=new Y(i)}return t.set(r,e),this.size=t.size,this}function Z(r){var e=this.__data__=new J(r);this.size=e.size}Z.prototype.clear=Kc,Z.prototype.delete=Jc,Z.prototype.get=Yc,Z.prototype.has=Zc,Z.prototype.set=ed;function ci(r,e){for(var t=-1,i=r==null?0:r.length,s=0,n=[];++t<i;){var a=r[t];e(a,t,r)&&(n[s++]=a)}return n}function td(){return[]}var rd=Object.prototype,id=rd.propertyIsEnumerable,di=Object.getOwnPropertySymbols,sd=di?function(r){return r==null?[]:(r=Object(r),ci(di(r),function(e){return id.call(r,e)}))}:td;function nd(r,e,t){var i=e(r);return N(r)?i:Xc(i,t(r))}function ui(r){return nd(r,we,sd)}var It=Ce(K,"DataView"),Dt=Ce(K,"Promise"),Mt=Ce(K,"Set"),hi="[object Map]",od="[object Object]",pi="[object Promise]",li="[object Set]",mi="[object WeakMap]",fi="[object DataView]",ad=he(It),cd=he(Ie),dd=he(Dt),ud=he(Mt),hd=he(kt),se=ge;(It&&se(new It(new ArrayBuffer(1)))!=fi||Ie&&se(new Ie)!=hi||Dt&&se(Dt.resolve())!=pi||Mt&&se(new Mt)!=li||kt&&se(new kt)!=mi)&&(se=function(r){var e=ge(r),t=e==od?r.constructor:void 0,i=t?he(t):"";if(i)switch(i){case ad:return fi;case cd:return hi;case dd:return pi;case ud:return li;case hd:return mi}return e});var _i=K.Uint8Array,pd="__lodash_hash_undefined__";function ld(r){return this.__data__.set(r,pd),this}function md(r){return this.__data__.has(r)}function Xe(r){var e=-1,t=r==null?0:r.length;for(this.__data__=new Y;++e<t;)this.add(r[e])}Xe.prototype.add=Xe.prototype.push=ld,Xe.prototype.has=md;function fd(r,e){for(var t=-1,i=r==null?0:r.length;++t<i;)if(e(r[t],t,r))return!0;return!1}function _d(r,e){return r.has(e)}var gd=1,vd=2;function gi(r,e,t,i,s,n){var a=t&gd,o=r.length,u=e.length;if(o!=u&&!(a&&u>o))return!1;var c=n.get(r),d=n.get(e);if(c&&d)return c==e&&d==r;var h=-1,p=!0,l=t&vd?new Xe:void 0;for(n.set(r,e),n.set(e,r);++h<o;){var f=r[h],g=e[h];if(i)var _=a?i(g,f,h,e,r,n):i(f,g,h,r,e,n);if(_!==void 0){if(_)continue;p=!1;break}if(l){if(!fd(e,function(T,b){if(!_d(l,b)&&(f===T||s(f,T,t,i,n)))return l.push(b)})){p=!1;break}}else if(!(f===g||s(f,g,t,i,n))){p=!1;break}}return n.delete(r),n.delete(e),p}function Cd(r){var e=-1,t=Array(r.size);return r.forEach(function(i,s){t[++e]=[s,i]}),t}function yd(r){var e=-1,t=Array(r.size);return r.forEach(function(i){t[++e]=i}),t}var Sd=1,Td=2,Ed="[object Boolean]",bd="[object Date]",kd="[object Error]",Pd="[object Map]",Rd="[object Number]",xd="[object RegExp]",Ad="[object Set]",wd="[object String]",Od="[object Symbol]",Id="[object ArrayBuffer]",Dd="[object DataView]",vi=ie?ie.prototype:void 0,Lt=vi?vi.valueOf:void 0;function Md(r,e,t,i,s,n,a){switch(t){case Dd:if(r.byteLength!=e.byteLength||r.byteOffset!=e.byteOffset)return!1;r=r.buffer,e=e.buffer;case Id:return!(r.byteLength!=e.byteLength||!n(new _i(r),new _i(e)));case Ed:case bd:case Rd:return Kr(+r,+e);case kd:return r.name==e.name&&r.message==e.message;case xd:case wd:return r==e+"";case Pd:var o=Cd;case Ad:var u=i&Sd;if(o||(o=yd),r.size!=e.size&&!u)return!1;var c=a.get(r);if(c)return c==e;i|=Td,a.set(r,e);var d=gi(o(r),o(e),i,s,n,a);return a.delete(r),d;case Od:if(Lt)return Lt.call(r)==Lt.call(e)}return!1}var Ld=1,Nd=Object.prototype,Fd=Nd.hasOwnProperty;function Vd(r,e,t,i,s,n){var a=t&Ld,o=ui(r),u=o.length,c=ui(e),d=c.length;if(u!=d&&!a)return!1;for(var h=u;h--;){var p=o[h];if(!(a?p in e:Fd.call(e,p)))return!1}var l=n.get(r),f=n.get(e);if(l&&f)return l==e&&f==r;var g=!0;n.set(r,e),n.set(e,r);for(var _=a;++h<u;){p=o[h];var T=r[p],b=e[p];if(i)var v=a?i(b,T,p,e,r,n):i(T,b,p,r,e,n);if(!(v===void 0?T===b||s(T,b,t,i,n):v)){g=!1;break}_||(_=p=="constructor")}if(g&&!_){var j=r.constructor,A=e.constructor;j!=A&&"constructor"in r&&"constructor"in e&&!(typeof j=="function"&&j instanceof j&&typeof A=="function"&&A instanceof A)&&(g=!1)}return n.delete(r),n.delete(e),g}var Ud=1,Ci="[object Arguments]",yi="[object Array]",Ke="[object Object]",$d=Object.prototype,Si=$d.hasOwnProperty;function Bd(r,e,t,i,s,n){var a=N(r),o=N(e),u=a?yi:se(r),c=o?yi:se(e);u=u==Ci?Ke:u,c=c==Ci?Ke:c;var d=u==Ke,h=c==Ke,p=u==c;if(p&&xt(r)){if(!xt(e))return!1;a=!0,d=!1}if(p&&!d)return n||(n=new Z),a||ni(r)?gi(r,e,t,i,s,n):Md(r,e,u,t,i,s,n);if(!(t&Ud)){var l=d&&Si.call(r,"__wrapped__"),f=h&&Si.call(e,"__wrapped__");if(l||f){var g=l?r.value():r,_=f?e.value():e;return n||(n=new Z),s(g,_,t,i,n)}}return p?(n||(n=new Z),Vd(r,e,t,i,s,n)):!1}function Nt(r,e,t,i,s){return r===e?!0:r==null||e==null||!ve(r)&&!ve(e)?r!==r&&e!==e:Bd(r,e,t,i,Nt,s)}var jd=1,zd=2;function Gd(r,e,t,i){var s=t.length,n=s;if(r==null)return!n;for(r=Object(r);s--;){var a=t[s];if(a[2]?a[1]!==r[a[0]]:!(a[0]in r))return!1}for(;++s<n;){a=t[s];var o=a[0],u=r[o],c=a[1];if(a[2]){if(u===void 0&&!(o in r))return!1}else{var d=new Z,h;if(!(h===void 0?Nt(c,u,jd|zd,i,d):h))return!1}}return!0}function Ti(r){return r===r&&!xe(r)}function Hd(r){for(var e=we(r),t=e.length;t--;){var i=e[t],s=r[i];e[t]=[i,s,Ti(s)]}return e}function Ei(r,e){return function(t){return t==null?!1:t[r]===e&&(e!==void 0||r in Object(t))}}function qd(r){var e=Hd(r);return e.length==1&&e[0][2]?Ei(e[0][0],e[0][1]):function(t){return t===r||Gd(t,r,e)}}function Wd(r,e){return r!=null&&e in Object(r)}function Xd(r,e,t){e=oi(e,r);for(var i=-1,s=e.length,n=!1;++i<s;){var a=We(e[i]);if(!(n=r!=null&&t(r,a)))break;r=r[a]}return n||++i!=s?n:(s=r==null?0:r.length,!!s&&Pt(s)&&Xr(a,s)&&(N(r)||Zr(r)))}function Kd(r,e){return r!=null&&Xd(r,e,Wd)}var Jd=1,Yd=2;function Zd(r,e){return wt(r)&&Ti(e)?Ei(We(r),e):function(t){var i=Wc(t,r);return i===void 0&&i===e?Kd(t,r):Nt(e,i,Jd|Yd)}}function Qd(r){return function(e){return e==null?void 0:e[r]}}function eu(r){return function(e){return ai(e,r)}}function tu(r){return wt(r)?Qd(We(r)):eu(r)}function Ft(r){return typeof r=="function"?r:r==null?ia:typeof r=="object"?N(r)?Zd(r[0],r[1]):qd(r):tu(r)}function ru(r){return function(e,t,i){for(var s=-1,n=Object(e),a=i(e),o=a.length;o--;){var u=a[++s];if(t(n[u],u,n)===!1)break}return e}}var iu=ru();function su(r,e){return r&&iu(r,e,we)}function nu(r,e){return function(t,i){if(t==null)return t;if(!Rt(t))return r(t,i);for(var s=t.length,n=-1,a=Object(t);++n<s&&i(a[n],n,a)!==!1;);return t}}var ou=nu(su);function au(r,e){var t=[];return ou(r,function(i,s,n){e(i,s,n)&&t.push(i)}),t}function bi(r,e){var t=N(r)?ci:au;return t(r,Ft(e))}function cu(r){return function(e,t,i){var s=Object(e);if(!Rt(e)){var n=Ft(t);e=we(e),t=function(o){return n(s[o],o,s)}}var a=r(e,t,i);return a>-1?s[n?e[a]:a]:void 0}}var du=Math.max;function uu(r,e,t){var i=r==null?0:r.length;if(!i)return-1;var s=t==null?0:ra(t);return s<0&&(s=du(i+s,0)),ya(r,Ft(e),s)}var De=cu(uu);function hu(r,e){return Br(e,function(t){return r[t]})}function Q(r){return r==null?[]:hu(r,we(r))}function pu(r){return r==null}class lu extends ze{constructor(e){super({type:S.Microphone,stream:e}),this._trackMap.audio=e.track()}get source(){return this._source}get mixerNode(){return this.source.node()}bindTrackEnd(e){this.source.on(D.ENDED,e)}destroy(){this.source.destroy()}}class mu extends _e{constructor(e){super({type:S.VideoFile,stream:e});const t=De(e,s=>s.kind===E.VIDEO),i=De(e,s=>s.kind===E.AUDIO);this._videoStream=t,this._audioStream=i,this._trackMap.video=t==null?void 0:t.track(),this._trackMap.audio=i==null?void 0:i.track(),t&&(this._height=t==null?void 0:t.height(),this._width=t==null?void 0:t.width())}get viewNode(){var e;return((e=this._videoStream)==null?void 0:e.node())??null}get mixerNode(){var e;return((e=this._audioStream)==null?void 0:e.node())??null}bindTrackEnd(e){var t;(t=this._videoStream)==null||t.on(D.ENDED,e)}destroy(){var e,t;(e=this._videoStream)==null||e.destroy(),(t=this._audioStream)==null||t.destroy(),delete this._trackMap.video,delete this._trackMap.audio}}class fu extends _e{constructor(e){super({type:S.Screen,stream:e});const t=De(e,s=>s.kind===E.VIDEO),i=De(e,s=>s.kind===E.AUDIO);this._videoStream=t,this._audioStream=i,this._trackMap.video=t==null?void 0:t.track(),this._trackMap.audio=i==null?void 0:i.track(),t&&(this._height=t==null?void 0:t.height(),this._width=t==null?void 0:t.width(),this.bindTrackSizeChangeEvent(t))}get viewNode(){var e;return((e=this._videoStream)==null?void 0:e.node())??null}get mixerNode(){var e;return((e=this._audioStream)==null?void 0:e.node())??null}bindTrackEnd(e){var t;(t=this._videoStream)==null||t.on(D.ENDED,e)}destroy(){var e,t;(e=this._videoStream)==null||e.destroy(),(t=this._audioStream)==null||t.destroy(),delete this._trackMap.video,delete this._trackMap.audio}}class _u extends ze{constructor(e){super({type:S.AudioFile,stream:e});const t=De(e,i=>i.kind===E.AUDIO);this._audioStream=t,this._trackMap.audio=t==null?void 0:t.track()}get mixerNode(){var e;return((e=this._audioStream)==null?void 0:e.node())??null}bindTrackEnd(e){var t;(t=this._audioStream)==null||t.on(D.ENDED,e)}destroy(){var e;(e=this._audioStream)==null||e.destroy()}}class gu extends _e{constructor(e){super({type:S.Image,stream:e}),this._width=e.width(),this._height=e.height()}get source(){return this._source}get mixerNode(){return null}get viewNode(){return this.source.node()}bindTrackEnd(e){this.source.on(D.ENDED,e)}destroy(){this.source.destroy()}}class vu extends _e{constructor(e){super({type:S.CustomVideo,stream:e}),this._trackMap.video=e.track(),this._width=e.width(),this._height=e.height()}get source(){return this._source}get viewNode(){return this.source.node()}get mixerNode(){return null}bindTrackEnd(e){this.source.on(D.ENDED,e)}destroy(){this.source.destroy()}}class Cu extends ze{constructor(e){super({type:S.CustomAudio,stream:e}),this._trackMap.audio=e==null?void 0:e.track()}get source(){return this._source}get mixerNode(){var e;return((e=this.source)==null?void 0:e.node())??null}bindTrackEnd(e){var t;(t=this._audioStream)==null||t.on(D.ENDED,e)}destroy(){var e;(e=this._audioStream)==null||e.destroy()}}const yu=["user","environment"],Su=18e4,Tu=1e4,ki=1e3;var F=(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))(F||{});class Me extends Error{constructor(e,t,i){super(),this.code=e,this.message=t,i&&(this.ext=i)}}function ye(r,e,t){const i=ot.Landscape;if(e==="video"){const u=(i===ot.Landscape?nr:or)[r],[c,d,h,p]=u.split("x").map(l=>Number(l));return{width:c,height:d,frameRate:h,bitrate:p*1e3}}const s=ar[r],[n,a]=s.split("x").map(o=>Number(o));return{sampleRate:n,bitrate:a*1e3}}class Eu extends te{constructor(){super(),this._videoConstraints={width:1080,height:720,frameRate:30},this._cameraStreams={},this._screenStreams={},this._videoFileStreams={},this._microphoneStreams={},this._audioFileStreams={},this._imageStreams={},this._customVideoStreams={},this._customAudioStreams={};const{width:e,height:t,frameRate:i}=ye(ur,"video"),{sampleRate:s}=ye(hr,"audio");this._videoConstraints={width:e,height:t,frameRate:i},this._audioConstraints={sampleRate:s,enableAutoGainControl:!0,enableNoiseSuppression:!0,enableEchoCancellation:!0}}_notifyCaptured(e){this.emit(z.DeviceCaptured,e)}_notifyStopCapture(e){this.emit(z.DeviceStopCapture,e)}_bindStreamEvent(e){e.bindTrackEnd(()=>{this.emit(z.Interrupted,e),this.stopCapture({streamId:e.id,type:e.type})})}_handleError(e,t){const i=new Me(t,e.message);this.emit(z.Error,i)}setVideoResolution(e){this._videoConstraints={...this._videoConstraints,...e}}setVideoFps(e){this._videoConstraints={...this._videoConstraints,frameRate:e}}setAudioSampleRate(e){this._audioConstraints={...this._audioConstraints,sampleRate:e}}async getDevicesList(e){return no(e?[e]:["audioinput","videoinput"])}async getMicrophones(){return this.getDevicesList("audioinput")}async getCameras(){return this.getDevicesList("videoinput")}stopCapture({streamId:e,type:t}){let i;switch(t){case S.Camera:i="_cameraStreams";break;case S.Screen:i="_screenStreams";break;case S.VideoFile:i="_videoFileStreams";break;case S.Microphone:i="_microphoneStreams";break;case S.AudioFile:i="_audioFileStreams";break;case S.Image:i="_imageStreams";break;case S.CustomVideo:i="_customVideoStreams";break;case S.CustomAudio:i="_customAudioStreams";break}if(i){let s=[];if(e){const n=this[i][e];s.push(n)}else s=Q(this[i]);s.forEach(n=>{this._notifyStopCapture(n),n.destroy(),delete this[i][n.id]})}}async startCameraCapture(e){let t={};yu.includes(e)?t={facingMode:e}:t={deviceId:e};try{const i=await oo({...t,...this._videoConstraints}),s=new Do(i);return this._cameraStreams[s.id]=s,this._notifyCaptured(s),this._bindStreamEvent(s),s.id}catch(i){throw this._handleError(i,F.OPEN_CAMERA_FAILED),i}}async startMicrophoneCapture(e){try{const t=await co({...this._audioConstraints,deviceId:e}),i=new lu(t);return this._microphoneStreams[i.id]=i,this._notifyCaptured(i),this._bindStreamEvent(i),i.id}catch(t){throw this._handleError(t,F.OPEN_MICROPHONE_FAILED),t}}async startScreenCapture(e){try{const t=await uo({audio:e,video:this._videoConstraints}),i=new fu(t);return this._screenStreams[i.id]=i,this._notifyCaptured(i),this._bindStreamEvent(i),i.id}catch(t){throw this._handleError(t,F.OPEN_SCREEN_FAILED),t}}async startVideoFileCapture(e){try{const t=await wr({url:e,video:!0,audio:!0,loop:!0}),i=new mu(t);return this._videoFileStreams[i.id]=i,this._notifyCaptured(i),this._bindStreamEvent(i),i.id}catch(t){throw this._handleError(t,F.VIDEO_FILE_CAPTURE_FAILED),t}}async startAudioFileCapture(e){try{const t=await wr({url:e,video:!1,audio:!0,loop:!0}),i=new _u(t);return this._audioFileStreams[i.id]=i,this._notifyCaptured(i),this._bindStreamEvent(i),i.id}catch(t){throw this._handleError(t,F.AUDIO_FILE_CAPTURE_FAILED),t}}async startImageCapture(e){try{const t=await ao({url:e,width:0,height:0,frameRate:30}),i=new gu(t);return this._imageStreams[i.id]=i,this._notifyCaptured(i),this._bindStreamEvent(i),i.id}catch(t){throw this._handleError(t,F.IMAGE_FILE_CAPTURE_FAILED),t}}startCustomVideoCapture(e){const t=po(e);if(t){const i=new vu(t);return this._customVideoStreams[i.id]=i,this._notifyCaptured(i),this._bindStreamEvent(i),i.id}}startCustomAudioCapture(e){const t=lo(e);if(t){const i=new Cu(t);return this._customAudioStreams[i.id]=i,this._notifyCaptured(i),this._bindStreamEvent(i),i.id}}async startVolumeDetect(e){const t=this.getStreamById(e);if(t)try{await t.startVolumeDetect()}catch(i){this._handleError(i,F.VOLUME_DETECT_FAILED)}}stopVolumeDetect(e){const t=this.getStreamById(e);t&&t.stopVolumeDetect()}getDefaultVideoStream(){return Q(this._cameraStreams)[0]||Q(this._screenStreams)[0]||Q(this._videoFileStreams)[0]||Q(this._imageStreams)[0]||Q(this._customVideoStreams)[0]}getDefaultAudioStream(){return Q(this._microphoneStreams)[0]||Q(this._audioFileStreams)[0]||Q(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(S).forEach(e=>{this.stopCapture({type:e})})}}let ne=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 Vt{constructor({streamManagerController:e,composedStream:t,streamComposeController:i}){this._streamManagerController=e,this._composedStream=t,this._streamComposeController=i,this._active=!1,this.bindStreamManagerControllerEvent()}bindStreamManagerControllerEvent(){this._streamManagerController.on(z.DeviceCaptured,e=>{this._active&&this.onStreamCapture(e)}),this._streamManagerController.on(z.DeviceStopCapture,e=>{this._active&&this.onStreamStopCapture(e)})}getComposedStream(){return this._composedStream}enable(){this._active=!0}disable(){this._active=!1}}const Pi=new ne("SingleComposer");class bu extends Vt{onStreamCapture(e){e.isVideoStream?this._handleVideoStreamCapture(e):this._handleAudioStreamCapture(e)}onStreamStopCapture(e){e&&(e.isVideoStream?this._handleVideoStreamStopCapture(e):this._handleAudioStreamStopCapture(e))}enable(){if(super.enable(),this._composedStream.videoStream){const e=this._streamManagerController.getDefaultVideoStream();e&&this._handleVideoStreamCapture(e)}}async setVideoQuality({width:e,height:t,frameRate:i}){var s,n;if(this._active)try{await((n=(s=this._composedStream.videoStream)==null?void 0:s.videoTrack)==null?void 0:n.applyConstraints({width:{min:e,ideal:e},height:{min:t,ideal:t},frameRate:{min:i,ideal:i}}))}catch(a){Pi.error("setVideoQuality error",a)}}_handleVideoStreamCapture(e){const t=this._composedStream.videoStream;t!=null&&t.id&&this._streamComposeController.getMixerComposer().haveMixedStream(t.id)&&this._streamComposeController.removeAudioStream(t.id),e.audioTrack&&this._streamComposeController.addAudioStream({streamId:e.id,volume:100}),this._composedStream.setVideoStream(e)}_handleAudioStreamCapture(e){const t=this._streamComposeController.getMixerComposer().getMixedStreamByType(e.type);t.length>0&&t.forEach(i=>{this._streamComposeController.removeAudioStream(i.id)}),this._streamComposeController.addAudioStream({streamId:e.id,volume:100})}_handleVideoStreamStopCapture(e){const t=this._composedStream.videoStream;if((t==null?void 0:t.id)===e.id){const i=this._streamManagerController.getDefaultVideoStream();i?this._handleVideoStreamCapture(i):Pi.error("all video stream stop capture")}}_handleAudioStreamStopCapture(e){this._streamComposeController.removeAudioStream(e.id)}getComposedStream(){return this._composedStream}}class ku extends te{constructor(e,{width:t,height:i,x:s,y:n,zOrder:a,keepRatio:o,mirrorType:u}){super(),this._rect={x:0,y:0,width:0,height:0,zOrder:0},this._isHidden=!1,this._paintSize={width:0,height:0},this._rect.width=t??e.width,this._rect.height=i??e.height,this._rect.x=s??0,this._rect.y=n??0,this._rect.zOrder=a??0,this._rect.sourceHeight=e.height,this._rect.sourceWidth=e.width,this._rect.keepRatio=o??!1,this._rect.mirrorType=u,this._stream=e,this._bindVideoTrackSizeChange()}_getPaintSize({elementWidth:e,elementHeight:t}){const i=this._rect.width,s=this._rect.height;if(i===0&&s===0)return{width:0,height:0};if(i===0)return{height:s,width:e*(s/t)};if(s===0)return{width:i,height:t*(i/e)};const n=e/t,a=i/s;let o=i,u=s;return n>a?(o=i,u=2*Math.round(i/n/2)):n<a&&(o=2*Math.round(s*n/2),u=s),{width:o,height:u}}_bindVideoTrackSizeChange(){this._stream.on(dr.SizeChange,({width:e,height:t})=>{this.setBaseProps("sourceWidth",e),this.setBaseProps("sourceHeight",t)})}getViewNode(){var s;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=(s=this._stream.viewNode)==null?void 0:s.size(e.width,e.height);let i;return this._rect.mirrorType!==void 0&&this._rect.mirrorType!==sr.None?i=t==null?void 0:t.mirror(this._rect.mirrorType):i=t,i=i==null?void 0:i.position(this._rect.x,this._rect.y),i}get x(){return this._rect.x}set x(e){this.setBaseProps("x",e)}get y(){return this._rect.y}set y(e){this.setBaseProps("y",e)}get width(){return this._rect.width}set width(e){this.setBaseProps("width",e)}get height(){return this._rect.height}set height(e){this.setBaseProps("height",e)}get zOrder(){return this._rect.zOrder}set zOrder(e){this.setBaseProps("zOrder",e)}get keepRatio(){return this._rect.keepRatio??!1}set keepRatio(e){this.setBaseProps("keepRatio",e)}set mirrorType(e){this.setBaseProps("mirrorType",e)}get paintSize(){return this._paintSize}setBaseProps(e,t){const i=this._rect[e]!==t;switch(e){case"width":this._rect.width=t;break;case"height":this._rect.height=t;break;case"x":this._rect.x=t;break;case"y":this._rect.y=t;break;case"zOrder":this._rect.zOrder=t;break;case"keepRatio":this._rect.keepRatio=t;break;case"mirrorType":this._rect.mirrorType=t;break}i&&this.emit("propsChange",{[e]:t})}show(){this._isHidden=!1}hide(){this._isHidden=!0}get stream(){return this._stream}get isHidden(){return this._isHidden}destroy(){}}class Ri extends _e{constructor(e){super({type:S.MixVideo,stream:e}),this._trackMap.video=e}get source(){return this._source}replaceVideoTrack(e){this._trackMap.video=e,this._source=e}get viewNode(){return null}get mixerNode(){return null}bindTrackEnd(e){this.source.onended=e}destroy(){this.source.stop(),delete this._trackMap.video}}var Pu=Object.defineProperty,Ru=Object.getOwnPropertyDescriptor,Le=(r,e,t,i)=>{for(var s=Ru(e,t),n=r.length-1,a;n>=0;n--)(a=r[n])&&(s=a(e,t,s)||s);return s&&Pu(e,t,s),s};const xi=new ne("composition-composer");function Ne(r,e,t){const i=t.value;return t.value=function(...s){return this._active||xi.error("composer is not active"),i.apply(this,s)},t}class Se extends Vt{constructor(e){super(e),this._compositionViewConfig={width:1080,height:720,frameRate:30,backgroundColor:"#000000"},this._sprites=[],this._videoMixer=new xo}onStreamCapture(e){}onStreamStopCapture(e){e&&e.isVideoStream&&this.removeVideoStream(e.id)}enable(){var i;if(this._active)return;super.enable();const e=this._videoMixer.track(),t=this._mixedVideoStream;this._mixedVideoStream=new Ri(e),this._composedStream.setVideoStream(this._mixedVideoStream),t&&((i=t.videoTrack)==null?void 0:i.id)!==e.id&&t.destroy()}disable(){super.disable(),this._videoMixer.stop()}_updateSpriteToMixer(){const e=bi(this._sprites.map(t=>t.isHidden?null:t.getViewNode()));this._videoMixer.draw(e)}_removeSprite(e){this._sprites=this._sprites.filter(t=>t!==e),e.destroy(),this._updateSpriteToMixer()}_addSprite(e){this._sprites.push(e),this._sprites=this._sprites.sort((t,i)=>t.zOrder-i.zOrder),e.on("propsChange",t=>{pu(t.zOrder)||(this._sprites=this._sprites.sort((i,s)=>i.zOrder-s.zOrder)),this._updateSpriteToMixer()}),this._updateSpriteToMixer()}setMixingConfig(e){const t=e.frameRate&&e.frameRate!==this._compositionViewConfig.frameRate;if(this._compositionViewConfig={...this._compositionViewConfig,...e},this._compositionViewConfig.frameRate<1&&(this._compositionViewConfig.frameRate=1),this._videoMixer.updateConfig(this._compositionViewConfig),t&&this._mixedVideoStream){const i=this._mixedVideoStream,s=this._videoMixer.updateFps();this._mixedVideoStream=new Ri(s),this._composedStream.setVideoStream(this._mixedVideoStream),i.destroy()}}getMixingConfig(){return this._compositionViewConfig}addVideoStream(e,t){if(!e.viewNode){xi.error("have no viewNode for composition");return}e.audioTrack&&this._streamComposeController.addAudioStream({streamId:e.id,volume:100});const i=new ku(e,t);this._addSprite(i)}_updateSingleVideoStream(e){const t=e.streamId;if(!t)return;const i=this._sprites.find(s=>s.stream.id===t);i&&(i.height=e.height,i.width=e.width,i.x=e.x,i.y=e.y,i.zOrder=e.zOrder,i.keepRatio=e.keepRatio??!1,i.mirrorType=e.mirrorType)}updateVideoStream(e){e.forEach(t=>{this._updateSingleVideoStream(t)}),this._updateSpriteToMixer()}removeVideoStream(e){if(!e)return;const t=this._sprites.find(i=>i.stream.id===e);t&&this._removeSprite(t)}muteVideoStream(e){if(e){const t=this._sprites.find(i=>i.stream.id===e);t&&t.hide()}else this._sprites.forEach(t=>{t.hide()});this._updateSpriteToMixer()}unmuteVideoStream(e){if(e){const t=this._sprites.find(i=>i.stream.id===e);t&&t.show()}else this._sprites.forEach(t=>{t.show()});this._updateSpriteToMixer()}setMixerWorkerScript(e){this._videoMixer.setWorkerTimerScriptUrl(e)}getVideoStreamRenderConfig(e){const t=this._sprites.find(i=>i.stream.id===e);if(t)return{width:t.width,height:t.height,paintWidth:t.paintSize.width,paintHeight:t.paintSize.height,x:t.x,y:t.y,zOrder:t.zOrder}}}Le([Ne],Se.prototype,"addVideoStream"),Le([Ne],Se.prototype,"updateVideoStream"),Le([Ne],Se.prototype,"removeVideoStream"),Le([Ne],Se.prototype,"muteVideoStream"),Le([Ne],Se.prototype,"unmuteVideoStream");class xu extends te{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 Au extends ze{constructor(e){super({type:S.MixAudio,stream:e}),this._trackMap.audio=e}get source(){return this._source}hasVideoTrack(){return!1}get mixerNode(){return null}bindTrackEnd(e){this.source.onended=e}destroy(){var e;(e=this._trackMap.audio)==null||e.stop(),delete this._trackMap.audio}}class wu extends Vt{constructor(e){super(e),this._spriteList=[],this._audioMixer=new fo}onStreamCapture(e){}onStreamStopCapture(e){e&&this.removeAudioStream(e.id)}_updateSpriteToMixer(){const e=bi(this._spriteList.map(t=>t.isMute?null:t.getMixerNode()));this._audioMixer.mix(e)}_updateSingleAudioStream(e){const{streamId:t,volume:i}=e,s=this._spriteList.find(n=>n.stream.id===t);s?i!==void 0&&(s.volume=i):console.error("can not find stream"+t)}enable(){super.enable();const e=this._audioMixer.track(),t=new Au(e);this._composedStream.setAudioStream(t),this._audioMixer.mix([])}addAudioStream(e,t){const i=new xu(e,t);this._spriteList.push(i),this._updateSpriteToMixer()}removeAudioStream(e){const t=this._spriteList.find(i=>i.stream.id===e);t&&(this._spriteList=this._spriteList.filter(i=>i!==t),this._updateSpriteToMixer())}updateAudioStream(e){e.forEach(t=>{this._updateSingleAudioStream(t)}),this._updateSpriteToMixer()}muteAudioStream(e){if(e){const t=this._spriteList.find(i=>i.stream.id===e);t&&t.mute()}else this._spriteList.forEach(t=>{t.mute()});this._updateSpriteToMixer()}unmuteAudioStream(e){if(e){const t=this._spriteList.find(i=>i.stream.id===e);t&&t.unmute()}else this._spriteList.forEach(t=>{t.unmute()});this._updateSpriteToMixer()}haveMixedStream(e){return this._spriteList.some(t=>t.stream.id===e)}getMixedStreamByType(e){return this._spriteList.filter(t=>t.stream.type===e).map(t=>t.stream)}}class Ou extends te{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(de.VideoStreamChange,e))}setAudioStream(e){var t;((t=this._audioStream)==null?void 0:t.id)!==e.id&&(this._audioStream=e,this.emit(de.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 Iu=new ne("streamComposeController");class Du{constructor(e){this._streamManagerController=e,this._composedStream=new Ou,this.singleComposer=new bu({streamManagerController:this._streamManagerController,composedStream:this._composedStream,streamComposeController:this}),this.compositionComposer=new Se({streamManagerController:this._streamManagerController,composedStream:this._composedStream,streamComposeController:this}),this.mixerComposer=new wu({streamManagerController:this._streamManagerController,composedStream:this._composedStream,streamComposeController:this}),this.singleComposer.enable(),this.mixerComposer.enable()}enableMixing(e){e?(this.compositionComposer.enable(),this.singleComposer.disable()):(this.compositionComposer.disable(),this.singleComposer.enable())}setVideoQuality({width:e,height:t,frameRate:i}){this.singleComposer.setVideoQuality({width:e,height:t,frameRate:i}),this.compositionComposer.setMixingConfig({width:e,height:t,frameRate:i})}setMixingConfig(e){this.compositionComposer.setMixingConfig(e)}getMixingConfig(){return this.compositionComposer.getMixingConfig()}addAudioStream(e){const t=this._streamManagerController.getStreamById(e.streamId);this.mixerComposer.addAudioStream(t,{volume:e.volume??100})}removeAudioStream(e){return this.mixerComposer.removeAudioStream(e)}updateAudioStream(e){this.mixerComposer.updateAudioStream(e)}addVideoStream(e){const t=this._streamManagerController.getVideoStream(e.streamId);if(!t){Iu.error("can not find video stream"+e.streamId);return}this.compositionComposer.addVideoStream(t,e)}updateVideoStream(e){this.compositionComposer.updateVideoStream(e);const t=e.map(i=>({streamId:i.streamId,volume:i.volume}));this.mixerComposer.updateAudioStream(t)}removeVideoStream(e){this.compositionComposer.removeVideoStream(e),this.mixerComposer.removeAudioStream(e)}getComposer(){return this.isEnableMixing?this.compositionComposer:this.singleComposer}getComposedStream(){return this._composedStream}muteVideoStream(e){this.isEnableMixing&&this.compositionComposer.muteVideoStream(e)}unmuteVideoStream(e){this.isEnableMixing&&this.compositionComposer.unmuteVideoStream(e)}muteAudioStream(e){this.mixerComposer.muteAudioStream(e)}unmuteAudioStream(e){this.mixerComposer.unmuteAudioStream(e)}get isEnableMixing(){return this.compositionComposer._active}getMixerComposer(){return this.mixerComposer}setMixerWorkerScript(e){this.compositionComposer.setMixerWorkerScript(e)}getVideoStreamRenderConfig(e){if(this.compositionComposer._active)return this.compositionComposer.getVideoStreamRenderConfig(e)}}class Ai{constructor(e){this._hasBindComposedStreamEvent=!1,this._composedStream=e}bindComposedStreamEvent(){this._hasBindComposedStreamEvent||(this._composedStream.on(de.VideoStreamChange,this.handleVideoStreamChange),this._composedStream.on(de.AudioStreamChange,this.handleAudioStreamChange),this._hasBindComposedStreamEvent=!0)}unbindComposedStreamEvent(){this._hasBindComposedStreamEvent&&(this._composedStream.off(de.VideoStreamChange,this.handleVideoStreamChange),this._composedStream.off(de.AudioStreamChange,this.handleAudioStreamChange),this._hasBindComposedStreamEvent=!1)}}const Te=new ne("PreviewConsumer");class Mu extends Ai{constructor(e,{streamConsumeController:t}){super(e),this._isPreviewing=!1,this._previewElement=null,this.handleAudioStreamChange=i=>{this.startPreview()},this.handleVideoStreamChange=i=>{this.startPreview()},this._streamConsumeController=t}start(){this.bindComposedStreamEvent()}stop(){this.unbindComposedStreamEvent()}setRenderView(e){if(!e)return;const t=document.getElementById(e);if(!t)throw new Error(`can not found element with id ${e}`);if(t===this._previewElement)return;if(this._previewElement){if(t.contains(this._previewElement))return;t.appendChild(this._previewElement);return}const i=document.createElement("video");i.style.width="100%",i.style.height="100%",i.autoplay=!0,i.playsInline=!0,i.setAttribute("webkit-playsinline",""),i.setAttribute("x5-playsinline",""),this._previewElement=i;const s={video:null,audio:null};i.addEventListener("loadeddata",()=>{const n=i.srcObject.getVideoTracks()[0],a=i.srcObject.getAudioTracks()[0];n&&n!==s.video&&(this._streamConsumeController.emit(R.CaptureFirstVideoFrame),s.video=n),a&&a!==s.audio&&(this._streamConsumeController.emit(R.CaptureFirstAudioFrame),s.audio=a)}),t.appendChild(i)}startPreview(){if(Te.log("startPreview"),!this._previewElement){Te.warn("preview element not found");return}this._isPreviewing||this.start();const e=this._composedStream.audioTrack,t=this._composedStream.videoTrack;e&&(this._appendTrack(this._previewElement,e),this._removeTrack(this._previewElement,null)),t&&(this._appendTrack(this._previewElement,t),this._removeTrack(this._previewElement,null)),this._previewElement.play().catch(i=>{this._streamConsumeController.emit(R.NotAllowedAutoPlay)}),this._isPreviewing=!0}stopPreview(){this._isPreviewing=!1;const e=this._composedStream.audioTrack,t=this._composedStream.videoTrack;e&&this._removeTrack(this._previewElement,e),t&&this._removeTrack(this._previewElement,t),this.stop()}destroy(){this.stopPreview(),this._previewElement=null,this.unbindComposedStreamEvent()}_appendTrack(e,t){if(!e||!t)return;const i=e.srcObject||new MediaStream;i.getTracks().find(s=>s.id===t.id)||(t.kind==="audio"&&i.getTracks().forEach(s=>{s.kind==="audio"&&(Te.log(`remove preview track, ${s.label}, readyState=${s.readyState}`),i.removeTrack(s))}),t.kind==="video"&&i.getTracks().forEach(s=>{s.kind==="video"&&(i.removeTrack(s),Te.log(`remove preview track, ${s.label}, readyState=${s.readyState}`))}),i.addTrack(t),e.srcObject?e.load():e.srcObject=i)}_removeTrack(e,t){if(!e)return;const i=e.srcObject;i&&(i.getTracks().forEach(s=>{(s.id===(t==null?void 0:t.id)||s.readyState==="ended")&&(Te.log(`remove preview track ${s.label}`),i.removeTrack(s))}),i.getTracks().length===0&&(e.srcObject=null,Te.log("set srcObject null")))}getPreviewElement(){if(this.isPreviewing)return this._previewElement}get isPreviewing(){return this._isPreviewing}}var B={},Ut={},$t={exports:{}},wi;function Bt(){if(wi)return $t.exports;wi=1;var r=$t.exports={v:[{name:"version",reg:/^(\d*)$/}],o:[{name:"origin",reg:/^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,names:["username","sessionId","sessionVersion","netType","ipVer","address"],format:"%s %s %d %s IP%d %s"}],s:[{name:"name"}],i:[{name:"description"}],u:[{name:"uri"}],e:[{name:"email"}],p:[{name:"phone"}],z:[{name:"timezones"}],r:[{name:"repeats"}],t:[{name:"timing",reg:/^(\d*) (\d*)/,names:["start","stop"],format:"%d %d"}],c:[{name:"connection",reg:/^IN IP(\d) (\S*)/,names:["version","ip"],format:"IN IP%d %s"}],b:[{push:"bandwidth",reg:/^(TIAS|AS|CT|RR|RS):(\d*)/,names:["type","limit"],format:"%s:%s"}],m:[{reg:/^(\w*) (\d*) ([\w/]*)(?: (.*))?/,names:["type","port","protocol","payloads"],format:"%s %d %s %s"}],a:[{push:"rtp",reg:/^rtpmap:(\d*) ([\w\-.]*)(?:\s*\/(\d*)(?:\s*\/(\S*))?)?/,names:["payload","codec","rate","encoding"],format:function(e){return e.encoding?"rtpmap:%d %s/%s/%s":e.rate?"rtpmap:%d %s/%s":"rtpmap:%d %s"}},{push:"fmtp",reg:/^fmtp:(\d*) ([\S| ]*)/,names:["payload","config"],format:"fmtp:%d %s"},{name:"control",reg:/^control:(.*)/,format:"control:%s"},{name:"rtcp",reg:/^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,names:["port","netType","ipVer","address"],format:function(e){return e.address!=null?"rtcp:%d %s IP%d %s":"rtcp:%d"}},{push:"rtcpFbTrrInt",reg:/^rtcp-fb:(\*|\d*) trr-int (\d*)/,names:["payload","value"],format:"rtcp-fb:%s trr-int %d"},{push:"rtcpFb",reg:/^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,names:["payload","type","subtype"],format:function(e){return e.subtype!=null?"rtcp-fb:%s %s %s":"rtcp-fb:%s %s"}},{push:"ext",reg:/^extmap:(\d+)(?:\/(\w+))?(?: (urn:ietf:params:rtp-hdrext:encrypt))? (\S*)(?: (\S*))?/,names:["value","direction","encrypt-uri","uri","config"],format:function(e){return"extmap:%d"+(e.direction?"/%s":"%v")+(e["encrypt-uri"]?" %s":"%v")+" %s"+(e.config?" %s":"")}},{name:"extmapAllowMixed",reg:/^(extmap-allow-mixed)/},{push:"crypto",reg:/^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,names:["id","suite","config","sessionConfig"],format:function(e){return e.sessionConfig!=null?"crypto:%d %s %s %s":"crypto:%d %s %s"}},{name:"setup",reg:/^setup:(\w*)/,format:"setup:%s"},{name:"connectionType",reg:/^connection:(new|existing)/,format:"connection:%s"},{name:"mid",reg:/^mid:([^\s]*)/,format:"mid:%s"},{name:"msid",reg:/^msid:(.*)/,format:"msid:%s"},{name:"ptime",reg:/^ptime:(\d*(?:\.\d*)*)/,format:"ptime:%d"},{name:"maxptime",reg:/^maxptime:(\d*(?:\.\d*)*)/,format:"maxptime:%d"},{name:"direction",reg:/^(sendrecv|recvonly|sendonly|inactive)/},{name:"icelite",reg:/^(ice-lite)/},{name:"iceUfrag",reg:/^ice-ufrag:(\S*)/,format:"ice-ufrag:%s"},{name:"icePwd",reg:/^ice-pwd:(\S*)/,format:"ice-pwd:%s"},{name:"fingerprint",reg:/^fingerprint:(\S*) (\S*)/,names:["type","hash"],format:"fingerprint:%s %s"},{push:"candidates",reg:/^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: tcptype (\S*))?(?: generation (\d*))?(?: network-id (\d*))?(?: network-cost (\d*))?/,names:["foundation","component","transport","priority","ip","port","type","raddr","rport","tcptype","generation","network-id","network-cost"],format:function(e){var t="candidate:%s %d %s %d %s %d typ %s";return t+=e.raddr!=null?" raddr %s rport %d":"%v%v",t+=e.tcptype!=null?" tcptype %s":"%v",e.generation!=null&&(t+=" generation %d"),t+=e["network-id"]!=null?" network-id %d":"%v",t+=e["network-cost"]!=null?" network-cost %d":"%v",t}},{name:"endOfCandidates",reg:/^(end-of-candidates)/},{name:"remoteCandidates",reg:/^remote-candidates:(.*)/,format:"remote-candidates:%s"},{name:"iceOptions",reg:/^ice-options:(\S*)/,format:"ice-options:%s"},{push:"ssrcs",reg:/^ssrc:(\d*) ([\w_-]*)(?::(.*))?/,names:["id","attribute","value"],format:function(e){var t="ssrc:%d";return e.attribute!=null&&(t+=" %s",e.value!=null&&(t+=":%s")),t}},{push:"ssrcGroups",reg:/^ssrc-group:([\x21\x23\x24\x25\x26\x27\x2A\x2B\x2D\x2E\w]*) (.*)/,names:["semantics","ssrcs"],format:"ssrc-group:%s %s"},{name:"msidSemantic",reg:/^msid-semantic:\s?(\w*) (\S*)/,names:["semantic","token"],format:"msid-semantic: %s %s"},{push:"groups",reg:/^group:(\w*) (.*)/,names:["type","mids"],format:"group:%s %s"},{name:"rtcpMux",reg:/^(rtcp-mux)/},{name:"rtcpRsize",reg:/^(rtcp-rsize)/},{name:"sctpmap",reg:/^sctpmap:([\w_/]*) (\S*)(?: (\S*))?/,names:["sctpmapNumber","app","maxMessageSize"],format:function(e){return e.maxMessageSize!=null?"sctpmap:%s %s %s":"sctpmap:%s %s"}},{name:"xGoogleFlag",reg:/^x-google-flag:([^\s]*)/,format:"x-google-flag:%s"},{push:"rids",reg:/^rid:([\d\w]+) (\w+)(?: ([\S| ]*))?/,names:["id","direction","params"],format:function(e){return e.params?"rid:%s %s %s":"rid:%s %s"}},{push:"imageattrs",reg:new RegExp("^imageattr:(\\d+|\\*)[\\s\\t]+(send|recv)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*)(?:[\\s\\t]+(recv|send)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*))?"),names:["pt","dir1","attrs1","dir2","attrs2"],format:function(e){return"imageattr:%s %s %s"+(e.dir2?" %s %s":"")}},{name:"simulcast",reg:new RegExp("^simulcast:(send|recv) ([a-zA-Z0-9\\-_~;,]+)(?:\\s?(send|recv) ([a-zA-Z0-9\\-_~;,]+))?$"),names:["dir1","list1","dir2","list2"],format:function(e){return"simulcast:%s %s"+(e.dir2?" %s %s":"")}},{name:"simulcast_03",reg:/^simulcast:[\s\t]+([\S+\s\t]+)$/,names:["value"],format:"simulcast: %s"},{name:"framerate",reg:/^framerate:(\d+(?:$|\.\d+))/,format:"framerate:%s"},{name:"sourceFilter",reg:/^source-filter: *(excl|incl) (\S*) (IP4|IP6|\*) (\S*) (.*)/,names:["filterMode","netType","addressTypes","destAddress","srcList"],format:"source-filter: %s %s %s %s %s"},{name:"bundleOnly",reg:/^(bundle-only)/},{name:"label",reg:/^label:(.+)/,format:"label:%s"},{name:"sctpPort",reg:/^sctp-port:(\d+)$/,format:"sctp-port:%s"},{name:"maxMessageSize",reg:/^max-message-size:(\d+)$/,format:"max-message-size:%s"},{push:"tsRefClocks",reg:/^ts-refclk:([^\s=]*)(?:=(\S*))?/,names:["clksrc","clksrcExt"],format:function(e){return"ts-refclk:%s"+(e.clksrcExt!=null?"=%s":"")}},{name:"mediaClk",reg:/^mediaclk:(?:id=(\S*))? *([^\s=]*)(?:=(\S*))?(?: *rate=(\d+)\/(\d+))?/,names:["id","mediaClockName","mediaClockValue","rateNumerator","rateDenominator"],format:function(e){var t="mediaclk:";return t+=e.id!=null?"id=%s %s":"%v%s",t+=e.mediaClockValue!=null?"=%s":"",t+=e.rateNumerator!=null?" rate=%s":"",t+=e.rateDenominator!=null?"/%s":"",t}},{name:"keywords",reg:/^keywds:(.+)$/,format:"keywds:%s"},{name:"content",reg:/^content:(.+)/,format:"content:%s"},{name:"bfcpFloorCtrl",reg:/^floorctrl:(c-only|s-only|c-s)/,format:"floorctrl:%s"},{name:"bfcpConfId",reg:/^confid:(\d+)/,format:"confid:%s"},{name:"bfcpUserId",reg:/^userid:(\d+)/,format:"userid:%s"},{name:"bfcpFloorId",reg:/^floorid:(.+) (?:m-stream|mstrm):(.+)/,names:["id","mStream"],format:"floorid:%s mstrm:%s"},{push:"invalid",names:["value"]}]};return Object.keys(r).forEach(function(e){var t=r[e];t.forEach(function(i){i.reg||(i.reg=/(.*)/),i.format||(i.format="%s")})}),$t.exports}var Oi;function Lu(){return Oi||(Oi=1,function(r){var e=function(o){return String(Number(o))===o?Number(o):o},t=function(o,u,c,d){if(d&&!c)u[d]=e(o[1]);else for(var h=0;h<c.length;h+=1)o[h+1]!=null&&(u[c[h]]=e(o[h+1]))},i=function(o,u,c){var d=o.name&&o.names;o.push&&!u[o.push]?u[o.push]=[]:d&&!u[o.name]&&(u[o.name]={});var h=o.push?{}:d?u[o.name]:u;t(c.match(o.reg),h,o.names,o.name),o.push&&u[o.push].push(h)},s=Bt(),n=RegExp.prototype.test.bind(/^([a-z])=(.*)/);r.parse=function(o){var u={},c=[],d=u;return o.split(/(\r\n|\r|\n)/).filter(n).forEach(function(h){var p=h[0],l=h.slice(2);p==="m"&&(c.push({rtp:[],fmtp:[]}),d=c[c.length-1]);for(var f=0;f<(s[p]||[]).length;f+=1){var g=s[p][f];if(g.reg.test(l))return i(g,d,l)}}),u.media=c,u};var a=function(o,u){var c=u.split(/=(.+)/,2);return c.length===2?o[c[0]]=e(c[1]):c.length===1&&u.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 u=[],c=o.split(" ").map(e),d=0;d<c.length;d+=3)u.push({component:c[d],ip:c[d+1],port:c[d+2]});return u},r.parseImageAttributes=function(o){return o.split(" ").map(function(u){return u.substring(1,u.length-1).split(",").reduce(a,{})})},r.parseSimulcastStreamList=function(o){return o.split(";").map(function(u){return u.split(",").map(function(c){var d,h=!1;return c[0]!=="~"?d=e(c):(d=e(c.substring(1,c.length)),h=!0),{scid:d,paused:h}})})}}(Ut)),Ut}var jt,Ii;function Nu(){if(Ii)return jt;Ii=1;var r=Bt(),e=/%[sdv%]/g,t=function(a){var o=1,u=arguments,c=u.length;return a.replace(e,function(d){if(o>=c)return d;var h=u[o];switch(o+=1,d){case"%%":return"%";case"%s":return String(h);case"%d":return Number(h);case"%v":return""}})},i=function(a,o,u){var c=o.format instanceof Function?o.format(o.push?u:u[o.name]):o.format,d=[a+"="+c];if(o.names)for(var h=0;h<o.names.length;h+=1){var p=o.names[h];o.name?d.push(u[o.name][p]):d.push(u[o.names[h]])}else d.push(u[o.name]);return t.apply(null,d)},s=["v","o","s","i","u","e","p","c","b","t","r","z","a"],n=["i","c","b","a"];return jt=function(a,o){o=o||{},a.version==null&&(a.version=0),a.name==null&&(a.name=" "),a.media.forEach(function(h){h.payloads==null&&(h.payloads="")});var u=o.outerOrder||s,c=o.innerOrder||n,d=[];return u.forEach(function(h){r[h].forEach(function(p){p.name in a&&a[p.name]!=null?d.push(i(h,p,a)):p.push in a&&a[p.push]!=null&&a[p.push].forEach(function(l){d.push(i(h,p,l))})})}),a.media.forEach(function(h){d.push(i("m",r.m[0],h)),c.forEach(function(p){r[p].forEach(function(l){l.name in h&&h[l.name]!=null?d.push(i(p,l,h)):l.push in h&&h[l.push]!=null&&h[l.push].forEach(function(f){d.push(i(p,l,f))})})})}),d.join(`\r
|
|
56
|
+
`,cl=URL.createObjectURL(new Blob([al],{type:"application/javascript"}));class ul{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||cl);const i=new MediaStream;i.addTrack(e);const s=n.createMediaStreamSource(i),a=new AudioWorkletNode(n,"vumeter");a.port.onmessage=o=>{const l=o.data.volume||0;this._volume=Math.min(l*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 jr{constructor(){this._volumeDetectScriptUrl=void 0}static get instance(){return this._instance||(this._instance=new jr),this._instance}get volumeDetectScriptUrl(){return this._volumeDetectScriptUrl}set volumeDetectScriptUrl(e){this._volumeDetectScriptUrl=e}}class Ns extends Qe{constructor(e){super(),this._width=0,this._height=0,this._mediaStream=null,this._nextStream=null,this._trackMap={},this.type=e.type,this.id=ol(),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[Z.Camera,Z.Screen,Z.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 ul),await this._volumeDetector.start(this.audioTrack,jr.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 Rt extends Ns{get isVideoStream(){return!0}get isAudioStream(){return!1}bindTrackSizeChangeEvent(e){e.on(fe.SIZE_CHANGE,({width:t,height:n})=>{this._width=t,this._height=n,this.emit(us.SizeChange,{width:t,height:n})})}}class Hr extends Ns{get isVideoStream(){return!1}get isAudioStream(){return!0}}class ll extends Rt{constructor(e){super({type:Z.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(fe.ENDED,e)}destroy(){this.source.destroy()}}var Us=typeof global=="object"&&global&&global.Object===Object&&global,hl=typeof self=="object"&&self&&self.Object===Object&&self,je=Us||hl||Function("return this")(),tt=je.Symbol,Gs=Object.prototype,dl=Gs.hasOwnProperty,pl=Gs.toString,Wt=tt?tt.toStringTag:void 0;function fl(r){var e=dl.call(r,Wt),t=r[Wt];try{r[Wt]=void 0;var n=!0}catch{}var i=pl.call(r);return n&&(e?r[Wt]=t:delete r[Wt]),i}var ml=Object.prototype,_l=ml.toString;function gl(r){return _l.call(r)}var vl="[object Null]",yl="[object Undefined]",Bs=tt?tt.toStringTag:void 0;function At(r){return r==null?r===void 0?yl:vl:Bs&&Bs in Object(r)?fl(r):gl(r)}function Dt(r){return r!=null&&typeof r=="object"}var Sl="[object Symbol]";function qr(r){return typeof r=="symbol"||Dt(r)&&At(r)==Sl}function Fs(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,Vs=tt?tt.prototype:void 0,js=Vs?Vs.toString:void 0;function Hs(r){if(typeof r=="string")return r;if(ae(r))return Fs(r,Hs)+"";if(qr(r))return js?js.call(r):"";var e=r+"";return e=="0"&&1/r==-1/0?"-0":e}var bl=/\s/;function El(r){for(var e=r.length;e--&&bl.test(r.charAt(e)););return e}var Cl=/^\s+/;function wl(r){return r&&r.slice(0,El(r)+1).replace(Cl,"")}function Jt(r){var e=typeof r;return r!=null&&(e=="object"||e=="function")}var qs=NaN,Tl=/^[-+]0x[0-9a-f]+$/i,kl=/^0b[01]+$/i,Rl=/^0o[0-7]+$/i,Al=parseInt;function Dl(r){if(typeof r=="number")return r;if(qr(r))return qs;if(Jt(r)){var e=typeof r.valueOf=="function"?r.valueOf():r;r=Jt(e)?e+"":e}if(typeof r!="string")return r===0?r:+r;r=wl(r);var t=kl.test(r);return t||Rl.test(r)?Al(r.slice(2),t?2:8):Tl.test(r)?qs:+r}var xl=1/0,Il=17976931348623157e292;function zl(r){if(!r)return r===0?r:0;if(r=Dl(r),r===xl||r===-1/0){var e=r<0?-1:1;return e*Il}return r===r?r:0}function Ol(r){var e=zl(r),t=e%1;return e===e?t?e-t:e:0}function Ml(r){return r}var Pl="[object AsyncFunction]",Ll="[object Function]",Nl="[object GeneratorFunction]",Ul="[object Proxy]";function $s(r){if(!Jt(r))return!1;var e=At(r);return e==Ll||e==Nl||e==Pl||e==Ul}var Hn=je["__core-js_shared__"],Ks=function(){var r=/[^.]+$/.exec(Hn&&Hn.keys&&Hn.keys.IE_PROTO||"");return r?"Symbol(src)_1."+r:""}();function Gl(r){return!!Ks&&Ks in r}var Bl=Function.prototype,Fl=Bl.toString;function pt(r){if(r!=null){try{return Fl.call(r)}catch{}try{return r+""}catch{}}return""}var Vl=/[\\^$.*+?()[\]{}|]/g,jl=/^\[object .+?Constructor\]$/,Hl=Function.prototype,ql=Object.prototype,$l=Hl.toString,Kl=ql.hasOwnProperty,Wl=RegExp("^"+$l.call(Kl).replace(Vl,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function Jl(r){if(!Jt(r)||Gl(r))return!1;var e=$s(r)?Wl:jl;return e.test(pt(r))}function Xl(r,e){return r==null?void 0:r[e]}function xt(r,e){var t=Xl(r,e);return Jl(t)?t:void 0}var qn=xt(je,"WeakMap");function Zl(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 Yl=9007199254740991,Ql=/^(?:0|[1-9]\d*)$/;function Ws(r,e){var t=typeof r;return e=e??Yl,!!e&&(t=="number"||t!="symbol"&&Ql.test(r))&&r>-1&&r%1==0&&r<e}function Js(r,e){return r===e||r!==r&&e!==e}var eh=9007199254740991;function $n(r){return typeof r=="number"&&r>-1&&r%1==0&&r<=eh}function $r(r){return r!=null&&$n(r.length)&&!$s(r)}var th=Object.prototype;function Xs(r){var e=r&&r.constructor,t=typeof e=="function"&&e.prototype||th;return r===t}function rh(r,e){for(var t=-1,n=Array(r);++t<r;)n[t]=e(t);return n}var nh="[object Arguments]";function Zs(r){return Dt(r)&&At(r)==nh}var Ys=Object.prototype,ih=Ys.hasOwnProperty,sh=Ys.propertyIsEnumerable,Kn=Zs(function(){return arguments}())?Zs:function(r){return Dt(r)&&ih.call(r,"callee")&&!sh.call(r,"callee")};function oh(){return!1}var Qs=typeof exports=="object"&&exports&&!exports.nodeType&&exports,eo=Qs&&typeof module=="object"&&module&&!module.nodeType&&module,ah=eo&&eo.exports===Qs,to=ah?je.Buffer:void 0,ch=to?to.isBuffer:void 0,Kr=ch||oh,uh="[object Arguments]",lh="[object Array]",hh="[object Boolean]",dh="[object Date]",ph="[object Error]",fh="[object Function]",mh="[object Map]",_h="[object Number]",gh="[object Object]",vh="[object RegExp]",yh="[object Set]",Sh="[object String]",bh="[object WeakMap]",Eh="[object ArrayBuffer]",Ch="[object DataView]",wh="[object Float32Array]",Th="[object Float64Array]",kh="[object Int8Array]",Rh="[object Int16Array]",Ah="[object Int32Array]",Dh="[object Uint8Array]",xh="[object Uint8ClampedArray]",Ih="[object Uint16Array]",zh="[object Uint32Array]",te={};te[wh]=te[Th]=te[kh]=te[Rh]=te[Ah]=te[Dh]=te[xh]=te[Ih]=te[zh]=!0,te[uh]=te[lh]=te[Eh]=te[hh]=te[Ch]=te[dh]=te[ph]=te[fh]=te[mh]=te[_h]=te[gh]=te[vh]=te[yh]=te[Sh]=te[bh]=!1;function Oh(r){return Dt(r)&&$n(r.length)&&!!te[At(r)]}function Mh(r){return function(e){return r(e)}}var ro=typeof exports=="object"&&exports&&!exports.nodeType&&exports,Xt=ro&&typeof module=="object"&&module&&!module.nodeType&&module,Ph=Xt&&Xt.exports===ro,Wn=Ph&&Us.process,no=function(){try{var r=Xt&&Xt.require&&Xt.require("util").types;return r||Wn&&Wn.binding&&Wn.binding("util")}catch{}}(),io=no&&no.isTypedArray,Jn=io?Mh(io):Oh,Lh=Object.prototype,Nh=Lh.hasOwnProperty;function Uh(r,e){var t=ae(r),n=!t&&Kn(r),i=!t&&!n&&Kr(r),s=!t&&!n&&!i&&Jn(r),a=t||n||i||s,o=a?rh(r.length,String):[],l=o.length;for(var c in r)Nh.call(r,c)&&!(a&&(c=="length"||i&&(c=="offset"||c=="parent")||s&&(c=="buffer"||c=="byteLength"||c=="byteOffset")||Ws(c,l)))&&o.push(c);return o}function Gh(r,e){return function(t){return r(e(t))}}var Bh=Gh(Object.keys,Object),Fh=Object.prototype,Vh=Fh.hasOwnProperty;function so(r){if(!Xs(r))return Bh(r);var e=[];for(var t in Object(r))Vh.call(r,t)&&t!="constructor"&&e.push(t);return e}function Zt(r){return $r(r)?Uh(r):so(r)}var jh=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,Hh=/^\w*$/;function Xn(r,e){if(ae(r))return!1;var t=typeof r;return t=="number"||t=="symbol"||t=="boolean"||r==null||qr(r)?!0:Hh.test(r)||!jh.test(r)||e!=null&&r in Object(e)}var Yt=xt(Object,"create");function qh(){this.__data__=Yt?Yt(null):{},this.size=0}function $h(r){var e=this.has(r)&&delete this.__data__[r];return this.size-=e?1:0,e}var Kh="__lodash_hash_undefined__",Wh=Object.prototype,Jh=Wh.hasOwnProperty;function Xh(r){var e=this.__data__;if(Yt){var t=e[r];return t===Kh?void 0:t}return Jh.call(e,r)?e[r]:void 0}var Zh=Object.prototype,Yh=Zh.hasOwnProperty;function Qh(r){var e=this.__data__;return Yt?e[r]!==void 0:Yh.call(e,r)}var ed="__lodash_hash_undefined__";function td(r,e){var t=this.__data__;return this.size+=this.has(r)?0:1,t[r]=Yt&&e===void 0?ed:e,this}function ft(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])}}ft.prototype.clear=qh,ft.prototype.delete=$h,ft.prototype.get=Xh,ft.prototype.has=Qh,ft.prototype.set=td;function rd(){this.__data__=[],this.size=0}function Wr(r,e){for(var t=r.length;t--;)if(Js(r[t][0],e))return t;return-1}var nd=Array.prototype,id=nd.splice;function sd(r){var e=this.__data__,t=Wr(e,r);if(t<0)return!1;var n=e.length-1;return t==n?e.pop():id.call(e,t,1),--this.size,!0}function od(r){var e=this.__data__,t=Wr(e,r);return t<0?void 0:e[t][1]}function ad(r){return Wr(this.__data__,r)>-1}function cd(r,e){var t=this.__data__,n=Wr(t,r);return n<0?(++this.size,t.push([r,e])):t[n][1]=e,this}function He(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])}}He.prototype.clear=rd,He.prototype.delete=sd,He.prototype.get=od,He.prototype.has=ad,He.prototype.set=cd;var Qt=xt(je,"Map");function ud(){this.size=0,this.__data__={hash:new ft,map:new(Qt||He),string:new ft}}function ld(r){var e=typeof r;return e=="string"||e=="number"||e=="symbol"||e=="boolean"?r!=="__proto__":r===null}function Jr(r,e){var t=r.__data__;return ld(e)?t[typeof e=="string"?"string":"hash"]:t.map}function hd(r){var e=Jr(this,r).delete(r);return this.size-=e?1:0,e}function dd(r){return Jr(this,r).get(r)}function pd(r){return Jr(this,r).has(r)}function fd(r,e){var t=Jr(this,r),n=t.size;return t.set(r,e),this.size+=t.size==n?0:1,this}function qe(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])}}qe.prototype.clear=ud,qe.prototype.delete=hd,qe.prototype.get=dd,qe.prototype.has=pd,qe.prototype.set=fd;var md="Expected a function";function Zn(r,e){if(typeof r!="function"||e!=null&&typeof e!="function")throw new TypeError(md);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||qe),t}Zn.Cache=qe;var _d=500;function gd(r){var e=Zn(r,function(n){return t.size===_d&&t.clear(),n}),t=e.cache;return e}var vd=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,yd=/\\(\\)?/g,Sd=gd(function(r){var e=[];return r.charCodeAt(0)===46&&e.push(""),r.replace(vd,function(t,n,i,s){e.push(i?s.replace(yd,"$1"):n||t)}),e});function bd(r){return r==null?"":Hs(r)}function oo(r,e){return ae(r)?r:Xn(r,e)?[r]:Sd(bd(r))}function Xr(r){if(typeof r=="string"||qr(r))return r;var e=r+"";return e=="0"&&1/r==-1/0?"-0":e}function ao(r,e){e=oo(e,r);for(var t=0,n=e.length;r!=null&&t<n;)r=r[Xr(e[t++])];return t&&t==n?r:void 0}function Ed(r,e,t){var n=r==null?void 0:ao(r,e);return n===void 0?t:n}function Cd(r,e){for(var t=-1,n=e.length,i=r.length;++t<n;)r[i+t]=e[t];return r}function wd(){this.__data__=new He,this.size=0}function Td(r){var e=this.__data__,t=e.delete(r);return this.size=e.size,t}function kd(r){return this.__data__.get(r)}function Rd(r){return this.__data__.has(r)}var Ad=200;function Dd(r,e){var t=this.__data__;if(t instanceof He){var n=t.__data__;if(!Qt||n.length<Ad-1)return n.push([r,e]),this.size=++t.size,this;t=this.__data__=new qe(n)}return t.set(r,e),this.size=t.size,this}function $e(r){var e=this.__data__=new He(r);this.size=e.size}$e.prototype.clear=wd,$e.prototype.delete=Td,$e.prototype.get=kd,$e.prototype.has=Rd,$e.prototype.set=Dd;function co(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 xd(){return[]}var Id=Object.prototype,zd=Id.propertyIsEnumerable,uo=Object.getOwnPropertySymbols,Od=uo?function(r){return r==null?[]:(r=Object(r),co(uo(r),function(e){return zd.call(r,e)}))}:xd;function Md(r,e,t){var n=e(r);return ae(r)?n:Cd(n,t(r))}function lo(r){return Md(r,Zt,Od)}var Yn=xt(je,"DataView"),Qn=xt(je,"Promise"),ei=xt(je,"Set"),ho="[object Map]",Pd="[object Object]",po="[object Promise]",fo="[object Set]",mo="[object WeakMap]",_o="[object DataView]",Ld=pt(Yn),Nd=pt(Qt),Ud=pt(Qn),Gd=pt(ei),Bd=pt(qn),Ke=At;(Yn&&Ke(new Yn(new ArrayBuffer(1)))!=_o||Qt&&Ke(new Qt)!=ho||Qn&&Ke(Qn.resolve())!=po||ei&&Ke(new ei)!=fo||qn&&Ke(new qn)!=mo)&&(Ke=function(r){var e=At(r),t=e==Pd?r.constructor:void 0,n=t?pt(t):"";if(n)switch(n){case Ld:return _o;case Nd:return ho;case Ud:return po;case Gd:return fo;case Bd:return mo}return e});var go=je.Uint8Array,Fd="__lodash_hash_undefined__";function Vd(r){return this.__data__.set(r,Fd),this}function jd(r){return this.__data__.has(r)}function Zr(r){var e=-1,t=r==null?0:r.length;for(this.__data__=new qe;++e<t;)this.add(r[e])}Zr.prototype.add=Zr.prototype.push=Vd,Zr.prototype.has=jd;function Hd(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 qd(r,e){return r.has(e)}var $d=1,Kd=2;function vo(r,e,t,n,i,s){var a=t&$d,o=r.length,l=e.length;if(o!=l&&!(a&&l>o))return!1;var c=s.get(r),u=s.get(e);if(c&&u)return c==e&&u==r;var d=-1,h=!0,f=t&Kd?new Zr:void 0;for(s.set(r,e),s.set(e,r);++d<o;){var b=r[d],T=e[d];if(n)var v=a?n(T,b,d,e,r,s):n(b,T,d,r,e,s);if(v!==void 0){if(v)continue;h=!1;break}if(f){if(!Hd(e,function(C,k){if(!qd(f,k)&&(b===C||i(b,C,t,n,s)))return f.push(k)})){h=!1;break}}else if(!(b===T||i(b,T,t,n,s))){h=!1;break}}return s.delete(r),s.delete(e),h}function Wd(r){var e=-1,t=Array(r.size);return r.forEach(function(n,i){t[++e]=[i,n]}),t}function Jd(r){var e=-1,t=Array(r.size);return r.forEach(function(n){t[++e]=n}),t}var Xd=1,Zd=2,Yd="[object Boolean]",Qd="[object Date]",ep="[object Error]",tp="[object Map]",rp="[object Number]",np="[object RegExp]",ip="[object Set]",sp="[object String]",op="[object Symbol]",ap="[object ArrayBuffer]",cp="[object DataView]",yo=tt?tt.prototype:void 0,ti=yo?yo.valueOf:void 0;function up(r,e,t,n,i,s,a){switch(t){case cp:if(r.byteLength!=e.byteLength||r.byteOffset!=e.byteOffset)return!1;r=r.buffer,e=e.buffer;case ap:return!(r.byteLength!=e.byteLength||!s(new go(r),new go(e)));case Yd:case Qd:case rp:return Js(+r,+e);case ep:return r.name==e.name&&r.message==e.message;case np:case sp:return r==e+"";case tp:var o=Wd;case ip:var l=n&Xd;if(o||(o=Jd),r.size!=e.size&&!l)return!1;var c=a.get(r);if(c)return c==e;n|=Zd,a.set(r,e);var u=vo(o(r),o(e),n,i,s,a);return a.delete(r),u;case op:if(ti)return ti.call(r)==ti.call(e)}return!1}var lp=1,hp=Object.prototype,dp=hp.hasOwnProperty;function pp(r,e,t,n,i,s){var a=t&lp,o=lo(r),l=o.length,c=lo(e),u=c.length;if(l!=u&&!a)return!1;for(var d=l;d--;){var h=o[d];if(!(a?h in e:dp.call(e,h)))return!1}var f=s.get(r),b=s.get(e);if(f&&b)return f==e&&b==r;var T=!0;s.set(r,e),s.set(e,r);for(var v=a;++d<l;){h=o[d];var C=r[h],k=e[h];if(n)var g=a?n(k,C,h,e,r,s):n(C,k,h,r,e,s);if(!(g===void 0?C===k||i(C,k,t,n,s):g)){T=!1;break}v||(v=h=="constructor")}if(T&&!v){var z=r.constructor,N=e.constructor;z!=N&&"constructor"in r&&"constructor"in e&&!(typeof z=="function"&&z instanceof z&&typeof N=="function"&&N instanceof N)&&(T=!1)}return s.delete(r),s.delete(e),T}var fp=1,So="[object Arguments]",bo="[object Array]",Yr="[object Object]",mp=Object.prototype,Eo=mp.hasOwnProperty;function _p(r,e,t,n,i,s){var a=ae(r),o=ae(e),l=a?bo:Ke(r),c=o?bo:Ke(e);l=l==So?Yr:l,c=c==So?Yr:c;var u=l==Yr,d=c==Yr,h=l==c;if(h&&Kr(r)){if(!Kr(e))return!1;a=!0,u=!1}if(h&&!u)return s||(s=new $e),a||Jn(r)?vo(r,e,t,n,i,s):up(r,e,l,t,n,i,s);if(!(t&fp)){var f=u&&Eo.call(r,"__wrapped__"),b=d&&Eo.call(e,"__wrapped__");if(f||b){var T=f?r.value():r,v=b?e.value():e;return s||(s=new $e),i(T,v,t,n,s)}}return h?(s||(s=new $e),pp(r,e,t,n,i,s)):!1}function ri(r,e,t,n,i){return r===e?!0:r==null||e==null||!Dt(r)&&!Dt(e)?r!==r&&e!==e:_p(r,e,t,n,ri,i)}var gp=1,vp=2;function yp(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],l=r[o],c=a[1];if(a[2]){if(l===void 0&&!(o in r))return!1}else{var u=new $e,d;if(!(d===void 0?ri(c,l,gp|vp,n,u):d))return!1}}return!0}function Co(r){return r===r&&!Jt(r)}function Sp(r){for(var e=Zt(r),t=e.length;t--;){var n=e[t],i=r[n];e[t]=[n,i,Co(i)]}return e}function wo(r,e){return function(t){return t==null?!1:t[r]===e&&(e!==void 0||r in Object(t))}}function bp(r){var e=Sp(r);return e.length==1&&e[0][2]?wo(e[0][0],e[0][1]):function(t){return t===r||yp(t,r,e)}}function Ep(r,e){return r!=null&&e in Object(r)}function Cp(r,e,t){e=oo(e,r);for(var n=-1,i=e.length,s=!1;++n<i;){var a=Xr(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)&&Ws(a,i)&&(ae(r)||Kn(r)))}function wp(r,e){return r!=null&&Cp(r,e,Ep)}var Tp=1,kp=2;function Rp(r,e){return Xn(r)&&Co(e)?wo(Xr(r),e):function(t){var n=Ed(t,r);return n===void 0&&n===e?wp(t,r):ri(e,n,Tp|kp)}}function Ap(r){return function(e){return e==null?void 0:e[r]}}function Dp(r){return function(e){return ao(e,r)}}function xp(r){return Xn(r)?Ap(Xr(r)):Dp(r)}function ni(r){return typeof r=="function"?r:r==null?Ml:typeof r=="object"?ae(r)?Rp(r[0],r[1]):bp(r):xp(r)}function Ip(r){return function(e,t,n){for(var i=-1,s=Object(e),a=n(e),o=a.length;o--;){var l=a[++i];if(t(s[l],l,s)===!1)break}return e}}var zp=Ip();function Op(r,e){return r&&zp(r,e,Zt)}function Mp(r,e){return function(t,n){if(t==null)return t;if(!$r(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 Pp=Mp(Op);function Lp(r,e){var t=[];return Pp(r,function(n,i,s){e(n,i,s)&&t.push(n)}),t}function To(r,e){var t=ae(r)?co:Lp;return t(r,ni(e))}function Np(r){return function(e,t,n){var i=Object(e);if(!$r(e)){var s=ni(t);e=Zt(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 Up=Math.max;function Gp(r,e,t){var n=r==null?0:r.length;if(!n)return-1;var i=t==null?0:Ol(t);return i<0&&(i=Up(n+i,0)),Zl(r,ni(e),i)}var er=Np(Gp);function Bp(r,e){return Fs(e,function(t){return r[t]})}function We(r){return r==null?[]:Bp(r,Zt(r))}var Fp="[object Map]",Vp="[object Set]",jp=Object.prototype,Hp=jp.hasOwnProperty;function qp(r){if(r==null)return!0;if($r(r)&&(ae(r)||typeof r=="string"||typeof r.splice=="function"||Kr(r)||Jn(r)||Kn(r)))return!r.length;var e=Ke(r);if(e==Fp||e==Vp)return!r.size;if(Xs(r))return!so(r).length;for(var t in r)if(Hp.call(r,t))return!1;return!0}function $p(r){return r==null}class Kp extends Hr{constructor(e){super({type:Z.Microphone,stream:e}),this._trackMap.audio=e.track()}get source(){return this._source}get mixerNode(){return this.source.node()}bindTrackEnd(e){this.source.on(fe.ENDED,e)}destroy(){this.source.destroy()}}class Wp extends Rt{constructor(e){super({type:Z.VideoFile,stream:e});const t=er(e,i=>i.kind===ee.VIDEO),n=er(e,i=>i.kind===ee.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(fe.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 Jp extends Rt{constructor(e){super({type:Z.Screen,stream:e});const t=er(e,i=>i.kind===ee.VIDEO),n=er(e,i=>i.kind===ee.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(fe.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 Xp extends Hr{constructor(e){super({type:Z.AudioFile,stream:e});const t=er(e,n=>n.kind===ee.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(fe.ENDED,e)}destroy(){var e;(e=this._audioStream)==null||e.destroy()}}class Zp extends Rt{constructor(e){super({type:Z.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(fe.ENDED,e)}destroy(){this.source.destroy()}}class Yp extends Rt{constructor(e){super({type:Z.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(fe.ENDED,e)}destroy(){this.source.destroy()}}class Qp extends Hr{constructor(e){super({type:Z.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(fe.ENDED,e)}destroy(){var e;(e=this._audioStream)==null||e.destroy()}}const ef=["user","environment"],tf=18e4,rf=1e4,ko=1e3;var ye=(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))(ye||{});class It extends Error{constructor(e,t,n){super(),this.code=e,this.message=t,n&&(this.ext=n)}}function zt(r,e,t){const n=Rn.Landscape;if(e==="video"){const l=(n===Rn.Landscape?ss:os)[r],[c,u,d,h]=l.split("x").map(f=>Number(f));return{width:c,height:u,frameRate:d,bitrate:h*1e3}}const i=as[r],[s,a]=i.split("x").map(o=>Number(o));return{sampleRate:s,bitrate:a*1e3}}var re=function(){return(re=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{l(n.next(c))}catch(u){s(u)}}function o(c){try{l(n.throw(c))}catch(u){s(u)}}function l(c){c.done?i(c.value):new t(function(u){u(c.value)}).then(a,o)}l((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(l){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(d){u=[6,d],n=0}finally{t=i=0}if(5&u[0])throw u[1];return{value:u[0]?u[1]:void 0,done:!0}}([l,c])}}}function nf(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 tr(){for(var r=[],e=0;e<arguments.length;e++)r=r.concat(nf(arguments[e]));return r}var Ro,sf=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&&tr(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}(),rr=function(r){return r!=null&&Object.prototype.toString.call(r)=="[object Object]"},oi=function(r){return Array.isArray(r)},of=(Ro=+Date.now()+Number((""+Math.random()).slice(2,8)),function(){return Ro+=1}),nr=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 l=parseInt(i[o],n);l=1*l^t;var c=String.fromCharCode(l);s.push(c)}return s.join("")}}(r,64,25)},Ao=function(){return!!navigator.userAgent.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/)},ir=function(r){Ao()?window.addEventListener("pagehide",r,!1):window.addEventListener("beforeunload",r,!1)},Do=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},Qr=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},en=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 xo(r,e){return r(e={exports:{}},e.exports),e.exports}var sr=xo(function(r,e){var t;t=function(){function n(){for(var s=0,a={};s<arguments.length;s++){var o=arguments[s];for(var l in o)a[l]=o[l]}return a}function i(s){return s.replace(/(%[0-9A-Z]{2})+/g,decodeURIComponent)}return function s(a){function o(){}function l(u,d,h){if(typeof document<"u"){typeof(h=n({path:"/"},o.defaults,h)).expires=="number"&&(h.expires=new Date(1*new Date+864e5*h.expires)),h.expires=h.expires?h.expires.toUTCString():"";try{var f=JSON.stringify(d);/^[\{\[]/.test(f)&&(d=f)}catch{}d=a.write?a.write(d,u):encodeURIComponent(String(d)).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 b="";for(var T in h)h[T]&&(b+="; "+T,h[T]!==!0&&(b+="="+h[T].split(";")[0]));return document.cookie=u+"="+d+b}}function c(u,d){if(typeof document<"u"){for(var h={},f=document.cookie?document.cookie.split("; "):[],b=0;b<f.length;b++){var T=f[b].split("="),v=T.slice(1).join("=");d||v.charAt(0)!=='"'||(v=v.slice(1,-1));try{var C=i(T[0]);if(v=(a.read||a)(v,C)||i(v),d)try{v=JSON.parse(v)}catch{}if(h[C]=v,u===C)break}catch{}}return u?h[u]:h}}return o.set=l,o.get=function(u){return c(u,!1)},o.getJSON=function(u){return c(u,!0)},o.remove=function(u,d){l(u,"",n(d,{expires:-1}))},o.defaults={},o.withConverter=s,o}(function(){})},r.exports=t()}),ui=xo(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 d=new Error("Cannot find module '"+c+"'");throw d.code="MODULE_NOT_FOUND",d}var h=i[c]={exports:{}};n[c][0].call(h.exports,function(f){var b=n[c][1][f];return a(b||f)},h,h.exports,t,n,i,s)}return i[c].exports}for(var o=ci,l=0;l<s.length;l++)a(s[l]);return a}({1:[function(t,n,i){(function(s){var a,o,l=s.MutationObserver||s.WebKitMutationObserver;if(l){var c=0,u=new l(b),d=s.document.createTextNode("");u.observe(d,{characterData:!0}),a=function(){d.data=c=++c%2}}else if(s.setImmediate||s.MessageChannel===void 0)a="document"in s&&"onreadystatechange"in s.document.createElement("script")?function(){var T=s.document.createElement("script");T.onreadystatechange=function(){b(),T.onreadystatechange=null,T.parentNode.removeChild(T),T=null},s.document.documentElement.appendChild(T)}:function(){setTimeout(b,0)};else{var h=new s.MessageChannel;h.port1.onmessage=b,a=function(){h.port2.postMessage(0)}}var f=[];function b(){var T,v;o=!0;for(var C=f.length;C;){for(v=f,f=[],T=-1;++T<C;)v[T]();C=f.length}o=!1}n.exports=function(T){f.push(T)!==1||o||a()}}).call(this,en!==void 0?en:typeof self<"u"?self:typeof window<"u"?window:{})},{}],2:[function(t,n,i){var s=t(1);function a(){}var o={},l=["REJECTED"],c=["FULFILLED"],u=["PENDING"];function d(C){if(typeof C!="function")throw new TypeError("resolver must be a function");this.state=u,this.queue=[],this.outcome=void 0,C!==a&&T(this,C)}function h(C,k,g){this.promise=C,typeof k=="function"&&(this.onFulfilled=k,this.callFulfilled=this.otherCallFulfilled),typeof g=="function"&&(this.onRejected=g,this.callRejected=this.otherCallRejected)}function f(C,k,g){s(function(){var z;try{z=k(g)}catch(N){return o.reject(C,N)}z===C?o.reject(C,new TypeError("Cannot resolve promise with itself")):o.resolve(C,z)})}function b(C){var k=C&&C.then;if(C&&(typeof C=="object"||typeof C=="function")&&typeof k=="function")return function(){k.apply(C,arguments)}}function T(C,k){var g=!1;function z(L){g||(g=!0,o.reject(C,L))}function N(L){g||(g=!0,o.resolve(C,L))}var A=v(function(){k(N,z)});A.status==="error"&&z(A.value)}function v(C,k){var g={};try{g.value=C(k),g.status="success"}catch(z){g.status="error",g.value=z}return g}n.exports=d,d.prototype.catch=function(C){return this.then(null,C)},d.prototype.then=function(C,k){if(typeof C!="function"&&this.state===c||typeof k!="function"&&this.state===l)return this;var g=new this.constructor(a);return this.state!==u?f(g,this.state===c?C:k,this.outcome):this.queue.push(new h(g,C,k)),g},h.prototype.callFulfilled=function(C){o.resolve(this.promise,C)},h.prototype.otherCallFulfilled=function(C){f(this.promise,this.onFulfilled,C)},h.prototype.callRejected=function(C){o.reject(this.promise,C)},h.prototype.otherCallRejected=function(C){f(this.promise,this.onRejected,C)},o.resolve=function(C,k){var g=v(b,k);if(g.status==="error")return o.reject(C,g.value);var z=g.value;if(z)T(C,z);else{C.state=c,C.outcome=k;for(var N=-1,A=C.queue.length;++N<A;)C.queue[N].callFulfilled(k)}return C},o.reject=function(C,k){C.state=l,C.outcome=k;for(var g=-1,z=C.queue.length;++g<z;)C.queue[g].callRejected(k);return C},d.resolve=function(C){return C instanceof this?C:o.resolve(new this(a),C)},d.reject=function(C){var k=new this(a);return o.reject(k,C)},d.all=function(C){var k=this;if(Object.prototype.toString.call(C)!=="[object Array]")return this.reject(new TypeError("must be an array"));var g=C.length,z=!1;if(!g)return this.resolve([]);for(var N=new Array(g),A=0,L=-1,U=new this(a);++L<g;)G(C[L],L);return U;function G(F,K){k.resolve(F).then(function(ne){N[K]=ne,++A!==g||z||(z=!0,o.resolve(U,N))},function(ne){z||(z=!0,o.reject(U,ne))})}},d.race=function(C){var k=this;if(Object.prototype.toString.call(C)!=="[object Array]")return this.reject(new TypeError("must be an array"));var g=C.length,z=!1;if(!g)return this.resolve([]);for(var N,A=-1,L=new this(a);++A<g;)N=C[A],k.resolve(N).then(function(U){z||(z=!0,o.resolve(L,U))},function(U){z||(z=!0,o.reject(L,U))});return L}},{1:1}],3:[function(t,n,i){(function(s){typeof s.Promise!="function"&&(s.Promise=t(2))}).call(this,en!==void 0?en: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(y){if(y.name!=="TypeError")throw y;for(var _=new(typeof BlobBuilder<"u"?BlobBuilder:typeof MSBlobBuilder<"u"?MSBlobBuilder:typeof MozBlobBuilder<"u"?MozBlobBuilder:WebKitBlobBuilder),E=0;E<p.length;E+=1)_.append(p[E]);return _.getBlob(m.type)}}typeof Promise>"u"&&t(3);var l=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 d(p){return typeof p!="string"&&(console.warn(p+" used as a key, but it is not a string."),p=String(p)),p}function h(){if(arguments.length&&typeof arguments[arguments.length-1]=="function")return arguments[arguments.length-1]}var f=void 0,b={},T=Object.prototype.toString;function v(p){return typeof f=="boolean"?l.resolve(f):function(m){return new l(function(_){var E=m.transaction("local-forage-detect-blob-support","readwrite"),y=o([""]);E.objectStore("local-forage-detect-blob-support").put(y,"key"),E.onabort=function(S){S.preventDefault(),S.stopPropagation(),_(!1)},E.oncomplete=function(){var S=navigator.userAgent.match(/Chrome\/(\d+)/),R=navigator.userAgent.match(/Edge\//);_(R||!S||parseInt(S[1],10)>=43)}}).catch(function(){return!1})}(p).then(function(m){return f=m})}function C(p){var m=b[p.name],_={};_.promise=new l(function(E,y){_.resolve=E,_.reject=y}),m.deferredOperations.push(_),m.dbReady?m.dbReady=m.dbReady.then(function(){return _.promise}):m.dbReady=_.promise}function k(p){var m=b[p.name].deferredOperations.pop();if(m)return m.resolve(),m.promise}function g(p,m){var _=b[p.name].deferredOperations.pop();if(_)return _.reject(m),_.promise}function z(p,m){return new l(function(_,E){if(b[p.name]=b[p.name]||{forages:[],db:null,dbReady:null,deferredOperations:[]},p.db){if(!m)return _(p.db);C(p),p.db.close()}var y=[p.name];m&&y.push(p.version);var S=a.open.apply(a,y);m&&(S.onupgradeneeded=function(R){var x=S.result;try{x.createObjectStore(p.storeName),R.oldVersion<=1&&x.createObjectStore("local-forage-detect-blob-support")}catch(I){if(I.name!=="ConstraintError")throw I;console.warn('The database "'+p.name+'" has been upgraded from version '+R.oldVersion+" to version "+R.newVersion+', but the storage "'+p.storeName+'" already exists.')}}),S.onerror=function(R){R.preventDefault(),E(S.error)},S.onsuccess=function(){var R=S.result;R.onversionchange=function(x){x.target.close()},_(R),k(p)}})}function N(p){return z(p,!1)}function A(p){return z(p,!0)}function L(p,m){if(!p.db)return!0;var _=!p.db.objectStoreNames.contains(p.storeName),E=p.version<p.db.version,y=p.version>p.db.version;if(E&&(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),y||_){if(_){var S=p.db.version+1;S>p.version&&(p.version=S)}return!0}return!1}function U(p){return o([function(m){for(var _=m.length,E=new ArrayBuffer(_),y=new Uint8Array(E),S=0;S<_;S++)y[S]=m.charCodeAt(S);return E}(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 E=b[m._dbInfo.name];if(E&&E.dbReady)return E.dbReady});return u(_,p,p),_}function K(p,m,_,E){E===void 0&&(E=1);try{var y=p.db.transaction(p.storeName,m);_(null,y)}catch(S){if(E>0&&(!p.db||S.name==="InvalidStateError"||S.name==="NotFoundError"))return l.resolve().then(function(){if(!p.db||S.name==="NotFoundError"&&!p.db.objectStoreNames.contains(p.storeName)&&p.version<=p.db.version)return p.db&&(p.version=p.db.version+1),A(p)}).then(function(){return function(R){C(R);for(var x=b[R.name],I=x.forages,O=0;O<I.length;O++){var P=I[O];P._dbInfo.db&&(P._dbInfo.db.close(),P._dbInfo.db=null)}return R.db=null,N(R).then(function(B){return R.db=B,L(R)?A(R):B}).then(function(B){R.db=x.db=B;for(var H=0;H<I.length;H++)I[H]._dbInfo.db=B}).catch(function(B){throw g(R,B),B})}(p).then(function(){K(p,m,_,E-1)})}).catch(_);_(S)}}var ne={_driver:"asyncStorage",_initStorage:function(p){var m=this,_={db:null};if(p)for(var E in p)_[E]=p[E];var y=b[_.name];y||(y={forages:[],db:null,dbReady:null,deferredOperations:[]},b[_.name]=y),y.forages.push(m),m._initReady||(m._initReady=m.ready,m.ready=F);var S=[];function R(){return l.resolve()}for(var x=0;x<y.forages.length;x++){var I=y.forages[x];I!==m&&S.push(I._initReady().catch(R))}var O=y.forages.slice(0);return l.all(S).then(function(){return _.db=y.db,N(_)}).then(function(P){return _.db=P,L(_,m._defaultConfig.version)?A(_):P}).then(function(P){_.db=y.db=P,m._dbInfo=_;for(var B=0;B<O.length;B++){var H=O[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,E=new l(function(y,S){_.ready().then(function(){K(_._dbInfo,"readonly",function(R,x){if(R)return S(R);try{var I=x.objectStore(_._dbInfo.storeName).openCursor(),O=1;I.onsuccess=function(){var P=I.result;if(P){var B=P.value;G(B)&&(B=U(B));var H=p(B,P.key,O++);H!==void 0?y(H):P.continue()}else y()},I.onerror=function(){S(I.error)}}catch(P){S(P)}})}).catch(S)});return c(E,m),E},getItem:function(p,m){var _=this;p=d(p);var E=new l(function(y,S){_.ready().then(function(){K(_._dbInfo,"readonly",function(R,x){if(R)return S(R);try{var I=x.objectStore(_._dbInfo.storeName).get(p);I.onsuccess=function(){var O=I.result;O===void 0&&(O=null),G(O)&&(O=U(O)),y(O)},I.onerror=function(){S(I.error)}}catch(O){S(O)}})}).catch(S)});return c(E,m),E},setItem:function(p,m,_){var E=this;p=d(p);var y=new l(function(S,R){var x;E.ready().then(function(){return x=E._dbInfo,T.call(m)==="[object Blob]"?v(x.db).then(function(I){return I?m:(O=m,new l(function(P,B){var H=new FileReader;H.onerror=B,H.onloadend=function(J){var W=btoa(J.target.result||"");P({__local_forage_encoded_blob:!0,data:W,type:O.type})},H.readAsBinaryString(O)}));var O}):m}).then(function(I){K(E._dbInfo,"readwrite",function(O,P){if(O)return R(O);try{var B=P.objectStore(E._dbInfo.storeName);I===null&&(I=void 0);var H=B.put(I,p);P.oncomplete=function(){I===void 0&&(I=null),S(I)},P.onabort=P.onerror=function(){try{var J=H.error?H.error:H.transaction.error;R(J)}catch(W){R(W)}}}catch(J){R(J)}})}).catch(R)});return c(y,_),y},removeItem:function(p,m){var _=this;p=d(p);var E=new l(function(y,S){_.ready().then(function(){K(_._dbInfo,"readwrite",function(R,x){if(R)return S(R);try{var I=x.objectStore(_._dbInfo.storeName).delete(p);x.oncomplete=function(){y()},x.onerror=function(){S(I.error)},x.onabort=function(){try{var O=I.error?I.error:I.transaction.error;S(O)}catch(P){S(P)}}}catch(O){S(O)}})}).catch(S)});return c(E,m),E},clear:function(p){var m=this,_=new l(function(E,y){m.ready().then(function(){K(m._dbInfo,"readwrite",function(S,R){if(S)return y(S);try{var x=R.objectStore(m._dbInfo.storeName).clear();R.oncomplete=function(){E()},R.onabort=R.onerror=function(){try{var I=x.error?x.error:x.transaction.error;y(I)}catch(O){y(O)}}}catch(I){y(I)}})}).catch(y)});return c(_,p),_},length:function(p){var m=this,_=new l(function(E,y){m.ready().then(function(){K(m._dbInfo,"readonly",function(S,R){if(S)return y(S);try{var x=R.objectStore(m._dbInfo.storeName).count();x.onsuccess=function(){E(x.result)},x.onerror=function(){y(x.error)}}catch(I){y(I)}})}).catch(y)});return c(_,p),_},key:function(p,m){var _=this,E=new l(function(y,S){p<0?y(null):_.ready().then(function(){K(_._dbInfo,"readonly",function(R,x){if(R)return S(R);try{var I=x.objectStore(_._dbInfo.storeName),O=!1,P=(I.openKeyCursor||I.openCursor).call(I);P.onsuccess=function(){var B=P.result;B?p===0||O?y(B.key):(O=!0,B.advance(p)):y(null)},P.onerror=function(){S(P.error)}}catch(B){S(B)}})}).catch(S)});return c(E,m),E},keys:function(p){var m=this,_=new l(function(E,y){m.ready().then(function(){K(m._dbInfo,"readonly",function(S,R){if(S)return y(S);try{var x=R.objectStore(m._dbInfo.storeName),I=(x.openKeyCursor||x.openCursor).call(x),O=[];I.onsuccess=function(){var P=I.result;P?(O.push(P.key),P.continue()):E(O)},I.onerror=function(){y(I.error)}}catch(P){y(P)}})}).catch(y)});return c(_,p),_},dropInstance:function(p,m){m=h.apply(this,arguments);var _=this.config();(p=typeof p!="function"&&p||{}).name||(p.name=p.name||_.name,p.storeName=p.storeName||_.storeName);var E,y=this;if(p.name){var S=p.name===_.name&&y._dbInfo.db,R=S?l.resolve(y._dbInfo.db):N(p).then(function(x){var I=b[p.name],O=I.forages;I.db=x;for(var P=0;P<O.length;P++)O[P]._dbInfo.db=x;return x});E=p.storeName?R.then(function(x){if(x.objectStoreNames.contains(p.storeName)){var I=x.version+1;C(p);var O=b[p.name],P=O.forages;x.close();for(var B=0;B<P.length;B++){var H=P[B];H._dbInfo.db=null,H._dbInfo.version=I}return new l(function(J,W){var de=a.open(p.name,I);de.onerror=function(Tt){de.result.close(),W(Tt)},de.onupgradeneeded=function(){de.result.deleteObjectStore(p.storeName)},de.onsuccess=function(){var Tt=de.result;Tt.close(),J(Tt)}}).then(function(J){O.db=J;for(var W=0;W<P.length;W++){var de=P[W];de._dbInfo.db=J,k(de._dbInfo)}}).catch(function(J){throw(g(p,J)||l.resolve()).catch(function(){}),J})}}):R.then(function(x){C(p);var I=b[p.name],O=I.forages;x.close();for(var P=0;P<O.length;P++)O[P]._dbInfo.db=null;return new l(function(B,H){var J=a.deleteDatabase(p.name);J.onerror=function(){var W=J.result;W&&W.close(),H(J.error)},J.onblocked=function(){console.warn('dropInstance blocked for database "'+p.name+'" until all open connections are closed')},J.onsuccess=function(){var W=J.result;W&&W.close(),B(W)}}).then(function(B){I.db=B;for(var H=0;H<O.length;H++)k(O[H]._dbInfo)}).catch(function(B){throw(g(p,B)||l.resolve()).catch(function(){}),B})})}else E=l.reject("Invalid arguments");return c(E,m),E}},Q="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",Ge=/^~~local_forage_type~([^~]+)~/,xe=9,xr=xe+4,Ir=Object.prototype.toString;function zr(p){var m,_,E,y,S,R=.75*p.length,x=p.length,I=0;p[p.length-1]==="="&&(R--,p[p.length-2]==="="&&R--);var O=new ArrayBuffer(R),P=new Uint8Array(O);for(m=0;m<x;m+=4)_=Q.indexOf(p[m]),E=Q.indexOf(p[m+1]),y=Q.indexOf(p[m+2]),S=Q.indexOf(p[m+3]),P[I++]=_<<2|E>>4,P[I++]=(15&E)<<4|y>>2,P[I++]=(3&y)<<6|63&S;return O}function Vt(p){var m,_=new Uint8Array(p),E="";for(m=0;m<_.length;m+=3)E+=Q[_[m]>>2],E+=Q[(3&_[m])<<4|_[m+1]>>4],E+=Q[(15&_[m+1])<<2|_[m+2]>>6],E+=Q[63&_[m+2]];return _.length%3==2?E=E.substring(0,E.length-1)+"=":_.length%3==1&&(E=E.substring(0,E.length-2)+"=="),E}var jt={serialize:function(p,m){var _="";if(p&&(_=Ir.call(p)),p&&(_==="[object ArrayBuffer]"||p.buffer&&Ir.call(p.buffer)==="[object ArrayBuffer]")){var E,y="__lfsc__:";p instanceof ArrayBuffer?(E=p,y+="arbf"):(E=p.buffer,_==="[object Int8Array]"?y+="si08":_==="[object Uint8Array]"?y+="ui08":_==="[object Uint8ClampedArray]"?y+="uic8":_==="[object Int16Array]"?y+="si16":_==="[object Uint16Array]"?y+="ur16":_==="[object Int32Array]"?y+="si32":_==="[object Uint32Array]"?y+="ui32":_==="[object Float32Array]"?y+="fl32":_==="[object Float64Array]"?y+="fl64":m(new Error("Failed to get type for BinaryArray"))),m(y+Vt(E))}else if(_==="[object Blob]"){var S=new FileReader;S.onload=function(){var R="~~local_forage_type~"+p.type+"~"+Vt(this.result);m("__lfsc__:blob"+R)},S.readAsArrayBuffer(p)}else try{m(JSON.stringify(p))}catch(R){console.error("Couldn't convert value into a JSON string: ",p),m(null,R)}},deserialize:function(p){if(p.substring(0,xe)!=="__lfsc__:")return JSON.parse(p);var m,_=p.substring(xr),E=p.substring(xe,xr);if(E==="blob"&&Ge.test(_)){var y=_.match(Ge);m=y[1],_=_.substring(y[0].length)}var S=zr(_);switch(E){case"arbf":return S;case"blob":return o([S],{type:m});case"si08":return new Int8Array(S);case"ui08":return new Uint8Array(S);case"uic8":return new Uint8ClampedArray(S);case"si16":return new Int16Array(S);case"ur16":return new Uint16Array(S);case"si32":return new Int32Array(S);case"ui32":return new Uint32Array(S);case"fl32":return new Float32Array(S);case"fl64":return new Float64Array(S);default:throw new Error("Unkown type: "+E)}},stringToBuffer:zr,bufferToString:Vt};function Or(p,m,_,E){p.executeSql("CREATE TABLE IF NOT EXISTS "+m.storeName+" (id INTEGER PRIMARY KEY, key unique, value)",[],_,E)}function Ie(p,m,_,E,y,S){p.executeSql(_,E,y,function(R,x){x.code===x.SYNTAX_ERR?R.executeSql("SELECT name FROM sqlite_master WHERE type='table' AND name = ?",[m.storeName],function(I,O){O.rows.length?S(I,x):Or(I,m,function(){I.executeSql(_,E,y,S)},S)},S):S(R,x)},S)}function Mr(p,m,_,E){var y=this;p=d(p);var S=new l(function(R,x){y.ready().then(function(){m===void 0&&(m=null);var I=m,O=y._dbInfo;O.serializer.serialize(m,function(P,B){B?x(B):O.db.transaction(function(H){Ie(H,O,"INSERT OR REPLACE INTO "+O.storeName+" (key, value) VALUES (?, ?)",[p,P],function(){R(I)},function(J,W){x(W)})},function(H){if(H.code===H.QUOTA_ERR){if(E>0)return void R(Mr.apply(y,[p,I,_,E-1]));x(H)}})})}).catch(x)});return c(S,_),S}function bn(p){return new l(function(m,_){p.transaction(function(E){E.executeSql("SELECT name FROM sqlite_master WHERE type='table' AND name <> '__WebKitDatabaseInfoTable__'",[],function(y,S){for(var R=[],x=0;x<S.rows.length;x++)R.push(S.rows.item(x).name);m({db:p,storeNames:R})},function(y,S){_(S)})},function(E){_(E)})})}var En={_driver:"webSQLStorage",_initStorage:function(p){var m=this,_={db:null};if(p)for(var E in p)_[E]=typeof p[E]!="string"?p[E].toString():p[E];var y=new l(function(S,R){try{_.db=openDatabase(_.name,String(_.version),_.description,_.size)}catch(x){return R(x)}_.db.transaction(function(x){Or(x,_,function(){m._dbInfo=_,S()},function(I,O){R(O)})},R)});return _.serializer=jt,y},_support:typeof openDatabase=="function",iterate:function(p,m){var _=this,E=new l(function(y,S){_.ready().then(function(){var R=_._dbInfo;R.db.transaction(function(x){Ie(x,R,"SELECT * FROM "+R.storeName,[],function(I,O){for(var P=O.rows,B=P.length,H=0;H<B;H++){var J=P.item(H),W=J.value;if(W&&(W=R.serializer.deserialize(W)),(W=p(W,J.key,H+1))!==void 0)return void y(W)}y()},function(I,O){S(O)})})}).catch(S)});return c(E,m),E},getItem:function(p,m){var _=this;p=d(p);var E=new l(function(y,S){_.ready().then(function(){var R=_._dbInfo;R.db.transaction(function(x){Ie(x,R,"SELECT * FROM "+R.storeName+" WHERE key = ? LIMIT 1",[p],function(I,O){var P=O.rows.length?O.rows.item(0).value:null;P&&(P=R.serializer.deserialize(P)),y(P)},function(I,O){S(O)})})}).catch(S)});return c(E,m),E},setItem:function(p,m,_){return Mr.apply(this,[p,m,_,1])},removeItem:function(p,m){var _=this;p=d(p);var E=new l(function(y,S){_.ready().then(function(){var R=_._dbInfo;R.db.transaction(function(x){Ie(x,R,"DELETE FROM "+R.storeName+" WHERE key = ?",[p],function(){y()},function(I,O){S(O)})})}).catch(S)});return c(E,m),E},clear:function(p){var m=this,_=new l(function(E,y){m.ready().then(function(){var S=m._dbInfo;S.db.transaction(function(R){Ie(R,S,"DELETE FROM "+S.storeName,[],function(){E()},function(x,I){y(I)})})}).catch(y)});return c(_,p),_},length:function(p){var m=this,_=new l(function(E,y){m.ready().then(function(){var S=m._dbInfo;S.db.transaction(function(R){Ie(R,S,"SELECT COUNT(key) as c FROM "+S.storeName,[],function(x,I){var O=I.rows.item(0).c;E(O)},function(x,I){y(I)})})}).catch(y)});return c(_,p),_},key:function(p,m){var _=this,E=new l(function(y,S){_.ready().then(function(){var R=_._dbInfo;R.db.transaction(function(x){Ie(x,R,"SELECT key FROM "+R.storeName+" WHERE id = ? LIMIT 1",[p+1],function(I,O){var P=O.rows.length?O.rows.item(0).key:null;y(P)},function(I,O){S(O)})})}).catch(S)});return c(E,m),E},keys:function(p){var m=this,_=new l(function(E,y){m.ready().then(function(){var S=m._dbInfo;S.db.transaction(function(R){Ie(R,S,"SELECT key FROM "+S.storeName,[],function(x,I){for(var O=[],P=0;P<I.rows.length;P++)O.push(I.rows.item(P).key);E(O)},function(x,I){y(I)})})}).catch(y)});return c(_,p),_},dropInstance:function(p,m){m=h.apply(this,arguments);var _=this.config();(p=typeof p!="function"&&p||{}).name||(p.name=p.name||_.name,p.storeName=p.storeName||_.storeName);var E,y=this;return c(E=p.name?new l(function(S){var R;R=p.name===_.name?y._dbInfo.db:openDatabase(p.name,"","",0),p.storeName?S({db:R,storeNames:[p.storeName]}):S(bn(R))}).then(function(S){return new l(function(R,x){S.db.transaction(function(I){function O(J){return new l(function(W,de){I.executeSql("DROP TABLE IF EXISTS "+J,[],function(){W()},function(Tt,Nr){de(Nr)})})}for(var P=[],B=0,H=S.storeNames.length;B<H;B++)P.push(O(S.storeNames[B]));l.all(P).then(function(){R()}).catch(function(J){x(J)})},function(I){x(I)})})}):l.reject("Invalid arguments"),m),E}};function Pr(p,m){var _=p.name+"/";return p.storeName!==m.storeName&&(_+=p.storeName+"/"),_}function Cn(){return!function(){try{return localStorage.setItem("_localforage_support_test",!0),localStorage.removeItem("_localforage_support_test"),!1}catch{return!0}}()||localStorage.length>0}var wn={_driver:"localStorageWrapper",_initStorage:function(p){var m={};if(p)for(var _ in p)m[_]=p[_];return m.keyPrefix=Pr(p,this._defaultConfig),Cn()?(this._dbInfo=m,m.serializer=jt,l.resolve()):l.reject()},_support:function(){try{return typeof localStorage<"u"&&"setItem"in localStorage&&!!localStorage.setItem}catch{return!1}}(),iterate:function(p,m){var _=this,E=_.ready().then(function(){for(var y=_._dbInfo,S=y.keyPrefix,R=S.length,x=localStorage.length,I=1,O=0;O<x;O++){var P=localStorage.key(O);if(P.indexOf(S)===0){var B=localStorage.getItem(P);if(B&&(B=y.serializer.deserialize(B)),(B=p(B,P.substring(R),I++))!==void 0)return B}}});return c(E,m),E},getItem:function(p,m){var _=this;p=d(p);var E=_.ready().then(function(){var y=_._dbInfo,S=localStorage.getItem(y.keyPrefix+p);return S&&(S=y.serializer.deserialize(S)),S});return c(E,m),E},setItem:function(p,m,_){var E=this;p=d(p);var y=E.ready().then(function(){m===void 0&&(m=null);var S=m;return new l(function(R,x){var I=E._dbInfo;I.serializer.serialize(m,function(O,P){if(P)x(P);else try{localStorage.setItem(I.keyPrefix+p,O),R(S)}catch(B){B.name!=="QuotaExceededError"&&B.name!=="NS_ERROR_DOM_QUOTA_REACHED"||x(B),x(B)}})})});return c(y,_),y},removeItem:function(p,m){var _=this;p=d(p);var E=_.ready().then(function(){var y=_._dbInfo;localStorage.removeItem(y.keyPrefix+p)});return c(E,m),E},clear:function(p){var m=this,_=m.ready().then(function(){for(var E=m._dbInfo.keyPrefix,y=localStorage.length-1;y>=0;y--){var S=localStorage.key(y);S.indexOf(E)===0&&localStorage.removeItem(S)}});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,E=_.ready().then(function(){var y,S=_._dbInfo;try{y=localStorage.key(p)}catch{y=null}return y&&(y=y.substring(S.keyPrefix.length)),y});return c(E,m),E},keys:function(p){var m=this,_=m.ready().then(function(){for(var E=m._dbInfo,y=localStorage.length,S=[],R=0;R<y;R++){var x=localStorage.key(R);x.indexOf(E.keyPrefix)===0&&S.push(x.substring(E.keyPrefix.length))}return S});return c(_,p),_},dropInstance:function(p,m){if(m=h.apply(this,arguments),!(p=typeof p!="function"&&p||{}).name){var _=this.config();p.name=p.name||_.name,p.storeName=p.storeName||_.storeName}var E,y=this;return c(E=p.name?new l(function(S){p.storeName?S(Pr(p,y._defaultConfig)):S(p.name+"/")}).then(function(S){for(var R=localStorage.length-1;R>=0;R--){var x=localStorage.key(R);x.indexOf(S)===0&&localStorage.removeItem(x)}}):l.reject("Invalid arguments"),m),E}},Tn=function(p,m){for(var _,E,y=p.length,S=0;S<y;){if((_=p[S])===(E=m)||typeof _=="number"&&typeof E=="number"&&isNaN(_)&&isNaN(E))return!0;S++}return!1},lt=Array.isArray||function(p){return Object.prototype.toString.call(p)==="[object Array]"},Ze={},wt={},Be={INDEXEDDB:ne,WEBSQL:En,LOCALSTORAGE:wn},kn=[Be.INDEXEDDB._driver,Be.WEBSQL._driver,Be.LOCALSTORAGE._driver],Ht=["dropInstance"],Lr=["clear","getItem","iterate","key","keys","length","removeItem","setItem"].concat(Ht),lg={description:"",driver:kn.slice(),name:"localforage",size:4980736,storeName:"keyvaluepairs",version:1};function hg(p,m){p[m]=function(){var _=arguments;return p.ready().then(function(){return p[m].apply(p,_)})}}function rs(){for(var p=1;p<arguments.length;p++){var m=arguments[p];if(m)for(var _ in m)m.hasOwnProperty(_)&&(lt(m[_])?arguments[0][_]=m[_].slice():arguments[0][_]=m[_])}return arguments[0]}var dg=new(function(){function p(m){for(var _ in function(S,R){if(!(S instanceof R))throw new TypeError("Cannot call a class as a function")}(this,p),Be)if(Be.hasOwnProperty(_)){var E=Be[_],y=E._driver;this[_]=y,Ze[y]||this.defineDriver(E)}this._defaultConfig=rs({},lg),this._config=rs({},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,_,E){var y=new l(function(S,R){try{var x=m._driver,I=new Error("Custom driver not compliant; see https://mozilla.github.io/localForage/#definedriver");if(!m._driver)return void R(I);for(var O=Lr.concat("_initStorage"),P=0,B=O.length;P<B;P++){var H=O[P];if((!Tn(Ht,H)||m[H])&&typeof m[H]!="function")return void R(I)}(function(){for(var W=function(pg){return function(){var fg=new Error("Method "+pg+" is not implemented by the current driver"),Uc=l.reject(fg);return c(Uc,arguments[arguments.length-1]),Uc}},de=0,Tt=Ht.length;de<Tt;de++){var Nr=Ht[de];m[Nr]||(m[Nr]=W(Nr))}})();var J=function(W){Ze[x]&&console.info("Redefining LocalForage driver: "+x),Ze[x]=m,wt[x]=W,S()};"_support"in m?m._support&&typeof m._support=="function"?m._support().then(J,R):J(!!m._support):J(!0)}catch(W){R(W)}});return u(y,_,E),y},p.prototype.driver=function(){return this._driver||null},p.prototype.getDriver=function(m,_,E){var y=Ze[m]?l.resolve(Ze[m]):l.reject(new Error("Driver not found."));return u(y,_,E),y},p.prototype.getSerializer=function(m){var _=l.resolve(jt);return u(_,m),_},p.prototype.ready=function(m){var _=this,E=_._driverSet.then(function(){return _._ready===null&&(_._ready=_._initDriver()),_._ready});return u(E,m,m),E},p.prototype.setDriver=function(m,_,E){var y=this;lt(m)||(m=[m]);var S=this._getSupportedDrivers(m);function R(){y._config.driver=y.driver()}function x(O){return y._extend(O),R(),y._ready=y._initStorage(y._config),y._ready}var I=this._driverSet!==null?this._driverSet.catch(function(){return l.resolve()}):l.resolve();return this._driverSet=I.then(function(){var O=S[0];return y._dbInfo=null,y._ready=null,y.getDriver(O).then(function(P){y._driver=P._driver,R(),y._wrapLibraryMethodsWithReady(),y._initDriver=function(B){return function(){var H=0;return function J(){for(;H<B.length;){var W=B[H];return H++,y._dbInfo=null,y._ready=null,y.getDriver(W).then(x).catch(J)}R();var de=new Error("No available storage method found.");return y._driverSet=l.reject(de),y._driverSet}()}}(S)})}).catch(function(){R();var O=new Error("No available storage method found.");return y._driverSet=l.reject(O),y._driverSet}),u(this._driverSet,_,E),this._driverSet},p.prototype.supports=function(m){return!!wt[m]},p.prototype._extend=function(m){rs(this,m)},p.prototype._getSupportedDrivers=function(m){for(var _=[],E=0,y=m.length;E<y;E++){var S=m[E];this.supports(S)&&_.push(S)}return _},p.prototype._wrapLibraryMethodsWithReady=function(){for(var m=0,_=Lr.length;m<_;m++)hg(this,Lr[m])},p.prototype.createInstance=function(m){return new p(m)},p}());n.exports=dg},{3:3}]},{},[4])(4)}),af=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}(),cf=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}(),uf=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}(),lf=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}(),hf=function(){function r(){this.defaultExpireTime=6048e5,this.local=new cf,this.session=new uf,this.cache=new af}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 sr.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;sr.set(e,t,{expires:new Date(a),path:"/",domain:s})}catch{}},r.prototype.removeCookie=function(e,t){try{sr.remove(e,{path:"/",domain:t||""})}catch{}},r}(),df=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=Qr(window.location.href),o=/Mobile|htc|mini|Android|iP(ad|od|hone)/.test(this.appVersion)?"wap":"web",l=((e=window.navigator.connection)===null||e===void 0?void 0:e.effectiveType)||"";this.utm=function(d,h,f,b){var T=new hf,v=d?"_tea_utm_cache_"+d:"_tea_utm_cache",C=d?"_$utm_from_url_"+d:"_$utm_from_url",k={},g=["tr_shareuser","tr_admaster","tr_param1","tr_param2","tr_param3","tr_param4","$utm_from_url"],z={ad_id:Number(h.ad_id)||void 0,campaign_id:Number(h.campaign_id)||void 0,creative_id:Number(h.creative_id)||void 0,utm_source:h.utm_source,utm_medium:h.utm_medium,utm_campaign:h.utm_campaign,utm_term:h.utm_term,utm_content:h.utm_content,tr_shareuser:h.tr_shareuser,tr_admaster:h.tr_admaster,tr_param1:h.tr_param1,tr_param2:h.tr_param2,tr_param3:h.tr_param3,tr_param4:h.tr_param4};try{var N=!1;for(var A in z)z[A]&&(g.indexOf(A)!==-1?(k.hasOwnProperty("tracer_data")||(k.tracer_data={}),k.tracer_data[A]=z[A]):k[A]=z[A],N=!0);if(N)T.setSessionItem(C,"1"),T.setCookie(v,JSON.stringify(k),b,f);else{var L=T.getCookie(v,f);L&&(k=JSON.parse(L))}T.getSessionItem(C)==1&&(k.hasOwnProperty("tracer_data")||(k.tracer_data={}),k.tracer_data.$utm_from_url=1)}catch{return z}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:l,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 l=Qr(e);l.keyword&&(s=l.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(d,h){var f=d.exec(h);return f&&f[1]?f[1]:""},o=function(d,h){var f=RegExp("(?:^|[^A-Z0-9-_]|[^A-Z0-9-]_|sprd-)(?:"+d+")","i").exec(h);return f?f.slice(1)[0]:""};/Windows/.test(e)&&(t=a(/Windows (.*)/,e),e="windows");var l,c;switch(e){case"Mac OS X":t=o("Mac[ +]OS[ +]X(?:[ /](?:Version )?(\\d+(?:[_\\.]\\d+)+))?",this.userAgent),e="mac";break;case"Android":l=this.userAgent,(c=a(/Android ([\.\_\d]+)/,l))||(c=a(/Android\/([\.\_\d]+)/,l)),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}(),li=function(r,e){try{return sr.get(r)}catch{return""}},hi=function(r,e,t,n){try{var i=n||document.domain,s=+new Date+(t||6048e5);sr.set(r,e,{expires:new Date(s),path:"/",domain:i})}catch{}},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.prototype.getCookie=function(e,t){return li(e)},r.prototype.setCookie=function(e,t,n,i){hi(e,t,n,i)},r}(),di,w,Io={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 li(r)},setCookie:function(r,e,t,n){hi(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}}()},ff={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 li(r)},setCookie:function(r,e,t,n){hi(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}}()},mt=function(){function r(e,t){this._storage=t&&t==="session"?ff:!e&&Io.isSupportLS?Io:new pf}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"},zo=function(){return new Set(Object.keys(pi))},fi=function(){return Object.keys(pi)},Oo={sg:"1fz22z22z1nz21z4mz4bz4bz21z1ez18z1jz1gz49z1kz1az21z4az19z27z22z1cz1mz24z1cz20z21z1cz18z4az1az1mz1k",va:"1fz22z22z1nz21z4mz4bz4bz1kz18z1jz1gz24z18z49z1kz1az21z4az19z27z22z1cz1mz24z1cz20z21z1cz18z4az1az1mz1k",my:"1fz22z22z1nz21z4mz4bz4bz1kz1az21z49z19z1bz49z1kz27z4az1jz18z20z1iz1mz1dz1dz1gz1az1cz4az1az1mz1k"},mi={va:"1fz22z22z1nz21z4mz4bz4bz22z1mz19z1jz1mz1ez4az1gz22z1mz19z21z1lz21z21z1bz1iz4az1az1mz1k",sg:"1fz22z22z1nz21z4mz4bz4bz22z1mz19z1jz1mz1ez4az22z1mz19z21z1lz21z21z1bz1iz4az1az1mz1k",in:"1fz22z22z1nz21z4mz4bz4bz22z1mz19z1jz1mz1ez4az1gz22z1mz19z21z1lz21z21z1bz1iz4az1az1mz1k"},mf={sg:"1fz22z22z1nz21z4mz4bz4bz1kz1az21z49z21z1ez4az22z1gz1iz22z1mz1iz24z4az1az1mz1k",va:"1fz22z22z1nz21z4mz4bz4bz1kz1az21z49z24z18z4az22z1gz1iz22z1mz1iz24z4az1az1mz1k",in:"1fz22z22z1nz21z4mz4bz4bz1kz1az21z49z24z18z49z23z21z1cz18z21z22z4ez18z4az22z1gz1iz22z1mz1iz24z4az1az1mz1k",ie2:"1fz22z22z1nz21z4mz4bz4bz1kz1az21z49z1gz1cz4ez4az22z1gz1iz22z1mz1iz25z4az1cz23"},_f={sg:"1fz22z22z1nz21z4mz4bz4bz1kz1az21z4az22z1gz1iz22z1mz1iz25z4az23z21",va:"1fz22z22z1nz21z4mz4bz4bz1kz1az21z4az22z1gz1iz22z1mz1iz24z4az23z21",ie2:"1fz22z22z1nz21z4mz4bz4bz1kz1az21z49z1gz1cz4ez4az22z1gz1iz22z1mz1iz25z4az1cz23"},or="5.3.11_oversea",gf=["1fz22z22z1nz21z4mz4bz4bz1bz18z22z18z4az19z27z22z1cz1bz18z1lz1az1cz4az1lz1cz22","1fz22z22z1nz21z4mz4bz4bz22z1cz18z49z24z18z4az22z1gz1iz22z1mz1iz49z20z1mz25z4az1lz1cz22","1fz22z22z1nz21z4mz4bz4bz22z1cz18z4az22z1gz1iz22z1mz1iz49z1cz23z4az1lz1cz22","1fz22z22z1nz21z4mz4bz4bz22z1cz18z4az22z1gz1iz22z1mz1iz49z23z21z22z21z4az1lz1cz22","1fz22z22z1nz21z4mz4bz4bz1gz1mz49z21z1ez4az22z1gz1iz22z1mz1iz49z20z1mz25z4az1lz1cz22","1fz22z22z1nz21z4mz4bz4bz1gz1mz49z24z18z4az22z1gz1iz22z1mz1iz49z20z1mz25z4az1lz1cz22"].map(function(r){return nr(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"})(di||(di={})),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"}(w||(w={}));var D=di,X=void 0,Mo=new Date().getTimezoneOffset(),vf=parseInt(""+-Mo/60,10),yf=60*Mo,Sf=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 df(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 mt(!1,"session"),this.localStorage=new mt(!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:X,user_type:X,user_id:X,user_is_auth:X,user_is_login:X,device_id:X,web_id:X,ip_addr_id:X,user_unique_id_type:X},header:{app_id:X,app_name:X,app_install_id:X,install_id:X,app_package:X,app_channel:X,app_version:X,ab_version:X,os_name:i.os_name,os_version:i.os_version,device_model:i.device_model,ab_client:X,traffic_type:X,network_type:i.network_type,client_ip:X,device_brand:X,os_api:X,access:X,language:i.language,region:X,app_language:X,app_region:X,creative_id:i.utm.creative_id,ad_id:i.utm.ad_id,campaign_id:i.utm.campaign_id,log_type:X,rnd:X,platform:i.platform,sdk_version:or,sdk_lib:"js",province:X,city:X,timezone:vf,tz_offset:yf,tz_name:X,sim_region:X,carrier:X,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=Oo.sg),this.domain=nr(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 zo().has(i)?pi[i]:((t=this.initConfig)===null||t===void 0?void 0:t.channel_type)==="tcpy"?mf[i]:((n=this.initConfig)===null||n===void 0?void 0:n.channel_type)==="ttp"?_f[i]:Oo[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=re(re({},t.evtParams||{}),e.evtParams||{});else if(n==="_staging_flag")t.evtParams=re(re({},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(w.DEBUGGER_MESSAGE,{type:w.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(w.DEBUGGER_MESSAGE,{type:w.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(w.DEBUGGER_MESSAGE,{type:w.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(w.DEBUGGER_MESSAGE,{type:w.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(w.DEBUGGER_MESSAGE,{type:w.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(w.DEBUGGER_MESSAGE,{type:w.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(w.DEBUGGER_MESSAGE,{type:w.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(w.DEBUGGER_MESSAGE,{type:w.DEBUGGER_MESSAGE_SDK,info:"SDK Something Error",level:"error",time:Date.now(),data:n.message,infoType:"sdk"}),console.log("delete error")}},r}(),bf=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}(),Ef=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}(),Cf=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}(),wf=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 lf(this.setKey,"LOGSETTING_DATA_STORE"),this.domain=t.logsetting_domain||this.collect.configManager.getDomain(),this.check()}else e.emit(D.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(D.LogSettingReady)):this.fetchSetting(),[3,3];case 2:return t.sent(),this.collect.emit(D.LogSettingReady),this.collect.emit(w.DEBUGGER_MESSAGE,{type:w.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(D.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:re(re({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(w.DEBUGGER_MESSAGE,{type:w.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(w.DEBUGGER_MESSAGE,{type:w.DEBUGGER_MESSAGE_SDK,info:"LogSetting Request Success",logType:"fetch",level:"info",time:Date.now(),data:a,infoType:"sdk"})):t.collect.emit(w.DEBUGGER_MESSAGE,{type:w.DEBUGGER_MESSAGE_SDK,info:"LogSetting Request Response No Data",logType:"fetch",level:"error",time:Date.now(),infoType:"sdk"}),t.collect.emit(D.LogSettingReady)},fail:function(){t.collect.emit(D.LogSettingReady),t.collect.emit(w.DEBUGGER_MESSAGE,{type:w.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(w.DEBUGGER_MESSAGE,{type:w.DEBUGGER_MESSAGE_SDK,info:"SDK Update LogSetting Cache",logType:"info",level:"info",time:Date.now(),infoType:"sdk",data:e})}catch{this.collect.emit(w.DEBUGGER_MESSAGE,{type:w.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}(),Tf=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 mt(!0),this.localStorage=new mt(!1),this.logSetting=new wf,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(D.Ready,function(){n.reportAll(!1)}),this.collect.on(D.ConfigDomain,function(){n.reportUrl=n.configManager.getUrl("event")}),this.collect.on(D.Event,function(i){n.event(i)}),this.collect.on(D.BeconEvent,function(i){n.beconEvent(i)}),this.collect.on(D.CleanEvents,function(){n.reportAll(!1)}),this.linster()},r.prototype.linster=function(){var e=this;window.addEventListener("unload",function(){e.reportAll(!0)},!1),ir(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&&Ao())return void this.beconEvent(e);var n=tr(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(w.DEBUGGER_MESSAGE,{type:w.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=tr(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(D.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(D.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(D.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(D.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"),l=this.configManager.get("user_unique_id_type"),c=[];try{var u=e.filter(function(h){try{Object.keys(o).length&&(h.params=re(re({},o),h.params)),l&&(h.params.$user_unique_id_type=l);var f=n.configManager.getAbCache(),b=a[n.config.ab_user_mode]||a.user_unique_id,T=n.configManager.getAbUuidCache(b);if(f&&f.uuid&&f.uuid===b){var v=n.configManager.getAbVersion();if(n.config.enable_ab_uuid){if(T&&T.length){var C=T.join(",");v&&v.includes(C)&&(h.ab_sdk_version=v)}}else v&&(h.ab_sdk_version=v)}return h.session_id=n.collect.sessionManager.getSessionId(),h.params=n.paramsAllow(h,t),h}catch(k){return console.warn("filter merge event: "+(h&&h.event)+" error, pls check",k&&k.message),n.collect.emit(w.DEBUGGER_MESSAGE,{type:w.DEBUGGER_MESSAGE_SDK,info:"SDK Merge Event Something Error",level:"error",time:Date.now(),data:k.message,infoType:"sdk"}),!1}}),d=JSON.parse(JSON.stringify({events:u,user:a,header:s}));d.local_time=Math.floor(Date.now()/1e3),d.user_unique_type=this.config.enable_ttwebid?this.config.user_unique_type:void 0,d.verbose=1,c.push(d)}catch(h){console.warn("event merge error, pls check",h&&h.message)}return c},r.prototype.split=function(e){return e=e.map(function(t){var 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(w.DEBUGGER_MESSAGE,{type:w.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 l in s)!this.logSetting.getPredefineParamsList().has(l)&&o.has(l)||(a[l]=s[l]);return JSON.stringify(a)}return JSON.stringify(e.params)}catch(c){return this.collect.emit(w.DEBUGGER_MESSAGE,{type:w.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 l=!0;if(a.forEach(function(c){c.events.length||(l=!1)}),!l)return;n.collect.emit(D.SubmitBefore,a),n.collect.requestManager.useRequest({url:n.reportUrl,data:a,success:function(c,u){c&&c.e!==0?(n.collect.emit(D.SubmitError,{type:"f_data",eventData:u,errorCode:c.e,response:c}),n.collect.emit(w.DEBUGGER_MESSAGE,{type:w.DEBUGGER_MESSAGE_EVENT,info:"Event Report Fail",time:Date.now(),data:o,code:c.e,failType:"event data error",status:"fail"})):(n.collect.emit(D.SubmitScuess,{eventData:u,res:c}),n.collect.emit(w.DEBUGGER_MESSAGE,{type:w.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(D.SubmitError,{type:"f_net",eventData:c,errorCode:u}),n.collect.emit(w.DEBUGGER_MESSAGE,{type:w.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(D.SubmitAfter,a)}catch(c){console.warn("something error, "+JSON.stringify(c.stack)),n.collect.emit(w.DEBUGGER_MESSAGE,{type:w.DEBUGGER_MESSAGE_SDK,info:"SDK Report Event Something Error",level:"error",time:Date.now(),data:c.message})}}))},r}(),tn=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)},kf=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 mt(!1),this.tokenKey="__tea_cache_tokens_"+t.app_id,this.enable_ttwebid=t.enable_ttwebid,this.enableCustomWebid=t.enable_custom_webid,this.collect.on(D.ConfigUuid,function(i){n.setUuid(i)}),this.collect.on(D.ConfigWebId,function(i){n.setWebId(i)}),this.collect.on(D.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(D.CustomWebId,function(){e.tokenReady=!0,e.collect.emit(D.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:tn(),user_unique_id:this.configManager.get("user_unique_id")||tn()}):this.remoteWebid()},r.prototype.checkEnv=function(){var e=window.navigator.userAgent;if(e.indexOf("miniProgram")!==-1||e.indexOf("MiniProgram")!==-1){var t=Qr(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(w.DEBUGGER_MESSAGE,{type:w.DEBUGGER_MESSAGE_SDK,info:"SDK Fetch WebID Request",logType:"fetch",level:"info",time:Date.now(),data:n});var i=tn();this.collect.requestManager.useRequest({url:t,data:n,success:function(s){var a;s&&s.e===0?(a=s.web_id,e.collect.emit(w.DEBUGGER_MESSAGE,{type:w.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(D.TokenError),e.collect.emit(w.DEBUGGER_MESSAGE,{type:w.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(D.TokenError),e.collect.emit(w.DEBUGGER_MESSAGE,{type:w.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=re(re({},e),{device_id:s})}else delete e.device_id;this.setStorage(e),this.tokenReady=!0,this.collect.emit(w.DEBUGGER_MESSAGE,{type:w.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(D.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(D.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(D.TokenChange,"uuid"),this.collect.emit(D.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(D.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(D.TokenChange,"uuid")),t!==e&&(this.configManager.set({web_id:e}),this.collect.emit(D.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(w.DEBUGGER_MESSAGE,{type:w.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(w.DEBUGGER_MESSAGE,{type:w.DEBUGGER_MESSAGE_SDK,info:"Fetch GetToken Request Success",logType:"fetch",level:"info",time:Date.now(),data:i,infoType:"sdk"})):(t(""),e.collect.emit(w.DEBUGGER_MESSAGE,{type:w.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(w.DEBUGGER_MESSAGE,{type:w.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}(),ar=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)})},Rf=function(){function r(){}return r.prototype.apply=function(e,t){var n=this;this.collect=e,this.storage=new mt(!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(D.SessionReset,function(i){n.resetSessionId(i)}),this.collect.on(D.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:ar(),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:ar(),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||ar(),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:ar(),timestamp:Date.now()},this.storage.setItem(this.sessionKey,e))},r}();function Ot(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]),rn=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]),Af=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7]),Po=new Uint8Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),Je=new Array(576);Ot(Je);const cr=new Array(60);Ot(cr);const ur=new Array(512);Ot(ur);const lr=new Array(256);Ot(lr);const gi=new Array(29);Ot(gi);const nn=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 Lo,No,Uo;function yi(r,e){this.dyn_tree=r,this.max_code=0,this.stat_desc=e}Ot(nn);const Go=r=>r<256?ur[r]:ur[256+(r>>>7)],hr=(r,e)=>{r.pending_buf[r.pending++]=255&e,r.pending_buf[r.pending++]=e>>>8&255},ve=(r,e,t)=>{r.bi_valid>16-t?(r.bi_buf|=e<<r.bi_valid&65535,hr(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)},Me=(r,e,t)=>{ve(r,t[2*e],t[2*e+1])},Bo=(r,e)=>{let t=0;do t|=1&r,r>>>=1,t<<=1;while(--e>0);return t>>>1},Fo=(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]=Bo(n[o]++,o))}},Vo=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},jo=r=>{r.bi_valid>8?hr(r,r.bi_buf):r.bi_valid>0&&(r.pending_buf[r.pending++]=r.bi_buf),r.bi_buf=0,r.bi_valid=0},Ho=(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&&Ho(e,r.heap[i+1],r.heap[i],r.depth)&&i++,!Ho(e,n,r.heap[i],r.depth));)r.heap[t]=r.heap[i],t=i,i<<=1;r.heap[t]=n},qo=(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?Me(r,i,e):(s=lr[i],Me(r,s+256+1,e),a=_i[s],a!==0&&(i-=gi[s],ve(r,i,a)),n--,s=Go(n),Me(r,s,t),a=rn[s],a!==0&&(n-=nn[s],ve(r,n,a)));while(o<r.sym_next);Me(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,l,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;)l=r.heap[++r.heap_len]=c<2?++c:0,t[2*l]=1,r.depth[l]=0,r.opt_len--,i&&(r.static_len-=n[2*l+1]);for(e.max_code=c,a=r.heap_len>>1;a>=1;a--)Si(r,t,a);l=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*l]=t[2*a]+t[2*o],r.depth[l]=(r.depth[a]>=r.depth[o]?r.depth[a]:r.depth[o])+1,t[2*a+1]=t[2*o+1]=l,r.heap[1]=l++,Si(r,t,1);while(r.heap_len>=2);r.heap[--r.heap_max]=r.heap[1],((u,d)=>{const h=d.dyn_tree,f=d.max_code,b=d.stat_desc.static_tree,T=d.stat_desc.has_stree,v=d.stat_desc.extra_bits,C=d.stat_desc.extra_base,k=d.stat_desc.max_length;let g,z,N,A,L,U,G=0;for(A=0;A<=15;A++)u.bl_count[A]=0;for(h[2*u.heap[u.heap_max]+1]=0,g=u.heap_max+1;g<573;g++)z=u.heap[g],A=h[2*h[2*z+1]+1]+1,A>k&&(A=k,G++),h[2*z+1]=A,z>f||(u.bl_count[A]++,L=0,z>=C&&(L=v[z-C]),U=h[2*z],u.opt_len+=U*(A+L),T&&(u.static_len+=U*(b[2*z+1]+L)));if(G!==0){do{for(A=k-1;u.bl_count[A]===0;)A--;u.bl_count[A]--,u.bl_count[A+1]+=2,u.bl_count[k]--,G-=2}while(G>0);for(A=k;A!==0;A--)for(z=u.bl_count[A];z!==0;)N=u.heap[--g],N>f||(h[2*N+1]!==A&&(u.opt_len+=(A-h[2*N+1])*h[2*N],h[2*N+1]=A),z--)}})(r,e),Fo(t,c,r.bl_count)},$o=(r,e,t)=>{let n,i,s=-1,a=e[1],o=0,l=7,c=4;for(a===0&&(l=138,c=3),e[2*(t+1)+1]=65535,n=0;n<=t;n++)i=a,a=e[2*(n+1)+1],++o<l&&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?(l=138,c=3):i===a?(l=6,c=3):(l=7,c=4))},Ko=(r,e,t)=>{let n,i,s=-1,a=e[1],o=0,l=7,c=4;for(a===0&&(l=138,c=3),n=0;n<=t;n++)if(i=a,a=e[2*(n+1)+1],!(++o<l&&i===a)){if(o<c)do Me(r,i,r.bl_tree);while(--o!=0);else i!==0?(i!==s&&(Me(r,i,r.bl_tree),o--),Me(r,16,r.bl_tree),ve(r,o-3,2)):o<=10?(Me(r,17,r.bl_tree),ve(r,o-3,3)):(Me(r,18,r.bl_tree),ve(r,o-11,7));o=0,s=i,a===0?(l=138,c=3):i===a?(l=6,c=3):(l=7,c=4)}};let Wo=!1;const Jo=(r,e,t,n)=>{ve(r,0+(n?1:0),3),jo(r),hr(r,t),hr(r,~t),t&&r.pending_buf.set(r.window.subarray(e,e+t),r.pending),r.pending+=t};var Df={_tr_init:r=>{Wo||((()=>{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++)lr[n++]=i;for(lr[n-1]=i,s=0,i=0;i<16;i++)for(nn[i]=s,e=0;e<1<<rn[i];e++)ur[s++]=i;for(s>>=7;i<30;i++)for(nn[i]=s<<7,e=0;e<1<<rn[i]-7;e++)ur[256+s++]=i;for(t=0;t<=15;t++)a[t]=0;for(e=0;e<=143;)Je[2*e+1]=8,e++,a[8]++;for(;e<=255;)Je[2*e+1]=9,e++,a[9]++;for(;e<=279;)Je[2*e+1]=7,e++,a[7]++;for(;e<=287;)Je[2*e+1]=8,e++,a[8]++;for(Fo(Je,287,a),e=0;e<30;e++)cr[2*e+1]=5,cr[2*e]=Bo(e,5);Lo=new vi(Je,_i,257,286,15),No=new vi(cr,rn,0,30,15),Uo=new vi(new Array(0),Af,0,19,7)})(),Wo=!0),r.l_desc=new yi(r.dyn_ltree,Lo),r.d_desc=new yi(r.dyn_dtree,No),r.bl_desc=new yi(r.bl_tree,Uo),r.bi_buf=0,r.bi_valid=0,Vo(r)},_tr_stored_block:Jo,_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 l,c=4093624447;for(l=0;l<=31;l++,c>>>=1)if(1&c&&o.dyn_ltree[2*l]!==0)return 0;if(o.dyn_ltree[18]!==0||o.dyn_ltree[20]!==0||o.dyn_ltree[26]!==0)return 1;for(l=32;l<256;l++)if(o.dyn_ltree[2*l]!==0)return 1;return 0})(r)),bi(r,r.l_desc),bi(r,r.d_desc),a=(o=>{let l;for($o(o,o.dyn_ltree,o.l_desc.max_code),$o(o,o.dyn_dtree,o.d_desc.max_code),bi(o,o.bl_desc),l=18;l>=3&&o.bl_tree[2*Po[l]+1]===0;l--);return o.opt_len+=3*(l+1)+5+5+4,l})(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?Jo(r,e,t,n):r.strategy===4||s===i?(ve(r,2+(n?1:0),3),qo(r,Je,cr)):(ve(r,4+(n?1:0),3),((o,l,c,u)=>{let d;for(ve(o,l-257,5),ve(o,c-1,5),ve(o,u-4,4),d=0;d<u;d++)ve(o,o.bl_tree[2*Po[d]+1],3);Ko(o,o.dyn_ltree,l-1),Ko(o,o.dyn_dtree,c-1)})(r,r.l_desc.max_code+1,r.d_desc.max_code+1,a+1),qo(r,r.dyn_ltree,r.dyn_dtree)),Vo(r),n&&jo(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*(lr[t]+256+1)]++,r.dyn_dtree[2*Go(e)]++),r.sym_next===r.sym_end),_tr_align:r=>{ve(r,2,3),Me(r,256,Je),(e=>{e.bi_valid===16?(hr(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)}},dr=(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 xf=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=xf,s=n+t;r^=-1;for(let a=n;a<s;a++)r=r>>>8^i[255&(r^e[a])];return-1^r},_t={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"},gt={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:If,_tr_stored_block:Ei,_tr_flush_block:zf,_tr_tally:rt,_tr_align:Of}=Df,{Z_NO_FLUSH:nt,Z_PARTIAL_FLUSH:Mf,Z_FULL_FLUSH:Pf,Z_FINISH:Ce,Z_BLOCK:Xo,Z_OK:he,Z_STREAM_END:Zo,Z_STREAM_ERROR:Pe,Z_DATA_ERROR:Lf,Z_BUF_ERROR:Ci,Z_DEFAULT_COMPRESSION:Nf,Z_FILTERED:Uf,Z_HUFFMAN_ONLY:sn,Z_RLE:Gf,Z_FIXED:Bf,Z_DEFAULT_STRATEGY:Ff,Z_UNKNOWN:Vf,Z_DEFLATED:on}=gt,vt=(r,e)=>(r.msg=_t[e],e),Yo=r=>2*r-(r>4?9:0),it=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 st=(r,e,t)=>(e<<r.hash_shift^t)&r.hash_mask;const Se=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))},be=(r,e)=>{zf(r,r.block_start>=0?r.block_start:-1,r.strstart-r.block_start,e),r.block_start=r.strstart,Se(r.strm)},Y=(r,e)=>{r.pending_buf[r.pending++]=e},pr=(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=dr(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)},Qo=(r,e)=>{let t,n,i=r.max_chain_length,s=r.strstart,a=r.prev_length,o=r.nice_match;const l=r.strstart>r.w_size-262?r.strstart-(r.w_size-262):0,c=r.window,u=r.w_mask,d=r.prev,h=r.strstart+258;let f=c[s+a-1],b=c[s+a];r.prev_length>=r.good_match&&(i>>=2),o>r.lookahead&&(o=r.lookahead);do if(t=e,c[t+a]===b&&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<h);if(n=258-(h-s),s=h-258,n>a){if(r.match_start=e,a=n,n>=o)break;f=c[s+a-1],b=c[s+a]}}while((e=d[e&u])>l&&--i!=0);return a<=r.lookahead?a:r.lookahead},Mt=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=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=st(r,r.ins_h,r.window[i+1]);r.insert&&(r.ins_h=st(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)},ea=(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!==Ce||e===nt||t!==n+r.strm.avail_in)))break;a=e===Ce&&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,Se(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!==nt&&e!==Ce&&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===Ce)&&e!==nt&&r.strm.avail_in===0&&n<=i)&&(t=n>i?i:n,a=e===Ce&&r.strm.avail_in===0&&t===n?1:0,Ei(r,r.block_start,t,a),r.block_start+=t,Se(r.strm)),a?3:1)},Ti=(r,e)=>{let t,n;for(;;){if(r.lookahead<262){if(Mt(r),r.lookahead<262&&e===nt)return 1;if(r.lookahead===0)break}if(t=0,r.lookahead>=3&&(r.ins_h=st(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=Qo(r,t)),r.match_length>=3)if(n=rt(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=st(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=st(r,r.ins_h,r.window[r.strstart+1]);else n=rt(r,0,r.window[r.strstart]),r.lookahead--,r.strstart++;if(n&&(be(r,!1),r.strm.avail_out===0))return 1}return r.insert=r.strstart<2?r.strstart:2,e===Ce?(be(r,!0),r.strm.avail_out===0?3:4):r.sym_next&&(be(r,!1),r.strm.avail_out===0)?1:2},Pt=(r,e)=>{let t,n,i;for(;;){if(r.lookahead<262){if(Mt(r),r.lookahead<262&&e===nt)return 1;if(r.lookahead===0)break}if(t=0,r.lookahead>=3&&(r.ins_h=st(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=Qo(r,t),r.match_length<=5&&(r.strategy===Uf||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=rt(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=st(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&&(be(r,!1),r.strm.avail_out===0))return 1}else if(r.match_available){if(n=rt(r,0,r.window[r.strstart-1]),n&&be(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=rt(r,0,r.window[r.strstart-1]),r.match_available=0),r.insert=r.strstart<2?r.strstart:2,e===Ce?(be(r,!0),r.strm.avail_out===0?3:4):r.sym_next&&(be(r,!1),r.strm.avail_out===0)?1:2};function Le(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 fr=[new Le(0,0,0,0,ea),new Le(4,4,8,4,Ti),new Le(4,5,16,8,Ti),new Le(4,6,32,32,Ti),new Le(4,4,16,16,Pt),new Le(8,16,32,32,Pt),new Le(8,16,128,128,Pt),new Le(8,32,128,256,Pt),new Le(32,128,258,1024,Pt),new Le(32,258,258,4096,Pt)];function Hf(){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=on,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),it(this.dyn_ltree),it(this.dyn_dtree),it(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),it(this.heap),this.heap_len=0,this.heap_max=0,this.depth=new Uint16Array(573),it(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 mr=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},ta=r=>{if(mr(r))return vt(r,Pe);r.total_in=r.total_out=0,r.data_type=Vf;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,If(e),he},ra=r=>{const e=ta(r);var t;return e===he&&((t=r.state).window_size=2*t.w_size,it(t.head),t.max_lazy_match=fr[t.level].max_lazy,t.good_match=fr[t.level].good_length,t.nice_match=fr[t.level].nice_length,t.max_chain_length=fr[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},na=(r,e,t,n,i,s)=>{if(!r)return Pe;let a=1;if(e===Nf&&(e=6),n<0?(a=0,n=-n):n>15&&(a=2,n-=16),i<1||i>9||t!==on||n<8||n>15||e<0||e>9||s<0||s>Bf||n===8&&a!==1)return vt(r,Pe);n===8&&(n=9);const o=new Hf;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,ra(r)};var _r={deflateInit:(r,e)=>na(r,e,on,15,8,Ff),deflateInit2:na,deflateReset:ra,deflateResetKeep:ta,deflateSetHeader:(r,e)=>mr(r)||r.state.wrap!==2?Pe:(r.state.gzhead=e,he),deflate:(r,e)=>{if(mr(r)||e>Xo||e<0)return r?vt(r,Pe):Pe;const t=r.state;if(!r.output||r.avail_in!==0&&!r.input||t.status===666&&e!==Ce)return vt(r,r.avail_out===0?Ci:Pe);const n=t.last_flush;if(t.last_flush=e,t.pending!==0){if(Se(r),r.avail_out===0)return t.last_flush=-1,he}else if(r.avail_in===0&&Yo(e)<=Yo(n)&&e!==Ce)return vt(r,Ci);if(t.status===666&&r.avail_in!==0)return vt(r,Ci);if(t.status===42&&t.wrap===0&&(t.status=113),t.status===42){let i=on+(t.w_bits-8<<4)<<8,s=-1;if(s=t.strategy>=sn||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,pr(t,i),t.strstart!==0&&(pr(t,r.adler>>>16),pr(t,65535&r.adler)),r.adler=1,t.status=113,Se(r),t.pending!==0)return t.last_flush=-1,he}if(t.status===57){if(r.adler=0,Y(t,31),Y(t,139),Y(t,8),t.gzhead)Y(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)),Y(t,255&t.gzhead.time),Y(t,t.gzhead.time>>8&255),Y(t,t.gzhead.time>>16&255),Y(t,t.gzhead.time>>24&255),Y(t,t.level===9?2:t.strategy>=sn||t.level<2?4:0),Y(t,255&t.gzhead.os),t.gzhead.extra&&t.gzhead.extra.length&&(Y(t,255&t.gzhead.extra.length),Y(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(Y(t,0),Y(t,0),Y(t,0),Y(t,0),Y(t,0),Y(t,t.level===9?2:t.strategy>=sn||t.level<2?4:0),Y(t,3),t.status=113,Se(r),t.pending!==0)return t.last_flush=-1,he}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,Se(r),t.pending!==0)return t.last_flush=-1,he;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)),Se(r),t.pending!==0)return t.last_flush=-1,he;s=0}i=t.gzindex<t.gzhead.name.length?255&t.gzhead.name.charCodeAt(t.gzindex++):0,Y(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)),Se(r),t.pending!==0)return t.last_flush=-1,he;s=0}i=t.gzindex<t.gzhead.comment.length?255&t.gzhead.comment.charCodeAt(t.gzindex++):0,Y(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&&(Se(r),t.pending!==0))return t.last_flush=-1,he;Y(t,255&r.adler),Y(t,r.adler>>8&255),r.adler=0}if(t.status=113,Se(r),t.pending!==0)return t.last_flush=-1,he}if(r.avail_in!==0||t.lookahead!==0||e!==nt&&t.status!==666){let i=t.level===0?ea(t,e):t.strategy===sn?((s,a)=>{let o;for(;;){if(s.lookahead===0&&(Mt(s),s.lookahead===0)){if(a===nt)return 1;break}if(s.match_length=0,o=rt(s,0,s.window[s.strstart]),s.lookahead--,s.strstart++,o&&(be(s,!1),s.strm.avail_out===0))return 1}return s.insert=0,a===Ce?(be(s,!0),s.strm.avail_out===0?3:4):s.sym_next&&(be(s,!1),s.strm.avail_out===0)?1:2})(t,e):t.strategy===Gf?((s,a)=>{let o,l,c,u;const d=s.window;for(;;){if(s.lookahead<=258){if(Mt(s),s.lookahead<=258&&a===nt)return 1;if(s.lookahead===0)break}if(s.match_length=0,s.lookahead>=3&&s.strstart>0&&(c=s.strstart-1,l=d[c],l===d[++c]&&l===d[++c]&&l===d[++c])){u=s.strstart+258;do;while(l===d[++c]&&l===d[++c]&&l===d[++c]&&l===d[++c]&&l===d[++c]&&l===d[++c]&&l===d[++c]&&l===d[++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=rt(s,1,s.match_length-3),s.lookahead-=s.match_length,s.strstart+=s.match_length,s.match_length=0):(o=rt(s,0,s.window[s.strstart]),s.lookahead--,s.strstart++),o&&(be(s,!1),s.strm.avail_out===0))return 1}return s.insert=0,a===Ce?(be(s,!0),s.strm.avail_out===0?3:4):s.sym_next&&(be(s,!1),s.strm.avail_out===0)?1:2})(t,e):fr[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),he;if(i===2&&(e===Mf?Of(t):e!==Xo&&(Ei(t,0,0,!1),e===Pf&&(it(t.head),t.lookahead===0&&(t.strstart=0,t.block_start=0,t.insert=0))),Se(r),r.avail_out===0))return t.last_flush=-1,he}return e!==Ce?he:t.wrap<=0?Zo:(t.wrap===2?(Y(t,255&r.adler),Y(t,r.adler>>8&255),Y(t,r.adler>>16&255),Y(t,r.adler>>24&255),Y(t,255&r.total_in),Y(t,r.total_in>>8&255),Y(t,r.total_in>>16&255),Y(t,r.total_in>>24&255)):(pr(t,r.adler>>>16),pr(t,65535&r.adler)),Se(r),t.wrap>0&&(t.wrap=-t.wrap),t.pending!==0?he:Zo)},deflateEnd:r=>{if(mr(r))return Pe;const e=r.state.status;return r.state=null,e===113?vt(r,Lf):he},deflateSetDictionary:(r,e)=>{let t=e.length;if(mr(r))return Pe;const n=r.state,i=n.wrap;if(i===2||i===1&&n.status!==42||n.lookahead)return Pe;if(i===1&&(r.adler=dr(r.adler,e,t,0)),n.wrap=0,t>=n.w_size){i===0&&(it(n.head),n.strstart=0,n.block_start=0,n.insert=0);let l=new Uint8Array(n.w_size);l.set(e.subarray(t-n.w_size,t),0),e=l,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,Mt(n);n.lookahead>=3;){let l=n.strstart,c=n.lookahead-2;do n.ins_h=st(n,n.ins_h,n.window[l+3-1]),n.prev[l&n.w_mask]=n.head[n.ins_h],n.head[n.ins_h]=l,l++;while(--c);n.strstart=l,n.lookahead=2,Mt(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,he},deflateInfo:"pako deflate (from Nodeca project)"};const qf=(r,e)=>Object.prototype.hasOwnProperty.call(r,e);var ia=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)qf(t,n)&&(r[n]=t[n])}}return r},sa=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 oa=!0;try{String.fromCharCode.apply(null,new Uint8Array(1))}catch{oa=!1}const gr=new Uint8Array(256);for(let r=0;r<256;r++)gr[r]=r>=252?6:r>=248?5:r>=240?4:r>=224?3:r>=192?2:1;gr[254]=gr[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},$f=(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=gr[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&&oa)return String.fromCharCode.apply(null,a.length===o?a:a.subarray(0,o));let l="";for(let c=0;c<o;c++)l+=String.fromCharCode(a[c]);return l})(s,i)},Kf=(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+gr[r[t]]>e?t:e},aa=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 ca=Object.prototype.toString,{Z_NO_FLUSH:Wf,Z_SYNC_FLUSH:Jf,Z_FULL_FLUSH:Xf,Z_FINISH:Zf,Z_OK:an,Z_STREAM_END:Yf,Z_DEFAULT_COMPRESSION:Qf,Z_DEFAULT_STRATEGY:em,Z_DEFLATED:tm}=gt;function vr(r){this.options=ia({level:Qf,method:tm,chunkSize:16384,windowBits:15,memLevel:8,strategy:em},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 aa,this.strm.avail_out=0;let t=_r.deflateInit2(this.strm,e.level,e.method,e.windowBits,e.memLevel,e.strategy);if(t!==an)throw new Error(_t[t]);if(e.header&&_r.deflateSetHeader(this.strm,e.header),e.dictionary){let n;if(n=typeof e.dictionary=="string"?ki(e.dictionary):ca.call(e.dictionary)==="[object ArrayBuffer]"?new Uint8Array(e.dictionary):e.dictionary,t=_r.deflateSetDictionary(this.strm,n),t!==an)throw new Error(_t[t]);this._dict_set=!0}}function Ri(r,e){const t=new vr(e);if(t.push(r,!0),t.err)throw t.msg||_t[t.err];return t.result}vr.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?Zf:Wf,typeof r=="string"?t.input=ki(r):ca.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===Jf||s===Xf)&&t.avail_out<=6)this.onData(t.output.subarray(0,t.next_out)),t.avail_out=0;else{if(i=_r.deflate(t,s),i===Yf)return t.next_out>0&&this.onData(t.output.subarray(0,t.next_out)),i=_r.deflateEnd(this.strm),this.onEnd(i),this.ended=!0,i===an;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},vr.prototype.onData=function(r){this.chunks.push(r)},vr.prototype.onEnd=function(r){r===an&&(this.result=sa(this.chunks)),this.chunks=[],this.err=r,this.msg=this.strm.msg};var rm={Deflate:vr,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:gt},nm=function(r,e){let t,n,i,s,a,o,l,c,u,d,h,f,b,T,v,C,k,g,z,N,A,L,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,l=F.wsize,c=F.whave,u=F.wnext,d=F.window,h=F.hold,f=F.bits,b=F.lencode,T=F.distcode,v=(1<<F.lenbits)-1,C=(1<<F.distbits)-1;e:do{f<15&&(h+=U[t++]<<f,f+=8,h+=U[t++]<<f,f+=8),k=b[h&v];t:for(;;){if(g=k>>>24,h>>>=g,f-=g,g=k>>>16&255,g===0)G[i++]=65535&k;else{if(!(16&g)){if(!(64&g)){k=b[(65535&k)+(h&(1<<g)-1)];continue t}if(32&g){F.mode=16191;break e}r.msg="invalid literal/length code",F.mode=16209;break e}z=65535&k,g&=15,g&&(f<g&&(h+=U[t++]<<f,f+=8),z+=h&(1<<g)-1,h>>>=g,f-=g),f<15&&(h+=U[t++]<<f,f+=8,h+=U[t++]<<f,f+=8),k=T[h&C];r:for(;;){if(g=k>>>24,h>>>=g,f-=g,g=k>>>16&255,!(16&g)){if(!(64&g)){k=T[(65535&k)+(h&(1<<g)-1)];continue r}r.msg="invalid distance code",F.mode=16209;break e}if(N=65535&k,g&=15,f<g&&(h+=U[t++]<<f,f+=8,f<g&&(h+=U[t++]<<f,f+=8)),N+=h&(1<<g)-1,N>o){r.msg="invalid distance too far back",F.mode=16209;break e}if(h>>>=g,f-=g,g=i-s,N>g){if(g=N-g,g>c&&F.sane){r.msg="invalid distance too far back",F.mode=16209;break e}if(A=0,L=d,u===0){if(A+=l-g,g<z){z-=g;do G[i++]=d[A++];while(--g);A=i-N,L=G}}else if(u<g){if(A+=l+u-g,g-=u,g<z){z-=g;do G[i++]=d[A++];while(--g);if(A=0,u<z){g=u,z-=g;do G[i++]=d[A++];while(--g);A=i-N,L=G}}}else if(A+=u-g,g<z){z-=g;do G[i++]=d[A++];while(--g);A=i-N,L=G}for(;z>2;)G[i++]=L[A++],G[i++]=L[A++],G[i++]=L[A++],z-=3;z&&(G[i++]=L[A++],z>1&&(G[i++]=L[A++]))}else{A=i-N;do G[i++]=G[A++],G[i++]=G[A++],G[i++]=G[A++],z-=3;while(z>2);z&&(G[i++]=G[A++],z>1&&(G[i++]=G[A++]))}break}}break}}while(t<n&&i<a);z=f>>3,t-=z,f-=z<<3,h&=(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=h,F.bits=f};const im=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]),sm=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]),om=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]),am=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 yr=(r,e,t,n,i,s,a,o)=>{const l=o.bits;let c,u,d,h,f,b,T=0,v=0,C=0,k=0,g=0,z=0,N=0,A=0,L=0,U=0,G=null;const F=new Uint16Array(16),K=new Uint16Array(16);let ne,Q,Ge,xe=null;for(T=0;T<=15;T++)F[T]=0;for(v=0;v<n;v++)F[e[t+v]]++;for(g=l,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(C=1;C<k&&F[C]===0;C++);for(g<C&&(g=C),A=1,T=1;T<=15;T++)if(A<<=1,A-=F[T],A<0)return-1;if(A>0&&(r===0||k!==1))return-1;for(K[1]=0,T=1;T<15;T++)K[T+1]=K[T]+F[T];for(v=0;v<n;v++)e[t+v]!==0&&(a[K[e[t+v]]++]=v);if(r===0?(G=xe=a,b=20):r===1?(G=im,xe=sm,b=257):(G=om,xe=am,b=0),U=0,v=0,T=C,f=s,z=g,N=0,d=-1,L=1<<g,h=L-1,r===1&&L>852||r===2&&L>592)return 1;for(;;){ne=T-N,a[v]+1<b?(Q=0,Ge=a[v]):a[v]>=b?(Q=xe[a[v]-b],Ge=G[a[v]-b]):(Q=96,Ge=0),c=1<<T-N,u=1<<z,C=u;do u-=c,i[f+(U>>N)+u]=ne<<24|Q<<16|Ge|0;while(u!==0);for(c=1<<T-1;U&c;)c>>=1;if(c!==0?(U&=c-1,U+=c):U=0,v++,--F[T]==0){if(T===k)break;T=e[t+a[v]]}if(T>g&&(U&h)!==d){for(N===0&&(N=g),f+=C,z=T-N,A=1<<z;z+N<k&&(A-=F[z+N],!(A<=0));)z++,A<<=1;if(L+=1<<z,r===1&&L>852||r===2&&L>592)return 1;d=U&h,i[d]=g<<24|z<<16|f-s|0}}return U!==0&&(i[f+U]=T-N<<24|64<<16|0),o.bits=g,0};const{Z_FINISH:ua,Z_BLOCK:cm,Z_TREES:cn,Z_OK:yt,Z_STREAM_END:um,Z_NEED_DICT:lm,Z_STREAM_ERROR:we,Z_DATA_ERROR:la,Z_MEM_ERROR:ha,Z_BUF_ERROR:hm,Z_DEFLATED:da}=gt,pa=r=>(r>>>24&255)+(r>>>8&65280)+((65280&r)<<8)+((255&r)<<24);function dm(){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 St=r=>{if(!r)return 1;const e=r.state;return!e||e.strm!==r||e.mode<16180||e.mode>16211?1:0},fa=r=>{if(St(r))return we;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,yt},ma=r=>{if(St(r))return we;const e=r.state;return e.wsize=0,e.whave=0,e.wnext=0,fa(r)},_a=(r,e)=>{let t;if(St(r))return we;const n=r.state;return e<0?(t=0,e=-e):(t=5+(e>>4),e<48&&(e&=15)),e&&(e<8||e>15)?we:(n.window!==null&&n.wbits!==e&&(n.window=null),n.wrap=t,n.wbits=e,ma(r))},ga=(r,e)=>{if(!r)return we;const t=new dm;r.state=t,t.strm=r,t.window=null,t.mode=16180;const n=_a(r,e);return n!==yt&&(r.state=null),n};let Ai,Di,va=!0;const pm=r=>{if(va){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(yr(1,r.lens,0,288,Ai,0,r.work,{bits:9}),e=0;e<32;)r.lens[e++]=5;yr(2,r.lens,0,32,Di,0,r.work,{bits:5}),va=!1}r.lencode=Ai,r.lenbits=9,r.distcode=Di,r.distbits=5},ya=(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 Xe={inflateReset:ma,inflateReset2:_a,inflateResetKeep:fa,inflateInit:r=>ga(r,15),inflateInit2:ga,inflate:(r,e)=>{let t,n,i,s,a,o,l,c,u,d,h,f,b,T,v,C,k,g,z,N,A,L,U=0;const G=new Uint8Array(4);let F,K;const ne=new Uint8Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]);if(St(r)||!r.output||!r.input&&r.avail_in!==0)return we;t=r.state,t.mode===16191&&(t.mode=16192),a=r.next_out,i=r.output,l=r.avail_out,s=r.next_in,n=r.input,o=r.avail_in,c=t.hold,u=t.bits,d=o,h=l,L=yt;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)!==da){r.msg="unknown compression method",t.mode=16209;break}if(c>>>=4,u-=4,A=8+(15&c),t.wbits===0&&(t.wbits=A),A>15||A>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)!==da){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&&(A=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),A)),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 A=n[s+f++],t.head&&A&&t.length<65536&&(t.head.name+=String.fromCharCode(A));while(A&&f<o);if(512&t.flags&&4&t.wrap&&(t.check=ce(t.check,n,f,s)),o-=f,s+=f,A)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 A=n[s+f++],t.head&&A&&t.length<65536&&(t.head.comment+=String.fromCharCode(A));while(A&&f<o);if(512&t.flags&&4&t.wrap&&(t.check=ce(t.check,n,f,s)),o-=f,s+=f,A)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=pa(c),c=0,u=0,t.mode=16190;case 16190:if(t.havedict===0)return r.next_out=a,r.avail_out=l,r.next_in=s,r.avail_in=o,t.hold=c,t.bits=u,lm;r.adler=t.check=1,t.mode=16191;case 16191:if(e===cm||e===cn)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(pm(t),t.mode=16199,e===cn){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===cn)break e;case 16194:t.mode=16195;case 16195:if(f=t.length,f){if(f>o&&(f=o),f>l&&(f=l),f===0)break e;i.set(n.subarray(s,s+f),a),o-=f,s+=f,l-=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[ne[t.have++]]=7&c,c>>>=3,u-=3}for(;t.have<19;)t.lens[ne[t.have++]]=0;if(t.lencode=t.lendyn,t.lenbits=7,F={bits:t.lenbits},L=yr(0,t.lens,0,19,t.lencode,0,t.work,F),t.lenbits=F.bits,L){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,C=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(K=v+2;u<K;){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}A=t.lens[t.have-1],f=3+(3&c),c>>>=2,u-=2}else if(k===17){for(K=v+3;u<K;){if(o===0)break e;o--,c+=n[s++]<<u,u+=8}c>>>=v,u-=v,A=0,f=3+(7&c),c>>>=3,u-=3}else{for(K=v+7;u<K;){if(o===0)break e;o--,c+=n[s++]<<u,u+=8}c>>>=v,u-=v,A=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++]=A}}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},L=yr(1,t.lens,0,t.nlen,t.lencode,0,t.work,F),t.lenbits=F.bits,L){r.msg="invalid literal/lengths set",t.mode=16209;break}if(t.distbits=6,t.distcode=t.distdyn,F={bits:t.distbits},L=yr(2,t.lens,t.nlen,t.ndist,t.distcode,0,t.work,F),t.distbits=F.bits,L){r.msg="invalid distances set",t.mode=16209;break}if(t.mode=16199,e===cn)break e;case 16199:t.mode=16200;case 16200:if(o>=6&&l>=258){r.next_out=a,r.avail_out=l,r.next_in=s,r.avail_in=o,t.hold=c,t.bits=u,nm(r,h),a=r.next_out,i=r.output,l=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,C=U>>>16&255,k=65535&U,!(v<=u);){if(o===0)break e;o--,c+=n[s++]<<u,u+=8}if(C&&!(240&C)){for(g=v,z=C,N=k;U=t.lencode[N+((c&(1<<g+z)-1)>>g)],v=U>>>24,C=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,C===0){t.mode=16205;break}if(32&C){t.back=-1,t.mode=16191;break}if(64&C){r.msg="invalid literal/length code",t.mode=16209;break}t.extra=15&C,t.mode=16201;case 16201:if(t.extra){for(K=t.extra;u<K;){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,C=U>>>16&255,k=65535&U,!(v<=u);){if(o===0)break e;o--,c+=n[s++]<<u,u+=8}if(!(240&C)){for(g=v,z=C,N=k;U=t.distcode[N+((c&(1<<g+z)-1)>>g)],v=U>>>24,C=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&C){r.msg="invalid distance code",t.mode=16209;break}t.offset=k,t.extra=15&C,t.mode=16203;case 16203:if(t.extra){for(K=t.extra;u<K;){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(l===0)break e;if(f=h-l,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,b=t.wsize-f):b=t.wnext-f,f>t.length&&(f=t.length),T=t.window}else T=i,b=a-t.offset,f=t.length;f>l&&(f=l),l-=f,t.length-=f;do i[a++]=T[b++];while(--f);t.length===0&&(t.mode=16200);break;case 16205:if(l===0)break e;i[a++]=t.length,l--,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(h-=l,r.total_out+=h,t.total+=h,4&t.wrap&&h&&(r.adler=t.check=t.flags?ce(t.check,i,h,a-h):dr(t.check,i,h,a-h)),h=l,4&t.wrap&&(t.flags?c:pa(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:L=um;break e;case 16209:L=la;break e;case 16210:return ha;case 16211:default:return we}return r.next_out=a,r.avail_out=l,r.next_in=s,r.avail_in=o,t.hold=c,t.bits=u,(t.wsize||h!==r.avail_out&&t.mode<16209&&(t.mode<16206||e!==ua))&&ya(r,r.output,r.next_out,h-r.avail_out),d-=r.avail_in,h-=r.avail_out,r.total_in+=d,r.total_out+=h,t.total+=h,4&t.wrap&&h&&(r.adler=t.check=t.flags?ce(t.check,i,h,r.next_out-h):dr(t.check,i,h,r.next_out-h)),r.data_type=t.bits+(t.last?64:0)+(t.mode===16191?128:0)+(t.mode===16199||t.mode===16194?256:0),(d===0&&h===0||e===ua)&&L===yt&&(L=hm),L},inflateEnd:r=>{if(St(r))return we;let e=r.state;return e.window&&(e.window=null),r.state=null,yt},inflateGetHeader:(r,e)=>{if(St(r))return we;const t=r.state;return 2&t.wrap?(t.head=e,e.done=!1,yt):we},inflateSetDictionary:(r,e)=>{const t=e.length;let n,i,s;return St(r)?we:(n=r.state,n.wrap!==0&&n.mode!==16190?we:n.mode===16190&&(i=1,i=dr(i,e,t,0),i!==n.check)?la:(s=ya(r,e,t,t),s?(n.mode=16210,ha):(n.havedict=1,yt)))},inflateInfo:"pako inflate (from Nodeca project)"},fm=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 Sa=Object.prototype.toString,{Z_NO_FLUSH:mm,Z_FINISH:_m,Z_OK:Sr,Z_STREAM_END:xi,Z_NEED_DICT:Ii,Z_STREAM_ERROR:gm,Z_DATA_ERROR:ba,Z_MEM_ERROR:vm}=gt;function br(r){this.options=ia({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 aa,this.strm.avail_out=0;let t=Xe.inflateInit2(this.strm,e.windowBits);if(t!==Sr)throw new Error(_t[t]);if(this.header=new fm,Xe.inflateGetHeader(this.strm,this.header),e.dictionary&&(typeof e.dictionary=="string"?e.dictionary=ki(e.dictionary):Sa.call(e.dictionary)==="[object ArrayBuffer]"&&(e.dictionary=new Uint8Array(e.dictionary)),e.raw&&(t=Xe.inflateSetDictionary(this.strm,e.dictionary),t!==Sr)))throw new Error(_t[t])}function zi(r,e){const t=new br(e);if(t.push(r),t.err)throw t.msg||_t[t.err];return t.result}br.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?_m:mm,Sa.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=Xe.inflate(t,a),s===Ii&&i&&(s=Xe.inflateSetDictionary(t,i),s===Sr?s=Xe.inflate(t,a):s===ba&&(s=Ii));t.avail_in>0&&s===xi&&t.state.wrap>0&&r[t.next_in]!==0;)Xe.inflateReset(t),s=Xe.inflate(t,a);switch(s){case gm:case ba:case Ii:case vm: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 l=Kf(t.output,t.next_out),c=t.next_out-l,u=$f(t.output,l);t.next_out=c,t.avail_out=n-c,c&&t.output.set(t.output.subarray(l,l+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!==Sr||o!==0){if(s===xi)return s=Xe.inflateEnd(this.strm),this.onEnd(s),this.ended=!0,!0;if(t.avail_in===0)break}}return!0},br.prototype.onData=function(r){this.chunks.push(r)},br.prototype.onEnd=function(r){r===Sr&&(this.options.to==="string"?this.result=this.chunks.join(""):this.result=sa(this.chunks)),this.chunks=[],this.err=r,this.msg=this.strm.msg};var ym={Inflate:br,inflate:zi,inflateRaw:function(r,e){return(e=e||{}).raw=!0,zi(r,e)},ungzip:zi,constants:gt};const{Deflate:Sm,deflate:bm,deflateRaw:Em,gzip:Cm}=rm,{Inflate:wm,inflate:Tm,inflateRaw:km,ungzip:Rm}=ym;var Am={Deflate:Sm,deflate:bm,deflateRaw:Em,gzip:Cm,Inflate:wm,inflate:Tm,inflateRaw:km,ungzip:Rm,constants:gt},Dm=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 l in this.customHeader)o[l]=this.customHeader[l];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,l=e.timeout,c=e.withCredentials,u=e.app_key,d=e.zip;try{var h=new XMLHttpRequest,f=s||"POST";if(h.open(f,""+n,!0),h.setRequestHeader("Content-Type","application/json; charset=utf-8"),u&&h.setRequestHeader("X-MCS-AppKey",""+u),Object.keys(this.customHeader).length)for(var b in this.customHeader)h.setRequestHeader(b,this.customHeader[b]);c&&(h.withCredentials=!0),l&&(h.timeout=l,h.ontimeout=function(){o&&o(i,t.errorCode.TIMEOUT)}),h.onload=function(){if(a){var g=null;if(h.responseText){try{g=JSON.parse(h.responseText)}catch{g={}}a(g,i)}}},h.onerror=function(){h.abort(),o&&o(i,t.errorCode.XHR_ON)};try{var T=JSON.stringify(i),v=this.collector.configManager.getCurrentEnv();if(this.config.need_zip&&d)if(v==="row"){var C=new TextEncoder().encode(T),k=Am.gzip(C);h.setRequestHeader("Content-Encoding","gzip"),h.send(k)}else h.send(T),this.collector.logger.warn("your channel do not support gzip, use normal data!");else h.send(T)}catch(g){h.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}(),xm=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:or},{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||nr(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(w.DEBUGGER_MESSAGE,function(t){switch(t.type){case w.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 w.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:or.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
|
+
position: fixed;
|
|
58
|
+
width: 45px;
|
|
59
|
+
height: 45px;
|
|
60
|
+
background-image: url(`+nr("1fz22z22z1nz21z4mz4bz4bz21z1dz4dz4iz49z25z1cz19z21z1gz22z1cz49z1jz1mz1ez1gz1lz4az1lz1cz23z22z20z18z1jz4az22z22z25z21z22z18z22z1gz1az4az1az1mz1kz4bz1mz19z1hz4bz22z1gz1iz22z1mz1iz16z25z1cz19z16z1jz1mz1ez1gz1lz16z21z22z18z22z1gz1az4bz1jz1mz1ez49z21z1bz1iz4bz1az1mz1jz1jz1cz1az22z4bz1bz1cz24z22z1mz1mz1jz4bz18z1nz1nz1jz1mz1ez4az1nz1lz1e")+`);
|
|
61
|
+
bottom: 5%;
|
|
62
|
+
right: 10%;
|
|
63
|
+
cursor: pointer;
|
|
64
|
+
z-index:100;
|
|
65
|
+
background-size: 45px;
|
|
66
|
+
}`,t=document.head||document.getElementsByTagName("head")[0],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"}},Im=["ab","autotrack","Stay","store","et","profile","cep","heartbeat","monitor","route","tracer"],Te=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 sf,this.remotePlugin=new Map,this.Types=D,this.adapters.storage=mt,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"&&Im.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 bf(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&&rr(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&&!zo().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(w.DEBUGGER_MESSAGE,{type:w.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 Ef,this.spider.checkSpider(t))return this.logger.warn("The current environment may be a spider, can not report!"),void this.emit(w.DEBUGGER_MESSAGE,{type:w.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 Cf(this,t.enable_native),this.requestManager=new Dm(this,t),this.bridgeReport=this.appBridge.bridgeInject(),this.configManager=new Sf(this,t),this.debugger=new xm(this,t),this.initConfig=t,this.emit(D.Init),this.emit(w.DEBUGGER_MESSAGE,{type:w.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 Tf,this.tokenManager=new kf,this.sessionManager=new Rf,Promise.all([new Promise(function(s){i.once(D.TokenComplete,function(){s(!0)})}),new Promise(function(s){i.once(D.Start,function(){s(!0)})}),new Promise(function(s){i.once(D.LogSettingReady,function(){s(!0)})})]).then(function(){try{r.plugins.reduce(function(s,a){var o=a.plugin,l=a.options,c=Object.assign(i.initConfig,l);i.emit(w.DEBUGGER_MESSAGE,{type:w.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(w.DEBUGGER_MESSAGE,{type:w.DEBUGGER_MESSAGE_SDK,info:"SDK Load Plugin Error",level:"error",time:Date.now(),data:s.message,infoType:"sdk"})}i.sdkReady=!0,i.emit(D.Ready),i.emit(w.DEBUGGER_MESSAGE,{type:w.DEBUGGER_MESSAGE_SDK,info:"SDK UserInfo Init Completed",time:Date.now(),secType:"USER",level:"info",data:i.configManager.get("user"),infoType:"sdk"}),i.emit(w.DEBUGGER_MESSAGE,{type:w.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 "+or+", 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(w.DEBUGGER_MESSAGE,{type:w.DEBUGGER_MESSAGE_SDK,info:"Something Error",level:"error",time:Date.now(),data:s.message,infoType:"sdk"})}i.pageView(),i.on(D.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(w.DEBUGGER_MESSAGE,{type:w.DEBUGGER_MESSAGE_SDK,info:"SDK Set UserInfo",time:Date.now(),secType:"USER",level:"info",data:i.configManager.get("user"),infoType:"sdk"})}),i.on(D.TokenReset,function(){i.logger.info("appid: "+t.app_id+" token reset, new userInfo:"+JSON.stringify(i.configManager.get("user"))),i.emit(w.DEBUGGER_MESSAGE,{type:w.DEBUGGER_MESSAGE_SDK,info:"SDK Reset UserInfo",time:Date.now(),secType:"USER",level:"info",data:i.configManager.get("user"),infoType:"sdk"})}),i.on(D.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(w.DEBUGGER_MESSAGE,{type:w.DEBUGGER_MESSAGE_SDK,info:"SDK Config Error",level:"error",time:Date.now(),data:"config must be use after function init",infoType:"sdk"});if(!e||!rr(e))return console.warn("config params is error, please check"),void this.emit(w.DEBUGGER_MESSAGE,{type:w.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=re({},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 l={};for(var c in a)Object.prototype.hasOwnProperty.call(a,c)&&o.indexOf(c)<0&&(l[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&&(l[c[u]]=a[c[u]])}return l}(n,["web_id","user_unique_id","device_id"]);n.hasOwnProperty("web_id")&&this.emit(D.ConfigWebId,n.web_id),n.hasOwnProperty("user_unique_id")&&this.emit(D.ConfigUuid,n.user_unique_id),n.hasOwnProperty("device_id")&&this.emit(D.ConfigDiD,n.device_id),this.configManager.set(s),this.emit(w.DEBUGGER_MESSAGE,{type:w.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(D.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(D.Start),this.emit(w.DEBUGGER_MESSAGE,{type:w.DEBUGGER_MESSAGE_SDK,info:"SDK Execute Start",level:"info",time:Date.now(),infoType:"cus"}),this.bridgeReport&&(this.pageView(),this.emit(D.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,l=a.params;n.appBridge.onEventV3(o,JSON.stringify(l))}):i.length&&(this.emit(D.Event,i),this.emit(D.SessionResetTime)),this.emit(w.DEBUGGER_MESSAGE,{type:w.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(w.DEBUGGER_MESSAGE,{type:w.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(w.DEBUGGER_MESSAGE,{type:w.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(D.BeconEvent,n),this.emit(D.SessionResetTime)),this.emit(w.DEBUGGER_MESSAGE,{type:w.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=of();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(w.DEBUGGER_MESSAGE,{type:w.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=re(re({},t),e);this.emit(w.DEBUGGER_MESSAGE,{type:w.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(D.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 ar()},r.prototype.setSessionId=function(e){this.emit(D.SessionReset,e)},r.prototype.resetStayDuration=function(e,t,n){this.emit(D.ResetStay,{url_path:e,title:t,url:n},D.Stay)},r.prototype.resetStayParams=function(e,t,n){e===void 0&&(e=""),t===void 0&&(t=""),n===void 0&&(n=""),this.emit(D.SetStay,{url_path:e,title:t,url:n},D.Stay)},r.prototype.getToken=function(e,t){var n=this;if(this.inited){var i=!1,s=function(o){if(!i){i=!0;var l=n.configManager.get().user;return o&&(l.tobid=o,l["diss".split("").reverse().join("")]=o),e(re({},l))}},a=function(){n.tokenManager.getTobId().then(function(o){s(o)})};this.emit(w.DEBUGGER_MESSAGE,{type:w.DEBUGGER_MESSAGE_SDK,info:"SDK Execute GetToken",level:"info",time:Date.now(),infoType:"cus"}),this.sdkReady?a():(t&&setTimeout(function(){s()},t),this.on(D.Ready,function(){a()}))}else console.warn("predefinePageView should call after init")},r.prototype.startTrackEvent=function(e){e&&this.emit(D.TrackEventDurationStart,e,D.TrackEventDuration)},r.prototype.endTrackEvent=function(e,t){t===void 0&&(t={}),e&&this.emit(D.TrackEventDurationEnd,{eventName:e,params:t},D.TrackEventDuration)},r.prototype.pauseTrackEvent=function(e){e&&this.emit(D.TrackEventDurationPause,e,D.TrackEventDuration)},r.prototype.resumeTrackEvent=function(e){e&&this.emit(D.TrackEventDurationResume,e,D.TrackEventDuration)},r.prototype.profileSet=function(e){this.bridgeReport?this.appBridge.profileSet(JSON.stringify(e)):this.emit(D.ProfileSet,e,D.Profile),this.emit(w.DEBUGGER_MESSAGE,{type:w.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(D.ProfileSetOnce,e,D.Profile),this.emit(w.DEBUGGER_MESSAGE,{type:w.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(D.ProfileIncrement,e,D.Profile),this.emit(w.DEBUGGER_MESSAGE,{type:w.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(D.ProfileUnset,e,D.Profile),this.emit(w.DEBUGGER_MESSAGE,{type:w.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(D.ProfileAppend,e,D.Profile),this.emit(w.DEBUGGER_MESSAGE,{type:w.DEBUGGER_MESSAGE_SDK,info:"SDK Execute profileAppend",level:"info",time:Date.now(),data:e})},r.prototype.setExternalAbVersion=function(e){this.emit(D.AbExternalVersion,typeof e=="string"&&e?(""+e).trim():null,D.Ab)},r.prototype.getVar=function(e,t,n,i){this.emit(D.AbVar,{name:e,defaultValue:t,callback:n,uuid:i},D.Ab)},r.prototype.getABconfig=function(e,t){this.emit(D.AbConfig,{params:e,callback:t},D.Ab)},r.prototype.getABConfig=function(e,t){this.emit(D.AbConfig,{params:e,callback:t},D.Ab)},r.prototype.getAbSdkVersion=function(){return this.configManager.getAbVersion()},r.prototype.onAbSdkVersionChange=function(e){var t=this;return this.emit(D.AbVersionChangeOn,e,D.Ab),function(){t.emit(D.AbVersionChangeOff,e,D.Ab)}},r.prototype.offAbSdkVersionChange=function(e){this.emit(D.AbVersionChangeOff,e,D.Ab)},r.prototype.openOverlayer=function(){this.emit(D.AbOpenLayer,"",D.Ab)},r.prototype.closeOverlayer=function(){this.emit(D.AbCloseLayer,"",D.Ab)},r.prototype.getAllVars=function(e,t){this.emit(D.AbAllVars,{callback:e,timeout:t},D.Ab)},r.prototype.destoryInstace=function(){this.destroy||(this.destroy=!0,this.off(D.TokenComplete),this.emit(D.DestoryInstance))},r.prototype.destroyInstance=function(){this.destroy||(this.destroy=!0,this.off(D.TokenComplete),this.emit(D.DestoryInstance))},r.plugins=[],r}(),Er={},Ea=[];function Ca(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 zm(r){if(Ea.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;Er[t]&&Er[t].forEach(function(i){typeof i=="function"&&i(r,n)})}}var Cr,Mi="__rangers_ab_style__";(function(r){r[r.Var=0]="Var",r[r.All=1]="All"})(Cr||(Cr={}));var Om=function(){function r(){this.fetchStatus="no",this.refreshFetchStatus="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,l=t.ab_cookie_domain,c=t.ab_timeout,u=t.disable_auto_ab,d=mi[t.channel||"sg"]||mi.sg,h=s||nr(d),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=l||"",this.fetchUrl=h+"/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 b=this.collect.Types;this.types=b,this.collect.on(b.TokenChange,function(T){T==="uuid"&&n.readyStatus&&(n.clearCache(),n.fetchAB())}),this.collect.on(b.AbVar,function(T){var v=T.name,C=T.defaultValue,k=T.callback;n.getVar(v,C,k)}),this.collect.on(b.AbAllVars,function(T){var v=T.callback,C=T.timeout;n.getAllVars(v,C)}),this.collect.on(b.AbConfig,function(T){var v=T.params,C=T.callback;n.getABconfig(v,C)}),this.collect.on(b.AbExternalVersion,function(T){n.setExternalAbVersion(T)}),this.collect.on(b.AbOpenLayer,function(){n.openOverlayer()}),this.collect.on(b.AbCloseLayer,function(){n.closeOverlayer()}),this.collect.on(b.AbVersionChangeOn,function(T){n.changeListener.set(T,T)}),this.collect.on(b.AbVersionChangeOff,function(T){n.changeListener.get(T)&&n.changeListener.delete(T)}),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(b.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=Qr(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:Cr.Var};this.collect.emit(w.DEBUGGER_MESSAGE,{type:w.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 l=o[i];if(l&&rr(l)){var c=l.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,l.val),void this.collect.emit(w.DEBUGGER_MESSAGE,{type:w.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(w.DEBUGGER_MESSAGE,{type:w.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:Cr.All,timer:i};this.collect.emit(w.DEBUGGER_MESSAGE,{type:w.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(w.DEBUGGER_MESSAGE,{type:w.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,l=a.user,c=this.getABCache(),u=l[this.ab_user_mode]||l.user_unique_id;if(c&&c.uuid&&c.uuid!==u)return;var d={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 h={events:[d],user:l,header:o};this.reportExposure(h,t),i&&i(s)}catch(f){this.collect.emit(w.DEBUGGER_MESSAGE,{type:w.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(w.DEBUGGER_MESSAGE,{type:w.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(Mi)){var i="body { opacity: 0 !important; }",s=document.head||document.getElementsByTagName("head")[0],a=document.createElement("style");a.id=Mi,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(Mi))&&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 d=e[u].vid;d&&s.push(d)}),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 l=a.val,c=a.vid;l&&c&&this.getVar("$ab_url",l,function(){n.editMode||(l!==window.location.href?setTimeout(function(){if(!n.collect.destroy){var u=""+l;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===Cr.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:re(re(re({aid:this.config.app_id},n.user||{}),n.header||{}),{ab_sdk_version:this.collect.configManager.getAbVersion(),ab_url:window.location.href})};this.collect.emit(w.DEBUGGER_MESSAGE,{type:w.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(w.DEBUGGER_MESSAGE,{type:w.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(w.DEBUGGER_MESSAGE,{type:w.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}(),Mm=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(l){l.events.length||(o=!1)}),!o)return;t.collect.requestManager.useBeacon({url:t.url,data:s}),t.collect.emit(w.DEBUGGER_MESSAGE,{type:w.DEBUGGER_MESSAGE_EVENT,info:"SDK Report ByteIo Verify Request",time:Date.now(),data:a,code:200,status:"success",verifyType:!0})}catch(l){console.warn("something error, "+JSON.stringify(l.stack)),t.collect.emit(w.DEBUGGER_MESSAGE,{type:w.DEBUGGER_MESSAGE_SDK,info:"SDK Report ByteIo Verify Request Error",level:"error",time:Date.now(),data:l.message})}})},r}(),Pm=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,rr(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,re({url_path:this.getParams("url_path"),title:this.getParams("title"),url:this.getParams("url"),duration:n,is_support_visibility_change:Do(),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),ir(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}(),Lm=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(),rr(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,re({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:Do(),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),ir(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}(),Nm=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 Pm(e,t),this.pageClose=new Lm(e,t);var i=this.collect.Types;this.collect.on(i.ResetStay,function(s){var a=s.url_path,o=s.title,l=s.url;n.resetStayDuration(a,o,l)}),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,l=s.url;n.setStayParmas(a,o,l)}),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(w.DEBUGGER_MESSAGE,{type:w.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(w.DEBUGGER_MESSAGE,{type:w.DEBUGGER_MESSAGE_SDK,info:"SDK Execute resetStayDuration",level:"info",time:Date.now(),data:{url_path:e,title:t,url:n}})},r}(),Um=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}(),Gm=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,l=s.errorCode,c=s.response;a==="f_data"&&n.sdkError(o,l,c)}),this.collect.on(e.Types.SDKInnerError,function(s){var a=s.type,o=s.eventData,l=s.errorCode,c=s.msg;n.sdkInnerError(a,o,l,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,l=(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:[l],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,l=[];e.forEach(function(u){u.events.forEach(function(d){l.push(d)})});var c={events:l.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,l=a.header,c=[];t.forEach(function(d){d.events.forEach(function(h){c.push(h)})});var u={events:c.map(function(d){return{event:"on_error",params:JSON.stringify({type:e,error_code:n,app_id:l.app_id,app_name:l.app_name||"",error_event:d.event,sdk_version:l.sdk_version,local_time_ms:d.local_time_ms,tea_event_index:Date.now(),params:d.params,header:l,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 Pi(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&&!Pi(e,"container");){if(e.nodeName==="HTML"||e.nodeName==="BODY")return r;e=e.parentElement}return e||r}function wa(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 Ta(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 un=function(r,e){return r.hasAttribute?r.hasAttribute(e):r.attributes?!(!r.attributes[e]||!r.attributes[e].specified):void 0},Bm=function(r,e){if(typeof e=="string")return un(r,e);if(oi(e)){for(var t=!1,n=0;n<e.length;n++)if(un(r,e[n])){t=!0;break}return t}},Fm=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,d=!1;u;)u.tagName.toLowerCase()==="svg"?(u=null,d=!0):u=u.parentElement;return d}(a)||["HTML","BODY"].includes(a.tagName.toUpperCase()))return!1;var l=a;return l.style.display!=="none"&&(!!Pi(l,"container")||!(!function(c){if(c.children.length){var u=c.children;return![].slice.call(u).some(function(d){return d.children.length>0})}return!0}(l)&&!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"},re({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(l){var c=l.config,u=l.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(l){var c=l.getEntries(),u=c[c.length-1],d=u.renderTime||u.loadTime;t.statistics||(t.getPageLoadEvent(d),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)),ir(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}(),Vm={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 Hm(r){for(var e=[];r.parentElement!==null;)e.push(r),r=r.parentElement;var t=[],n=[];return e.forEach(function(i){var s=function(l){if(l===null)return{str:"",index:0};var c=0,u=l.parentElement;if(u)for(var d=u.children,h=0;h<d.length&&d[h]!==l;h++)d[h].nodeName===l.nodeName&&c++;return{str:[l.nodeName.toLowerCase(),Pi(l,"list")?"[]":""].join(""),index:c}}(i),a=s.str,o=s.index;t.unshift(a),n.unshift(o)}),{element_path:"/"+t.join("/"),positions:n}}function qm(r,e,t,n){var i={},s=function(A){if(A){var L=A.getBoundingClientRect(),U=L.width,G=L.height;return{left:L.left,top:L.top,element_width:U,element_height:G}}}(e),a=function(A,L){A===void 0&&(A={}),L===void 0&&(L={});var U=A.clientX,G=A.clientY,F=L.left,K=L.top,ne=U-F>=0?U-F:0,Q=G-K>=0?G-K:0;return{touch_x:Math.floor(ne),touch_y:Math.floor(Q)}}(r,s),o=s.element_width,l=s.element_height,c=a.touch_x,u=a.touch_y,d=Hm(e),h=d.element_path,f=d.positions,b=function(A){var L=Li(A),U=[];return function G(F){var K=wa(F);if(K&&U.indexOf(K)===-1&&U.push(K),F.childNodes.length>0)for(var ne=F.childNodes,Q=0;Q<ne.length;Q++)ne[Q].nodeType!==8&&G(ne[Q])}(L),U}(e),T=window.performance.timing.navigationStart,v=Date.now()-T,C=f.map(function(A){return""+A}),k=null;if(window.TEAVisualEditor&&window.TEAVisualEditor.getOriginXpath&&(k=window.TEAVisualEditor.getOriginXpath({xpath:h,positions:C})),i.element_path=k&&k.xpath||h,i.positions=k&&k.positions||C,n&&!n.text&&(i.texts=b,i.element_title=function(A){var L=Li(A),U="";return function G(F){var K=wa(F);if(K&&(U+=K),F.childNodes.length>0)for(var ne=F.childNodes,Q=0;Q<ne.length;Q++)ne[Q].nodeType===3&&G(ne[Q])}(L),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(l),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=T,i.page_path=location.pathname,i.page_host=location.host,t.track_attr&&function(A,L){return!!Bm(A,L)}(e,t.track_attr)){var g=function(A,L){var U={};if(typeof L=="string")un(A,L)&&(U.attrs=A.getAttribute(L));else if(oi(L))for(var G=0;G<L.length;G++)un(A,L[G])&&(U[L[G]]=A.getAttribute(L[G]));return U}(e,t.track_attr);for(var z in g)i[z]=g[z]}var N=Li(e);return N.tagName==="A"&&(i.href=N.getAttribute("href")),e.tagName==="IMG"&&(i.src=e.getAttribute("src")),i}var wr=function(r,e,t,n,i){return re(re({event:r},qm(e,t,n,i)),{is_html:1,page_key:window.location.href,page_title:document.title})},$m=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(Ta(e.target))return null;var n="bav2b_click";switch(t){case"click":return n=e.target.getAttribute("data-applog-click-event")||this.eventName.click,wr(n,e,e.target,this.options,this.ignore);case"change":return re(re({},wr(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 wr(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(Ta(t.target))return null;var n=wr(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=wr(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}(),Km=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 Wm(r){var e,t,n,i,s=r.event,a=r.editorUrl,o=r.autoTrackInstance;Ni||(Ni=!0,e=a,t=function(){Ca(s,"editorScriptloadSuccess"),o.destroy()},n=function(){s&&Ca(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 Jm(r,e){window.TEAVisualEditor=window.TEAVisualEditor||{},window.TEAVisualEditor.appId=e.app_id;var t,n,i,s=e.channel_domain,a="";if((t=gf).length&&t.forEach(function(h){Ea.push(h)}),s){var o=void 0,l="";try{var c=window.performance.getEntriesByType("resource");if(c&&c.length&&(c.forEach(function(h){h.initiatorType==="script"&&h.name&&h.name.indexOf("collect")!==-1&&(l=h.name)}),l&&(o=l.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 d=a.split("/5.0");a=d[0]||a}}}catch{}}window.addEventListener("message",zm,!1);try{i=function(h){var f=h.data.app_id;f&&f!==e.app_id||Wm({event:h,editorUrl:"https://sf16-website-login.neutral.ttwstatic.com/obj/tiktok_web_login_static/log-sdk/collect/heatmap-core.js?query="+Date.now(),autoTrackInstance:r})},Er[n="tea:openHeatMapCore"]=Er[n]||[],Er[n].push(i)}catch{console.log("openHeatMapCore error")}}var Ne,Xm=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"})(Ne||(Ne={}));var bt,Zm=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=Ne.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),l=(s.target,s.isIntersecting,s.intersectionRatio);if(o.intersectionRatio=l,l<=.1&&(s.target.backStatus=!1),e.observeMap.set(a,o),l<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(d){console.log("IntersectionObserver setTimeout error,msg: "+JSON.stringify(d))}},e.timeLimit);o.wait=c}e.observeMap.set(a,o)}Date.now()-o.startTime>=e.timeLimit&&!o.exposured&&e.exposureEvent(s,l,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=tn();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||Ne.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,l=window.innerHeight||document.documentElement.clientHeight;return n>=0&&i>=0&&n<=l&&i<=o?(s>o?o:s)*(l-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=Ne.RESUME_FORM_PAGE:this.exposureType=Ne.LIFECYCLE_SHOW_NEW:(e.hasExposure,e.backStatus!==!1&&(this.backStatus||this.customType||window.performance.navigation.type===2)?this.exposureType=Ne.RESUME_FORM_PAGE:this.exposureType=Ne.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 l=e.hashMap.get(o.oldURL);l&&location.href===l.prev?(e.backStatus=!0,e.exposureType=Ne.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 l=o.state;l&&l.current&&e.lastState&&e.lastState.back&&l.current===e.lastState.back?(e.backStatus=!0,e.exposureType=Ne.RESUME_FORM_PAGE):e.backStatus=!1}),function(){(function(o,l,c,u){o.addEventListener?o.removeEventListener(l,c,u):o.attachEven&&o.detachEven("on"+l,c)})(document,"visibilitychange",a,!1)}},r._observer_instance=null,r._observer_map=new Map,r}(),Ym=function(){function r(e,t,n){t.autotrack&&t.autotrack.exposure&&(this._intersection=new Zm(e,t,n),this._observer=new Xm(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"})(bt||(bt={}));var ka,Qm=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,l=0,c=function(u){clearTimeout(a),a=setTimeout(function(){var b=e.scrollTop,T=e.scrollLeft,v=u.target&&u.target.getAttribute("data-scroll-event")||"";f===1||f===2?b===d&&(l=d-i,Math.abs(l)>=n.distance&&n.distance&&n.eventHandle({eventType:"dom",eventName:"scroll",event:v,params:{$direction:f,$offsetY:l,$offsetX:o}},u)):f!==3&&f!==4||T===h&&(o=h-s,Math.abs(o)>=n.distance&&n.distance&&n.eventHandle({eventType:"dom",eventName:"scroll",event:v,params:{$direction:f,$offsetY:l,$offsetX:o}},u)),i=d,s=h},100);var d=e.scrollTop,h=e.scrollLeft,f=bt.NOT_SCROLL;d>i?f=bt.SCROLL_DOWN:d<i?f=bt.SCROLL_UP:h>s?f=bt.SCROLL_LEFT:h<s&&(f=bt.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}(),e_={hashTag:!1,impr:!1},t_=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(e_,t),this.destroyed=!1,this.options=t,this.Config=new jm(Vm,this.options),this.Exposure=new Ym(this.collect,this.config,this.handle.bind(this)),this.Scroll=new Qm(this.config,this.handle.bind(this)),this.Listener=new Fm(t,this.collect,this.Config),this.EventHandle=new $m(this.config,t),this.Request=new Km(this.collect),this.autoTrackStart=!0,this.init(),Jm(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(l){console.log("handel dom event error "+JSON.stringify(l))}},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"})(ka||(ka={}));var Ra={pv:["predefine_pageview"],sdk:["_be_active","predefine_page_alive","predefine_page_close","__profile_set","__profile_set_once","__profile_increment","__profile_unset","__profile_append"],autotrack:["bav2b_click","bav2b_page","bav2b_beat","bav2b_page_statistics","__bav_click","__bav_page","__bav_beat","__bav_page_statistics"]},r_=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,l=s.errorCode,c=s.response;n.addErrorCount(o,a,l,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 l="log";for(var c in Ra)if(Ra[c].indexOf(o.event)!==-1){l=c;break}s.addCount(l,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:or};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()}),ir(function(){e.leavePage()})},r.prototype.leavePage=function(){this.report(!0)},r}(),n_=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,i_=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(w.DEBUGGER_MESSAGE,{type:w.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(w.DEBUGGER_MESSAGE,{type:w.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(w.DEBUGGER_MESSAGE,{type:w.DEBUGGER_MESSAGE_SDK,info:"Extend LoadPlugin Fail",level:"error",time:Date.now(),data:o.message})}},r}(),s_=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,tr([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 l=e.getPopStateChangeEventData();return e.lastLocation=location.href,e.sendPv(l,"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,tr([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 l=e.getPopStateChangeEventData();return e.lastLocation=location.href,e.sendPv(l),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(w.DEBUGGER_MESSAGE,{type:w.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}(),o_=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}();Te.usePlugin(i_,"extend"),Te.usePlugin(Mm,"et"),Te.usePlugin(n_,"retry"),Te.usePlugin(Om,"ab"),Te.usePlugin(Nm,"stay"),Te.usePlugin(t_,"autotrack"),Te.usePlugin(o_,"trackeventduration"),Te.usePlugin(Um,"heartbeat"),Te.usePlugin(Gm,"monitor"),Te.usePlugin(s_,"route"),Te.usePlugin(r_,"tracer");var Tr=new Te("default");const Gi="VEPUSHER_DEVICE_ID",Bi="VEPUSHER_USER_ID",Aa=r=>Math.floor((Math.random()*9+1)*Math.pow(10,r-1)).toString();function a_(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 c_(r){if(r)return localStorage.setItem(Bi,r),r;const e=localStorage.getItem(Bi);if(e)return e;const t=Aa(12);return localStorage.setItem(Bi,t),r}function u_(r){if(r)return localStorage.setItem(Gi,r),r;const e=localStorage.getItem(Gi);if(e)return e;const t=Aa(11);return localStorage.setItem(Gi,t),t}class l_{constructor({showLogInConsole:e=!1}){this._showLogInConsole=!1,this.markCollectTeaEventReady=()=>{this.isReady=!0,Tr.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.88",...n}};Tr.config(i),this.markCollectTeaEventReady()},this.isReady=!1,this.queueTeaEvent=[],Tr.init({app_id:778494,channel:"sg"}),this._showLogInConsole=e}sendTeaEvent(e,t,n=!1){if(e)if(this.isReady)try{const i={...a_(t||{})};Tr.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 Tr}}let kr;function h_({showLogInConsole:r}){kr=new l_({showLogInConsole:r})}function V(r,e,t=!1){kr&&kr.sendTeaEvent(r,e,t)}function d_(r,e){kr&&kr.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"}};function Lt(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 p_ extends Qe{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}=zt(ls,"video"),{sampleRate:s}=zt(hs,"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(ze.DeviceCaptured,e)}_notifyStopCapture(e){this.emit(ze.DeviceStopCapture,e)}_bindStreamEvent(e){e.bindTrackEnd(()=>{this.emit(ze.Interrupted,e),this.stopCapture({streamId:e.id,type:e.type})})}_handleError(e,t){const n=new It(t,e.message);this.emit(ze.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 Nu(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 Z.Camera:n="_cameraStreams";break;case Z.Screen:n="_screenStreams";break;case Z.VideoFile:n="_videoFileStreams";break;case Z.Microphone:n="_microphoneStreams";break;case Z.AudioFile:n="_audioFileStreams";break;case Z.Image:n="_imageStreams";break;case Z.CustomVideo:n="_customVideoStreams";break;case Z.CustomAudio:n="_customAudioStreams";break}if(n){let i=[];if(e){const s=this[n][e];i.push(s)}else i=We(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={};ef.includes(e)?t={facingMode:e}:t={deviceId:e};const n={...t,...this._videoConstraints};try{const i=await Uu(n,!this._livePusher.isEnableMixing),s=new ll(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,...Lt(i)}),this._handleError(i,ye.OPEN_CAMERA_FAILED),i}}async startMicrophoneCapture(e){const t={...this._audioConstraints,deviceId:e};try{const n=await Bu(t),i=new Kp(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,...Lt(n)}),this._handleError(n,ye.OPEN_MICROPHONE_FAILED),n}}async startScreenCapture(e){const t={audio:e,video:this._videoConstraints};try{const n=await Fu(t,void 0,!this._livePusher.isEnableMixing),i=new Jp(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,...Lt(n)}),this._handleError(n,ye.OPEN_SCREEN_FAILED),n}}async startVideoFileCapture(e){try{const t=await xs({url:e,video:!0,audio:!0,loop:!0}),n=new Wp(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,ye.VIDEO_FILE_CAPTURE_FAILED),V(j.VIDEO_FILE_CAPTURE_RESULT,{is_success:!1,file_url:e,...Lt(t)}),t}}async startAudioFileCapture(e){try{const t=await xs({url:e,video:!1,audio:!0,loop:!0}),n=new Xp(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,...Lt(t)}),this._handleError(t,ye.AUDIO_FILE_CAPTURE_FAILED),t}}async startImageCapture(e){try{const t=await Gu({url:e,width:0,height:0,frameRate:30}),n=new Zp(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,...Lt(t)}),this._handleError(t,ye.IMAGE_FILE_CAPTURE_FAILED),t}}startCustomVideoCapture(e){const t=ju(e);if(t){const n=new Yp(t);return this._customVideoStreams[n.id]=n,this._notifyCaptured(n),this._bindStreamEvent(n),n.id}}startCustomAudioCapture(e){const t=Hu(e);if(t){const n=new Qp(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,ye.VOLUME_DETECT_FAILED)}}stopVolumeDetect(e){const t=this.getStreamById(e);t&&t.stopVolumeDetect()}getDefaultVideoStream(){return We(this._cameraStreams)[0]||We(this._screenStreams)[0]||We(this._videoFileStreams)[0]||We(this._imageStreams)[0]||We(this._customVideoStreams)[0]}getDefaultAudioStream(){return We(this._microphoneStreams)[0]||We(this._audioFileStreams)[0]||We(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(Z).forEach(e=>{this.stopCapture({type:e})})}}let ot=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(ze.DeviceCaptured,e=>{this._active&&this.onStreamCapture(e)}),this._streamManagerController.on(ze.DeviceStopCapture,e=>{this._active&&this.onStreamStopCapture(e)})}getComposedStream(){return this._composedStream}enable(){this._active=!0}disable(){this._active=!1}}const Da=new ot("SingleComposer");class f_ 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){Da.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):Da.error("all video stream stop capture")}}_handleAudioStreamStopCapture(e){this._streamComposeController.removeAudioStream(e.id)}getComposedStream(){return this._composedStream}}class m_ extends Qe{constructor(e,{width:t,height:n,x:i,y:s,zOrder:a,keepRatio:o,mirrorType:l}){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=l,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,l=i;return s>a?(o=n,l=2*Math.round(n/s/2)):s<a&&(o=2*Math.round(i*s/2),l=i),{width:o,height:l}}_bindVideoTrackSizeChange(){this._stream.on(us.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!==is.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 xa extends Rt{constructor(e){super({type:Z.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 __=Object.defineProperty,g_=Object.getOwnPropertyDescriptor,Rr=(r,e,t,n)=>{for(var i=g_(e,t),s=r.length-1,a;s>=0;s--)(a=r[s])&&(i=a(e,t,i)||i);return i&&__(e,t,i),i};const Ia=new ot("composition-composer");function Ar(r,e,t){const n=t.value;return t.value=function(...i){return this._active||Ia.error("composer is not active"),n.apply(this,i)},t}class Nt extends Fi{constructor(e){super(e),this._compositionViewConfig={width:1080,height:720,frameRate:30,backgroundColor:"#000000"},this._sprites=[],this._videoMixer=new sl}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 xa(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=To(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=>{$p(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 xa(i),this._composedStream.setVideoStream(this._mixedVideoStream),n.destroy()}}getMixingConfig(){return this._compositionViewConfig}addVideoStream(e,t){if(!e.viewNode){Ia.error("have no viewNode for composition");return}e.audioTrack&&this._streamComposeController.addAudioStream({streamId:e.id,volume:100});const n=new m_(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}}}Rr([Ar],Nt.prototype,"addVideoStream"),Rr([Ar],Nt.prototype,"updateVideoStream"),Rr([Ar],Nt.prototype,"removeVideoStream"),Rr([Ar],Nt.prototype,"muteVideoStream"),Rr([Ar],Nt.prototype,"unmuteVideoStream");class v_ extends Qe{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 y_ extends Hr{constructor(e){super({type:Z.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 S_ extends Fi{constructor(e){super(e),this._spriteList=[],this._audioMixer=new $u({keepAlive:!0})}onStreamCapture(e){}onStreamStopCapture(e){e&&this.removeAudioStream(e.id)}_updateSpriteToMixer(){const e=To(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 y_(e);this._composedStream.setAudioStream(t),this._audioMixer.mix([])}addAudioStream(e,t){const n=new v_(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 b_ extends Qe{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(ht.VideoStreamChange,e))}setAudioStream(e){var t;((t=this._audioStream)==null?void 0:t.id)!==e.id&&(this._audioStream=e,this.emit(ht.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 E_=new ot("streamComposeController");class C_{constructor(e){this._streamManagerController=e,this._composedStream=new b_,this.singleComposer=new f_({streamManagerController:this._streamManagerController,composedStream:this._composedStream,streamComposeController:this}),this.compositionComposer=new Nt({streamManagerController:this._streamManagerController,composedStream:this._composedStream,streamComposeController:this}),this.mixerComposer=new S_({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){E_.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()}}class za{constructor(e){this._hasBindComposedStreamEvent=!1,this._composedStream=e}bindComposedStreamEvent(){this._hasBindComposedStreamEvent||(this._composedStream.on(ht.VideoStreamChange,this.handleVideoStreamChange),this._composedStream.on(ht.AudioStreamChange,this.handleAudioStreamChange),this._hasBindComposedStreamEvent=!0)}unbindComposedStreamEvent(){this._hasBindComposedStreamEvent&&(this._composedStream.off(ht.VideoStreamChange,this.handleVideoStreamChange),this._composedStream.off(ht.AudioStreamChange,this.handleAudioStreamChange),this._hasBindComposedStreamEvent=!1)}}const Ut=new ot("PreviewConsumer");class w_ extends za{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(Ut.log("startPreview"),!this._previewElement){Ut.warn("preview element not found");return}this._isPreviewing||this.start();const e=this._composedStream.audioTrack,t=this._composedStream.videoTrack;e&&(this._appendTrack(this._previewElement,e),this._removeTrack(this._previewElement,null)),t&&(this._appendTrack(this._previewElement,t),this._removeTrack(this._previewElement,null)),this._previewElement.play().catch(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"&&(Ut.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),Ut.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")&&(Ut.log(`remove preview track ${i.label}`),n.removeTrack(i))}),n.getTracks().length===0&&(e.srcObject=null,Ut.log("set srcObject null")))}getPreviewElement(){if(this.isPreviewing)return this._previewElement}get isPreviewing(){return this._isPreviewing}}var De={},Vi={},ji={exports:{}},Oa;function Hi(){if(Oa)return ji.exports;Oa=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 Ma;function T_(){return Ma||(Ma=1,function(r){var e=function(o){return String(Number(o))===o?Number(o):o},t=function(o,l,c,u){if(u&&!c)l[u]=e(o[1]);else for(var d=0;d<c.length;d+=1)o[d+1]!=null&&(l[c[d]]=e(o[d+1]))},n=function(o,l,c){var u=o.name&&o.names;o.push&&!l[o.push]?l[o.push]=[]:u&&!l[o.name]&&(l[o.name]={});var d=o.push?{}:u?l[o.name]:l;t(c.match(o.reg),d,o.names,o.name),o.push&&l[o.push].push(d)},i=Hi(),s=RegExp.prototype.test.bind(/^([a-z])=(.*)/);r.parse=function(o){var l={},c=[],u=l;return o.split(/(\r\n|\r|\n)/).filter(s).forEach(function(d){var h=d[0],f=d.slice(2);h==="m"&&(c.push({rtp:[],fmtp:[]}),u=c[c.length-1]);for(var b=0;b<(i[h]||[]).length;b+=1){var T=i[h][b];if(T.reg.test(f))return n(T,u,f)}}),l.media=c,l};var a=function(o,l){var c=l.split(/=(.+)/,2);return c.length===2?o[c[0]]=e(c[1]):c.length===1&&l.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 l=[],c=o.split(" ").map(e),u=0;u<c.length;u+=3)l.push({component:c[u],ip:c[u+1],port:c[u+2]});return l},r.parseImageAttributes=function(o){return o.split(" ").map(function(l){return l.substring(1,l.length-1).split(",").reduce(a,{})})},r.parseSimulcastStreamList=function(o){return o.split(";").map(function(l){return l.split(",").map(function(c){var u,d=!1;return c[0]!=="~"?u=e(c):(u=e(c.substring(1,c.length)),d=!0),{scid:u,paused:d}})})}}(Vi)),Vi}var qi,Pa;function k_(){if(Pa)return qi;Pa=1;var r=Hi(),e=/%[sdv%]/g,t=function(a){var o=1,l=arguments,c=l.length;return a.replace(e,function(u){if(o>=c)return u;var d=l[o];switch(o+=1,u){case"%%":return"%";case"%s":return String(d);case"%d":return Number(d);case"%v":return""}})},n=function(a,o,l){var c=o.format instanceof Function?o.format(o.push?l:l[o.name]):o.format,u=[a+"="+c];if(o.names)for(var d=0;d<o.names.length;d+=1){var h=o.names[d];o.name?u.push(l[o.name][h]):u.push(l[o.names[d]])}else u.push(l[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(d){d.payloads==null&&(d.payloads="")});var l=o.outerOrder||i,c=o.innerOrder||s,u=[];return l.forEach(function(d){r[d].forEach(function(h){h.name in a&&a[h.name]!=null?u.push(n(d,h,a)):h.push in a&&a[h.push]!=null&&a[h.push].forEach(function(f){u.push(n(d,h,f))})})}),a.media.forEach(function(d){u.push(n("m",r.m[0],d)),c.forEach(function(h){r[h].forEach(function(f){f.name in d&&d[f.name]!=null?u.push(n(h,f,d)):f.push in d&&d[f.push]!=null&&d[f.push].forEach(function(b){u.push(n(h,f,b))})})})}),u.join(`\r
|
|
57
67
|
`)+`\r
|
|
58
|
-
`},jt}var Di;function Fu(){if(Di)return B;Di=1;var r=Lu(),e=Nu(),t=Bt();return B.grammar=t,B.write=e,B.parse=r.parse,B.parseParams=r.parseParams,B.parseFmtpConfig=r.parseFmtpConfig,B.parsePayloads=r.parsePayloads,B.parseRemoteCandidates=r.parseRemoteCandidates,B.parseImageAttributes=r.parseImageAttributes,B.parseSimulcastStreamList=r.parseSimulcastStreamList,B}var Vu=Fu();const Je=I(Vu);function Mi(r){return new Promise(e=>{setTimeout(e,r)})}async function Uu(r,e={},t=0){const i=new AbortController;let s=!1;e=Object.assign({},e,{signal:i.signal});const n=[fetch(r,e)];t&&n.push(new Promise((a,o)=>{setTimeout(()=>{s||(o({httpCode:0,message:"Timeout"}),i.abort())},t)}));try{const a=await Promise.race(n);if(s=!0,!a.ok||a.status<200||a.status>=300)throw{httpCode:a.status,message:a.statusText};return a.json()}catch(a){throw s=!0,a}}async function Li(r,e={},t={}){const{timeout:i=0,retryDelay:s=0}=t;let{retryCount:n=0}=t;try{return await Uu(r,e,i)}catch(a){if(n--,t.retryCount=n,n<0)throw a;return await Mi(s),await Li(r,e,t)}}function w(r,e){let t;return e.forEach(i=>{i.type===r&&(t=i)}),t}async function zt(r,e){const t={},i=await(r==null?void 0:r.getStats()),s=await(e==null?void 0:e.getStats());return i&&(t.audio={mediaSource:w("media-source",i),codec:w("codec",i),candidatePair:w("candidate-pair",i),remoteCandidate:w("remote-candidate",i),localCandidate:w("local-candidate",i),track:w("track",i),outboundRtp:w("outbound-rtp",i),remoteInboundRtp:w("remote-inbound-rtp",i),transport:w("transport",i)}),s&&(t.video={mediaSource:w("media-source",s),codec:w("codec",s),candidatePair:w("candidate-pair",s),remoteCandidate:w("remote-candidate",s),localCandidate:w("local-candidate",s),track:w("track",s),outboundRtp:w("outbound-rtp",s),remoteInboundRtp:w("remote-inbound-rtp",s),transport:w("transport",s)}),t}async function $u(r,e,t){var d,h,p,l,f,g,_,T,b,v,j,A,Ls,Ns,Fs,Vs,Us,$s,Bs,js,zs,Gs,Hs,qs,Ws,Xs,Ks,Js,Ys,Zs,Qs,en,tn,rn,sn,nn;const i=await zt(e,t);await Mi(r);const s=await zt(e,t),{audio:n,video:a}=i,{audio:o,video:u}=s,c={};if(n!=null&&n.codec&&(o!=null&&o.codec)){const Qt=((d=o.outboundRtp)==null?void 0:d.timestamp)-((h=n.outboundRtp)==null?void 0:h.timestamp),er=((p=o.outboundRtp)==null?void 0:p.bytesSent)-((l=n.outboundRtp)==null?void 0:l.bytesSent),tr=((f=o.remoteInboundRtp)==null?void 0:f.packetsLost)-((g=n.remoteInboundRtp)==null?void 0:g.packetsLost),rr=((_=o.outboundRtp)==null?void 0:_.packetsSent)-((T=n.outboundRtp)==null?void 0:T.packetsSent);c.audio={codec:o.codec.mimeType,channels:o.codec.channels,sendBitrate:er/Qt*8e3,packetsSent:(b=o.outboundRtp)==null?void 0:b.packetsSent,nackCount:(v=o.outboundRtp)==null?void 0:v.nackCount,packetsLost:(j=o.remoteInboundRtp)==null?void 0:j.packetsLost,packetsLostPercent:tr/rr}}if(a!=null&&a.codec&&(u!=null&&u.codec)){const Qt=((A=u.outboundRtp)==null?void 0:A.timestamp)-((Ls=a.outboundRtp)==null?void 0:Ls.timestamp),er=((Ns=u.outboundRtp)==null?void 0:Ns.bytesSent)-((Fs=a.outboundRtp)==null?void 0:Fs.bytesSent),tr=((Vs=u.outboundRtp)==null?void 0:Vs.framesEncoded)-((Us=a.outboundRtp)==null?void 0:Us.framesEncoded),rr=(($s=u.outboundRtp)==null?void 0:$s.totalEncodeTime)-((Bs=a.outboundRtp)==null?void 0:Bs.totalEncodeTime),on=((js=u.outboundRtp)==null?void 0:js.packetsSent)-((zs=a.outboundRtp)==null?void 0:zs.packetsSent),vh=((Gs=u.outboundRtp)==null?void 0:Gs.totalPacketSendDelay)-((Hs=a.outboundRtp)==null?void 0:Hs.totalPacketSendDelay),Ch=((qs=u.remoteInboundRtp)==null?void 0:qs.packetsLost)-((Ws=a.remoteInboundRtp)==null?void 0:Ws.packetsLost);c.video={codec:u.codec.mimeType,sendBitrate:er/Qt*8e3,frameWidth:(Xs=u.outboundRtp)==null?void 0:Xs.frameWidth,frameHeight:(Ks=u.outboundRtp)==null?void 0:Ks.frameHeight,framesPerSecond:(Js=u.outboundRtp)==null?void 0:Js.framesPerSecond,framesEncoded:(Ys=u.outboundRtp)==null?void 0:Ys.framesEncoded,keyFramesEncoded:(Zs=u.outboundRtp)==null?void 0:Zs.keyFramesEncoded,framesSent:(Qs=u.outboundRtp)==null?void 0:Qs.frameHeight,frameEncodeAvgTime:rr*1e3/tr,packetsSent:(en=u.outboundRtp)==null?void 0:en.packetsSent,packetSendDelay:vh*1e3/on,nackCount:(tn=u.outboundRtp)==null?void 0:tn.nackCount,firCount:(rn=u.outboundRtp)==null?void 0:rn.firCount,pliCount:(sn=u.outboundRtp)==null?void 0:sn.pliCount,packetsLost:(nn=u.remoteInboundRtp)==null?void 0:nn.packetsLost,packetsLostPercent:Ch/on}}return c}const Bu=r=>{var t;if(!vr)return;const e=(t=r.rtp.filter(i=>i.codec==="opus")[0])==null?void 0:t.payload;e&&r.fmtp.forEach(i=>{i.payload===e&&(i.config="minptime=10;useinbandfec=1")})},ju=r=>{r.ext&&(gn||Fe)&&(r.ext=r.ext.filter(e=>{var t;return!((t=e.uri)!=null&&t.includes("video-orientation"))}))};function zu(r,e){r==null||r.rtp.forEach(({codec:t,payload:i})=>{if(["vp8","h264"].includes(t.toLocaleLowerCase())){const s=r.fmtp.find(n=>n.payload===i);s?s.config=[...s.config.split(";"),"x-google-min-bitrate=100",`x-google-start-bitrate=${e}`].join(";"):r.fmtp.push({payload:i,config:`x-google-min-bitrate=100;x-google-start-bitrate=${e}`})}})}const M=new ne("PCConnect");class Gu{constructor(e,t,i){this._pc=null,this._ms=new MediaStream,this._signalUrl="",this._videoTransceiver=null,this._audioTransceiver=null,this._opts=void 0,this._sessionId=Date.now(),this._signalUrl=e,this._opts=t,this._onConnectStateChange=i}get isPushing(){var e,t,i,s;return((t=(e=this._videoTransceiver)==null?void 0:e.sender)==null?void 0:t.track)||((s=(i=this._audioTransceiver)==null?void 0:i.sender)==null?void 0:s.track)}get pushUrl(){return this._signalUrl}get sessionId(){return this._sessionId}async publish(e,t,i){var h;const s=new RTCPeerConnection;this._pc=s,this._bindRTCEvent();const n=e.filter(p=>(p==null?void 0:p.kind)==="audio")[0],a=e.filter(p=>(p==null?void 0:p.kind)==="video")[0];n&&this._ms.addTrack(n),a&&this._ms.addTrack(a),this._audioTransceiver=s.addTransceiver(n||"audio",{direction:"sendonly",sendEncodings:[{maxBitrate:t[0]}],streams:[this._ms]}),M.log("add track to pc,",n),this._videoTransceiver=s.addTransceiver(a||"video",{direction:"sendonly",sendEncodings:[{maxBitrate:t[1]}],streams:[this._ms]}),M.log("add track to pc,",a);const o=await s.createOffer();M.groupCollapsed("local offer"),M.log(o.sdp);const u=Je.parse(o.sdp);u.media.forEach(p=>{p.type==="audio"?Bu(p):p.type==="video"&&(ju(p),zu(p,t[1]))}),o.sdp=Je.write(u),M.log("local offer modified"),M.log(o.sdp),await s.setLocalDescription(o);const c=await Li(this._signalUrl,{method:"POST",mode:"cors",body:JSON.stringify({sessionId:""+this._sessionId,version:"1.0-html",localSdp:o,metadata:{platform:"Web"}})},{...this._opts,timeout:i!=null&&i.isReconnect?10*ki:(h=this._opts)==null?void 0:h.timeout});if((c==null?void 0:c.code)!==200)throw{code:c.code,message:c.message};M.log("remote answer:"),M.log(c.remoteSdp.sdp);const d=Je.parse(c.remoteSdp.sdp);if(d.media.forEach(p=>{var l;(l=p.fingerprint)!=null&&l.hash&&(p.fingerprint.hash=p.fingerprint.hash.toUpperCase())}),c.remoteSdp.sdp=Je.write(d),M.log("remote answer modified"),M.log(c.remoteSdp.sdp),M.groupEnd(),s.connectionState==="closed"){M.log("PeerConnection is closed, skipping setRemoteDescription");return}await s.setRemoteDescription(c.remoteSdp)}async updatePublish(e,t){var n,a;let i;t==="video"?i=this._videoTransceiver:i=this._audioTransceiver;const s=(n=i==null?void 0:i.sender)==null?void 0:n.track;(s==null?void 0:s.id)!==(e==null?void 0:e.id)&&(await((a=i==null?void 0:i.sender)==null?void 0:a.replaceTrack(e)),M.log(`replace ${t} track done! ${s==null?void 0:s.label} -> ${e==null?void 0:e.label}`))}applyBitrate(e,t,i){var a,o,u;const s=t==="video"?(a=this._videoTransceiver)==null?void 0:a.sender:(o=this._audioTransceiver)==null?void 0:o.sender;if(!s)return;const n=s.getParameters();n.encodings=(u=n.encodings)!=null&&u.length?n.encodings:[{}],i?n.encodings[0].minBitrate=e:n.encodings[0].maxBitrate=e,s.setParameters(n),M.log(`set bitrate for ${t}, ${e} bps, min:${i}`)}unpublish(){var e,t;(e=this._pc)==null||e.getSenders().forEach(i=>{var s;(s=this._pc)==null||s.removeTrack(i)}),(t=this._pc)==null||t.close(),this._audioTransceiver=null,this._videoTransceiver=null,this._pc=null,M.log("close pc!")}getStats(){var e,t;return zt((e=this._audioTransceiver)==null?void 0:e.sender,(t=this._videoTransceiver)==null?void 0:t.sender)}getStatsSnapshoot(e){var t,i;return $u(e||100,(t=this._audioTransceiver)==null?void 0:t.sender,(i=this._videoTransceiver)==null?void 0:i.sender)}_bindRTCEvent(){const e=this._pc;e==null||e.addEventListener("connectionstatechange",()=>{M.log("onconnectionstatechange:",e.connectionState),this._onConnectStateChange(e.connectionState)})}}var oe=(r=>(r.OnError="onerror",r.OnConnectClosed="onconnectclosed",r.OnFirstFramePushed="onfirstframepushed",r))(oe||{}),ae=(r=>(r.Video="video",r.Audio="audio",r))(ae||{}),V=(r=>(r.Init="init",r.AvExist="avexist",r.VideoFrame="videoframe",r.MockVideoEncode="mockvideoencode",r.AudioFrame="audioframe",r.AdjustBitrate="adjustbitrate",r.Publish="publish",r.UnPublish="unpublish",r.Download="download",r.GetStats="getstats",r.EncodeConfig="encodeconfig",r))(V||{}),le=(r=>(r.Ready="ready",r.Error="error",r.FirstFramePushed="firstframepushed",r.Flvfile="flvfile",r.STATS="stats",r.Close="close",r))(le||{}),Gt={exports:{}},Ni;function Hu(){return Ni||(Ni=1,function(r){var e=Object.prototype.hasOwnProperty,t="~";function i(){}Object.create&&(i.prototype=Object.create(null),new i().__proto__||(t=!1));function s(u,c,d){this.fn=u,this.context=c,this.once=d||!1}function n(u,c,d,h,p){if(typeof d!="function")throw new TypeError("The listener must be a function");var l=new s(d,h||u,p),f=t?t+c:c;return u._events[f]?u._events[f].fn?u._events[f]=[u._events[f],l]:u._events[f].push(l):(u._events[f]=l,u._eventsCount++),u}function a(u,c){--u._eventsCount===0?u._events=new i:delete u._events[c]}function o(){this._events=new i,this._eventsCount=0}o.prototype.eventNames=function(){var c=[],d,h;if(this._eventsCount===0)return c;for(h in d=this._events)e.call(d,h)&&c.push(t?h.slice(1):h);return Object.getOwnPropertySymbols?c.concat(Object.getOwnPropertySymbols(d)):c},o.prototype.listeners=function(c){var d=t?t+c:c,h=this._events[d];if(!h)return[];if(h.fn)return[h.fn];for(var p=0,l=h.length,f=new Array(l);p<l;p++)f[p]=h[p].fn;return f},o.prototype.listenerCount=function(c){var d=t?t+c:c,h=this._events[d];return h?h.fn?1:h.length:0},o.prototype.emit=function(c,d,h,p,l,f){var g=t?t+c:c;if(!this._events[g])return!1;var _=this._events[g],T=arguments.length,b,v;if(_.fn){switch(_.once&&this.removeListener(c,_.fn,void 0,!0),T){case 1:return _.fn.call(_.context),!0;case 2:return _.fn.call(_.context,d),!0;case 3:return _.fn.call(_.context,d,h),!0;case 4:return _.fn.call(_.context,d,h,p),!0;case 5:return _.fn.call(_.context,d,h,p,l),!0;case 6:return _.fn.call(_.context,d,h,p,l,f),!0}for(v=1,b=new Array(T-1);v<T;v++)b[v-1]=arguments[v];_.fn.apply(_.context,b)}else{var j=_.length,A;for(v=0;v<j;v++)switch(_[v].once&&this.removeListener(c,_[v].fn,void 0,!0),T){case 1:_[v].fn.call(_[v].context);break;case 2:_[v].fn.call(_[v].context,d);break;case 3:_[v].fn.call(_[v].context,d,h);break;case 4:_[v].fn.call(_[v].context,d,h,p);break;default:if(!b)for(A=1,b=new Array(T-1);A<T;A++)b[A-1]=arguments[A];_[v].fn.apply(_[v].context,b)}}return!0},o.prototype.on=function(c,d,h){return n(this,c,d,h,!1)},o.prototype.once=function(c,d,h){return n(this,c,d,h,!0)},o.prototype.removeListener=function(c,d,h,p){var l=t?t+c:c;if(!this._events[l])return this;if(!d)return a(this,l),this;var f=this._events[l];if(f.fn)f.fn===d&&(!p||f.once)&&(!h||f.context===h)&&a(this,l);else{for(var g=0,_=[],T=f.length;g<T;g++)(f[g].fn!==d||p&&!f[g].once||h&&f[g].context!==h)&&_.push(f[g]);_.length?this._events[l]=_.length===1?_[0]:_:a(this,l)}return this},o.prototype.removeAllListeners=function(c){var d;return c?(d=t?t+c:c,this._events[d]&&a(this,d)):(this._events=new i,this._eventsCount=0),this},o.prototype.off=o.prototype.removeListener,o.prototype.addListener=o.prototype.on,o.prefixed=t,o.EventEmitter=o,r.exports=o}(Gt)),Gt.exports}var qu=Hu();const Wu=I(qu);var Ye=(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))(Ye||{});class Fi extends Error{constructor(e,t,i){super(),this.code=e,this.message=t,i&&(this.ext=i),this.toJson=()=>({code:this.code,message:this.message,ext:this.ext})}}function Vi(r,e,t){return new Fi(r,e,t)}const be=class be{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 be.enable}get _enableLong(){return be.enableLong}get long(){return this._enableLong}};be.enable=!1,be.enableLong=!1;let ce=be;const U=new ce("RTMP_Capture");class Xu{constructor(e){this._videoFirstframeCaptured=!1,this._audioFirstframeCaptured=!1,this._videoProcessorReader=null,this._audioProcessorReader=null,this._bridge=e}get audioTrack(){return this._bridge.audioMsTrack}get videoTrack(){return this._bridge.videoMsTrack}start(){this._startVideoCapture(),this._startAudioCapture()}restartCapture(e){if(U.log(`replace ${e} track`),e===ae.Video){if(this._videoProcessorReader){this._videoProcessorReader.cancel().finally(()=>{this._startVideoCapture()});return}this._startVideoCapture();return}if(this._audioProcessorReader){this._audioProcessorReader.cancel().finally(()=>{this._startAudioCapture()});return}this._startAudioCapture()}async _startVideoCapture(){var s;if(!this.videoTrack){U.log("no video track to capture");return}if(this.videoTrack.readyState!=="live"){U.warn("video track not live");return}const e=new MediaStreamTrackProcessor(this.videoTrack);e.track=this.videoTrack;const t=e.readable.getReader();this._videoProcessorReader=t,U.log("start capture video frame",this.videoTrack);let i;for(;;){i&&clearInterval(i),i=setTimeout(()=>{U.warn("long time no capture output"),this._bridge._postMockVideoEncodeFlag()},1500);const n=await t.read();if(clearInterval(i),this._videoFirstframeCaptured||(this._videoFirstframeCaptured=!0,U.log("video first frame captured")),n.done||!n.value){(s=n.value)==null||s.close();break}this._bridge._postVideoFrame(n.value,this.videoTrack.getSettings())}clearInterval(i),this._videoFirstframeCaptured=!1,this._videoProcessorReader=null,U.log("video track read done!",e.track)}async _startAudioCapture(){if(!this.audioTrack){U.log("no audio track to capture");return}if(this.audioTrack.readyState!=="live"){U.warn("audio track not live");return}const e=new MediaStreamTrackProcessor(this.audioTrack);e.track=this.audioTrack;const t=e.readable.getReader();for(this._audioProcessorReader=t,U.log("start capture audio frame");;){const i=await t.read();if(this._audioFirstframeCaptured||(this._audioFirstframeCaptured=!0,U.log("audio first frame captured")),i.done||!i.value)break;this._bridge._postAudioFrame(i.value,this.audioTrack.getSettings())}this._audioFirstframeCaptured=!1,this._audioProcessorReader=null,U.log("audio track read done!",e.track)}destroy(){var e,t;(e=this._audioProcessorReader)==null||e.cancel().catch(()=>{}),(t=this._videoProcessorReader)==null||t.cancel().catch(()=>{})}}const Ui='(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',$i=typeof self<"u"&&self.Blob&&new Blob([Ui],{type:"text/javascript;charset=utf-8"});function Ku(r){let e;try{if(e=$i&&(self.URL||self.webkitURL).createObjectURL($i),!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(Ui),{name:r==null?void 0:r.name})}finally{e&&(self.URL||self.webkitURL).revokeObjectURL(e)}}try{ce.enable=location.href.indexOf("rtmpdebug")!==-1,ce.enableLong=location.href.indexOf("rtmpdebug=long")!==-1}catch{}const Ze=new ce("Bridge");class Bi extends Wu{constructor(){super(),this._worker=null,this._audioMsTrack=null,this._videoMsTrack=null,this._capture=new Xu(this)}static isSupported(){return typeof WebTransport<"u"&&typeof MediaStreamTrackProcessor<"u"&&typeof MediaStreamTrackGenerator<"u"&&typeof VideoEncoder<"u"}get audioMsTrack(){return this._audioMsTrack}get videoMsTrack(){return this._videoMsTrack}async ready(){var n,a;let e,t;const i=new Promise((o,u)=>{e=o,t=u}),s=o=>{var u;switch((u=this._worker)==null||u.removeEventListener("message",s),o.data.type){case le.Error:t(o.data.data);break;default:this._bindWorkerEvent(),Ze.log("rtmp ready!"),e(!0)}};try{this._worker=new Ku}catch(o){t(Vi(Ye.RTMP_INIT_FAIL,o.message))}return(n=this._worker)==null||n.postMessage({type:V.Init,options:{logEnable:ce.enable,logEnableLong:ce.enableLong}}),(a=this._worker)==null||a.addEventListener("message",s),i}_bindWorkerEvent(){var e,t;(e=this._worker)==null||e.addEventListener("message",i=>{switch(i.data.type){case le.Error:Ze.table(i.data.data),this.emit(oe.OnError,i.data.data);break;case le.Flvfile:Ju(i.data.buffer);break;case le.FirstFramePushed:this.emit(oe.OnFirstFramePushed);break;case le.Close:this.emit(oe.OnConnectClosed),this.destroy();break}}),(t=this._worker)==null||t.addEventListener("error",i=>{this.emit(oe.OnError,Vi(Ye.WORKER_ERROR,i.message))})}addTrack(e){e.kind===ae.Video&&(this._videoMsTrack=e),e.kind===ae.Audio&&(this._audioMsTrack=e),this._setAVExist(!!this._videoMsTrack,!!this._audioMsTrack)}replaceTrack(e,t){e===ae.Video&&(this._videoMsTrack=t),e===ae.Audio&&(this._audioMsTrack=t),this._setAVExist(!!this._videoMsTrack,!!this._audioMsTrack),this._capture.restartCapture(e)}async getStats(){var n,a;let e,t;const i=new Promise((o,u)=>{e=o,t=u});this._worker||setTimeout(()=>{t()},0);const s=o=>{var u;switch(o.data.type){case le.STATS:e(o.data.data),(u=this._worker)==null||u.removeEventListener("message",s);break}};return(n=this._worker)==null||n.addEventListener("message",s),(a=this._worker)==null||a.postMessage({type:V.GetStats}),i}_postVideoFrame(e,t){var i;(i=this._worker)==null||i.postMessage({type:V.VideoFrame,frame:e,setting:t},[e])}_postMockVideoEncodeFlag(){var e;(e=this._worker)==null||e.postMessage({type:V.MockVideoEncode})}_setAVExist(e,t){var i;(i=this._worker)==null||i.postMessage({type:V.AvExist,hasVideo:e,hasAudio:t})}_postAudioFrame(e,t){var i;(i=this._worker)==null||i.postMessage({type:V.AudioFrame,frame:e,setting:t},[e])}setEncodeCapacity(e){var t;(t=this._worker)==null||t.postMessage({type:V.EncodeConfig,cfg:e})}adjustBitrate(e,t){var i;(i=this._worker)==null||i.postMessage({type:V.AdjustBitrate,kind:e,bitrate:t})}publish(e){var t;Ze.log("start capture & connect"),this._capture.start(),(t=this._worker)==null||t.postMessage({type:V.Publish,url:e})}unpublish(){var e;this._capture.destroy(),(e=this._worker)==null||e.postMessage({type:V.UnPublish})}destroy(){var e;Ze.log("destroy capture & rtmp worker"),this._capture.destroy(),(e=this._worker)==null||e.terminate(),this._worker=null}download(){var e;(e=this._worker)==null||e.postMessage({type:V.Download})}}function Ju(r){const e=document.createElement("a");e.href=URL.createObjectURL(new Blob([r])),e.download=Date.now()+".flv",e.click()}const ji=new ne("RTMPConnect");class Yu{constructor(e,t,i,s){this._opts=void 0,this._isPushing=!1,this._url=e,this._opts=t,this._onError=i,this._OnSuccess=s,this._rtmp=new Bi,this._bindEvents()}get isPushing(){return this._isPushing}get pushUrl(){return this._url}get sessionId(){return 0}_bindEvents(){this._rtmp.on(oe.OnError,e=>{this._isPushing=!1,this._onError(e)}),this._rtmp.on(oe.OnConnectClosed,()=>{this._isPushing=!1,this._onError(new Fi(Ye.WTP_CONNECT_FAIL,"connect lost"))}),this._rtmp.on(oe.OnFirstFramePushed,()=>{this._isPushing=!0,this._OnSuccess()})}async publish(e,t,i){await this._rtmp.ready(),i!=null&&i.cfg&&this._rtmp.setEncodeCapacity(i.cfg),e.filter(Boolean).forEach(s=>this._rtmp.addTrack(s)),t[0]&&this._rtmp.adjustBitrate(ae.Audio,t[0]),t[1]&&this._rtmp.adjustBitrate(ae.Video,t[1]),this._rtmp.publish(this._url)}updatePublish(e,t){ji.log(`replace track to ${e==null?void 0:e.label}`),this._rtmp.replaceTrack(t,e)}applyBitrate(e,t){this._rtmp.adjustBitrate(t,e)}async getStats(){return this._rtmp.getStats()}async getStatsSnapshoot(){return this._rtmp.getStats()}unpublish(){ji.warn("unpublish"),this._rtmp.unpublish(),this._isPushing=!1}}class Zu{constructor(e,t=Su){this._reconnectDelay=0,this._reconnectCount=0,this._timeoutTimerId=null,this._reconnectTimeout=null,this.handleOnlineReconnect=()=>{this.execute(!0)},this.execute=(i=!1)=>{var s;this._logger.log("start reconnect strategy"),this.state===0&&(this.bindOnlineEvent(),this.setStrategyState(1),(s=this._logger)==null||s.log("start reconnecting with max timeout: ",this._maxTimeout),this.startTimeoutTimer(this._maxTimeout),this._pushConsumer.emitReconnectStateChange(fe.START)),this.state===1&&(this._reconnectTimeout&&clearTimeout(this._reconnectTimeout),this.executeStrategy(i))},this.attemptReconnect=async()=>{var i;if(this.state===1){this.setStrategyState(2),this._reconnectCount+=1,this._pushConsumer.emitReconnectStateChange(fe.RECONNECTING,{retryTime:this._reconnectCount});try{await this._pushConsumer.reconnect(this.getNextPushUrl()),this.setStrategyState(1)}catch(s){const n=s.ext||{},{httpCode:a}=n;a!==void 0&&String(a).startsWith("4")?(this.stop({isSuccess:!1,reason:at.PushUrlInvalid}),(i=this._onReconnectError)==null||i.call(this,"pushError",s)):(this.setStrategyState(1),this.execute())}}},this.executeStrategy=(i=!1)=>{const s=i?0:this._reconnectDelay;this._pushConsumer.emitReconnectStateChange(fe.WAITING,{waitingTime:s,retryTime:this._reconnectCount+1}),this._logger.log("reconnect after delay: ",s,Date.now()),this._reconnectTimeout=window.setTimeout(this.attemptReconnect,s),this._reconnectDelay=this._reconnectDelay===0?2e3:Math.min(this._reconnectDelay*2,Tu)},this.state=0,this._pushConsumer=e,this._maxTimeout=t,this._logger=new ne("ReconnectStrategy")}getNextPushUrl(){const e=this._pushConsumer.pushUrl;if(!e)return"";const t=new URL(e),i=Date.now();return t.searchParams.set("pri",i.toString()),t.href}set onReconnectError(e){this._onReconnectError=e}bindOnlineEvent(){window.addEventListener("online",this.handleOnlineReconnect)}unbindOnlineEvent(){window.removeEventListener("online",this.handleOnlineReconnect)}setStrategyState(e){this._logger.log("reconnect state change to: ",e),this.state=e}stop({isSuccess:e=!0,reason:t,quiet:i=!1}){this.state!==0&&(i||(e?this._pushConsumer.emitReconnectStateChange(fe.SUCCESS):(this._logger.log("Reconnect strategy stopped: ",t),this._pushConsumer.emitReconnectStateChange(fe.FAILED,{failedCode:t}))),this.setStrategyState(0),this._timeoutTimerId&&clearTimeout(this._timeoutTimerId),this._reconnectTimeout&&clearTimeout(this._reconnectTimeout),this._reconnectDelay=0,this._reconnectCount=0,this.unbindOnlineEvent())}startTimeoutTimer(e){this._timeoutTimerId=window.setTimeout(()=>{var t;this.state!==0&&(this._logger.log("Reconnect strategy timed out"),this.stop({isSuccess:!1,reason:at.ReconnectTimeout}),(t=this._onReconnectError)==null||t.call(this,"timeout"))},e)}isActive(){return this.state!==0}}const Qu=new ne("PushController");class eh extends Ai{constructor(e,{config:t,streamConsumeController:i}){var s,n;if(super(e),this._connect=null,this._connectionState=G.DISCONNECTED,this._pushMode="rtm",this._reconnectStrategy=null,this._pushConfig={timeout:5e3,retryCount:1,retryDelay:1e3},this._audioBitrate=ye(hr,"audio").bitrate,this._videoBitrate=ye(ur,"video").bitrate,this.handleReconnectError=(a,o)=>{this.unpublish()},this.handleAudioStreamChange=a=>{this.updatePush({audioTrack:a.audioTrack})},this.handleVideoStreamChange=a=>{this.updatePush({videoTrack:a.videoTrack})},this._OnRTMPSuccess=()=>{this.setConnectState(G.CONNECTED)},this._OnRTMPError=a=>{const o=new Me(F.PUBLISH_FAILED,`code:${a.code}, message: ${a.message}`);this._streamConsumeController.emit(R.PushError,o),this.unpublish()},this._executeReconnect=()=>{var a;(a=this._reconnectStrategy)==null||a.execute(),this.setConnectState(G.RECONNECTING),this.unpublish(!0)},this._OnRtcStateChange=a=>{var o;switch(this._streamConsumeController.emit(R.RTCConnectStateChanged,a),a){case"connected":this.setConnectState(G.CONNECTED);break;case"disconnected":this._reconnectStrategy&&this._executeReconnect();break;case"failed":(o=this._reconnectStrategy)!=null&&o.isActive()?this._executeReconnect():(this.unpublish(),this._streamConsumeController.emit(R.PushError,new Me(F.PUSH_CONNECT_FAILED,"pc failed")));break}},this._pushMode=(t==null?void 0:t.mode)||"rtm",this._streamConsumeController=i,t&&(this._pushConfig=t),(s=t==null?void 0:t.reconnectConfig)!=null&&s.enable||!(t!=null&&t.reconnectConfig)){const a=(n=t==null?void 0:t.reconnectConfig)!=null&&n.maxTimeout?t.reconnectConfig.maxTimeout*ki:void 0;this._reconnectStrategy=new Zu(this,a),this._reconnectStrategy.onReconnectError=this.handleReconnectError}}get isPushing(){return this._connectionState===G.CONNECTED||this._connectionState===G.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(R.LiveConnectStateChange,e),e){case G.CONNECTED:(t=this._reconnectStrategy)!=null&&t.isActive()?this._reconnectStrategy.stop({isSuccess:!0}):this._streamConsumeController.emit(R.PushStart);break}}async getStats(e=2e3){var t;return(t=this._connect)==null?void 0:t.getStatsSnapshoot(e)}async startPush(e,t={}){var a,o;if(!e)throw new Error("lack publish url");if(this._connect)return;this.start(),this._pushUrl=e,this._pushEncodeConfig=t.cfg;const i=this._composedStream.videoTrack,s=this._composedStream.audioTrack;if(!i&&!s)return;let n;this._pushMode==="rtm"?n=new Gu(e,this._pushConfig,this._OnRtcStateChange):n=new Yu(e,this._pushConfig,this._OnRTMPError,this._OnRTMPSuccess),this._connect=n;try{(a=this._reconnectStrategy)!=null&&a.isActive()||this.setConnectState(G.CONNECTING),await n.publish([s,i],[this._audioBitrate,this._videoBitrate],{cfg:t.cfg,isReconnect:t.isReconnect})}catch(u){const c=new Me(F.PUBLISH_FAILED,u.message,u);if(Qu.groupEnd(),(o=this._reconnectStrategy)!=null&&o.isActive())throw this.unpublish(!0),c;this._streamConsumeController.emit(R.PushError,c),this.unpublish()}}async reconnect(e){if(this.pushMode==="rtm")return this.startPush(e,{isReconnect:!0})}async updatePush({videoTrack:e,audioTrack:t}){if(this._connect)try{const i=[];e&&i.push(()=>{var s;return(s=this._connect)==null?void 0:s.updatePublish(e,"video")}),t&&i.push(()=>{var s;return(s=this._connect)==null?void 0:s.updatePublish(t,"audio")}),await Promise.all(i.map(s=>s()))}catch(i){const s=new Me(F.UPDATE_PUBLISH_FAILED,`${i.name}, code:${i.code}`);this._streamConsumeController.emit(R.PushError,s)}}unpublish(e=!1){var t,i;(t=this._connect)==null||t.unpublish(),this._connect=null,e||(this._pushEncodeConfig=void 0,this._pushUrl=void 0,this.setConnectState(G.DISCONNECTED),(i=this._reconnectStrategy)==null||i.stop({quiet:!0}),this._streamConsumeController.emit(R.PushStop))}async destroy(){this._connect&&await this.unpublish(),this.unbindComposedStreamEvent()}setPushMode(e){this._pushMode=e}updatePushUrl(e){this._pushUrl=e}setBitrate(e,t,i){var s;t==="video"?this._videoBitrate=e:this._audioBitrate=e,(s=this._connect)==null||s.applyBitrate(e,t,i)}get pushMode(){return this._pushMode}get connectionState(){return this._connectionState}emitReconnectStateChange(e,t){this._streamConsumeController.emit(R.ReconnectStateChange,e,t)}}class th extends te{constructor(e,t){super(),this._previewConsumer=new Mu(e.getComposedStream(),{streamConsumeController:this}),this._pushConsumer=new eh(e.getComposedStream(),{streamConsumeController:this,config:t})}startPreview(){this._previewConsumer.startPreview()}setRenderView(e){this._previewConsumer.setRenderView(e)}async startPush(e,t){return this._pushConsumer.startPush(e,t)}async stopPush(){return this._pushConsumer.unpublish()}setPushMode(e){this._pushConsumer.setPushMode(e)}isPushing(){return this._pushConsumer.isPushing}getStats(){return this._pushConsumer.getStats()}getPreviewElement(){return this._previewConsumer.getPreviewElement()}stopPreview(){this._previewConsumer.stopPreview()}setBitrate(e,t,i){this._pushConsumer.setBitrate(e,t,i)}setPushConfig(e){this._pushConsumer.setPushConfig(e)}updatePushUrl(e){this._pushConsumer.updatePushUrl(e)}get pushMode(){return this._pushConsumer.pushMode}async destroy(){await this._pushConsumer.destroy(),this._previewConsumer.destroy()}}const rh=()=>typeof window>"u",q={},Qe=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 zi(r){const e=r.split(`
|
|
59
|
-
`);let t=!1;for(const i of e)if(i.includes("level-asymmetry-allowed=1")&&i.includes("packetization-mode=1")&&i.includes("profile-level-id=42e0")){t=!0;break}if(t){const i=navigator.userAgent.toLowerCase();let s=!1;const n=[/miuibrowser/,/70.*HeyTapBrowser/i];for(const a of n)a.test(i)&&(s=!0);return!s}return!1}const ih=async()=>{let r=await Qe("sendonly");return navigator.userAgent.includes("VivoBrowser")&&(r=await Qe("sendonly")),q.h264encode=zi(r),q.vp8encode=r.indexOf("vp8")>-1,q},sh=async()=>{let r=await Qe("recvonly");return navigator.userAgent.includes("VivoBrowser")&&(r=await Qe("recvonly")),q.h264decode=zi(r),q.vp8decode=r.indexOf("vp8")>-1,q},nh=async()=>{if(typeof q.h264encode>"u")try{await ih()}catch{return!1}return q.h264encode||!1},oh=async()=>{if(typeof q.h264decode>"u")try{await sh()}catch{return!1}return q.h264decode||!1};class ah{constructor(){this.onError=(e,t,i)=>{},this.onWarning=e=>{},this.onCaptureFirstAudioFrame=()=>{},this.onCaptureFirstVideoFrame=()=>{},this.onPushStatusUpdate=(e,t)=>{},this.onMicrophoneChanged=e=>{},this.onCameraChanged=e=>{},this.onCaptureInterrupted=e=>{},this.onPushStart=()=>{},this.onPushStop=()=>{},this.onStopCapture=e=>{},this.onLiveConnectStateChange=e=>{},this.onReconnectStateChange=(e,t)=>{}}}const ch=new ah;let Gi=!0,Hi=!0;function et(r,e,t){const i=r.match(e);return i&&i.length>=t&&parseInt(i[t],10)}function me(r,e,t){if(!r.RTCPeerConnection)return;const i=r.RTCPeerConnection.prototype,s=i.addEventListener;i.addEventListener=function(a,o){if(a!==e)return s.apply(this,arguments);const u=c=>{const d=t(c);d&&(o.handleEvent?o.handleEvent(d):o(d))};return this._eventMap=this._eventMap||{},this._eventMap[e]||(this._eventMap[e]=new Map),this._eventMap[e].set(o,u),s.apply(this,[a,u])};const n=i.removeEventListener;i.removeEventListener=function(a,o){if(a!==e||!this._eventMap||!this._eventMap[e])return n.apply(this,arguments);if(!this._eventMap[e].has(o))return n.apply(this,arguments);const u=this._eventMap[e].get(o);return this._eventMap[e].delete(o),this._eventMap[e].size===0&&delete this._eventMap[e],Object.keys(this._eventMap).length===0&&delete this._eventMap,n.apply(this,[a,u])},Object.defineProperty(i,"on"+e,{get(){return this["_on"+e]},set(a){this["_on"+e]&&(this.removeEventListener(e,this["_on"+e]),delete this["_on"+e]),a&&this.addEventListener(e,this["_on"+e]=a)},enumerable:!0,configurable:!0})}function dh(r){return typeof r!="boolean"?new Error("Argument type: "+typeof r+". Please use a boolean."):(Gi=r,r?"adapter.js logging disabled":"adapter.js logging enabled")}function uh(r){return typeof r!="boolean"?new Error("Argument type: "+typeof r+". Please use a boolean."):(Hi=!r,"adapter.js deprecation warnings "+(r?"disabled":"enabled"))}function qi(){if(typeof window=="object"){if(Gi)return;typeof console<"u"&&typeof console.log=="function"&&console.log.apply(console,arguments)}}function Ht(r,e){Hi&&console.warn(r+" is deprecated, please use "+e+" instead.")}function hh(r){const e={browser:null,version:null};if(typeof r>"u"||!r.navigator||!r.navigator.userAgent)return e.browser="Not a browser.",e;const{navigator:t}=r;if(t.userAgentData&&t.userAgentData.brands){const i=t.userAgentData.brands.find(s=>s.brand==="Chromium");if(i)return{browser:"chrome",version:parseInt(i.version,10)}}if(t.mozGetUserMedia)e.browser="firefox",e.version=et(t.userAgent,/Firefox\/(\d+)\./,1);else if(t.webkitGetUserMedia||r.isSecureContext===!1&&r.webkitRTCPeerConnection)e.browser="chrome",e.version=et(t.userAgent,/Chrom(e|ium)\/(\d+)\./,2);else if(r.RTCPeerConnection&&t.userAgent.match(/AppleWebKit\/(\d+)\./))e.browser="safari",e.version=et(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 Wi(r){return Object.prototype.toString.call(r)==="[object Object]"}function Xi(r){return Wi(r)?Object.keys(r).reduce(function(e,t){const i=Wi(r[t]),s=i?Xi(r[t]):r[t],n=i&&!Object.keys(s).length;return s===void 0||n?e:Object.assign(e,{[t]:s})},{}):r}function qt(r,e,t){!e||t.has(e.id)||(t.set(e.id,e),Object.keys(e).forEach(i=>{i.endsWith("Id")?qt(r,r.get(e[i]),t):i.endsWith("Ids")&&e[i].forEach(s=>{qt(r,r.get(s),t)})}))}function Ki(r,e,t){const i=t?"outbound-rtp":"inbound-rtp",s=new Map;if(e===null)return s;const n=[];return r.forEach(a=>{a.type==="track"&&a.trackIdentifier===e.id&&n.push(a)}),n.forEach(a=>{r.forEach(o=>{o.type===i&&o.trackId===a.id&&qt(r,o,s)})}),s}const Ji=qi;function Yi(r,e){const t=r&&r.navigator;if(!t.mediaDevices)return;const i=function(o){if(typeof o!="object"||o.mandatory||o.optional)return o;const u={};return Object.keys(o).forEach(c=>{if(c==="require"||c==="advanced"||c==="mediaSource")return;const d=typeof o[c]=="object"?o[c]:{ideal:o[c]};d.exact!==void 0&&typeof d.exact=="number"&&(d.min=d.max=d.exact);const h=function(p,l){return p?p+l.charAt(0).toUpperCase()+l.slice(1):l==="deviceId"?"sourceId":l};if(d.ideal!==void 0){u.optional=u.optional||[];let p={};typeof d.ideal=="number"?(p[h("min",c)]=d.ideal,u.optional.push(p),p={},p[h("max",c)]=d.ideal,u.optional.push(p)):(p[h("",c)]=d.ideal,u.optional.push(p))}d.exact!==void 0&&typeof d.exact!="number"?(u.mandatory=u.mandatory||{},u.mandatory[h("",c)]=d.exact):["min","max"].forEach(p=>{d[p]!==void 0&&(u.mandatory=u.mandatory||{},u.mandatory[h(p,c)]=d[p])})}),o.advanced&&(u.optional=(u.optional||[]).concat(o.advanced)),u},s=function(o,u){if(e.version>=61)return u(o);if(o=JSON.parse(JSON.stringify(o)),o&&typeof o.audio=="object"){const c=function(d,h,p){h in d&&!(p in d)&&(d[p]=d[h],delete d[h])};o=JSON.parse(JSON.stringify(o)),c(o.audio,"autoGainControl","googAutoGainControl"),c(o.audio,"noiseSuppression","googNoiseSuppression"),o.audio=i(o.audio)}if(o&&typeof o.video=="object"){let c=o.video.facingMode;c=c&&(typeof c=="object"?c:{ideal:c});const d=e.version<66;if(c&&(c.exact==="user"||c.exact==="environment"||c.ideal==="user"||c.ideal==="environment")&&!(t.mediaDevices.getSupportedConstraints&&t.mediaDevices.getSupportedConstraints().facingMode&&!d)){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(p=>{p=p.filter(f=>f.kind==="videoinput");let l=p.find(f=>h.some(g=>f.label.toLowerCase().includes(g)));return!l&&p.length&&h.includes("back")&&(l=p[p.length-1]),l&&(o.video.deviceId=c.exact?{exact:l.deviceId}:{ideal:l.deviceId}),o.video=i(o.video),Ji("chrome: "+JSON.stringify(o)),u(o)})}o.video=i(o.video)}return Ji("chrome: "+JSON.stringify(o)),u(o)},n=function(o){return e.version>=64?o:{name:{PermissionDeniedError:"NotAllowedError",PermissionDismissedError:"NotAllowedError",InvalidStateError:"NotAllowedError",DevicesNotFoundError:"NotFoundError",ConstraintNotSatisfiedError:"OverconstrainedError",TrackStartError:"NotReadableError",MediaDeviceFailedDueToShutdown:"NotAllowedError",MediaDeviceKillSwitchOn:"NotAllowedError",TabCaptureError:"AbortError",ScreenCaptureError:"AbortError",DeviceCaptureError:"AbortError"}[o.name]||o.name,message:o.message,constraint:o.constraint||o.constraintName,toString(){return this.name+(this.message&&": ")+this.message}}},a=function(o,u,c){s(o,d=>{t.webkitGetUserMedia(d,u,h=>{c&&c(n(h))})})};if(t.getUserMedia=a.bind(t),t.mediaDevices.getUserMedia){const o=t.mediaDevices.getUserMedia.bind(t.mediaDevices);t.mediaDevices.getUserMedia=function(u){return s(u,c=>o(c).then(d=>{if(c.audio&&!d.getAudioTracks().length||c.video&&!d.getVideoTracks().length)throw d.getTracks().forEach(h=>{h.stop()}),new DOMException("","NotFoundError");return d},d=>Promise.reject(n(d))))}}}function Zi(r){r.MediaStream=r.MediaStream||r.webkitMediaStream}function Qi(r){if(typeof r=="object"&&r.RTCPeerConnection&&!("ontrack"in r.RTCPeerConnection.prototype)){Object.defineProperty(r.RTCPeerConnection.prototype,"ontrack",{get(){return this._ontrack},set(t){this._ontrack&&this.removeEventListener("track",this._ontrack),this.addEventListener("track",this._ontrack=t)},enumerable:!0,configurable:!0});const e=r.RTCPeerConnection.prototype.setRemoteDescription;r.RTCPeerConnection.prototype.setRemoteDescription=function(){return this._ontrackpoly||(this._ontrackpoly=i=>{i.stream.addEventListener("addtrack",s=>{let n;r.RTCPeerConnection.prototype.getReceivers?n=this.getReceivers().find(o=>o.track&&o.track.id===s.track.id):n={track:s.track};const a=new Event("track");a.track=s.track,a.receiver=n,a.transceiver={receiver:n},a.streams=[i.stream],this.dispatchEvent(a)}),i.stream.getTracks().forEach(s=>{let n;r.RTCPeerConnection.prototype.getReceivers?n=this.getReceivers().find(o=>o.track&&o.track.id===s.id):n={track:s};const a=new Event("track");a.track=s,a.receiver=n,a.transceiver={receiver:n},a.streams=[i.stream],this.dispatchEvent(a)})},this.addEventListener("addstream",this._ontrackpoly)),e.apply(this,arguments)}}else me(r,"track",e=>(e.transceiver||Object.defineProperty(e,"transceiver",{value:{receiver:e.receiver}}),e))}function es(r){if(typeof r=="object"&&r.RTCPeerConnection&&!("getSenders"in r.RTCPeerConnection.prototype)&&"createDTMFSender"in r.RTCPeerConnection.prototype){const e=function(s,n){return{track:n,get dtmf(){return this._dtmf===void 0&&(n.kind==="audio"?this._dtmf=s.createDTMFSender(n):this._dtmf=null),this._dtmf},_pc:s}};if(!r.RTCPeerConnection.prototype.getSenders){r.RTCPeerConnection.prototype.getSenders=function(){return this._senders=this._senders||[],this._senders.slice()};const s=r.RTCPeerConnection.prototype.addTrack;r.RTCPeerConnection.prototype.addTrack=function(o,u){let c=s.apply(this,arguments);return c||(c=e(this,o),this._senders.push(c)),c};const n=r.RTCPeerConnection.prototype.removeTrack;r.RTCPeerConnection.prototype.removeTrack=function(o){n.apply(this,arguments);const u=this._senders.indexOf(o);u!==-1&&this._senders.splice(u,1)}}const t=r.RTCPeerConnection.prototype.addStream;r.RTCPeerConnection.prototype.addStream=function(n){this._senders=this._senders||[],t.apply(this,[n]),n.getTracks().forEach(a=>{this._senders.push(e(this,a))})};const i=r.RTCPeerConnection.prototype.removeStream;r.RTCPeerConnection.prototype.removeStream=function(n){this._senders=this._senders||[],i.apply(this,[n]),n.getTracks().forEach(a=>{const o=this._senders.find(u=>u.track===a);o&&this._senders.splice(this._senders.indexOf(o),1)})}}else if(typeof r=="object"&&r.RTCPeerConnection&&"getSenders"in r.RTCPeerConnection.prototype&&"createDTMFSender"in r.RTCPeerConnection.prototype&&r.RTCRtpSender&&!("dtmf"in r.RTCRtpSender.prototype)){const e=r.RTCPeerConnection.prototype.getSenders;r.RTCPeerConnection.prototype.getSenders=function(){const i=e.apply(this,[]);return i.forEach(s=>s._pc=this),i},Object.defineProperty(r.RTCRtpSender.prototype,"dtmf",{get(){return this._dtmf===void 0&&(this.track.kind==="audio"?this._dtmf=this._pc.createDTMFSender(this.track):this._dtmf=null),this._dtmf}})}}function ts(r){if(!(typeof r=="object"&&r.RTCPeerConnection&&r.RTCRtpSender&&r.RTCRtpReceiver))return;if(!("getStats"in r.RTCRtpSender.prototype)){const t=r.RTCPeerConnection.prototype.getSenders;t&&(r.RTCPeerConnection.prototype.getSenders=function(){const n=t.apply(this,[]);return n.forEach(a=>a._pc=this),n});const i=r.RTCPeerConnection.prototype.addTrack;i&&(r.RTCPeerConnection.prototype.addTrack=function(){const n=i.apply(this,arguments);return n._pc=this,n}),r.RTCRtpSender.prototype.getStats=function(){const n=this;return this._pc.getStats().then(a=>Ki(a,n.track,!0))}}if(!("getStats"in r.RTCRtpReceiver.prototype)){const t=r.RTCPeerConnection.prototype.getReceivers;t&&(r.RTCPeerConnection.prototype.getReceivers=function(){const s=t.apply(this,[]);return s.forEach(n=>n._pc=this),s}),me(r,"track",i=>(i.receiver._pc=i.srcElement,i)),r.RTCRtpReceiver.prototype.getStats=function(){const s=this;return this._pc.getStats().then(n=>Ki(n,s.track,!1))}}if(!("getStats"in r.RTCRtpSender.prototype&&"getStats"in r.RTCRtpReceiver.prototype))return;const e=r.RTCPeerConnection.prototype.getStats;r.RTCPeerConnection.prototype.getStats=function(){if(arguments.length>0&&arguments[0]instanceof r.MediaStreamTrack){const i=arguments[0];let s,n,a;return this.getSenders().forEach(o=>{o.track===i&&(s?a=!0:s=o)}),this.getReceivers().forEach(o=>(o.track===i&&(n?a=!0:n=o),o.track===i)),a||s&&n?Promise.reject(new DOMException("There are more than one sender or receiver for the track.","InvalidAccessError")):s?s.getStats():n?n.getStats():Promise.reject(new DOMException("There is no sender or receiver for the track.","InvalidAccessError"))}return e.apply(this,arguments)}}function rs(r){r.RTCPeerConnection.prototype.getLocalStreams=function(){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},Object.keys(this._shimmedLocalStreams).map(a=>this._shimmedLocalStreams[a][0])};const e=r.RTCPeerConnection.prototype.addTrack;r.RTCPeerConnection.prototype.addTrack=function(a,o){if(!o)return e.apply(this,arguments);this._shimmedLocalStreams=this._shimmedLocalStreams||{};const u=e.apply(this,arguments);return this._shimmedLocalStreams[o.id]?this._shimmedLocalStreams[o.id].indexOf(u)===-1&&this._shimmedLocalStreams[o.id].push(u):this._shimmedLocalStreams[o.id]=[o,u],u};const t=r.RTCPeerConnection.prototype.addStream;r.RTCPeerConnection.prototype.addStream=function(a){this._shimmedLocalStreams=this._shimmedLocalStreams||{},a.getTracks().forEach(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 u=this.getSenders().filter(c=>o.indexOf(c)===-1);this._shimmedLocalStreams[a.id]=[a].concat(u)};const i=r.RTCPeerConnection.prototype.removeStream;r.RTCPeerConnection.prototype.removeStream=function(a){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},delete this._shimmedLocalStreams[a.id],i.apply(this,arguments)};const s=r.RTCPeerConnection.prototype.removeTrack;r.RTCPeerConnection.prototype.removeTrack=function(a){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},a&&Object.keys(this._shimmedLocalStreams).forEach(o=>{const u=this._shimmedLocalStreams[o].indexOf(a);u!==-1&&this._shimmedLocalStreams[o].splice(u,1),this._shimmedLocalStreams[o].length===1&&delete this._shimmedLocalStreams[o]}),s.apply(this,arguments)}}function is(r,e){if(!r.RTCPeerConnection)return;if(r.RTCPeerConnection.prototype.addTrack&&e.version>=65)return rs(r);const t=r.RTCPeerConnection.prototype.getLocalStreams;r.RTCPeerConnection.prototype.getLocalStreams=function(){const d=t.apply(this);return this._reverseStreams=this._reverseStreams||{},d.map(h=>this._reverseStreams[h.id])};const i=r.RTCPeerConnection.prototype.addStream;r.RTCPeerConnection.prototype.addStream=function(d){if(this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},d.getTracks().forEach(h=>{if(this.getSenders().find(l=>l.track===h))throw new DOMException("Track already exists.","InvalidAccessError")}),!this._reverseStreams[d.id]){const h=new r.MediaStream(d.getTracks());this._streams[d.id]=h,this._reverseStreams[h.id]=d,d=h}i.apply(this,[d])};const s=r.RTCPeerConnection.prototype.removeStream;r.RTCPeerConnection.prototype.removeStream=function(d){this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},s.apply(this,[this._streams[d.id]||d]),delete this._reverseStreams[this._streams[d.id]?this._streams[d.id].id:d.id],delete this._streams[d.id]},r.RTCPeerConnection.prototype.addTrack=function(d,h){if(this.signalingState==="closed")throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");const p=[].slice.call(arguments,1);if(p.length!==1||!p[0].getTracks().find(g=>g===d))throw new DOMException("The adapter.js addTrack polyfill only supports a single stream which is associated with the specified track.","NotSupportedError");if(this.getSenders().find(g=>g.track===d))throw new DOMException("Track already exists.","InvalidAccessError");this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{};const f=this._streams[h.id];if(f)f.addTrack(d),Promise.resolve().then(()=>{this.dispatchEvent(new Event("negotiationneeded"))});else{const g=new r.MediaStream([d]);this._streams[h.id]=g,this._reverseStreams[g.id]=h,this.addStream(g)}return this.getSenders().find(g=>g.track===d)};function n(c,d){let h=d.sdp;return Object.keys(c._reverseStreams||[]).forEach(p=>{const l=c._reverseStreams[p],f=c._streams[l.id];h=h.replace(new RegExp(f.id,"g"),l.id)}),new RTCSessionDescription({type:d.type,sdp:h})}function a(c,d){let h=d.sdp;return Object.keys(c._reverseStreams||[]).forEach(p=>{const l=c._reverseStreams[p],f=c._streams[l.id];h=h.replace(new RegExp(l.id,"g"),f.id)}),new RTCSessionDescription({type:d.type,sdp:h})}["createOffer","createAnswer"].forEach(function(c){const d=r.RTCPeerConnection.prototype[c],h={[c](){const p=arguments;return arguments.length&&typeof arguments[0]=="function"?d.apply(this,[f=>{const g=n(this,f);p[0].apply(null,[g])},f=>{p[1]&&p[1].apply(null,f)},arguments[2]]):d.apply(this,arguments).then(f=>n(this,f))}};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 u=Object.getOwnPropertyDescriptor(r.RTCPeerConnection.prototype,"localDescription");Object.defineProperty(r.RTCPeerConnection.prototype,"localDescription",{get(){const c=u.get.apply(this);return c.type===""?c:n(this,c)}}),r.RTCPeerConnection.prototype.removeTrack=function(d){if(this.signalingState==="closed")throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");if(!d._pc)throw new DOMException("Argument 1 of RTCPeerConnection.removeTrack does not implement interface RTCRtpSender.","TypeError");if(!(d._pc===this))throw new DOMException("Sender was not created by this connection.","InvalidAccessError");this._streams=this._streams||{};let p;Object.keys(this._streams).forEach(l=>{this._streams[l].getTracks().find(g=>d.track===g)&&(p=this._streams[l])}),p&&(p.getTracks().length===1?this.removeStream(this._reverseStreams[p.id]):p.removeTrack(d.track),this.dispatchEvent(new Event("negotiationneeded")))}}function Wt(r,e){!r.RTCPeerConnection&&r.webkitRTCPeerConnection&&(r.RTCPeerConnection=r.webkitRTCPeerConnection),r.RTCPeerConnection&&e.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach(function(t){const i=r.RTCPeerConnection.prototype[t],s={[t](){return arguments[0]=new(t==="addIceCandidate"?r.RTCIceCandidate:r.RTCSessionDescription)(arguments[0]),i.apply(this,arguments)}};r.RTCPeerConnection.prototype[t]=s[t]})}function ss(r,e){me(r,"negotiationneeded",t=>{const i=t.target;if(!((e.version<72||i.getConfiguration&&i.getConfiguration().sdpSemantics==="plan-b")&&i.signalingState!=="stable"))return t})}const ns=Object.freeze(Object.defineProperty({__proto__:null,fixNegotiationNeeded:ss,shimAddTrackRemoveTrack:is,shimAddTrackRemoveTrackWithNative:rs,shimGetSendersWithDtmf:es,shimGetUserMedia:Yi,shimMediaStream:Zi,shimOnTrack:Qi,shimPeerConnection:Wt,shimSenderReceiverGetStats:ts},Symbol.toStringTag,{value:"Module"}));function os(r,e){const t=r&&r.navigator,i=r&&r.MediaStreamTrack;if(t.getUserMedia=function(s,n,a){Ht("navigator.getUserMedia","navigator.mediaDevices.getUserMedia"),t.mediaDevices.getUserMedia(s).then(n,a)},!(e.version>55&&"autoGainControl"in t.mediaDevices.getSupportedConstraints())){const s=function(a,o,u){o in a&&!(u in a)&&(a[u]=a[o],delete a[o])},n=t.mediaDevices.getUserMedia.bind(t.mediaDevices);if(t.mediaDevices.getUserMedia=function(a){return typeof a=="object"&&typeof a.audio=="object"&&(a=JSON.parse(JSON.stringify(a)),s(a.audio,"autoGainControl","mozAutoGainControl"),s(a.audio,"noiseSuppression","mozNoiseSuppression")),n(a)},i&&i.prototype.getSettings){const a=i.prototype.getSettings;i.prototype.getSettings=function(){const o=a.apply(this,arguments);return s(o,"mozAutoGainControl","autoGainControl"),s(o,"mozNoiseSuppression","noiseSuppression"),o}}if(i&&i.prototype.applyConstraints){const a=i.prototype.applyConstraints;i.prototype.applyConstraints=function(o){return this.kind==="audio"&&typeof o=="object"&&(o=JSON.parse(JSON.stringify(o)),s(o,"autoGainControl","mozAutoGainControl"),s(o,"noiseSuppression","mozNoiseSuppression")),a.apply(this,[o])}}}}function ph(r,e){r.navigator.mediaDevices&&"getDisplayMedia"in r.navigator.mediaDevices||r.navigator.mediaDevices&&(r.navigator.mediaDevices.getDisplayMedia=function(i){if(!(i&&i.video)){const s=new DOMException("getDisplayMedia without video constraints is undefined");return s.name="NotFoundError",s.code=8,Promise.reject(s)}return i.video===!0?i.video={mediaSource:e}:i.video.mediaSource=e,r.navigator.mediaDevices.getUserMedia(i)})}function as(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 Xt(r,e){if(typeof r!="object"||!(r.RTCPeerConnection||r.mozRTCPeerConnection))return;!r.RTCPeerConnection&&r.mozRTCPeerConnection&&(r.RTCPeerConnection=r.mozRTCPeerConnection),e.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach(function(s){const n=r.RTCPeerConnection.prototype[s],a={[s](){return arguments[0]=new(s==="addIceCandidate"?r.RTCIceCandidate:r.RTCSessionDescription)(arguments[0]),n.apply(this,arguments)}};r.RTCPeerConnection.prototype[s]=a[s]});const t={inboundrtp:"inbound-rtp",outboundrtp:"outbound-rtp",candidatepair:"candidate-pair",localcandidate:"local-candidate",remotecandidate:"remote-candidate"},i=r.RTCPeerConnection.prototype.getStats;r.RTCPeerConnection.prototype.getStats=function(){const[n,a,o]=arguments;return i.apply(this,[n||null]).then(u=>{if(e.version<53&&!a)try{u.forEach(c=>{c.type=t[c.type]||c.type})}catch(c){if(c.name!=="TypeError")throw c;u.forEach((d,h)=>{u.set(h,Object.assign({},d,{type:t[d.type]||d.type}))})}return u}).then(a,o)}}function cs(r){if(!(typeof r=="object"&&r.RTCPeerConnection&&r.RTCRtpSender)||r.RTCRtpSender&&"getStats"in r.RTCRtpSender.prototype)return;const e=r.RTCPeerConnection.prototype.getSenders;e&&(r.RTCPeerConnection.prototype.getSenders=function(){const s=e.apply(this,[]);return s.forEach(n=>n._pc=this),s});const t=r.RTCPeerConnection.prototype.addTrack;t&&(r.RTCPeerConnection.prototype.addTrack=function(){const s=t.apply(this,arguments);return s._pc=this,s}),r.RTCRtpSender.prototype.getStats=function(){return this.track?this._pc.getStats(this.track):Promise.resolve(new Map)}}function ds(r){if(!(typeof r=="object"&&r.RTCPeerConnection&&r.RTCRtpSender)||r.RTCRtpSender&&"getStats"in r.RTCRtpReceiver.prototype)return;const e=r.RTCPeerConnection.prototype.getReceivers;e&&(r.RTCPeerConnection.prototype.getReceivers=function(){const i=e.apply(this,[]);return i.forEach(s=>s._pc=this),i}),me(r,"track",t=>(t.receiver._pc=t.srcElement,t)),r.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track)}}function us(r){!r.RTCPeerConnection||"removeStream"in r.RTCPeerConnection.prototype||(r.RTCPeerConnection.prototype.removeStream=function(t){Ht("removeStream","removeTrack"),this.getSenders().forEach(i=>{i.track&&t.getTracks().includes(i.track)&&this.removeTrack(i)})})}function hs(r){r.DataChannel&&!r.RTCDataChannel&&(r.RTCDataChannel=r.DataChannel)}function ps(r){if(!(typeof r=="object"&&r.RTCPeerConnection))return;const e=r.RTCPeerConnection.prototype.addTransceiver;e&&(r.RTCPeerConnection.prototype.addTransceiver=function(){this.setParametersPromises=[];let i=arguments[1]&&arguments[1].sendEncodings;i===void 0&&(i=[]),i=[...i];const s=i.length>0;s&&i.forEach(a=>{if("rid"in a&&!/^[a-z0-9]{0,16}$/i.test(a.rid))throw new TypeError("Invalid RID value provided.");if("scaleResolutionDownBy"in a&&!(parseFloat(a.scaleResolutionDownBy)>=1))throw new RangeError("scale_resolution_down_by must be >= 1.0");if("maxFramerate"in a&&!(parseFloat(a.maxFramerate)>=0))throw new RangeError("max_framerate must be >= 0.0")});const n=e.apply(this,arguments);if(s){const{sender:a}=n,o=a.getParameters();(!("encodings"in o)||o.encodings.length===1&&Object.keys(o.encodings[0]).length===0)&&(o.encodings=i,a.sendEncodings=i,this.setParametersPromises.push(a.setParameters(o).then(()=>{delete a.sendEncodings}).catch(()=>{delete a.sendEncodings})))}return n})}function ls(r){if(!(typeof r=="object"&&r.RTCRtpSender))return;const e=r.RTCRtpSender.prototype.getParameters;e&&(r.RTCRtpSender.prototype.getParameters=function(){const i=e.apply(this,arguments);return"encodings"in i||(i.encodings=[].concat(this.sendEncodings||[{}])),i})}function ms(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 fs(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 _s=Object.freeze(Object.defineProperty({__proto__:null,shimAddTransceiver:ps,shimCreateAnswer:fs,shimCreateOffer:ms,shimGetDisplayMedia:ph,shimGetParameters:ls,shimGetUserMedia:os,shimOnTrack:as,shimPeerConnection:Xt,shimRTCDataChannel:hs,shimReceiverGetStats:ds,shimRemoveStream:us,shimSenderGetStats:cs},Symbol.toStringTag,{value:"Module"}));function gs(r){if(!(typeof r!="object"||!r.RTCPeerConnection)){if("getLocalStreams"in r.RTCPeerConnection.prototype||(r.RTCPeerConnection.prototype.getLocalStreams=function(){return this._localStreams||(this._localStreams=[]),this._localStreams}),!("addStream"in r.RTCPeerConnection.prototype)){const e=r.RTCPeerConnection.prototype.addTrack;r.RTCPeerConnection.prototype.addStream=function(i){this._localStreams||(this._localStreams=[]),this._localStreams.includes(i)||this._localStreams.push(i),i.getAudioTracks().forEach(s=>e.call(this,s,i)),i.getVideoTracks().forEach(s=>e.call(this,s,i))},r.RTCPeerConnection.prototype.addTrack=function(i,...s){return s&&s.forEach(n=>{this._localStreams?this._localStreams.includes(n)||this._localStreams.push(n):this._localStreams=[n]}),e.apply(this,arguments)}}"removeStream"in r.RTCPeerConnection.prototype||(r.RTCPeerConnection.prototype.removeStream=function(t){this._localStreams||(this._localStreams=[]);const i=this._localStreams.indexOf(t);if(i===-1)return;this._localStreams.splice(i,1);const s=t.getTracks();this.getSenders().forEach(n=>{s.includes(n.track)&&this.removeTrack(n)})})}}function vs(r){if(!(typeof r!="object"||!r.RTCPeerConnection)&&("getRemoteStreams"in r.RTCPeerConnection.prototype||(r.RTCPeerConnection.prototype.getRemoteStreams=function(){return this._remoteStreams?this._remoteStreams:[]}),!("onaddstream"in r.RTCPeerConnection.prototype))){Object.defineProperty(r.RTCPeerConnection.prototype,"onaddstream",{get(){return this._onaddstream},set(t){this._onaddstream&&(this.removeEventListener("addstream",this._onaddstream),this.removeEventListener("track",this._onaddstreampoly)),this.addEventListener("addstream",this._onaddstream=t),this.addEventListener("track",this._onaddstreampoly=i=>{i.streams.forEach(s=>{if(this._remoteStreams||(this._remoteStreams=[]),this._remoteStreams.includes(s))return;this._remoteStreams.push(s);const n=new Event("addstream");n.stream=s,this.dispatchEvent(n)})})}});const e=r.RTCPeerConnection.prototype.setRemoteDescription;r.RTCPeerConnection.prototype.setRemoteDescription=function(){const i=this;return this._onaddstreampoly||this.addEventListener("track",this._onaddstreampoly=function(s){s.streams.forEach(n=>{if(i._remoteStreams||(i._remoteStreams=[]),i._remoteStreams.indexOf(n)>=0)return;i._remoteStreams.push(n);const a=new Event("addstream");a.stream=n,i.dispatchEvent(a)})}),e.apply(i,arguments)}}}function Cs(r){if(typeof r!="object"||!r.RTCPeerConnection)return;const e=r.RTCPeerConnection.prototype,t=e.createOffer,i=e.createAnswer,s=e.setLocalDescription,n=e.setRemoteDescription,a=e.addIceCandidate;e.createOffer=function(c,d){const h=arguments.length>=2?arguments[2]:arguments[0],p=t.apply(this,[h]);return d?(p.then(c,d),Promise.resolve()):p},e.createAnswer=function(c,d){const h=arguments.length>=2?arguments[2]:arguments[0],p=i.apply(this,[h]);return d?(p.then(c,d),Promise.resolve()):p};let o=function(u,c,d){const h=s.apply(this,[u]);return d?(h.then(c,d),Promise.resolve()):h};e.setLocalDescription=o,o=function(u,c,d){const h=n.apply(this,[u]);return d?(h.then(c,d),Promise.resolve()):h},e.setRemoteDescription=o,o=function(u,c,d){const h=a.apply(this,[u]);return d?(h.then(c,d),Promise.resolve()):h},e.addIceCandidate=o}function ys(r){const e=r&&r.navigator;if(e.mediaDevices&&e.mediaDevices.getUserMedia){const t=e.mediaDevices,i=t.getUserMedia.bind(t);e.mediaDevices.getUserMedia=s=>i(Ss(s))}!e.getUserMedia&&e.mediaDevices&&e.mediaDevices.getUserMedia&&(e.getUserMedia=(function(i,s,n){e.mediaDevices.getUserMedia(i).then(s,n)}).bind(e))}function Ss(r){return r&&r.video!==void 0?Object.assign({},r,{video:Xi(r.video)}):r}function Ts(r){if(!r.RTCPeerConnection)return;const e=r.RTCPeerConnection;r.RTCPeerConnection=function(i,s){if(i&&i.iceServers){const n=[];for(let a=0;a<i.iceServers.length;a++){let o=i.iceServers[a];o.urls===void 0&&o.url?(Ht("RTCIceServer.url","RTCIceServer.urls"),o=JSON.parse(JSON.stringify(o)),o.urls=o.url,delete o.url,n.push(o)):n.push(i.iceServers[a])}i.iceServers=n}return new e(i,s)},r.RTCPeerConnection.prototype=e.prototype,"generateCertificate"in e&&Object.defineProperty(r.RTCPeerConnection,"generateCertificate",{get(){return e.generateCertificate}})}function Es(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 bs(r){const e=r.RTCPeerConnection.prototype.createOffer;r.RTCPeerConnection.prototype.createOffer=function(i){if(i){typeof i.offerToReceiveAudio<"u"&&(i.offerToReceiveAudio=!!i.offerToReceiveAudio);const s=this.getTransceivers().find(a=>a.receiver.track.kind==="audio");i.offerToReceiveAudio===!1&&s?s.direction==="sendrecv"?s.setDirection?s.setDirection("sendonly"):s.direction="sendonly":s.direction==="recvonly"&&(s.setDirection?s.setDirection("inactive"):s.direction="inactive"):i.offerToReceiveAudio===!0&&!s&&this.addTransceiver("audio",{direction:"recvonly"}),typeof i.offerToReceiveVideo<"u"&&(i.offerToReceiveVideo=!!i.offerToReceiveVideo);const n=this.getTransceivers().find(a=>a.receiver.track.kind==="video");i.offerToReceiveVideo===!1&&n?n.direction==="sendrecv"?n.setDirection?n.setDirection("sendonly"):n.direction="sendonly":n.direction==="recvonly"&&(n.setDirection?n.setDirection("inactive"):n.direction="inactive"):i.offerToReceiveVideo===!0&&!n&&this.addTransceiver("video",{direction:"recvonly"})}return e.apply(this,arguments)}}function ks(r){typeof r!="object"||r.AudioContext||(r.AudioContext=r.webkitAudioContext)}const Ps=Object.freeze(Object.defineProperty({__proto__:null,shimAudioContext:ks,shimCallbacksAPI:Cs,shimConstraints:Ss,shimCreateOfferLegacy:bs,shimGetUserMedia:ys,shimLocalStreamsAPI:gs,shimRTCIceServerUrls:Ts,shimRemoteStreamsAPI:vs,shimTrackEventTransceiver:Es},Symbol.toStringTag,{value:"Module"}));var Kt={exports:{}},Rs;function lh(){return Rs||(Rs=1,function(r){const e={};e.generateIdentifier=function(){return Math.random().toString(36).substring(2,12)},e.localCName=e.generateIdentifier(),e.splitLines=function(t){return t.trim().split(`
|
|
60
|
-
`).map(
|
|
61
|
-
m=`).map((s
|
|
62
|
-
`)},e.getDescription=function(t){const
|
|
63
|
-
`},e.parseExtmap=function(t){const
|
|
64
|
-
`},e.parseFmtp=function(t){const
|
|
65
|
-
`}return
|
|
66
|
-
`}),
|
|
67
|
-
`;return t.fingerprints.forEach(
|
|
68
|
-
`}),
|
|
69
|
-
`},e.parseCryptoKeyParams=function(t){if(t.indexOf("inline:")!==0)return null;const
|
|
68
|
+
`},qi}var La;function R_(){if(La)return De;La=1;var r=T_(),e=k_(),t=Hi();return De.grammar=t,De.write=e,De.parse=r.parse,De.parseParams=r.parseParams,De.parseFmtpConfig=r.parseFmtpConfig,De.parsePayloads=r.parsePayloads,De.parseRemoteCandidates=r.parseRemoteCandidates,De.parseImageAttributes=r.parseImageAttributes,De.parseSimulcastStreamList=r.parseSimulcastStreamList,De}var A_=R_();const ln=pe(A_);function hn(r){return new Promise(e=>{setTimeout(e,r)})}async function D_(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 Na(r,e={},t={}){const{timeout:n=0,retryDelay:i=0}=t;let{retryCount:s=0}=t;try{return await D_(r,e,n)}catch(a){if(s--,t.retryCount=s,s<0)throw a;return await hn(i),await Na(r,e,t)}}const x_=-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 I_(r,e,t){var u,d,h,f,b,T,v,C,k,g,z,N,A,L,U,G,F,K,ne,Q,Ge,xe,xr,Ir,zr,Vt,jt,Or,Ie,Mr,bn,En,Pr,Cn,wn,Tn;const n=await $i(e,t);await hn(r);const i=await $i(e,t),{audio:s,video:a}=n,{audio:o,video:l}=i,c={};if(s!=null&&s.codec&&(o!=null&&o.codec)){const lt=((u=o.outboundRtp)==null?void 0:u.timestamp)-((d=s.outboundRtp)==null?void 0:d.timestamp),Ze=((h=o.outboundRtp)==null?void 0:h.bytesSent)-((f=s.outboundRtp)==null?void 0:f.bytesSent),wt=((b=o.remoteInboundRtp)==null?void 0:b.packetsLost)-((T=s.remoteInboundRtp)==null?void 0:T.packetsLost),Be=((v=o.outboundRtp)==null?void 0:v.packetsSent)-((C=s.outboundRtp)==null?void 0:C.packetsSent);c.audio={codec:o.codec.mimeType,channels:o.codec.channels,sendBitrate:Ze/lt*8e3,packetsSent:(k=o.outboundRtp)==null?void 0:k.packetsSent,nackCount:(g=o.outboundRtp)==null?void 0:g.nackCount,packetsLost:(z=o.remoteInboundRtp)==null?void 0:z.packetsLost,packetsLostPercent:wt/Be}}if(a!=null&&a.codec&&(l!=null&&l.codec)){const lt=((N=l.outboundRtp)==null?void 0:N.timestamp)-((A=a.outboundRtp)==null?void 0:A.timestamp),Ze=((L=l.outboundRtp)==null?void 0:L.bytesSent)-((U=a.outboundRtp)==null?void 0:U.bytesSent),wt=((G=l.outboundRtp)==null?void 0:G.framesEncoded)-((F=a.outboundRtp)==null?void 0:F.framesEncoded),Be=((K=l.outboundRtp)==null?void 0:K.totalEncodeTime)-((ne=a.outboundRtp)==null?void 0:ne.totalEncodeTime),kn=((Q=l.outboundRtp)==null?void 0:Q.packetsSent)-((Ge=a.outboundRtp)==null?void 0:Ge.packetsSent),Ht=((xe=l.outboundRtp)==null?void 0:xe.totalPacketSendDelay)-((xr=a.outboundRtp)==null?void 0:xr.totalPacketSendDelay),Lr=((Ir=l.remoteInboundRtp)==null?void 0:Ir.packetsLost)-((zr=a.remoteInboundRtp)==null?void 0:zr.packetsLost);c.video={codec:l.codec.mimeType,sendBitrate:Ze/lt*8e3,frameWidth:(Vt=l.outboundRtp)==null?void 0:Vt.frameWidth,frameHeight:(jt=l.outboundRtp)==null?void 0:jt.frameHeight,framesPerSecond:(Or=l.outboundRtp)==null?void 0:Or.framesPerSecond,framesEncoded:(Ie=l.outboundRtp)==null?void 0:Ie.framesEncoded,framesEncodedPerSecond:wt*1e3/lt,keyFramesEncoded:(Mr=l.outboundRtp)==null?void 0:Mr.keyFramesEncoded,framesSent:(bn=l.outboundRtp)==null?void 0:bn.frameHeight,frameEncodeAvgTime:Be*1e3/wt,packetsSent:(En=l.outboundRtp)==null?void 0:En.packetsSent,packetSendDelay:Ht*1e3/kn,nackCount:(Pr=l.outboundRtp)==null?void 0:Pr.nackCount,firCount:(Cn=l.outboundRtp)==null?void 0:Cn.firCount,pliCount:(wn=l.outboundRtp)==null?void 0:wn.pliCount,packetsLost:(Tn=l.remoteInboundRtp)==null?void 0:Tn.packetsLost,packetsLostPercent:Lr/kn,deltaTime:lt}}return c}function me(r,e=x_){return r??e}function z_(r){var e,t,n,i,s,a,o,l,c,u,d,h,f,b,T,v,C,k,g,z,N;return{video_send_k_bitrate:me((e=r.video)==null?void 0:e.sendBitrate)/1e3,video_send_frame_rate:me((t=r.video)==null?void 0:t.framesPerSecond),video_encoder_output_frame_rate:me((n=r.video)==null?void 0:n.framesEncodedPerSecond),video_encoded_frame_width:me((i=r.video)==null?void 0:i.frameWidth),video_encoded_frame_height:me((s=r.video)==null?void 0:s.frameHeight),video_encoded_key_frames:me((a=r.video)==null?void 0:a.keyFramesEncoded),video_delta_time:me((o=r.video)==null?void 0:o.deltaTime,2e3),video_packets_sent:me((l=r.video)==null?void 0:l.packetsSent),video_nack_count:me((c=r.video)==null?void 0:c.nackCount),video_fir_count:me((u=r.video)==null?void 0:u.firCount),video_pli_count:me((d=r.video)==null?void 0:d.pliCount),video_packets_lost:me((h=r.video)==null?void 0:h.packetsLost),video_packets_lost_percent:(f=r.video)==null?void 0:f.packetsLostPercent,video_codec:(b=r.video)==null?void 0:b.codec,video_duration:(T=r.video)==null?void 0:T.deltaTime,audio_send_k_bitrate:me((v=r.audio)==null?void 0:v.sendBitrate)/1e3,audio_send_channels:me((C=r.audio)==null?void 0:C.channels),audio_packets_sent:me((k=r.audio)==null?void 0:k.packetsSent),audio_packets_lost:me((g=r.audio)==null?void 0:g.packetsLost),audio_packets_lost_percent:(z=r.audio)==null?void 0:z.packetsLostPercent,audio_codec:(N=r.audio)==null?void 0:N.codec}}function O_(r){return{video_send_k_bitrate:r.video.sendBitrate/1e3,video_send_frame_rate:r.video.framesPerSecond,video_encoded_frame_width:r.video.frameWidth,video_encoded_frame_height:r.video.frameHeight,video_encoded_key_frames:r.video.keyFramesEncoded,video_send_speed:r.video.sendSpeed/1e3,video_gop_size:r.video.gopSize,video_codec:r.video.codec,video_duration:0,audio_send_k_bitrate:r.audio.sendBitrate/1e3,audio_codec:r.audio.codec,audio_send_channels:r.audio.channels,audio_send_sample_rate:r.audio.sampleRate}}const M_=r=>{var t;if(!vs)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")})},P_=r=>{r.ext&&(Jc||Ur)&&(r.ext=r.ext.filter(e=>{var t;return!((t=e.uri)!=null&&t.includes("video-orientation"))}))};function L_(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 _e=new ot("PCConnect");class N_{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 pushUrl(){return this._signalUrl}get sessionId(){return this._sessionId}async publish(e,t,n){var d;const i=new RTCPeerConnection;this._pc=i,this._bindRTCEvent();const s=e.filter(h=>(h==null?void 0:h.kind)==="audio")[0],a=e.filter(h=>(h==null?void 0:h.kind)==="video")[0];s&&this._ms.addTrack(s),a&&this._ms.addTrack(a),this._audioTransceiver=i.addTransceiver(s||"audio",{direction:"sendonly",sendEncodings:[{maxBitrate:t[0]}],streams:[this._ms]}),_e.log("add track to pc,",s),this._videoTransceiver=i.addTransceiver(a||"video",{direction:"sendonly",sendEncodings:[{maxBitrate:t[1]}],streams:[this._ms]}),_e.log("add track to pc,",a);const o=await i.createOffer();_e.groupCollapsed("local offer"),_e.log(o.sdp);const l=ln.parse(o.sdp);l.media.forEach(h=>{h.type==="audio"?M_(h):h.type==="video"&&(P_(h),L_(h,t[1]))}),o.sdp=ln.write(l),_e.log("local offer modified"),_e.log(o.sdp),await i.setLocalDescription(o);const c=await Na(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*ko:(d=this._opts)==null?void 0:d.timeout});if((c==null?void 0:c.code)!==200)throw{code:c.code,message:c.message};_e.log("remote answer:"),_e.log(c.remoteSdp.sdp);const u=ln.parse(c.remoteSdp.sdp);if(u.media.forEach(h=>{var f;(f=h.fingerprint)!=null&&f.hash&&(h.fingerprint.hash=h.fingerprint.hash.toUpperCase())}),c.remoteSdp.sdp=ln.write(u),_e.log("remote answer modified"),_e.log(c.remoteSdp.sdp),_e.groupEnd(),i.connectionState==="closed"){_e.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)),_e.log(`replace ${t} track done! ${i==null?void 0:i.label} -> ${e==null?void 0:e.label}`))}applyBitrate(e,t,n){var a,o,l;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=(l=s.encodings)!=null&&l.length?s.encodings:[{}],n?s.encodings[0].minBitrate=e:s.encodings[0].maxBitrate=e,i.setParameters(s),_e.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,_e.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 I_(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",()=>{_e.log("onconnectionstatechange:",e.connectionState),this._onConnectStateChange(e.connectionState)})}}var at=(r=>(r.OnError="onerror",r.OnConnectClosed="onconnectclosed",r.OnFirstFramePushed="onfirstframepushed",r))(at||{}),ct=(r=>(r.Video="video",r.Audio="audio",r))(ct||{}),ke=(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))(ke||{}),Et=(r=>(r.Ready="ready",r.Error="error",r.FirstFramePushed="firstframepushed",r.Flvfile="flvfile",r.STATS="stats",r.Close="close",r))(Et||{}),Ki={exports:{}},Ua;function U_(){return Ua||(Ua=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(l,c,u){this.fn=l,this.context=c,this.once=u||!1}function s(l,c,u,d,h){if(typeof u!="function")throw new TypeError("The listener must be a function");var f=new i(u,d||l,h),b=t?t+c:c;return l._events[b]?l._events[b].fn?l._events[b]=[l._events[b],f]:l._events[b].push(f):(l._events[b]=f,l._eventsCount++),l}function a(l,c){--l._eventsCount===0?l._events=new n:delete l._events[c]}function o(){this._events=new n,this._eventsCount=0}o.prototype.eventNames=function(){var c=[],u,d;if(this._eventsCount===0)return c;for(d in u=this._events)e.call(u,d)&&c.push(t?d.slice(1):d);return Object.getOwnPropertySymbols?c.concat(Object.getOwnPropertySymbols(u)):c},o.prototype.listeners=function(c){var u=t?t+c:c,d=this._events[u];if(!d)return[];if(d.fn)return[d.fn];for(var h=0,f=d.length,b=new Array(f);h<f;h++)b[h]=d[h].fn;return b},o.prototype.listenerCount=function(c){var u=t?t+c:c,d=this._events[u];return d?d.fn?1:d.length:0},o.prototype.emit=function(c,u,d,h,f,b){var T=t?t+c:c;if(!this._events[T])return!1;var v=this._events[T],C=arguments.length,k,g;if(v.fn){switch(v.once&&this.removeListener(c,v.fn,void 0,!0),C){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,d),!0;case 4:return v.fn.call(v.context,u,d,h),!0;case 5:return v.fn.call(v.context,u,d,h,f),!0;case 6:return v.fn.call(v.context,u,d,h,f,b),!0}for(g=1,k=new Array(C-1);g<C;g++)k[g-1]=arguments[g];v.fn.apply(v.context,k)}else{var z=v.length,N;for(g=0;g<z;g++)switch(v[g].once&&this.removeListener(c,v[g].fn,void 0,!0),C){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,d);break;case 4:v[g].fn.call(v[g].context,u,d,h);break;default:if(!k)for(N=1,k=new Array(C-1);N<C;N++)k[N-1]=arguments[N];v[g].fn.apply(v[g].context,k)}}return!0},o.prototype.on=function(c,u,d){return s(this,c,u,d,!1)},o.prototype.once=function(c,u,d){return s(this,c,u,d,!0)},o.prototype.removeListener=function(c,u,d,h){var f=t?t+c:c;if(!this._events[f])return this;if(!u)return a(this,f),this;var b=this._events[f];if(b.fn)b.fn===u&&(!h||b.once)&&(!d||b.context===d)&&a(this,f);else{for(var T=0,v=[],C=b.length;T<C;T++)(b[T].fn!==u||h&&!b[T].once||d&&b[T].context!==d)&&v.push(b[T]);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 G_=U_();const B_=pe(G_);var dn=(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))(dn||{});class Ga 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 Ba(r,e,t){return new Ga(r,e,t)}const Ft=class Ft{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 Ft.enable}get _enableLong(){return Ft.enableLong}get long(){return this._enableLong}};Ft.enable=!1,Ft.enableLong=!1;let ut=Ft;const Re=new ut("RTMP_Capture");class F_{constructor(e){this._videoFirstframeCaptured=!1,this._audioFirstframeCaptured=!1,this._videoProcessorReader=null,this._audioProcessorReader=null,this._bridge=e}get audioTrack(){return this._bridge.audioMsTrack}get videoTrack(){return this._bridge.videoMsTrack}start(){this._startVideoCapture(),this._startAudioCapture()}restartCapture(e){if(Re.log(`replace ${e} track`),e===ct.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){Re.log("no video track to capture");return}if(this.videoTrack.readyState!=="live"){Re.warn("video track not live");return}const e=new MediaStreamTrackProcessor(this.videoTrack);e.track=this.videoTrack;const t=e.readable.getReader();this._videoProcessorReader=t,Re.log("start capture video frame",this.videoTrack);let n;for(;;){n&&clearInterval(n),n=setTimeout(()=>{Re.warn("long time no capture output"),this._bridge._postMockVideoEncodeFlag()},1500);const s=await t.read();if(clearInterval(n),this._videoFirstframeCaptured||(this._videoFirstframeCaptured=!0,Re.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,Re.log("video track read done!",e.track)}async _startAudioCapture(){if(!this.audioTrack){Re.log("no audio track to capture");return}if(this.audioTrack.readyState!=="live"){Re.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,Re.log("start capture audio frame");;){const n=await t.read();if(this._audioFirstframeCaptured||(this._audioFirstframeCaptured=!0,Re.log("audio first frame captured")),n.done||!n.value)break;this._bridge._postAudioFrame(n.value,this.audioTrack.getSettings())}this._audioFirstframeCaptured=!1,this._audioProcessorReader=null,Re.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 Fa='(function(){"use strict";var l=(i=>(i.OnVideoCaptured="onvideocaptured",i.OnAudioCaptured="onaudiocaptured",i.OnVideoCaptureNoOutput="onvideocapturenooutput",i.OnVideoEncoded="onvideoencoded",i.OnAudioEncoded="onaudioencoded",i.OnEncodedFrame="onencodedframe",i.OnPacketed="onpacketed",i.OnUpstreamFeedback="onupstreamfeedback",i.OnBitrateChanged="onbitratechanged",i))(l||{}),O=(i=>(i.OnError="onerror",i.OnConnectClosed="onconnectclosed",i.OnFirstFramePushed="onfirstframepushed",i))(O||{}),I=(i=>(i.Video="video",i.Audio="audio",i))(I||{}),v=(i=>(i.Init="init",i.AvExist="avexist",i.VideoFrame="videoframe",i.MockVideoEncode="mockvideoencode",i.AudioFrame="audioframe",i.AdjustBitrate="adjustbitrate",i.Publish="publish",i.UnPublish="unpublish",i.Download="download",i.GetStats="getstats",i.EncodeConfig="encodeconfig",i))(v||{}),w=(i=>(i.Ready="ready",i.Error="error",i.FirstFramePushed="firstframepushed",i.Flvfile="flvfile",i.STATS="stats",i.Close="close",i))(w||{});function $(i){return i&&i.__esModule&&Object.prototype.hasOwnProperty.call(i,"default")?i.default:i}var k={exports:{}},U;function q(){return U||(U=1,function(i){var t=Object.prototype.hasOwnProperty,e="~";function s(){}Object.create&&(s.prototype=Object.create(null),new s().__proto__||(e=!1));function r(u,a,n){this.fn=u,this.context=a,this.once=n||!1}function o(u,a,n,h,m){if(typeof n!="function")throw new TypeError("The listener must be a function");var g=new r(n,h||u,m),f=e?e+a:a;return u._events[f]?u._events[f].fn?u._events[f]=[u._events[f],g]:u._events[f].push(g):(u._events[f]=g,u._eventsCount++),u}function _(u,a){--u._eventsCount===0?u._events=new s:delete u._events[a]}function c(){this._events=new s,this._eventsCount=0}c.prototype.eventNames=function(){var a=[],n,h;if(this._eventsCount===0)return a;for(h in n=this._events)t.call(n,h)&&a.push(e?h.slice(1):h);return Object.getOwnPropertySymbols?a.concat(Object.getOwnPropertySymbols(n)):a},c.prototype.listeners=function(a){var n=e?e+a:a,h=this._events[n];if(!h)return[];if(h.fn)return[h.fn];for(var m=0,g=h.length,f=new Array(g);m<g;m++)f[m]=h[m].fn;return f},c.prototype.listenerCount=function(a){var n=e?e+a:a,h=this._events[n];return h?h.fn?1:h.length:0},c.prototype.emit=function(a,n,h,m,g,f){var F=e?e+a:a;if(!this._events[F])return!1;var d=this._events[F],C=arguments.length,N,p;if(d.fn){switch(d.once&&this.removeListener(a,d.fn,void 0,!0),C){case 1:return d.fn.call(d.context),!0;case 2:return d.fn.call(d.context,n),!0;case 3:return d.fn.call(d.context,n,h),!0;case 4:return d.fn.call(d.context,n,h,m),!0;case 5:return d.fn.call(d.context,n,h,m,g),!0;case 6:return d.fn.call(d.context,n,h,m,g,f),!0}for(p=1,N=new Array(C-1);p<C;p++)N[p-1]=arguments[p];d.fn.apply(d.context,N)}else{var fe=d.length,R;for(p=0;p<fe;p++)switch(d[p].once&&this.removeListener(a,d[p].fn,void 0,!0),C){case 1:d[p].fn.call(d[p].context);break;case 2:d[p].fn.call(d[p].context,n);break;case 3:d[p].fn.call(d[p].context,n,h);break;case 4:d[p].fn.call(d[p].context,n,h,m);break;default:if(!N)for(R=1,N=new Array(C-1);R<C;R++)N[R-1]=arguments[R];d[p].fn.apply(d[p].context,N)}}return!0},c.prototype.on=function(a,n,h){return o(this,a,n,h,!1)},c.prototype.once=function(a,n,h){return o(this,a,n,h,!0)},c.prototype.removeListener=function(a,n,h,m){var g=e?e+a:a;if(!this._events[g])return this;if(!n)return _(this,g),this;var f=this._events[g];if(f.fn)f.fn===n&&(!m||f.once)&&(!h||f.context===h)&&_(this,g);else{for(var F=0,d=[],C=f.length;F<C;F++)(f[F].fn!==n||m&&!f[F].once||h&&f[F].context!==h)&&d.push(f[F]);d.length?this._events[g]=d.length===1?d[0]:d:_(this,g)}return this},c.prototype.removeAllListeners=function(a){var n;return a?(n=e?e+a:a,this._events[n]&&_(this,n)):(this._events=new s,this._eventsCount=0),this},c.prototype.off=c.prototype.removeListener,c.prototype.addListener=c.prototype.on,c.prefixed=e,c.EventEmitter=c,i.exports=c}(k)),k.exports}var z=q(),H=$(z);const x=class x{constructor(t){this.group=(...e)=>{this._enabled&&console.group(`[${this._prefix}]: `,...e)},this.groupCollapsed=(...e)=>{this._enabled&&console.groupCollapsed(`[${this._prefix}]: `,...e)},this.groupEnd=()=>{this._enabled&&console.groupEnd()},this.log=(...e)=>{this._enabled&&console.log(`[${this._prefix}]: `,...e)},this.warn=(...e)=>{this._enabled&&console.warn(`[${this._prefix}]: `,...e)},this.error=(...e)=>{this._enabled&&console.error(`[${this._prefix}]: `,...e)},this.table=(...e)=>{this._enabled&&console.table(...e)},this._prefix=t}get _enabled(){return x.enable}get _enableLong(){return x.enableLong}get long(){return this._enableLong}};x.enable=!1,x.enableLong=!1;let E=x;function S(i){i=i.filter(Boolean);const t=new Uint8Array(i.reduce((s,r)=>s+r.byteLength,0));let e=0;return i.forEach(s=>{t.set(s,e),e+=s.byteLength}),t}const A={codec:"avc1.4DE033",MaxCachedFrameSize:100,RealSpeedPercent:.8,UplinkBitrateCheckInterval:60*1e3,VideoBitrateDefault:1e6,AudioBitrateDefault:68e3,gopSize:90,sampleRate:48e3,channel:2,audioEncoderPath:"https://lf-unpkg.volccdn.com/obj/vcloudfe/sdk/Web_push/1.0.1/1735619140327/pcm2aac.js",audioEncoderWasmPath:"https://lf-unpkg.volccdn.com/obj/vcloudfe/sdk/Web_push/1.0.2/1735619208418/pcm2aac.wasm",ignoreRelPublish:!1},T=new E("RTMP_AudioEncoder");class j{constructor(t){this._encodedFrameCount=0,this._ready=!1,this._lastFrame=null,this._aacOutput=(e,s)=>{const r=this._module.HEAPU8.subarray(e,e+s);if(!this._lastFrame)return;this._encodedFrameCount++;const{props:o}=this._lastFrame,_={buffer:new Uint8Array(r),props:{timestamp:parseInt(o.timestamp/1e3),originTs:parseInt(o.timestamp/1e3)}};this._core.emit(l.OnAudioEncoded,_)},this._core=t}async init(){const t=await fetch(A.audioEncoderPath).then(_=>_.text());new Function(`self.exports={};${t}`)();const e=self.exports.m;let s,r;const o=new Promise((_,c)=>{r=_,s=c});return e({instantiateWasm:function(_,c){fetch(A.audioEncoderWasmPath).then(u=>u.arrayBuffer()).then(u=>WebAssembly.instantiate(u,_)).then(function(u){return c(u.instance)}).then(()=>{r(),T.log("aac module inited")}).catch(u=>{s(u)})}}).then(_=>{const c=_.addFunction(this._aacOutput,"vii");_._init_callback(c),this._module=_}).catch(s),o}rnnoise(t){var s;const e=t.length;for(let r=0;r<e;r++)t[r]=t[r]*32768;(s=this._rnnoiseModule)==null||s.processFrame(t);for(let r=0;r<e;r++)t[r]=t[r]/32768}updateConfigure(){this._module._flush(),this._module._free_encoder(),this._ready=!1}encode(t){if(!this._ready){const o=this._start_encoder();if(o<0)throw new Error(`init aac encoder error, code:${o}`)}this._lastFrame=t;const e=t.buffer.buffer,s=this._module._malloc(e.byteLength);this._module.HEAPU8.subarray(s,s+e.byteLength).set(new Uint8Array(e));const r=this._module._encode_one_frame(s);if(r<0)throw new Error(`encode aac frame error, code:${r}`)}_start_encoder(){const t=this._core.getSetting(),e=this._module._init_encoder(t.sampleRate,t.channel,t.audioBitrate);if(e<0)return e;this._ready=!0,T.log(`init encoder: sampleRate=${t.sampleRate}, channel:${t.channel}, bitrate:${t.audioBitrate}`)}destroy(){var t;(t=this._module)==null||t._free_encoder()}}const P=1024;class M{constructor(){this._queue=[],this._sampleCount=0}compose(t){if(this._queue.push(t),this._sampleCount+=t.data.audioData.numberOfFrames,this._sampleCount>=P)return this._doCompose()}_doCompose(){const t=new Float32Array(P);let e=0,s=P;const r=this._queue[0];for(;;){const o=this._queue[0];if(!o)break;const _=Math.min(s,o.data.audioData.numberOfFrames-o.offset,480),c=o.data.buffer.slice(o.offset,o.offset+_);if(o.offset+=_,o.offset>=o.data.audioData.numberOfFrames&&this._queue.shift(),s-=_,this._sampleCount-=_,t.set(c,e),e+=_,s<=0)break}return{buffer:t,props:{timestamp:r.data.audioData.timestamp,sampleRate:r.data.audioData.sampleRate,numberOfChannels:r.data.audioData.numberOfChannels}}}}var y=(i=>(i[i.RTMP_INIT_FAIL=3e3]="RTMP_INIT_FAIL",i[i.AUDIO_ENCODER_INIT_FAIL=3001]="AUDIO_ENCODER_INIT_FAIL",i[i.AUDIO_RRNOISE_INIT_FAIL=3002]="AUDIO_RRNOISE_INIT_FAIL",i[i.AUDIO_ENCODE_FAIL=3003]="AUDIO_ENCODE_FAIL",i[i.VIDEO_ENCODE_CONFIGURE_FAIL=3004]="VIDEO_ENCODE_CONFIGURE_FAIL",i[i.VIDEO_ENCODE_FAIL=3005]="VIDEO_ENCODE_FAIL",i[i.WTP_OPEN_FAIL=3006]="WTP_OPEN_FAIL",i[i.WTP_CONNECT_FAIL=3007]="WTP_CONNECT_FAIL",i[i.WORKER_ERROR=3008]="WORKER_ERROR",i))(y||{});class W extends Error{constructor(t,e,s){super(),this.code=t,this.message=e,s&&(this.ext=s),this.toJson=()=>({code:this.code,message:this.message,ext:this.ext})}}function b(i,t,e){return new W(i,t,e)}class G{constructor(t){this._audioFrameQueue=new M,this.encode=e=>{const s=new Float32Array(e.numberOfFrames);e.copyTo(s,{planeIndex:0,frameOffset:0,frameCount:e.numberOfFrames});const r=this._audioFrameQueue.compose({offset:0,data:{audioData:e,buffer:s}});if(r)try{this._encoder.encode(r)}catch(o){this._core.emit(O.OnError,b(y.AUDIO_ENCODE_FAIL,o.message))}},this._core=t,this._encoder=new j(t)}async init(){try{await this._encoder.init()}catch(t){throw b(y.AUDIO_ENCODER_INIT_FAIL,t.message)}}setConfiguration(t){const e=Object.assign({},this._core.getSetting(),{audioBitrate:t});this._core.updateSetting(e),this._encoder.updateConfigure()}destroy(){this._encoder.destroy()}}const L=new E("RTMP_VEncoder");class J{constructor(t){this._encoder=null,this._queue=[],this._encodeTimer=0,this._loopEncodeTimer=0,this._frameIndex=0,this._gopSize=0,this._encodedFrameCount=0,this._lastFrame=null,this._startTimer=()=>{this._clearEncodeTimer(),this._encodeTimer=setInterval(()=>{const e=this._queue.shift();if(!(!e||!this._encoder||this._encoder.state==="closed"))try{this._encoder.encode(e,{keyFrame:this._frameIndex%this._gopSize===0}),this._frameIndex++,this._lastFrame&&this._lastFrame.close(),this._lastFrame=e}catch(s){L.log("encode frame error",s)}},5)},this._core=t}configurate(t){return this._gopSize=t.gopSize,this._encoder?this.flush().then(()=>this._configure(t)):this._configure(t)}_configure(t){return this._clearEncodeTimer(),L.log("start config encoder",t),VideoEncoder.isConfigSupported(t).then(e=>{if(!e.supported)throw new Error(`VideoEncoder not support config, ${JSON.stringify(t)}`);this._encoder=new VideoEncoder({output:(s,r)=>{const o=new Uint8Array(s.byteLength);s.copyTo(o),this._emitFrame(o,s,r)},error:s=>{this._clearEncodeTimer(),this._core.emit(O.OnError,b(y.VIDEO_ENCODE_FAIL,s.message))}}),this._encoder.configure(t),L.log("encoder configured")}).then(this._startTimer).catch(e=>{throw b(y.VIDEO_ENCODE_CONFIGURE_FAIL,e.message)})}_emitFrame(t,e,s){this._encodedFrameCount++,this._core.emit(l.OnVideoEncoded,{buffer:t,props:{byteLength:e.byteLength,duration:e.duration,timestamp:parseInt(e.timestamp/1e3),originTs:parseInt(e.timestamp/1e3),type:e.type},cfg:s.decoderConfig})}_clearEncodeTimer(){clearInterval(this._encodeTimer)}_clearLoopEncodeTimer(){this._loopEncodeTimer&&clearInterval(this._loopEncodeTimer)}flush(){return this._encoder?this._encoder.flush().then(()=>{var t;this._clearEncodeTimer(),(t=this._encoder)==null||t.close(),this._frameIndex=0,this._encoder=null,L.log("encoder flush & closed")}).catch(t=>{console.log("encoder flush & close error:",t)}):Promise.resolve()}encode(t){this._clearLoopEncodeTimer(),this._queue.push(t)}startLoop(t){if(!this._lastFrame)return;const e=Math.floor(1e3/t*1e3);L.log("start encode last frame looped, ",t,"increment:",e),this._loopEncodeTimer=setInterval(()=>{if(!this._lastFrame)return;const s=new VideoFrame(this._lastFrame,{duration:e,timestamp:(this._lastFrame.timestamp||0)+e});this._queue.push(s)},Math.floor(1e3/t))}destroy(){this._queue.forEach(t=>t.close()),this._lastFrame&&this._lastFrame.close(),this._clearEncodeTimer(),this._clearLoopEncodeTimer(),this.flush()}}const Q=new E("RTMP_VideoEncode");class K{constructor(t){this._core=t,this._encoder=new J(t)}async setConfiguration(t={}){const e=Object.assign({},this._core.getSetting(),t),s={width:e.width,height:e.height,displayWidth:e.width,displayHeight:e.height,bitrate:e.videoBitrate,framerate:Math.floor(e.frameRate),codec:e.codec,gopSize:e.gopSize,hardwareAcceleration:e.hardwareAcceleration};this._core.updateSetting(e),Q.log("set Configuration:",s,t);try{await this._encoder.configurate(s)}catch(r){this._core.emit(O.OnError,r)}}encode(t){this._encoder.encode(t)}startLoopEncodeLastFrame(){this._encoder.startLoop(this._core.getSetting().frameRate)}flushEncoder(){this._encoder.flush()}destroy(){this._encoder.destroy()}}const V=new E("RTMP_AVSync");class Z{constructor(t){this._videoFrameGot=!1,this._videoBaseDts=0,this._audioBaseDts=0,this._videoNextDts=0,this._videoLastDts=0,this._audioNextDts=0,this._lastVideoReceived=0,this._core=t}get avExist(){return this._core.getSetting().hasVideo&&this._core.getSetting().hasAudio}get videoRefDuration(){return parseInt(1e3/this._core.getSetting().frameRate)}get audioRefDuration(){return parseInt(1024/this._core.getSetting().sampleRate*1e3)}addVideoFrame(t){this._videoFrameGot||(this._videoFrameGot=!0);const e=t.props;if(Math.abs(this._videoNextDts-e.timestamp-this._videoBaseDts)>1e3){const r=Date.now()-this._lastVideoReceived;this._videoNextDts=this._videoNextDts===this._audioNextDts?this._videoNextDts+this.videoRefDuration:this._audioNextDts||this._videoNextDts+r,this._videoBaseDts=this._videoNextDts-e.timestamp,V.warn(`video stream timestamp breaked! dts:${this._videoNextDts} -> ${e.timestamp}, videoBaseDts=${this._videoBaseDts}, deltaToLastFrame=${r}`)}e.timestamp=e.timestamp+this._videoBaseDts;const s=e.timestamp-this._videoLastDts;return s>100&&V.warn("video frame large gap",s),this._videoLastDts=this._videoNextDts=e.timestamp,V.long&&V.log(`V frame, dts: ${e.timestamp}, originDts:${e.originTs}, videoBaseDts=${this._videoBaseDts}, type=${e.type}, duration=${s}`),this._lastVideoReceived=Date.now(),this._core.emit(l.OnEncodedFrame,I.Video,t),{size:t.buffer.length,duration:s,key:t.props.type==="key"}}addAudioFrame(t){if(this.avExist&&!this._videoFrameGot)return;const e=t.props;return this._audioBaseDts||(this._audioBaseDts=e.timestamp-this._videoNextDts),Math.abs(e.timestamp-this._audioBaseDts-this._audioNextDts)>1e3&&(this._audioBaseDts=this._audioNextDts+this.audioRefDuration-e.timestamp,V.warn(`audio stream timestamp breaked! dts:${this._audioNextDts} -> ${e.timestamp}, audioBaseDts=${this._audioBaseDts}`)),this._audioNextDts=e.timestamp=e.timestamp-this._audioBaseDts,V.long&&V.log(`A frame, dts: ${e.timestamp}, originDts:${e.originTs}`),this._core.emit(l.OnEncodedFrame,I.Audio,t),{size:t.buffer.length,duration:this.audioRefDuration}}}class X{constructor(){this._videoSize=0,this._videoDuration=0,this._videoBitrate=0,this._frameCount=0,this._fps=0,this._videoEncodedCount=0,this._keyCount=0,this._audioSize=0,this._audioDuration=0,this._audioBitrate=0,this._audioEncodedCount=0}get videoStats(){return{sendBitrate:this._videoBitrate,framesPerSecond:this._fps,framesEncoded:this._videoEncodedCount,keyFramesEncoded:this._keyCount}}get audioStats(){return{sendBitrate:this._audioBitrate,framesEncoded:this._audioEncodedCount}}addVideoSample({size:t,duration:e,key:s}){this._videoEncodedCount++,this._videoSize+=t,this._videoDuration+=e,this._frameCount++,s&&this._keyCount++,this._videoDuration>=1e3&&(this._videoBitrate=Math.floor(this._videoSize/this._videoDuration*8e3),this._fps=this._frameCount,this._frameCount=0,this._videoSize=0,this._videoDuration=0)}addAudioSample({size:t,duration:e}){this._audioEncodedCount++,this._audioSize+=t,this._audioDuration+=e,this._audioDuration>=1e3&&(this._audioBitrate=Math.floor(this._audioSize/this._audioDuration*1e3),this._audioSize=0,this._audioDuration=0)}}const Y=new E("RTMP_EncodeController");class ee{constructor(t){this._analyse=new X,this._gotFrame=!1,this._OnVideoCaptured=(e,s)=>{this._gotFrame=!0,this._videoSettingChanged(s)&&(Y.log("video track setting changed!",s),this._core.updateSetting({width:s.width,height:s.height,frameRate:s.frameRate,vDeviceId:s.deviceId}),this._videoEncode.setConfiguration()),this._videoEncode.encode(e)},this._OnVideoCaptureNoOutput=()=>{this._videoEncode.startLoopEncodeLastFrame()},this._OnAudioCaptured=e=>{this._gotFrame=!0,this._audioEncode.encode(e)},this._OnVideoEncoded=e=>{const s=this._avSync.addVideoFrame(e);this._analyse.addVideoSample(s)},this._OnAudioEncoded=e=>{if(!e.buffer.length)return;const s=this._avSync.addAudioFrame(e);s&&this._analyse.addAudioSample(s)},this._OnUpstreamFeedback=e=>{this._videoEncode.setConfiguration(e)},this._OnBitrateChanged=(e,s)=>{this._gotFrame&&(e===I.Video&&this._videoEncode.setConfiguration({videoBitrate:s}),e===I.Audio&&this._audioEncode.setConfiguration(s))},this._core=t,this._audioEncode=new G(t),this._videoEncode=new K(t),this._avSync=new Z(t),this._bindEvents()}getStats(){return{video:this._analyse.videoStats,audio:this._analyse.audioStats}}init(){return this._audioEncode.init()}_bindEvents(){this._core.on(l.OnVideoCaptured,this._OnVideoCaptured),this._core.on(l.OnAudioCaptured,this._OnAudioCaptured),this._core.on(l.OnVideoCaptureNoOutput,this._OnVideoCaptureNoOutput),this._core.on(l.OnVideoEncoded,this._OnVideoEncoded),this._core.on(l.OnAudioEncoded,this._OnAudioEncoded),this._core.on(l.OnUpstreamFeedback,this._OnUpstreamFeedback),this._core.on(l.OnBitrateChanged,this._OnBitrateChanged)}_videoSettingChanged(t){const e=this._core.getSetting();return t.width!==e.width||t.height!==e.height||Math.floor(t.frameRate)!==Math.floor(e.frameRate)||t.deviceId!==e.vDeviceId}destroy(){this._videoEncode.destroy(),this._audioEncode.destroy()}}var B=(i=>(i[i.AUDIO=8]="AUDIO",i[i.VIDEO=9]="VIDEO",i[i.SCRIPT_DATA=18]="SCRIPT_DATA",i))(B||{});const te=10,ie=1,se=7,oe={96e3:0,48e3:3,44100:4,22050:7,16e3:8,8e3:11};function re(i){const t=(i[4]&3)+1;let e;const s=[],r=[];let o=6;const _=i[5]&31;let c;for(let n=0;n<_;n++){if(c=i[o]<<8|i[o+1],o+=2,!c)continue;const h=i.subarray(o,o+c);o+=c,s.push(h)}const u=i[o];o++;let a;for(let n=0;n<u;n++)a=i[o]<<8|i[o+1],o+=2,a&&(r.push(i.subarray(o,o+a)),o+=a);return{sps:e,spsArr:s,ppsArr:r,nalUnitSize:t}}class ne{constructor(){this._cfg={hasVideo:!1,hasAudio:!1,sampleRate:48e3,channelCount:1},this._hasAudioSeqHeader=!1,this._hasVideoSeqHeader=!1}setConfig(t){this._cfg=Object.assign(this._cfg,t)}genHeader(){const t=[70,76,86,1,(this._cfg.hasAudio?1:0)<<2|(this._cfg.hasVideo?1:0),0,0,0,9,0,0,0,0];return new Uint8Array(t)}genSeqTag(t,e){let s;t===8?(s=this._genAudioTagPaylod(0,e),this._hasAudioSeqHeader=!0):(s=this._genVideoTagPayload(0,e),this._hasVideoSeqHeader=!0);const r=this._genTagHeader(t,s.length,e.props.timestamp),o=r.length+s.length;return S([r,s,new Uint8Array([o>>>24,o>>>16,o>>>8,o])])}genFrameTag(t,e){let s;t===8?s=this._genAudioTagPaylod(1,e):s=this._genVideoTagPayload(1,e);const r=this._genTagHeader(t,s.length,e.props.timestamp),o=r.length+s.length;return S([r,s,new Uint8Array([o>>>24,o>>>16,o>>>8,o])])}_genTagHeader(t,e,s){return new Uint8Array([t,e>>>16,e>>>8,e,s>>>16,s>>>8,s,s>>>24,0,0,0])}_genAudioTagPaylod(t,e){return S(t===0?[this._genAudioTagHeader(),this._genAudioSequenceHeader()]:[this._genAudioTagHeader(),this._genAudioData(e)])}_genAudioTagHeader(){return new Uint8Array([te<<4|12|ie<<1|this._cfg.channelCount-1])}_genAudioSequenceHeader(){const t=4096|oe[this._cfg.sampleRate]<<7|this._cfg.channelCount<<3;return new Uint8Array([0,t>>8,t])}_genAudioData(t){const e=new Uint8Array(1+t.buffer.length);return e.set([1],0),e.set(t.buffer,1),e}_genVideoTagPayload(t,e){return S(t===0?[this._genVideoTagHeader(e),this._genVideoSequenceHeader(e)]:[this._genVideoTagHeader(e),this._genVideoData(e)])}_genVideoTagHeader(t){return new Uint8Array([(t.props.type==="key"?1:2)<<4|se,this._hasVideoSeqHeader?1:0,0,0,0])}_genVideoSequenceHeader(t){return new Uint8Array(t.cfg.description)}_genVideoData(t){if(t.props.type==="delta")return t.buffer;const e=re(new Uint8Array(t.cfg.description)),s=e.spsArr[0].length,r=e.ppsArr[0].length;return S([new Uint8Array([0,0,s>>8,s%256]),e.spsArr[0],new Uint8Array([0,0,r>>8,r%256]),e.ppsArr[0],t.buffer])}}const ae=new E("RTMP_Packet");class de{constructor(t){this._firstFrame=!0,this._flv=new ne,this._OnEncodedFrame=(e,s)=>{if(this._firstFrame){const o=this._core.getSetting();this._flv.setConfig({hasVideo:o.hasVideo,hasAudio:o.hasAudio,sampleRate:o.sampleRate,channelCount:o.channel});const _=this._flv.genHeader();if(this._core.emit(l.OnPacketed,_),o.hasVideo){const c=this._flv.genSeqTag(B.VIDEO,s);this._core.emit(l.OnPacketed,c)}if(o.hasAudio){const c=this._flv.genSeqTag(B.AUDIO,s);this._core.emit(l.OnPacketed,c)}this._firstFrame=!1,ae.log("first frame encoded & packed")}const r=this._flv.genFrameTag(e==="video"?B.VIDEO:B.AUDIO,s);this._core.emit(l.OnPacketed,r,s.props.type==="key")},this._core=t,this._bindEvents()}_bindEvents(){this._core.on(l.OnEncodedFrame,this._OnEncodedFrame)}destroy(){}}class he{constructor(){this._lastDot=0,this._totalSize=0,this._speed=[]}addSample(t){this._lastDot||(this._lastDot=Date.now()),this._totalSize+=t;const e=Date.now()-this._lastDot;e>=500&&(this._addSpeedSample(this._totalSize/e*8e3),this._totalSize=0,this._lastDot=Date.now())}_addSpeedSample(t){this._speed.push(t),this._speed=this._speed.slice(-6)}reset(){this._speed=[]}getUpSpeed(){return this._speed.length?parseInt(this._speed.reduce((t,e)=>t+=e,0)/this._speed.length):0}}const D=new E("RTMP_Wtp");class ce{constructor(t){this._queue=[],this._url="",this._connectClosed=!1,this._upSpeed=new he,this._transport=null,this._writer=null,this._inWriting=!1,this._inAdjustEncode=!1,this._increaseTimer=0,this._firstFramePushed=!1,this._core=t,this._bindEvents()}get sendSpeed(){return this._upSpeed.getUpSpeed()}getStats(){var t;return(t=this._transport)==null?void 0:t.getStats()}_bindEvents(){this._core.on(l.OnPacketed,(t,e=!1)=>{this._checkDecreaseBitrate(),this._checkDeleteCache(e),this._queue.push(t),this._inWriting||this._write()})}_checkDecreaseBitrate(){if(this._inAdjustEncode)return;const t=this._upSpeed.getUpSpeed();if(!t||this._queue.length<A.MaxCachedFrameSize)return;D.log(`up speed: ${t} low, ajust encode setting`);const e=this._core.getSetting();this._core.emit(l.OnUpstreamFeedback,{videoBitrate:t*A.RealSpeedPercent,width:e.width,height:e.height,frameRate:e.frameRate}),this._inAdjustEncode=!0,this._checkIncreaseBitrate()}_checkIncreaseBitrate(){D.log("add timer to check uplink speed increased"),clearInterval(this._increaseTimer),this._increaseTimer=setTimeout(()=>{const t=this._core.getSetting();D.log(`set encode bitrate to specified ${t.videoBitrate}`),this._core.emit(l.OnUpstreamFeedback,{videoBitrate:t.videoBitrate,width:t.width,height:t.height,frameRate:t.frameRate}),this._inAdjustEncode=!0},A.UplinkBitrateCheckInterval)}_checkDeleteCache(t){this._inAdjustEncode&&t&&(D.log(`ajust encode setting finish, delete cached ${this._queue.length} frame`),this._queue=[],this._upSpeed.reset(),this._inAdjustEncode=!1)}async start(t){this._url=t;try{await this._connect()}catch(e){throw b(y.WTP_OPEN_FAIL,e.message)}}async _connect(){const t=new WebTransport(this._url);let e;t.closed.then(()=>{D.log("webtransport closed")}).catch(r=>{e=r.message,D.log("webtransport closed due to",r)}).finally(()=>{this._connectClosed=!0,this._core.emit(O.OnConnectClosed,e),this._core.emit(O.OnError,b(y.WTP_CONNECT_FAIL,e))}),await t.ready,this._transport=t;const s=await t.createBidirectionalStream();this._writer=s.writable.getWriter(),this._write(),D.log("transport opend")}async _write(){var e;if(!this._writer)return;this._inWriting=!0;const t=this._queue.shift();if(!t){this._inWriting=!1;return}await((e=this._writer)==null?void 0:e.write(t)),this._firstFramePushed||(this._firstFramePushed=!0,this._core.emit(O.OnFirstFramePushed),D.log("first frame pushed")),this._upSpeed.addSample(t.length);try{await this._write()}catch(s){D.log("writer error:",s)}}getFile(){return S(this._queue)}destroy(){var t,e;clearTimeout(this._increaseTimer),this._connectClosed||(t=this._writer)==null||t.close(),this._writer=null,(e=this._transport)==null||e.close(),this._transport=null}}const ue=new E("LiveRTMP");class _e extends H{constructor(){super(),this._ts=0,this._setting={codec:A.codec,hardwareAcceleration:"prefer-hardware",width:-1,height:-1,frameRate:-1,sampleRate:A.sampleRate,channel:A.channel,gopSize:A.gopSize,videoBitrate:A.VideoBitrateDefault,audioBitrate:A.AudioBitrateDefault,hasAudio:!1,hasVideo:!1,vDeviceId:"",aDeviceId:""},this._encode=new ee(this),this._packet=new de(this),this._transport=new ce(this)}async checkVideoHardwareAcceleration(){const t=["prefer-hardware","prefer-software","no-preference"],e=this.getSetting(),s={codec:e.codec,width:1280,height:720,framerate:15,bitrate:e.videoBitrate};for(const r of t)try{if((await VideoEncoder.isConfigSupported({...s,hardwareAcceleration:r})).supported)return this.updateSetting({hardwareAcceleration:r}),Promise.resolve()}catch{throw b(y.VIDEO_ENCODE_CONFIGURE_FAIL,`VideoEncoder not support hardwareAcceleration, ${JSON.stringify({...s,hardwareAcceleration:r})}`)}throw b(y.VIDEO_ENCODE_CONFIGURE_FAIL,"VideoEncoder not support hardwareAcceleration")}async ready(){await Promise.all([this.checkVideoHardwareAcceleration(),this._encode.init()])}getSetting(){return this._setting}updateSetting(t){this._setting=Object.assign({},this._setting,t)}videoFrameCaptured(t,e){this.emit(l.OnVideoCaptured,t,e)}audioFrameCaptured(t,e){this.emit(l.OnAudioCaptured,t,e)}startMockVideoEncode(){this.emit(l.OnVideoCaptureNoOutput)}adjustBitrate(t,e){t===I.Video&&this.updateSetting({videoBitrate:e}),t===I.Audio&&this.updateSetting({audioBitrate:e}),this.emit(l.OnBitrateChanged,t,e)}avExist(t,e){this._setting.hasVideo=t,this._setting.hasAudio=e}publish(t){return this._transport.start(t)}setEncodeCapacity(t){this._setting=Object.assign({},this._setting,t)}getStats(){return{video:{...this._encode.getStats().video,sendSpeed:this._transport.sendSpeed,codec:this._setting.codec,frameWidth:this._setting.width,frameHeight:this._setting.height,gopSize:this._setting.gopSize},audio:{...this._encode.getStats().audio,codec:"aac",channels:this._setting.channel,sampleRate:this._setting.sampleRate}}}destroy(){ue.log("destroy"),this._encode.destroy(),this._packet.destroy(),this._transport.destroy()}down(){return this._transport.getFile()}}self.constructor.name!=="Window"&&le();function le(){let i={};self.addEventListener("message",async t=>{switch(t.data.type){case v.Init:{const{options:e}=t.data;e.logEnable&&(E.enable=!0),e.logEnableLong&&(E.enableLong=!0),i=new _e,i.on(O.OnError,s=>{self.postMessage({type:w.Error,data:s.toJson()})}),i.on(O.OnConnectClosed,()=>{self.postMessage({type:w.Close})}),i.on(O.OnFirstFramePushed,()=>{self.postMessage({type:w.FirstFramePushed})});try{await i.ready(),self.postMessage({type:w.Ready})}catch(s){self.postMessage({type:w.Error,data:s.toJson()})}}break;case v.AvExist:{const{hasAudio:e,hasVideo:s}=t.data;i.avExist(s,e)}break;case v.VideoFrame:{const{frame:e,setting:s}=t.data;i.videoFrameCaptured(e,s)}break;case v.MockVideoEncode:i.startMockVideoEncode();break;case v.AudioFrame:{const{frame:e,setting:s}=t.data;i.audioFrameCaptured(e,s)}break;case v.AdjustBitrate:{const{kind:e,bitrate:s}=t.data;i.adjustBitrate(e,s)}break;case v.Publish:{const{url:e}=t.data;try{await i.publish(e)}catch(s){self.postMessage({type:w.Error,data:s.toJson()})}}break;case v.GetStats:self.postMessage({type:w.STATS,data:i.getStats()});break;case v.EncodeConfig:{i.setEncodeCapacity(t.data.cfg);break}case v.Download:{const e=i.down();self.postMessage({type:w.Flvfile,buffer:e},[e.buffer])}break;case v.UnPublish:{i.destroy();break}}})}})();\n',Va=typeof self<"u"&&self.Blob&&new Blob([Fa],{type:"text/javascript;charset=utf-8"});function V_(r){let e;try{if(e=Va&&(self.URL||self.webkitURL).createObjectURL(Va),!e)throw"";const t=new Worker(e,{name:r==null?void 0:r.name});return t.addEventListener("error",()=>{(self.URL||self.webkitURL).revokeObjectURL(e)}),t}catch{return new Worker("data:text/javascript;charset=utf-8,"+encodeURIComponent(Fa),{name:r==null?void 0:r.name})}finally{e&&(self.URL||self.webkitURL).revokeObjectURL(e)}}try{ut.enable=location.href.indexOf("rtmpdebug")!==-1,ut.enableLong=location.href.indexOf("rtmpdebug=long")!==-1}catch{}const pn=new ut("Bridge");class ja extends B_{constructor(){super(),this._worker=null,this._audioMsTrack=null,this._videoMsTrack=null,this._capture=new F_(this)}static isSupported(){return typeof WebTransport<"u"&&typeof MediaStreamTrackProcessor<"u"&&typeof MediaStreamTrackGenerator<"u"&&typeof VideoEncoder<"u"}get audioMsTrack(){return this._audioMsTrack}get videoMsTrack(){return this._videoMsTrack}async ready(){var s,a;let e,t;const n=new Promise((o,l)=>{e=o,t=l}),i=o=>{var l;switch((l=this._worker)==null||l.removeEventListener("message",i),o.data.type){case Et.Error:t(o.data.data);break;default:this._bindWorkerEvent(),pn.log("rtmp ready!"),e(!0)}};try{this._worker=new V_}catch(o){t(Ba(dn.RTMP_INIT_FAIL,o.message))}return(s=this._worker)==null||s.postMessage({type:ke.Init,options:{logEnable:ut.enable,logEnableLong:ut.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 Et.Error:pn.table(n.data.data),this.emit(at.OnError,n.data.data);break;case Et.Flvfile:j_(n.data.buffer);break;case Et.FirstFramePushed:this.emit(at.OnFirstFramePushed);break;case Et.Close:this.emit(at.OnConnectClosed),this.destroy();break}}),(t=this._worker)==null||t.addEventListener("error",n=>{this.emit(at.OnError,Ba(dn.WORKER_ERROR,n.message))})}addTrack(e){e.kind===ct.Video&&(this._videoMsTrack=e),e.kind===ct.Audio&&(this._audioMsTrack=e),this._setAVExist(!!this._videoMsTrack,!!this._audioMsTrack)}replaceTrack(e,t){e===ct.Video&&(this._videoMsTrack=t),e===ct.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,l)=>{e=o,t=l});this._worker||setTimeout(()=>{t()},0);const i=o=>{var l;switch(o.data.type){case Et.STATS:e(o.data.data),(l=this._worker)==null||l.removeEventListener("message",i);break}};return(s=this._worker)==null||s.addEventListener("message",i),(a=this._worker)==null||a.postMessage({type:ke.GetStats}),n}_postVideoFrame(e,t){var n;(n=this._worker)==null||n.postMessage({type:ke.VideoFrame,frame:e,setting:t},[e])}_postMockVideoEncodeFlag(){var e;(e=this._worker)==null||e.postMessage({type:ke.MockVideoEncode})}_setAVExist(e,t){var n;(n=this._worker)==null||n.postMessage({type:ke.AvExist,hasVideo:e,hasAudio:t})}_postAudioFrame(e,t){var n;(n=this._worker)==null||n.postMessage({type:ke.AudioFrame,frame:e,setting:t},[e])}setEncodeCapacity(e){var t;(t=this._worker)==null||t.postMessage({type:ke.EncodeConfig,cfg:e})}adjustBitrate(e,t){var n;(n=this._worker)==null||n.postMessage({type:ke.AdjustBitrate,kind:e,bitrate:t})}publish(e){var t;pn.log("start capture & connect"),this._capture.start(),(t=this._worker)==null||t.postMessage({type:ke.Publish,url:e})}unpublish(){var e;this._capture.destroy(),(e=this._worker)==null||e.postMessage({type:ke.UnPublish})}destroy(){var e;pn.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:ke.Download})}}function j_(r){const e=document.createElement("a");e.href=URL.createObjectURL(new Blob([r])),e.download=Date.now()+".flv",e.click()}const Ha=new ot("RTMPConnect");class H_{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 ja,this._bindEvents()}get isPushing(){return this._isPushing}get pushUrl(){return this._url}get sessionId(){return 0}_bindEvents(){this._rtmp.on(at.OnError,e=>{this._isPushing=!1,this._onError(e)}),this._rtmp.on(at.OnConnectClosed,()=>{this._isPushing=!1,this._onError(new Ga(dn.WTP_CONNECT_FAIL,"connect lost"))}),this._rtmp.on(at.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(ct.Audio,t[0]),t[1]&&this._rtmp.adjustBitrate(ct.Video,t[1]),this._rtmp.publish(this._url)}updatePublish(e,t){Ha.log(`replace track to ${e==null?void 0:e.label}`),this._rtmp.replaceTrack(t,e)}applyBitrate(e,t){this._rtmp.adjustBitrate(t,e)}async getStats(){return this._rtmp.getStats()}async getStatsSnapshoot(e){return e&&await hn(e),this._rtmp.getStats()}unpublish(){Ha.warn("unpublish"),this._rtmp.unpublish(),this._isPushing=!1}}class q_{constructor(e,t=tf){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:kt.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:kt.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:An.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:kt.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,rf)},this.state="idle",this._pushConsumer=e,this._maxTimeout=t,this._logger=new ot("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:kt.SUCCESS,teaParams:{reconnect_duration:s,session_id:this._pushConsumer.pushSessionId}}):(this._logger.log("Reconnect strategy stopped: ",t),this._pushConsumer.emitReconnectStateChange({state:kt.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:An.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 Dr={ManualStop:0,ReconnectFailed:1,StartPushError:2,PushError:3},Gt={PushCheck:0,PushError:1},qa=new ot("PushController");class $_ extends za{constructor(e,{config:t,streamConsumeController:n}){var i,s;if(super(e),this._connect=null,this._connectionState=Ee.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=zt(hs,"audio").bitrate,this._videoBitrate=zt(ls,"video").bitrate,this.handleReconnectError=(a,o)=>{var l,c;V(j.STOP_PUSH_STREAM,{reason:Dr.ReconnectFailed,error_message:a,session_id:this._pushSessionId,push_mode:this._pushMode,duration:this.pushDuration,reconnect_times:(l=this._reconnectStrategy)==null?void 0:l.getReconnectInfo().totalReconnectCount,reconnect_duration:(c=this._reconnectStrategy)==null?void 0:c.getReconnectInfo().totalReconnectDuration}),this.unpublish()},this.handleAudioStreamChange=a=>{this.updatePush({audioTrack:a.audioTrack})},this.handleVideoStreamChange=a=>{this.updatePush({videoTrack:a.videoTrack})},this._OnRTMPSuccess=()=>{this.setConnectState(Ee.CONNECTED)},this._OnRTMPError=a=>{const o=new It(ye.PUBLISH_FAILED,`code:${a.code}, message: ${a.message}`);this._streamConsumeController.emit(se.PushError,o),V(j.STOP_PUSH_STREAM,{reason:Dr.PushError,duration:this.pushDuration,session_id:this._pushSessionId,push_mode:this._pushMode,error_msg:a.message,error_code:a.code}),V(j.START_PUSH_STATUS,{is_success:!1,reason:Gt.PushError,error_message:a.message,session_id:this._pushSessionId,push_mode:this._pushMode,push_url:this._pushUrl}),this.unpublish()},this._executeReconnect=()=>{var a;(a=this._reconnectStrategy)==null||a.execute(),this.setConnectState(Ee.RECONNECTING),this.unpublish({isReconnecting:!0})},this._OnRtcStateChange=a=>{var o;switch(this._streamConsumeController.emit(se.RTCConnectStateChanged,a),a){case"connected":this.setConnectState(Ee.CONNECTED);break;case"disconnected":this._reconnectStrategy&&this._executeReconnect();break;case"failed":(o=this._reconnectStrategy)!=null&&o.isActive()?this._executeReconnect():(this.connectionState===Ee.CONNECTED?V(j.STOP_PUSH_STREAM,{reason:Dr.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:Gt.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 It(ye.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),(i=t==null?void 0:t.reconnectConfig)!=null&&i.enable||!(t!=null&&t.reconnectConfig)){const a=(s=t==null?void 0:t.reconnectConfig)!=null&&s.maxTimeout?t.reconnectConfig.maxTimeout*ko:void 0;this._reconnectStrategy=new q_(this,a),this._reconnectStrategy.onReconnectError=this.handleReconnectError}}get isPushing(){return this._connectionState===Ee.CONNECTED||this._connectionState===Ee.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 Ee.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,l;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:Gt.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:Gt.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:Gt.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 N_(e,this._pushConfig,this._OnRtcStateChange):s=new H_(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(Ee.CONNECTING),await s.publish([i,n],[this._audioBitrate,this._videoBitrate],{cfg:t.cfg,isReconnect:t.isReconnect}),t.isReconnect||(qa.log("startPush begin"),this._connectionStartDate=Date.now())}catch(c){const u=new It(ye.PUBLISH_FAILED,c.message,c);if(qa.groupEnd(),(l=this._reconnectStrategy)!=null&&l.isActive())throw this.unpublish({isReconnecting:!0}),u;this._streamConsumeController.emit(se.PushError,u),V(j.STOP_PUSH_STREAM,{reason:Dr.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:Gt.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(),a=await((n=this._connect)==null?void 0:n.getStatsSnapshoot(2e3)),l=Date.now()-s;qp(a)?this._prevStats=void 0:this._prevStats=a;const c=this.pushMode==="rtm"?z_(a):O_(a);V(j.PUSH_STATS,{...c,stats:a,push_url:this._pushUrl,push_mode:this._pushMode,session_id:this._pushSessionId,duration:c.video_duration||l,video_duration:c.video_duration||l,is_push:!0},!0)}else await hn(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!==Ee.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 It(ye.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:Dr.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(Ee.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 K_ extends Qe{constructor(e,t){super(),this._previewConsumer=new w_(e.getComposedStream(),{streamConsumeController:this}),this._pushConsumer=new $_(e.getComposedStream(),{streamConsumeController:this,config:t})}startPreview(){this._previewConsumer.startPreview()}setRenderView(e){this._previewConsumer.setRenderView(e)}async startPush(e,t){return this._pushConsumer.startPush(e,{cfg:t})}async stopPush(){return this._pushConsumer.unpublish({isReconnecting:!1,isManual:!0})}setPushMode(e){this._pushConsumer.setPushMode(e)}isPushing(){return this._pushConsumer.isPushing}getStats(){return this._pushConsumer.getStats()}getPreviewElement(){return this._previewConsumer.getPreviewElement()}stopPreview(){this._previewConsumer.stopPreview()}setBitrate(e,t,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 W_=()=>typeof window>"u",Ue={},fn=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 $a(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 J_=async()=>{let r=await fn("sendonly");return navigator.userAgent.includes("VivoBrowser")&&(r=await fn("sendonly")),Ue.h264encode=$a(r),Ue.vp8encode=r.indexOf("vp8")>-1,Ue},X_=async()=>{let r=await fn("recvonly");return navigator.userAgent.includes("VivoBrowser")&&(r=await fn("recvonly")),Ue.h264decode=$a(r),Ue.vp8decode=r.indexOf("vp8")>-1,Ue},Z_=async()=>{if(typeof Ue.h264encode>"u")try{await J_()}catch{return!1}return Ue.h264encode||!1},Y_=async()=>{if(typeof Ue.h264decode>"u")try{await X_()}catch{return!1}return Ue.h264decode||!1};class Q_{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 eg=new Q_;let Ka=!0,Wa=!0;function mn(r,e,t){const n=r.match(e);return n&&n.length>=t&&parseInt(n[t],10)}function Ct(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 l=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,l),i.apply(this,[a,l])};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 l=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,l])},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 tg(r){return typeof r!="boolean"?new Error("Argument type: "+typeof r+". Please use a boolean."):(Ka=r,r?"adapter.js logging disabled":"adapter.js logging enabled")}function rg(r){return typeof r!="boolean"?new Error("Argument type: "+typeof r+". Please use a boolean."):(Wa=!r,"adapter.js deprecation warnings "+(r?"disabled":"enabled"))}function Ja(){if(typeof window=="object"){if(Ka)return;typeof console<"u"&&typeof console.log=="function"&&console.log.apply(console,arguments)}}function Wi(r,e){Wa&&console.warn(r+" is deprecated, please use "+e+" instead.")}function ng(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=mn(t.userAgent,/Firefox\/(\d+)\./,1);else if(t.webkitGetUserMedia||r.isSecureContext===!1&&r.webkitRTCPeerConnection)e.browser="chrome",e.version=mn(t.userAgent,/Chrom(e|ium)\/(\d+)\./,2);else if(r.RTCPeerConnection&&t.userAgent.match(/AppleWebKit\/(\d+)\./))e.browser="safari",e.version=mn(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 Xa(r){return Object.prototype.toString.call(r)==="[object Object]"}function Za(r){return Xa(r)?Object.keys(r).reduce(function(e,t){const n=Xa(r[t]),i=n?Za(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 Ya(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 Qa=Ja;function ec(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 l={};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 d=function(h,f){return h?h+f.charAt(0).toUpperCase()+f.slice(1):f==="deviceId"?"sourceId":f};if(u.ideal!==void 0){l.optional=l.optional||[];let h={};typeof u.ideal=="number"?(h[d("min",c)]=u.ideal,l.optional.push(h),h={},h[d("max",c)]=u.ideal,l.optional.push(h)):(h[d("",c)]=u.ideal,l.optional.push(h))}u.exact!==void 0&&typeof u.exact!="number"?(l.mandatory=l.mandatory||{},l.mandatory[d("",c)]=u.exact):["min","max"].forEach(h=>{u[h]!==void 0&&(l.mandatory=l.mandatory||{},l.mandatory[d(h,c)]=u[h])})}),o.advanced&&(l.optional=(l.optional||[]).concat(o.advanced)),l},i=function(o,l){if(e.version>=61)return l(o);if(o=JSON.parse(JSON.stringify(o)),o&&typeof o.audio=="object"){const c=function(u,d,h){d in u&&!(h in u)&&(u[h]=u[d],delete u[d])};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 d;if(c.exact==="environment"||c.ideal==="environment"?d=["back","rear"]:(c.exact==="user"||c.ideal==="user")&&(d=["front"]),d)return t.mediaDevices.enumerateDevices().then(h=>{h=h.filter(b=>b.kind==="videoinput");let f=h.find(b=>d.some(T=>b.label.toLowerCase().includes(T)));return!f&&h.length&&d.includes("back")&&(f=h[h.length-1]),f&&(o.video.deviceId=c.exact?{exact:f.deviceId}:{ideal:f.deviceId}),o.video=n(o.video),Qa("chrome: "+JSON.stringify(o)),l(o)})}o.video=n(o.video)}return Qa("chrome: "+JSON.stringify(o)),l(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,l,c){i(o,u=>{t.webkitGetUserMedia(u,l,d=>{c&&c(s(d))})})};if(t.getUserMedia=a.bind(t),t.mediaDevices.getUserMedia){const o=t.mediaDevices.getUserMedia.bind(t.mediaDevices);t.mediaDevices.getUserMedia=function(l){return i(l,c=>o(c).then(u=>{if(c.audio&&!u.getAudioTracks().length||c.video&&!u.getVideoTracks().length)throw u.getTracks().forEach(d=>{d.stop()}),new DOMException("","NotFoundError");return u},u=>Promise.reject(s(u))))}}}function tc(r){r.MediaStream=r.MediaStream||r.webkitMediaStream}function rc(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 Ct(r,"track",e=>(e.transceiver||Object.defineProperty(e,"transceiver",{value:{receiver:e.receiver}}),e))}function nc(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,l){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 l=this._senders.indexOf(o);l!==-1&&this._senders.splice(l,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(l=>l.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 ic(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=>Ya(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}),Ct(r,"track",n=>(n.receiver._pc=n.srcElement,n)),r.RTCRtpReceiver.prototype.getStats=function(){const i=this;return this._pc.getStats().then(s=>Ya(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 sc(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 l=e.apply(this,arguments);return this._shimmedLocalStreams[o.id]?this._shimmedLocalStreams[o.id].indexOf(l)===-1&&this._shimmedLocalStreams[o.id].push(l):this._shimmedLocalStreams[o.id]=[o,l],l};const t=r.RTCPeerConnection.prototype.addStream;r.RTCPeerConnection.prototype.addStream=function(a){this._shimmedLocalStreams=this._shimmedLocalStreams||{},a.getTracks().forEach(c=>{if(this.getSenders().find(d=>d.track===c))throw new DOMException("Track already exists.","InvalidAccessError")});const o=this.getSenders();t.apply(this,arguments);const l=this.getSenders().filter(c=>o.indexOf(c)===-1);this._shimmedLocalStreams[a.id]=[a].concat(l)};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 l=this._shimmedLocalStreams[o].indexOf(a);l!==-1&&this._shimmedLocalStreams[o].splice(l,1),this._shimmedLocalStreams[o].length===1&&delete this._shimmedLocalStreams[o]}),i.apply(this,arguments)}}function oc(r,e){if(!r.RTCPeerConnection)return;if(r.RTCPeerConnection.prototype.addTrack&&e.version>=65)return sc(r);const t=r.RTCPeerConnection.prototype.getLocalStreams;r.RTCPeerConnection.prototype.getLocalStreams=function(){const u=t.apply(this);return this._reverseStreams=this._reverseStreams||{},u.map(d=>this._reverseStreams[d.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(d=>{if(this.getSenders().find(f=>f.track===d))throw new DOMException("Track already exists.","InvalidAccessError")}),!this._reverseStreams[u.id]){const d=new r.MediaStream(u.getTracks());this._streams[u.id]=d,this._reverseStreams[d.id]=u,u=d}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,d){if(this.signalingState==="closed")throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");const h=[].slice.call(arguments,1);if(h.length!==1||!h[0].getTracks().find(T=>T===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(T=>T.track===u))throw new DOMException("Track already exists.","InvalidAccessError");this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{};const b=this._streams[d.id];if(b)b.addTrack(u),Promise.resolve().then(()=>{this.dispatchEvent(new Event("negotiationneeded"))});else{const T=new r.MediaStream([u]);this._streams[d.id]=T,this._reverseStreams[T.id]=d,this.addStream(T)}return this.getSenders().find(T=>T.track===u)};function s(c,u){let d=u.sdp;return Object.keys(c._reverseStreams||[]).forEach(h=>{const f=c._reverseStreams[h],b=c._streams[f.id];d=d.replace(new RegExp(b.id,"g"),f.id)}),new RTCSessionDescription({type:u.type,sdp:d})}function a(c,u){let d=u.sdp;return Object.keys(c._reverseStreams||[]).forEach(h=>{const f=c._reverseStreams[h],b=c._streams[f.id];d=d.replace(new RegExp(f.id,"g"),b.id)}),new RTCSessionDescription({type:u.type,sdp:d})}["createOffer","createAnswer"].forEach(function(c){const u=r.RTCPeerConnection.prototype[c],d={[c](){const h=arguments;return arguments.length&&typeof arguments[0]=="function"?u.apply(this,[b=>{const T=s(this,b);h[0].apply(null,[T])},b=>{h[1]&&h[1].apply(null,b)},arguments[2]]):u.apply(this,arguments).then(b=>s(this,b))}};r.RTCPeerConnection.prototype[c]=d[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 l=Object.getOwnPropertyDescriptor(r.RTCPeerConnection.prototype,"localDescription");Object.defineProperty(r.RTCPeerConnection.prototype,"localDescription",{get(){const c=l.get.apply(this);return c.type===""?c:s(this,c)}}),r.RTCPeerConnection.prototype.removeTrack=function(u){if(this.signalingState==="closed")throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");if(!u._pc)throw new DOMException("Argument 1 of RTCPeerConnection.removeTrack does not implement interface RTCRtpSender.","TypeError");if(!(u._pc===this))throw new DOMException("Sender was not created by this connection.","InvalidAccessError");this._streams=this._streams||{};let h;Object.keys(this._streams).forEach(f=>{this._streams[f].getTracks().find(T=>u.track===T)&&(h=this._streams[f])}),h&&(h.getTracks().length===1?this.removeStream(this._reverseStreams[h.id]):h.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 ac(r,e){Ct(r,"negotiationneeded",t=>{const n=t.target;if(!((e.version<72||n.getConfiguration&&n.getConfiguration().sdpSemantics==="plan-b")&&n.signalingState!=="stable"))return t})}const cc=Object.freeze(Object.defineProperty({__proto__:null,fixNegotiationNeeded:ac,shimAddTrackRemoveTrack:oc,shimAddTrackRemoveTrackWithNative:sc,shimGetSendersWithDtmf:nc,shimGetUserMedia:ec,shimMediaStream:tc,shimOnTrack:rc,shimPeerConnection:Xi,shimSenderReceiverGetStats:ic},Symbol.toStringTag,{value:"Module"}));function uc(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,l){o in a&&!(l in a)&&(a[l]=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 ig(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 lc(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(l=>{if(e.version<53&&!a)try{l.forEach(c=>{c.type=t[c.type]||c.type})}catch(c){if(c.name!=="TypeError")throw c;l.forEach((u,d)=>{l.set(d,Object.assign({},u,{type:t[u.type]||u.type}))})}return l}).then(a,o)}}function hc(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 dc(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}),Ct(r,"track",t=>(t.receiver._pc=t.srcElement,t)),r.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track)}}function pc(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 fc(r){r.DataChannel&&!r.RTCDataChannel&&(r.RTCDataChannel=r.DataChannel)}function mc(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 _c(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 gc(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 vc(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 yc=Object.freeze(Object.defineProperty({__proto__:null,shimAddTransceiver:mc,shimCreateAnswer:vc,shimCreateOffer:gc,shimGetDisplayMedia:ig,shimGetParameters:_c,shimGetUserMedia:uc,shimOnTrack:lc,shimPeerConnection:Zi,shimRTCDataChannel:fc,shimReceiverGetStats:dc,shimRemoveStream:pc,shimSenderGetStats:hc},Symbol.toStringTag,{value:"Module"}));function Sc(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 bc(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 Ec(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 d=arguments.length>=2?arguments[2]:arguments[0],h=t.apply(this,[d]);return u?(h.then(c,u),Promise.resolve()):h},e.createAnswer=function(c,u){const d=arguments.length>=2?arguments[2]:arguments[0],h=n.apply(this,[d]);return u?(h.then(c,u),Promise.resolve()):h};let o=function(l,c,u){const d=i.apply(this,[l]);return u?(d.then(c,u),Promise.resolve()):d};e.setLocalDescription=o,o=function(l,c,u){const d=s.apply(this,[l]);return u?(d.then(c,u),Promise.resolve()):d},e.setRemoteDescription=o,o=function(l,c,u){const d=a.apply(this,[l]);return u?(d.then(c,u),Promise.resolve()):d},e.addIceCandidate=o}function Cc(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(wc(i))}!e.getUserMedia&&e.mediaDevices&&e.mediaDevices.getUserMedia&&(e.getUserMedia=(function(n,i,s){e.mediaDevices.getUserMedia(n).then(i,s)}).bind(e))}function wc(r){return r&&r.video!==void 0?Object.assign({},r,{video:Za(r.video)}):r}function Tc(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 kc(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 Rc(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 Ac(r){typeof r!="object"||r.AudioContext||(r.AudioContext=r.webkitAudioContext)}const Dc=Object.freeze(Object.defineProperty({__proto__:null,shimAudioContext:Ac,shimCallbacksAPI:Ec,shimConstraints:wc,shimCreateOfferLegacy:Rc,shimGetUserMedia:Cc,shimLocalStreamsAPI:Sc,shimRTCIceServerUrls:Tc,shimRemoteStreamsAPI:bc,shimTrackEventTransceiver:kc},Symbol.toStringTag,{value:"Module"}));var Yi={exports:{}},xc;function sg(){return xc||(xc=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
|
+
`).map(n=>n.trim())},e.splitSections=function(t){return t.split(`
|
|
71
|
+
m=`).map((i,s)=>(s>0?"m="+i:i).trim()+`\r
|
|
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
|
|
73
|
+
`},e.parseExtmap=function(t){const n=t.substring(9).split(" ");return{id:parseInt(n[0],10),direction:n[0].indexOf("/")>0?n[0].split("/")[1]:"sendrecv",uri:n[1],attributes:n.slice(2).join(" ")}},e.writeExtmap=function(t){return"a=extmap:"+(t.id||t.preferredId)+(t.direction&&t.direction!=="sendrecv"?"/"+t.direction:"")+" "+t.uri+(t.attributes?" "+t.attributes:"")+`\r
|
|
74
|
+
`},e.parseFmtp=function(t){const n={};let i;const s=t.substring(t.indexOf(" ")+1).split(";");for(let a=0;a<s.length;a++)i=s[a].trim().split("="),n[i[0].trim()]=i[1];return n},e.writeFmtp=function(t){let n="",i=t.payloadType;if(t.preferredPayloadType!==void 0&&(i=t.preferredPayloadType),t.parameters&&Object.keys(t.parameters).length){const s=[];Object.keys(t.parameters).forEach(a=>{t.parameters[a]!==void 0?s.push(a+"="+t.parameters[a]):s.push(a)}),n+="a=fmtp:"+i+" "+s.join(";")+`\r
|
|
75
|
+
`}return n},e.parseRtcpFb=function(t){const n=t.substring(t.indexOf(" ")+1).split(" ");return{type:n.shift(),parameter:n.join(" ")}},e.writeRtcpFb=function(t){let n="",i=t.payloadType;return t.preferredPayloadType!==void 0&&(i=t.preferredPayloadType),t.rtcpFeedback&&t.rtcpFeedback.length&&t.rtcpFeedback.forEach(s=>{n+="a=rtcp-fb:"+i+" "+s.type+(s.parameter&&s.parameter.length?" "+s.parameter:"")+`\r
|
|
76
|
+
`}),n},e.parseSsrcMedia=function(t){const n=t.indexOf(" "),i={ssrc:parseInt(t.substring(7,n),10)},s=t.indexOf(":",n);return s>-1?(i.attribute=t.substring(n+1,s),i.value=t.substring(s+1)):i.attribute=t.substring(n+1),i},e.parseSsrcGroup=function(t){const n=t.substring(13).split(" ");return{semantics:n.shift(),ssrcs:n.map(i=>parseInt(i,10))}},e.getMid=function(t){const n=e.matchPrefix(t,"a=mid:")[0];if(n)return n.substring(6)},e.parseFingerprint=function(t){const n=t.substring(14).split(" ");return{algorithm:n[0].toLowerCase(),value:n[1].toUpperCase()}},e.getDtlsParameters=function(t,n){return{role:"auto",fingerprints:e.matchPrefix(t+n,"a=fingerprint:").map(e.parseFingerprint)}},e.writeDtlsParameters=function(t,n){let i="a=setup:"+n+`\r
|
|
77
|
+
`;return t.fingerprints.forEach(s=>{i+="a=fingerprint:"+s.algorithm+" "+s.value+`\r
|
|
78
|
+
`}),i},e.parseCryptoLine=function(t){const n=t.substring(9).split(" ");return{tag:parseInt(n[0],10),cryptoSuite:n[1],keyParams:n[2],sessionParams:n.slice(3)}},e.writeCryptoLine=function(t){return"a=crypto:"+t.tag+" "+t.cryptoSuite+" "+(typeof t.keyParams=="object"?e.writeCryptoKeyParams(t.keyParams):t.keyParams)+(t.sessionParams?" "+t.sessionParams.join(" "):"")+`\r
|
|
79
|
+
`},e.parseCryptoKeyParams=function(t){if(t.indexOf("inline:")!==0)return null;const n=t.substring(7).split("|");return{keyMethod:"inline",keySalt:n[0],lifeTime:n[1],mkiValue:n[2]?n[2].split(":")[0]:void 0,mkiLength:n[2]?n[2].split(":")[1]:void 0}},e.writeCryptoKeyParams=function(t){return t.keyMethod+":"+t.keySalt+(t.lifeTime?"|"+t.lifeTime:"")+(t.mkiValue&&t.mkiLength?"|"+t.mkiValue+":"+t.mkiLength:"")},e.getCryptoParameters=function(t,n){return e.matchPrefix(t+n,"a=crypto:").map(e.parseCryptoLine)},e.getIceParameters=function(t,n){const i=e.matchPrefix(t+n,"a=ice-ufrag:")[0],s=e.matchPrefix(t+n,"a=ice-pwd:")[0];return i&&s?{usernameFragment:i.substring(12),password:s.substring(10)}:null},e.writeIceParameters=function(t){let n="a=ice-ufrag:"+t.usernameFragment+`\r
|
|
70
80
|
a=ice-pwd:`+t.password+`\r
|
|
71
|
-
`;return t.iceLite&&(
|
|
72
|
-
`),
|
|
73
|
-
`,
|
|
74
|
-
`,
|
|
75
|
-
`,
|
|
76
|
-
`),
|
|
77
|
-
`),t.mux&&(
|
|
78
|
-
`),t.ssrc!==void 0&&t.cname&&(
|
|
79
|
-
`),
|
|
81
|
+
`;return t.iceLite&&(n+=`a=ice-lite\r
|
|
82
|
+
`),n},e.parseRtpParameters=function(t){const n={codecs:[],headerExtensions:[],fecMechanisms:[],rtcp:[]},s=e.splitLines(t)[0].split(" ");n.profile=s[2];for(let o=3;o<s.length;o++){const l=s[o],c=e.matchPrefix(t,"a=rtpmap:"+l+" ")[0];if(c){const u=e.parseRtpMap(c),d=e.matchPrefix(t,"a=fmtp:"+l+" ");switch(u.parameters=d.length?e.parseFmtp(d[0]):{},u.rtcpFeedback=e.matchPrefix(t,"a=rtcp-fb:"+l+" ").map(e.parseRtcpFb),n.codecs.push(u),u.name.toUpperCase()){case"RED":case"ULPFEC":n.fecMechanisms.push(u.name.toUpperCase());break}}}e.matchPrefix(t,"a=extmap:").forEach(o=>{n.headerExtensions.push(e.parseExtmap(o))});const a=e.matchPrefix(t,"a=rtcp-fb:* ").map(e.parseRtcpFb);return n.codecs.forEach(o=>{a.forEach(l=>{o.rtcpFeedback.find(u=>u.type===l.type&&u.parameter===l.parameter)||o.rtcpFeedback.push(l)})}),n},e.writeRtpDescription=function(t,n){let i="";i+="m="+t+" ",i+=n.codecs.length>0?"9":"0",i+=" "+(n.profile||"UDP/TLS/RTP/SAVPF")+" ",i+=n.codecs.map(a=>a.preferredPayloadType!==void 0?a.preferredPayloadType:a.payloadType).join(" ")+`\r
|
|
83
|
+
`,i+=`c=IN IP4 0.0.0.0\r
|
|
84
|
+
`,i+=`a=rtcp:9 IN IP4 0.0.0.0\r
|
|
85
|
+
`,n.codecs.forEach(a=>{i+=e.writeRtpMap(a),i+=e.writeFmtp(a),i+=e.writeRtcpFb(a)});let s=0;return n.codecs.forEach(a=>{a.maxptime>s&&(s=a.maxptime)}),s>0&&(i+="a=maxptime:"+s+`\r
|
|
86
|
+
`),n.headerExtensions&&n.headerExtensions.forEach(a=>{i+=e.writeExtmap(a)}),i},e.parseRtpEncodingParameters=function(t){const n=[],i=e.parseRtpParameters(t),s=i.fecMechanisms.indexOf("RED")!==-1,a=i.fecMechanisms.indexOf("ULPFEC")!==-1,o=e.matchPrefix(t,"a=ssrc:").map(h=>e.parseSsrcMedia(h)).filter(h=>h.attribute==="cname"),l=o.length>0&&o[0].ssrc;let c;const u=e.matchPrefix(t,"a=ssrc-group:FID").map(h=>h.substring(17).split(" ").map(b=>parseInt(b,10)));u.length>0&&u[0].length>1&&u[0][0]===l&&(c=u[0][1]),i.codecs.forEach(h=>{if(h.name.toUpperCase()==="RTX"&&h.parameters.apt){let f={ssrc:l,codecPayloadType:parseInt(h.parameters.apt,10)};l&&c&&(f.rtx={ssrc:c}),n.push(f),s&&(f=JSON.parse(JSON.stringify(f)),f.fec={ssrc:l,mechanism:a?"red+ulpfec":"red"},n.push(f))}}),n.length===0&&l&&n.push({ssrc:l});let d=e.matchPrefix(t,"b=");return d.length&&(d[0].indexOf("b=TIAS:")===0?d=parseInt(d[0].substring(7),10):d[0].indexOf("b=AS:")===0?d=parseInt(d[0].substring(5),10)*1e3*.95-50*40*8:d=void 0,n.forEach(h=>{h.maxBitrate=d})),n},e.parseRtcpParameters=function(t){const n={},i=e.matchPrefix(t,"a=ssrc:").map(o=>e.parseSsrcMedia(o)).filter(o=>o.attribute==="cname")[0];i&&(n.cname=i.value,n.ssrc=i.ssrc);const s=e.matchPrefix(t,"a=rtcp-rsize");n.reducedSize=s.length>0,n.compound=s.length===0;const a=e.matchPrefix(t,"a=rtcp-mux");return n.mux=a.length>0,n},e.writeRtcpParameters=function(t){let n="";return t.reducedSize&&(n+=`a=rtcp-rsize\r
|
|
87
|
+
`),t.mux&&(n+=`a=rtcp-mux\r
|
|
88
|
+
`),t.ssrc!==void 0&&t.cname&&(n+="a=ssrc:"+t.ssrc+" cname:"+t.cname+`\r
|
|
89
|
+
`),n},e.parseMsid=function(t){let n;const i=e.matchPrefix(t,"a=msid:");if(i.length===1)return n=i[0].substring(7).split(" "),{stream:n[0],track:n[1]};const s=e.matchPrefix(t,"a=ssrc:").map(a=>e.parseSsrcMedia(a)).filter(a=>a.attribute==="msid");if(s.length>0)return n=s[0].value.split(" "),{stream:n[0],track:n[1]}},e.parseSctpDescription=function(t){const n=e.parseMLine(t),i=e.matchPrefix(t,"a=max-message-size:");let s;i.length>0&&(s=parseInt(i[0].substring(19),10)),isNaN(s)&&(s=65536);const a=e.matchPrefix(t,"a=sctp-port:");if(a.length>0)return{port:parseInt(a[0].substring(12),10),protocol:n.fmt,maxMessageSize:s};const o=e.matchPrefix(t,"a=sctpmap:");if(o.length>0){const l=o[0].substring(10).split(" ");return{port:parseInt(l[0],10),protocol:l[1],maxMessageSize:s}}},e.writeSctpDescription=function(t,n){let i=[];return t.protocol!=="DTLS/SCTP"?i=["m="+t.kind+" 9 "+t.protocol+" "+n.protocol+`\r
|
|
80
90
|
`,`c=IN IP4 0.0.0.0\r
|
|
81
|
-
`,"a=sctp-port:"+
|
|
82
|
-
`]:
|
|
91
|
+
`,"a=sctp-port:"+n.port+`\r
|
|
92
|
+
`]:i=["m="+t.kind+" 9 "+t.protocol+" "+n.port+`\r
|
|
83
93
|
`,`c=IN IP4 0.0.0.0\r
|
|
84
|
-
`,"a=sctpmap:"+
|
|
85
|
-
`],
|
|
86
|
-
`),
|
|
87
|
-
o=`+(
|
|
94
|
+
`,"a=sctpmap:"+n.port+" "+n.protocol+` 65535\r
|
|
95
|
+
`],n.maxMessageSize!==void 0&&i.push("a=max-message-size:"+n.maxMessageSize+`\r
|
|
96
|
+
`),i.join("")},e.generateSessionId=function(){return Math.random().toString().substr(2,22)},e.writeSessionBoilerplate=function(t,n,i){let s;const a=n!==void 0?n:2;return t?s=t:s=e.generateSessionId(),`v=0\r
|
|
97
|
+
o=`+(i||"thisisadapterortc")+" "+s+" "+a+` IN IP4 127.0.0.1\r
|
|
88
98
|
s=-\r
|
|
89
99
|
t=0 0\r
|
|
90
|
-
`},e.getDirection=function(t,
|
|
91
|
-
a=extmap-allow-mixed`)!==-1){const
|
|
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}(Yi)),Yi.exports}var Ic=sg();const Bt=pe(Ic),og=Ae({__proto__:null,default:Bt},[Ic]);function _n(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=Bt.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,Ct(r,"icecandidate",t=>(t.candidate&&Object.defineProperty(t,"candidate",{value:new r.RTCIceCandidate(t.candidate),writable:"false"}),t))}function Qi(r){!r.RTCIceCandidate||r.RTCIceCandidate&&"relayProtocol"in r.RTCIceCandidate.prototype||Ct(r,"icecandidate",e=>{if(e.candidate){const t=Bt.parseCandidate(e.candidate.candidate);t.type==="relay"&&(e.candidate.relayProtocol={0:"tls",1:"tcp",2:"udp"}[t.priority>>24])}return e})}function gn(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 l=Bt.splitSections(o.sdp);return l.shift(),l.some(c=>{const u=Bt.parseMLine(c);return u&&u.kind==="application"&&u.protocol.indexOf("SCTP")!==-1})},n=function(o){const l=o.sdp.match(/mozilla...THIS_IS_SDPARTA-(\d+)/);if(l===null||l.length<2)return-1;const c=parseInt(l[1],10);return c!==c?-1:c},i=function(o){let l=65536;return e.browser==="firefox"&&(e.version<57?o===-1?l=16384:l=2147483637:e.version<60?l=e.version===57?65535:65536:l=2147483637),l},s=function(o,l){let c=65536;e.browser==="firefox"&&e.version===57&&(c=65535);const u=Bt.matchPrefix(o.sdp,"a=max-message-size:");return u.length>0?c=parseInt(u[0].substring(19),10):e.browser==="firefox"&&l!==-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:l}=this.getConfiguration();l==="plan-b"&&Object.defineProperty(this,"sctp",{get(){return typeof this._sctp>"u"?null:this._sctp},enumerable:!0,configurable:!0})}if(t(arguments[0])){const l=n(arguments[0]),c=i(l),u=s(arguments[0],l);let d;c===0&&u===0?d=Number.POSITIVE_INFINITY:c===0||u===0?d=Math.max(c,u):d=Math.min(c,u);const h={};Object.defineProperty(h,"maxMessageSize",{get(){return d}}),this._sctp=h}return a.apply(this,arguments)}}function vn(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],l=o.length||o.size||o.byteLength;if(n.readyState==="open"&&i.sctp&&l>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},Ct(r,"datachannel",n=>(e(n.channel,n.target),n))}function es(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 ts(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
|
+
a=extmap-allow-mixed`)!==-1){const s=i.sdp.split(`
|
|
92
102
|
`).filter(a=>a.trim()!=="a=extmap-allow-mixed").join(`
|
|
93
|
-
`);r.RTCSessionDescription&&s instanceof r.RTCSessionDescription?arguments[0]=new r.RTCSessionDescription({type:s.type,sdp:n}):s.sdp=n}return t.apply(this,arguments)}}function st(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 nt(r,e){if(!(r.RTCPeerConnection&&r.RTCPeerConnection.prototype))return;const t=r.RTCPeerConnection.prototype.setLocalDescription;!t||t.length===0||(r.RTCPeerConnection.prototype.setLocalDescription=function(){let s=arguments[0]||{};if(typeof s!="object"||s.type&&s.sdp)return t.apply(this,arguments);if(s={type:s.type,sdp:s.sdp},!s.type)switch(this.signalingState){case"stable":case"have-local-offer":case"have-remote-pranswer":s.type="offer";break;default:s.type="answer";break}return s.sdp||s.type!=="offer"&&s.type!=="answer"?t.apply(this,[s]):(s.type==="offer"?this.createOffer:this.createAnswer).apply(this).then(a=>t.apply(this,[a]))})}const fh=Object.freeze(Object.defineProperty({__proto__:null,removeExtmapAllowMixed:Zt,shimAddIceCandidateNullOrEmpty:st,shimConnectionState:Yt,shimMaxMessageSize:rt,shimParameterlessSetLocalDescription:nt,shimRTCIceCandidate:tt,shimRTCIceCandidateRelayProtocol:Jt,shimSendThrowTypeError:it},Symbol.toStringTag,{value:"Module"}));function _h({window:r}={},e={shimChrome:!0,shimFirefox:!0,shimSafari:!0}){const t=qi,i=hh(r),s={browserDetails:i,commonShim:fh,extractVersion:et,disableLog:dh,disableWarnings:uh,sdp:mh};switch(i.browser){case"chrome":if(!ns||!Wt||!e.shimChrome)return t("Chrome shim is not included in this adapter release."),s;if(i.version===null)return t("Chrome shim can not determine version, not shimming."),s;t("adapter.js shimming chrome."),s.browserShim=ns,st(r,i),nt(r),Yi(r,i),Zi(r),Wt(r,i),Qi(r),is(r,i),es(r),ts(r),ss(r,i),tt(r),Jt(r),Yt(r),rt(r,i),it(r),Zt(r,i);break;case"firefox":if(!_s||!Xt||!e.shimFirefox)return t("Firefox shim is not included in this adapter release."),s;t("adapter.js shimming firefox."),s.browserShim=_s,st(r,i),nt(r),os(r,i),Xt(r,i),as(r),us(r),cs(r),ds(r),hs(r),ps(r),ls(r),ms(r),fs(r),tt(r),Yt(r),rt(r,i),it(r);break;case"safari":if(!Ps||!e.shimSafari)return t("Safari shim is not included in this adapter release."),s;t("adapter.js shimming safari."),s.browserShim=Ps,st(r,i),nt(r),Ts(r),bs(r),Cs(r),gs(r),vs(r),Es(r),ys(r),ks(r),tt(r),Jt(r),rt(r,i),it(r),Zt(r,i);break;default:t("Unsupported browser!");break}return s}_h({window:typeof window>"u"?void 0:window});class gh extends te{static async isSupported(e){if(e==="webTransport")return Promise.resolve(Bi.isSupported());try{return rh()||!window.RTCPeerConnection||!window.RTCPeerConnection.prototype.addTransceiver||!window.RTCPeerConnection.prototype.createDataChannel?!1:await oh()&&await nh()}catch{return!1}}constructor(e){super(),this._streamManagerController=new Eu,this._streamComposeController=new Du(this._streamManagerController),this._streamConsumeController=new th(this._streamComposeController,e),this._streamConsumeController.setPushConfig(e),this._observer=ch,this._bindEvent()}async getDevicesList(e){return this._streamManagerController.getDevicesList(e)}async getCameras(){return this._streamManagerController.getCameras()}async getMicrophones(){return this._streamManagerController.getMicrophones()}async startCamera(e){return this._streamManagerController.startCameraCapture(e)}stopCamera(e){this._streamManagerController.stopCapture({streamId:e,type:S.Camera})}async startMicrophone(e){return await this._streamManagerController.startMicrophoneCapture(e)}stopMicrophone(e){this._streamManagerController.stopCapture({streamId:e,type:S.Microphone})}async startVideoFileCapture(e){return e?await this._streamManagerController.startVideoFileCapture(e):void 0}stopVideoFileCapture(e){this._streamManagerController.stopCapture({streamId:e,type:S.VideoFile})}async startScreenCapture(e=!1){return await this._streamManagerController.startScreenCapture(e)}stopScreenCapture(e){this._streamManagerController.stopCapture({streamId:e,type:S.Screen})}async startAudioFileCapture(e){return e?await this._streamManagerController.startAudioFileCapture(e):void 0}stopAudioFileCapture(e){this._streamManagerController.stopCapture({streamId:e,type:S.AudioFile})}async startImageCapture(e){return e?await this._streamManagerController.startImageCapture(e):void 0}stopImageCapture(e){this._streamManagerController.stopCapture({streamId:e,type:S.Image})}startCustomVideoCapture(e){return e?this._streamManagerController.startCustomVideoCapture(e):void 0}stopCustomVideoCapture(e){this._streamManagerController.stopCapture({streamId:e,type:S.CustomVideo})}startCustomAudioCapture(e){return e?this._streamManagerController.startCustomAudioCapture(e):void 0}stopCustomAudioCapture(e){this._streamManagerController.stopCapture({streamId:e,type:S.CustomAudio})}async startVolumeDetect(e){var t;e?await this._streamManagerController.startVolumeDetect(e):await((t=this._streamComposeController.getComposedStream().audioStream)==null?void 0:t.startVolumeDetect())}stopVolumeDetect(e){var t;e?this._streamManagerController.stopVolumeDetect(e):(t=this._streamComposeController.getComposedStream().audioStream)==null||t.stopVolumeDetect()}getVolume(e){var t;return e?this._streamManagerController.getVolume(e):((t=this._streamComposeController.getComposedStream().audioStream)==null?void 0:t.volume)??0}enableMixing(e){if(this.isPushing())throw new Error("can not change mixing while pushing");this._streamComposeController.enableMixing(e)}setMixingConfig(e){this._streamComposeController.setMixingConfig(e)}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){return this._streamConsumeController.startPush(e)}addVideoStream(e){N(e)?e.forEach(t=>{this._streamComposeController.addVideoStream(t)}):this._streamComposeController.addVideoStream(e)}removeVideoStream(e){this._streamComposeController.removeVideoStream(e)}updateVideoStream(e){N(e)?this._streamComposeController.updateVideoStream(e):this._streamComposeController.updateVideoStream([e])}muteVideoStream(e){this._streamComposeController.muteVideoStream(e)}unmuteVideoStream(e){this._streamComposeController.unmuteVideoStream(e)}addAudioStream(e){N(e)?e.map(t=>this._streamComposeController.addAudioStream(t)):this._streamComposeController.addAudioStream(e)}removeAudioStream(e){this._streamComposeController.removeAudioStream(e)}updateAudioStream(e){N(e)?this._streamComposeController.updateAudioStream(e):this._streamComposeController.updateAudioStream([e])}muteAudioStream(e){this._streamComposeController.muteAudioStream(e)}unmuteAudioStream(e){this._streamComposeController.unmuteAudioStream(e)}setProperty(e,t){switch(e){case"setVideoResolution":this._streamManagerController.setVideoResolution(t);break;case"setVideoFps":this._streamManagerController.setVideoFps(t);break;case"setAudioSampleRate":this._streamManagerController.setAudioSampleRate(t);break;case"setPushMode":this._streamConsumeController.setPushMode(t);break;case"setVideoBitrate":this._streamConsumeController.setBitrate(t,"video");break;case"setAudioBitrate":this._streamConsumeController.setBitrate(t,"audio");break;case"setVolumeDetectScriptUrl":je.instance.volumeDetectScriptUrl=t;break;case"setMixerWorkerScriptUrl":this._streamComposeController.setMixerWorkerScript(t);break;case"updatePushUrl":this._streamConsumeController.updatePushUrl(t);break}}setVideoQuality(e){if(this._streamConsumeController.pushMode==="webTransport"&&["120p","180p","240p"].indexOf(e)!==-1)throw new Error("quality not allowed lower than 360p on rtmp mode");const{width:t,height:i,frameRate:s,bitrate:n}=ye(e,"video");this._streamManagerController.setVideoResolution({width:t,height:i}),this._streamManagerController.setVideoFps(s),this._streamComposeController.setVideoQuality({width:t,height:i,frameRate:s}),this._streamConsumeController.setBitrate(n,"video")}setAudioQuality(e){const{sampleRate:t,bitrate:i}=ye(e,"audio");this._streamManagerController.setAudioSampleRate(t),this._streamConsumeController.setBitrate(i,"audio")}getMediaStream(e){return this._streamManagerController.getStreamById(e).mediaStream}getStream(e){return this._streamManagerController.getStreamById(e)}stopPush(){return this._streamConsumeController.stopPush()}isPushing(){return this._streamConsumeController.isPushing()}getStats(){return this._streamConsumeController.getStats()}getPreviewElement(){return this._streamConsumeController.getPreviewElement()}getVideoStreamRenderConfig(e){return this._streamComposeController.getVideoStreamRenderConfig(e)}_bindEvent(){this._streamManagerController.on(z.Error,e=>{this.observer.onError(e.code,e.message,e.ext)}),this._streamManagerController.on(z.Interrupted,e=>{this.observer.onCaptureInterrupted(e.id)}),this._streamConsumeController.on(R.PushStart,()=>{this.observer.onPushStart()}),this._streamConsumeController.on(R.PushStop,()=>{this.observer.onPushStop()}),this._streamConsumeController.on(R.RTCConnectStateChanged,e=>{this.observer.onPushStatusUpdate(cr[e],e)}),this._streamConsumeController.on(R.PushError,e=>{this.observer.onError(e.code,e.message,e.ext)}),this._streamManagerController.on(z.DeviceStopCapture,e=>{this.observer.onStopCapture(e.id)}),this._streamConsumeController.on(R.CaptureFirstAudioFrame,()=>{this.observer.onCaptureFirstAudioFrame()}),this._streamConsumeController.on(R.CaptureFirstVideoFrame,()=>{this.observer.onCaptureFirstVideoFrame()}),this._streamConsumeController.on(R.ReconnectStateChange,(e,t)=>{this.observer.onReconnectStateChange(e,t)}),this._streamConsumeController.on(R.LiveConnectStateChange,e=>{this.observer.onLiveConnectStateChange(e)}),ho(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 gh});
|
|
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 yn(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 Sn(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 ag=Object.freeze(Object.defineProperty({__proto__:null,removeExtmapAllowMixed:ts,shimAddIceCandidateNullOrEmpty:yn,shimConnectionState:es,shimMaxMessageSize:gn,shimParameterlessSetLocalDescription:Sn,shimRTCIceCandidate:_n,shimRTCIceCandidateRelayProtocol:Qi,shimSendThrowTypeError:vn},Symbol.toStringTag,{value:"Module"}));function cg({window:r}={},e={shimChrome:!0,shimFirefox:!0,shimSafari:!0}){const t=Ja,n=ng(r),i={browserDetails:n,commonShim:ag,extractVersion:mn,disableLog:tg,disableWarnings:rg,sdp:og};switch(n.browser){case"chrome":if(!cc||!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=cc,yn(r,n),Sn(r),ec(r,n),tc(r),Xi(r,n),rc(r),oc(r,n),nc(r),ic(r),ac(r,n),_n(r),Qi(r),es(r),gn(r,n),vn(r),ts(r,n);break;case"firefox":if(!yc||!Zi||!e.shimFirefox)return t("Firefox shim is not included in this adapter release."),i;t("adapter.js shimming firefox."),i.browserShim=yc,yn(r,n),Sn(r),uc(r,n),Zi(r,n),lc(r),pc(r),hc(r),dc(r),fc(r),mc(r),_c(r),gc(r),vc(r),_n(r),es(r),gn(r,n),vn(r);break;case"safari":if(!Dc||!e.shimSafari)return t("Safari shim is not included in this adapter release."),i;t("adapter.js shimming safari."),i.browserShim=Dc,yn(r,n),Sn(r),Tc(r),Rc(r),Ec(r),Sc(r),bc(r),kc(r),Cc(r),Ac(r),_n(r),Qi(r),gn(r,n),vn(r),ts(r,n);break;default:t("Unsupported browser!");break}return i}cg({window:typeof window>"u"?void 0:window});class ug extends Qe{static async isSupported(e){if(e==="webTransport")return Promise.resolve(ja.isSupported());try{return W_()||!window.RTCPeerConnection||!window.RTCPeerConnection.prototype.addTransceiver||!window.RTCPeerConnection.prototype.createDataChannel?!1:await Y_()&&await Z_()}catch{return!1}}constructor(e){var t,n,i,s,a,o,l,c,u,d;if(super(),this._options=e??{},this._streamManagerController=new p_(this),this._streamComposeController=new C_(this._streamManagerController),this._streamConsumeController=new K_(this._streamComposeController,e),this._streamConsumeController.setPushConfig(e),this._observer=eg,this._bindEvent(),!(e!=null&&e.loggerConfig)||(t=e==null?void 0:e.loggerConfig)!=null&&t.enable){h_({showLogInConsole:((n=e==null?void 0:e.loggerConfig)==null?void 0:n.showInConsole)??!1});const h=c_((i=e==null?void 0:e.loggerConfig)==null?void 0:i.userId),f=u_((s=e==null?void 0:e.loggerConfig)==null?void 0:s.deviceId);d_({user_unique_id:h,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:((l=e==null?void 0:e.loggerConfig)==null?void 0:l.appId)??0},{user_id:h,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:((d=e==null?void 0:e.loggerConfig)==null?void 0:d.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:Z.Camera})}async startMicrophone(e){return await this._streamManagerController.startMicrophoneCapture(e)}stopMicrophone(e){this._streamManagerController.stopCapture({streamId:e,type:Z.Microphone})}async startVideoFileCapture(e){return e?await this._streamManagerController.startVideoFileCapture(e):void 0}stopVideoFileCapture(e){this._streamManagerController.stopCapture({streamId:e,type:Z.VideoFile})}async startScreenCapture(e=!1){return await this._streamManagerController.startScreenCapture(e)}stopScreenCapture(e){this._streamManagerController.stopCapture({streamId:e,type:Z.Screen})}async startAudioFileCapture(e){return e?await this._streamManagerController.startAudioFileCapture(e):void 0}stopAudioFileCapture(e){this._streamManagerController.stopCapture({streamId:e,type:Z.AudioFile})}async startImageCapture(e){return e?await this._streamManagerController.startImageCapture(e):void 0}stopImageCapture(e){this._streamManagerController.stopCapture({streamId:e,type:Z.Image})}startCustomVideoCapture(e){return e?this._streamManagerController.startCustomVideoCapture(e):void 0}stopCustomVideoCapture(e){this._streamManagerController.stopCapture({streamId:e,type:Z.CustomVideo})}startCustomAudioCapture(e){return e?this._streamManagerController.startCustomAudioCapture(e):void 0}stopCustomAudioCapture(e){this._streamManagerController.stopCapture({streamId:e,type:Z.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 It(ye.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":jr.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}=zt(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}=zt(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(ze.Error,e=>{this.observer.onError(e.code,e.message,e.ext)}),this._streamManagerController.on(ze.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(cs[e],e)}),this._streamConsumeController.on(se.PushError,e=>{this.observer.onError(e.code,e.message,e.ext)}),this._streamManagerController.on(ze.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)}),Vu(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 ug});
|