@vkontakte/videoplayer-statistics 1.0.103-dev.5aefbe80.0 → 1.0.103-dev.5aefbe808.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/esnext.cjs CHANGED
@@ -1,7 +1,7 @@
1
1
  /**
2
- * @vkontakte/videoplayer-statistics v1.0.103-dev.5aefbe80.0
3
- * Fri, 27 Mar 2026 12:51:36 GMT
2
+ * @vkontakte/videoplayer-statistics v1.0.103-dev.5aefbe808.0
3
+ * Mon, 08 Jun 2026 14:39:36 GMT
4
4
  * https://st.mycdn.me/static/vkontakte-videoplayer/1-0-103/doc/
5
5
  */
6
- var e=Object.defineProperty,t=Object.getOwnPropertyNames,n=Object.getOwnPropertyDescriptor,r=Object.prototype.hasOwnProperty;function i(e){return this[e]}var a=a=>{var s=(o??=new WeakMap).get(a),c;if(s)return s;if(s=e({},`__esModule`,{value:!0}),a&&typeof a==`object`||typeof a==`function`)for(var l of t(a))r.call(s,l)||e(s,l,{get:i.bind(a,l),enumerable:!(c=n(a,l))||c.enumerable});return o.set(a,s),s},o,s=e=>e;function c(e,t){this[e]=s.bind(null,t)}var l=(t,n)=>{for(var r in n)e(t,r,{get:n[r],enumerable:!0,configurable:!0,set:c.bind(n,r)})},u={};l(u,{VERSION:()=>D,ThinOneStat:()=>Te,SeekAction:()=>g,Quality:()=>p,OneStat:()=>we,MediascopePixel:()=>ot,InteractiveInterfaceClick:()=>_,ContentType:()=>m,ConnectionType:()=>h,ApiEnv:()=>f}),module.exports=a(u);var d=require(`@vkontakte/videoplayer-shared`),f;(e=>{e.PROD=`prod`,e.VK_ALIAS=`vk_alias`,e.VIDEOTEST=`videotest`,e.TEST=`test`,e.OKCDN=`okcdn`,e.AUTO=`auto`})(f||={});var p;(e=>{e.Q144P=`mobile`,e.Q240P=`lowest`,e.Q360P=`low`,e.Q480P=`medium`,e.Q720P=`high`,e.Q1080P=`fullhd`,e.Q1440P=`quadhd`,e.Q2160P=`ultrahd`,e.UNKNOWN=`unknown`})(p||={});var m;(e=>{e.MP4=`mp4`,e.DASH=`dash`,e.DASH_SEP=`dash_sep`,e.ONDEMAND_DASH=`ondemand_dash`,e.HLS=`hls`,e.HLS_FMP4=`hls_fmp4`,e.ONDEMAND_HLS=`ondemand_hls`,e.WEBM=`webm`,e.AV1=`av1`,e.ONDEMAND_DASH_LIVE=`ondemand_dash_live`,e.ONDEMAND_HLS_LIVE=`ondemand_hls_live`,e.WEBRTC=`webrtc`,e.UNKNOWN=`unknown`,e.RTMP=`rtmp`})(m||={});var h;(e=>{e.HTTP1=`http1`,e.HTTP2=`http2`,e.HTTP3=`http3`})(h||={});var g;(e=>{e.SLIDER=`slider`,e.RICH=`rich`,e.DOUBLE_TAP=`double_tap`,e.TIME_CODE=`time_code`,e.EPISODE=`episode`,e.REWIND=`rewind`,e.LIVE=`live`,e.UNKNOWN=`unknown`})(g||={});var _;(e=>{e.GRAPH_SHOW=`iGraphShow`,e.GRAPH_HIDE=`iGraphHide`,e.NEXT_AREA=`iNextChapterArea`,e.NEXT_BUTTON=`iNextChapterBtn`,e.WATCH_AGAIN=`iWatchAgainBtn`})(_||={});var v={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`},y={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`},b={unknown:`un`,mobile:`m`,lowest:`ls`,low:`l`,medium:`md`,high:`h`,fullhd:`f`,quadhd:`q`,ultrahd:`u`},ee={pip:`pi`,fullscreen:`fs`,external:`ex`,prefetch:`pr`,airplay:`ap`,chromecast:`cc`,invisible:`iv`,minimal:`minimal`},x=require(`@vkontakte/videoplayer-shared`),S=`CIOPGQJGDIHBABABA`,C={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:``},te={apiEnv:`vk_alias`,apiKey:S,apiBaseUrl:null,requestRetryCount:1,useVsid64:!1,firstFlushTime:5e3,flushDebounceTime:1e4,flushMaxWait:6e4,storageExpiration:2160*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:300*1e3,random:.1},useKeepalive:!1,watchCoverageTimeoutFix:!1},ne=e=>x.fillWithDefault(e,te);function re(){let e=`0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz`.split(``),t=Array(36),n=0,r,i;for(i=0;i<36;i++)i===8||i===13||i===18||i===23?t[i]=`-`:i===14?t[i]=`4`:(n<=2&&(n=33554432+Math.random()*16777216|0),r=n&15,n>>=4,t[i]=e[i===19?r&3|8:r]);return t.join(``)}var w=require(`@vkontakte/videoplayer-shared`),ie=require(`@vkontakte/videoplayer-shared`),ae=()=>Math.floor(Math.random()*2**32).toString(36).padStart(13,`0`),T=()=>Math.floor(Math.random()*2**64).toString(36).padStart(13,`0`);class E{static vsid;static getVSID(){return E.vsid}static generateVSID(e){return E.vsid=e?T():ae(),E.vsid}}var oe=e=>{let{operation:t,custom:n}=e,r=Object.fromEntries(Object.entries(n).map(([e,t])=>{let n=y[e]??e,r=t;return t&&(e===`mode`?r=ee[t]??t:e===`quality`&&(r=b[t]??t)),[n,r]}));return{...e,operation:v[t]??t,custom:r}},D=`1.0.103-dev.5aefbe80.0`,O=require(`@vkontakte/videoplayer-shared`),se=/Mobile|mini|Fennec|Android|iP(ad|od|hone)|opera (mini|mobi)/i;class ce{params;authToken;sessionKey;authorizePromise;refreshAuthTokenPromise;consequentAuthErrors=0;authorized$=new O.ValueSubject(!1);backoffTimeoutId;constructor(e){this.params=e}async authorize(e){return this.authToken=e??await this.refreshAuthToken(),this._authorizeWithBackoff()}logBeacon(e){let t=this.createLogParams(e),n=this.sessionKey;n&&(this.params.apiTransport.sendBeacon(`log.externalLog`,t,n)||this.logRequest(e).catch(()=>{}))}async logRequest(e){let t=`log.externalLog`,n=this.createLogParams(e),r=this.sessionKey??await this._authorizeWithBackoff();if(!r)return;let i=async(e,a=this.params.config.requestRetryCount)=>{try{return await this.params.apiTransport.sendRequest(t,n,r)}catch(n){if(!n||!(`error_code`in n)){this.params.error$.next({id:`logRequestUnknown`,category:O.ErrorCategory.NETWORK,message:`Unknown ${t} error`,thrown:n});return}let r=n?.error_code;switch(r){case 102:case 103:case 104:return this.authorized$.next(!1),this.sessionKey=await this._authorizeWithBackoff(),a>0?i(e,a-1):void 0;case 401:return this.authorized$.next(!1),this.authToken=await this.refreshAuthToken(),this.sessionKey=await this._authorizeWithBackoff(),a>0?i(e,a-1):void 0;default:this.params.error$.next({id:`LogRequest#${r}`,category:O.ErrorCategory.EXTERNAL_API,message:`${t} error`,data:n});return}}};return i(e)}destroy(){window.clearTimeout(this.backoffTimeoutId),this.backoffTimeoutId=0}async refreshAuthToken(){if(this.params.refreshAuthToken)return this.refreshAuthTokenPromise||=this.params.refreshAuthToken().finally(()=>{this.refreshAuthTokenPromise=void 0}),this.refreshAuthTokenPromise}createLogParams(e){let t=`WEB`,n=!1,r=`@vkontakte/videoplayer-statistics:${D}`;if(this.params.config.useVKComIsMobileLogic){let{appVersion:e}=window.navigator;n=se.test(e)}else this.params.mobile&&(n=!0);return n&&(t=`M_WEB`),this.params.vktvVersion&&(t=`SMART_TV`,r=this.params.vktvVersion),{collector:`ok.mobile.apps.video`,data:JSON.stringify({application:r,platform:t,items:this.params.config.shorten?e.map(oe):e})}}_authorizeWithBackoff(){if(!this.consequentAuthErrors)return this._authorize();let e=O.getExponentialDelay(this.consequentAuthErrors,this.params.config.backoff);return new Promise(t=>{this.backoffTimeoutId||=window.setTimeout(()=>{this._authorize().then(t).catch(e=>this.params.error$.next({id:`AuthorizeBackoff`,category:O.ErrorCategory.NETWORK,message:`Otherwise unhandled error in authorization`,thrown:e})).finally(()=>this.backoffTimeoutId=0)},e)})}async _authorize(){if(this.authorizePromise)return this.authorizePromise;this.sessionKey=void 0,this.authorized$.next(!1);let e={session_data:{version:2,device_id:this.params.deviceId,client_version:D.split(`-`)[0],client_type:`SDK_JS`}};return this.authToken!==void 0&&(e.session_data.auth_token=this.authToken,e.session_data.version=3),this.authorizePromise=this.params.apiTransport.sendRequest(`auth.anonymLogin`,e).then(e=>((!e||!e.session_key)&&this.params.error$.next({id:`AuthorizeFailed`,category:O.ErrorCategory.EXTERNAL_API,message:`No session key`,data:e}),this.sessionKey=e?.session_key??void 0,this.sessionKey)).catch(async e=>{this.sessionKey=void 0;let t=e?.error_code;switch(t){case 401:return this.authToken=await this.refreshAuthToken(),this._authorizeWithBackoff()}t?this.params.error$.next({id:`Authorize#${t}`,category:O.ErrorCategory.EXTERNAL_API,message:`authorize error`,data:e}):this.params.error$.next({id:`AuthorizeUnknown`,category:O.ErrorCategory.NETWORK,message:`authorize error`,thrown:e})}).finally(()=>{this.authorizePromise=void 0,this.consequentAuthErrors=this.sessionKey?0:this.consequentAuthErrors+1,this.authorized$.next(this.sessionKey!==void 0)}),this.authorizePromise}}var le=require(`@vkontakte/videoplayer-shared`),k=require(`@vkontakte/videoplayer-shared`);class ue{apiKey;apiBaseUrl;apiEnv;timeSynchronisation;isApiBaseUrlFetched;params;constructor(e){this.params=e,this.apiKey=e.config.apiKey,this.apiEnv=e.config.apiEnv,this.apiBaseUrl=e.config.apiBaseUrl??C[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=`),t=(await(await le.fetchPolyfilled(e,{method:`GET`,mode:`cors`,cache:`no-cache`})).json())?.Answer[0]?.data;if(!t)throw Error(`Wrong DNS response`);return t}catch(e){return this.params.error$.next({id:`OneStat:ApiTransport:resolveApiBaseUrl`,category:k.ErrorCategory.NETWORK,message:`Unhandled resolve api base url error`,thrown:e}),C.vk_alias}finally{this.isApiBaseUrlFetched=!0}}sendBeacon(e,t,n){if(!window.Blob||!window.navigator.sendBeacon)return!1;let r=this._prepareQueryParams({method:e,queryParams:t,sessionKey:n}),i=new window.Blob([r.toString()],{type:`application/x-www-form-urlencoded`});try{return window.navigator.sendBeacon(`${this.apiBaseUrl}/fb.do`,i)}catch(n){this.params.error$.next({id:`OneStat:ApiTransport:sendBeacon`,category:k.ErrorCategory.NETWORK,message:`Unhandled beacon error`,thrown:n,data:{method:e,params:t}})}return!1}async sendRequest(e,t,n){let r=k.now(),i=i=>{if(i instanceof TypeError&&[`Failed to fetch`,`NetworkError when attempting to fetch resource.`].includes(i.message)){this.params.error$.next({id:`Network`,category:k.ErrorCategory.NETWORK,message:`Request failed`,thrown:i});return}this.params.error$.next({id:`OneStat:ApiTransport:sendRequest`,category:k.ErrorCategory.NETWORK,message:`Unhandled request error`,thrown:i,data:{method:e,params:t,sessionKey:n,time:k.now()-r}})};this.apiBaseUrl=await this.resolveApiBaseUrl();let a={method:`post`,headers:{"Content-type":`application/x-www-form-urlencoded`},body:this._prepareQueryParams({method:e,queryParams:t,sessionKey:n})};return this.params.config.useKeepalive&&(a.keepalive=!0),le.fetchPolyfilled(`${this.apiBaseUrl}/fb.do`,a).then(e=>{let t=Number(e.headers.get(`content-length`))===0,n=new Date(e.headers.get(`date`)??``).getTime(),a=k.now()-r;if(isFinite(n)&&this.timeSynchronisation?.addServerTime(n,a),!t)return e.json().then(e=>Object.prototype.hasOwnProperty.call(e,`error_msg`)?Promise.reject(e):e,i)},i)}_prepareQueryParams(e){let t=new URLSearchParams({format:`JSON`,method:e.method,application_key:this.apiKey});return e.sessionKey!==void 0&&t.append(`session_key`,e.sessionKey),Object.entries(e.queryParams).forEach(([e,n])=>t.append(e,typeof n==`string`?n:JSON.stringify(n))),t}}var A=require(`@vkontakte/videoplayer-shared`),j=`onestat_events`,de=e=>t=>t.timestamp+e>=A.now();class fe{params;api;error$;subscription;userSalt;unsaltedStorage=[];lastVsid;isPaused=!1;firstFlush;debouncedFlush;loggerDebugLog;constructor(e){this.params=e,this.api=e.api,this.error$=e.error$,this.userSalt=e.userSalt,this.loggerDebugLog=e.debugLogger.createComponentLog(`stat logger`),this.firstFlush=A.debounceFn(()=>this.safeFlush(),this.params.config.firstFlushTime,{maxWait:this.params.config.firstFlushTime});let t=A.safeStorage.isPersistent()?this.params.config.flushMaxWait:0;this.debouncedFlush=A.debounceFn(()=>this.safeFlush(),this.params.config.flushDebounceTime,{maxWait:t}),this.subscription=this.api.authorized$.subscribe(e=>{e&&this.debouncedFlush()}),this.housekeepStorage()}isUrgent=e=>{let{operation:t}=e;return[`action_play`,`watch_coverage_record`,`watch_coverage_live`].includes(t)};safeFlush(){try{this.flush()}catch(e){this.error$.next({id:`LoggerError`,category:A.ErrorCategory.WTF,message:e?String(e):`Unknown logger error`,thrown:e})}}readFromStorage(){let e=A.safeStorage.get(j);try{return e?JSON.parse(e):{}}catch{}return{}}addToStorage(e){if(!this.userSalt){this.unsaltedStorage.push(e);return}let t=this.readFromStorage(),n=(t[this.userSalt]??[]).filter(de(this.params.config.storageExpiration));A.safeStorage.set(j,JSON.stringify({...t,[this.userSalt]:[...n,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],A.safeStorage.set(j,JSON.stringify(e))}housekeepStorage(){let e=this.readFromStorage();for(let[t,n]of Object.entries(e)){let r=n.filter(de(this.params.config.storageExpiration));r.length?e[t]=r:delete e[t],this.loggerDebugLog({message:`${n.length} retrieved from storage, ${r.length} of them actual`})}A.safeStorage.set(j,JSON.stringify(e))}log(e){this.addToStorage(e),!this.isPaused&&(this.isUrgent(e)?this.flush():this.lastVsid===e.custom.vsid?this.debouncedFlush():this.firstFlush(),this.lastVsid=e.custom.vsid)}flush({wantBeacon:e,clearStorage:t}={wantBeacon:!1,clearStorage:!0}){let n=this.getFromStorage();n.length!==0&&(this.api.authorized$.getValue()?(e&&this.params.config.useBeacon?(this.loggerDebugLog({message:`Flushing ${n.length} events through beacon`}),this.api.logBeacon(n)):(this.loggerDebugLog({message:`Flushing ${n.length} events`}),this.api.logRequest(n)),t&&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()}}var M=require(`@vkontakte/videoplayer-core`),pe=require(`@vkontakte/videoplayer-shared`),me=e=>e&&{[M.VideoQuality.INVARIANT]:`unknown`,[M.VideoQuality.Q_144P]:`mobile`,[M.VideoQuality.Q_240P]:`lowest`,[M.VideoQuality.Q_360P]:`low`,[M.VideoQuality.Q_480P]:`medium`,[M.VideoQuality.Q_576P]:`unknown`,[M.VideoQuality.Q_720P]:`high`,[M.VideoQuality.Q_1080P]:`fullhd`,[M.VideoQuality.Q_1440P]:`quadhd`,[M.VideoQuality.Q_2160P]:`ultrahd`,[M.VideoQuality.Q_4320P]:`unknown`}[e],he=e=>e&&{[M.HttpConnectionType.HTTP1]:`http1`,[M.HttpConnectionType.HTTP2]:`http2`,[M.HttpConnectionType.QUIC]:`http3`}[e],ge=e=>{if(e!==void 0)switch(e){case M.VideoFormat.MPEG:return`mp4`;case M.VideoFormat.DASH:case M.VideoFormat.DASH_LIVE:case M.VideoFormat.DASH_STREAMS:return`dash`;case M.VideoFormat.DASH_SEP:return`dash_sep`;case M.VideoFormat.DASH_ONDEMAND:return`ondemand_dash`;case M.VideoFormat.DASH_WEBM:case M.VideoFormat.DASH_LIVE_WEBM:return`webm`;case M.VideoFormat.DASH_WEBM_AV1:return`av1`;case M.VideoFormat.DASH_LIVE_CMAF:return`ondemand_dash_live`;case M.VideoFormat.HLS:case M.VideoFormat.HLS_LIVE:return`hls`;case M.VideoFormat.HLS_FMP4:return`hls_fmp4`;case M.VideoFormat.HLS_ONDEMAND:return`ondemand_hls`;case M.VideoFormat.HLS_LIVE_CMAF:return`ondemand_hls_live`;case M.VideoFormat.WEB_RTC_LIVE:return`webrtc`;default:return pe.assertNever(e)}},_e=(e,t)=>{if(t)return`minimal`;switch(e){case void 0:case M.Surface.NONE:case M.Surface.INLINE:return;case M.Surface.FULLSCREEN:return`fullscreen`;case M.Surface.SECOND_SCREEN:return`chromecast`;case M.Surface.PIP:return`pip`;case M.Surface.INVISIBLE:return`invisible`;default:return pe.assertNever(e)}},ve=e=>{switch(e){case`slow-2g`:return`poor`;case`2g`:return`poor`;case`3g`:return`good`;case`4g`:return`excellent`}};class ye{offset=void 0;constructor(e){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,t){let n=e-Date.now()-t/2;if(Math.abs(n)<1e3){this.offset=0;return}if(this.offset===void 0)this.offset=Math.round(n);else{let e=.2;this.offset=Math.round(e*n+(1-e)*this.offset)}}}var be=require(`@vkontakte/videoplayer-core`),N=require(`@vkontakte/videoplayer-shared`),xe=(e,t)=>new N.Observable(n=>{let r=new N.Subscription,i=N.merge(N.fromEvent(window,`beforeunload`),e.events.willDestruct$),a=new N.ValueSubject(void 0),o;r.add(e.info.isLive$.pipe(N.filterChanged()).subscribe(t=>{o&&(o.unsubscribe(),a.next(void 0)),o=t?e.info.liveTime$.pipe(N.map(e=>e&&e/1e3)).subscribe(a):e.info.position$.subscribe(a),r.add(o)}));let{playing$:s,paused$:c}=e.events,l=e.events.willSeek$.pipe(N.filter(()=>e.info.playbackState$.getValue()===be.PlaybackState.PLAYING)),u=e.events.seeked$.pipe(N.filter(()=>e.info.playbackState$.getValue()===be.PlaybackState.PLAYING)),d=!1,f=new N.Subject;r.add(l.subscribe(()=>{d||f.next(),d=!0})),r.add(u.subscribe(()=>d=!1));let p=new N.Subject,m=new N.Subject,h=N.merge(s,u,p),g=N.merge(c,f,i,e.events.looped$,m),_,v=()=>_=a.getValue(),y=()=>{let e=a.getValue();N.isNullable(_)||_===e||N.isNullable(e)||(n.next({from:_,to:e}),_=void 0)},b=()=>{m.next(),p.next()};if(r.add(h.subscribe(v)),r.add(g.subscribe(y)),t.forceInterval&&isFinite(t.forceInterval))if(t.watchCoverageTimeoutFix){let e,n=()=>{e!==void 0&&(window.clearTimeout(e),e=void 0)};r.add(h.subscribe(()=>{n(),e=window.setTimeout(b,t.forceInterval)})),r.add(g.subscribe(()=>n())),r.add(()=>n())}else{let e=0;r.add(h.subscribe(()=>e=window.setTimeout(b,t.forceInterval))),r.add(g.subscribe(()=>window.clearTimeout(e)))}return r}),P=require(`@vkontakte/videoplayer-core`),F=require(`@vkontakte/videoplayer-shared`),Se=(e,t,n)=>{let r=new F.Subject,i=r.pipe(F.debounce(0),F.filterChanged()),a=!1,o=!1,s=!1;return t(e.inPiP$,e=>{a=e,r.next(e?P.Surface.PIP:o?P.Surface.FULLSCREEN:s?P.Surface.INLINE:void 0)}),t(e.inFullscreen$,e=>{o=e,r.next(e?P.Surface.FULLSCREEN:a?P.Surface.PIP:s?P.Surface.INLINE:void 0)}),n&&t(n.info.surface$,e=>{switch(e){case P.Surface.SECOND_SCREEN:case P.Surface.NONE:case P.Surface.INLINE:!o&&!a&&(e===P.Surface.INLINE&&(s=!0),r.next(e));break}}),{surface$:i}},Ce=`_one-stat_deviceId`,I=()=>{let e=new w.Subscription;return{subscription:e,subscribe:(t,n)=>{t&&e.add(t.subscribe(n))}}};class we{api;logger;config;subscription=new w.Subscription;beforeunloadSubscription;timeSynchronisation;debugLogger=new ie.Logger;oneStatDebugLog=this.debugLogger.createComponentLog(`onestat`);loopCounter=0;disabled=!1;experimental;get vsid$(){return new w.ValueSubject(E.getVSID())}isid$=new w.ValueSubject(void 0);zenUid$=new w.ValueSubject(void 0);statContext;isEmbed;embedParent;uiEvents;player;seekAction$=new w.ValueSubject(`unknown`);deviceId;constructor(e,t){this.statContext=e,this.config=ne(t.config??{}),w.isNonNullable(t.apiEnv)&&(this.config.apiEnv=t.apiEnv),this.config.synchronizeTime&&(this.timeSynchronisation=new ye);let n=new w.Subject;this.experimental={error$:n};let r=w.safeStorage.get(Ce);this.statContext.deviceId?this.deviceId=this.statContext.deviceId:r?this.deviceId=r:(this.deviceId=re(),w.safeStorage.set(Ce,this.deviceId)),this.resetViewSession(),t.useIsid&&this.isid$.next(t.isid??T()),this.zenUid$.next(t.zenUid);let i=new ue({config:this.config,error$:n,timeSynchronisation:this.timeSynchronisation});this.api=new ce({config:this.config,apiTransport:i,refreshAuthToken:t.refreshAuthToken,mobile:this.statContext.mobile??!1,deviceId:this.deviceId,error$:n,vktvVersion:t.vktvVersion}),this.logger=new fe({config:this.config,debugLogger:this.debugLogger,api:this.api,error$:n,userSalt:t.userSalt});let{isEmbed:a,topOrigin:o}=ie.detectEmbed();this.isEmbed=a,this.embedParent=o?new URL(o).hostname:void 0,this.subscribe()}updateContext(e){this.statContext={...this.statContext,...e}}attachTo(e){let t=new w.Subscription,n=(e,n)=>t.add(e.subscribe(n));n(e.events.willStart$,()=>{let t=e.info.position$.getValue();this.logActionPlay({position:t}),this.statContext.projectId&&this.logActionPlayInteractive()}),n(e.events.looped$,()=>{this.resetViewSession(),++this.loopCounter>this.config.maxLoops&&(this.disabled=!0),this.logActionPlay({position:e.info.position$.getValue()})}),n(e.events.seeked$,()=>{let t=this.seekAction$.getValue();this.logSeek({action:t===`rich`?`slider`:t,time:e.info.position$.getValue()}),this.seekAction$.next(`unknown`)}),n(e.events.paused$,()=>{this.logPause({position:e.info.position$.getValue()})}),n(e.events.willResume$,()=>{this.logPlay()}),n(e.events.started$,()=>{this.statContext.clip&&this.logWatchCoverageRecord({start:0,end:0})}),n(e.events.playing$,()=>{this.logPlaying()}),n(xe(e,{forceInterval:this.config.watchCoverageInterval,watchCoverageTimeoutFix:this.config.watchCoverageTimeoutFix}),t=>{let n=e.info.isLive$.getValue(),r=e.info.atLiveEdge$.getValue(),i={start:parseFloat(t.from.toFixed(3)),end:parseFloat(t.to.toFixed(3))};if(r){let t=e.info.liveLatency$.getValue()??0,n=e.info.currentBuffer$.getValue()?.end??0,r=e.info.liveBufferTime$.getValue()??0,a=Math.round((t-(n-r))*1e3),o=Math.round(t*1e3);a&&o&&(i.latency=a,i.bufferLatency=o)}n?this.logWatchCoverageLive(i):this.logWatchCoverageRecord(i)});let r;n(e.info.isStalled$,e=>{e?r=w.now():(w.isNonNullable(r)&&this.logEmptyBuffer({duration:w.now()-r}),r=void 0)});let i=!1;t.add(e.events.fatalError$.pipe(w.once()).subscribe(()=>i=!0)),n(e.events.willStop$,()=>{if(e.info.isStalled$.getValue()){let e=w.isNonNullable(r)?w.now()-r:void 0;this.logCloseAtEmptyBuffer({duration:e??0}),r=void 0}else i||this.logActionStop()}),n(e.events.managedError$,({id:e})=>{this.logError({fatal:!1,errorType:e})}),n(e.events.fatalError$,({id:e})=>{this.logError({fatal:!0,errorType:e})});let a,o,s=!1;n(e.events.firstBytes$,e=>{a=w.now(),this.logFirstBytes({time:e})}),n(e.events.willStart$,()=>o=w.now()),n(e.info.currentBuffer$,e=>{!s&&e&&e.end-e.start>0&&w.isNonNullable(a)&&(this.logPlayerReady({duration:w.now()-a}),s=!0)}),n(e.events.firstFrame$,()=>{w.isNonNullable(a)&&!s&&(this.logPlayerReady({duration:w.now()-a}),s=!0),w.isNonNullable(o)&&this.logFirstFrame({time:w.now()-o})});let c;n(e.info.currentVideoStream$,e=>{e&&(c&&e.id!==c&&this.logTrackSwitch(e),c=e.id)});let l;n(e.info.currentAudioStream$,e=>{e&&(l&&e.id!==l&&this.logTrackSwitch(e),l=e.id)}),n(e.info.atLiveEdge$,e=>this.updateContext({liveEdge:e})),n(w.combine({muted:e.info.muted$,volume:e.info.volume$}),({muted:e,volume:t})=>this.updateContext({audible:!e&&t>0})),n(e.info.currentQuality$,e=>{let t=me(e);this.updateContext({quality:t}),t&&this.logQuality(t)}),n(e.info.isAutoQualityEnabled$,e=>this.updateContext({autoQuality:e})),n(e.info.currentFormat$,e=>this.updateContext({contentType:ge(e)})),n(e.info.currentPlaybackRate$,e=>this.updateContext({rate:e})),n(e.info.is3DVideo$,e=>this.updateContext({is3d:e}));let u;return n(e.info.hostname$,e=>{let t=u!==void 0&&u!==e;this.updateContext({cdnHostname:e,failover:t}),t&&this.logFailover(e),u=e}),n(e.info.throughputEstimation$,e=>this.updateContext({downloadSpeed:e})),n(e.info.httpConnectionType$,e=>{this.statContext.firstConnectionType||this.updateContext({firstConnectionType:he(e)}),this.updateContext({connectionType:he(e)})}),n(e.info.httpConnectionReused$,e=>{w.isNullable(this.statContext.firstConnectionReused)&&this.updateContext({firstConnectionReused:e}),this.updateContext({connectionReused:e})}),n(e.info.surface$,e=>{this.uiEvents||this.updateContext({mode:_e(e,this.statContext.isPreviewPlayerView)})}),n(w.combine({current:e.info.currentTextTrack$,available:e.info.availableTextTracks$}),({current:e,available:t})=>{let n=t.find(({id:t})=>t===e),r=n&&(n.isAuto?`${n.language}_auto`:n.language);this.updateContext({subtitles:r?.split(`.`)[0]})}),this.player=e,this.uiEvents&&this.attachToUi(this.uiEvents),this.resubscribeBeforeunload(),this.subscription.add(t),t}attachToUi(e){this.uiEvents=e;let{subscription:t,subscribe:n}=I();if(!this.player)return t;n(e.actionRewind$,()=>{this.player&&(this.resetViewSession(),this.logActionPlay({position:this.player.info.position$.getValue()}))}),n(e.actionSeek$,this.seekAction$);let{surface$:r}=Se(this.uiEvents,n,this.player);return n(r,e=>{this.updateContext({mode:_e(e,this.statContext.isPreviewPlayerView)})}),n(e.actionSetSubtitle$,e=>this.updateContext({subtitles:e?.split(`.`)[0]})),n(e.nextMovie$,e=>this.logNextMovie(e)),this.resubscribeBeforeunload(),this.subscription.add(t),t}attachToAds(e){let{subscription:t,subscribe:n}=I();return n(e.slotRequested$,()=>this.logAdSlotRequest()),n(e.started$,e=>this.logAdStarted(e)),n(e.paused$,()=>this.logAdPaused()),n(e.resumed$,()=>this.logAdResumed()),n(e.ended$,()=>this.logAdEnded()),n(e.skipped$,()=>this.logAdSkipped()),n(e.clicked$,()=>this.logAdClicked()),n(e.error$,e=>this.logError({errorType:e,fatal:!1})),this.resubscribeBeforeunload(),this.subscription.add(t),t}attachToInteractive(e){let{subscription:t,subscribe:n}=I();return n(e.click$,e=>this.logInterfaceClick(e)),n(e.nextMovie$,e=>this.logNextMovie(e)),this.resubscribeBeforeunload(),this.subscription.add(t),t}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`}),E.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 t=this.timeSynchronisation?.getOffset()??0,n=e.start+t,r=e.end+t;this.log({operation:`watch_coverage_live`,param:`${n}-${r}`},{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(w.merge(w.fromEvent(e,`change`),w.observableFrom([`init`])).subscribe(()=>this.updateContext({network:ve(e.effectiveType)}))),this.config.debugLog&&this.debugLogger.log$.subscribe(e=>{console.debug(`%c stat `,`background:#fa6470;`,`component: ${e.component}.`,e.message)})}resubscribeBeforeunload(){this.beforeunloadSubscription?.unsubscribe(),this.beforeunloadSubscription=w.fromEvent(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,t={}){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 n=this.createLogItem(e,t);this.logger.log(n)}createLogItem({operation:e,param:t,time:n},r={}){let i=this.timeSynchronisation?.now()??w.now(),a=this.vsid$.getValue();w.assertNonNullable(a);let o=this.isid$.getValue(),s=e===`empty_buffer`||e===`close_at_empty_buffer`?this.statContext.connectionType:this.statContext.firstConnectionType,c=this.statContext.firstConnectionReused,l,u;if(this.isEmbed||this.statContext.place===`embed`){l=this.embedParent;let e=[...new URLSearchParams(location.search).entries()].filter(([e,t])=>this.config.embedUrlParams.includes(e));u=new URLSearchParams(e).toString()}else if(this.statContext.place===`direct`){let e=this.statContext.refDomain||document.referrer;l=e&&d.urlCanParsePolyfilled(URL,e)?new URL(e).hostname:e,u=location.href.substring(0,1024)}let f={vsid:a,isid:o,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:t,vk_app_id:this.statContext.vkAppId,track_code:this.statContext.trackCode,connection_type:s,connection_reused:c===!0?1:c===!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:l,direct_url:u,rate:this.statContext.rate===1||w.isNullable(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,...r};for(let e of this.config.disabledCustomFields)delete f[e];return{operation:e,type:1,time:n,network:this.statContext.network,timestamp:i,custom:f}}}var Te={};l(Te,{VERSION:()=>D,ThinOneStat:()=>et,ActionSeekType:()=>Oe});var L=require(`@vkontakte/videoplayer-shared`),R=require(`@vkontakte/videoplayer-core`),Ee=require(`@vkontakte/videoplayer-shared`),De;(e=>{e.AUTO=`auto`,e.AUTO_POOR=`auto_poor`,e.AUTO_RICH=`auto_rich`})(De||={});var Oe;(e=>{e.SLIDER=`slider`,e.RICH=`rich`,e.DOUBLE_TAP=`double_tap`,e.TIME_CODE=`time_code`,e.EPISODE=`episode`,e.REWIND=`rewind`,e.LIVE=`live`,e.UNKNOWN=`unknown`})(Oe||={});var ke=`CIOPGQJGDIHBABABA`,Ae={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:``},je={apiKey:ke,apiEnv:`okcdn`,apiBaseUrl:null,requestRetryCount:1,useVsid64:!1,firstFlushTime:5e3,flushDebounceTime:1e4,flushMaxWait:6e4,storageExpiration:2160*60*1e3,watchCoverageHeartbeatInterval:3e4,disabledEvents:[],disabledParams:[],synchronizeTime:!0,useBeacon:!1,alwaysSendDesktop:!1,watchedNDefaultTargetDuration:1e3,telemetryInterval:3e4,downloadBytesMaxTime:3e4},Me=e=>Ee.fillWithDefault(e,je),z=require(`@vkontakte/videoplayer-shared`);class Ne{authorized$;params;authToken;sessionKey;authorizePromise;refreshAuthTokenPromise;consequentAuthErrors;backoffTimeoutId;constructor(e){this.params=e,this.authorized$=new z.ValueSubject(!1),this.consequentAuthErrors=0}async authorize(e){return this.authToken=e??await this.refreshAuthToken(),this.authorizeWithBackoff()}logBeacon(e){let t=this.createLogParams(e),n=this.sessionKey;n&&(this.params.apiTransport.sendBeacon(`log.logUvStat`,t,n)||this.logRequest(e).catch(()=>{}))}async logRequest(e){let t=`log.logUvStat`,n=this.createLogParams(e),r={},i=this.sessionKey??await this.authorizeWithBackoff();if(!i)return;let a=async(e,o=this.params.config.requestRetryCount)=>{try{return await this.params.apiTransport.sendRequest(t,n,i,r)}catch(n){if(!n||!(`error_code`in n)){this.params.error$.next({id:`logRequestUnknown`,category:z.ErrorCategory.NETWORK,message:`Unknown ${t} error`,thrown:n});return}let r=n?.error_code;switch(r){case 102:case 103:case 104:return this.authorized$.next(!1),this.sessionKey=await this.authorizeWithBackoff(),o>0?a(e,o-1):void 0;case 401:return this.authorized$.next(!1),this.authToken=await this.refreshAuthToken(),this.sessionKey=await this.authorizeWithBackoff(),o>0?a(e,o-1):void 0;default:this.params.error$.next({id:`LogRequest#${r}`,category:z.ErrorCategory.EXTERNAL_API,message:`${t} error`,data:n});return}}};return a(e)}destroy(){window.clearTimeout(this.backoffTimeoutId),this.backoffTimeoutId=0}async refreshAuthToken(){if(this.params.refreshAuthToken)return 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:${D}`,platform:e[0].platform,product:e[0].product,events:e})}}authorizeWithBackoff(){if(!this.consequentAuthErrors)return this.doAuthorize();let e=z.getExponentialDelay(this.consequentAuthErrors);return new Promise(t=>{this.backoffTimeoutId||=window.setTimeout(async()=>{try{t(await this.doAuthorize())}catch(e){this.params.error$.next({id:`AuthorizeBackoff`,category:z.ErrorCategory.NETWORK,message:`Otherwise unhandled error in authorization`,thrown:e})}finally{this.backoffTimeoutId=0}},e)})}doAuthorize(){if(this.authorizePromise)return this.authorizePromise;this.sessionKey=void 0,this.authorized$.next(!1);let e={session_data:{version:2,device_id:this.params.deviceId,client_version:D.split(`-`)[0],client_type:`SDK_JS`}};return this.authToken!==void 0&&(e.session_data.auth_token=this.authToken,e.session_data.version=3),this.authorizePromise=this.params.apiTransport.sendRequest(`auth.anonymLogin`,e).then(e=>((!e||!e.session_key)&&this.params.error$.next({id:`AuthorizeFailed`,category:z.ErrorCategory.EXTERNAL_API,message:`No session key`,data:e}),this.sessionKey=e?.session_key??void 0,this.sessionKey)).catch(async e=>{this.sessionKey=void 0;let t=e?.error_code;switch(t){case 401:return this.authToken=await this.refreshAuthToken(),this.authorizeWithBackoff()}t?this.params.error$.next({id:`Authorize#${t}`,category:z.ErrorCategory.EXTERNAL_API,message:`authorize error`,data:e}):this.params.error$.next({id:`AuthorizeUnknown`,category:z.ErrorCategory.NETWORK,message:`authorize error`,thrown:e})}).finally(()=>{this.authorizePromise=void 0,this.consequentAuthErrors=this.sessionKey?0:this.consequentAuthErrors+1,this.authorized$.next(this.sessionKey!==void 0)}),this.authorizePromise}}var Pe=require(`@vkontakte/videoplayer-shared`),B=require(`@vkontakte/videoplayer-shared`);class Fe{params;apiKey;apiBaseUrl;apiEnv;isApiBaseUrlFetched;timeSynchronisation;constructor(e){this.params=e,this.apiKey=e.config.apiKey,this.apiEnv=e.config.apiEnv,this.apiBaseUrl=e.config.apiBaseUrl??Ae[this.apiEnv],this.timeSynchronisation=e.timeSynchronisation,this.isApiBaseUrlFetched=!1}sendBeacon(e,t,n){if(!window.Blob||!window.navigator.sendBeacon)return!1;let r=this.prepareQueryParams({method:e,queryParams:t,sessionKey:n}),i=new window.Blob([r.toString()],{type:`application/x-www-form-urlencoded`});try{return window.navigator.sendBeacon(`${this.apiBaseUrl}/fb.do`,i)}catch(n){this.params.error$.next({id:`OneStat:ApiTransport:sendBeacon`,category:B.ErrorCategory.NETWORK,message:`Unhandled beacon error`,thrown:n,data:{method:e,params:t}})}return!1}async sendRequest(e,t,n,r){let i=B.now(),a=r=>{if(r instanceof TypeError&&[`Failed to fetch`,`NetworkError when attempting to fetch resource.`].includes(r.message)){this.params.error$.next({id:`Network`,category:B.ErrorCategory.NETWORK,message:`Request failed`,thrown:r});return}this.params.error$.next({id:`ThinOneStat:ApiTransport:sendRequest`,category:B.ErrorCategory.NETWORK,message:`Unhandled request error`,thrown:r,data:{method:e,params:t,sessionKey:n,time:B.now()-i}})};return this.apiBaseUrl=await this.resolveApiBaseUrl(),Pe.fetchPolyfilled(`${this.apiBaseUrl}/fb.do`,{method:`post`,headers:{"Content-type":`application/x-www-form-urlencoded`,...r},body:this.prepareQueryParams({method:e,queryParams:t,sessionKey:n})}).then(e=>{let t=Number(e.headers.get(`content-length`))===0,n=new Date(e.headers.get(`date`)??``).getTime(),r=B.now()-i;if(isFinite(n)&&this.timeSynchronisation?.addServerTime(n,r),!t)return e.json().then(e=>Object.prototype.hasOwnProperty.call(e,`error_msg`)?Promise.reject(e):e,a)},a)}async resolveApiBaseUrl(){if(this.apiEnv!==`auto`||this.isApiBaseUrlFetched)return this.apiBaseUrl;try{let e=atob(`aHR0cHM6Ly9kbnMuZ29vZ2xlL3Jlc29sdmU/bmFtZT12aWRlby5fZW5kcG9pbnQub2sucnUmdHlwZT1UWFQ=`),t=(await(await Pe.fetchPolyfilled(e,{method:`GET`,mode:`cors`,cache:`no-cache`})).json())?.Answer[0]?.data;if(!t)throw Error(`Wrong DNS response`);return t}catch(e){return this.params.error$.next({id:`ThinOneStat:ApiTransport:resolveApiBaseUrl`,category:B.ErrorCategory.NETWORK,message:`Unhandled resolve api base url error`,thrown:e}),Ae.vk_alias}finally{this.isApiBaseUrlFetched=!0}}prepareQueryParams(e){let t=new URLSearchParams({format:`JSON`,method:e.method,application_key:this.apiKey});return e.sessionKey!==void 0&&t.append(`session_key`,e.sessionKey),Object.entries(e.queryParams).forEach(([e,n])=>t.append(e,typeof n==`string`?n:JSON.stringify(n))),t}}var V=require(`@vkontakte/videoplayer-shared`),H=`thinonestat_events`,U=e=>t=>t.client_time+e>=V.now();class Ie{params;api;error$;subscription;userSalt;unsaltedStorage=[];lastVsid;isPaused=!1;firstFlush;debouncedFlush;loggerDebugLog;constructor(e){this.params=e,this.api=e.api,this.error$=e.error$,this.userSalt=e.userSalt,this.loggerDebugLog=e.debugLogger.createComponentLog(`stat logger`),this.firstFlush=V.debounceFn(()=>this.safeFlush(),this.params.config.firstFlushTime,{maxWait:this.params.config.firstFlushTime});let t=V.safeStorage.isPersistent()?this.params.config.flushMaxWait:0;this.debouncedFlush=V.debounceFn(()=>this.safeFlush(),this.params.config.flushDebounceTime,{maxWait:t}),this.subscription=this.api.authorized$.subscribe(e=>{e&&this.debouncedFlush()}),this.housekeepStorage()}isUrgent=e=>{let{event_name:t}=e;return[`watch_coverage`,`watch_coverage_live`,`watched_n`,`playback_started`].includes(t)};safeFlush(){try{this.flush()}catch(e){this.error$.next({id:`LoggerError`,category:V.ErrorCategory.WTF,message:String(e)||`Unknown logger error`,thrown:e})}}readFromStorage(){let e=V.safeStorage.get(H);try{return e?JSON.parse(e):{}}catch{}return{}}addToStorage(e){if(!this.userSalt){this.unsaltedStorage.push(e);return}let t=this.readFromStorage(),n=(t[this.userSalt]??[]).filter(U(this.params.config.storageExpiration));V.safeStorage.set(H,JSON.stringify({...t,[this.userSalt]:[...n,e]}))}getFromStorage(){return this.userSalt?(this.readFromStorage()[this.userSalt]??[]).filter(U(this.params.config.storageExpiration)):this.unsaltedStorage}markStorageSent(){if(!this.userSalt){this.unsaltedStorage=[];return}let e=this.readFromStorage();delete e[this.userSalt],V.safeStorage.set(H,JSON.stringify(e))}housekeepStorage(){let e=this.readFromStorage();for(let[t,n]of Object.entries(e)){let r=n.filter(U(this.params.config.storageExpiration));r.length?e[t]=r:delete e[t],this.loggerDebugLog({message:`${n.length} retrieved from storage, ${r.length} of them actual`})}V.safeStorage.set(H,JSON.stringify(e))}log(e){this.addToStorage(e),!this.isPaused&&(this.isUrgent(e)?this.flush():this.lastVsid===e.vsid?this.debouncedFlush():this.firstFlush(),this.lastVsid=e.vsid)}flush({wantBeacon:e,clearStorage:t}={wantBeacon:!1,clearStorage:!0}){let n=this.getFromStorage();n.length!==0&&(this.api.authorized$.getValue()?(e&&this.params.config.useBeacon?(this.loggerDebugLog({message:`Flushing ${n.length} events through beacon`}),this.api.logBeacon(n)):(this.loggerDebugLog({message:`Flushing ${n.length} events`}),this.api.logRequest(n)),t&&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 Le(){let e=`0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz`.split(``),t=Array(36),n=0,r,i;for(i=0;i<36;i++)i===8||i===13||i===18||i===23?t[i]=`-`:i===14?t[i]=`4`:(n<=2&&(n=33554432+Math.random()*16777216|0),r=n&15,n>>=4,t[i]=e[i===19?r&3|8:r]);return t.join(``)}class Re{offset=void 0;constructor(e){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,t){let n=e-Date.now()-t/2;if(Math.abs(n)<1e3){this.offset=0;return}if(this.offset===void 0)this.offset=Math.round(n);else{let e=.2;this.offset=Math.round(e*n+(1-e)*this.offset)}}}var ze=require(`@vkontakte/videoplayer-core`),W=require(`@vkontakte/videoplayer-shared`),Be=(e,t,n)=>new W.Observable(r=>{let i=new W.Subscription,a=new W.ValueSubject(void 0),o;i.add(e.info.isLive$.pipe(W.filterChanged()).subscribe(t=>{o&&(o.unsubscribe(),a.next(void 0)),o=t?e.info.liveTime$.pipe(W.filterChanged()).subscribe(a):e.info.position$.subscribe(a),i.add(o)}));let{playing$:s,paused$:c,ended$:l,looped$:u}=e.events,d=e.events.willSeek$.pipe(W.filter(()=>e.info.playbackState$.getValue()===ze.PlaybackState.PLAYING)),f=e.events.seeked$.pipe(W.filter(()=>e.info.playbackState$.getValue()===ze.PlaybackState.PLAYING)),p=!1,m=new W.Subject;i.add(d.subscribe(()=>{p||m.next(),p=!0})).add(f.subscribe(()=>p=!1));let h=W.merge(W.fromEvent(W.getWindow(),`beforeunload`),e.events.willDestruct$),g,_=()=>g=a.getValue(),v=()=>{let e=a.getValue();W.isNullable(g)||W.isNullable(e)||g===e||(r.next({from:g,to:e}),g=void 0)},y=new W.Subject,b=new W.Subject,ee=W.merge(s,f,y),x=W.merge(c,m,h,l,u,b),S=t.started$&&t.ended$?W.merge(ee,t.ended$):ee,C=t.started$&&t.ended$?W.merge(x,t.started$):x;if(i.add(S.subscribe(_)).add(C.subscribe(v)),n.heartbeatInterval&&isFinite(n.heartbeatInterval)){let e=[],t=()=>{b.next(),y.next()};i.add(S.subscribe(()=>{let r=W.getWindow().setTimeout(t,n.heartbeatInterval);e.push(r)})).add(C.subscribe(()=>{e.forEach(e=>{W.getWindow().clearTimeout(e)}),e=[]}))}return i}),Ve=require(`@vkontakte/videoplayer-core`),He=require(`@vkontakte/videoplayer-shared`),Ue=(e,t)=>new He.Observable(n=>{let r=new Ve.Subscription;return r.add(He.merge(e.info.position$,e.info.liveTime$).subscribe(()=>{let e=t.getTotalViewTime();e>=t.targetDuration&&(n.next({target_duration:t.targetDuration,current_tvt:e}),r.unsubscribe())})),r}),We=require(`@vkontakte/videoplayer-core`),G=require(`@vkontakte/videoplayer-shared`),Ge=(e,{maxTimeWindow:t})=>new G.Observable(n=>{let r=new We.Subscription,i={maxBytesThreshold:100*1024*1024,minBytesThreshold:100*1024,maxTimeWindow:t,minTimeWindow:2e3},a={bytes:0,startTime:0,lastEmitTime:0,timeoutId:0},o=()=>{a.timeoutId&&=(G.getWindow().clearTimeout(a.timeoutId),null)},s=()=>{a.bytes=0,a.startTime=0,a.lastEmitTime=0,o()},c=e=>{if(a.bytes<i.minBytesThreshold||e-a.lastEmitTime<i.minTimeWindow&&a.lastEmitTime>0)return!1;let t=(a.startTime>0?e-a.startTime:0)>=i.maxTimeWindow,n=a.bytes>=i.maxBytesThreshold;return t||n},l=(e=!1)=>{let t=Date.now();if(!e&&!c(t))return;o();let r=a.startTime>0?t-a.startTime:Math.max(i.minTimeWindow,1),l=a.bytes/(r/1e3);n.next({download_bytes:Math.round(a.bytes),download_speed:Math.round(l)}),a.lastEmitTime=t,s()},u=()=>{if(o(),a.startTime>0&&a.bytes>=i.minBytesThreshold){let e=Date.now()-a.startTime,t=i.maxTimeWindow-e;t>100?a.timeoutId=G.getWindow().setTimeout(()=>{a.timeoutId=null,l()},t):t>0&&l()}};return r.add(e.info.httpDownloadMetrics$.pipe(G.filter(e=>e!==void 0)).subscribe(e=>{let t=Date.now();a.startTime===0&&(a.startTime=t),a.bytes+=e.bytes,c(t)?l():u()})),r.add(()=>{if(o(),a.bytes>0){let e=Date.now(),t=a.startTime>0?e-a.startTime:i.minTimeWindow,r=a.bytes/(t/1e3);n.next({download_bytes:Math.round(a.bytes),download_speed:Math.round(r)})}s()}),r}),K=require(`@vkontakte/videoplayer-shared`),Ke=e=>new K.Observable(t=>{let n=new K.Subscription,r=0,i=1,a=0,o=!1,s=!1,c=()=>{if(!o)return;let e=Date.now();a+=(e-r)*i,r=e},l=()=>{(!o||s)&&(r=Date.now(),o=!0,s=!1)},u=()=>{o&&=(c(),!1)},d=()=>{o&&(c(),o=!1,s=!0)},f=e=>{o&&c(),i=e,r=Date.now()},{started$:p,playing$:m,paused$:h,willSeek$:g,ended$:_,willDestruct$:v}=e.events,{currentPlaybackRate$:y}=e.info;return n.add(g.subscribe(d)).add(K.merge(p,m).subscribe(l)).add(K.merge(h,_,v).subscribe(u)).add(y.subscribe(f)),t.next(()=>{let e=a;return o&&(e+=(Date.now()-r)*i),e}),n}),q=require(`@vkontakte/videoplayer-shared`),qe=(e,t)=>new q.Observable(n=>{let r=new q.Subscription,i=0;return r.add(q.merge(e.info.position$,e.info.liveTime$).subscribe(()=>{let e=t.getTotalViewTime();e>i&&Math.floor(e/t.interval)>Math.floor(i/t.interval)&&(i=e,n.next())})),r}),Je=require(`@vkontakte/videoplayer-shared`),J=require(`@vkontakte/videoplayer-core`),Ye=e=>e&&{[J.HttpConnectionType.HTTP1]:`http1`,[J.HttpConnectionType.HTTP2]:`http2`,[J.HttpConnectionType.QUIC]:`http3`}[e],Y=e=>{if(e!==void 0)switch(e){case J.VideoFormat.MPEG:return`MP4`;case J.VideoFormat.DASH:case J.VideoFormat.DASH_LIVE:return`DASH`;case J.VideoFormat.DASH_SEP:return`DASH_SEP`;case J.VideoFormat.DASH_ONDEMAND:return`ONDEMAND_DASH`;case J.VideoFormat.HLS_ONDEMAND:return`ONDEMAND_HLS`;case J.VideoFormat.HLS:case J.VideoFormat.HLS_LIVE:return`HLS`;case J.VideoFormat.HLS_FMP4:return`HLS_FMP4`;case J.VideoFormat.DASH_WEBM:case J.VideoFormat.DASH_LIVE_WEBM:return`WEBM`;case J.VideoFormat.DASH_LIVE_CMAF:return`ONDEMAND_DASH_LIVE`;case J.VideoFormat.HLS_LIVE_CMAF:return`ONDEMAND_HLS_LIVE`;case J.VideoFormat.WEB_RTC_LIVE:return`WEBRTC`;case J.VideoFormat.DASH_WEBM_AV1:return`AV1`;case J.VideoFormat.DASH_STREAMS:return`MULTI_DASH`;default:return Je.assertNever(e)}},X=e=>{if(e!==void 0)switch(e){case J.VideoQuality.Q_144P:return`144p`;case J.VideoQuality.Q_240P:return`240p`;case J.VideoQuality.Q_360P:return`360p`;case J.VideoQuality.Q_480P:return`480p`;case J.VideoQuality.Q_720P:return`720p`;case J.VideoQuality.Q_1080P:return`1080p`;case J.VideoQuality.Q_1440P:return`1440p`;case J.VideoQuality.Q_2160P:return`2160p`;case J.VideoQuality.INVARIANT:case J.VideoQuality.Q_576P:case J.VideoQuality.Q_4320P:return`UNKNOWN`;default:return Je.assertNever(e)}},Xe=e=>{if(e!==void 0)switch(e){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}},Z=(e,t,n)=>{if(e&&t)switch(e){case J.VideoFormat.MPEG:return n&&t[e]&&t[e][n];default:return t[e]?.url}},Ze=(e,t=!1)=>{if(t)return`minimal`;switch(e){case void 0:case J.Surface.NONE:return;case J.Surface.INLINE:return`inline`;case J.Surface.FULLSCREEN:return`fullscreen`;case J.Surface.SECOND_SCREEN:return`chromecast`;case J.Surface.PIP:return`pip_external`}},Q=e=>{switch(e){case void 0:return;case J.Surface.INVISIBLE:return`background`;default:return`foreground`}},Qe=`_thin-one-stat_deviceId`,$e=()=>{let e=new L.Subscription;return{subscription:e,subscribe:(t,n)=>{t&&e.add(t.subscribe(n))}}};class et{api;logger;config;subscription;beforeunloadSubscription;timeSynchronisation;statContext;deviceId;targetDuration;debugLogger=new L.Logger;thinOneStatDebugLog=this.debugLogger.createComponentLog(`ThinOneStat`);eventNumber=1;isStarted;wasPaused;isLive;position;cdnHostname;isEmbed;embedHostname;connectionType;connectionReused;player;playerSize={width:0,height:0};currentSubtitle;userQuality;downloadQuality;downloadSpeed;networkType;uiEvents;seekAction$=new L.ValueSubject(`unknown`);get vsid$(){return new L.ValueSubject(E.getVSID())}isid$=new L.ValueSubject(void 0);getTotalViewTime=()=>0;constructor(e,t){this.statContext=e,this.config=Me(t.config??{}),this.subscription=new L.Subscription,this.config.synchronizeTime&&(this.timeSynchronisation=new Re);let n=new L.Subject,r=L.safeStorage.get(Qe);this.statContext.deviceId?this.deviceId=this.statContext.deviceId:r?this.deviceId=r:(this.deviceId=Le(),L.safeStorage.set(Qe,this.deviceId)),this.statContext.targetDuration?this.targetDuration=this.statContext.targetDuration:this.targetDuration=this.config.watchedNDefaultTargetDuration,this.resetViewSession(),t.useIsid&&this.isid$.next(t.isid??T());let i=new Fe({error$:n,config:this.config,timeSynchronisation:this.timeSynchronisation});this.api=new Ne({config:this.config,apiTransport:i,error$:n,deviceId:this.deviceId,refreshAuthToken:t.refreshAuthToken}),this.logger=new Ie({config:this.config,debugLogger:this.debugLogger,api:this.api,error$:n,userSalt:t.userSalt});let{isEmbed:a,topOrigin:o}=L.detectEmbed();this.isEmbed=a,this.embedHostname=o?new URL(o).hostname:void 0}authorize(e){return this.api.authorize(e)}updateContext(e){this.statContext={...this.statContext,...e}}attachTo(e,t){let n=new L.Subscription,r=(e,t)=>n.add(e.subscribe(t));r(Ke(e),e=>{this.getTotalViewTime=e}),r(e.info.isLive$,e=>this.isLive=e),r(e.info.hostname$.pipe(L.filter(e=>e!==void 0)),e=>{this.cdnHostname=e});let i;r(L.combine({hostname:e.info.hostname$,connectionType:e.info.httpConnectionType$,connectionReused:e.info.httpConnectionReused$}).pipe(L.filter(({hostname:e})=>e!==void 0),L.filter(({connectionType:e})=>e!==void 0),L.filter(({connectionReused:e})=>e!==void 0)),({hostname:t,connectionType:n,connectionReused:r})=>{if(i!==void 0&&i!==t){let i={cdn_host:t,connection_type:Ye(n),connection_reused:r,content_type:Y(e.info.currentFormat$.getValue())};this.logFailover(i)}this.cdnHostname=i=t}),r(e.info.httpConnectionType$,e=>{this.connectionType=Ye(e)}),r(e.info.httpConnectionReused$,e=>{this.connectionReused=e}),r(Be(e,t,{heartbeatInterval:this.config.watchCoverageHeartbeatInterval}),t=>{let n={watch_interval:`${Math.round(t.from*1e3)}-${Math.round(t.to*1e3)}`,in_history:!!this.statContext.inHistory,content_type:Y(e.info.currentFormat$.getValue()),playback_quality:X(e.info.currentQuality$.getValue()),recom_info:this.statContext.recomInfo};if(!e.info.isLive$.getValue())this.logWatchCoverage(n);else{let t=e.info.atLiveEdge$.getValue();this.logWatchCoverageLive({...n,live:!!t})}}),r(qe(e,{interval:this.statContext.telemetryInterval??this.config.telemetryInterval,getTotalViewTime:this.getTotalViewTime}),()=>{this.logTelemetry(this.collectTelemetryData())}),r(Ue(e,{targetDuration:this.targetDuration,getTotalViewTime:this.getTotalViewTime}),e=>{this.logWatchedN(e)}),r(e.events.willReady$,()=>{if(this.statContext.preload){let t=e.info.currentFormat$.getValue(),n=e.info.availableSources$.getValue(),r=e.info.currentBuffer$.getValue(),i=e.info.currentQuality$.getValue(),a={target_buffer_time:this.calcBufferTime(r),playback_url:Z(t,n,i),playback_quality:X(i)};this.logPreloadStarted(a)}}),r(L.combine({manifestRequested$:e.events.manifestRequested$,connectionType:e.info.httpConnectionType$,connectionReused:e.info.httpConnectionReused$}).pipe(L.filter(({connectionType:e})=>e!==void 0),L.filter(({connectionReused:e})=>e!==void 0),L.once()),()=>{let t={playback_url:Z(e.info.currentFormat$.getValue(),e.info.availableSources$.getValue(),e.info.currentQuality$.getValue()),cdn_host:this.cdnHostname,connection_type:this.connectionType,connection_reused:this.connectionReused};this.logManifestRequest(t)}),r(L.combine({firstBytesManifest:e.events.firstBytesManifest$,connectionType:e.info.httpConnectionType$,connectionReused:e.info.httpConnectionReused$}).pipe(L.filter(({connectionType:e})=>e!==void 0),L.filter(({connectionReused:e})=>e!==void 0),L.once()),()=>{let t={playback_url:Z(e.info.currentFormat$.getValue(),e.info.availableSources$.getValue(),e.info.currentQuality$.getValue()),cdn_host:this.cdnHostname,connection_type:this.connectionType,connection_reused:this.connectionReused};this.logFirstByteManifest(t)}),r(e.events.manifestReceived$,()=>{let t={playback_url:Z(e.info.currentFormat$.getValue(),e.info.availableSources$.getValue(),e.info.currentQuality$.getValue()),cdn_host:this.cdnHostname,connection_type:this.connectionType,connection_reused:this.connectionReused};this.logManifestReceived(t)}),r(e.events.firstBytesRequested$,()=>{let t={playback_url:Z(e.info.currentFormat$.getValue(),e.info.availableSources$.getValue(),e.info.currentQuality$.getValue()),cdn_host:this.cdnHostname,connection_type:this.connectionType,connection_reused:this.connectionReused};this.logFirstMediaRequest(t)}),r(e.events.firstBytesReceived$,()=>{let t={playback_url:Z(e.info.currentFormat$.getValue(),e.info.availableSources$.getValue(),e.info.currentQuality$.getValue()),cdn_host:this.cdnHostname,connection_type:this.connectionType,connection_reused:this.connectionReused};this.logFirstByteMedia(t)}),r(L.merge(e.events.willStart$,e.events.looped$),t=>{t&&this.resetViewSession();let n={isid:this.isid$.getValue(),stream_profile:Xe(Y(e.info.currentFormat$.getValue())),dpi:this.statContext.dpi??96*R.clientChecker.display.pixelRatio,web_layout:this.statContext.isMobile||R.clientChecker.device.isMobile?`mobile`:`desktop`,preloaded:this.statContext.preload,navigation:this.statContext.navigation,recom_info:this.statContext.recomInfo};this.isEmbed&&(n.iframe_host=this.embedHostname??`unknown`),this.logStartSession(n)}),r(e.events.started$,()=>{this.isStarted=!0;let t=e.info.currentBuffer$.getValue(),n=e.info.currentQuality$.getValue(),r=e.info.isAutoQualityEnabled$.getValue(),i=e.info.muted$.getValue(),a=e.info.volume$.getValue(),o=e.info.surface$.getValue(),s=e.info.availableTextTracks$.getValue(),c=e.info.currentTextTrack$.getValue(),l=e.info.currentAudioStream$.getValue(),u=e.info.currentPlaybackRate$.getValue(),d={playback_quality:X(n),user_quality:r?`auto`:X(n),player_width:this.statContext.playerSize?.width??this.playerSize.width,player_height:this.statContext.playerSize?.height??this.playerSize.height,muted:i,sound_volume:Math.round(a*100),buffer_time:this.calcBufferTime(t),mode:Ze(o,this.statContext.isPreviewPlayerView),visibility:Q(o),subtitles_enabled:c?!!c:this.currentSubtitle?.enabled,auto_subtitles:s.find(({id:e})=>e===c)?.isAuto??this.currentSubtitle?.auto,audio_track_lang:l?.language,playback_rate:u,recom_info:this.statContext.recomInfo};this.logPlaybackStarted(d)}),r(e.events.willStart$,()=>{this.logPlay()}),r(e.events.playing$,()=>{let t=e.info.currentBuffer$.getValue(),n={buffer_time:this.calcBufferTime(t)};this.logPlaying(n),this.wasPaused&&this.logResume()}),r(e.events.paused$,()=>{this.wasPaused=!0,this.logPause()}),r(e.events.willStop$,()=>{this.isStarted=!1,this.logStop()}),r(L.merge(e.events.fetcherRecoverableError$,e.events.fatalError$),()=>{this.statContext.preload&&this.logPreloadError()});let a=e=>{switch(e){case L.ErrorCategory.NETWORK:return`network`;case L.ErrorCategory.VIDEO_PIPELINE:return`video_pipeline`;case L.ErrorCategory.EXTERNAL_API:return`external_api`;case L.ErrorCategory.PARSER:return`parser`;case L.ErrorCategory.DOM:return`dom`;default:return`wtf`}},o=e=>L.ErrorCategory.FATAL===e?`critical`:`informative`;r(e.events.fetcherRecoverableError$,({id:t,category:n,data:r,message:i,httpCode:s,UVBackendErrorCode:c})=>{let l={error_severity:o(n),error_category:a(n),player_error_code:t,player_error_trace:r,http_error_code:s,uv_backend_error_code_subcode:c,error_message:i,content_type:Y(e.info.currentFormat$.getValue())};this.logError(l),o(n)===`critical`&&this.logCannotPlay()}),r(e.events.managedError$,({id:t,category:n,data:r,message:i})=>{let s={error_severity:o(n),error_category:a(n),player_error_code:t,player_error_trace:r,error_message:i,content_type:Y(e.info.currentFormat$.getValue())};this.logError(s)}),r(e.events.fatalError$,({id:t,category:n,data:r,message:i})=>{let o={error_severity:`critical`,error_category:a(n),player_error_code:t,player_error_trace:r,error_message:i,content_type:Y(e.info.currentFormat$.getValue())};this.logError(o),this.logCannotPlay()}),r(L.combine({connectionType:e.info.httpConnectionType$,connectionReused:e.info.httpConnectionReused$,connectionMetrics:e.info.httpConnectionMetrics$}).pipe(L.filter(({connectionReused:e})=>e!==void 0),L.filter(({connectionMetrics:e})=>e!==void 0),L.filterChanged((e,t)=>e.connectionType===t.connectionType)),({connectionMetrics:t})=>{let n=e.info.currentFormat$.getValue(),r=e.info.availableSources$.getValue(),i=e.info.currentQuality$.getValue(),a=e.info.rttEstimation$.getValue();this.networkType=this.statContext.networkType??t?.networkType;let o={playback_url:Z(n,r,i),cdn_host:this.cdnHostname,connection_type:this.connectionType,connection_reused:this.connectionReused,rtt:a?Math.round(a):void 0,network_type:this.networkType,dns_resolve_time:t?.dnsResolveTime,tcp_handshake_time:t?.tcpHandshakeTime,tls_handshake_time:t?.tlsHandshakeTime};this.logConnectionEstablished(o)}),r(Ge(e,{maxTimeWindow:this.config.downloadBytesMaxTime}),e=>{this.downloadSpeed=e.download_speed,this.logDownloadBytes(e)}),r(e.events.firstFrame$,()=>{this.logFirstVideoFrameDecoded()}),r(e.events.willSeek$,()=>{let e={seek_type:this.seekAction$.getValue()};this.isStarted&&this.logSeeking(e)}),r(e.events.seeked$,()=>{let e={seek_type:this.seekAction$.getValue()};this.isStarted&&this.logSeeked(e),this.seekAction$.next(`unknown`)}),r(e.info.isStalled$,t=>{let n=e.info.currentBuffer$.getValue(),r=this.calcBufferTime(n);t&&r&&r>0&&this.logBufferStarvation({buffer_time:r})}),r(e.info.currentBuffer$.pipe(L.filter(e=>!!this.calcBufferTime(e)),L.once()),e=>{let t=this.calcBufferTime(e);if(this.statContext.preload){let e={buffer_time:t};this.logPreloadEnded(e)}this.logReady({buffer_time:t})});let s;r(L.combine({videoStream:e.info.currentVideoStream$,audioStream:e.info.currentAudioStream$,quality:e.info.currentQuality$}).pipe(L.filter(({videoStream:e,audioStream:t})=>e!==void 0&&t!==void 0),L.filter(({quality:e})=>e!==void 0)),({videoStream:t,audioStream:n,quality:r})=>{if(s!==r){if(this.userQuality=e.info.isAutoQualityEnabled$.getValue()?`auto`:X(r),this.downloadQuality=X(r),this.isStarted){let e=t?.codec,r=n?.codec,i={user_quality:this.userQuality,playback_quality:X(s),download_quality:this.downloadQuality,codec_info:this.genCodecInfo(e,r)};this.logQualityChanged(i)}s=r}});let c,l;return r(e.info.surface$,e=>{let t=Ze(e,this.statContext.isPreviewPlayerView);t&&!this.uiEvents&&this.isStarted&&this.logModeChanged({mode:t}),l=Q(e),c!==l&&(this.isStarted&&this.logVisibilityChanged({visibility:l}),c=Q(e))}),r(L.combine({muted:e.info.muted$,volume:e.info.volume$}).pipe(L.debounce(300)),({muted:e,volume:t})=>{if(this.isStarted){let n={muted:e,sound_volume:Math.round(t*100)};this.logSoundChanged(n)}}),r(e.info.currentFormat$.pipe(L.filter(e=>e!==void 0),L.skip(1)),e=>{let t={content_type:Y(e),cdn_host:this.cdnHostname,connection_type:this.connectionType,connection_reused:this.connectionReused};this.logContentTypeChange(t)}),r(e.info.currentAudioStream$.pipe(L.filter(e=>e!==void 0),L.skip(1)),e=>{let t={audio_track_lang:e.language,codec_info:e.codec};this.logAudioTrackSwitched(t)}),r(e.info.currentVideoStream$.pipe(L.filter(e=>e!==void 0),L.skip(1)),e=>{let t={hdr:e.hdr,codec_info:e.codec};this.logVideoTrackSwitched(t)}),this.player=e,this.resubscribeBeforeunload(),this.subscription.add(n),n}attachToUi(e){this.uiEvents=e;let{subscribe:t,subscription:n}=$e();t(e.actionSeek$,this.seekAction$),t(e.playerSize$,({width:e,height:t})=>{e&&t&&(this.playerSize={width:e,height:t},this.isStarted&&this.logViewPortChanged({player_width:e,player_height:t}))}),t(e.isLoaderVisible$,e=>{e&&this.isStarted&&this.logShowLoader()}),t(e.actionSubtitlesSwitched$,e=>{if(this.currentSubtitle={...e},this.isStarted){let t={subtitles_enabled:e.enabled,subtitles_track_lang:e.lang,auto_subtitles:e.auto};this.logSubtitlesSwitched(t)}});let{surface$:r}=Se(this.uiEvents,t,this.player);return t(r,e=>{this.isStarted&&this.logModeChanged({mode:Ze(e)})}),t(e.actionQuality$,e=>{let t=e=>Object.values(De).includes(e),n=this.player?.info.currentVideoStream$.getValue()?.codec,r=this.player?.info.currentAudioStream$.getValue()?.codec,i={user_quality:t(e)?`auto`:X(e),playback_quality:X(this.player?.info.currentQuality$.getValue()),download_quality:t(e)?X(this.player?.info.currentQuality$?.getValue()):X(e),codec_info:this.genCodecInfo(n,r)};this.logQualityChangeRequested(i)}),this.resubscribeBeforeunload(),this.subscription.add(n),n}attachToAds(e){let{subscription:t,subscribe:n}=$e();return n(e.init$,e=>{let t={slot:e};this.logAdvConfiguration(t)}),n(e.slotRequested$,e=>{let t={adv_section:e};this.logAdvRequest(t)}),n(e.started$,e=>{let t={adv_section:e};this.logAdvBreakStarted(t)}),n(e.ended$,({section:e,ordIds:t})=>{let n={adv_section:e,erids:t.join(`,`)};this.logAdvBreakEnded(n)}),n(e.error$,e=>{let t={error_message:e};this.logAdvError(t)}),this.resubscribeBeforeunload(),this.subscription.add(t),t}getDeviceId(){return this.deviceId}resetViewSession(){this.thinOneStatDebugLog({message:`VSID reset`}),E.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}genCodecInfo(e,t){return e&&t?`${e},${t}`:void 0}getLatencyInfo(){let e=this.player?.info.atLiveEdge$.getValue(),t={client_time:Date.now(),live:e};return JSON.stringify(t)}collectTelemetryData(){if(!this.player)return{};let e=this.player.info.currentBuffer$.getValue(),t=this.player.experimental.element$.getValue(),n=0,r=0;t&&(n=t.getVideoPlaybackQuality().droppedVideoFrames,r=t.getVideoPlaybackQuality().totalVideoFrames);let i=Y(this.player.info.currentFormat$.getValue()),a=this.player.info.currentVideoStream$.getValue()?.codec,o=this.player.info.currentAudioStream$.getValue()?.codec,s=this.player.info.videoBitrate$.getValue(),c=this.player.info.rttEstimation$.getValue();return{buffer_time:this.calcBufferTime(e),dropped_frames_count:n,rendered_frames_count:r,content_type:i,user_quality:this.userQuality,playback_quality:X(this.player.info.currentQuality$.getValue()),download_quality:this.downloadQuality,codec_info:this.genCodecInfo(a,o),bandwidth_from_manifest:s,cdn_host:this.cdnHostname,download_speed:this.downloadSpeed,network_type:this.networkType,rtt:c?Math.round(c):void 0,latency:this.getLatencyInfo()}}createRequiredParams(e){let t=this.vsid$.getValue();L.assertNonNullable(t);let n=this.eventNumber++,r=((this.isLive?this.player?.info.liveTime$.getValue():this.player?.info.position$.getValue())??0)*1e3,i={vsid:t,uv_movie_id:this.statContext.movieId,event_name:e,client_time:Date.now(),application:this.statContext.application??`@vkontakte/videoplayer-statistics:${D}`,platform:this.statContext.platform??`web:${this.statContext.isMobile||R.clientChecker.device.isMobile?`mobile`:`desktop`}`,product:this.statContext.product,event_number:n,playback_position:Math.round(r),current_tvt:this.getTotalViewTime(),cdn_host:this.cdnHostname};for(let e of this.config.disabledParams)delete i[e];return i}createRequiredFatParams(){let e={stats_version:`2.1.1`,browser:this.statContext.browser??R.clientChecker.browser.current,browser_version:this.statContext.browserVersion??String(R.clientChecker.browser.currentVersion),os:this.statContext.os??R.clientChecker.device.os.name,os_version:this.statContext.osVersion??R.clientChecker.device.os.version,device_type:this.statContext.deviceType??(this.statContext.isMobile||R.clientChecker.device.isMobile?`mobile`:`desktop`),device_manufacturer:this.statContext.deviceManufacturer??R.clientChecker.device.details.vendor,device_model:this.statContext.deviceModel??R.clientChecker.device.details.model,navigation:this.statContext.navigation};for(let t of this.config.disabledParams)delete e[t];return e}log(e,t,n=!1){if(this.config.disabledEvents.includes(e))return;let r=this.createRequiredParams(e),i={};n&&(i=this.createRequiredFatParams()),this.logger.log({...r,...i,...t})}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)}logTelemetry(e){this.log(`telemetry`,e)}logAdvConfiguration(e){this.log(`adv_configuration`,e)}logAdvRequest(e){this.log(`adv_request`,e)}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=L.fromEvent(L.getWindow(),`beforeunload`).subscribe(()=>{}),this.subscription.add(this.beforeunloadSubscription)}}var tt=require(`@vkontakte/videoplayer-shared`),nt=require(`@vkontakte/videoplayer-shared`),$=require(`@vkontakte/videoplayer-core`),rt=require(`@vkontakte/videoplayer-shared`);class it{startTime=null;stopTime=null;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.startTime=this.now():(this.accumulatedTime+=this.now()-this.stopTime,this.stopTime=null))}stop(){this.isRunning&&(this.stopTime=this.now())}reset(){this.startTime=null,this.stopTime=null,this.accumulatedTime=0}now(){return Date.now()}}var at=()=>window.Image?new Image:document.createElement(`img`);class ot{params;position=0;started=!1;isActiveLive;heartbeatPixels=[];heartbeatLastTimeSent={};heartbeatInterval;heartbeatFirstTimeoutId;idleCallbackIds=[];log;stopwatch=new it;subscription=new $.Subscription;constructor(e){this.params=e,this.log=new rt.Logger().createComponentLog(`MediascopePixel`)}attachTo(e){this.subscription.add(e.info.playbackState$.subscribe(e=>this.onPlaybackState(e))).add(e.info.position$.subscribe(e=>this.onPosition(e))).add(e.info.atLiveEdge$.subscribe(e=>this.isActiveLive=e)),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=>tt.cancelIdleCallbackPolyfilled(e)),this.send(`stop`)}onPlaybackState(e){e===$.PlaybackState.PLAYING?this.started?this.play():this.start():e===$.PlaybackState.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,t=this.heartbeatPixels[0]?.delay;if(t!==void 0&&e)try{this.heartbeatFirstTimeoutId=window.setTimeout(()=>{this.sendHeartbeat(e)},t*1e3)}catch(e){this.log({message:e.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[e,{url:t}]of this.heartbeatPixels.entries())this.heartbeatLastTimeSent[e]!==this.stopwatch.time&&(this.heartbeatLastTimeSent[e]=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,t){return e?.filter(e=>e.event===t.event&&t.keys.every(t=>!!e[t]))}getFrameTimestamp(){let e;if(this.isActiveLive){let t=Math.floor(Math.random()*25)+5;e=Date.now()/1e3-t}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(e=>!/={@[a-zA-Z_]+}/.test(e)).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(nt.requestIdleCallbackPolyfilled(()=>at().src=this.prepareUrl(e)))}catch(e){this.log({message:e.message})}}send(e){let t=this.preparePixels(e);for(let{url:e}of t)this.call(e)}sendHeartbeat(e){this.call(e)}}
6
+ var e=Object.defineProperty,t=Object.getOwnPropertyNames,n=Object.getOwnPropertyDescriptor,r=Object.prototype.hasOwnProperty;function i(e){return this[e]}var a=a=>{var s=(o??=new WeakMap).get(a),c;if(s)return s;if(s=e({},`__esModule`,{value:!0}),a&&typeof a==`object`||typeof a==`function`)for(var l of t(a))r.call(s,l)||e(s,l,{get:i.bind(a,l),enumerable:!(c=n(a,l))||c.enumerable});return o.set(a,s),s},o,s=e=>e;function c(e,t){this[e]=s.bind(null,t)}var l=(t,n)=>{for(var r in n)e(t,r,{get:n[r],enumerable:!0,configurable:!0,set:c.bind(n,r)})},u={};l(u,{VERSION:()=>D,ThinOneStat:()=>Te,SeekAction:()=>g,Quality:()=>p,OneStat:()=>we,MediascopePixel:()=>ot,InteractiveInterfaceClick:()=>_,ContentType:()=>m,ConnectionType:()=>h,ApiEnv:()=>f}),module.exports=a(u);var d=require(`@vkontakte/videoplayer-shared`),f;(e=>{e.PROD=`prod`,e.VK_ALIAS=`vk_alias`,e.VIDEOTEST=`videotest`,e.TEST=`test`,e.OKCDN=`okcdn`,e.AUTO=`auto`})(f||={});var p;(e=>{e.Q144P=`mobile`,e.Q240P=`lowest`,e.Q360P=`low`,e.Q480P=`medium`,e.Q720P=`high`,e.Q1080P=`fullhd`,e.Q1440P=`quadhd`,e.Q2160P=`ultrahd`,e.UNKNOWN=`unknown`})(p||={});var m;(e=>{e.MP4=`mp4`,e.DASH=`dash`,e.DASH_SEP=`dash_sep`,e.ONDEMAND_DASH=`ondemand_dash`,e.HLS=`hls`,e.HLS_FMP4=`hls_fmp4`,e.ONDEMAND_HLS=`ondemand_hls`,e.WEBM=`webm`,e.AV1=`av1`,e.ONDEMAND_DASH_LIVE=`ondemand_dash_live`,e.ONDEMAND_HLS_LIVE=`ondemand_hls_live`,e.WEBRTC=`webrtc`,e.UNKNOWN=`unknown`,e.RTMP=`rtmp`})(m||={});var h;(e=>{e.HTTP1=`http1`,e.HTTP2=`http2`,e.HTTP3=`http3`})(h||={});var g;(e=>{e.SLIDER=`slider`,e.RICH=`rich`,e.DOUBLE_TAP=`double_tap`,e.TIME_CODE=`time_code`,e.EPISODE=`episode`,e.REWIND=`rewind`,e.LIVE=`live`,e.UNKNOWN=`unknown`})(g||={});var _;(e=>{e.GRAPH_SHOW=`iGraphShow`,e.GRAPH_HIDE=`iGraphHide`,e.NEXT_AREA=`iNextChapterArea`,e.NEXT_BUTTON=`iNextChapterBtn`,e.WATCH_AGAIN=`iWatchAgainBtn`})(_||={});var v={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`},y={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`},b={unknown:`un`,mobile:`m`,lowest:`ls`,low:`l`,medium:`md`,high:`h`,fullhd:`f`,quadhd:`q`,ultrahd:`u`},ee={pip:`pi`,fullscreen:`fs`,external:`ex`,prefetch:`pr`,airplay:`ap`,chromecast:`cc`,invisible:`iv`,minimal:`minimal`},x=require(`@vkontakte/videoplayer-shared`),S=`CIOPGQJGDIHBABABA`,C={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:``},te={apiEnv:`vk_alias`,apiKey:S,apiBaseUrl:null,requestRetryCount:1,useVsid64:!1,firstFlushTime:5e3,flushDebounceTime:1e4,flushMaxWait:6e4,storageExpiration:2160*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:300*1e3,random:.1},useKeepalive:!1,watchCoverageTimeoutFix:!1},ne=e=>x.fillWithDefault(e,te);function re(){let e=`0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz`.split(``),t=Array(36),n=0,r,i;for(i=0;i<36;i++)i===8||i===13||i===18||i===23?t[i]=`-`:i===14?t[i]=`4`:(n<=2&&(n=33554432+Math.random()*16777216|0),r=n&15,n>>=4,t[i]=e[i===19?r&3|8:r]);return t.join(``)}var w=require(`@vkontakte/videoplayer-shared`),ie=require(`@vkontakte/videoplayer-shared`),ae=()=>Math.floor(Math.random()*2**32).toString(36).padStart(13,`0`),T=()=>Math.floor(Math.random()*2**64).toString(36).padStart(13,`0`);class E{static vsid;static getVSID(){return E.vsid}static generateVSID(e){return E.vsid=e?T():ae(),E.vsid}}var oe=e=>{let{operation:t,custom:n}=e,r=Object.fromEntries(Object.entries(n).map(([e,t])=>{let n=y[e]??e,r=t;return t&&(e===`mode`?r=ee[t]??t:e===`quality`&&(r=b[t]??t)),[n,r]}));return{...e,operation:v[t]??t,custom:r}},D=`1.0.103-dev.5aefbe808.0`,O=require(`@vkontakte/videoplayer-shared`),se=/Mobile|mini|Fennec|Android|iP(ad|od|hone)|opera (mini|mobi)/i;class ce{params;authToken;sessionKey;authorizePromise;refreshAuthTokenPromise;consequentAuthErrors=0;authorized$=new O.ValueSubject(!1);backoffTimeoutId;constructor(e){this.params=e}async authorize(e){return this.authToken=e??await this.refreshAuthToken(),this._authorizeWithBackoff()}logBeacon(e){let t=this.createLogParams(e),n=this.sessionKey;n&&(this.params.apiTransport.sendBeacon(`log.externalLog`,t,n)||this.logRequest(e).catch(()=>{}))}async logRequest(e){let t=`log.externalLog`,n=this.createLogParams(e),r=this.sessionKey??await this._authorizeWithBackoff();if(!r)return;let i=async(e,a=this.params.config.requestRetryCount)=>{try{return await this.params.apiTransport.sendRequest(t,n,r)}catch(n){if(!n||!(`error_code`in n)){this.params.error$.next({id:`logRequestUnknown`,category:O.ErrorCategory.NETWORK,message:`Unknown ${t} error`,thrown:n});return}let r=n?.error_code;switch(r){case 102:case 103:case 104:return this.authorized$.next(!1),this.sessionKey=await this._authorizeWithBackoff(),a>0?i(e,a-1):void 0;case 401:return this.authorized$.next(!1),this.authToken=await this.refreshAuthToken(),this.sessionKey=await this._authorizeWithBackoff(),a>0?i(e,a-1):void 0;default:this.params.error$.next({id:`LogRequest#${r}`,category:O.ErrorCategory.EXTERNAL_API,message:`${t} error`,data:n});return}}};return i(e)}destroy(){window.clearTimeout(this.backoffTimeoutId),this.backoffTimeoutId=0}async refreshAuthToken(){if(this.params.refreshAuthToken)return this.refreshAuthTokenPromise||=this.params.refreshAuthToken().finally(()=>{this.refreshAuthTokenPromise=void 0}),this.refreshAuthTokenPromise}createLogParams(e){let t=`WEB`,n=!1,r=`@vkontakte/videoplayer-statistics:${D}`;if(this.params.config.useVKComIsMobileLogic){let{appVersion:e}=window.navigator;n=se.test(e)}else this.params.mobile&&(n=!0);return n&&(t=`M_WEB`),this.params.vktvVersion&&(t=`SMART_TV`,r=this.params.vktvVersion),{collector:`ok.mobile.apps.video`,data:JSON.stringify({application:r,platform:t,items:this.params.config.shorten?e.map(oe):e})}}_authorizeWithBackoff(){if(!this.consequentAuthErrors)return this._authorize();let e=O.getExponentialDelay(this.consequentAuthErrors,this.params.config.backoff);return new Promise(t=>{this.backoffTimeoutId||=window.setTimeout(()=>{this._authorize().then(t).catch(e=>this.params.error$.next({id:`AuthorizeBackoff`,category:O.ErrorCategory.NETWORK,message:`Otherwise unhandled error in authorization`,thrown:e})).finally(()=>this.backoffTimeoutId=0)},e)})}async _authorize(){if(this.authorizePromise)return this.authorizePromise;this.sessionKey=void 0,this.authorized$.next(!1);let e={session_data:{version:2,device_id:this.params.deviceId,client_version:D.split(`-`)[0],client_type:`SDK_JS`}};return this.authToken!==void 0&&(e.session_data.auth_token=this.authToken,e.session_data.version=3),this.authorizePromise=this.params.apiTransport.sendRequest(`auth.anonymLogin`,e).then(e=>((!e||!e.session_key)&&this.params.error$.next({id:`AuthorizeFailed`,category:O.ErrorCategory.EXTERNAL_API,message:`No session key`,data:e}),this.sessionKey=e?.session_key??void 0,this.sessionKey)).catch(async e=>{this.sessionKey=void 0;let t=e?.error_code;switch(t){case 401:return this.authToken=await this.refreshAuthToken(),this._authorizeWithBackoff()}t?this.params.error$.next({id:`Authorize#${t}`,category:O.ErrorCategory.EXTERNAL_API,message:`authorize error`,data:e}):this.params.error$.next({id:`AuthorizeUnknown`,category:O.ErrorCategory.NETWORK,message:`authorize error`,thrown:e})}).finally(()=>{this.authorizePromise=void 0,this.consequentAuthErrors=this.sessionKey?0:this.consequentAuthErrors+1,this.authorized$.next(this.sessionKey!==void 0)}),this.authorizePromise}}var le=require(`@vkontakte/videoplayer-shared`),k=require(`@vkontakte/videoplayer-shared`);class ue{apiKey;apiBaseUrl;apiEnv;timeSynchronisation;isApiBaseUrlFetched;params;constructor(e){this.params=e,this.apiKey=e.config.apiKey,this.apiEnv=e.config.apiEnv,this.apiBaseUrl=e.config.apiBaseUrl??C[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=`),t=(await(await le.fetchPolyfilled(e,{method:`GET`,mode:`cors`,cache:`no-cache`})).json())?.Answer[0]?.data;if(!t)throw Error(`Wrong DNS response`);return t}catch(e){return this.params.error$.next({id:`OneStat:ApiTransport:resolveApiBaseUrl`,category:k.ErrorCategory.NETWORK,message:`Unhandled resolve api base url error`,thrown:e}),C.vk_alias}finally{this.isApiBaseUrlFetched=!0}}sendBeacon(e,t,n){if(!window.Blob||!window.navigator.sendBeacon)return!1;let r=this._prepareQueryParams({method:e,queryParams:t,sessionKey:n}),i=new window.Blob([r.toString()],{type:`application/x-www-form-urlencoded`});try{return window.navigator.sendBeacon(`${this.apiBaseUrl}/fb.do`,i)}catch(n){this.params.error$.next({id:`OneStat:ApiTransport:sendBeacon`,category:k.ErrorCategory.NETWORK,message:`Unhandled beacon error`,thrown:n,data:{method:e,params:t}})}return!1}async sendRequest(e,t,n){let r=k.now(),i=i=>{if(i instanceof TypeError&&[`Failed to fetch`,`NetworkError when attempting to fetch resource.`].includes(i.message)){this.params.error$.next({id:`Network`,category:k.ErrorCategory.NETWORK,message:`Request failed`,thrown:i});return}this.params.error$.next({id:`OneStat:ApiTransport:sendRequest`,category:k.ErrorCategory.NETWORK,message:`Unhandled request error`,thrown:i,data:{method:e,params:t,sessionKey:n,time:k.now()-r}})};this.apiBaseUrl=await this.resolveApiBaseUrl();let a={method:`post`,headers:{"Content-type":`application/x-www-form-urlencoded`},body:this._prepareQueryParams({method:e,queryParams:t,sessionKey:n})};return this.params.config.useKeepalive&&(a.keepalive=!0),le.fetchPolyfilled(`${this.apiBaseUrl}/fb.do`,a).then(e=>{let t=Number(e.headers.get(`content-length`))===0,n=new Date(e.headers.get(`date`)??``).getTime(),a=k.now()-r;if(isFinite(n)&&this.timeSynchronisation?.addServerTime(n,a),!t)return e.json().then(e=>Object.prototype.hasOwnProperty.call(e,`error_msg`)?Promise.reject(e):e,i)},i)}_prepareQueryParams(e){let t=new URLSearchParams({format:`JSON`,method:e.method,application_key:this.apiKey});return e.sessionKey!==void 0&&t.append(`session_key`,e.sessionKey),Object.entries(e.queryParams).forEach(([e,n])=>t.append(e,typeof n==`string`?n:JSON.stringify(n))),t}}var A=require(`@vkontakte/videoplayer-shared`),j=`onestat_events`,de=e=>t=>t.timestamp+e>=A.now();class fe{params;api;error$;subscription;userSalt;unsaltedStorage=[];lastVsid;isPaused=!1;firstFlush;debouncedFlush;loggerDebugLog;constructor(e){this.params=e,this.api=e.api,this.error$=e.error$,this.userSalt=e.userSalt,this.loggerDebugLog=e.debugLogger.createComponentLog(`stat logger`),this.firstFlush=A.debounceFn(()=>this.safeFlush(),this.params.config.firstFlushTime,{maxWait:this.params.config.firstFlushTime});let t=A.safeStorage.isPersistent()?this.params.config.flushMaxWait:0;this.debouncedFlush=A.debounceFn(()=>this.safeFlush(),this.params.config.flushDebounceTime,{maxWait:t}),this.subscription=this.api.authorized$.subscribe(e=>{e&&this.debouncedFlush()}),this.housekeepStorage()}isUrgent=e=>{let{operation:t}=e;return[`action_play`,`watch_coverage_record`,`watch_coverage_live`].includes(t)};safeFlush(){try{this.flush()}catch(e){this.error$.next({id:`LoggerError`,category:A.ErrorCategory.WTF,message:e?String(e):`Unknown logger error`,thrown:e})}}readFromStorage(){let e=A.safeStorage.get(j);try{return e?JSON.parse(e):{}}catch{}return{}}addToStorage(e){if(!this.userSalt){this.unsaltedStorage.push(e);return}let t=this.readFromStorage(),n=(t[this.userSalt]??[]).filter(de(this.params.config.storageExpiration));A.safeStorage.set(j,JSON.stringify({...t,[this.userSalt]:[...n,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],A.safeStorage.set(j,JSON.stringify(e))}housekeepStorage(){let e=this.readFromStorage();for(let[t,n]of Object.entries(e)){let r=n.filter(de(this.params.config.storageExpiration));r.length?e[t]=r:delete e[t],this.loggerDebugLog({message:`${n.length} retrieved from storage, ${r.length} of them actual`})}A.safeStorage.set(j,JSON.stringify(e))}log(e){this.addToStorage(e),!this.isPaused&&(this.isUrgent(e)?this.flush():this.lastVsid===e.custom.vsid?this.debouncedFlush():this.firstFlush(),this.lastVsid=e.custom.vsid)}flush({wantBeacon:e,clearStorage:t}={wantBeacon:!1,clearStorage:!0}){let n=this.getFromStorage();n.length!==0&&(this.api.authorized$.getValue()?(e&&this.params.config.useBeacon?(this.loggerDebugLog({message:`Flushing ${n.length} events through beacon`}),this.api.logBeacon(n)):(this.loggerDebugLog({message:`Flushing ${n.length} events`}),this.api.logRequest(n)),t&&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()}}var M=require(`@vkontakte/videoplayer-core`),pe=require(`@vkontakte/videoplayer-shared`),me=e=>e&&{[M.VideoQuality.INVARIANT]:`unknown`,[M.VideoQuality.Q_144P]:`mobile`,[M.VideoQuality.Q_240P]:`lowest`,[M.VideoQuality.Q_360P]:`low`,[M.VideoQuality.Q_480P]:`medium`,[M.VideoQuality.Q_576P]:`unknown`,[M.VideoQuality.Q_720P]:`high`,[M.VideoQuality.Q_1080P]:`fullhd`,[M.VideoQuality.Q_1440P]:`quadhd`,[M.VideoQuality.Q_2160P]:`ultrahd`,[M.VideoQuality.Q_4320P]:`unknown`}[e],he=e=>e&&{[M.HttpConnectionType.HTTP1]:`http1`,[M.HttpConnectionType.HTTP2]:`http2`,[M.HttpConnectionType.QUIC]:`http3`}[e],ge=e=>{if(e!==void 0)switch(e){case M.VideoFormat.MPEG:return`mp4`;case M.VideoFormat.DASH:case M.VideoFormat.DASH_LIVE:case M.VideoFormat.DASH_STREAMS:return`dash`;case M.VideoFormat.DASH_SEP:return`dash_sep`;case M.VideoFormat.DASH_ONDEMAND:return`ondemand_dash`;case M.VideoFormat.DASH_WEBM:case M.VideoFormat.DASH_LIVE_WEBM:return`webm`;case M.VideoFormat.DASH_WEBM_AV1:return`av1`;case M.VideoFormat.DASH_LIVE_CMAF:return`ondemand_dash_live`;case M.VideoFormat.HLS:case M.VideoFormat.HLS_LIVE:return`hls`;case M.VideoFormat.HLS_FMP4:return`hls_fmp4`;case M.VideoFormat.HLS_ONDEMAND:return`ondemand_hls`;case M.VideoFormat.HLS_LIVE_CMAF:return`ondemand_hls_live`;case M.VideoFormat.WEB_RTC_LIVE:return`webrtc`;default:return pe.assertNever(e)}},_e=(e,t)=>{if(t)return`minimal`;switch(e){case void 0:case M.Surface.NONE:case M.Surface.INLINE:return;case M.Surface.FULLSCREEN:return`fullscreen`;case M.Surface.SECOND_SCREEN:return`chromecast`;case M.Surface.PIP:return`pip`;case M.Surface.INVISIBLE:return`invisible`;default:return pe.assertNever(e)}},ve=e=>{switch(e){case`slow-2g`:return`poor`;case`2g`:return`poor`;case`3g`:return`good`;case`4g`:return`excellent`}};class ye{offset=void 0;constructor(e){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,t){let n=e-Date.now()-t/2;if(Math.abs(n)<1e3){this.offset=0;return}if(this.offset===void 0)this.offset=Math.round(n);else{let e=.2;this.offset=Math.round(e*n+(1-e)*this.offset)}}}var be=require(`@vkontakte/videoplayer-core`),N=require(`@vkontakte/videoplayer-shared`),xe=(e,t)=>new N.Observable(n=>{let r=new N.Subscription,i=N.merge(N.fromEvent(window,`beforeunload`),e.events.willDestruct$),a=new N.ValueSubject(void 0),o;r.add(e.info.isLive$.pipe(N.filterChanged()).subscribe(t=>{o&&(o.unsubscribe(),a.next(void 0)),o=t?e.info.liveTime$.pipe(N.map(e=>e&&e/1e3)).subscribe(a):e.info.position$.subscribe(a),r.add(o)}));let{playing$:s,paused$:c}=e.events,l=e.events.willSeek$.pipe(N.filter(()=>e.info.playbackState$.getValue()===be.PlaybackState.PLAYING)),u=e.events.seeked$.pipe(N.filter(()=>e.info.playbackState$.getValue()===be.PlaybackState.PLAYING)),d=!1,f=new N.Subject;r.add(l.subscribe(()=>{d||f.next(),d=!0})),r.add(u.subscribe(()=>d=!1));let p=new N.Subject,m=new N.Subject,h=N.merge(s,u,p),g=N.merge(c,f,i,e.events.looped$,m),_,v=()=>_=a.getValue(),y=()=>{let e=a.getValue();N.isNullable(_)||_===e||N.isNullable(e)||(n.next({from:_,to:e}),_=void 0)},b=()=>{m.next(),p.next()};if(r.add(h.subscribe(v)),r.add(g.subscribe(y)),t.forceInterval&&isFinite(t.forceInterval))if(t.watchCoverageTimeoutFix){let e,n=()=>{e!==void 0&&(window.clearTimeout(e),e=void 0)};r.add(h.subscribe(()=>{n(),e=window.setTimeout(b,t.forceInterval)})),r.add(g.subscribe(()=>n())),r.add(()=>n())}else{let e=0;r.add(h.subscribe(()=>e=window.setTimeout(b,t.forceInterval))),r.add(g.subscribe(()=>window.clearTimeout(e)))}return r}),P=require(`@vkontakte/videoplayer-core`),F=require(`@vkontakte/videoplayer-shared`),Se=(e,t,n)=>{let r=new F.Subject,i=r.pipe(F.debounce(0),F.filterChanged()),a=!1,o=!1,s=!1;return t(e.inPiP$,e=>{a=e,r.next(e?P.Surface.PIP:o?P.Surface.FULLSCREEN:s?P.Surface.INLINE:void 0)}),t(e.inFullscreen$,e=>{o=e,r.next(e?P.Surface.FULLSCREEN:a?P.Surface.PIP:s?P.Surface.INLINE:void 0)}),n&&t(n.info.surface$,e=>{switch(e){case P.Surface.SECOND_SCREEN:case P.Surface.NONE:case P.Surface.INLINE:!o&&!a&&(e===P.Surface.INLINE&&(s=!0),r.next(e));break}}),{surface$:i}},Ce=`_one-stat_deviceId`,I=()=>{let e=new w.Subscription;return{subscription:e,subscribe:(t,n)=>{t&&e.add(t.subscribe(n))}}};class we{api;logger;config;subscription=new w.Subscription;beforeunloadSubscription;timeSynchronisation;debugLogger=new ie.Logger;oneStatDebugLog=this.debugLogger.createComponentLog(`onestat`);loopCounter=0;disabled=!1;experimental;get vsid$(){return new w.ValueSubject(E.getVSID())}isid$=new w.ValueSubject(void 0);zenUid$=new w.ValueSubject(void 0);statContext;isEmbed;embedParent;uiEvents;player;seekAction$=new w.ValueSubject(`unknown`);deviceId;constructor(e,t){this.statContext=e,this.config=ne(t.config??{}),w.isNonNullable(t.apiEnv)&&(this.config.apiEnv=t.apiEnv),this.config.synchronizeTime&&(this.timeSynchronisation=new ye);let n=new w.Subject;this.experimental={error$:n};let r=w.safeStorage.get(Ce);this.statContext.deviceId?this.deviceId=this.statContext.deviceId:r?this.deviceId=r:(this.deviceId=re(),w.safeStorage.set(Ce,this.deviceId)),this.resetViewSession(),t.useIsid&&this.isid$.next(t.isid??T()),this.zenUid$.next(t.zenUid);let i=new ue({config:this.config,error$:n,timeSynchronisation:this.timeSynchronisation});this.api=new ce({config:this.config,apiTransport:i,refreshAuthToken:t.refreshAuthToken,mobile:this.statContext.mobile??!1,deviceId:this.deviceId,error$:n,vktvVersion:t.vktvVersion}),this.logger=new fe({config:this.config,debugLogger:this.debugLogger,api:this.api,error$:n,userSalt:t.userSalt});let{isEmbed:a,topOrigin:o}=ie.detectEmbed();this.isEmbed=a,this.embedParent=o?new URL(o).hostname:void 0,this.subscribe()}updateContext(e){this.statContext={...this.statContext,...e}}attachTo(e){let t=new w.Subscription,n=(e,n)=>t.add(e.subscribe(n));n(e.events.willStart$,()=>{let t=e.info.position$.getValue();this.logActionPlay({position:t}),this.statContext.projectId&&this.logActionPlayInteractive()}),n(e.events.looped$,()=>{this.resetViewSession(),++this.loopCounter>this.config.maxLoops&&(this.disabled=!0),this.logActionPlay({position:e.info.position$.getValue()})}),n(e.events.seeked$,()=>{let t=this.seekAction$.getValue();this.logSeek({action:t===`rich`?`slider`:t,time:e.info.position$.getValue()}),this.seekAction$.next(`unknown`)}),n(e.events.paused$,()=>{this.logPause({position:e.info.position$.getValue()})}),n(e.events.willResume$,()=>{this.logPlay()}),n(e.events.started$,()=>{this.statContext.clip&&this.logWatchCoverageRecord({start:0,end:0})}),n(e.events.playing$,()=>{this.logPlaying()}),n(xe(e,{forceInterval:this.config.watchCoverageInterval,watchCoverageTimeoutFix:this.config.watchCoverageTimeoutFix}),t=>{let n=e.info.isLive$.getValue(),r=e.info.atLiveEdge$.getValue(),i={start:parseFloat(t.from.toFixed(3)),end:parseFloat(t.to.toFixed(3))};if(r){let t=e.info.liveLatency$.getValue()??0,n=e.info.currentBuffer$.getValue()?.end??0,r=e.info.liveBufferTime$.getValue()??0,a=Math.round((t-(n-r))*1e3),o=Math.round(t*1e3);a&&o&&(i.latency=a,i.bufferLatency=o)}n?this.logWatchCoverageLive(i):this.logWatchCoverageRecord(i)});let r;n(e.info.isStalled$,e=>{e?r=w.now():(w.isNonNullable(r)&&this.logEmptyBuffer({duration:w.now()-r}),r=void 0)});let i=!1;t.add(e.events.fatalError$.pipe(w.once()).subscribe(()=>i=!0)),n(e.events.willStop$,()=>{if(e.info.isStalled$.getValue()){let e=w.isNonNullable(r)?w.now()-r:void 0;this.logCloseAtEmptyBuffer({duration:e??0}),r=void 0}else i||this.logActionStop()}),n(e.events.managedError$,({id:e})=>{this.logError({fatal:!1,errorType:e})}),n(e.events.fatalError$,({id:e})=>{this.logError({fatal:!0,errorType:e})});let a,o,s=!1;n(e.events.firstBytes$,e=>{a=w.now(),this.logFirstBytes({time:e})}),n(e.events.willStart$,()=>o=w.now()),n(e.info.currentBuffer$,e=>{!s&&e&&e.end-e.start>0&&w.isNonNullable(a)&&(this.logPlayerReady({duration:w.now()-a}),s=!0)}),n(e.events.firstFrame$,()=>{w.isNonNullable(a)&&!s&&(this.logPlayerReady({duration:w.now()-a}),s=!0),w.isNonNullable(o)&&this.logFirstFrame({time:w.now()-o})});let c;n(e.info.currentVideoStream$,e=>{e&&(c&&e.id!==c&&this.logTrackSwitch(e),c=e.id)});let l;n(e.info.currentAudioStream$,e=>{e&&(l&&e.id!==l&&this.logTrackSwitch(e),l=e.id)}),n(e.info.atLiveEdge$,e=>this.updateContext({liveEdge:e})),n(w.combine({muted:e.info.muted$,volume:e.info.volume$}),({muted:e,volume:t})=>this.updateContext({audible:!e&&t>0})),n(e.info.currentQuality$,e=>{let t=me(e);this.updateContext({quality:t}),t&&this.logQuality(t)}),n(e.info.isAutoQualityEnabled$,e=>this.updateContext({autoQuality:e})),n(e.info.currentFormat$,e=>this.updateContext({contentType:ge(e)})),n(e.info.currentPlaybackRate$,e=>this.updateContext({rate:e})),n(e.info.is3DVideo$,e=>this.updateContext({is3d:e}));let u;return n(e.info.hostname$,e=>{let t=u!==void 0&&u!==e;this.updateContext({cdnHostname:e,failover:t}),t&&this.logFailover(e),u=e}),n(e.info.throughputEstimation$,e=>this.updateContext({downloadSpeed:e})),n(e.info.httpConnectionType$,e=>{this.statContext.firstConnectionType||this.updateContext({firstConnectionType:he(e)}),this.updateContext({connectionType:he(e)})}),n(e.info.httpConnectionReused$,e=>{w.isNullable(this.statContext.firstConnectionReused)&&this.updateContext({firstConnectionReused:e}),this.updateContext({connectionReused:e})}),n(e.info.surface$,e=>{this.uiEvents||this.updateContext({mode:_e(e,this.statContext.isPreviewPlayerView)})}),n(w.combine({current:e.info.currentTextTrack$,available:e.info.availableTextTracks$}),({current:e,available:t})=>{let n=t.find(({id:t})=>t===e),r=n&&(n.isAuto?`${n.language}_auto`:n.language);this.updateContext({subtitles:r?.split(`.`)[0]})}),this.player=e,this.uiEvents&&this.attachToUi(this.uiEvents),this.resubscribeBeforeunload(),this.subscription.add(t),t}attachToUi(e){this.uiEvents=e;let{subscription:t,subscribe:n}=I();if(!this.player)return t;n(e.actionRewind$,()=>{this.player&&(this.resetViewSession(),this.logActionPlay({position:this.player.info.position$.getValue()}))}),n(e.actionSeek$,this.seekAction$);let{surface$:r}=Se(this.uiEvents,n,this.player);return n(r,e=>{this.updateContext({mode:_e(e,this.statContext.isPreviewPlayerView)})}),n(e.actionSetSubtitle$,e=>this.updateContext({subtitles:e?.split(`.`)[0]})),n(e.nextMovie$,e=>this.logNextMovie(e)),this.resubscribeBeforeunload(),this.subscription.add(t),t}attachToAds(e){let{subscription:t,subscribe:n}=I();return n(e.slotRequested$,()=>this.logAdSlotRequest()),n(e.started$,e=>this.logAdStarted(e)),n(e.paused$,()=>this.logAdPaused()),n(e.resumed$,()=>this.logAdResumed()),n(e.ended$,()=>this.logAdEnded()),n(e.skipped$,()=>this.logAdSkipped()),n(e.clicked$,()=>this.logAdClicked()),n(e.error$,e=>this.logError({errorType:e,fatal:!1})),this.resubscribeBeforeunload(),this.subscription.add(t),t}attachToInteractive(e){let{subscription:t,subscribe:n}=I();return n(e.click$,e=>this.logInterfaceClick(e)),n(e.nextMovie$,e=>this.logNextMovie(e)),this.resubscribeBeforeunload(),this.subscription.add(t),t}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`}),E.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 t=this.timeSynchronisation?.getOffset()??0,n=e.start+t,r=e.end+t;this.log({operation:`watch_coverage_live`,param:`${n}-${r}`},{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(w.merge(w.fromEvent(e,`change`),w.observableFrom([`init`])).subscribe(()=>this.updateContext({network:ve(e.effectiveType)}))),this.config.debugLog&&this.debugLogger.log$.subscribe(e=>{console.debug(`%c stat `,`background:#fa6470;`,`component: ${e.component}.`,e.message)})}resubscribeBeforeunload(){this.beforeunloadSubscription?.unsubscribe(),this.beforeunloadSubscription=w.fromEvent(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,t={}){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 n=this.createLogItem(e,t);this.logger.log(n)}createLogItem({operation:e,param:t,time:n},r={}){let i=this.timeSynchronisation?.now()??w.now(),a=this.vsid$.getValue();w.assertNonNullable(a);let o=this.isid$.getValue(),s=e===`empty_buffer`||e===`close_at_empty_buffer`?this.statContext.connectionType:this.statContext.firstConnectionType,c=this.statContext.firstConnectionReused,l,u;if(this.isEmbed||this.statContext.place===`embed`){l=this.embedParent;let e=[...new URLSearchParams(location.search).entries()].filter(([e,t])=>this.config.embedUrlParams.includes(e));u=new URLSearchParams(e).toString()}else if(this.statContext.place===`direct`){let e=this.statContext.refDomain||document.referrer;l=e&&d.urlCanParsePolyfilled(URL,e)?new URL(e).hostname:e,u=location.href.substring(0,1024)}let f={vsid:a,isid:o,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:t,vk_app_id:this.statContext.vkAppId,track_code:this.statContext.trackCode,connection_type:s,connection_reused:c===!0?1:c===!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:l,direct_url:u,rate:this.statContext.rate===1||w.isNullable(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,...r};for(let e of this.config.disabledCustomFields)delete f[e];return{operation:e,type:1,time:n,network:this.statContext.network,timestamp:i,custom:f}}}var Te={};l(Te,{VERSION:()=>D,ThinOneStat:()=>et,ActionSeekType:()=>Oe});var L=require(`@vkontakte/videoplayer-shared`),R=require(`@vkontakte/videoplayer-core`),Ee=require(`@vkontakte/videoplayer-shared`),De;(e=>{e.AUTO=`auto`,e.AUTO_POOR=`auto_poor`,e.AUTO_RICH=`auto_rich`})(De||={});var Oe;(e=>{e.SLIDER=`slider`,e.RICH=`rich`,e.DOUBLE_TAP=`double_tap`,e.TIME_CODE=`time_code`,e.EPISODE=`episode`,e.REWIND=`rewind`,e.LIVE=`live`,e.UNKNOWN=`unknown`})(Oe||={});var ke=`CIOPGQJGDIHBABABA`,Ae={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:``},je={apiKey:ke,apiEnv:`okcdn`,apiBaseUrl:null,requestRetryCount:1,useVsid64:!1,firstFlushTime:5e3,flushDebounceTime:1e4,flushMaxWait:6e4,storageExpiration:2160*60*1e3,watchCoverageHeartbeatInterval:3e4,disabledEvents:[],disabledParams:[],synchronizeTime:!0,useBeacon:!1,alwaysSendDesktop:!1,watchedNDefaultTargetDuration:1e3,telemetryInterval:3e4,downloadBytesMaxTime:3e4},Me=e=>Ee.fillWithDefault(e,je),z=require(`@vkontakte/videoplayer-shared`);class Ne{authorized$;params;authToken;sessionKey;authorizePromise;refreshAuthTokenPromise;consequentAuthErrors;backoffTimeoutId;constructor(e){this.params=e,this.authorized$=new z.ValueSubject(!1),this.consequentAuthErrors=0}async authorize(e){return this.authToken=e??await this.refreshAuthToken(),this.authorizeWithBackoff()}logBeacon(e){let t=this.createLogParams(e),n=this.sessionKey;n&&(this.params.apiTransport.sendBeacon(`log.logUvStat`,t,n)||this.logRequest(e).catch(()=>{}))}async logRequest(e){let t=`log.logUvStat`,n=this.createLogParams(e),r={},i=this.sessionKey??await this.authorizeWithBackoff();if(!i)return;let a=async(e,o=this.params.config.requestRetryCount)=>{try{return await this.params.apiTransport.sendRequest(t,n,i,r)}catch(n){if(!n||!(`error_code`in n)){this.params.error$.next({id:`logRequestUnknown`,category:z.ErrorCategory.NETWORK,message:`Unknown ${t} error`,thrown:n});return}let r=n?.error_code;switch(r){case 102:case 103:case 104:return this.authorized$.next(!1),this.sessionKey=await this.authorizeWithBackoff(),o>0?a(e,o-1):void 0;case 401:return this.authorized$.next(!1),this.authToken=await this.refreshAuthToken(),this.sessionKey=await this.authorizeWithBackoff(),o>0?a(e,o-1):void 0;default:this.params.error$.next({id:`LogRequest#${r}`,category:z.ErrorCategory.EXTERNAL_API,message:`${t} error`,data:n});return}}};return a(e)}destroy(){window.clearTimeout(this.backoffTimeoutId),this.backoffTimeoutId=0}async refreshAuthToken(){if(this.params.refreshAuthToken)return 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:${D}`,platform:e[0].platform,product:e[0].product,events:e})}}authorizeWithBackoff(){if(!this.consequentAuthErrors)return this.doAuthorize();let e=z.getExponentialDelay(this.consequentAuthErrors);return new Promise(t=>{this.backoffTimeoutId||=window.setTimeout(async()=>{try{t(await this.doAuthorize())}catch(e){this.params.error$.next({id:`AuthorizeBackoff`,category:z.ErrorCategory.NETWORK,message:`Otherwise unhandled error in authorization`,thrown:e})}finally{this.backoffTimeoutId=0}},e)})}doAuthorize(){if(this.authorizePromise)return this.authorizePromise;this.sessionKey=void 0,this.authorized$.next(!1);let e={session_data:{version:2,device_id:this.params.deviceId,client_version:D.split(`-`)[0],client_type:`SDK_JS`}};return this.authToken!==void 0&&(e.session_data.auth_token=this.authToken,e.session_data.version=3),this.authorizePromise=this.params.apiTransport.sendRequest(`auth.anonymLogin`,e).then(e=>((!e||!e.session_key)&&this.params.error$.next({id:`AuthorizeFailed`,category:z.ErrorCategory.EXTERNAL_API,message:`No session key`,data:e}),this.sessionKey=e?.session_key??void 0,this.sessionKey)).catch(async e=>{this.sessionKey=void 0;let t=e?.error_code;switch(t){case 401:return this.authToken=await this.refreshAuthToken(),this.authorizeWithBackoff()}t?this.params.error$.next({id:`Authorize#${t}`,category:z.ErrorCategory.EXTERNAL_API,message:`authorize error`,data:e}):this.params.error$.next({id:`AuthorizeUnknown`,category:z.ErrorCategory.NETWORK,message:`authorize error`,thrown:e})}).finally(()=>{this.authorizePromise=void 0,this.consequentAuthErrors=this.sessionKey?0:this.consequentAuthErrors+1,this.authorized$.next(this.sessionKey!==void 0)}),this.authorizePromise}}var Pe=require(`@vkontakte/videoplayer-shared`),B=require(`@vkontakte/videoplayer-shared`);class Fe{params;apiKey;apiBaseUrl;apiEnv;isApiBaseUrlFetched;timeSynchronisation;constructor(e){this.params=e,this.apiKey=e.config.apiKey,this.apiEnv=e.config.apiEnv,this.apiBaseUrl=e.config.apiBaseUrl??Ae[this.apiEnv],this.timeSynchronisation=e.timeSynchronisation,this.isApiBaseUrlFetched=!1}sendBeacon(e,t,n){if(!window.Blob||!window.navigator.sendBeacon)return!1;let r=this.prepareQueryParams({method:e,queryParams:t,sessionKey:n}),i=new window.Blob([r.toString()],{type:`application/x-www-form-urlencoded`});try{return window.navigator.sendBeacon(`${this.apiBaseUrl}/fb.do`,i)}catch(n){this.params.error$.next({id:`OneStat:ApiTransport:sendBeacon`,category:B.ErrorCategory.NETWORK,message:`Unhandled beacon error`,thrown:n,data:{method:e,params:t}})}return!1}async sendRequest(e,t,n,r){let i=B.now(),a=r=>{if(r instanceof TypeError&&[`Failed to fetch`,`NetworkError when attempting to fetch resource.`].includes(r.message)){this.params.error$.next({id:`Network`,category:B.ErrorCategory.NETWORK,message:`Request failed`,thrown:r});return}this.params.error$.next({id:`ThinOneStat:ApiTransport:sendRequest`,category:B.ErrorCategory.NETWORK,message:`Unhandled request error`,thrown:r,data:{method:e,params:t,sessionKey:n,time:B.now()-i}})};return this.apiBaseUrl=await this.resolveApiBaseUrl(),Pe.fetchPolyfilled(`${this.apiBaseUrl}/fb.do`,{method:`post`,headers:{"Content-type":`application/x-www-form-urlencoded`,...r},body:this.prepareQueryParams({method:e,queryParams:t,sessionKey:n})}).then(e=>{let t=Number(e.headers.get(`content-length`))===0,n=new Date(e.headers.get(`date`)??``).getTime(),r=B.now()-i;if(isFinite(n)&&this.timeSynchronisation?.addServerTime(n,r),!t)return e.json().then(e=>Object.prototype.hasOwnProperty.call(e,`error_msg`)?Promise.reject(e):e,a)},a)}async resolveApiBaseUrl(){if(this.apiEnv!==`auto`||this.isApiBaseUrlFetched)return this.apiBaseUrl;try{let e=atob(`aHR0cHM6Ly9kbnMuZ29vZ2xlL3Jlc29sdmU/bmFtZT12aWRlby5fZW5kcG9pbnQub2sucnUmdHlwZT1UWFQ=`),t=(await(await Pe.fetchPolyfilled(e,{method:`GET`,mode:`cors`,cache:`no-cache`})).json())?.Answer[0]?.data;if(!t)throw Error(`Wrong DNS response`);return t}catch(e){return this.params.error$.next({id:`ThinOneStat:ApiTransport:resolveApiBaseUrl`,category:B.ErrorCategory.NETWORK,message:`Unhandled resolve api base url error`,thrown:e}),Ae.vk_alias}finally{this.isApiBaseUrlFetched=!0}}prepareQueryParams(e){let t=new URLSearchParams({format:`JSON`,method:e.method,application_key:this.apiKey});return e.sessionKey!==void 0&&t.append(`session_key`,e.sessionKey),Object.entries(e.queryParams).forEach(([e,n])=>t.append(e,typeof n==`string`?n:JSON.stringify(n))),t}}var V=require(`@vkontakte/videoplayer-shared`),H=`thinonestat_events`,U=e=>t=>t.client_time+e>=V.now();class Ie{params;api;error$;subscription;userSalt;unsaltedStorage=[];lastVsid;isPaused=!1;firstFlush;debouncedFlush;loggerDebugLog;constructor(e){this.params=e,this.api=e.api,this.error$=e.error$,this.userSalt=e.userSalt,this.loggerDebugLog=e.debugLogger.createComponentLog(`stat logger`),this.firstFlush=V.debounceFn(()=>this.safeFlush(),this.params.config.firstFlushTime,{maxWait:this.params.config.firstFlushTime});let t=V.safeStorage.isPersistent()?this.params.config.flushMaxWait:0;this.debouncedFlush=V.debounceFn(()=>this.safeFlush(),this.params.config.flushDebounceTime,{maxWait:t}),this.subscription=this.api.authorized$.subscribe(e=>{e&&this.debouncedFlush()}),this.housekeepStorage()}isUrgent=e=>{let{event_name:t}=e;return[`watch_coverage`,`watch_coverage_live`,`watched_n`,`playback_started`].includes(t)};safeFlush(){try{this.flush()}catch(e){this.error$.next({id:`LoggerError`,category:V.ErrorCategory.WTF,message:String(e)||`Unknown logger error`,thrown:e})}}readFromStorage(){let e=V.safeStorage.get(H);try{return e?JSON.parse(e):{}}catch{}return{}}addToStorage(e){if(!this.userSalt){this.unsaltedStorage.push(e);return}let t=this.readFromStorage(),n=(t[this.userSalt]??[]).filter(U(this.params.config.storageExpiration));V.safeStorage.set(H,JSON.stringify({...t,[this.userSalt]:[...n,e]}))}getFromStorage(){return this.userSalt?(this.readFromStorage()[this.userSalt]??[]).filter(U(this.params.config.storageExpiration)):this.unsaltedStorage}markStorageSent(){if(!this.userSalt){this.unsaltedStorage=[];return}let e=this.readFromStorage();delete e[this.userSalt],V.safeStorage.set(H,JSON.stringify(e))}housekeepStorage(){let e=this.readFromStorage();for(let[t,n]of Object.entries(e)){let r=n.filter(U(this.params.config.storageExpiration));r.length?e[t]=r:delete e[t],this.loggerDebugLog({message:`${n.length} retrieved from storage, ${r.length} of them actual`})}V.safeStorage.set(H,JSON.stringify(e))}log(e){this.addToStorage(e),!this.isPaused&&(this.isUrgent(e)?this.flush():this.lastVsid===e.vsid?this.debouncedFlush():this.firstFlush(),this.lastVsid=e.vsid)}flush({wantBeacon:e,clearStorage:t}={wantBeacon:!1,clearStorage:!0}){let n=this.getFromStorage();n.length!==0&&(this.api.authorized$.getValue()?(e&&this.params.config.useBeacon?(this.loggerDebugLog({message:`Flushing ${n.length} events through beacon`}),this.api.logBeacon(n)):(this.loggerDebugLog({message:`Flushing ${n.length} events`}),this.api.logRequest(n)),t&&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 Le(){let e=`0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz`.split(``),t=Array(36),n=0,r,i;for(i=0;i<36;i++)i===8||i===13||i===18||i===23?t[i]=`-`:i===14?t[i]=`4`:(n<=2&&(n=33554432+Math.random()*16777216|0),r=n&15,n>>=4,t[i]=e[i===19?r&3|8:r]);return t.join(``)}class Re{offset=void 0;constructor(e){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,t){let n=e-Date.now()-t/2;if(Math.abs(n)<1e3){this.offset=0;return}if(this.offset===void 0)this.offset=Math.round(n);else{let e=.2;this.offset=Math.round(e*n+(1-e)*this.offset)}}}var ze=require(`@vkontakte/videoplayer-core`),W=require(`@vkontakte/videoplayer-shared`),Be=(e,t,n)=>new W.Observable(r=>{let i=new W.Subscription,a=new W.ValueSubject(void 0),o;i.add(e.info.isLive$.pipe(W.filterChanged()).subscribe(t=>{o&&(o.unsubscribe(),a.next(void 0)),o=t?e.info.liveTime$.pipe(W.filterChanged()).subscribe(a):e.info.position$.subscribe(a),i.add(o)}));let{playing$:s,paused$:c,ended$:l,looped$:u}=e.events,d=e.events.willSeek$.pipe(W.filter(()=>e.info.playbackState$.getValue()===ze.PlaybackState.PLAYING)),f=e.events.seeked$.pipe(W.filter(()=>e.info.playbackState$.getValue()===ze.PlaybackState.PLAYING)),p=!1,m=new W.Subject;i.add(d.subscribe(()=>{p||m.next(),p=!0})).add(f.subscribe(()=>p=!1));let h=W.merge(W.fromEvent(W.getWindow(),`beforeunload`),e.events.willDestruct$),g,_=()=>g=a.getValue(),v=()=>{let e=a.getValue();W.isNullable(g)||W.isNullable(e)||g===e||(r.next({from:g,to:e}),g=void 0)},y=new W.Subject,b=new W.Subject,ee=W.merge(s,f,y),x=W.merge(c,m,h,l,u,b),S=t.started$&&t.ended$?W.merge(ee,t.ended$):ee,C=t.started$&&t.ended$?W.merge(x,t.started$):x;if(i.add(S.subscribe(_)).add(C.subscribe(v)),n.heartbeatInterval&&isFinite(n.heartbeatInterval)){let e=[],t=()=>{b.next(),y.next()};i.add(S.subscribe(()=>{let r=W.getWindow().setTimeout(t,n.heartbeatInterval);e.push(r)})).add(C.subscribe(()=>{e.forEach(e=>{W.getWindow().clearTimeout(e)}),e=[]}))}return i}),Ve=require(`@vkontakte/videoplayer-core`),He=require(`@vkontakte/videoplayer-shared`),Ue=(e,t)=>new He.Observable(n=>{let r=new Ve.Subscription;return r.add(He.merge(e.info.position$,e.info.liveTime$).subscribe(()=>{let e=t.getTotalViewTime();e>=t.targetDuration&&(n.next({target_duration:t.targetDuration,current_tvt:e}),r.unsubscribe())})),r}),We=require(`@vkontakte/videoplayer-core`),G=require(`@vkontakte/videoplayer-shared`),Ge=(e,{maxTimeWindow:t})=>new G.Observable(n=>{let r=new We.Subscription,i={maxBytesThreshold:100*1024*1024,minBytesThreshold:100*1024,maxTimeWindow:t,minTimeWindow:2e3},a={bytes:0,startTime:0,lastEmitTime:0,timeoutId:0},o=()=>{a.timeoutId&&=(G.getWindow().clearTimeout(a.timeoutId),null)},s=()=>{a.bytes=0,a.startTime=0,a.lastEmitTime=0,o()},c=e=>{if(a.bytes<i.minBytesThreshold||e-a.lastEmitTime<i.minTimeWindow&&a.lastEmitTime>0)return!1;let t=(a.startTime>0?e-a.startTime:0)>=i.maxTimeWindow,n=a.bytes>=i.maxBytesThreshold;return t||n},l=(e=!1)=>{let t=Date.now();if(!e&&!c(t))return;o();let r=a.startTime>0?t-a.startTime:Math.max(i.minTimeWindow,1),l=a.bytes/(r/1e3);n.next({download_bytes:Math.round(a.bytes),download_speed:Math.round(l)}),a.lastEmitTime=t,s()},u=()=>{if(o(),a.startTime>0&&a.bytes>=i.minBytesThreshold){let e=Date.now()-a.startTime,t=i.maxTimeWindow-e;t>100?a.timeoutId=G.getWindow().setTimeout(()=>{a.timeoutId=null,l()},t):t>0&&l()}};return r.add(e.info.httpDownloadMetrics$.pipe(G.filter(e=>e!==void 0)).subscribe(e=>{let t=Date.now();a.startTime===0&&(a.startTime=t),a.bytes+=e.bytes,c(t)?l():u()})),r.add(()=>{if(o(),a.bytes>0){let e=Date.now(),t=a.startTime>0?e-a.startTime:i.minTimeWindow,r=a.bytes/(t/1e3);n.next({download_bytes:Math.round(a.bytes),download_speed:Math.round(r)})}s()}),r}),K=require(`@vkontakte/videoplayer-shared`),Ke=e=>new K.Observable(t=>{let n=new K.Subscription,r=0,i=1,a=0,o=!1,s=!1,c=()=>{if(!o)return;let e=Date.now();a+=(e-r)*i,r=e},l=()=>{(!o||s)&&(r=Date.now(),o=!0,s=!1)},u=()=>{o&&=(c(),!1)},d=()=>{o&&(c(),o=!1,s=!0)},f=e=>{o&&c(),i=e,r=Date.now()},{started$:p,playing$:m,paused$:h,willSeek$:g,ended$:_,willDestruct$:v}=e.events,{currentPlaybackRate$:y}=e.info;return n.add(g.subscribe(d)).add(K.merge(p,m).subscribe(l)).add(K.merge(h,_,v).subscribe(u)).add(y.subscribe(f)),t.next(()=>{let e=a;return o&&(e+=(Date.now()-r)*i),e}),n}),q=require(`@vkontakte/videoplayer-shared`),qe=(e,t)=>new q.Observable(n=>{let r=new q.Subscription,i=0;return r.add(q.merge(e.info.position$,e.info.liveTime$).subscribe(()=>{let e=t.getTotalViewTime();e>i&&Math.floor(e/t.interval)>Math.floor(i/t.interval)&&(i=e,n.next())})),r}),Je=require(`@vkontakte/videoplayer-shared`),J=require(`@vkontakte/videoplayer-core`),Ye=e=>e&&{[J.HttpConnectionType.HTTP1]:`http1`,[J.HttpConnectionType.HTTP2]:`http2`,[J.HttpConnectionType.QUIC]:`http3`}[e],Y=e=>{if(e!==void 0)switch(e){case J.VideoFormat.MPEG:return`MP4`;case J.VideoFormat.DASH:case J.VideoFormat.DASH_LIVE:return`DASH`;case J.VideoFormat.DASH_SEP:return`DASH_SEP`;case J.VideoFormat.DASH_ONDEMAND:return`ONDEMAND_DASH`;case J.VideoFormat.HLS_ONDEMAND:return`ONDEMAND_HLS`;case J.VideoFormat.HLS:case J.VideoFormat.HLS_LIVE:return`HLS`;case J.VideoFormat.HLS_FMP4:return`HLS_FMP4`;case J.VideoFormat.DASH_WEBM:case J.VideoFormat.DASH_LIVE_WEBM:return`WEBM`;case J.VideoFormat.DASH_LIVE_CMAF:return`ONDEMAND_DASH_LIVE`;case J.VideoFormat.HLS_LIVE_CMAF:return`ONDEMAND_HLS_LIVE`;case J.VideoFormat.WEB_RTC_LIVE:return`WEBRTC`;case J.VideoFormat.DASH_WEBM_AV1:return`AV1`;case J.VideoFormat.DASH_STREAMS:return`MULTI_DASH`;default:return Je.assertNever(e)}},X=e=>{if(e!==void 0)switch(e){case J.VideoQuality.Q_144P:return`144p`;case J.VideoQuality.Q_240P:return`240p`;case J.VideoQuality.Q_360P:return`360p`;case J.VideoQuality.Q_480P:return`480p`;case J.VideoQuality.Q_720P:return`720p`;case J.VideoQuality.Q_1080P:return`1080p`;case J.VideoQuality.Q_1440P:return`1440p`;case J.VideoQuality.Q_2160P:return`2160p`;case J.VideoQuality.INVARIANT:case J.VideoQuality.Q_576P:case J.VideoQuality.Q_4320P:return`UNKNOWN`;default:return Je.assertNever(e)}},Xe=e=>{if(e!==void 0)switch(e){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}},Z=(e,t,n)=>{if(e&&t)switch(e){case J.VideoFormat.MPEG:return n&&t[e]&&t[e][n];default:return t[e]?.url}},Ze=(e,t=!1)=>{if(t)return`minimal`;switch(e){case void 0:case J.Surface.NONE:return;case J.Surface.INLINE:return`inline`;case J.Surface.FULLSCREEN:return`fullscreen`;case J.Surface.SECOND_SCREEN:return`chromecast`;case J.Surface.PIP:return`pip_external`}},Q=e=>{switch(e){case void 0:return;case J.Surface.INVISIBLE:return`background`;default:return`foreground`}},Qe=`_thin-one-stat_deviceId`,$e=()=>{let e=new L.Subscription;return{subscription:e,subscribe:(t,n)=>{t&&e.add(t.subscribe(n))}}};class et{api;logger;config;subscription;beforeunloadSubscription;timeSynchronisation;statContext;deviceId;targetDuration;debugLogger=new L.Logger;thinOneStatDebugLog=this.debugLogger.createComponentLog(`ThinOneStat`);eventNumber=1;isStarted;wasPaused;isLive;position;cdnHostname;isEmbed;embedHostname;connectionType;connectionReused;player;playerSize={width:0,height:0};currentSubtitle;userQuality;downloadQuality;downloadSpeed;networkType;uiEvents;seekAction$=new L.ValueSubject(`unknown`);get vsid$(){return new L.ValueSubject(E.getVSID())}isid$=new L.ValueSubject(void 0);getTotalViewTime=()=>0;constructor(e,t){this.statContext=e,this.config=Me(t.config??{}),this.subscription=new L.Subscription,this.config.synchronizeTime&&(this.timeSynchronisation=new Re);let n=new L.Subject,r=L.safeStorage.get(Qe);this.statContext.deviceId?this.deviceId=this.statContext.deviceId:r?this.deviceId=r:(this.deviceId=Le(),L.safeStorage.set(Qe,this.deviceId)),this.statContext.targetDuration?this.targetDuration=this.statContext.targetDuration:this.targetDuration=this.config.watchedNDefaultTargetDuration,this.resetViewSession(),t.useIsid&&this.isid$.next(t.isid??T());let i=new Fe({error$:n,config:this.config,timeSynchronisation:this.timeSynchronisation});this.api=new Ne({config:this.config,apiTransport:i,error$:n,deviceId:this.deviceId,refreshAuthToken:t.refreshAuthToken}),this.logger=new Ie({config:this.config,debugLogger:this.debugLogger,api:this.api,error$:n,userSalt:t.userSalt});let{isEmbed:a,topOrigin:o}=L.detectEmbed();this.isEmbed=a,this.embedHostname=o?new URL(o).hostname:void 0}authorize(e){return this.api.authorize(e)}updateContext(e){this.statContext={...this.statContext,...e}}attachTo(e,t){let n=new L.Subscription,r=(e,t)=>n.add(e.subscribe(t));r(Ke(e),e=>{this.getTotalViewTime=e}),r(e.info.isLive$,e=>this.isLive=e),r(e.info.hostname$.pipe(L.filter(e=>e!==void 0)),e=>{this.cdnHostname=e});let i;r(L.combine({hostname:e.info.hostname$,connectionType:e.info.httpConnectionType$,connectionReused:e.info.httpConnectionReused$}).pipe(L.filter(({hostname:e})=>e!==void 0),L.filter(({connectionType:e})=>e!==void 0),L.filter(({connectionReused:e})=>e!==void 0)),({hostname:t,connectionType:n,connectionReused:r})=>{if(i!==void 0&&i!==t){let i={cdn_host:t,connection_type:Ye(n),connection_reused:r,content_type:Y(e.info.currentFormat$.getValue())};this.logFailover(i)}this.cdnHostname=i=t}),r(e.info.httpConnectionType$,e=>{this.connectionType=Ye(e)}),r(e.info.httpConnectionReused$,e=>{this.connectionReused=e}),r(Be(e,t,{heartbeatInterval:this.config.watchCoverageHeartbeatInterval}),t=>{let n={watch_interval:`${Math.round(t.from*1e3)}-${Math.round(t.to*1e3)}`,in_history:!!this.statContext.inHistory,content_type:Y(e.info.currentFormat$.getValue()),playback_quality:X(e.info.currentQuality$.getValue()),recom_info:this.statContext.recomInfo};if(!e.info.isLive$.getValue())this.logWatchCoverage(n);else{let t=e.info.atLiveEdge$.getValue();this.logWatchCoverageLive({...n,live:!!t})}}),r(qe(e,{interval:this.statContext.telemetryInterval??this.config.telemetryInterval,getTotalViewTime:this.getTotalViewTime}),()=>{this.logTelemetry(this.collectTelemetryData())}),r(Ue(e,{targetDuration:this.targetDuration,getTotalViewTime:this.getTotalViewTime}),e=>{this.logWatchedN(e)}),r(e.events.willReady$,()=>{if(this.statContext.preload){let t=e.info.currentFormat$.getValue(),n=e.info.availableSources$.getValue(),r=e.info.currentBuffer$.getValue(),i=e.info.currentQuality$.getValue(),a={target_buffer_time:this.calcBufferTime(r),playback_url:Z(t,n,i),playback_quality:X(i)};this.logPreloadStarted(a)}}),r(L.combine({manifestRequested$:e.events.manifestRequested$,connectionType:e.info.httpConnectionType$,connectionReused:e.info.httpConnectionReused$}).pipe(L.filter(({connectionType:e})=>e!==void 0),L.filter(({connectionReused:e})=>e!==void 0),L.once()),()=>{let t={playback_url:Z(e.info.currentFormat$.getValue(),e.info.availableSources$.getValue(),e.info.currentQuality$.getValue()),cdn_host:this.cdnHostname,connection_type:this.connectionType,connection_reused:this.connectionReused};this.logManifestRequest(t)}),r(L.combine({firstBytesManifest:e.events.firstBytesManifest$,connectionType:e.info.httpConnectionType$,connectionReused:e.info.httpConnectionReused$}).pipe(L.filter(({connectionType:e})=>e!==void 0),L.filter(({connectionReused:e})=>e!==void 0),L.once()),()=>{let t={playback_url:Z(e.info.currentFormat$.getValue(),e.info.availableSources$.getValue(),e.info.currentQuality$.getValue()),cdn_host:this.cdnHostname,connection_type:this.connectionType,connection_reused:this.connectionReused};this.logFirstByteManifest(t)}),r(e.events.manifestReceived$,()=>{let t={playback_url:Z(e.info.currentFormat$.getValue(),e.info.availableSources$.getValue(),e.info.currentQuality$.getValue()),cdn_host:this.cdnHostname,connection_type:this.connectionType,connection_reused:this.connectionReused};this.logManifestReceived(t)}),r(e.events.firstBytesRequested$,()=>{let t={playback_url:Z(e.info.currentFormat$.getValue(),e.info.availableSources$.getValue(),e.info.currentQuality$.getValue()),cdn_host:this.cdnHostname,connection_type:this.connectionType,connection_reused:this.connectionReused};this.logFirstMediaRequest(t)}),r(e.events.firstBytesReceived$,()=>{let t={playback_url:Z(e.info.currentFormat$.getValue(),e.info.availableSources$.getValue(),e.info.currentQuality$.getValue()),cdn_host:this.cdnHostname,connection_type:this.connectionType,connection_reused:this.connectionReused};this.logFirstByteMedia(t)}),r(L.merge(e.events.willStart$,e.events.looped$),t=>{t&&this.resetViewSession();let n={isid:this.isid$.getValue(),stream_profile:Xe(Y(e.info.currentFormat$.getValue())),dpi:this.statContext.dpi??96*R.clientChecker.display.pixelRatio,web_layout:this.statContext.isMobile||R.clientChecker.device.isMobile?`mobile`:`desktop`,preloaded:this.statContext.preload,navigation:this.statContext.navigation,recom_info:this.statContext.recomInfo};this.isEmbed&&(n.iframe_host=this.embedHostname??`unknown`),this.logStartSession(n)}),r(e.events.started$,()=>{this.isStarted=!0;let t=e.info.currentBuffer$.getValue(),n=e.info.currentQuality$.getValue(),r=e.info.isAutoQualityEnabled$.getValue(),i=e.info.muted$.getValue(),a=e.info.volume$.getValue(),o=e.info.surface$.getValue(),s=e.info.availableTextTracks$.getValue(),c=e.info.currentTextTrack$.getValue(),l=e.info.currentAudioStream$.getValue(),u=e.info.currentPlaybackRate$.getValue(),d={playback_quality:X(n),user_quality:r?`auto`:X(n),player_width:this.statContext.playerSize?.width??this.playerSize.width,player_height:this.statContext.playerSize?.height??this.playerSize.height,muted:i,sound_volume:Math.round(a*100),buffer_time:this.calcBufferTime(t),mode:Ze(o,this.statContext.isPreviewPlayerView),visibility:Q(o),subtitles_enabled:c?!!c:this.currentSubtitle?.enabled,auto_subtitles:s.find(({id:e})=>e===c)?.isAuto??this.currentSubtitle?.auto,audio_track_lang:l?.language,playback_rate:u,recom_info:this.statContext.recomInfo};this.logPlaybackStarted(d)}),r(e.events.willStart$,()=>{this.logPlay()}),r(e.events.playing$,()=>{let t=e.info.currentBuffer$.getValue(),n={buffer_time:this.calcBufferTime(t)};this.logPlaying(n),this.wasPaused&&this.logResume()}),r(e.events.paused$,()=>{this.wasPaused=!0,this.logPause()}),r(e.events.willStop$,()=>{this.isStarted=!1,this.logStop()}),r(L.merge(e.events.fetcherRecoverableError$,e.events.fatalError$),()=>{this.statContext.preload&&this.logPreloadError()});let a=e=>{switch(e){case L.ErrorCategory.NETWORK:return`network`;case L.ErrorCategory.VIDEO_PIPELINE:return`video_pipeline`;case L.ErrorCategory.EXTERNAL_API:return`external_api`;case L.ErrorCategory.PARSER:return`parser`;case L.ErrorCategory.DOM:return`dom`;default:return`wtf`}},o=e=>L.ErrorCategory.FATAL===e?`critical`:`informative`;r(e.events.fetcherRecoverableError$,({id:t,category:n,data:r,message:i,httpCode:s,UVBackendErrorCode:c})=>{let l={error_severity:o(n),error_category:a(n),player_error_code:t,player_error_trace:r,http_error_code:s,uv_backend_error_code_subcode:c,error_message:i,content_type:Y(e.info.currentFormat$.getValue())};this.logError(l),o(n)===`critical`&&this.logCannotPlay()}),r(e.events.managedError$,({id:t,category:n,data:r,message:i})=>{let s={error_severity:o(n),error_category:a(n),player_error_code:t,player_error_trace:r,error_message:i,content_type:Y(e.info.currentFormat$.getValue())};this.logError(s)}),r(e.events.fatalError$,({id:t,category:n,data:r,message:i})=>{let o={error_severity:`critical`,error_category:a(n),player_error_code:t,player_error_trace:r,error_message:i,content_type:Y(e.info.currentFormat$.getValue())};this.logError(o),this.logCannotPlay()}),r(L.combine({connectionType:e.info.httpConnectionType$,connectionReused:e.info.httpConnectionReused$,connectionMetrics:e.info.httpConnectionMetrics$}).pipe(L.filter(({connectionReused:e})=>e!==void 0),L.filter(({connectionMetrics:e})=>e!==void 0),L.filterChanged((e,t)=>e.connectionType===t.connectionType)),({connectionMetrics:t})=>{let n=e.info.currentFormat$.getValue(),r=e.info.availableSources$.getValue(),i=e.info.currentQuality$.getValue(),a=e.info.rttEstimation$.getValue();this.networkType=this.statContext.networkType??t?.networkType;let o={playback_url:Z(n,r,i),cdn_host:this.cdnHostname,connection_type:this.connectionType,connection_reused:this.connectionReused,rtt:a?Math.round(a):void 0,network_type:this.networkType,dns_resolve_time:t?.dnsResolveTime,tcp_handshake_time:t?.tcpHandshakeTime,tls_handshake_time:t?.tlsHandshakeTime};this.logConnectionEstablished(o)}),r(Ge(e,{maxTimeWindow:this.config.downloadBytesMaxTime}),e=>{this.downloadSpeed=e.download_speed,this.logDownloadBytes(e)}),r(e.events.firstFrame$,()=>{this.logFirstVideoFrameDecoded()}),r(e.events.willSeek$,()=>{let e={seek_type:this.seekAction$.getValue()};this.isStarted&&this.logSeeking(e)}),r(e.events.seeked$,()=>{let e={seek_type:this.seekAction$.getValue()};this.isStarted&&this.logSeeked(e),this.seekAction$.next(`unknown`)}),r(e.info.isStalled$,t=>{let n=e.info.currentBuffer$.getValue(),r=this.calcBufferTime(n);t&&r&&r>0&&this.logBufferStarvation({buffer_time:r})}),r(e.info.currentBuffer$.pipe(L.filter(e=>!!this.calcBufferTime(e)),L.once()),e=>{let t=this.calcBufferTime(e);if(this.statContext.preload){let e={buffer_time:t};this.logPreloadEnded(e)}this.logReady({buffer_time:t})});let s;r(L.combine({videoStream:e.info.currentVideoStream$,audioStream:e.info.currentAudioStream$,quality:e.info.currentQuality$}).pipe(L.filter(({videoStream:e,audioStream:t})=>e!==void 0&&t!==void 0),L.filter(({quality:e})=>e!==void 0)),({videoStream:t,audioStream:n,quality:r})=>{if(s!==r){if(this.userQuality=e.info.isAutoQualityEnabled$.getValue()?`auto`:X(r),this.downloadQuality=X(r),this.isStarted){let e=t?.codec,r=n?.codec,i={user_quality:this.userQuality,playback_quality:X(s),download_quality:this.downloadQuality,codec_info:this.genCodecInfo(e,r)};this.logQualityChanged(i)}s=r}});let c,l;return r(e.info.surface$,e=>{let t=Ze(e,this.statContext.isPreviewPlayerView);t&&!this.uiEvents&&this.isStarted&&this.logModeChanged({mode:t}),l=Q(e),c!==l&&(this.isStarted&&this.logVisibilityChanged({visibility:l}),c=Q(e))}),r(L.combine({muted:e.info.muted$,volume:e.info.volume$}).pipe(L.debounce(300)),({muted:e,volume:t})=>{if(this.isStarted){let n={muted:e,sound_volume:Math.round(t*100)};this.logSoundChanged(n)}}),r(e.info.currentFormat$.pipe(L.filter(e=>e!==void 0),L.skip(1)),e=>{let t={content_type:Y(e),cdn_host:this.cdnHostname,connection_type:this.connectionType,connection_reused:this.connectionReused};this.logContentTypeChange(t)}),r(e.info.currentAudioStream$.pipe(L.filter(e=>e!==void 0),L.skip(1)),e=>{let t={audio_track_lang:e.language,codec_info:e.codec};this.logAudioTrackSwitched(t)}),r(e.info.currentVideoStream$.pipe(L.filter(e=>e!==void 0),L.skip(1)),e=>{let t={hdr:e.hdr,codec_info:e.codec};this.logVideoTrackSwitched(t)}),this.player=e,this.resubscribeBeforeunload(),this.subscription.add(n),n}attachToUi(e){this.uiEvents=e;let{subscribe:t,subscription:n}=$e();t(e.actionSeek$,this.seekAction$),t(e.playerSize$,({width:e,height:t})=>{e&&t&&(this.playerSize={width:e,height:t},this.isStarted&&this.logViewPortChanged({player_width:e,player_height:t}))}),t(e.isLoaderVisible$,e=>{e&&this.isStarted&&this.logShowLoader()}),t(e.actionSubtitlesSwitched$,e=>{if(this.currentSubtitle={...e},this.isStarted){let t={subtitles_enabled:e.enabled,subtitles_track_lang:e.lang,auto_subtitles:e.auto};this.logSubtitlesSwitched(t)}});let{surface$:r}=Se(this.uiEvents,t,this.player);return t(r,e=>{this.isStarted&&this.logModeChanged({mode:Ze(e)})}),t(e.actionQuality$,e=>{let t=e=>Object.values(De).includes(e),n=this.player?.info.currentVideoStream$.getValue()?.codec,r=this.player?.info.currentAudioStream$.getValue()?.codec,i={user_quality:t(e)?`auto`:X(e),playback_quality:X(this.player?.info.currentQuality$.getValue()),download_quality:t(e)?X(this.player?.info.currentQuality$?.getValue()):X(e),codec_info:this.genCodecInfo(n,r)};this.logQualityChangeRequested(i)}),this.resubscribeBeforeunload(),this.subscription.add(n),n}attachToAds(e){let{subscription:t,subscribe:n}=$e();return n(e.init$,e=>{let t={slot:e};this.logAdvConfiguration(t)}),n(e.slotRequested$,e=>{let t={adv_section:e};this.logAdvRequest(t)}),n(e.started$,e=>{let t={adv_section:e};this.logAdvBreakStarted(t)}),n(e.ended$,({section:e,ordIds:t})=>{let n={adv_section:e,erids:t.join(`,`)};this.logAdvBreakEnded(n)}),n(e.error$,e=>{let t={error_message:e};this.logAdvError(t)}),this.resubscribeBeforeunload(),this.subscription.add(t),t}getDeviceId(){return this.deviceId}resetViewSession(){this.thinOneStatDebugLog({message:`VSID reset`}),E.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}genCodecInfo(e,t){return e&&t?`${e},${t}`:void 0}getLatencyInfo(){let e=this.player?.info.atLiveEdge$.getValue(),t={client_time:Date.now(),live:e};return JSON.stringify(t)}collectTelemetryData(){if(!this.player)return{};let e=this.player.info.currentBuffer$.getValue(),t=this.player.experimental.element$.getValue(),n=0,r=0;t&&(n=t.getVideoPlaybackQuality().droppedVideoFrames,r=t.getVideoPlaybackQuality().totalVideoFrames);let i=Y(this.player.info.currentFormat$.getValue()),a=this.player.info.currentVideoStream$.getValue()?.codec,o=this.player.info.currentAudioStream$.getValue()?.codec,s=this.player.info.videoBitrate$.getValue(),c=this.player.info.rttEstimation$.getValue();return{buffer_time:this.calcBufferTime(e),dropped_frames_count:n,rendered_frames_count:r,content_type:i,user_quality:this.userQuality,playback_quality:X(this.player.info.currentQuality$.getValue()),download_quality:this.downloadQuality,codec_info:this.genCodecInfo(a,o),bandwidth_from_manifest:s,cdn_host:this.cdnHostname,download_speed:this.downloadSpeed,network_type:this.networkType,rtt:c?Math.round(c):void 0,latency:this.getLatencyInfo()}}createRequiredParams(e){let t=this.vsid$.getValue();L.assertNonNullable(t);let n=this.eventNumber++,r=((this.isLive?this.player?.info.liveTime$.getValue():this.player?.info.position$.getValue())??0)*1e3,i={vsid:t,uv_movie_id:this.statContext.movieId,event_name:e,client_time:Date.now(),application:this.statContext.application??`@vkontakte/videoplayer-statistics:${D}`,platform:this.statContext.platform??`web:${this.statContext.isMobile||R.clientChecker.device.isMobile?`mobile`:`desktop`}`,product:this.statContext.product,event_number:n,playback_position:Math.round(r),current_tvt:this.getTotalViewTime(),cdn_host:this.cdnHostname};for(let e of this.config.disabledParams)delete i[e];return i}createRequiredFatParams(){let e={stats_version:`2.1.1`,browser:this.statContext.browser??R.clientChecker.browser.current,browser_version:this.statContext.browserVersion??String(R.clientChecker.browser.currentVersion),os:this.statContext.os??R.clientChecker.device.os.name,os_version:this.statContext.osVersion??R.clientChecker.device.os.version,device_type:this.statContext.deviceType??(this.statContext.isMobile||R.clientChecker.device.isMobile?`mobile`:`desktop`),device_manufacturer:this.statContext.deviceManufacturer??R.clientChecker.device.details.vendor,device_model:this.statContext.deviceModel??R.clientChecker.device.details.model,navigation:this.statContext.navigation};for(let t of this.config.disabledParams)delete e[t];return e}log(e,t,n=!1){if(this.config.disabledEvents.includes(e))return;let r=this.createRequiredParams(e),i={};n&&(i=this.createRequiredFatParams()),this.logger.log({...r,...i,...t})}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)}logTelemetry(e){this.log(`telemetry`,e)}logAdvConfiguration(e){this.log(`adv_configuration`,e)}logAdvRequest(e){this.log(`adv_request`,e)}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=L.fromEvent(L.getWindow(),`beforeunload`).subscribe(()=>{}),this.subscription.add(this.beforeunloadSubscription)}}var tt=require(`@vkontakte/videoplayer-shared`),nt=require(`@vkontakte/videoplayer-shared`),$=require(`@vkontakte/videoplayer-core`),rt=require(`@vkontakte/videoplayer-shared`);class it{startTime=null;stopTime=null;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.startTime=this.now():(this.accumulatedTime+=this.now()-this.stopTime,this.stopTime=null))}stop(){this.isRunning&&(this.stopTime=this.now())}reset(){this.startTime=null,this.stopTime=null,this.accumulatedTime=0}now(){return Date.now()}}var at=()=>window.Image?new Image:document.createElement(`img`);class ot{params;position=0;started=!1;isActiveLive;heartbeatPixels=[];heartbeatLastTimeSent={};heartbeatInterval;heartbeatFirstTimeoutId;idleCallbackIds=[];log;stopwatch=new it;subscription=new $.Subscription;constructor(e){this.params=e,this.log=new rt.Logger().createComponentLog(`MediascopePixel`)}attachTo(e){this.subscription.add(e.info.playbackState$.subscribe(e=>this.onPlaybackState(e))).add(e.info.position$.subscribe(e=>this.onPosition(e))).add(e.info.atLiveEdge$.subscribe(e=>this.isActiveLive=e)),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=>tt.cancelIdleCallbackPolyfilled(e)),this.send(`stop`)}onPlaybackState(e){e===$.PlaybackState.PLAYING?this.started?this.play():this.start():e===$.PlaybackState.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,t=this.heartbeatPixels[0]?.delay;if(t!==void 0&&e)try{this.heartbeatFirstTimeoutId=window.setTimeout(()=>{this.sendHeartbeat(e)},t*1e3)}catch(e){this.log({message:e.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[e,{url:t}]of this.heartbeatPixels.entries())this.heartbeatLastTimeSent[e]!==this.stopwatch.time&&(this.heartbeatLastTimeSent[e]=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,t){return e?.filter(e=>e.event===t.event&&t.keys.every(t=>!!e[t]))}getFrameTimestamp(){let e;if(this.isActiveLive){let t=Math.floor(Math.random()*25)+5;e=Date.now()/1e3-t}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(e=>!/={@[a-zA-Z_]+}/.test(e)).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(nt.requestIdleCallbackPolyfilled(()=>at().src=this.prepareUrl(e)))}catch(e){this.log({message:e.message})}}send(e){let t=this.preparePixels(e);for(let{url:e}of t)this.call(e)}sendHeartbeat(e){this.call(e)}}
7
7
  //# sourceMappingURL=esnext.cjs.map