@vkontakte/videoplayer-statistics 1.0.98-beta.0 → 1.0.98-dev.10e34fe1.0

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/evergreen.esm.js CHANGED
@@ -1,6 +1,6 @@
1
1
  /**
2
- * @vkontakte/videoplayer-statistics v1.0.98-beta.0
3
- * Wed, 11 Feb 2026 13:57:25 GMT
2
+ * @vkontakte/videoplayer-statistics v1.0.98-dev.10e34fe1.0
3
+ * Thu, 12 Feb 2026 11:49:34 GMT
4
4
  * https://st.mycdn.me/static/vkontakte-videoplayer/1-0-98/doc/
5
5
  */
6
- var Ot=Object.defineProperty;var Bt=(a,e)=>{for(var i in e)Ot(a,i,{get:e[i],enumerable:!0})};var H=(c=>(c.PROD="prod",c.VK_ALIAS="vk_alias",c.VIDEOTEST="videotest",c.TEST="test",c.OKCDN="okcdn",c.AUTO="auto",c))(H||{}),ge=(p=>(p.Q144P="mobile",p.Q240P="lowest",p.Q360P="low",p.Q480P="medium",p.Q720P="high",p.Q1080P="fullhd",p.Q1440P="quadhd",p.Q2160P="ultrahd",p.UNKNOWN="unknown",p))(ge||{}),me=(u=>(u.MP4="mp4",u.DASH="dash",u.DASH_SEP="dash_sep",u.ONDEMAND_DASH="ondemand_dash",u.HLS="hls",u.HLS_FMP4="hls_fmp4",u.ONDEMAND_HLS="ondemand_hls",u.WEBM="webm",u.AV1="av1",u.ONDEMAND_DASH_LIVE="ondemand_dash_live",u.ONDEMAND_HLS_LIVE="ondemand_hls_live",u.WEBRTC="webrtc",u.UNKNOWN="unknown",u.RTMP="rtmp",u))(me||{});var be=(t=>(t.HTTP1="http1",t.HTTP2="http2",t.HTTP3="http3",t))(be||{});var ve=(l=>(l.SLIDER="slider",l.RICH="rich",l.DOUBLE_TAP="double_tap",l.TIME_CODE="time_code",l.EPISODE="episode",l.REWIND="rewind",l.LIVE="live",l.UNKNOWN="unknown",l))(ve||{}),Ke=(n=>(n.GRAPH_SHOW="iGraphShow",n.GRAPH_HIDE="iGraphHide",n.NEXT_AREA="iNextChapterArea",n.NEXT_BUTTON="iNextChapterBtn",n.WATCH_AGAIN="iWatchAgainBtn",n))(Ke||{}),ze={action_play:"ap",action_play_interactive:"api",first_bytes:"fb",player_ready:"pr",first_frame:"ff",seek:"sk",watch_coverage_record:"wr",watch_coverage_live:"wl",empty_buffer:"eb",action_stop:"as",close_at_empty_buffer:"cb",content_error:"er",player_interface_click:"pc",next_movie:"nm",track_switch:"ts",failover:"fo",quality:"qt"},je={vsid:"si",isid:"is",vid:"vi",place:"pl",quality:"qt",cdn_host:"ch",stat_type:"st",param:"pm",vk_app_id:"va",track_code:"tc",connection_type:"cnt",connection_reused:"cr",cached_data:"cd",live:"lv",muted:"mu",mode:"mo",subtitles:"sb",failover:"fo",download_speed:"ds",manual_quality:"mq",ref_domain:"rd",direct_url:"du"},Ge={unknown:"un",mobile:"m",lowest:"ls",low:"l",medium:"md",high:"h",fullhd:"f",quadhd:"q",ultrahd:"u"},Ye={pip:"pi",fullscreen:"fs",external:"ex",prefetch:"pr",airplay:"ap",chromecast:"cc",invisible:"iv",minimal:"minimal"};import{fillWithDefault as Ft}from"@vkontakte/videoplayer-shared/evergreen";var Xe="CIOPGQJGDIHBABABA",Ie={prod:"https://api.ok.ru",vk_alias:"https://api.mycdn.me",videotest:"https://videotestapi.ok.ru/api",test:"https://apitest.ok.ru",okcdn:"https://api.okcdn.ru",auto:""};var Ut={apiEnv:"vk_alias",apiKey:Xe,apiBaseUrl:null,requestRetryCount:1,useVsid64:!1,firstFlushTime:5e3,flushDebounceTime:1e4,flushMaxWait:6e4,storageExpiration:36*60*60*1e3,watchCoverageInterval:15e3,disabledOperations:["quality"],disabledCustomFields:[],shorten:!0,maxLoops:100,embedUrlParams:[],useBeacon:!0,synchronizeTime:!0,debugLog:!1,clearStorageAtUnload:!0,useVKComIsMobileLogic:!1,backoff:{start:1e3,factor:1.5,max:5*60*1e3,random:.1},useKeepalive:!1,watchCoverageTimeoutFix:!1},Je=a=>Ft(a,Ut);function ye(){let a="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".split(""),e=new Array(36),i=0,t,o;for(o=0;o<36;o++)o===8||o===13||o===18||o===23?e[o]="-":o===14?e[o]="4":(i<=2&&(i=33554432+Math.random()*16777216|0),t=i&15,i=i>>4,e[o]=a[o===19?t&3|8:t]);return e.join("")}import{assertNonNullable as oi,combine as ct,fromEvent as lt,isNonNullable as O,isNullable as ut,merge as ri,now as R,observableFrom as si,once as ni,safeStorage as ht,Subject as ai,Subscription as ke,ValueSubject as te}from"@vkontakte/videoplayer-shared/evergreen";import{Logger as di,detectEmbed as ci}from"@vkontakte/videoplayer-shared/evergreen";var Ht=()=>Math.floor(Math.random()*4294967296).toString(36).padStart(13,"0"),q=()=>Math.floor(Math.random()*18446744073709552e3).toString(36).padStart(13,"0"),D=class a{static getVSID(){return a.vsid}static generateVSID(e){return a.vsid=e?q():Ht(),a.vsid}};var Ze=a=>{let{operation:e,custom:i}=a,t=Object.fromEntries(Object.entries(i).map(([o,n])=>{let c=je[o]??o,h=n;return n&&(o==="mode"?h=Ye[n]??n:o==="quality"&&(h=Ge[n]??n)),[c,h]}));return{...a,operation:ze[e]??e,custom:t}};var P="1.0.98-beta.0";import{ValueSubject as qt,getExponentialDelay as Wt,ErrorCategory as M}from"@vkontakte/videoplayer-shared/evergreen";var Qt=/Mobile|mini|Fennec|Android|iP(ad|od|hone)|opera (mini|mobi)/i,W=class{constructor(e){this.consequentAuthErrors=0;this.authorized$=new qt(!1);this.params=e}async authorize(e){return this.authToken=e??await this.refreshAuthToken(),this._authorizeWithBackoff()}logBeacon(e){let i="log.externalLog",t=this.createLogParams(e),o=this.sessionKey;if(!o)return;this.params.apiTransport.sendBeacon(i,t,o)||this.logRequest(e).catch(()=>{})}async logRequest(e){let i="log.externalLog",t=this.createLogParams(e),o=this.sessionKey??await this._authorizeWithBackoff();if(!o)return;let n=async(c,h=this.params.config.requestRetryCount)=>{try{return await this.params.apiTransport.sendRequest(i,t,o)}catch(l){if(!l||!("error_code"in l)){this.params.error$.next({id:"logRequestUnknown",category:M.NETWORK,message:`Unknown ${i} error`,thrown:l});return}let p=l?.error_code;switch(p){case 102:case 103:case 104:return this.authorized$.next(!1),this.sessionKey=await this._authorizeWithBackoff(),h>0?n(c,h-1):void 0;case 401:return this.authorized$.next(!1),this.authToken=await this.refreshAuthToken(),this.sessionKey=await this._authorizeWithBackoff(),h>0?n(c,h-1):void 0;default:{this.params.error$.next({id:`LogRequest#${p}`,category:M.EXTERNAL_API,message:`${i} error`,data:l});return}}}};return n(e)}destroy(){window.clearTimeout(this.backoffTimeoutId),this.backoffTimeoutId=0}async refreshAuthToken(){if(this.params.refreshAuthToken)return this.refreshAuthTokenPromise||(this.refreshAuthTokenPromise=this.params.refreshAuthToken().finally(()=>{this.refreshAuthTokenPromise=void 0})),this.refreshAuthTokenPromise}createLogParams(e){let i="WEB",t=!1,o=`@vkontakte/videoplayer-statistics:${P}`;if(this.params.config.useVKComIsMobileLogic){let{appVersion:n}=window.navigator;t=Qt.test(n)}else this.params.mobile&&(t=!0);return t&&(i="M_WEB"),this.params.vktvVersion&&(i="SMART_TV",o=this.params.vktvVersion),{collector:"ok.mobile.apps.video",data:JSON.stringify({application:o,platform:i,items:this.params.config.shorten?e.map(Ze):e})}}_authorizeWithBackoff(){if(!this.consequentAuthErrors)return this._authorize();let e=Wt(this.consequentAuthErrors,this.params.config.backoff);return new Promise(i=>{this.backoffTimeoutId||(this.backoffTimeoutId=window.setTimeout(()=>{this._authorize().then(i).catch(t=>this.params.error$.next({id:"AuthorizeBackoff",category:M.NETWORK,message:"Otherwise unhandled error in authorization",thrown:t})).finally(()=>this.backoffTimeoutId=0)},e))})}async _authorize(){if(this.authorizePromise)return this.authorizePromise;this.sessionKey=void 0,this.authorized$.next(!1);let e="auth.anonymLogin",i={session_data:{version:2,device_id:this.params.deviceId,client_version:P.split("-")[0],client_type:"SDK_JS"}};return this.authToken!==void 0&&(i.session_data.auth_token=this.authToken,i.session_data.version=3),this.authorizePromise=this.params.apiTransport.sendRequest(e,i).then(t=>((!t||!t.session_key)&&this.params.error$.next({id:"AuthorizeFailed",category:M.EXTERNAL_API,message:"No session key",data:t}),this.sessionKey=t?.session_key??void 0,this.sessionKey)).catch(async t=>{this.sessionKey=void 0;let o=t?.error_code;switch(o){case 401:return this.authToken=await this.refreshAuthToken(),this._authorizeWithBackoff()}o?this.params.error$.next({id:`Authorize#${o}`,category:M.EXTERNAL_API,message:"authorize error",data:t}):this.params.error$.next({id:"AuthorizeUnknown",category:M.NETWORK,message:"authorize error",thrown:t})}).finally(()=>{this.authorizePromise=void 0,this.consequentAuthErrors=this.sessionKey?0:this.consequentAuthErrors+1,this.authorized$.next(this.sessionKey!==void 0)}),this.authorizePromise}};import{ErrorCategory as Y,now as Se}from"@vkontakte/videoplayer-shared/evergreen";var Q=class{constructor(e){this.params=e,this.apiKey=e.config.apiKey,this.apiEnv=e.config.apiEnv,this.apiBaseUrl=e.config.apiBaseUrl??Ie[this.apiEnv],this.timeSynchronisation=e.timeSynchronisation,this.isApiBaseUrlFetched=!1}async resolveApiBaseUrl(){if(this.apiEnv!=="auto"||this.isApiBaseUrlFetched)return this.apiBaseUrl;try{let e=atob("aHR0cHM6Ly9kbnMuZ29vZ2xlL3Jlc29sdmU/bmFtZT12aWRlby5fZW5kcG9pbnQub2sucnUmdHlwZT1UWFQ="),o=(await(await fetch(e,{method:"GET",mode:"cors",cache:"no-cache"})).json())?.Answer[0]?.data;if(!o)throw new Error("Wrong DNS response");return o}catch(e){return this.params.error$.next({id:"OneStat:ApiTransport:resolveApiBaseUrl",category:Y.NETWORK,message:"Unhandled resolve api base url error",thrown:e}),Ie.vk_alias}finally{this.isApiBaseUrlFetched=!0}}sendBeacon(e,i,t){if(!window.Blob||!window.navigator.sendBeacon)return!1;let o=this._prepareQueryParams({method:e,queryParams:i,sessionKey:t}),n=new window.Blob([o.toString()],{type:"application/x-www-form-urlencoded"});try{return window.navigator.sendBeacon(`${this.apiBaseUrl}/fb.do`,n)}catch(c){this.params.error$.next({id:"OneStat:ApiTransport:sendBeacon",category:Y.NETWORK,message:"Unhandled beacon error",thrown:c,data:{method:e,params:i}})}return!1}async sendRequest(e,i,t){let o=Se(),n=h=>{if(h instanceof TypeError&&["Failed to fetch","NetworkError when attempting to fetch resource."].includes(h.message)){this.params.error$.next({id:"Network",category:Y.NETWORK,message:"Request failed",thrown:h});return}this.params.error$.next({id:"OneStat:ApiTransport:sendRequest",category:Y.NETWORK,message:"Unhandled request error",thrown:h,data:{method:e,params:i,sessionKey:t,time:Se()-o}})};this.apiBaseUrl=await this.resolveApiBaseUrl();let c={method:"post",headers:{"Content-type":"application/x-www-form-urlencoded"},body:this._prepareQueryParams({method:e,queryParams:i,sessionKey:t})};return this.params.config.useKeepalive&&(c.keepalive=!0),fetch(`${this.apiBaseUrl}/fb.do`,c).then(h=>{let l=Number(h.headers.get("content-length"))===0,p=new Date(h.headers.get("date")??"").getTime(),g=Se()-o;if(isFinite(p)&&this.timeSynchronisation?.addServerTime(p,g),!l)return h.json().then(s=>Object.prototype.hasOwnProperty.call(s,"error_msg")?Promise.reject(s):s,n)},n)}_prepareQueryParams(e){let i=new URLSearchParams({format:"JSON",method:e.method,application_key:this.apiKey});return e.sessionKey!==void 0&&i.append("session_key",e.sessionKey),Object.entries(e.queryParams).forEach(([t,o])=>i.append(t,typeof o=="string"?o:JSON.stringify(o))),i}};import{ErrorCategory as Kt,now as zt,safeStorage as K,debounceFn as et}from"@vkontakte/videoplayer-shared/evergreen";var X="onestat_events",_e=a=>e=>e.timestamp+a>=zt(),J=class{constructor(e){this.unsaltedStorage=[];this.isPaused=!1;this.isUrgent=e=>{let{operation:i}=e;return["action_play","watch_coverage_record","watch_coverage_live"].includes(i)};this.params=e,this.api=e.api,this.error$=e.error$,this.userSalt=e.userSalt,this.loggerDebugLog=e.debugLogger.createComponentLog("stat logger"),this.firstFlush=et(()=>this.safeFlush(),this.params.config.firstFlushTime,{maxWait:this.params.config.firstFlushTime});let i=K.isPersistent()?this.params.config.flushMaxWait:0;this.debouncedFlush=et(()=>this.safeFlush(),this.params.config.flushDebounceTime,{maxWait:i}),this.subscription=this.api.authorized$.subscribe(t=>{t&&this.debouncedFlush()}),this.housekeepStorage()}safeFlush(){try{this.flush()}catch(e){this.error$.next({id:"LoggerError",category:Kt.WTF,message:e?String(e):"Unknown logger error",thrown:e})}}readFromStorage(){let e=K.get(X);try{return e?JSON.parse(e):{}}catch{}return{}}addToStorage(e){if(!this.userSalt){this.unsaltedStorage.push(e);return}let i=this.readFromStorage(),o=(i[this.userSalt]??[]).filter(_e(this.params.config.storageExpiration));K.set(X,JSON.stringify({...i,[this.userSalt]:[...o,e]}))}getFromStorage(){return this.userSalt?(this.readFromStorage()[this.userSalt]??[]).filter(_e(this.params.config.storageExpiration)):this.unsaltedStorage}markStorageSent(){if(!this.userSalt){this.unsaltedStorage=[];return}let e=this.readFromStorage();delete e[this.userSalt],K.set(X,JSON.stringify(e))}housekeepStorage(){let e=this.readFromStorage();for(let[i,t]of Object.entries(e)){let o=t.filter(_e(this.params.config.storageExpiration));o.length?e[i]=o:delete e[i],this.loggerDebugLog({message:`${t.length} retrieved from storage, ${o.length} of them actual`})}K.set(X,JSON.stringify(e))}log(e){this.addToStorage(e),!this.isPaused&&(this.isUrgent(e)?this.flush():this.lastVsid!==e.custom.vsid?this.firstFlush():this.debouncedFlush(),this.lastVsid=e.custom.vsid)}flush({wantBeacon:e,clearStorage:i}={wantBeacon:!1,clearStorage:!0}){let t=this.getFromStorage();t.length!==0&&(this.api.authorized$.getValue()?(e&&this.params.config.useBeacon?(this.loggerDebugLog({message:`Flushing ${t.length} events through beacon`}),this.api.logBeacon(t)):(this.loggerDebugLog({message:`Flushing ${t.length} events`}),this.api.logRequest(t)),i&&this.markStorageSent()):this.api.authorize(),this.firstFlush.cancel(),this.debouncedFlush.cancel())}pause(){this.isPaused=!0,this.debouncedFlush.cancel()}resume(){this.isPaused=!1,this.debouncedFlush()}destroy(){this.subscription.unsubscribe(),this.firstFlush.cancel(),this.debouncedFlush.cancel()}};import{HttpConnectionType as Pe,Surface as V,VideoFormat as y,VideoQuality as w}from"@vkontakte/videoplayer-core/evergreen";import{assertNever as tt}from"@vkontakte/videoplayer-shared/evergreen";var it=a=>a&&{[w.INVARIANT]:"unknown",[w.Q_144P]:"mobile",[w.Q_240P]:"lowest",[w.Q_360P]:"low",[w.Q_480P]:"medium",[w.Q_576P]:"unknown",[w.Q_720P]:"high",[w.Q_1080P]:"fullhd",[w.Q_1440P]:"quadhd",[w.Q_2160P]:"ultrahd",[w.Q_4320P]:"unknown"}[a],Te=a=>a&&{[Pe.HTTP1]:"http1",[Pe.HTTP2]:"http2",[Pe.QUIC]:"http3"}[a],ot=a=>{if(a!==void 0)switch(a){case y.MPEG:return"mp4";case y.DASH:case y.DASH_LIVE:case y.DASH_STREAMS:return"dash";case y.DASH_SEP:return"dash_sep";case y.DASH_ONDEMAND:return"ondemand_dash";case y.DASH_WEBM:case y.DASH_LIVE_WEBM:return"webm";case y.DASH_WEBM_AV1:return"av1";case y.DASH_LIVE_CMAF:return"ondemand_dash_live";case y.HLS:case y.HLS_LIVE:return"hls";case y.HLS_FMP4:return"hls_fmp4";case y.HLS_ONDEMAND:return"ondemand_hls";case y.HLS_LIVE_CMAF:return"ondemand_hls_live";case y.WEB_RTC_LIVE:return"webrtc";default:return tt(a)}},Ee=(a,e)=>{if(e)return"minimal";switch(a){case void 0:case V.NONE:case V.INLINE:return;case V.FULLSCREEN:return"fullscreen";case V.SECOND_SCREEN:return"chromecast";case V.PIP:return"pip";case V.INVISIBLE:return"invisible";default:return tt(a)}},rt=a=>{switch(a){case"slow-2g":return"poor";case"2g":return"poor";case"3g":return"good";case"4g":return"excellent"}};var Z=class{constructor(e){this.offset=void 0;this.offset=e}getOffset(){return this.offset??0}setOffset(e){this.offset=e}now(){return Date.now()+(this.offset??0)}date(e=new Date){return e.setTime(e.getTime()+(this.offset??0)),e}addServerTime(e,i){let t=Date.now(),o=e-t-i/2;if(Math.abs(o)<1e3){this.offset=0;return}this.offset===void 0?this.offset=Math.round(o):this.offset=Math.round(.2*o+(1-.2)*this.offset)}};import{PlaybackState as st}from"@vkontakte/videoplayer-core/evergreen";import{filter as nt,filterChanged as jt,fromEvent as Gt,isNullable as at,map as Yt,merge as we,Observable as Xt,Subject as Ae,Subscription as Jt,ValueSubject as Zt}from"@vkontakte/videoplayer-shared/evergreen";var dt=(a,e)=>new Xt(i=>{let t=new Jt,o=we(Gt(window,"beforeunload"),a.events.willDestruct$),n=new Zt(void 0),c;t.add(a.info.isLive$.pipe(jt()).subscribe(b=>{c&&(c.unsubscribe(),n.next(void 0)),b?c=a.info.liveTime$.pipe(Yt(_=>_&&_/1e3)).subscribe(n):c=a.info.position$.subscribe(n),t.add(c)}));let{playing$:h,paused$:l}=a.events,p=a.events.willSeek$.pipe(nt(()=>a.info.playbackState$.getValue()===st.PLAYING)),g=a.events.seeked$.pipe(nt(()=>a.info.playbackState$.getValue()===st.PLAYING)),s=!1,r=new Ae;t.add(p.subscribe(()=>{s||r.next(),s=!0})),t.add(g.subscribe(()=>s=!1));let d=new Ae,u=new Ae,f=we(h,g,d),m=we(l,r,o,a.events.looped$,u),v,T=()=>v=n.getValue(),E=()=>{let b=n.getValue();at(v)||v===b||at(b)||(i.next({from:v,to:b}),v=void 0)},S=()=>{u.next(),d.next()};if(t.add(f.subscribe(T)),t.add(m.subscribe(E)),e.forceInterval&&isFinite(e.forceInterval))if(e.watchCoverageTimeoutFix){let b,_=()=>{b!==void 0&&(window.clearTimeout(b),b=void 0)};t.add(f.subscribe(()=>{_(),b=window.setTimeout(S,e.forceInterval)})),t.add(m.subscribe(()=>_())),t.add(()=>_())}else{let b=0;t.add(f.subscribe(()=>b=window.setTimeout(S,e.forceInterval))),t.add(m.subscribe(()=>window.clearTimeout(b)))}return t});import{Surface as C}from"@vkontakte/videoplayer-core/evergreen";import{debounce as ei,filterChanged as ti,Subject as ii}from"@vkontakte/videoplayer-shared/evergreen";var ee=(a,e,i)=>{let t=new ii,o=t.pipe(ei(0),ti()),n=!1,c=!1,h=!1;return e(a.inPiP$,l=>{n=l,t.next(l?C.PIP:c?C.FULLSCREEN:h?C.INLINE:void 0)}),e(a.inFullscreen$,l=>{c=l,t.next(l?C.FULLSCREEN:n?C.PIP:h?C.INLINE:void 0)}),i&&e(i.info.surface$,l=>{switch(l){case C.SECOND_SCREEN:case C.NONE:case C.INLINE:{!c&&!n&&(l===C.INLINE&&(h=!0),t.next(l));break}}}),{surface$:o}};var li="_one-stat_",pt=`${li}deviceId`,xe=()=>{let a=new ke;return{subscription:a,subscribe:(e,i)=>{e&&a.add(e.subscribe(i))}}},Ce=class{constructor(e,i){this.subscription=new ke;this.debugLogger=new di;this.oneStatDebugLog=this.debugLogger.createComponentLog("onestat");this.loopCounter=0;this.disabled=!1;this.isid$=new te(void 0);this.zenUid$=new te(void 0);this.seekAction$=new te("unknown");this.statContext=e,this.config=Je(i.config??{}),O(i.apiEnv)&&(this.config.apiEnv=i.apiEnv),this.config.synchronizeTime&&(this.timeSynchronisation=new Z);let t=new ai;this.experimental={error$:t};let o=ht.get(pt);this.statContext.deviceId?this.deviceId=this.statContext.deviceId:o?this.deviceId=o:(this.deviceId=ye(),ht.set(pt,this.deviceId)),this.resetViewSession(),i.useIsid&&this.isid$.next(i.isid??q()),this.zenUid$.next(i.zenUid);let n=new Q({config:this.config,error$:t,timeSynchronisation:this.timeSynchronisation});this.api=new W({config:this.config,apiTransport:n,refreshAuthToken:i.refreshAuthToken,mobile:this.statContext.mobile??!1,deviceId:this.deviceId,error$:t,vktvVersion:i.vktvVersion}),this.logger=new J({config:this.config,debugLogger:this.debugLogger,api:this.api,error$:t,userSalt:i.userSalt});let{isEmbed:c,topOrigin:h}=ci();this.isEmbed=c,this.embedParent=h?new URL(h).hostname:void 0,this.subscribe()}get vsid$(){return new te(D.getVSID())}updateContext(e){this.statContext={...this.statContext,...e}}attachTo(e){let i=new ke,t=(r,d)=>i.add(r.subscribe(d));t(e.events.willStart$,()=>{let r=e.info.position$.getValue();this.logActionPlay({position:r}),this.statContext.projectId&&this.logActionPlayInteractive()}),t(e.events.looped$,()=>{this.resetViewSession(),++this.loopCounter>this.config.maxLoops&&(this.disabled=!0),this.logActionPlay({position:e.info.position$.getValue()})}),t(e.events.seeked$,()=>{let r=this.seekAction$.getValue();this.logSeek({action:r==="rich"?"slider":r,time:e.info.position$.getValue()}),this.seekAction$.next("unknown")}),t(e.events.paused$,()=>{this.logPause({position:e.info.position$.getValue()})}),t(e.events.willResume$,()=>{this.logPlay()}),t(e.events.started$,()=>{this.statContext.clip&&this.logWatchCoverageRecord({start:0,end:0})}),t(e.events.playing$,()=>{this.logPlaying()}),t(dt(e,{forceInterval:this.config.watchCoverageInterval,watchCoverageTimeoutFix:this.config.watchCoverageTimeoutFix}),r=>{let d=e.info.isLive$.getValue(),u=e.info.atLiveEdge$.getValue(),f={start:parseFloat(r.from.toFixed(3)),end:parseFloat(r.to.toFixed(3))};if(u){let m=e.info.liveLatency$.getValue()??0,v=e.info.currentBuffer$.getValue()?.end??0,T=e.info.liveBufferTime$.getValue()??0,E=Math.round((m-(v-T))*1e3),S=Math.round(m*1e3);E&&S&&(f.latency=E,f.bufferLatency=S)}d?this.logWatchCoverageLive(f):this.logWatchCoverageRecord(f)});let o;t(e.info.isStalled$,r=>{r?o=R():(O(o)&&this.logEmptyBuffer({duration:R()-o}),o=void 0)});let n=!1;i.add(e.events.fatalError$.pipe(ni()).subscribe(()=>n=!0)),t(e.events.willStop$,()=>{if(e.info.isStalled$.getValue()){let d=O(o)?R()-o:void 0;this.logCloseAtEmptyBuffer({duration:d??0}),o=void 0}else n||this.logActionStop()}),t(e.events.managedError$,({id:r})=>{this.logError({fatal:!1,errorType:r})}),t(e.events.fatalError$,({id:r})=>{this.logError({fatal:!0,errorType:r})});let c,h,l=!1;t(e.events.firstBytes$,r=>{c=R(),this.logFirstBytes({time:r})}),t(e.events.willStart$,()=>h=R()),t(e.info.currentBuffer$,r=>{!l&&r&&r.end-r.start>0&&O(c)&&(this.logPlayerReady({duration:R()-c}),l=!0)}),t(e.events.firstFrame$,()=>{O(c)&&!l&&(this.logPlayerReady({duration:R()-c}),l=!0),O(h)&&this.logFirstFrame({time:R()-h})});let p;t(e.info.currentVideoStream$,r=>{r&&(p&&r.id!==p&&this.logTrackSwitch(r),p=r.id)});let g;t(e.info.currentAudioStream$,r=>{r&&(g&&r.id!==g&&this.logTrackSwitch(r),g=r.id)}),t(e.info.atLiveEdge$,r=>this.updateContext({liveEdge:r})),t(ct({muted:e.info.muted$,volume:e.info.volume$}),({muted:r,volume:d})=>this.updateContext({audible:!r&&d>0})),t(e.info.currentQuality$,r=>{let d=it(r);this.updateContext({quality:d}),d&&this.logQuality(d)}),t(e.info.isAutoQualityEnabled$,r=>this.updateContext({autoQuality:r})),t(e.info.currentFormat$,r=>this.updateContext({contentType:ot(r)})),t(e.info.currentPlaybackRate$,r=>this.updateContext({rate:r})),t(e.info.is3DVideo$,r=>this.updateContext({is3d:r}));let s;return t(e.info.hostname$,r=>{let d=s!==void 0&&s!==r;this.updateContext({cdnHostname:r,failover:d}),d&&this.logFailover(r),s=r}),t(e.info.throughputEstimation$,r=>this.updateContext({downloadSpeed:r})),t(e.info.httpConnectionType$,r=>{this.statContext.firstConnectionType||this.updateContext({firstConnectionType:Te(r)}),this.updateContext({connectionType:Te(r)})}),t(e.info.httpConnectionReused$,r=>{ut(this.statContext.firstConnectionReused)&&this.updateContext({firstConnectionReused:r}),this.updateContext({connectionReused:r})}),t(e.info.surface$,r=>{this.uiEvents||this.updateContext({mode:Ee(r,this.statContext.isPreviewPlayerView)})}),t(ct({current:e.info.currentTextTrack$,available:e.info.availableTextTracks$}),({current:r,available:d})=>{let u=d.find(({id:m})=>m===r),f=u&&(u.isAuto?`${u.language}_auto`:u.language);this.updateContext({subtitles:f?.split(".")[0]})}),this.player=e,this.uiEvents&&this.attachToUi(this.uiEvents),this.resubscribeBeforeunload(),this.subscription.add(i),i}attachToUi(e){this.uiEvents=e;let{subscription:i,subscribe:t}=xe();if(!this.player)return i;t(e.actionRewind$,()=>{this.player&&(this.resetViewSession(),this.logActionPlay({position:this.player.info.position$.getValue()}))}),t(e.actionSeek$,this.seekAction$);let{surface$:o}=ee(this.uiEvents,t,this.player);return t(o,n=>{this.updateContext({mode:Ee(n,this.statContext.isPreviewPlayerView)})}),t(e.actionSetSubtitle$,n=>this.updateContext({subtitles:n?.split(".")[0]})),t(e.nextMovie$,n=>this.logNextMovie(n)),this.resubscribeBeforeunload(),this.subscription.add(i),i}attachToAds(e){let{subscription:i,subscribe:t}=xe();return t(e.slotRequested$,()=>this.logAdSlotRequest()),t(e.started$,o=>this.logAdStarted(o)),t(e.paused$,()=>this.logAdPaused()),t(e.resumed$,()=>this.logAdResumed()),t(e.ended$,()=>this.logAdEnded()),t(e.skipped$,()=>this.logAdSkipped()),t(e.clicked$,()=>this.logAdClicked()),t(e.error$,o=>this.logError({errorType:o,fatal:!1})),this.resubscribeBeforeunload(),this.subscription.add(i),i}attachToInteractive(e){let{subscription:i,subscribe:t}=xe();return t(e.click$,o=>this.logInterfaceClick(o)),t(e.nextMovie$,o=>this.logNextMovie(o)),this.resubscribeBeforeunload(),this.subscription.add(i),i}authorize(e){return this.api.authorize(e)}pause(){this.logger.pause(),this.oneStatDebugLog({message:"paused"})}resume(){this.logger.resume(),this.oneStatDebugLog({message:"resumed"})}destroy(){this.logger.flush(),this.subscription.unsubscribe(),this.api.destroy(),this.logger.destroy()}resetViewSession(){this.oneStatDebugLog({message:"VSID reset"}),D.generateVSID(this.config.useVsid64)}getDeviceId(){return this.deviceId}setFieldBlacklist(){}logInited(){}logReady(e){this.log({operation:"player_ready",param:String(e.time)})}logStarted(...e){this.logActionPlay(...e)}logPlay(){this.log({operation:"play_toggle"})}logPlaying(){this.log({operation:"playing"})}logPause(e){this.log({operation:"pause",param:String(Math.round(e.position))})}logSeek(e){this.log({operation:"seek",param:e.action,time:e.time})}logFirstBytes(e){this.log({operation:"first_bytes",param:String(e.time)})}logFirstFrame(e){this.log({operation:"first_frame",param:String(e.time)})}logError(e){this.log({operation:"content_error",param:`${e.fatal?"fatal":"recoverable"}_${e.errorType}`})}logWatchCoverageRecord(e){this.log({operation:"watch_coverage_record",param:`${e.start}-${e.end}`},{in_history:this.statContext.inHistory?1:void 0})}logWatchCoverageLive(e){let i=this.timeSynchronisation?.getOffset()??0,t=e.start+i,o=e.end+i;this.log({operation:"watch_coverage_live",param:`${t}-${o}`},{in_history:this.statContext.inHistory?1:void 0,latency:e.latency,buffer_latency:e.bufferLatency})}logEmptyBuffer(e){this.log({operation:"empty_buffer",param:String(e.duration)})}logDownloadSpeed(){}logAdSlotRequest(){this.log({operation:"adv",param:"slot_request"})}logAdStarted(e){this.log({operation:"adv",param:e})}logAdPaused(){this.log({operation:"adv",param:"pause"})}logAdResumed(){this.log({operation:"adv",param:"resume"})}logAdEnded(){this.log({operation:"adv",param:"ended"})}logAdSkipped(){this.log({operation:"adv",param:"skip"})}logAdClicked(){this.log({operation:"adv",param:"click"})}logInterfaceClick(e){this.log({operation:"player_interface_click",param:e})}logNextMovie(e){this.log({operation:"next_movie",param:String(e)})}subscribe(){this.resubscribeBeforeunload();let e=window.navigator.connection;e&&"onchange"in e&&"effectiveType"in e&&this.subscription.add(ri(lt(e,"change"),si(["init"])).subscribe(()=>this.updateContext({network:rt(e.effectiveType)}))),this.config.debugLog&&this.debugLogger.log$.subscribe(i=>{console.debug("%c stat ","background:#fa6470;",`component: ${i.component}.`,i.message)})}resubscribeBeforeunload(){this.beforeunloadSubscription?.unsubscribe(),this.beforeunloadSubscription=lt(window,"beforeunload").subscribe(()=>this.logger.flush({wantBeacon:!0,clearStorage:this.config.clearStorageAtUnload})),this.subscription.add(this.beforeunloadSubscription)}logPlayerReady(e){this.log({operation:"player_ready",param:String(Math.round(e.duration))})}logActionPlay(e){this.log({operation:"action_play",param:String(Math.round(e.position))})}logActionPlayInteractive(){this.statContext.projectId&&this.log({operation:"action_play_interactive",param:String(this.statContext.movieId)},{vid:this.statContext.projectId})}logFailover(e){this.log({operation:"failover",param:e})}logCloseAtEmptyBuffer(e){this.log({operation:"close_at_empty_buffer",param:String(Math.round(e.duration))})}logActionStop(){this.log({operation:"action_stop"})}logTrackSwitch(e){this.log({operation:"track_switch",param:e.id})}logQuality(e){this.log({operation:"quality",param:e})}log(e,i={}){if(this.disabled){this.oneStatDebugLog({message:`operation ${e.operation} but statistics is disabled`});return}if(this.config.disabledOperations.includes(e.operation)){this.oneStatDebugLog({message:`operation ${e.operation} but it is disabled`});return}this.oneStatDebugLog({message:`operation ${e.operation} ${e.param}`});let t=this.createLogItem(e,i);this.logger.log(t)}createLogItem({operation:e,param:i,time:t},o={}){let n=this.timeSynchronisation?.now()??R(),c=this.vsid$.getValue();oi(c);let h=this.isid$.getValue(),l=e==="empty_buffer"||e==="close_at_empty_buffer"?this.statContext.connectionType:this.statContext.firstConnectionType,p=this.statContext.firstConnectionReused,g,s;if(this.isEmbed||this.statContext.place==="embed"){g=this.embedParent;let d=[...new URLSearchParams(location.search).entries()].filter(([u,f])=>this.config.embedUrlParams.includes(u));s=new URLSearchParams(d).toString()}else if(this.statContext.place==="direct"){let d=this.statContext.refDomain||document.referrer;d&&URL.canParse(d)?g=new URL(d).hostname:g=d,s=location.href.substring(0,1024)}let r={vsid:c,isid:h,vid:this.statContext.movieId,uid:this.zenUid$.getValue(),ct:this.statContext.contentType,place:this.isEmbed?"embed":this.statContext.place,quality:this.statContext.quality,cdn_host:this.statContext.cdnHostname,stat_type:this.statContext.autoplay===!0?"auto":this.statContext.autoplay===!1?"":void 0,param:i,vk_app_id:this.statContext.vkAppId,track_code:this.statContext.trackCode,connection_type:l,connection_reused:p===!0?1:p===!1?0:void 0,cached_data:this.statContext.cached===!0?1:this.statContext.cached===!1?0:void 0,live:this.statContext.liveEdge?1:void 0,muted:this.statContext.audible===!1?1:void 0,mode:this.statContext.mode,subtitles:this.statContext.subtitles,download_speed:this.statContext.downloadSpeed,manual_quality:this.statContext.autoQuality?void 0:1,ref_domain:g,direct_url:s,rate:this.statContext.rate===1||ut(this.statContext.rate)?void 0:this.statContext.rate.toFixed(2),view_360:this.statContext.is3d?1:void 0,aid:this.statContext.albumId,vk_playlist_id:this.statContext.vkPlaylistId,...o};for(let d of this.config.disabledCustomFields)delete r[d];return{operation:e,type:1,time:t,network:this.statContext.network,timestamp:n,custom:r}}};var Dt={};Bt(Dt,{ActionSeekType:()=>ie,ThinOneStat:()=>he,VERSION:()=>P});import{assertNonNullable as ki,detectEmbed as Ci,fromEvent as $i,Logger as Li,merge as Ct,combine as ue,filter as k,filterChanged as Ri,once as Di,skip as Fe,safeStorage as $t,getWindow as Ni,Subject as Mi,Subscription as He,ValueSubject as Ue,ErrorCategory as U}from"@vkontakte/videoplayer-shared/evergreen";import{clientChecker as $}from"@vkontakte/videoplayer-core/evergreen";import{fillWithDefault as ui}from"@vkontakte/videoplayer-shared/evergreen";var $e=(t=>(t.AUTO="auto",t.AUTO_POOR="auto_poor",t.AUTO_RICH="auto_rich",t))($e||{});var ie=(l=>(l.SLIDER="slider",l.RICH="rich",l.DOUBLE_TAP="double_tap",l.TIME_CODE="time_code",l.EPISODE="episode",l.REWIND="rewind",l.LIVE="live",l.UNKNOWN="unknown",l))(ie||{});var gt="CIOPGQJGDIHBABABA",Le={prod:"https://api.ok.ru",vk_alias:"https://api.mycdn.me",videotest:"https://videotestapi.ok.ru/api",test:"https://apitest.ok.ru",okcdn:"https://api.okcdn.ru",auto:""};var hi={apiKey:gt,apiEnv:"okcdn",apiBaseUrl:null,requestRetryCount:1,useVsid64:!1,firstFlushTime:5e3,flushDebounceTime:1e4,flushMaxWait:6e4,storageExpiration:36*60*60*1e3,watchCoverageHeartbeatInterval:3e4,disabledEvents:[],disabledParams:[],synchronizeTime:!0,useBeacon:!1,alwaysSendDesktop:!1,watchedNDefaultTargetDuration:1e3,downloadBytesMaxTime:3e4},mt=a=>ui(a,hi);import{getExponentialDelay as pi,ErrorCategory as B,ValueSubject as fi}from"@vkontakte/videoplayer-shared/evergreen";var oe=class{constructor(e){this.params=e,this.authorized$=new fi(!1),this.consequentAuthErrors=0}async authorize(e){return this.authToken=e??await this.refreshAuthToken(),this.authorizeWithBackoff()}logBeacon(e){let i="log.logUvStat",t=this.createLogParams(e),o=this.sessionKey;if(!o)return;this.params.apiTransport.sendBeacon(i,t,o)||this.logRequest(e).catch(()=>{})}async logRequest(e){let i="log.logUvStat",t=this.createLogParams(e),o={},n=this.sessionKey??await this.authorizeWithBackoff();if(!n)return;let c=async(h,l=this.params.config.requestRetryCount)=>{try{return await this.params.apiTransport.sendRequest(i,t,n,o)}catch(p){if(!p||!("error_code"in p)){this.params.error$.next({id:"logRequestUnknown",category:B.NETWORK,message:`Unknown ${i} error`,thrown:p});return}let g=p?.error_code;switch(g){case 102:case 103:case 104:return this.authorized$.next(!1),this.sessionKey=await this.authorizeWithBackoff(),l>0?c(h,l-1):void 0;case 401:return this.authorized$.next(!1),this.authToken=await this.refreshAuthToken(),this.sessionKey=await this.authorizeWithBackoff(),l>0?c(h,l-1):void 0;default:{this.params.error$.next({id:`LogRequest#${g}`,category:B.EXTERNAL_API,message:`${i} error`,data:p});return}}}};return c(e)}destroy(){window.clearTimeout(this.backoffTimeoutId),this.backoffTimeoutId=0}async refreshAuthToken(){if(this.params.refreshAuthToken)return this.refreshAuthTokenPromise||(this.refreshAuthTokenPromise=this.params.refreshAuthToken().finally(()=>{this.refreshAuthTokenPromise=void 0})),this.refreshAuthTokenPromise}createLogParams(e){return{collector:"ok.mobile.apps.video",uv_stat_data:JSON.stringify({application:`@vkontakte/videoplayer-statistics:${P}`,platform:e[0].platform,product:e[0].product,events:e})}}authorizeWithBackoff(){if(!this.consequentAuthErrors)return this.doAuthorize();let e=pi(this.consequentAuthErrors);return new Promise(i=>{this.backoffTimeoutId||(this.backoffTimeoutId=window.setTimeout(async()=>{try{let t=await this.doAuthorize();i(t)}catch(t){this.params.error$.next({id:"AuthorizeBackoff",category:B.NETWORK,message:"Otherwise unhandled error in authorization",thrown:t})}finally{this.backoffTimeoutId=0}},e))})}doAuthorize(){if(this.authorizePromise)return this.authorizePromise;this.sessionKey=void 0,this.authorized$.next(!1);let e="auth.anonymLogin",i={session_data:{version:2,device_id:this.params.deviceId,client_version:P.split("-")[0],client_type:"SDK_JS"}};return this.authToken!==void 0&&(i.session_data.auth_token=this.authToken,i.session_data.version=3),this.authorizePromise=this.params.apiTransport.sendRequest(e,i).then(t=>((!t||!t.session_key)&&this.params.error$.next({id:"AuthorizeFailed",category:B.EXTERNAL_API,message:"No session key",data:t}),this.sessionKey=t?.session_key??void 0,this.sessionKey)).catch(async t=>{this.sessionKey=void 0;let o=t?.error_code;switch(o){case 401:return this.authToken=await this.refreshAuthToken(),this.authorizeWithBackoff()}o?this.params.error$.next({id:`Authorize#${o}`,category:B.EXTERNAL_API,message:"authorize error",data:t}):this.params.error$.next({id:"AuthorizeUnknown",category:B.NETWORK,message:"authorize error",thrown:t})}).finally(()=>{this.authorizePromise=void 0,this.consequentAuthErrors=this.sessionKey?0:this.consequentAuthErrors+1,this.authorized$.next(this.sessionKey!==void 0)}),this.authorizePromise}};import{now as Re,ErrorCategory as re}from"@vkontakte/videoplayer-shared/evergreen";var se=class{constructor(e){this.params=e,this.apiKey=e.config.apiKey,this.apiEnv=e.config.apiEnv,this.apiBaseUrl=e.config.apiBaseUrl??Le[this.apiEnv],this.timeSynchronisation=e.timeSynchronisation,this.isApiBaseUrlFetched=!1}sendBeacon(e,i,t){if(!window.Blob||!window.navigator.sendBeacon)return!1;let o=this.prepareQueryParams({method:e,queryParams:i,sessionKey:t}),n=new window.Blob([o.toString()],{type:"application/x-www-form-urlencoded"});try{return window.navigator.sendBeacon(`${this.apiBaseUrl}/fb.do`,n)}catch(c){this.params.error$.next({id:"OneStat:ApiTransport:sendBeacon",category:re.NETWORK,message:"Unhandled beacon error",thrown:c,data:{method:e,params:i}})}return!1}async sendRequest(e,i,t,o){let n=Re(),c=h=>{if(h instanceof TypeError&&["Failed to fetch","NetworkError when attempting to fetch resource."].includes(h.message)){this.params.error$.next({id:"Network",category:re.NETWORK,message:"Request failed",thrown:h});return}this.params.error$.next({id:"ThinOneStat:ApiTransport:sendRequest",category:re.NETWORK,message:"Unhandled request error",thrown:h,data:{method:e,params:i,sessionKey:t,time:Re()-n}})};return this.apiBaseUrl=await this.resolveApiBaseUrl(),fetch(`${this.apiBaseUrl}/fb.do`,{method:"post",headers:{"Content-type":"application/x-www-form-urlencoded",...o},body:this.prepareQueryParams({method:e,queryParams:i,sessionKey:t})}).then(h=>{let l=Number(h.headers.get("content-length"))===0,p=new Date(h.headers.get("date")??"").getTime(),g=Re()-n;if(isFinite(p)&&this.timeSynchronisation?.addServerTime(p,g),!l)return h.json().then(s=>Object.prototype.hasOwnProperty.call(s,"error_msg")?Promise.reject(s):s,c)},c)}async resolveApiBaseUrl(){if(this.apiEnv!=="auto"||this.isApiBaseUrlFetched)return this.apiBaseUrl;try{let e=atob("aHR0cHM6Ly9kbnMuZ29vZ2xlL3Jlc29sdmU/bmFtZT12aWRlby5fZW5kcG9pbnQub2sucnUmdHlwZT1UWFQ="),o=(await(await fetch(e,{method:"GET",mode:"cors",cache:"no-cache"})).json())?.Answer[0]?.data;if(!o)throw new Error("Wrong DNS response");return o}catch(e){return this.params.error$.next({id:"ThinOneStat:ApiTransport:resolveApiBaseUrl",category:re.NETWORK,message:"Unhandled resolve api base url error",thrown:e}),Le.vk_alias}finally{this.isApiBaseUrlFetched=!0}}prepareQueryParams(e){let i=new URLSearchParams({format:"JSON",method:e.method,application_key:this.apiKey});return e.sessionKey!==void 0&&i.append("session_key",e.sessionKey),Object.entries(e.queryParams).forEach(([t,o])=>i.append(t,typeof o=="string"?o:JSON.stringify(o))),i}};import{ErrorCategory as gi,now as mi,safeStorage as z,debounceFn as bt}from"@vkontakte/videoplayer-shared/evergreen";var ne="thinonestat_events",De=a=>e=>e.client_time+a>=mi(),ae=class{constructor(e){this.unsaltedStorage=[];this.isPaused=!1;this.isUrgent=e=>{let{event_name:i}=e;return["watch_coverage","watch_coverage_live","watched_n","playback_started"].includes(i)};this.params=e,this.api=e.api,this.error$=e.error$,this.userSalt=e.userSalt,this.loggerDebugLog=e.debugLogger.createComponentLog("stat logger"),this.firstFlush=bt(()=>this.safeFlush(),this.params.config.firstFlushTime,{maxWait:this.params.config.firstFlushTime});let i=z.isPersistent()?this.params.config.flushMaxWait:0;this.debouncedFlush=bt(()=>this.safeFlush(),this.params.config.flushDebounceTime,{maxWait:i}),this.subscription=this.api.authorized$.subscribe(t=>{t&&this.debouncedFlush()}),this.housekeepStorage()}safeFlush(){try{this.flush()}catch(e){this.error$.next({id:"LoggerError",category:gi.WTF,message:String(e)||"Unknown logger error",thrown:e})}}readFromStorage(){let e=z.get(ne);try{return e?JSON.parse(e):{}}catch{}return{}}addToStorage(e){if(!this.userSalt){this.unsaltedStorage.push(e);return}let i=this.readFromStorage(),o=(i[this.userSalt]??[]).filter(De(this.params.config.storageExpiration));z.set(ne,JSON.stringify({...i,[this.userSalt]:[...o,e]}))}getFromStorage(){return this.userSalt?(this.readFromStorage()[this.userSalt]??[]).filter(De(this.params.config.storageExpiration)):this.unsaltedStorage}markStorageSent(){if(!this.userSalt){this.unsaltedStorage=[];return}let e=this.readFromStorage();delete e[this.userSalt],z.set(ne,JSON.stringify(e))}housekeepStorage(){let e=this.readFromStorage();for(let[i,t]of Object.entries(e)){let o=t.filter(De(this.params.config.storageExpiration));o.length?e[i]=o:delete e[i],this.loggerDebugLog({message:`${t.length} retrieved from storage, ${o.length} of them actual`})}z.set(ne,JSON.stringify(e))}log(e){this.addToStorage(e),!this.isPaused&&(this.isUrgent(e)?this.flush():this.lastVsid!==e.vsid?this.firstFlush():this.debouncedFlush(),this.lastVsid=e.vsid)}flush({wantBeacon:e,clearStorage:i}={wantBeacon:!1,clearStorage:!0}){let t=this.getFromStorage();t.length!==0&&(this.api.authorized$.getValue()?(e&&this.params.config.useBeacon?(this.loggerDebugLog({message:`Flushing ${t.length} events through beacon`}),this.api.logBeacon(t)):(this.loggerDebugLog({message:`Flushing ${t.length} events`}),this.api.logRequest(t)),i&&this.markStorageSent()):this.api.authorize(),this.firstFlush.cancel(),this.debouncedFlush.cancel())}pause(){this.isPaused=!0,this.debouncedFlush.cancel()}resume(){this.isPaused=!1,this.debouncedFlush()}destroy(){this.subscription.unsubscribe(),this.firstFlush.cancel(),this.debouncedFlush.cancel()}};function Ne(){let a="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".split(""),e=new Array(36),i=0,t,o;for(o=0;o<36;o++)o===8||o===13||o===18||o===23?e[o]="-":o===14?e[o]="4":(i<=2&&(i=33554432+Math.random()*16777216|0),t=i&15,i=i>>4,e[o]=a[o===19?t&3|8:t]);return e.join("")}var de=class{constructor(e){this.offset=void 0;this.offset=e}getOffset(){return this.offset??0}setOffset(e){this.offset=e}now(){return Date.now()+(this.offset??0)}date(e=new Date){return e.setTime(e.getTime()+(this.offset??0)),e}addServerTime(e,i){let t=Date.now(),o=e-t-i/2;if(Math.abs(o)<1e3){this.offset=0;return}this.offset===void 0?this.offset=Math.round(o):this.offset=Math.round(.2*o+(1-.2)*this.offset)}};import{PlaybackState as vt}from"@vkontakte/videoplayer-core/evergreen";import{Observable as bi,Subscription as vi,ValueSubject as Ii,Subject as Me,fromEvent as yi,isNullable as It,merge as j,filter as yt,filterChanged as St,getWindow as Ve}from"@vkontakte/videoplayer-shared/evergreen";var _t=(a,e,i)=>new bi(t=>{let o=new vi,n=new Ii(void 0),c;o.add(a.info.isLive$.pipe(St()).subscribe(L=>{c&&(c.unsubscribe(),n.next(void 0)),L?c=a.info.liveTime$.pipe(St()).subscribe(n):c=a.info.position$.subscribe(n),o.add(c)}));let{playing$:h,paused$:l,ended$:p,looped$:g}=a.events,s=a.events.willSeek$.pipe(yt(()=>a.info.playbackState$.getValue()===vt.PLAYING)),r=a.events.seeked$.pipe(yt(()=>a.info.playbackState$.getValue()===vt.PLAYING)),d=!1,u=new Me;o.add(s.subscribe(()=>{d||u.next(),d=!0})).add(r.subscribe(()=>d=!1));let f=j(yi(Ve(),"beforeunload"),a.events.willDestruct$),m,v=()=>m=n.getValue(),T=()=>{let L=n.getValue();It(m)||It(L)||m===L||(t.next({from:m,to:L}),m=void 0)},E=new Me,S=new Me,b=j(h,r,E),_=j(l,u,f,p,g,S),We=e.started$&&e.ended$?j(b,e.ended$):b,Qe=e.started$&&e.ended$?j(_,e.started$):_;if(o.add(We.subscribe(v)).add(Qe.subscribe(T)),i.heartbeatInterval&&isFinite(i.heartbeatInterval)){let L=[],Vt=()=>{S.next(),E.next()};o.add(We.subscribe(()=>{let fe=Ve().setTimeout(Vt,i.heartbeatInterval);L.push(fe)})).add(Qe.subscribe(()=>{L.forEach(fe=>{Ve().clearTimeout(fe)}),L=[]}))}return o});import{Subscription as Si}from"@vkontakte/videoplayer-core/evergreen";import{Observable as _i,merge as Pi}from"@vkontakte/videoplayer-shared/evergreen";var Pt=(a,e)=>new _i(i=>{let t=new Si;return t.add(Pi(a.info.position$,a.info.liveTime$).subscribe(()=>{let o=e.getTotalViewTime();o>=e.targetDuration&&(i.next({target_duration:e.targetDuration,current_tvt:o}),t.unsubscribe())})),t});import{Subscription as Ti}from"@vkontakte/videoplayer-core/evergreen";import{Observable as Ei,filter as wi,getWindow as Tt}from"@vkontakte/videoplayer-shared/evergreen";var Et=(a,{maxTimeWindow:e})=>new Ei(i=>{let t=new Ti,o={maxBytesThreshold:100*1024*1024,minBytesThreshold:100*1024,maxTimeWindow:e,minTimeWindow:2e3},n={bytes:0,startTime:0,lastEmitTime:0,timeoutId:0},c=()=>{n.timeoutId&&(Tt().clearTimeout(n.timeoutId),n.timeoutId=null)},h=()=>{n.bytes=0,n.startTime=0,n.lastEmitTime=0,c()},l=s=>{if(n.bytes<o.minBytesThreshold||s-n.lastEmitTime<o.minTimeWindow&&n.lastEmitTime>0)return!1;let u=(n.startTime>0?s-n.startTime:0)>=o.maxTimeWindow,f=n.bytes>=o.maxBytesThreshold;return u||f},p=(s=!1)=>{let r=Date.now();if(!s&&!l(r))return;c();let d=n.startTime>0?r-n.startTime:Math.max(o.minTimeWindow,1),u=n.bytes/(d/1e3);i.next({download_bytes:Math.round(n.bytes),download_speed:Math.round(u)}),n.lastEmitTime=r,h()},g=()=>{if(c(),n.startTime>0&&n.bytes>=o.minBytesThreshold){let r=Date.now()-n.startTime,d=o.maxTimeWindow-r;d>100?n.timeoutId=Tt().setTimeout(()=>{n.timeoutId=null,p()},d):d>0&&p()}};return t.add(a.info.httpDownloadMetrics$.pipe(wi(s=>s!==void 0)).subscribe(s=>{let r=Date.now();n.startTime===0&&(n.startTime=r),n.bytes+=s.bytes,l(r)?p():g()})),t.add(()=>{if(c(),n.bytes>0){let s=Date.now(),r=n.startTime>0?s-n.startTime:o.minTimeWindow,d=n.bytes/(r/1e3);i.next({download_bytes:Math.round(n.bytes),download_speed:Math.round(d)})}h()}),t});import{Observable as Ai,Subscription as xi,merge as wt}from"@vkontakte/videoplayer-shared/evergreen";var At=a=>new Ai(e=>{let i=new xi,t=0,o=1,n=0,c=!1,h=!1,l=()=>{if(!c)return;let b=Date.now();n+=(b-t)*o,t=b},p=()=>{(!c||h)&&(t=Date.now(),c=!0,h=!1)},g=()=>{c&&(l(),c=!1)},s=()=>{c&&(l(),c=!1,h=!0)},r=b=>{c&&l(),o=b,t=Date.now()},{started$:d,playing$:u,paused$:f,willSeek$:m,ended$:v,willDestruct$:T}=a.events,{currentPlaybackRate$:E}=a.info;i.add(m.subscribe(s)).add(wt(d,u).subscribe(p)).add(wt(f,v,T).subscribe(g)).add(E.subscribe(r));let S=()=>{let b=n;return c&&(b+=(Date.now()-t)*o),b};return e.next(S),i});import{assertNever as xt}from"@vkontakte/videoplayer-shared/evergreen";import{HttpConnectionType as Oe,Surface as F,VideoFormat as I,VideoQuality as A}from"@vkontakte/videoplayer-core/evergreen";var Be=a=>a&&{[Oe.HTTP1]:"http1",[Oe.HTTP2]:"http2",[Oe.QUIC]:"http3"}[a],G=a=>{if(a!==void 0)switch(a){case I.MPEG:return"MP4";case I.DASH:case I.DASH_LIVE:return"DASH";case I.DASH_SEP:return"DASH_SEP";case I.DASH_ONDEMAND:return"ONDEMAND_DASH";case I.HLS_ONDEMAND:return"ONDEMAND_HLS";case I.HLS:case I.HLS_LIVE:return"HLS";case I.HLS_FMP4:return"HLS_FMP4";case I.DASH_WEBM:case I.DASH_LIVE_WEBM:return"WEBM";case I.DASH_LIVE_CMAF:return"ONDEMAND_DASH_LIVE";case I.HLS_LIVE_CMAF:return"ONDEMAND_HLS_LIVE";case I.WEB_RTC_LIVE:return"WEBRTC";case I.DASH_WEBM_AV1:return"AV1";case I.DASH_STREAMS:return"MULTI_DASH";default:return xt(a)}},x=a=>{if(a!==void 0)switch(a){case A.Q_144P:return"144p";case A.Q_240P:return"240p";case A.Q_360P:return"360p";case A.Q_480P:return"480p";case A.Q_720P:return"720p";case A.Q_1080P:return"1080p";case A.Q_1440P:return"1440p";case A.Q_2160P:return"2160p";case A.INVARIANT:case A.Q_576P:case A.Q_4320P:return"UNKNOWN";default:return xt(a)}},kt=a=>{if(a!==void 0)switch(a){case"MP4":case"ONDEMAND_DASH":case"ONDEMAND_DASH_LIVE":case"ONDEMAND_HLS":case"ONDEMAND_HLS_LIVE":case"MULTI_DASH":case"WEBM":case"AV1":return"vod";case"DASH":case"HLS":case"HLS_FMP4":case"WEBRTC":return"live";default:return}},N=(a,e,i)=>{if(a&&e)switch(a){case I.MPEG:return i&&e[a]&&e[a][i];default:return e[a]?.url}},ce=(a,e=!1)=>{if(e)return"minimal";switch(a){case void 0:case F.NONE:return;case F.INLINE:return"inline";case F.FULLSCREEN:return"fullscreen";case F.SECOND_SCREEN:return"chromecast";case F.PIP:return"pip_external"}},le=a=>{switch(a){case void 0:return;case F.INVISIBLE:return"background";default:return"foreground"}};var Vi="_thin-one-stat_",Lt=`${Vi}deviceId`,Rt=()=>{let a=new He;return{subscription:a,subscribe:(e,i)=>{e&&a.add(e.subscribe(i))}}},he=class{constructor(e,i){this.debugLogger=new Li;this.thinOneStatDebugLog=this.debugLogger.createComponentLog("ThinOneStat");this.eventNumber=1;this.playerSize={width:0,height:0};this.seekAction$=new Ue("unknown");this.isid$=new Ue(void 0);this.getTotalViewTime=()=>0;this.statContext=e,this.config=mt(i.config??{}),this.subscription=new He,this.config.synchronizeTime&&(this.timeSynchronisation=new de);let t=new Mi,o=$t.get(Lt);this.statContext.deviceId?this.deviceId=this.statContext.deviceId:o?this.deviceId=o:(this.deviceId=Ne(),$t.set(Lt,this.deviceId)),this.statContext.targetDuration?this.targetDuration=this.statContext.targetDuration:this.targetDuration=this.config.watchedNDefaultTargetDuration,this.resetViewSession(),i.useIsid&&this.isid$.next(i.isid??q());let n=new se({error$:t,config:this.config,timeSynchronisation:this.timeSynchronisation});this.api=new oe({config:this.config,apiTransport:n,error$:t,deviceId:this.deviceId,refreshAuthToken:i.refreshAuthToken}),this.logger=new ae({config:this.config,debugLogger:this.debugLogger,api:this.api,error$:t,userSalt:i.userSalt});let{isEmbed:c,topOrigin:h}=Ci();this.isEmbed=c,this.embedHostname=h?new URL(h).hostname:void 0}get vsid$(){return new Ue(D.getVSID())}authorize(e){return this.api.authorize(e)}updateContext(e){this.statContext={...this.statContext,...e}}attachTo(e,i){let t=new He,o=(s,r)=>t.add(s.subscribe(r));o(At(e),s=>{this.getTotalViewTime=s}),o(e.info.isLive$,s=>this.isLive=s);let n;o(ue({hostname:e.info.hostname$,connectionType:e.info.httpConnectionType$,connectionReused:e.info.httpConnectionReused$}).pipe(k(({hostname:s})=>s!==void 0),k(({connectionType:s})=>s!==void 0),k(({connectionReused:s})=>s!==void 0)),({hostname:s,connectionType:r,connectionReused:d})=>{if(n!==void 0&&n!==s){let f={cdn_host:s,connection_type:Be(r),connection_reused:d,content_type:G(e.info.currentFormat$.getValue())};this.logFailover(f)}this.cdnHostname=n=s}),o(e.info.httpConnectionType$,s=>{this.connectionType=Be(s)}),o(e.info.httpConnectionReused$,s=>{this.connectionReused=s}),o(_t(e,i,{heartbeatInterval:this.config.watchCoverageHeartbeatInterval}),s=>{let r=Math.round(s.from*1e3),d=Math.round(s.to*1e3),u={watch_interval:`${r}-${d}`,in_history:!!this.statContext.inHistory,content_type:G(e.info.currentFormat$.getValue()),playback_quality:x(e.info.currentQuality$.getValue()),recom_info:this.statContext.recomInfo};if(!e.info.isLive$.getValue())this.logWatchCoverage(u);else{let m=e.info.atLiveEdge$.getValue();this.logWatchCoverageLive({...u,live:!!m})}}),o(Pt(e,{targetDuration:this.targetDuration,getTotalViewTime:this.getTotalViewTime}),s=>{this.logWatchedN(s)}),o(e.events.willReady$,()=>{if(this.statContext.preload){let s=e.info.currentFormat$.getValue(),r=e.info.availableSources$.getValue(),d=e.info.currentBuffer$.getValue(),u=e.info.currentQuality$.getValue(),f={target_buffer_time:this.calcBufferTime(d),playback_url:N(s,r,u),playback_quality:x(u)};this.logPreloadStarted(f)}}),o(e.events.manifestRequested$,()=>{let s=e.info.currentFormat$.getValue(),r=e.info.availableSources$.getValue(),d=e.info.currentQuality$.getValue(),u={playback_url:N(s,r,d),cdn_host:this.cdnHostname,connection_type:this.connectionType,connection_reused:this.connectionReused};this.logManifestRequest(u)}),o(e.events.firstBytesManifest$,()=>{let s=e.info.currentFormat$.getValue(),r=e.info.availableSources$.getValue(),d=e.info.currentQuality$.getValue(),u={playback_url:N(s,r,d),cdn_host:this.cdnHostname,connection_type:this.connectionType,connection_reused:this.connectionReused};this.logFirstByteManifest(u)}),o(e.events.manifestReceived$,()=>{let s=e.info.currentFormat$.getValue(),r=e.info.availableSources$.getValue(),d=e.info.currentQuality$.getValue(),u={playback_url:N(s,r,d),cdn_host:this.cdnHostname,connection_type:this.connectionType,connection_reused:this.connectionReused};this.logManifestReceived(u)}),o(e.events.firstBytesRequested$,()=>{let s=e.info.currentFormat$.getValue(),r=e.info.availableSources$.getValue(),d=e.info.currentQuality$.getValue(),u={playback_url:N(s,r,d),cdn_host:this.cdnHostname,connection_type:this.connectionType,connection_reused:this.connectionReused};this.logFirstMediaRequest(u)}),o(e.events.firstBytesReceived$,()=>{let s=e.info.currentFormat$.getValue(),r=e.info.availableSources$.getValue(),d=e.info.currentQuality$.getValue(),u={playback_url:N(s,r,d),cdn_host:this.cdnHostname,connection_type:this.connectionType,connection_reused:this.connectionReused};this.logFirstByteMedia(u)}),o(Ct(e.events.willStart$,e.events.looped$),s=>{s&&this.resetViewSession();let d={isid:this.isid$.getValue(),stream_profile:kt(G(e.info.currentFormat$.getValue())),dpi:this.statContext.dpi??96*$.display.pixelRatio,web_layout:this.statContext.isMobile||$.device.isMobile?"mobile":"desktop",preloaded:this.statContext.preload,navigation:this.statContext.navigation,recom_info:this.statContext.recomInfo};this.isEmbed&&(d.iframe_host=this.embedHostname??"unknown"),this.logStartSession(d)}),o(e.events.started$,()=>{this.isStarted=!0;let s=e.info.currentBuffer$.getValue(),r=e.info.currentQuality$.getValue(),d=e.info.isAutoQualityEnabled$.getValue(),u=e.info.muted$.getValue(),f=e.info.volume$.getValue(),m=e.info.surface$.getValue(),v=e.info.availableTextTracks$.getValue(),T=e.info.currentTextTrack$.getValue(),E=e.info.currentAudioStream$.getValue(),S=e.info.currentPlaybackRate$.getValue(),b={playback_quality:x(r),user_quality:d?"auto":x(r),player_width:this.statContext.playerSize?.width??this.playerSize.width,player_height:this.statContext.playerSize?.height??this.playerSize.height,muted:u,sound_volume:Math.round(f*100),buffer_time:this.calcBufferTime(s),mode:ce(m,this.statContext.isPreviewPlayerView),visibility:le(m),subtitles_enabled:T?!!T:this.currentSubtitle?.enabled,auto_subtitles:v.find(({id:_})=>_===T)?.isAuto??this.currentSubtitle?.auto,audio_track_lang:E?.language,playback_rate:S,recom_info:this.statContext.recomInfo};this.logPlaybackStarted(b)}),o(e.events.willStart$,()=>{this.logPlay()}),o(e.events.playing$,()=>{let s=e.info.currentBuffer$.getValue(),r={buffer_time:this.calcBufferTime(s)};this.logPlaying(r),this.wasPaused&&this.logResume()}),o(e.events.paused$,()=>{this.wasPaused=!0,this.logPause()}),o(e.events.willStop$,()=>{this.logStop()}),o(Ct(e.events.fetcherRecoverableError$,e.events.fatalError$),()=>{this.statContext.preload&&this.logPreloadError()});let c=s=>{switch(s){case U.NETWORK:return"network";case U.VIDEO_PIPELINE:return"video_pipeline";case U.EXTERNAL_API:return"external_api";case U.PARSER:return"parser";case U.DOM:return"dom";default:return"wtf"}},h=s=>U.FATAL===s?"critical":"informative";o(e.events.fetcherRecoverableError$,({id:s,category:r,data:d,message:u,httpCode:f,UVBackendErrorCode:m})=>{let v={error_severity:h(r),error_category:c(r),player_error_code:s,player_error_trace:d,http_error_code:f,uv_backend_error_code_subcode:m,error_message:u};this.logError(v),h(r)==="critical"&&this.logCannotPlay()}),o(e.events.managedError$,({id:s,category:r,data:d,message:u})=>{let f={error_severity:h(r),error_category:c(r),player_error_code:s,player_error_trace:d,error_message:u};this.logError(f)}),o(e.events.fatalError$,({id:s,category:r,data:d,message:u})=>{let f={error_severity:"critical",error_category:c(r),player_error_code:s,player_error_trace:d,error_message:u};this.logError(f),this.logCannotPlay()}),o(ue({connectionType:e.info.httpConnectionType$,connectionReused:e.info.httpConnectionReused$,connectionMetrics:e.info.httpConnectionMetrics$}).pipe(k(({connectionReused:s})=>s!==void 0),k(({connectionMetrics:s})=>s!==void 0),Ri((s,r)=>s.connectionType===r.connectionType)),({connectionMetrics:s})=>{let r=e.info.currentFormat$.getValue(),d=e.info.availableSources$.getValue(),u=e.info.currentQuality$.getValue(),f=e.info.rttEstimation$.getValue(),m={playback_url:N(r,d,u),cdn_host:this.cdnHostname,connection_type:this.connectionType,connection_reused:this.connectionReused,rtt:f?Math.round(f):void 0,network_type:this.statContext.networkType??s?.networkType,dns_resolve_time:s?.dnsResolveTime,tcp_handshake_time:s?.tcpHandshakeTime,tls_handshake_time:s?.tlsHandshakeTime};this.logConnectionEstablished(m)}),o(Et(e,{maxTimeWindow:this.config.downloadBytesMaxTime}),s=>{this.logDownloadBytes(s)}),o(e.events.firstFrame$,()=>{this.logFirstVideoFrameDecoded()}),o(e.events.willSeek$,()=>{let s={seek_type:this.seekAction$.getValue()};this.isStarted&&this.logSeeking(s)}),o(e.events.seeked$,()=>{let s={seek_type:this.seekAction$.getValue()};this.isStarted&&this.logSeeked(s),this.seekAction$.next("unknown")}),o(e.info.isStalled$,s=>{let r=e.info.currentBuffer$.getValue(),d=this.calcBufferTime(r);s&&d&&d>0&&this.logBufferStarvation({buffer_time:d})}),o(e.info.currentBuffer$.pipe(k(s=>!!this.calcBufferTime(s)),Di()),s=>{let r=this.calcBufferTime(s);if(this.statContext.preload){let d={buffer_time:r};this.logPreloadEnded(d)}this.logReady({buffer_time:r})});let l;o(ue({videoStream:e.info.currentVideoStream$,audioStream:e.info.currentAudioStream$,quality:e.info.currentQuality$}).pipe(k(({videoStream:s,audioStream:r})=>s!==void 0&&r!==void 0),k(({quality:s})=>s!==void 0)),({videoStream:s,audioStream:r,quality:d})=>{if(l!==d){let u=e.info.isAutoQualityEnabled$.getValue(),f=s?.codec,m=r?.codec,v={user_quality:u?"auto":x(d),playback_quality:x(l),download_quality:x(d),codec_info:f&&m?`${f},${m}`:void 0};l=d,this.logQualityChanged(v)}});let p,g;return o(e.info.surface$,s=>{let r=ce(s,this.statContext.isPreviewPlayerView);r&&!this.uiEvents&&this.isStarted&&this.logModeChanged({mode:r}),g=le(s),p!==g&&this.isStarted&&(p=le(s),this.logVisibilityChanged({visibility:g}))}),o(ue({muted:e.info.muted$,volume:e.info.volume$}),({muted:s,volume:r})=>{if(this.isStarted){let d={muted:s,sound_volume:Math.round(r*100)};this.logSoundChanged(d)}}),o(e.info.currentFormat$.pipe(k(s=>s!==void 0),Fe(1)),s=>{let r={content_type:G(s),cdn_host:this.cdnHostname,connection_type:this.connectionType,connection_reused:this.connectionReused};this.logContentTypeChange(r)}),o(e.info.currentAudioStream$.pipe(k(s=>s!==void 0),Fe(1)),s=>{let r={audio_track_lang:s.language,codec_info:s.codec};this.logAudioTrackSwitched(r)}),o(e.info.currentVideoStream$.pipe(k(s=>s!==void 0),Fe(1)),s=>{let r={hdr:s.hdr,codec_info:s.codec};this.logVideoTrackSwitched(r)}),this.player=e,this.resubscribeBeforeunload(),this.subscription.add(t),t}attachToUi(e){this.uiEvents=e;let{subscribe:i,subscription:t}=Rt();i(e.actionSeek$,this.seekAction$),i(e.playerSize$,({width:n,height:c})=>{n&&c&&(this.playerSize={width:n,height:c},this.isStarted&&this.logViewPortChanged({player_width:n,player_height:c}))}),i(e.isLoaderVisible$,n=>{n&&this.isStarted&&this.logShowLoader()}),i(e.actionSubtitlesSwitched$,n=>{if(this.currentSubtitle={...n},this.isStarted){let c={subtitles_enabled:n.enabled,subtitles_track_lang:n.lang,auto_subtitles:n.auto};this.logSubtitlesSwitched(c)}});let{surface$:o}=ee(this.uiEvents,i,this.player);return i(o,n=>{this.isStarted&&this.logModeChanged({mode:ce(n)})}),i(e.actionQuality$,n=>{let c=g=>Object.values($e).includes(g),h=this.player?.info.currentVideoStream$.getValue()?.codec,l=this.player?.info.currentAudioStream$.getValue()?.codec,p={user_quality:c(n)?"auto":x(n),playback_quality:x(this.player?.info.currentQuality$.getValue()),download_quality:x(this.player?.info.currentQuality$.getValue()),codec_info:h&&l?`${h},${l}`:void 0};this.logQualityChangeRequested(p)}),this.resubscribeBeforeunload(),this.subscription.add(t),t}attachToAds(e){let{subscription:i,subscribe:t}=Rt();return t(e.init$,o=>{let n={slot:o};this.logAdvConfiguration(n)}),t(e.slotRequested$,()=>{this.logAdvRequest()}),t(e.started$,o=>{let n={adv_section:o};this.logAdvBreakStarted(n)}),t(e.ended$,o=>{let n={adv_section:o};this.logAdvBreakEnded(n)}),t(e.error$,o=>{let n={error_message:o};this.logAdvError(n)}),this.resubscribeBeforeunload(),this.subscription.add(i),i}getDeviceId(){return this.deviceId}resetViewSession(){this.thinOneStatDebugLog({message:"VSID reset"}),D.generateVSID(this.config.useVsid64),this.eventNumber=0}destroy(){this.api.destroy()}calcBufferTime(e){return e?Math.round((e.end??0)-(e.start??0))*1e3:void 0}createRequiredParams(e){let i=this.vsid$.getValue();ki(i);let t=this.eventNumber++,o=((this.isLive?this.player?.info.liveTime$.getValue():this.player?.info.position$.getValue())??0)*1e3,n={vsid:i,uv_movie_id:this.statContext.movieId,event_name:e,client_time:Date.now(),application:this.statContext.application??`@vkontakte/videoplayer-statistics:${P}`,platform:this.statContext.platform??`web:${this.statContext.isMobile||$.device.isMobile?"mobile":"desktop"}`,product:this.statContext.product,event_number:t,playback_position:o,current_tvt:this.getTotalViewTime(),cdn_host:this.cdnHostname};for(let c of this.config.disabledParams)delete n[c];return n}createRequiredFatParams(){let e={stats_version:"2.1.1",browser:this.statContext.browser??$.browser.current,browser_version:this.statContext.browserVersion??String($.browser.currentVersion),os:this.statContext.os??$.device.os.name,os_version:this.statContext.osVersion??$.device.os.version,device_type:this.statContext.deviceType??(this.statContext.isMobile||$.device.isMobile?"mobile":"desktop"),device_manufacturer:this.statContext.deviceManufacturer??$.device.details.vendor,device_model:this.statContext.deviceModel??$.device.details.model,navigation:this.statContext.navigation};for(let i of this.config.disabledParams)delete e[i];return e}log(e,i,t=!1){if(this.config.disabledEvents.includes(e))return;let o=this.createRequiredParams(e),n={};t&&(n=this.createRequiredFatParams()),this.logger.log({...o,...n,...i})}logWatchCoverage(e){this.log("watch_coverage",e,!0)}logWatchCoverageLive(e){this.log("watch_coverage_live",e,!0)}logWatchedN(e){this.log("watched_n",e,!0)}logStartSession(e){this.log("start_session",e,!0)}logPreloadStarted(e){this.log("preload_started",e)}logPreloadEnded(e){this.log("preload_ended",e)}logPreloadError(){this.log("preload_error")}logPlaybackStarted(e){this.log("playback_started",e,!0)}logPlay(){this.log("play")}logManifestRequest(e){this.log("manifest_request",e)}logFirstByteManifest(e){this.log("first_byte_manifest",e)}logFirstMediaRequest(e){this.log("first_media_request",e)}logFirstByteMedia(e){this.log("first_byte_media",e)}logManifestReceived(e){this.log("manifest_received",e)}logConnectionEstablished(e){this.log("connection_established",e)}logFirstVideoFrameDecoded(){this.log("first_video_frame_decoded")}logReady(e){this.log("ready",e)}logPlaying(e){this.log("playing",e)}logPause(){this.log("pause")}logResume(){this.log("resume")}logSeeking(e){this.log("seeking",e)}logSeeked(e){this.log("seeked",e)}logStop(){this.log("stop")}logBufferStarvation(e){this.log("buffer_starvation",e)}logShowLoader(){this.log("show_loader")}logQualityChangeRequested(e){this.log("quality_change_requested",e)}logQualityChanged(e){this.log("quality_changed",e)}logCdnHostChanged(e){this.log("cdn_host_changed",e)}logViewPortChanged(e){this.log("view_port_changed",e)}logModeChanged(e){this.log("mode_changed",e)}logVisibilityChanged(e){this.log("visibility_changed",e)}logAudioTrackSwitched(e){this.log("audio_track_switched",e)}logVideoTrackSwitched(e){this.log("video_track_switched",e)}logSubtitlesSwitched(e){this.log("subtitles_switched",e)}logSoundChanged(e){this.log("sound_changed",e)}logFailover(e){this.log("failover",e)}logContentTypeChange(e){this.log("content_type_change",e)}logError(e){this.log("error",e,!0)}logCannotPlay(){this.log("cannot_play",{},!0)}logDownloadBytes(e){this.log("download_bytes",e)}logAdvConfiguration(e){this.log("adv_configuration",e)}logAdvRequest(){this.log("adv_request")}logAdvBreakStarted(e){this.log("adv_break_started",e)}logAdvBreakEnded(e){this.log("adv_break_ended",e)}logAdvError(e){this.log("adv_error",e)}resubscribeBeforeunload(){this.beforeunloadSubscription?.unsubscribe(),this.beforeunloadSubscription=$i(Ni(),"beforeunload").subscribe(()=>{}),this.subscription.add(this.beforeunloadSubscription)}};var Oi={};import{PlaybackState as Mt,Subscription as Bi}from"@vkontakte/videoplayer-core/evergreen";import{Logger as Fi}from"@vkontakte/videoplayer-shared/evergreen";var pe=class{constructor(){this.startTime=null;this.stopTime=null;this.accumulatedTime=0}get time(){return Math.floor(this.timeMs/1e3)}get timeMs(){return this.startTime===null?0:(this.stopTime??this.now())-this.startTime-this.accumulatedTime}get isRunning(){return this.startTime!==null&&this.stopTime===null}start(){this.isRunning||(this.stopTime!==null?(this.accumulatedTime+=this.now()-this.stopTime,this.stopTime=null):this.startTime=this.now())}stop(){this.isRunning&&(this.stopTime=this.now())}reset(){this.startTime=null,this.stopTime=null,this.accumulatedTime=0}now(){return Date.now()}};var Nt=()=>window.Image?new Image:document.createElement("img");var qe=class{constructor(e){this.position=0;this.started=!1;this.heartbeatPixels=[];this.heartbeatLastTimeSent={};this.idleCallbackIds=[];this.stopwatch=new pe;this.subscription=new Bi;this.params=e;let i=new Fi;this.log=i.createComponentLog("MediascopePixel")}attachTo(e){this.subscription.add(e.info.playbackState$.subscribe(i=>this.onPlaybackState(i))).add(e.info.position$.subscribe(i=>this.onPosition(i))).add(e.info.atLiveEdge$.subscribe(i=>this.isActiveLive=i)),this.subscription.add(e.events.willSeek$.subscribe(()=>this.onWillSeek())).add(e.events.seeked$.subscribe(()=>this.onSeeked())).add(e.events.ended$.subscribe(()=>this.onEnded()))}destroy(){this.stopwatch.reset(),this.subscription.unsubscribe(),window.clearTimeout(this.heartbeatFirstTimeoutId),this.idleCallbackIds.forEach(e=>window.cancelIdleCallback(e)),this.send("stop")}onPlaybackState(e){e===Mt.PLAYING?this.started?this.play():this.start():e===Mt.PAUSED&&this.pause()}start(){this.started=!0,this.stopwatch.start(),this.send("start"),this.heartbeatPixels=this.prepareHeartbeatPixels(),this.heartbeatInterval=this.heartbeatPixels[0]?.interval;let e=this.heartbeatPixels[0]?.url,i=this.heartbeatPixels[0]?.delay;if(i!==void 0&&e)try{this.heartbeatFirstTimeoutId=window.setTimeout(()=>{this.sendHeartbeat(e)},i*1e3)}catch(t){this.log({message:t.message})}}play(){this.stopwatch.start(),this.send("resume")}pause(){this.stopwatch.stop(),this.send("pause")}onPosition(e){if(this.position=e,this.heartbeatInterval&&this.stopwatch.time!==0&&this.stopwatch.time%this.heartbeatInterval===0)for(let[i,{url:t}]of this.heartbeatPixels.entries())this.heartbeatLastTimeSent[i]!==this.stopwatch.time&&(this.heartbeatLastTimeSent[i]=this.stopwatch.time,this.sendHeartbeat(t))}onWillSeek(){this.started&&this.send("stop")}onSeeked(){this.started&&this.send("start")}onEnded(){this.stopwatch.stop(),this.send("stop")}validatePixels(e,i){return e?.filter(t=>t.event===i.event&&i.keys.every(o=>!!t[o]))}getFrameTimestamp(){let e;if(this.isActiveLive){let i=Math.floor(Math.random()*25)+5;e=Date.now()/1e3-i}else e=this.position||0;return Math.floor(e)}getUTC(){return Math.floor(Date.now()/1e3)}prepareUrl(e){return e.replace("{@fts_fake_sec}",String(this.getFrameTimestamp())).replace("{@utc_sec}",String(this.getUTC())).split("&").filter(i=>!/={@[a-zA-Z_]+}/.test(i)).join("&")}preparePixels(e){return this.validatePixels(this.params.pixels,{event:e,keys:["url"]})}prepareHeartbeatPixels(){return this.validatePixels(this.params.pixels,{event:"heartbeat",keys:["url","interval"]})}call(e){try{this.idleCallbackIds.push(requestIdleCallback(()=>Nt().src=this.prepareUrl(e)))}catch(i){this.log({message:i.message})}}send(e){let i=this.preparePixels(e);for(let{url:t}of i)this.call(t)}sendHeartbeat(e){this.call(e)}};export{H as ApiEnv,be as ConnectionType,me as ContentType,Ke as InteractiveInterfaceClick,qe as MediascopePixel,Oi as MediascopePixelTypes,Ce as OneStat,ge as Quality,ve as SeekAction,Dt as ThinOneStat,P as VERSION};
6
+ var Ot=Object.defineProperty;var Bt=(a,e)=>{for(var i in e)Ot(a,i,{get:e[i],enumerable:!0})};var H=(c=>(c.PROD="prod",c.VK_ALIAS="vk_alias",c.VIDEOTEST="videotest",c.TEST="test",c.OKCDN="okcdn",c.AUTO="auto",c))(H||{}),ge=(p=>(p.Q144P="mobile",p.Q240P="lowest",p.Q360P="low",p.Q480P="medium",p.Q720P="high",p.Q1080P="fullhd",p.Q1440P="quadhd",p.Q2160P="ultrahd",p.UNKNOWN="unknown",p))(ge||{}),me=(u=>(u.MP4="mp4",u.DASH="dash",u.DASH_SEP="dash_sep",u.ONDEMAND_DASH="ondemand_dash",u.HLS="hls",u.HLS_FMP4="hls_fmp4",u.ONDEMAND_HLS="ondemand_hls",u.WEBM="webm",u.AV1="av1",u.ONDEMAND_DASH_LIVE="ondemand_dash_live",u.ONDEMAND_HLS_LIVE="ondemand_hls_live",u.WEBRTC="webrtc",u.UNKNOWN="unknown",u.RTMP="rtmp",u))(me||{});var ve=(t=>(t.HTTP1="http1",t.HTTP2="http2",t.HTTP3="http3",t))(ve||{});var be=(l=>(l.SLIDER="slider",l.RICH="rich",l.DOUBLE_TAP="double_tap",l.TIME_CODE="time_code",l.EPISODE="episode",l.REWIND="rewind",l.LIVE="live",l.UNKNOWN="unknown",l))(be||{}),Ke=(n=>(n.GRAPH_SHOW="iGraphShow",n.GRAPH_HIDE="iGraphHide",n.NEXT_AREA="iNextChapterArea",n.NEXT_BUTTON="iNextChapterBtn",n.WATCH_AGAIN="iWatchAgainBtn",n))(Ke||{}),ze={action_play:"ap",action_play_interactive:"api",first_bytes:"fb",player_ready:"pr",first_frame:"ff",seek:"sk",watch_coverage_record:"wr",watch_coverage_live:"wl",empty_buffer:"eb",action_stop:"as",close_at_empty_buffer:"cb",content_error:"er",player_interface_click:"pc",next_movie:"nm",track_switch:"ts",failover:"fo",quality:"qt"},je={vsid:"si",isid:"is",vid:"vi",place:"pl",quality:"qt",cdn_host:"ch",stat_type:"st",param:"pm",vk_app_id:"va",track_code:"tc",connection_type:"cnt",connection_reused:"cr",cached_data:"cd",live:"lv",muted:"mu",mode:"mo",subtitles:"sb",failover:"fo",download_speed:"ds",manual_quality:"mq",ref_domain:"rd",direct_url:"du"},Ge={unknown:"un",mobile:"m",lowest:"ls",low:"l",medium:"md",high:"h",fullhd:"f",quadhd:"q",ultrahd:"u"},Ye={pip:"pi",fullscreen:"fs",external:"ex",prefetch:"pr",airplay:"ap",chromecast:"cc",invisible:"iv",minimal:"minimal"};import{fillWithDefault as Ft}from"@vkontakte/videoplayer-shared/evergreen";var Xe="CIOPGQJGDIHBABABA",Ie={prod:"https://api.ok.ru",vk_alias:"https://api.mycdn.me",videotest:"https://videotestapi.ok.ru/api",test:"https://apitest.ok.ru",okcdn:"https://api.okcdn.ru",auto:""};var Ut={apiEnv:"vk_alias",apiKey:Xe,apiBaseUrl:null,requestRetryCount:1,useVsid64:!1,firstFlushTime:5e3,flushDebounceTime:1e4,flushMaxWait:6e4,storageExpiration:36*60*60*1e3,watchCoverageInterval:15e3,disabledOperations:["quality"],disabledCustomFields:[],shorten:!0,maxLoops:100,embedUrlParams:[],useBeacon:!0,synchronizeTime:!0,debugLog:!1,clearStorageAtUnload:!0,useVKComIsMobileLogic:!1,backoff:{start:1e3,factor:1.5,max:5*60*1e3,random:.1},useKeepalive:!1,watchCoverageTimeoutFix:!1},Je=a=>Ft(a,Ut);function ye(){let a="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".split(""),e=new Array(36),i=0,t,o;for(o=0;o<36;o++)o===8||o===13||o===18||o===23?e[o]="-":o===14?e[o]="4":(i<=2&&(i=33554432+Math.random()*16777216|0),t=i&15,i=i>>4,e[o]=a[o===19?t&3|8:t]);return e.join("")}import{assertNonNullable as oi,combine as ct,fromEvent as lt,isNonNullable as O,isNullable as ut,merge as ri,now as R,observableFrom as si,once as ni,safeStorage as ht,Subject as ai,Subscription as ke,ValueSubject as te}from"@vkontakte/videoplayer-shared/evergreen";import{Logger as di,detectEmbed as ci}from"@vkontakte/videoplayer-shared/evergreen";var Ht=()=>Math.floor(Math.random()*4294967296).toString(36).padStart(13,"0"),q=()=>Math.floor(Math.random()*18446744073709552e3).toString(36).padStart(13,"0"),D=class a{static getVSID(){return a.vsid}static generateVSID(e){return a.vsid=e?q():Ht(),a.vsid}};var Ze=a=>{let{operation:e,custom:i}=a,t=Object.fromEntries(Object.entries(i).map(([o,n])=>{let c=je[o]??o,h=n;return n&&(o==="mode"?h=Ye[n]??n:o==="quality"&&(h=Ge[n]??n)),[c,h]}));return{...a,operation:ze[e]??e,custom:t}};var P="1.0.98-dev.10e34fe1.0";import{ValueSubject as qt,getExponentialDelay as Wt,ErrorCategory as M}from"@vkontakte/videoplayer-shared/evergreen";var Qt=/Mobile|mini|Fennec|Android|iP(ad|od|hone)|opera (mini|mobi)/i,W=class{constructor(e){this.consequentAuthErrors=0;this.authorized$=new qt(!1);this.params=e}async authorize(e){return this.authToken=e??await this.refreshAuthToken(),this._authorizeWithBackoff()}logBeacon(e){let i="log.externalLog",t=this.createLogParams(e),o=this.sessionKey;if(!o)return;this.params.apiTransport.sendBeacon(i,t,o)||this.logRequest(e).catch(()=>{})}async logRequest(e){let i="log.externalLog",t=this.createLogParams(e),o=this.sessionKey??await this._authorizeWithBackoff();if(!o)return;let n=async(c,h=this.params.config.requestRetryCount)=>{try{return await this.params.apiTransport.sendRequest(i,t,o)}catch(l){if(!l||!("error_code"in l)){this.params.error$.next({id:"logRequestUnknown",category:M.NETWORK,message:`Unknown ${i} error`,thrown:l});return}let p=l?.error_code;switch(p){case 102:case 103:case 104:return this.authorized$.next(!1),this.sessionKey=await this._authorizeWithBackoff(),h>0?n(c,h-1):void 0;case 401:return this.authorized$.next(!1),this.authToken=await this.refreshAuthToken(),this.sessionKey=await this._authorizeWithBackoff(),h>0?n(c,h-1):void 0;default:{this.params.error$.next({id:`LogRequest#${p}`,category:M.EXTERNAL_API,message:`${i} error`,data:l});return}}}};return n(e)}destroy(){window.clearTimeout(this.backoffTimeoutId),this.backoffTimeoutId=0}async refreshAuthToken(){if(this.params.refreshAuthToken)return this.refreshAuthTokenPromise||(this.refreshAuthTokenPromise=this.params.refreshAuthToken().finally(()=>{this.refreshAuthTokenPromise=void 0})),this.refreshAuthTokenPromise}createLogParams(e){let i="WEB",t=!1,o=`@vkontakte/videoplayer-statistics:${P}`;if(this.params.config.useVKComIsMobileLogic){let{appVersion:n}=window.navigator;t=Qt.test(n)}else this.params.mobile&&(t=!0);return t&&(i="M_WEB"),this.params.vktvVersion&&(i="SMART_TV",o=this.params.vktvVersion),{collector:"ok.mobile.apps.video",data:JSON.stringify({application:o,platform:i,items:this.params.config.shorten?e.map(Ze):e})}}_authorizeWithBackoff(){if(!this.consequentAuthErrors)return this._authorize();let e=Wt(this.consequentAuthErrors,this.params.config.backoff);return new Promise(i=>{this.backoffTimeoutId||(this.backoffTimeoutId=window.setTimeout(()=>{this._authorize().then(i).catch(t=>this.params.error$.next({id:"AuthorizeBackoff",category:M.NETWORK,message:"Otherwise unhandled error in authorization",thrown:t})).finally(()=>this.backoffTimeoutId=0)},e))})}async _authorize(){if(this.authorizePromise)return this.authorizePromise;this.sessionKey=void 0,this.authorized$.next(!1);let e="auth.anonymLogin",i={session_data:{version:2,device_id:this.params.deviceId,client_version:P.split("-")[0],client_type:"SDK_JS"}};return this.authToken!==void 0&&(i.session_data.auth_token=this.authToken,i.session_data.version=3),this.authorizePromise=this.params.apiTransport.sendRequest(e,i).then(t=>((!t||!t.session_key)&&this.params.error$.next({id:"AuthorizeFailed",category:M.EXTERNAL_API,message:"No session key",data:t}),this.sessionKey=t?.session_key??void 0,this.sessionKey)).catch(async t=>{this.sessionKey=void 0;let o=t?.error_code;switch(o){case 401:return this.authToken=await this.refreshAuthToken(),this._authorizeWithBackoff()}o?this.params.error$.next({id:`Authorize#${o}`,category:M.EXTERNAL_API,message:"authorize error",data:t}):this.params.error$.next({id:"AuthorizeUnknown",category:M.NETWORK,message:"authorize error",thrown:t})}).finally(()=>{this.authorizePromise=void 0,this.consequentAuthErrors=this.sessionKey?0:this.consequentAuthErrors+1,this.authorized$.next(this.sessionKey!==void 0)}),this.authorizePromise}};import{ErrorCategory as Y,now as Se}from"@vkontakte/videoplayer-shared/evergreen";var Q=class{constructor(e){this.params=e,this.apiKey=e.config.apiKey,this.apiEnv=e.config.apiEnv,this.apiBaseUrl=e.config.apiBaseUrl??Ie[this.apiEnv],this.timeSynchronisation=e.timeSynchronisation,this.isApiBaseUrlFetched=!1}async resolveApiBaseUrl(){if(this.apiEnv!=="auto"||this.isApiBaseUrlFetched)return this.apiBaseUrl;try{let e=atob("aHR0cHM6Ly9kbnMuZ29vZ2xlL3Jlc29sdmU/bmFtZT12aWRlby5fZW5kcG9pbnQub2sucnUmdHlwZT1UWFQ="),o=(await(await fetch(e,{method:"GET",mode:"cors",cache:"no-cache"})).json())?.Answer[0]?.data;if(!o)throw new Error("Wrong DNS response");return o}catch(e){return this.params.error$.next({id:"OneStat:ApiTransport:resolveApiBaseUrl",category:Y.NETWORK,message:"Unhandled resolve api base url error",thrown:e}),Ie.vk_alias}finally{this.isApiBaseUrlFetched=!0}}sendBeacon(e,i,t){if(!window.Blob||!window.navigator.sendBeacon)return!1;let o=this._prepareQueryParams({method:e,queryParams:i,sessionKey:t}),n=new window.Blob([o.toString()],{type:"application/x-www-form-urlencoded"});try{return window.navigator.sendBeacon(`${this.apiBaseUrl}/fb.do`,n)}catch(c){this.params.error$.next({id:"OneStat:ApiTransport:sendBeacon",category:Y.NETWORK,message:"Unhandled beacon error",thrown:c,data:{method:e,params:i}})}return!1}async sendRequest(e,i,t){let o=Se(),n=h=>{if(h instanceof TypeError&&["Failed to fetch","NetworkError when attempting to fetch resource."].includes(h.message)){this.params.error$.next({id:"Network",category:Y.NETWORK,message:"Request failed",thrown:h});return}this.params.error$.next({id:"OneStat:ApiTransport:sendRequest",category:Y.NETWORK,message:"Unhandled request error",thrown:h,data:{method:e,params:i,sessionKey:t,time:Se()-o}})};this.apiBaseUrl=await this.resolveApiBaseUrl();let c={method:"post",headers:{"Content-type":"application/x-www-form-urlencoded"},body:this._prepareQueryParams({method:e,queryParams:i,sessionKey:t})};return this.params.config.useKeepalive&&(c.keepalive=!0),fetch(`${this.apiBaseUrl}/fb.do`,c).then(h=>{let l=Number(h.headers.get("content-length"))===0,p=new Date(h.headers.get("date")??"").getTime(),g=Se()-o;if(isFinite(p)&&this.timeSynchronisation?.addServerTime(p,g),!l)return h.json().then(s=>Object.prototype.hasOwnProperty.call(s,"error_msg")?Promise.reject(s):s,n)},n)}_prepareQueryParams(e){let i=new URLSearchParams({format:"JSON",method:e.method,application_key:this.apiKey});return e.sessionKey!==void 0&&i.append("session_key",e.sessionKey),Object.entries(e.queryParams).forEach(([t,o])=>i.append(t,typeof o=="string"?o:JSON.stringify(o))),i}};import{ErrorCategory as Kt,now as zt,safeStorage as K,debounceFn as et}from"@vkontakte/videoplayer-shared/evergreen";var X="onestat_events",_e=a=>e=>e.timestamp+a>=zt(),J=class{constructor(e){this.unsaltedStorage=[];this.isPaused=!1;this.isUrgent=e=>{let{operation:i}=e;return["action_play","watch_coverage_record","watch_coverage_live"].includes(i)};this.params=e,this.api=e.api,this.error$=e.error$,this.userSalt=e.userSalt,this.loggerDebugLog=e.debugLogger.createComponentLog("stat logger"),this.firstFlush=et(()=>this.safeFlush(),this.params.config.firstFlushTime,{maxWait:this.params.config.firstFlushTime});let i=K.isPersistent()?this.params.config.flushMaxWait:0;this.debouncedFlush=et(()=>this.safeFlush(),this.params.config.flushDebounceTime,{maxWait:i}),this.subscription=this.api.authorized$.subscribe(t=>{t&&this.debouncedFlush()}),this.housekeepStorage()}safeFlush(){try{this.flush()}catch(e){this.error$.next({id:"LoggerError",category:Kt.WTF,message:e?String(e):"Unknown logger error",thrown:e})}}readFromStorage(){let e=K.get(X);try{return e?JSON.parse(e):{}}catch{}return{}}addToStorage(e){if(!this.userSalt){this.unsaltedStorage.push(e);return}let i=this.readFromStorage(),o=(i[this.userSalt]??[]).filter(_e(this.params.config.storageExpiration));K.set(X,JSON.stringify({...i,[this.userSalt]:[...o,e]}))}getFromStorage(){return this.userSalt?(this.readFromStorage()[this.userSalt]??[]).filter(_e(this.params.config.storageExpiration)):this.unsaltedStorage}markStorageSent(){if(!this.userSalt){this.unsaltedStorage=[];return}let e=this.readFromStorage();delete e[this.userSalt],K.set(X,JSON.stringify(e))}housekeepStorage(){let e=this.readFromStorage();for(let[i,t]of Object.entries(e)){let o=t.filter(_e(this.params.config.storageExpiration));o.length?e[i]=o:delete e[i],this.loggerDebugLog({message:`${t.length} retrieved from storage, ${o.length} of them actual`})}K.set(X,JSON.stringify(e))}log(e){this.addToStorage(e),!this.isPaused&&(this.isUrgent(e)?this.flush():this.lastVsid!==e.custom.vsid?this.firstFlush():this.debouncedFlush(),this.lastVsid=e.custom.vsid)}flush({wantBeacon:e,clearStorage:i}={wantBeacon:!1,clearStorage:!0}){let t=this.getFromStorage();t.length!==0&&(this.api.authorized$.getValue()?(e&&this.params.config.useBeacon?(this.loggerDebugLog({message:`Flushing ${t.length} events through beacon`}),this.api.logBeacon(t)):(this.loggerDebugLog({message:`Flushing ${t.length} events`}),this.api.logRequest(t)),i&&this.markStorageSent()):this.api.authorize(),this.firstFlush.cancel(),this.debouncedFlush.cancel())}pause(){this.isPaused=!0,this.debouncedFlush.cancel()}resume(){this.isPaused=!1,this.debouncedFlush()}destroy(){this.subscription.unsubscribe(),this.firstFlush.cancel(),this.debouncedFlush.cancel()}};import{HttpConnectionType as Pe,Surface as V,VideoFormat as y,VideoQuality as w}from"@vkontakte/videoplayer-core/evergreen";import{assertNever as tt}from"@vkontakte/videoplayer-shared/evergreen";var it=a=>a&&{[w.INVARIANT]:"unknown",[w.Q_144P]:"mobile",[w.Q_240P]:"lowest",[w.Q_360P]:"low",[w.Q_480P]:"medium",[w.Q_576P]:"unknown",[w.Q_720P]:"high",[w.Q_1080P]:"fullhd",[w.Q_1440P]:"quadhd",[w.Q_2160P]:"ultrahd",[w.Q_4320P]:"unknown"}[a],Te=a=>a&&{[Pe.HTTP1]:"http1",[Pe.HTTP2]:"http2",[Pe.QUIC]:"http3"}[a],ot=a=>{if(a!==void 0)switch(a){case y.MPEG:return"mp4";case y.DASH:case y.DASH_LIVE:case y.DASH_STREAMS:return"dash";case y.DASH_SEP:return"dash_sep";case y.DASH_ONDEMAND:return"ondemand_dash";case y.DASH_WEBM:case y.DASH_LIVE_WEBM:return"webm";case y.DASH_WEBM_AV1:return"av1";case y.DASH_LIVE_CMAF:return"ondemand_dash_live";case y.HLS:case y.HLS_LIVE:return"hls";case y.HLS_FMP4:return"hls_fmp4";case y.HLS_ONDEMAND:return"ondemand_hls";case y.HLS_LIVE_CMAF:return"ondemand_hls_live";case y.WEB_RTC_LIVE:return"webrtc";default:return tt(a)}},Ee=(a,e)=>{if(e)return"minimal";switch(a){case void 0:case V.NONE:case V.INLINE:return;case V.FULLSCREEN:return"fullscreen";case V.SECOND_SCREEN:return"chromecast";case V.PIP:return"pip";case V.INVISIBLE:return"invisible";default:return tt(a)}},rt=a=>{switch(a){case"slow-2g":return"poor";case"2g":return"poor";case"3g":return"good";case"4g":return"excellent"}};var Z=class{constructor(e){this.offset=void 0;this.offset=e}getOffset(){return this.offset??0}setOffset(e){this.offset=e}now(){return Date.now()+(this.offset??0)}date(e=new Date){return e.setTime(e.getTime()+(this.offset??0)),e}addServerTime(e,i){let t=Date.now(),o=e-t-i/2;if(Math.abs(o)<1e3){this.offset=0;return}this.offset===void 0?this.offset=Math.round(o):this.offset=Math.round(.2*o+(1-.2)*this.offset)}};import{PlaybackState as st}from"@vkontakte/videoplayer-core/evergreen";import{filter as nt,filterChanged as jt,fromEvent as Gt,isNullable as at,map as Yt,merge as we,Observable as Xt,Subject as Ae,Subscription as Jt,ValueSubject as Zt}from"@vkontakte/videoplayer-shared/evergreen";var dt=(a,e)=>new Xt(i=>{let t=new Jt,o=we(Gt(window,"beforeunload"),a.events.willDestruct$),n=new Zt(void 0),c;t.add(a.info.isLive$.pipe(jt()).subscribe(v=>{c&&(c.unsubscribe(),n.next(void 0)),v?c=a.info.liveTime$.pipe(Yt(_=>_&&_/1e3)).subscribe(n):c=a.info.position$.subscribe(n),t.add(c)}));let{playing$:h,paused$:l}=a.events,p=a.events.willSeek$.pipe(nt(()=>a.info.playbackState$.getValue()===st.PLAYING)),g=a.events.seeked$.pipe(nt(()=>a.info.playbackState$.getValue()===st.PLAYING)),s=!1,r=new Ae;t.add(p.subscribe(()=>{s||r.next(),s=!0})),t.add(g.subscribe(()=>s=!1));let d=new Ae,u=new Ae,f=we(h,g,d),m=we(l,r,o,a.events.looped$,u),b,T=()=>b=n.getValue(),E=()=>{let v=n.getValue();at(b)||b===v||at(v)||(i.next({from:b,to:v}),b=void 0)},S=()=>{u.next(),d.next()};if(t.add(f.subscribe(T)),t.add(m.subscribe(E)),e.forceInterval&&isFinite(e.forceInterval))if(e.watchCoverageTimeoutFix){let v,_=()=>{v!==void 0&&(window.clearTimeout(v),v=void 0)};t.add(f.subscribe(()=>{_(),v=window.setTimeout(S,e.forceInterval)})),t.add(m.subscribe(()=>_())),t.add(()=>_())}else{let v=0;t.add(f.subscribe(()=>v=window.setTimeout(S,e.forceInterval))),t.add(m.subscribe(()=>window.clearTimeout(v)))}return t});import{Surface as C}from"@vkontakte/videoplayer-core/evergreen";import{debounce as ei,filterChanged as ti,Subject as ii}from"@vkontakte/videoplayer-shared/evergreen";var ee=(a,e,i)=>{let t=new ii,o=t.pipe(ei(0),ti()),n=!1,c=!1,h=!1;return e(a.inPiP$,l=>{n=l,t.next(l?C.PIP:c?C.FULLSCREEN:h?C.INLINE:void 0)}),e(a.inFullscreen$,l=>{c=l,t.next(l?C.FULLSCREEN:n?C.PIP:h?C.INLINE:void 0)}),i&&e(i.info.surface$,l=>{switch(l){case C.SECOND_SCREEN:case C.NONE:case C.INLINE:{!c&&!n&&(l===C.INLINE&&(h=!0),t.next(l));break}}}),{surface$:o}};var li="_one-stat_",pt=`${li}deviceId`,xe=()=>{let a=new ke;return{subscription:a,subscribe:(e,i)=>{e&&a.add(e.subscribe(i))}}},Ce=class{constructor(e,i){this.subscription=new ke;this.debugLogger=new di;this.oneStatDebugLog=this.debugLogger.createComponentLog("onestat");this.loopCounter=0;this.disabled=!1;this.isid$=new te(void 0);this.zenUid$=new te(void 0);this.seekAction$=new te("unknown");this.statContext=e,this.config=Je(i.config??{}),O(i.apiEnv)&&(this.config.apiEnv=i.apiEnv),this.config.synchronizeTime&&(this.timeSynchronisation=new Z);let t=new ai;this.experimental={error$:t};let o=ht.get(pt);this.statContext.deviceId?this.deviceId=this.statContext.deviceId:o?this.deviceId=o:(this.deviceId=ye(),ht.set(pt,this.deviceId)),this.resetViewSession(),i.useIsid&&this.isid$.next(i.isid??q()),this.zenUid$.next(i.zenUid);let n=new Q({config:this.config,error$:t,timeSynchronisation:this.timeSynchronisation});this.api=new W({config:this.config,apiTransport:n,refreshAuthToken:i.refreshAuthToken,mobile:this.statContext.mobile??!1,deviceId:this.deviceId,error$:t,vktvVersion:i.vktvVersion}),this.logger=new J({config:this.config,debugLogger:this.debugLogger,api:this.api,error$:t,userSalt:i.userSalt});let{isEmbed:c,topOrigin:h}=ci();this.isEmbed=c,this.embedParent=h?new URL(h).hostname:void 0,this.subscribe()}get vsid$(){return new te(D.getVSID())}updateContext(e){this.statContext={...this.statContext,...e}}attachTo(e){let i=new ke,t=(r,d)=>i.add(r.subscribe(d));t(e.events.willStart$,()=>{let r=e.info.position$.getValue();this.logActionPlay({position:r}),this.statContext.projectId&&this.logActionPlayInteractive()}),t(e.events.looped$,()=>{this.resetViewSession(),++this.loopCounter>this.config.maxLoops&&(this.disabled=!0),this.logActionPlay({position:e.info.position$.getValue()})}),t(e.events.seeked$,()=>{let r=this.seekAction$.getValue();this.logSeek({action:r==="rich"?"slider":r,time:e.info.position$.getValue()}),this.seekAction$.next("unknown")}),t(e.events.paused$,()=>{this.logPause({position:e.info.position$.getValue()})}),t(e.events.willResume$,()=>{this.logPlay()}),t(e.events.started$,()=>{this.statContext.clip&&this.logWatchCoverageRecord({start:0,end:0})}),t(e.events.playing$,()=>{this.logPlaying()}),t(dt(e,{forceInterval:this.config.watchCoverageInterval,watchCoverageTimeoutFix:this.config.watchCoverageTimeoutFix}),r=>{let d=e.info.isLive$.getValue(),u=e.info.atLiveEdge$.getValue(),f={start:parseFloat(r.from.toFixed(3)),end:parseFloat(r.to.toFixed(3))};if(u){let m=e.info.liveLatency$.getValue()??0,b=e.info.currentBuffer$.getValue()?.end??0,T=e.info.liveBufferTime$.getValue()??0,E=Math.round((m-(b-T))*1e3),S=Math.round(m*1e3);E&&S&&(f.latency=E,f.bufferLatency=S)}d?this.logWatchCoverageLive(f):this.logWatchCoverageRecord(f)});let o;t(e.info.isStalled$,r=>{r?o=R():(O(o)&&this.logEmptyBuffer({duration:R()-o}),o=void 0)});let n=!1;i.add(e.events.fatalError$.pipe(ni()).subscribe(()=>n=!0)),t(e.events.willStop$,()=>{if(e.info.isStalled$.getValue()){let d=O(o)?R()-o:void 0;this.logCloseAtEmptyBuffer({duration:d??0}),o=void 0}else n||this.logActionStop()}),t(e.events.managedError$,({id:r})=>{this.logError({fatal:!1,errorType:r})}),t(e.events.fatalError$,({id:r})=>{this.logError({fatal:!0,errorType:r})});let c,h,l=!1;t(e.events.firstBytes$,r=>{c=R(),this.logFirstBytes({time:r})}),t(e.events.willStart$,()=>h=R()),t(e.info.currentBuffer$,r=>{!l&&r&&r.end-r.start>0&&O(c)&&(this.logPlayerReady({duration:R()-c}),l=!0)}),t(e.events.firstFrame$,()=>{O(c)&&!l&&(this.logPlayerReady({duration:R()-c}),l=!0),O(h)&&this.logFirstFrame({time:R()-h})});let p;t(e.info.currentVideoStream$,r=>{r&&(p&&r.id!==p&&this.logTrackSwitch(r),p=r.id)});let g;t(e.info.currentAudioStream$,r=>{r&&(g&&r.id!==g&&this.logTrackSwitch(r),g=r.id)}),t(e.info.atLiveEdge$,r=>this.updateContext({liveEdge:r})),t(ct({muted:e.info.muted$,volume:e.info.volume$}),({muted:r,volume:d})=>this.updateContext({audible:!r&&d>0})),t(e.info.currentQuality$,r=>{let d=it(r);this.updateContext({quality:d}),d&&this.logQuality(d)}),t(e.info.isAutoQualityEnabled$,r=>this.updateContext({autoQuality:r})),t(e.info.currentFormat$,r=>this.updateContext({contentType:ot(r)})),t(e.info.currentPlaybackRate$,r=>this.updateContext({rate:r})),t(e.info.is3DVideo$,r=>this.updateContext({is3d:r}));let s;return t(e.info.hostname$,r=>{let d=s!==void 0&&s!==r;this.updateContext({cdnHostname:r,failover:d}),d&&this.logFailover(r),s=r}),t(e.info.throughputEstimation$,r=>this.updateContext({downloadSpeed:r})),t(e.info.httpConnectionType$,r=>{this.statContext.firstConnectionType||this.updateContext({firstConnectionType:Te(r)}),this.updateContext({connectionType:Te(r)})}),t(e.info.httpConnectionReused$,r=>{ut(this.statContext.firstConnectionReused)&&this.updateContext({firstConnectionReused:r}),this.updateContext({connectionReused:r})}),t(e.info.surface$,r=>{this.uiEvents||this.updateContext({mode:Ee(r,this.statContext.isPreviewPlayerView)})}),t(ct({current:e.info.currentTextTrack$,available:e.info.availableTextTracks$}),({current:r,available:d})=>{let u=d.find(({id:m})=>m===r),f=u&&(u.isAuto?`${u.language}_auto`:u.language);this.updateContext({subtitles:f?.split(".")[0]})}),this.player=e,this.uiEvents&&this.attachToUi(this.uiEvents),this.resubscribeBeforeunload(),this.subscription.add(i),i}attachToUi(e){this.uiEvents=e;let{subscription:i,subscribe:t}=xe();if(!this.player)return i;t(e.actionRewind$,()=>{this.player&&(this.resetViewSession(),this.logActionPlay({position:this.player.info.position$.getValue()}))}),t(e.actionSeek$,this.seekAction$);let{surface$:o}=ee(this.uiEvents,t,this.player);return t(o,n=>{this.updateContext({mode:Ee(n,this.statContext.isPreviewPlayerView)})}),t(e.actionSetSubtitle$,n=>this.updateContext({subtitles:n?.split(".")[0]})),t(e.nextMovie$,n=>this.logNextMovie(n)),this.resubscribeBeforeunload(),this.subscription.add(i),i}attachToAds(e){let{subscription:i,subscribe:t}=xe();return t(e.slotRequested$,()=>this.logAdSlotRequest()),t(e.started$,o=>this.logAdStarted(o)),t(e.paused$,()=>this.logAdPaused()),t(e.resumed$,()=>this.logAdResumed()),t(e.ended$,()=>this.logAdEnded()),t(e.skipped$,()=>this.logAdSkipped()),t(e.clicked$,()=>this.logAdClicked()),t(e.error$,o=>this.logError({errorType:o,fatal:!1})),this.resubscribeBeforeunload(),this.subscription.add(i),i}attachToInteractive(e){let{subscription:i,subscribe:t}=xe();return t(e.click$,o=>this.logInterfaceClick(o)),t(e.nextMovie$,o=>this.logNextMovie(o)),this.resubscribeBeforeunload(),this.subscription.add(i),i}authorize(e){return this.api.authorize(e)}pause(){this.logger.pause(),this.oneStatDebugLog({message:"paused"})}resume(){this.logger.resume(),this.oneStatDebugLog({message:"resumed"})}destroy(){this.logger.flush(),this.subscription.unsubscribe(),this.api.destroy(),this.logger.destroy()}resetViewSession(){this.oneStatDebugLog({message:"VSID reset"}),D.generateVSID(this.config.useVsid64)}getDeviceId(){return this.deviceId}setFieldBlacklist(){}logInited(){}logReady(e){this.log({operation:"player_ready",param:String(e.time)})}logStarted(...e){this.logActionPlay(...e)}logPlay(){this.log({operation:"play_toggle"})}logPlaying(){this.log({operation:"playing"})}logPause(e){this.log({operation:"pause",param:String(Math.round(e.position))})}logSeek(e){this.log({operation:"seek",param:e.action,time:e.time})}logFirstBytes(e){this.log({operation:"first_bytes",param:String(e.time)})}logFirstFrame(e){this.log({operation:"first_frame",param:String(e.time)})}logError(e){this.log({operation:"content_error",param:`${e.fatal?"fatal":"recoverable"}_${e.errorType}`})}logWatchCoverageRecord(e){this.log({operation:"watch_coverage_record",param:`${e.start}-${e.end}`},{in_history:this.statContext.inHistory?1:void 0})}logWatchCoverageLive(e){let i=this.timeSynchronisation?.getOffset()??0,t=e.start+i,o=e.end+i;this.log({operation:"watch_coverage_live",param:`${t}-${o}`},{in_history:this.statContext.inHistory?1:void 0,latency:e.latency,buffer_latency:e.bufferLatency})}logEmptyBuffer(e){this.log({operation:"empty_buffer",param:String(e.duration)})}logDownloadSpeed(){}logAdSlotRequest(){this.log({operation:"adv",param:"slot_request"})}logAdStarted(e){this.log({operation:"adv",param:e})}logAdPaused(){this.log({operation:"adv",param:"pause"})}logAdResumed(){this.log({operation:"adv",param:"resume"})}logAdEnded(){this.log({operation:"adv",param:"ended"})}logAdSkipped(){this.log({operation:"adv",param:"skip"})}logAdClicked(){this.log({operation:"adv",param:"click"})}logInterfaceClick(e){this.log({operation:"player_interface_click",param:e})}logNextMovie(e){this.log({operation:"next_movie",param:String(e)})}subscribe(){this.resubscribeBeforeunload();let e=window.navigator.connection;e&&"onchange"in e&&"effectiveType"in e&&this.subscription.add(ri(lt(e,"change"),si(["init"])).subscribe(()=>this.updateContext({network:rt(e.effectiveType)}))),this.config.debugLog&&this.debugLogger.log$.subscribe(i=>{console.debug("%c stat ","background:#fa6470;",`component: ${i.component}.`,i.message)})}resubscribeBeforeunload(){this.beforeunloadSubscription?.unsubscribe(),this.beforeunloadSubscription=lt(window,"beforeunload").subscribe(()=>this.logger.flush({wantBeacon:!0,clearStorage:this.config.clearStorageAtUnload})),this.subscription.add(this.beforeunloadSubscription)}logPlayerReady(e){this.log({operation:"player_ready",param:String(Math.round(e.duration))})}logActionPlay(e){this.log({operation:"action_play",param:String(Math.round(e.position))})}logActionPlayInteractive(){this.statContext.projectId&&this.log({operation:"action_play_interactive",param:String(this.statContext.movieId)},{vid:this.statContext.projectId})}logFailover(e){this.log({operation:"failover",param:e})}logCloseAtEmptyBuffer(e){this.log({operation:"close_at_empty_buffer",param:String(Math.round(e.duration))})}logActionStop(){this.log({operation:"action_stop"})}logTrackSwitch(e){this.log({operation:"track_switch",param:e.id})}logQuality(e){this.log({operation:"quality",param:e})}log(e,i={}){if(this.disabled){this.oneStatDebugLog({message:`operation ${e.operation} but statistics is disabled`});return}if(this.config.disabledOperations.includes(e.operation)){this.oneStatDebugLog({message:`operation ${e.operation} but it is disabled`});return}this.oneStatDebugLog({message:`operation ${e.operation} ${e.param}`});let t=this.createLogItem(e,i);this.logger.log(t)}createLogItem({operation:e,param:i,time:t},o={}){let n=this.timeSynchronisation?.now()??R(),c=this.vsid$.getValue();oi(c);let h=this.isid$.getValue(),l=e==="empty_buffer"||e==="close_at_empty_buffer"?this.statContext.connectionType:this.statContext.firstConnectionType,p=this.statContext.firstConnectionReused,g,s;if(this.isEmbed||this.statContext.place==="embed"){g=this.embedParent;let d=[...new URLSearchParams(location.search).entries()].filter(([u,f])=>this.config.embedUrlParams.includes(u));s=new URLSearchParams(d).toString()}else if(this.statContext.place==="direct"){let d=this.statContext.refDomain||document.referrer;d&&URL.canParse(d)?g=new URL(d).hostname:g=d,s=location.href.substring(0,1024)}let r={vsid:c,isid:h,vid:this.statContext.movieId,uid:this.zenUid$.getValue(),ct:this.statContext.contentType,place:this.isEmbed?"embed":this.statContext.place,quality:this.statContext.quality,cdn_host:this.statContext.cdnHostname,stat_type:this.statContext.autoplay===!0?"auto":this.statContext.autoplay===!1?"":void 0,param:i,vk_app_id:this.statContext.vkAppId,track_code:this.statContext.trackCode,connection_type:l,connection_reused:p===!0?1:p===!1?0:void 0,cached_data:this.statContext.cached===!0?1:this.statContext.cached===!1?0:void 0,live:this.statContext.liveEdge?1:void 0,muted:this.statContext.audible===!1?1:void 0,mode:this.statContext.mode,subtitles:this.statContext.subtitles,download_speed:this.statContext.downloadSpeed,manual_quality:this.statContext.autoQuality?void 0:1,ref_domain:g,direct_url:s,rate:this.statContext.rate===1||ut(this.statContext.rate)?void 0:this.statContext.rate.toFixed(2),view_360:this.statContext.is3d?1:void 0,aid:this.statContext.albumId,vk_playlist_id:this.statContext.vkPlaylistId,...o};for(let d of this.config.disabledCustomFields)delete r[d];return{operation:e,type:1,time:t,network:this.statContext.network,timestamp:n,custom:r}}};var Dt={};Bt(Dt,{ActionSeekType:()=>ie,ThinOneStat:()=>he,VERSION:()=>P});import{assertNonNullable as ki,detectEmbed as Ci,fromEvent as $i,Logger as Li,merge as Ct,combine as ue,filter as k,filterChanged as Ri,once as Di,skip as Fe,safeStorage as $t,getWindow as Ni,Subject as Mi,Subscription as He,ValueSubject as Ue,ErrorCategory as U}from"@vkontakte/videoplayer-shared/evergreen";import{clientChecker as $}from"@vkontakte/videoplayer-core/evergreen";import{fillWithDefault as ui}from"@vkontakte/videoplayer-shared/evergreen";var $e=(t=>(t.AUTO="auto",t.AUTO_POOR="auto_poor",t.AUTO_RICH="auto_rich",t))($e||{});var ie=(l=>(l.SLIDER="slider",l.RICH="rich",l.DOUBLE_TAP="double_tap",l.TIME_CODE="time_code",l.EPISODE="episode",l.REWIND="rewind",l.LIVE="live",l.UNKNOWN="unknown",l))(ie||{});var gt="CIOPGQJGDIHBABABA",Le={prod:"https://api.ok.ru",vk_alias:"https://api.mycdn.me",videotest:"https://videotestapi.ok.ru/api",test:"https://apitest.ok.ru",okcdn:"https://api.okcdn.ru",auto:""};var hi={apiKey:gt,apiEnv:"okcdn",apiBaseUrl:null,requestRetryCount:1,useVsid64:!1,firstFlushTime:5e3,flushDebounceTime:1e4,flushMaxWait:6e4,storageExpiration:36*60*60*1e3,watchCoverageHeartbeatInterval:3e4,disabledEvents:[],disabledParams:[],synchronizeTime:!0,useBeacon:!1,alwaysSendDesktop:!1,watchedNDefaultTargetDuration:1e3,downloadBytesMaxTime:3e4},mt=a=>ui(a,hi);import{getExponentialDelay as pi,ErrorCategory as B,ValueSubject as fi}from"@vkontakte/videoplayer-shared/evergreen";var oe=class{constructor(e){this.params=e,this.authorized$=new fi(!1),this.consequentAuthErrors=0}async authorize(e){return this.authToken=e??await this.refreshAuthToken(),this.authorizeWithBackoff()}logBeacon(e){let i="log.logUvStat",t=this.createLogParams(e),o=this.sessionKey;if(!o)return;this.params.apiTransport.sendBeacon(i,t,o)||this.logRequest(e).catch(()=>{})}async logRequest(e){let i="log.logUvStat",t=this.createLogParams(e),o={},n=this.sessionKey??await this.authorizeWithBackoff();if(!n)return;let c=async(h,l=this.params.config.requestRetryCount)=>{try{return await this.params.apiTransport.sendRequest(i,t,n,o)}catch(p){if(!p||!("error_code"in p)){this.params.error$.next({id:"logRequestUnknown",category:B.NETWORK,message:`Unknown ${i} error`,thrown:p});return}let g=p?.error_code;switch(g){case 102:case 103:case 104:return this.authorized$.next(!1),this.sessionKey=await this.authorizeWithBackoff(),l>0?c(h,l-1):void 0;case 401:return this.authorized$.next(!1),this.authToken=await this.refreshAuthToken(),this.sessionKey=await this.authorizeWithBackoff(),l>0?c(h,l-1):void 0;default:{this.params.error$.next({id:`LogRequest#${g}`,category:B.EXTERNAL_API,message:`${i} error`,data:p});return}}}};return c(e)}destroy(){window.clearTimeout(this.backoffTimeoutId),this.backoffTimeoutId=0}async refreshAuthToken(){if(this.params.refreshAuthToken)return this.refreshAuthTokenPromise||(this.refreshAuthTokenPromise=this.params.refreshAuthToken().finally(()=>{this.refreshAuthTokenPromise=void 0})),this.refreshAuthTokenPromise}createLogParams(e){return{collector:"ok.mobile.apps.video",uv_stat_data:JSON.stringify({application:`@vkontakte/videoplayer-statistics:${P}`,platform:e[0].platform,product:e[0].product,events:e})}}authorizeWithBackoff(){if(!this.consequentAuthErrors)return this.doAuthorize();let e=pi(this.consequentAuthErrors);return new Promise(i=>{this.backoffTimeoutId||(this.backoffTimeoutId=window.setTimeout(async()=>{try{let t=await this.doAuthorize();i(t)}catch(t){this.params.error$.next({id:"AuthorizeBackoff",category:B.NETWORK,message:"Otherwise unhandled error in authorization",thrown:t})}finally{this.backoffTimeoutId=0}},e))})}doAuthorize(){if(this.authorizePromise)return this.authorizePromise;this.sessionKey=void 0,this.authorized$.next(!1);let e="auth.anonymLogin",i={session_data:{version:2,device_id:this.params.deviceId,client_version:P.split("-")[0],client_type:"SDK_JS"}};return this.authToken!==void 0&&(i.session_data.auth_token=this.authToken,i.session_data.version=3),this.authorizePromise=this.params.apiTransport.sendRequest(e,i).then(t=>((!t||!t.session_key)&&this.params.error$.next({id:"AuthorizeFailed",category:B.EXTERNAL_API,message:"No session key",data:t}),this.sessionKey=t?.session_key??void 0,this.sessionKey)).catch(async t=>{this.sessionKey=void 0;let o=t?.error_code;switch(o){case 401:return this.authToken=await this.refreshAuthToken(),this.authorizeWithBackoff()}o?this.params.error$.next({id:`Authorize#${o}`,category:B.EXTERNAL_API,message:"authorize error",data:t}):this.params.error$.next({id:"AuthorizeUnknown",category:B.NETWORK,message:"authorize error",thrown:t})}).finally(()=>{this.authorizePromise=void 0,this.consequentAuthErrors=this.sessionKey?0:this.consequentAuthErrors+1,this.authorized$.next(this.sessionKey!==void 0)}),this.authorizePromise}};import{now as Re,ErrorCategory as re}from"@vkontakte/videoplayer-shared/evergreen";var se=class{constructor(e){this.params=e,this.apiKey=e.config.apiKey,this.apiEnv=e.config.apiEnv,this.apiBaseUrl=e.config.apiBaseUrl??Le[this.apiEnv],this.timeSynchronisation=e.timeSynchronisation,this.isApiBaseUrlFetched=!1}sendBeacon(e,i,t){if(!window.Blob||!window.navigator.sendBeacon)return!1;let o=this.prepareQueryParams({method:e,queryParams:i,sessionKey:t}),n=new window.Blob([o.toString()],{type:"application/x-www-form-urlencoded"});try{return window.navigator.sendBeacon(`${this.apiBaseUrl}/fb.do`,n)}catch(c){this.params.error$.next({id:"OneStat:ApiTransport:sendBeacon",category:re.NETWORK,message:"Unhandled beacon error",thrown:c,data:{method:e,params:i}})}return!1}async sendRequest(e,i,t,o){let n=Re(),c=h=>{if(h instanceof TypeError&&["Failed to fetch","NetworkError when attempting to fetch resource."].includes(h.message)){this.params.error$.next({id:"Network",category:re.NETWORK,message:"Request failed",thrown:h});return}this.params.error$.next({id:"ThinOneStat:ApiTransport:sendRequest",category:re.NETWORK,message:"Unhandled request error",thrown:h,data:{method:e,params:i,sessionKey:t,time:Re()-n}})};return this.apiBaseUrl=await this.resolveApiBaseUrl(),fetch(`${this.apiBaseUrl}/fb.do`,{method:"post",headers:{"Content-type":"application/x-www-form-urlencoded",...o},body:this.prepareQueryParams({method:e,queryParams:i,sessionKey:t})}).then(h=>{let l=Number(h.headers.get("content-length"))===0,p=new Date(h.headers.get("date")??"").getTime(),g=Re()-n;if(isFinite(p)&&this.timeSynchronisation?.addServerTime(p,g),!l)return h.json().then(s=>Object.prototype.hasOwnProperty.call(s,"error_msg")?Promise.reject(s):s,c)},c)}async resolveApiBaseUrl(){if(this.apiEnv!=="auto"||this.isApiBaseUrlFetched)return this.apiBaseUrl;try{let e=atob("aHR0cHM6Ly9kbnMuZ29vZ2xlL3Jlc29sdmU/bmFtZT12aWRlby5fZW5kcG9pbnQub2sucnUmdHlwZT1UWFQ="),o=(await(await fetch(e,{method:"GET",mode:"cors",cache:"no-cache"})).json())?.Answer[0]?.data;if(!o)throw new Error("Wrong DNS response");return o}catch(e){return this.params.error$.next({id:"ThinOneStat:ApiTransport:resolveApiBaseUrl",category:re.NETWORK,message:"Unhandled resolve api base url error",thrown:e}),Le.vk_alias}finally{this.isApiBaseUrlFetched=!0}}prepareQueryParams(e){let i=new URLSearchParams({format:"JSON",method:e.method,application_key:this.apiKey});return e.sessionKey!==void 0&&i.append("session_key",e.sessionKey),Object.entries(e.queryParams).forEach(([t,o])=>i.append(t,typeof o=="string"?o:JSON.stringify(o))),i}};import{ErrorCategory as gi,now as mi,safeStorage as z,debounceFn as vt}from"@vkontakte/videoplayer-shared/evergreen";var ne="thinonestat_events",De=a=>e=>e.client_time+a>=mi(),ae=class{constructor(e){this.unsaltedStorage=[];this.isPaused=!1;this.isUrgent=e=>{let{event_name:i}=e;return["watch_coverage","watch_coverage_live","watched_n","playback_started"].includes(i)};this.params=e,this.api=e.api,this.error$=e.error$,this.userSalt=e.userSalt,this.loggerDebugLog=e.debugLogger.createComponentLog("stat logger"),this.firstFlush=vt(()=>this.safeFlush(),this.params.config.firstFlushTime,{maxWait:this.params.config.firstFlushTime});let i=z.isPersistent()?this.params.config.flushMaxWait:0;this.debouncedFlush=vt(()=>this.safeFlush(),this.params.config.flushDebounceTime,{maxWait:i}),this.subscription=this.api.authorized$.subscribe(t=>{t&&this.debouncedFlush()}),this.housekeepStorage()}safeFlush(){try{this.flush()}catch(e){this.error$.next({id:"LoggerError",category:gi.WTF,message:String(e)||"Unknown logger error",thrown:e})}}readFromStorage(){let e=z.get(ne);try{return e?JSON.parse(e):{}}catch{}return{}}addToStorage(e){if(!this.userSalt){this.unsaltedStorage.push(e);return}let i=this.readFromStorage(),o=(i[this.userSalt]??[]).filter(De(this.params.config.storageExpiration));z.set(ne,JSON.stringify({...i,[this.userSalt]:[...o,e]}))}getFromStorage(){return this.userSalt?(this.readFromStorage()[this.userSalt]??[]).filter(De(this.params.config.storageExpiration)):this.unsaltedStorage}markStorageSent(){if(!this.userSalt){this.unsaltedStorage=[];return}let e=this.readFromStorage();delete e[this.userSalt],z.set(ne,JSON.stringify(e))}housekeepStorage(){let e=this.readFromStorage();for(let[i,t]of Object.entries(e)){let o=t.filter(De(this.params.config.storageExpiration));o.length?e[i]=o:delete e[i],this.loggerDebugLog({message:`${t.length} retrieved from storage, ${o.length} of them actual`})}z.set(ne,JSON.stringify(e))}log(e){this.addToStorage(e),!this.isPaused&&(this.isUrgent(e)?this.flush():this.lastVsid!==e.vsid?this.firstFlush():this.debouncedFlush(),this.lastVsid=e.vsid)}flush({wantBeacon:e,clearStorage:i}={wantBeacon:!1,clearStorage:!0}){let t=this.getFromStorage();t.length!==0&&(this.api.authorized$.getValue()?(e&&this.params.config.useBeacon?(this.loggerDebugLog({message:`Flushing ${t.length} events through beacon`}),this.api.logBeacon(t)):(this.loggerDebugLog({message:`Flushing ${t.length} events`}),this.api.logRequest(t)),i&&this.markStorageSent()):this.api.authorize(),this.firstFlush.cancel(),this.debouncedFlush.cancel())}pause(){this.isPaused=!0,this.debouncedFlush.cancel()}resume(){this.isPaused=!1,this.debouncedFlush()}destroy(){this.subscription.unsubscribe(),this.firstFlush.cancel(),this.debouncedFlush.cancel()}};function Ne(){let a="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".split(""),e=new Array(36),i=0,t,o;for(o=0;o<36;o++)o===8||o===13||o===18||o===23?e[o]="-":o===14?e[o]="4":(i<=2&&(i=33554432+Math.random()*16777216|0),t=i&15,i=i>>4,e[o]=a[o===19?t&3|8:t]);return e.join("")}var de=class{constructor(e){this.offset=void 0;this.offset=e}getOffset(){return this.offset??0}setOffset(e){this.offset=e}now(){return Date.now()+(this.offset??0)}date(e=new Date){return e.setTime(e.getTime()+(this.offset??0)),e}addServerTime(e,i){let t=Date.now(),o=e-t-i/2;if(Math.abs(o)<1e3){this.offset=0;return}this.offset===void 0?this.offset=Math.round(o):this.offset=Math.round(.2*o+(1-.2)*this.offset)}};import{PlaybackState as bt}from"@vkontakte/videoplayer-core/evergreen";import{Observable as vi,Subscription as bi,ValueSubject as Ii,Subject as Me,fromEvent as yi,isNullable as It,merge as j,filter as yt,filterChanged as St,getWindow as Ve}from"@vkontakte/videoplayer-shared/evergreen";var _t=(a,e,i)=>new vi(t=>{let o=new bi,n=new Ii(void 0),c;o.add(a.info.isLive$.pipe(St()).subscribe(L=>{c&&(c.unsubscribe(),n.next(void 0)),L?c=a.info.liveTime$.pipe(St()).subscribe(n):c=a.info.position$.subscribe(n),o.add(c)}));let{playing$:h,paused$:l,ended$:p,looped$:g}=a.events,s=a.events.willSeek$.pipe(yt(()=>a.info.playbackState$.getValue()===bt.PLAYING)),r=a.events.seeked$.pipe(yt(()=>a.info.playbackState$.getValue()===bt.PLAYING)),d=!1,u=new Me;o.add(s.subscribe(()=>{d||u.next(),d=!0})).add(r.subscribe(()=>d=!1));let f=j(yi(Ve(),"beforeunload"),a.events.willDestruct$),m,b=()=>m=n.getValue(),T=()=>{let L=n.getValue();It(m)||It(L)||m===L||(t.next({from:m,to:L}),m=void 0)},E=new Me,S=new Me,v=j(h,r,E),_=j(l,u,f,p,g,S),We=e.started$&&e.ended$?j(v,e.ended$):v,Qe=e.started$&&e.ended$?j(_,e.started$):_;if(o.add(We.subscribe(b)).add(Qe.subscribe(T)),i.heartbeatInterval&&isFinite(i.heartbeatInterval)){let L=[],Vt=()=>{S.next(),E.next()};o.add(We.subscribe(()=>{let fe=Ve().setTimeout(Vt,i.heartbeatInterval);L.push(fe)})).add(Qe.subscribe(()=>{L.forEach(fe=>{Ve().clearTimeout(fe)}),L=[]}))}return o});import{Subscription as Si}from"@vkontakte/videoplayer-core/evergreen";import{Observable as _i,merge as Pi}from"@vkontakte/videoplayer-shared/evergreen";var Pt=(a,e)=>new _i(i=>{let t=new Si;return t.add(Pi(a.info.position$,a.info.liveTime$).subscribe(()=>{let o=e.getTotalViewTime();o>=e.targetDuration&&(i.next({target_duration:e.targetDuration,current_tvt:o}),t.unsubscribe())})),t});import{Subscription as Ti}from"@vkontakte/videoplayer-core/evergreen";import{Observable as Ei,filter as wi,getWindow as Tt}from"@vkontakte/videoplayer-shared/evergreen";var Et=(a,{maxTimeWindow:e})=>new Ei(i=>{let t=new Ti,o={maxBytesThreshold:100*1024*1024,minBytesThreshold:100*1024,maxTimeWindow:e,minTimeWindow:2e3},n={bytes:0,startTime:0,lastEmitTime:0,timeoutId:0},c=()=>{n.timeoutId&&(Tt().clearTimeout(n.timeoutId),n.timeoutId=null)},h=()=>{n.bytes=0,n.startTime=0,n.lastEmitTime=0,c()},l=s=>{if(n.bytes<o.minBytesThreshold||s-n.lastEmitTime<o.minTimeWindow&&n.lastEmitTime>0)return!1;let u=(n.startTime>0?s-n.startTime:0)>=o.maxTimeWindow,f=n.bytes>=o.maxBytesThreshold;return u||f},p=(s=!1)=>{let r=Date.now();if(!s&&!l(r))return;c();let d=n.startTime>0?r-n.startTime:Math.max(o.minTimeWindow,1),u=n.bytes/(d/1e3);i.next({download_bytes:Math.round(n.bytes),download_speed:Math.round(u)}),n.lastEmitTime=r,h()},g=()=>{if(c(),n.startTime>0&&n.bytes>=o.minBytesThreshold){let r=Date.now()-n.startTime,d=o.maxTimeWindow-r;d>100?n.timeoutId=Tt().setTimeout(()=>{n.timeoutId=null,p()},d):d>0&&p()}};return t.add(a.info.httpDownloadMetrics$.pipe(wi(s=>s!==void 0)).subscribe(s=>{let r=Date.now();n.startTime===0&&(n.startTime=r),n.bytes+=s.bytes,l(r)?p():g()})),t.add(()=>{if(c(),n.bytes>0){let s=Date.now(),r=n.startTime>0?s-n.startTime:o.minTimeWindow,d=n.bytes/(r/1e3);i.next({download_bytes:Math.round(n.bytes),download_speed:Math.round(d)})}h()}),t});import{Observable as Ai,Subscription as xi,merge as wt}from"@vkontakte/videoplayer-shared/evergreen";var At=a=>new Ai(e=>{let i=new xi,t=0,o=1,n=0,c=!1,h=!1,l=()=>{if(!c)return;let v=Date.now();n+=(v-t)*o,t=v},p=()=>{(!c||h)&&(t=Date.now(),c=!0,h=!1)},g=()=>{c&&(l(),c=!1)},s=()=>{c&&(l(),c=!1,h=!0)},r=v=>{c&&l(),o=v,t=Date.now()},{started$:d,playing$:u,paused$:f,willSeek$:m,ended$:b,willDestruct$:T}=a.events,{currentPlaybackRate$:E}=a.info;i.add(m.subscribe(s)).add(wt(d,u).subscribe(p)).add(wt(f,b,T).subscribe(g)).add(E.subscribe(r));let S=()=>{let v=n;return c&&(v+=(Date.now()-t)*o),v};return e.next(S),i});import{assertNever as xt}from"@vkontakte/videoplayer-shared/evergreen";import{HttpConnectionType as Oe,Surface as F,VideoFormat as I,VideoQuality as A}from"@vkontakte/videoplayer-core/evergreen";var Be=a=>a&&{[Oe.HTTP1]:"http1",[Oe.HTTP2]:"http2",[Oe.QUIC]:"http3"}[a],G=a=>{if(a!==void 0)switch(a){case I.MPEG:return"MP4";case I.DASH:case I.DASH_LIVE:return"DASH";case I.DASH_SEP:return"DASH_SEP";case I.DASH_ONDEMAND:return"ONDEMAND_DASH";case I.HLS_ONDEMAND:return"ONDEMAND_HLS";case I.HLS:case I.HLS_LIVE:return"HLS";case I.HLS_FMP4:return"HLS_FMP4";case I.DASH_WEBM:case I.DASH_LIVE_WEBM:return"WEBM";case I.DASH_LIVE_CMAF:return"ONDEMAND_DASH_LIVE";case I.HLS_LIVE_CMAF:return"ONDEMAND_HLS_LIVE";case I.WEB_RTC_LIVE:return"WEBRTC";case I.DASH_WEBM_AV1:return"AV1";case I.DASH_STREAMS:return"MULTI_DASH";default:return xt(a)}},x=a=>{if(a!==void 0)switch(a){case A.Q_144P:return"144p";case A.Q_240P:return"240p";case A.Q_360P:return"360p";case A.Q_480P:return"480p";case A.Q_720P:return"720p";case A.Q_1080P:return"1080p";case A.Q_1440P:return"1440p";case A.Q_2160P:return"2160p";case A.INVARIANT:case A.Q_576P:case A.Q_4320P:return"UNKNOWN";default:return xt(a)}},kt=a=>{if(a!==void 0)switch(a){case"MP4":case"ONDEMAND_DASH":case"ONDEMAND_DASH_LIVE":case"ONDEMAND_HLS":case"ONDEMAND_HLS_LIVE":case"MULTI_DASH":case"WEBM":case"AV1":return"vod";case"DASH":case"HLS":case"HLS_FMP4":case"WEBRTC":return"live";default:return}},N=(a,e,i)=>{if(a&&e)switch(a){case I.MPEG:return i&&e[a]&&e[a][i];default:return e[a]?.url}},ce=(a,e=!1)=>{if(e)return"minimal";switch(a){case void 0:case F.NONE:return;case F.INLINE:return"inline";case F.FULLSCREEN:return"fullscreen";case F.SECOND_SCREEN:return"chromecast";case F.PIP:return"pip_external"}},le=a=>{switch(a){case void 0:return;case F.INVISIBLE:return"background";default:return"foreground"}};var Vi="_thin-one-stat_",Lt=`${Vi}deviceId`,Rt=()=>{let a=new He;return{subscription:a,subscribe:(e,i)=>{e&&a.add(e.subscribe(i))}}},he=class{constructor(e,i){this.debugLogger=new Li;this.thinOneStatDebugLog=this.debugLogger.createComponentLog("ThinOneStat");this.eventNumber=1;this.playerSize={width:0,height:0};this.seekAction$=new Ue("unknown");this.isid$=new Ue(void 0);this.getTotalViewTime=()=>0;this.statContext=e,this.config=mt(i.config??{}),this.subscription=new He,this.config.synchronizeTime&&(this.timeSynchronisation=new de);let t=new Mi,o=$t.get(Lt);this.statContext.deviceId?this.deviceId=this.statContext.deviceId:o?this.deviceId=o:(this.deviceId=Ne(),$t.set(Lt,this.deviceId)),this.statContext.targetDuration?this.targetDuration=this.statContext.targetDuration:this.targetDuration=this.config.watchedNDefaultTargetDuration,this.resetViewSession(),i.useIsid&&this.isid$.next(i.isid??q());let n=new se({error$:t,config:this.config,timeSynchronisation:this.timeSynchronisation});this.api=new oe({config:this.config,apiTransport:n,error$:t,deviceId:this.deviceId,refreshAuthToken:i.refreshAuthToken}),this.logger=new ae({config:this.config,debugLogger:this.debugLogger,api:this.api,error$:t,userSalt:i.userSalt});let{isEmbed:c,topOrigin:h}=Ci();this.isEmbed=c,this.embedHostname=h?new URL(h).hostname:void 0}get vsid$(){return new Ue(D.getVSID())}authorize(e){return this.api.authorize(e)}updateContext(e){this.statContext={...this.statContext,...e}}attachTo(e,i){let t=new He,o=(s,r)=>t.add(s.subscribe(r));o(At(e),s=>{this.getTotalViewTime=s}),o(e.info.isLive$,s=>this.isLive=s);let n;o(ue({hostname:e.info.hostname$,connectionType:e.info.httpConnectionType$,connectionReused:e.info.httpConnectionReused$}).pipe(k(({hostname:s})=>s!==void 0),k(({connectionType:s})=>s!==void 0),k(({connectionReused:s})=>s!==void 0)),({hostname:s,connectionType:r,connectionReused:d})=>{if(n!==void 0&&n!==s){let f={cdn_host:s,connection_type:Be(r),connection_reused:d,content_type:G(e.info.currentFormat$.getValue())};this.logFailover(f)}this.cdnHostname=n=s}),o(e.info.httpConnectionType$,s=>{this.connectionType=Be(s)}),o(e.info.httpConnectionReused$,s=>{this.connectionReused=s}),o(_t(e,i,{heartbeatInterval:this.config.watchCoverageHeartbeatInterval}),s=>{let r=Math.round(s.from*1e3),d=Math.round(s.to*1e3),u={watch_interval:`${r}-${d}`,in_history:!!this.statContext.inHistory,content_type:G(e.info.currentFormat$.getValue()),playback_quality:x(e.info.currentQuality$.getValue()),recom_info:this.statContext.recomInfo};if(!e.info.isLive$.getValue())this.logWatchCoverage(u);else{let m=e.info.atLiveEdge$.getValue();this.logWatchCoverageLive({...u,live:!!m})}}),o(Pt(e,{targetDuration:this.targetDuration,getTotalViewTime:this.getTotalViewTime}),s=>{this.logWatchedN(s)}),o(e.events.willReady$,()=>{if(this.statContext.preload){let s=e.info.currentFormat$.getValue(),r=e.info.availableSources$.getValue(),d=e.info.currentBuffer$.getValue(),u=e.info.currentQuality$.getValue(),f={target_buffer_time:this.calcBufferTime(d),playback_url:N(s,r,u),playback_quality:x(u)};this.logPreloadStarted(f)}}),o(e.events.manifestRequested$,()=>{let s=e.info.currentFormat$.getValue(),r=e.info.availableSources$.getValue(),d=e.info.currentQuality$.getValue(),u={playback_url:N(s,r,d),cdn_host:this.cdnHostname,connection_type:this.connectionType,connection_reused:this.connectionReused};this.logManifestRequest(u)}),o(e.events.firstBytesManifest$,()=>{let s=e.info.currentFormat$.getValue(),r=e.info.availableSources$.getValue(),d=e.info.currentQuality$.getValue(),u={playback_url:N(s,r,d),cdn_host:this.cdnHostname,connection_type:this.connectionType,connection_reused:this.connectionReused};this.logFirstByteManifest(u)}),o(e.events.manifestReceived$,()=>{let s=e.info.currentFormat$.getValue(),r=e.info.availableSources$.getValue(),d=e.info.currentQuality$.getValue(),u={playback_url:N(s,r,d),cdn_host:this.cdnHostname,connection_type:this.connectionType,connection_reused:this.connectionReused};this.logManifestReceived(u)}),o(e.events.firstBytesRequested$,()=>{let s=e.info.currentFormat$.getValue(),r=e.info.availableSources$.getValue(),d=e.info.currentQuality$.getValue(),u={playback_url:N(s,r,d),cdn_host:this.cdnHostname,connection_type:this.connectionType,connection_reused:this.connectionReused};this.logFirstMediaRequest(u)}),o(e.events.firstBytesReceived$,()=>{let s=e.info.currentFormat$.getValue(),r=e.info.availableSources$.getValue(),d=e.info.currentQuality$.getValue(),u={playback_url:N(s,r,d),cdn_host:this.cdnHostname,connection_type:this.connectionType,connection_reused:this.connectionReused};this.logFirstByteMedia(u)}),o(Ct(e.events.willStart$,e.events.looped$),s=>{s&&this.resetViewSession();let d={isid:this.isid$.getValue(),stream_profile:kt(G(e.info.currentFormat$.getValue())),dpi:this.statContext.dpi??96*$.display.pixelRatio,web_layout:this.statContext.isMobile||$.device.isMobile?"mobile":"desktop",preloaded:this.statContext.preload,navigation:this.statContext.navigation,recom_info:this.statContext.recomInfo};this.isEmbed&&(d.iframe_host=this.embedHostname??"unknown"),this.logStartSession(d)}),o(e.events.started$,()=>{this.isStarted=!0;let s=e.info.currentBuffer$.getValue(),r=e.info.currentQuality$.getValue(),d=e.info.isAutoQualityEnabled$.getValue(),u=e.info.muted$.getValue(),f=e.info.volume$.getValue(),m=e.info.surface$.getValue(),b=e.info.availableTextTracks$.getValue(),T=e.info.currentTextTrack$.getValue(),E=e.info.currentAudioStream$.getValue(),S=e.info.currentPlaybackRate$.getValue(),v={playback_quality:x(r),user_quality:d?"auto":x(r),player_width:this.statContext.playerSize?.width??this.playerSize.width,player_height:this.statContext.playerSize?.height??this.playerSize.height,muted:u,sound_volume:Math.round(f*100),buffer_time:this.calcBufferTime(s),mode:ce(m,this.statContext.isPreviewPlayerView),visibility:le(m),subtitles_enabled:T?!!T:this.currentSubtitle?.enabled,auto_subtitles:b.find(({id:_})=>_===T)?.isAuto??this.currentSubtitle?.auto,audio_track_lang:E?.language,playback_rate:S,recom_info:this.statContext.recomInfo};this.logPlaybackStarted(v)}),o(e.events.willStart$,()=>{this.logPlay()}),o(e.events.playing$,()=>{let s=e.info.currentBuffer$.getValue(),r={buffer_time:this.calcBufferTime(s)};this.logPlaying(r),this.wasPaused&&this.logResume()}),o(e.events.paused$,()=>{this.wasPaused=!0,this.logPause()}),o(e.events.willStop$,()=>{this.logStop()}),o(Ct(e.events.fetcherRecoverableError$,e.events.fatalError$),()=>{this.statContext.preload&&this.logPreloadError()});let c=s=>{switch(s){case U.NETWORK:return"network";case U.VIDEO_PIPELINE:return"video_pipeline";case U.EXTERNAL_API:return"external_api";case U.PARSER:return"parser";case U.DOM:return"dom";default:return"wtf"}},h=s=>U.FATAL===s?"critical":"informative";o(e.events.fetcherRecoverableError$,({id:s,category:r,data:d,message:u,httpCode:f,UVBackendErrorCode:m})=>{let b={error_severity:h(r),error_category:c(r),player_error_code:s,player_error_trace:d,http_error_code:f,uv_backend_error_code_subcode:m,error_message:u};this.logError(b),h(r)==="critical"&&this.logCannotPlay()}),o(e.events.managedError$,({id:s,category:r,data:d,message:u})=>{let f={error_severity:h(r),error_category:c(r),player_error_code:s,player_error_trace:d,error_message:u};this.logError(f)}),o(e.events.fatalError$,({id:s,category:r,data:d,message:u})=>{let f={error_severity:"critical",error_category:c(r),player_error_code:s,player_error_trace:d,error_message:u};this.logError(f),this.logCannotPlay()}),o(ue({connectionType:e.info.httpConnectionType$,connectionReused:e.info.httpConnectionReused$,connectionMetrics:e.info.httpConnectionMetrics$}).pipe(k(({connectionReused:s})=>s!==void 0),k(({connectionMetrics:s})=>s!==void 0),Ri((s,r)=>s.connectionType===r.connectionType)),({connectionMetrics:s})=>{let r=e.info.currentFormat$.getValue(),d=e.info.availableSources$.getValue(),u=e.info.currentQuality$.getValue(),f=e.info.rttEstimation$.getValue(),m={playback_url:N(r,d,u),cdn_host:this.cdnHostname,connection_type:this.connectionType,connection_reused:this.connectionReused,rtt:f?Math.round(f):void 0,network_type:this.statContext.networkType??s?.networkType,dns_resolve_time:s?.dnsResolveTime,tcp_handshake_time:s?.tcpHandshakeTime,tls_handshake_time:s?.tlsHandshakeTime};this.logConnectionEstablished(m)}),o(Et(e,{maxTimeWindow:this.config.downloadBytesMaxTime}),s=>{this.logDownloadBytes(s)}),o(e.events.firstFrame$,()=>{this.logFirstVideoFrameDecoded()}),o(e.events.willSeek$,()=>{let s={seek_type:this.seekAction$.getValue()};this.isStarted&&this.logSeeking(s)}),o(e.events.seeked$,()=>{let s={seek_type:this.seekAction$.getValue()};this.isStarted&&this.logSeeked(s),this.seekAction$.next("unknown")}),o(e.info.isStalled$,s=>{let r=e.info.currentBuffer$.getValue(),d=this.calcBufferTime(r);s&&d&&d>0&&this.logBufferStarvation({buffer_time:d})}),o(e.info.currentBuffer$.pipe(k(s=>!!this.calcBufferTime(s)),Di()),s=>{let r=this.calcBufferTime(s);if(this.statContext.preload){let d={buffer_time:r};this.logPreloadEnded(d)}this.logReady({buffer_time:r})});let l;o(ue({videoStream:e.info.currentVideoStream$,audioStream:e.info.currentAudioStream$,quality:e.info.currentQuality$}).pipe(k(({videoStream:s,audioStream:r})=>s!==void 0&&r!==void 0),k(({quality:s})=>s!==void 0)),({videoStream:s,audioStream:r,quality:d})=>{if(l!==d){let u=e.info.isAutoQualityEnabled$.getValue(),f=s?.codec,m=r?.codec,b={user_quality:u?"auto":x(d),playback_quality:x(l),download_quality:x(d),codec_info:f&&m?`${f},${m}`:void 0};l=d,this.logQualityChanged(b)}});let p,g;return o(e.info.surface$,s=>{let r=ce(s,this.statContext.isPreviewPlayerView);r&&!this.uiEvents&&this.isStarted&&this.logModeChanged({mode:r}),g=le(s),p!==g&&this.isStarted&&(p=le(s),this.logVisibilityChanged({visibility:g}))}),o(ue({muted:e.info.muted$,volume:e.info.volume$}),({muted:s,volume:r})=>{if(this.isStarted){let d={muted:s,sound_volume:Math.round(r*100)};this.logSoundChanged(d)}}),o(e.info.currentFormat$.pipe(k(s=>s!==void 0),Fe(1)),s=>{let r={content_type:G(s),cdn_host:this.cdnHostname,connection_type:this.connectionType,connection_reused:this.connectionReused};this.logContentTypeChange(r)}),o(e.info.currentAudioStream$.pipe(k(s=>s!==void 0),Fe(1)),s=>{let r={audio_track_lang:s.language,codec_info:s.codec};this.logAudioTrackSwitched(r)}),o(e.info.currentVideoStream$.pipe(k(s=>s!==void 0),Fe(1)),s=>{let r={hdr:s.hdr,codec_info:s.codec};this.logVideoTrackSwitched(r)}),this.player=e,this.resubscribeBeforeunload(),this.subscription.add(t),t}attachToUi(e){this.uiEvents=e;let{subscribe:i,subscription:t}=Rt();i(e.actionSeek$,this.seekAction$),i(e.playerSize$,({width:n,height:c})=>{n&&c&&(this.playerSize={width:n,height:c},this.isStarted&&this.logViewPortChanged({player_width:n,player_height:c}))}),i(e.isLoaderVisible$,n=>{n&&this.isStarted&&this.logShowLoader()}),i(e.actionSubtitlesSwitched$,n=>{if(this.currentSubtitle={...n},this.isStarted){let c={subtitles_enabled:n.enabled,subtitles_track_lang:n.lang,auto_subtitles:n.auto};this.logSubtitlesSwitched(c)}});let{surface$:o}=ee(this.uiEvents,i,this.player);return i(o,n=>{this.isStarted&&this.logModeChanged({mode:ce(n)})}),i(e.actionQuality$,n=>{let c=g=>Object.values($e).includes(g),h=this.player?.info.currentVideoStream$.getValue()?.codec,l=this.player?.info.currentAudioStream$.getValue()?.codec,p={user_quality:c(n)?"auto":x(n),playback_quality:x(this.player?.info.currentQuality$.getValue()),download_quality:x(this.player?.info.currentQuality$.getValue()),codec_info:h&&l?`${h},${l}`:void 0};this.logQualityChangeRequested(p)}),this.resubscribeBeforeunload(),this.subscription.add(t),t}attachToAds(e){let{subscription:i,subscribe:t}=Rt();return t(e.init$,o=>{let n={slot:o};this.logAdvConfiguration(n)}),t(e.slotRequested$,()=>{this.logAdvRequest()}),t(e.started$,o=>{let n={adv_section:o};this.logAdvBreakStarted(n)}),t(e.ended$,o=>{let n={adv_section:o};this.logAdvBreakEnded(n)}),t(e.error$,o=>{let n={error_message:o};this.logAdvError(n)}),this.resubscribeBeforeunload(),this.subscription.add(i),i}getDeviceId(){return this.deviceId}resetViewSession(){this.thinOneStatDebugLog({message:"VSID reset"}),D.generateVSID(this.config.useVsid64),this.eventNumber=0}destroy(){this.api.destroy()}calcBufferTime(e){return e?Math.round((e.end??0)-(e.start??0))*1e3:void 0}createRequiredParams(e){let i=this.vsid$.getValue();ki(i);let t=this.eventNumber++,o=((this.isLive?this.player?.info.liveTime$.getValue():this.player?.info.position$.getValue())??0)*1e3,n={vsid:i,uv_movie_id:this.statContext.movieId,event_name:e,client_time:Date.now(),application:this.statContext.application??`@vkontakte/videoplayer-statistics:${P}`,platform:this.statContext.platform??`web:${this.statContext.isMobile||$.device.isMobile?"mobile":"desktop"}`,product:this.statContext.product,event_number:t,playback_position:o,current_tvt:this.getTotalViewTime(),cdn_host:this.cdnHostname};for(let c of this.config.disabledParams)delete n[c];return n}createRequiredFatParams(){let e={stats_version:"2.1.1",browser:this.statContext.browser??$.browser.current,browser_version:this.statContext.browserVersion??String($.browser.currentVersion),os:this.statContext.os??$.device.os.name,os_version:this.statContext.osVersion??$.device.os.version,device_type:this.statContext.deviceType??(this.statContext.isMobile||$.device.isMobile?"mobile":"desktop"),device_manufacturer:this.statContext.deviceManufacturer??$.device.details.vendor,device_model:this.statContext.deviceModel??$.device.details.model,navigation:this.statContext.navigation};for(let i of this.config.disabledParams)delete e[i];return e}log(e,i,t=!1){if(this.config.disabledEvents.includes(e))return;let o=this.createRequiredParams(e),n={};t&&(n=this.createRequiredFatParams()),this.logger.log({...o,...n,...i})}logWatchCoverage(e){this.log("watch_coverage",e,!0)}logWatchCoverageLive(e){this.log("watch_coverage_live",e,!0)}logWatchedN(e){this.log("watched_n",e,!0)}logStartSession(e){this.log("start_session",e,!0)}logPreloadStarted(e){this.log("preload_started",e)}logPreloadEnded(e){this.log("preload_ended",e)}logPreloadError(){this.log("preload_error")}logPlaybackStarted(e){this.log("playback_started",e,!0)}logPlay(){this.log("play")}logManifestRequest(e){this.log("manifest_request",e)}logFirstByteManifest(e){this.log("first_byte_manifest",e)}logFirstMediaRequest(e){this.log("first_media_request",e)}logFirstByteMedia(e){this.log("first_byte_media",e)}logManifestReceived(e){this.log("manifest_received",e)}logConnectionEstablished(e){this.log("connection_established",e)}logFirstVideoFrameDecoded(){this.log("first_video_frame_decoded")}logReady(e){this.log("ready",e)}logPlaying(e){this.log("playing",e)}logPause(){this.log("pause")}logResume(){this.log("resume")}logSeeking(e){this.log("seeking",e)}logSeeked(e){this.log("seeked",e)}logStop(){this.log("stop")}logBufferStarvation(e){this.log("buffer_starvation",e)}logShowLoader(){this.log("show_loader")}logQualityChangeRequested(e){this.log("quality_change_requested",e)}logQualityChanged(e){this.log("quality_changed",e)}logCdnHostChanged(e){this.log("cdn_host_changed",e)}logViewPortChanged(e){this.log("view_port_changed",e)}logModeChanged(e){this.log("mode_changed",e)}logVisibilityChanged(e){this.log("visibility_changed",e)}logAudioTrackSwitched(e){this.log("audio_track_switched",e)}logVideoTrackSwitched(e){this.log("video_track_switched",e)}logSubtitlesSwitched(e){this.log("subtitles_switched",e)}logSoundChanged(e){this.log("sound_changed",e)}logFailover(e){this.log("failover",e)}logContentTypeChange(e){this.log("content_type_change",e)}logError(e){this.log("error",e,!0)}logCannotPlay(){this.log("cannot_play",{},!0)}logDownloadBytes(e){this.log("download_bytes",e)}logAdvConfiguration(e){this.log("adv_configuration",e)}logAdvRequest(){this.log("adv_request")}logAdvBreakStarted(e){this.log("adv_break_started",e)}logAdvBreakEnded(e){this.log("adv_break_ended",e)}logAdvError(e){this.log("adv_error",e)}resubscribeBeforeunload(){this.beforeunloadSubscription?.unsubscribe(),this.beforeunloadSubscription=$i(Ni(),"beforeunload").subscribe(()=>{}),this.subscription.add(this.beforeunloadSubscription)}};var Oi={};import{PlaybackState as Mt,Subscription as Bi}from"@vkontakte/videoplayer-core/evergreen";import{Logger as Fi}from"@vkontakte/videoplayer-shared/evergreen";var pe=class{constructor(){this.startTime=null;this.stopTime=null;this.accumulatedTime=0}get time(){return Math.floor(this.timeMs/1e3)}get timeMs(){return this.startTime===null?0:(this.stopTime??this.now())-this.startTime-this.accumulatedTime}get isRunning(){return this.startTime!==null&&this.stopTime===null}start(){this.isRunning||(this.stopTime!==null?(this.accumulatedTime+=this.now()-this.stopTime,this.stopTime=null):this.startTime=this.now())}stop(){this.isRunning&&(this.stopTime=this.now())}reset(){this.startTime=null,this.stopTime=null,this.accumulatedTime=0}now(){return Date.now()}};var Nt=()=>window.Image?new Image:document.createElement("img");var qe=class{constructor(e){this.position=0;this.started=!1;this.heartbeatPixels=[];this.heartbeatLastTimeSent={};this.idleCallbackIds=[];this.stopwatch=new pe;this.subscription=new Bi;this.params=e;let i=new Fi;this.log=i.createComponentLog("MediascopePixel")}attachTo(e){this.subscription.add(e.info.playbackState$.subscribe(i=>this.onPlaybackState(i))).add(e.info.position$.subscribe(i=>this.onPosition(i))).add(e.info.atLiveEdge$.subscribe(i=>this.isActiveLive=i)),this.subscription.add(e.events.willSeek$.subscribe(()=>this.onWillSeek())).add(e.events.seeked$.subscribe(()=>this.onSeeked())).add(e.events.ended$.subscribe(()=>this.onEnded()))}destroy(){this.stopwatch.reset(),this.subscription.unsubscribe(),window.clearTimeout(this.heartbeatFirstTimeoutId),this.idleCallbackIds.forEach(e=>window.cancelIdleCallback(e)),this.send("stop")}onPlaybackState(e){e===Mt.PLAYING?this.started?this.play():this.start():e===Mt.PAUSED&&this.pause()}start(){this.started=!0,this.stopwatch.start(),this.send("start"),this.heartbeatPixels=this.prepareHeartbeatPixels(),this.heartbeatInterval=this.heartbeatPixels[0]?.interval;let e=this.heartbeatPixels[0]?.url,i=this.heartbeatPixels[0]?.delay;if(i!==void 0&&e)try{this.heartbeatFirstTimeoutId=window.setTimeout(()=>{this.sendHeartbeat(e)},i*1e3)}catch(t){this.log({message:t.message})}}play(){this.stopwatch.start(),this.send("resume")}pause(){this.stopwatch.stop(),this.send("pause")}onPosition(e){if(this.position=e,this.heartbeatInterval&&this.stopwatch.time!==0&&this.stopwatch.time%this.heartbeatInterval===0)for(let[i,{url:t}]of this.heartbeatPixels.entries())this.heartbeatLastTimeSent[i]!==this.stopwatch.time&&(this.heartbeatLastTimeSent[i]=this.stopwatch.time,this.sendHeartbeat(t))}onWillSeek(){this.started&&this.send("stop")}onSeeked(){this.started&&this.send("start")}onEnded(){this.stopwatch.stop(),this.send("stop")}validatePixels(e,i){return e?.filter(t=>t.event===i.event&&i.keys.every(o=>!!t[o]))}getFrameTimestamp(){let e;if(this.isActiveLive){let i=Math.floor(Math.random()*25)+5;e=Date.now()/1e3-i}else e=this.position||0;return Math.floor(e)}getUTC(){return Math.floor(Date.now()/1e3)}prepareUrl(e){return e.replace("{@fts_fake_sec}",String(this.getFrameTimestamp())).replace("{@utc_sec}",String(this.getUTC())).split("&").filter(i=>!/={@[a-zA-Z_]+}/.test(i)).join("&")}preparePixels(e){return this.validatePixels(this.params.pixels,{event:e,keys:["url"]})}prepareHeartbeatPixels(){return this.validatePixels(this.params.pixels,{event:"heartbeat",keys:["url","interval"]})}call(e){try{this.idleCallbackIds.push(requestIdleCallback(()=>Nt().src=this.prepareUrl(e)))}catch(i){this.log({message:i.message})}}send(e){let i=this.preparePixels(e);for(let{url:t}of i)this.call(t)}sendHeartbeat(e){this.call(e)}};export{H as ApiEnv,ve as ConnectionType,me as ContentType,Ke as InteractiveInterfaceClick,qe as MediascopePixel,Oi as MediascopePixelTypes,Ce as OneStat,ge as Quality,be as SeekAction,Dt as ThinOneStat,P as VERSION};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vkontakte/videoplayer-statistics",
3
- "version": "1.0.98-beta.0",
3
+ "version": "1.0.98-dev.10e34fe1.0",
4
4
  "author": "vk.com",
5
5
  "description": "Statistics library for vk.com videoplayer",
6
6
  "homepage": "https://vk.com",
@@ -54,7 +54,7 @@
54
54
  "**/*.d.ts"
55
55
  ],
56
56
  "dependencies": {
57
- "@vkontakte/videoplayer-core": "2.0.152-beta.0",
58
- "@vkontakte/videoplayer-shared": "1.0.81-beta.0"
57
+ "@vkontakte/videoplayer-core": "2.0.152-dev.10e34fe1.0",
58
+ "@vkontakte/videoplayer-shared": "1.0.81-dev.10e34fe1.0"
59
59
  }
60
60
  }