@vkontakte/videoplayer-statistics 1.0.110-dev.bd7a642f0.0 → 1.0.110-dev.f2fd80887.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/es2015.cjs CHANGED
@@ -1,6 +1,6 @@
1
1
  /**
2
- * @vkontakte/videoplayer-statistics v1.0.110-dev.bd7a642f0.0
3
- * Wed, 17 Jun 2026 10:29:48 GMT
2
+ * @vkontakte/videoplayer-statistics v1.0.110-dev.f2fd80887.0
3
+ * Wed, 17 Jun 2026 10:13:14 GMT
4
4
  * https://st.mycdn.me/static/vkontakte-videoplayer/1-0-110/doc/
5
5
  */
6
- const e=[`application`,`platform`,`product`];var t=require(`@oxc-project/runtime/helpers/defineProperty`),n=require(`@oxc-project/runtime/helpers/objectSpread2`),r=require(`@oxc-project/runtime/helpers/asyncToGenerator`),i=require(`@oxc-project/runtime/helpers/objectWithoutProperties`),a=Object.defineProperty,o=Object.getOwnPropertyNames,s=Object.getOwnPropertyDescriptor,c=Object.prototype.hasOwnProperty;function l(e){return this[e]}var u=e=>{var t=(d??=new WeakMap).get(e),n;if(t)return t;if(t=a({},`__esModule`,{value:!0}),e&&typeof e==`object`||typeof e==`function`)for(var r of o(e))c.call(t,r)||a(t,r,{get:l.bind(e,r),enumerable:!(n=s(e,r))||n.enumerable});return d.set(e,t),t},d,f=e=>e;function p(e,t){this[e]=f.bind(null,t)}var m=(e,t)=>{for(var n in t)a(e,n,{get:t[n],enumerable:!0,configurable:!0,set:p.bind(t,n)})},h={};m(h,{VERSION:()=>O,ThinOneStat:()=>Re,SeekAction:()=>S,Quality:()=>y,OneStat:()=>Le,MediascopePixel:()=>Vt,InteractiveInterfaceClick:()=>C,ContentType:()=>b,ConnectionType:()=>x,ApiEnv:()=>v}),module.exports=u(h);var g=require(`@vkontakte/videoplayer-shared`),_=require(`@vkontakte/videoplayer-shared`),v;(e=>{e.PROD=`prod`,e.VK_ALIAS=`vk_alias`,e.VIDEOTEST=`videotest`,e.TEST=`test`,e.OKCDN=`okcdn`,e.AUTO=`auto`})(v||={});var y;(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`})(y||={});var b;(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`})(b||={});var x;(e=>{e.HTTP1=`http1`,e.HTTP2=`http2`,e.HTTP3=`http3`})(x||={});var S;(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`})(S||={});var C;(e=>{e.GRAPH_SHOW=`iGraphShow`,e.GRAPH_HIDE=`iGraphHide`,e.NEXT_AREA=`iNextChapterArea`,e.NEXT_BUTTON=`iNextChapterBtn`,e.WATCH_AGAIN=`iWatchAgainBtn`})(C||={});var w={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`},ee={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`},te={unknown:`un`,mobile:`m`,lowest:`ls`,low:`l`,medium:`md`,high:`h`,fullhd:`f`,quadhd:`q`,ultrahd:`u`},ne={pip:`pi`,fullscreen:`fs`,external:`ex`,prefetch:`pr`,airplay:`ap`,chromecast:`cc`,invisible:`iv`,minimal:`minimal`},re=require(`@vkontakte/videoplayer-shared`),ie=`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:``},oe={apiEnv:`vk_alias`,apiKey:ie,apiBaseUrl:null,apiUvRestBaseUrl:`https://uvapi.okcdn.ru`,apiCollector:`ok.mobile.apps.video`,apiForticom:!0,apiUvRest:!1,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:!0,watchCoverageExactTime:!1},se=e=>re.fillWithDefault(e,oe);function ce(){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 T=require(`@vkontakte/videoplayer-shared`),le=require(`@vkontakte/videoplayer-shared`),ue=require(`@vkontakte/videoplayer-shared`),de=()=>ue.stringPadStart(Math.floor(Math.random()*2**32).toString(36),13,`0`),fe=()=>ue.stringPadStart(Math.floor(Math.random()*2**64).toString(36),13,`0`);class E{static getVSID(){return E.vsid}static generateVSID(e){return E.vsid=e?fe():de(),E.vsid}}t(E,`vsid`,void 0);var D=require(`@vkontakte/videoplayer-shared`),pe=require(`@vkontakte/videoplayer-shared`),me=require(`@vkontakte/videoplayer-shared`),he=e=>{let{operation:t,custom:r}=e,i=me.objectFromEntries(pe.objectEntries(r).map(([e,t])=>{let n=ee[e]??e,r=t;return t&&(e===`mode`?r=ne[t]??t:e===`quality`&&(r=te[t]??t)),[n,r]}));return n(n({},e),{},{operation:w[t]??t,custom:i})},O=`1.0.110-dev.bd7a642f0.0`,k=require(`@vkontakte/videoplayer-shared`),ge=/Mobile|mini|Fennec|Android|iP(ad|od|hone)|opera (mini|mobi)/i;class _e{constructor(e){t(this,`id`,`forticom`),t(this,`params`,void 0),t(this,`authToken`,void 0),t(this,`sessionKey`,void 0),t(this,`authorizePromise`,void 0),t(this,`refreshAuthTokenPromise`,void 0),t(this,`consequentAuthErrors`,0),t(this,`authorized$`,new k.ValueSubject(!1)),t(this,`backoffTimeoutId`,void 0),this.params=e}authorize(e){var t=this;return r(function*(){return t.authToken=e??(yield t.refreshAuthToken()),t._authorizeWithBackoff()})()}logBeacon(e){let t=this.createLogParams(e),n=this.sessionKey;n&&(this.params.apiTransport.sendBeacon(`log.externalLog`,t,n)||this.logRequest(e).catch(()=>{}))}logRequest(e){var t=this;return r(function*(){let n=`log.externalLog`,i=t.createLogParams(e),a=t.sessionKey??(yield t._authorizeWithBackoff());if(!a)return;let o=function(){var e=r(function*(e,r=t.params.config.requestRetryCount){try{return yield t.params.apiTransport.sendRequest(n,i,a)}catch(i){if(!i||!(`error_code`in i)){t.params.error$.next({id:`logRequestUnknown`,category:k.ErrorCategory.NETWORK,message:`Unknown ${n} error`,thrown:i});return}let a=i?.error_code;switch(a){case 102:case 103:case 104:return t.authorized$.next(!1),t.sessionKey=yield t._authorizeWithBackoff(),r>0?o(e,r-1):void 0;case 401:return t.authorized$.next(!1),t.authToken=yield t.refreshAuthToken(),t.sessionKey=yield t._authorizeWithBackoff(),r>0?o(e,r-1):void 0;default:t.params.error$.next({id:`LogRequest#${a}`,category:k.ErrorCategory.EXTERNAL_API,message:`${n} error`,data:i});return}}});return function(t){return e.apply(this,arguments)}}();return o(e)})()}destroy(){k.getWindow().clearTimeout(this.backoffTimeoutId),this.backoffTimeoutId=0}refreshAuthToken(){var e=this;return r(function*(){if(e.params.refreshAuthToken)return e.refreshAuthTokenPromise||=D.promiseFinally(e.params.refreshAuthToken(),()=>{e.refreshAuthTokenPromise=void 0}),e.refreshAuthTokenPromise})()}createLogParams(e){let t=`WEB`,n=!1,r=`@vkontakte/videoplayer-statistics:${O}`;if(this.params.config.useVKComIsMobileLogic){let{appVersion:e}=k.getWindow().navigator;n=ge.test(e)}else this.params.mobile&&(n=!0);return n&&(t=`M_WEB`),this.params.vktvVersion&&(t=`SMART_TV`,r=this.params.vktvVersion),{collector:this.params.config.apiCollector,data:JSON.stringify({application:r,platform:t,items:this.params.config.shorten?e.map(he):e})}}_authorizeWithBackoff(){if(!this.consequentAuthErrors)return this._authorize();let e=k.getExponentialDelay(this.consequentAuthErrors,this.params.config.backoff);return new Promise(t=>{this.backoffTimeoutId||=k.getWindow().setTimeout(()=>{D.promiseFinally(this._authorize().then(t).catch(e=>this.params.error$.next({id:`AuthorizeBackoff`,category:k.ErrorCategory.NETWORK,message:`Otherwise unhandled error in authorization`,thrown:e})),()=>this.backoffTimeoutId=0)},e)})}_authorize(){var e=this;return r(function*(){if(e.authorizePromise)return e.authorizePromise;e.sessionKey=void 0,e.authorized$.next(!1);let t={session_data:{version:2,device_id:e.params.deviceId,client_version:O.split(`-`)[0],client_type:`SDK_JS`}};return e.authToken!==void 0&&(t.session_data.auth_token=e.authToken,t.session_data.version=3),e.authorizePromise=D.promiseFinally(e.params.apiTransport.sendRequest(`auth.anonymLogin`,t).then(t=>((!t||!t.session_key)&&e.params.error$.next({id:`AuthorizeFailed`,category:k.ErrorCategory.EXTERNAL_API,message:`No session key`,data:t}),e.sessionKey=t?.session_key??void 0,e.sessionKey)).catch(function(){var t=r(function*(t){e.sessionKey=void 0;let n=t?.error_code;switch(n){case 401:return e.authToken=yield e.refreshAuthToken(),e._authorizeWithBackoff()}n?e.params.error$.next({id:`Authorize#${n}`,category:k.ErrorCategory.EXTERNAL_API,message:`authorize error`,data:t}):e.params.error$.next({id:`AuthorizeUnknown`,category:k.ErrorCategory.NETWORK,message:`authorize error`,thrown:t})});return function(e){return t.apply(this,arguments)}}()),()=>{e.authorizePromise=void 0,e.consequentAuthErrors=e.sessionKey?0:e.consequentAuthErrors+1,e.authorized$.next(e.sessionKey!==void 0)}),e.authorizePromise})()}}class ve{constructor(e){t(this,`id`,`uvrest`),t(this,`authorized$`,new k.ValueSubject(!1)),t(this,`params`,void 0),t(this,`statToken`,void 0),t(this,`authorizePromise`,void 0),t(this,`isDestroyed`,!1),this.params=e}authorize(e){var t=this;return r(function*(){if(!t.isDestroyed)return e?(t.statToken=e,t.authorized$.next(!0),e):t.authorizePromise?t.authorizePromise:(t.authorized$.next(!1),t.authorizePromise=D.promiseFinally(t.executeAuthorize(),()=>{t.authorizePromise=void 0,t.isDestroyed||t.authorized$.next(t.statToken!==void 0)}),t.authorizePromise)})()}logRequest(e){var t=this;return r(function*(){if(!e.length)return;let n=t.buildBody(e);try{let e=yield t.getValidToken();if(!e){t.params.error$.next({id:`OneStat:UvRestApi:LogRequestNoToken`,category:k.ErrorCategory.NETWORK,message:`No stat token available for log request`});return}yield t.params.apiTransport.sendJsonRequest(`/uv/stat/externalLog`,n,{Authorization:`Bearer ${e}`})}catch(e){(yield t.handleLogRequestError(e))&&(yield t.retryLogRequestAfterRecovery(n))}})()}logBeacon(e){if(!e.length)return;let t=this.statToken;if(!t)return;let n=this.buildBody(e);this.params.apiTransport.sendJsonBeacon(`/uv/stat/externalLog`,n,{Authorization:`Bearer ${t}`})}destroy(){this.isDestroyed=!0,this.authorizePromise=void 0,this.statToken=void 0,this.authorized$.next(!1)}getValidToken(){var e=this;return r(function*(){return e.statToken?e.statToken:e.authorize()})()}executeAuthorize(){var e=this;return r(function*(){try{let t=yield e.params.getAuthToken();if(e.isDestroyed)return;if(!t){e.params.error$.next({id:`OneStat:UvRestApi:NoToken`,category:k.ErrorCategory.EXTERNAL_API,message:`getAuthToken returned no token`});return}return e.statToken=t,e.statToken}catch(t){if(e.isDestroyed)return;e.params.error$.next({id:`OneStat:UvRestApi:AuthorizeFailed`,category:k.ErrorCategory.NETWORK,message:`Failed to get stat token`,thrown:t});return}})()}handleLogRequestError(e){var t=this;return r(function*(){let n=e?.status;return n===401?(t.params.error$.next({id:`OneStat:UvRestApi:TokenExpired`,category:k.ErrorCategory.EXTERNAL_API,message:`Stat token expired (401), refreshing`,thrown:e}),t.authorized$.next(!1),t.statToken=void 0,(yield t.authorize())!==void 0):(t.params.error$.next({id:`OneStat:UvRestApi:LogRequestFailed#${n??`unknown`}`,category:k.ErrorCategory.EXTERNAL_API,message:`Log request failed with status ${n}`,thrown:e}),!1)})()}retryLogRequestAfterRecovery(e){var t=this;return r(function*(){let n=t.statToken;if(!n){t.params.error$.next({id:`OneStat:UvRestApi:RetryNoToken`,category:k.ErrorCategory.NETWORK,message:`Cannot retry log request: no token after recovery`});return}try{yield t.params.apiTransport.sendJsonRequest(`/uv/stat/externalLog`,e,{Authorization:`Bearer ${n}`})}catch(e){t.params.error$.next({id:`OneStat:UvRestApi:RetryFailed`,category:k.ErrorCategory.EXTERNAL_API,message:`Log request failed after token refresh`,thrown:e})}})()}buildBody(e){let t=`WEB`,n=!1,r=`@vkontakte/videoplayer-statistics:${O}`;if(this.params.config.useVKComIsMobileLogic){let{appVersion:e}=k.getWindow().navigator;n=ge.test(e)}else this.params.mobile&&(n=!0);return n&&(t=`M_WEB`),this.params.vktvVersion&&(t=`SMART_TV`,r=this.params.vktvVersion),[{application:r,platform:t,user_id:this.params.userId,items:this.params.config.shorten?e.map(he):e}]}}var A=require(`@vkontakte/videoplayer-shared`),ye=require(`@vkontakte/videoplayer-shared`),be=require(`@vkontakte/videoplayer-shared`),j=require(`@vkontakte/videoplayer-shared`);class xe{constructor(e){t(this,`apiKey`,void 0),t(this,`apiBaseUrl`,void 0),t(this,`apiUvRestBaseUrl`,void 0),t(this,`apiEnv`,void 0),t(this,`timeSynchronisation`,void 0),t(this,`isApiBaseUrlFetched`,void 0),t(this,`params`,void 0),this.params=e,this.apiKey=e.config.apiKey,this.apiEnv=e.config.apiEnv,this.apiBaseUrl=e.config.apiBaseUrl??ae[this.apiEnv],this.apiUvRestBaseUrl=e.config.apiUvRestBaseUrl,this.timeSynchronisation=e.timeSynchronisation,this.isApiBaseUrlFetched=!1}resolveApiBaseUrl(){var e=this;return r(function*(){if(e.apiEnv!==`auto`||e.isApiBaseUrlFetched)return e.apiBaseUrl;try{var t;let e=atob(`aHR0cHM6Ly9kbnMuZ29vZ2xlL3Jlc29sdmU/bmFtZT12aWRlby5fZW5kcG9pbnQub2sucnUmdHlwZT1UWFQ=`),n=yield(yield A.fetchPolyfilled(e,{method:`GET`,mode:`cors`,cache:`no-cache`})).json(),r=n==null||(t=n.Answer[0])==null?void 0:t.data;if(!r)throw Error(`Wrong DNS response`);return r}catch(t){return e.params.error$.next({id:`OneStat:ApiTransport:resolveApiBaseUrl`,category:j.ErrorCategory.NETWORK,message:`Unhandled resolve api base url error`,thrown:t}),ae.vk_alias}finally{e.isApiBaseUrlFetched=!0}})()}sendBeacon(e,t,n){if(!j.getWindow().Blob||!j.getWindow().navigator.sendBeacon)return!1;let r=this._prepareQueryParams({method:e,queryParams:t,sessionKey:n}),i=j.getWindow().Blob,a=new i([r.toString()],{type:`application/x-www-form-urlencoded`});try{return j.getWindow().navigator.sendBeacon(`${this.apiBaseUrl}/fb.do`,a)}catch(n){this.params.error$.next({id:`OneStat:ApiTransport:sendBeacon`,category:j.ErrorCategory.NETWORK,message:`Unhandled beacon error`,thrown:n,data:{method:e,params:t}})}return!1}sendRequest(e,t,n){var i=this;return r(function*(){let r=j.now(),a=a=>{if(a instanceof TypeError&&ye.arrayIncludes([`Failed to fetch`,`NetworkError when attempting to fetch resource.`],a.message)){i.params.error$.next({id:`Network`,category:j.ErrorCategory.NETWORK,message:`Request failed`,thrown:a});return}i.params.error$.next({id:`OneStat:ApiTransport:sendRequest`,category:j.ErrorCategory.NETWORK,message:`Unhandled request error`,thrown:a,data:{method:e,params:t,sessionKey:n,time:j.now()-r}})};i.apiBaseUrl=yield i.resolveApiBaseUrl();let o={method:`post`,headers:{"Content-type":`application/x-www-form-urlencoded`},body:i._prepareQueryParams({method:e,queryParams:t,sessionKey:n})};return i.params.config.useKeepalive&&(o.keepalive=!0),A.fetchPolyfilled(`${i.apiBaseUrl}/fb.do`,o).then(e=>{let t=Number(e.headers.get(`content-length`))===0,n=new Date(e.headers.get(`date`)??``).getTime(),o=j.now()-r;if(isFinite(n)&&i.timeSynchronisation?.addServerTime(n,o),!t)return e.json().then(e=>Object.prototype.hasOwnProperty.call(e,`error_msg`)?Promise.reject(e):e,a)},a)})()}sendJsonBeacon(e,t,r){let i=`${this.apiUvRestBaseUrl}${e}`;try{A.fetchPolyfilled(i,{method:`POST`,headers:n({"Content-Type":`application/json`},r),body:JSON.stringify(t),keepalive:!0}).catch(t=>{this.params.error$.next({id:`OneStat:ApiTransport:sendJsonBeacon`,category:j.ErrorCategory.NETWORK,message:`Keepalive request failed`,thrown:t,data:{path:e}})})}catch(t){this.params.error$.next({id:`OneStat:ApiTransport:sendJsonBeacon`,category:j.ErrorCategory.NETWORK,message:`Failed to initiate keepalive request`,thrown:t,data:{path:e}})}}sendJsonRequest(e,t,i){var a=this;return r(function*(){let r=j.now(),o=t=>{if(t instanceof TypeError&&ye.arrayIncludes([`Failed to fetch`,`NetworkError when attempting to fetch resource.`],t.message)){a.params.error$.next({id:`Network`,category:j.ErrorCategory.NETWORK,message:`JSON request failed`,thrown:t});return}a.params.error$.next({id:`OneStat:ApiTransport:sendJsonRequest`,category:j.ErrorCategory.NETWORK,message:`Unhandled JSON request error`,thrown:t,data:{path:e,time:j.now()-r}})},s={method:`POST`,headers:n({"Content-Type":`application/json`},i),body:JSON.stringify(t)};return a.params.config.useKeepalive&&(s.keepalive=!0),A.fetchPolyfilled(`${a.apiUvRestBaseUrl}${e}`,s).then(e=>{let t=Number(e.headers.get(`content-length`))===0,n=new Date(e.headers.get(`date`)??``).getTime(),i=j.now()-r;if(isFinite(n)&&a.timeSynchronisation?.addServerTime(n,i),!e.ok)return Promise.reject({status:e.status,statusText:e.statusText});if(!t)return e.json().catch(o)},o)})()}_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),be.objectEntries(e.queryParams).forEach(([e,n])=>t.append(e,typeof n==`string`?n:JSON.stringify(n))),t}}var Se=require(`@vkontakte/videoplayer-shared`),Ce=require(`@vkontakte/videoplayer-shared`),M=require(`@vkontakte/videoplayer-shared`),N=e=>t=>t.timestamp+e>=M.now();class we{constructor(e){t(this,`params`,void 0),t(this,`error$`,void 0),t(this,`userSalt`,void 0),t(this,`isPaused`,!1),t(this,`loggerDebugLog`,void 0),t(this,`queues`,[]),t(this,`isUrgent`,e=>{let{operation:t}=e;return Se.arrayIncludes([`action_play`,`action_play_interactive`,`watch_coverage_record`,`watch_coverage_live`,`action_stop`,`close_at_empty_buffer`],t)}),this.params=e,this.error$=e.error$,this.userSalt=e.userSalt,this.loggerDebugLog=e.debugLogger.createComponentLog(`stat logger`);for(let t of e.apis)this.queues.push(this.createQueueState(t));this.housekeepStorage()}createQueueState(e){let t=`onestat_events_${e.id}`,n=M.debounceFn(()=>this.safeFlushQueue(a),this.params.config.firstFlushTime,{maxWait:this.params.config.firstFlushTime}),r=M.safeStorage.isPersistent()?this.params.config.flushMaxWait:0,i=M.debounceFn(()=>this.safeFlushQueue(a),this.params.config.flushDebounceTime,{maxWait:r}),a={api:e,storageKey:t,unsaltedStorage:[],lastVsid:void 0,firstFlush:n,debouncedFlush:i,subscription:e.authorized$.subscribe(e=>{e&&i()})};return a}safeFlushQueue(e){try{this.flushQueue(e)}catch(t){this.error$.next({id:`LoggerError`,category:M.ErrorCategory.WTF,message:t?String(t):`Unknown logger error`,thrown:t,data:{storageKey:e.storageKey}})}}readFromStorage(e){let t=M.safeStorage.get(e);try{return t?JSON.parse(t):{}}catch{}return{}}addToStorage(e,t){if(!this.userSalt){e.unsaltedStorage.push(t);return}let r=this.readFromStorage(e.storageKey),i=(r[this.userSalt]??[]).filter(N(this.params.config.storageExpiration));M.safeStorage.set(e.storageKey,JSON.stringify(n(n({},r),{},{[this.userSalt]:[...i,t]})))}getFromStorage(e){return this.userSalt?(this.readFromStorage(e.storageKey)[this.userSalt]??[]).filter(N(this.params.config.storageExpiration)):e.unsaltedStorage}markStorageSent(e){if(!this.userSalt){e.unsaltedStorage=[];return}let t=this.readFromStorage(e.storageKey);delete t[this.userSalt],M.safeStorage.set(e.storageKey,JSON.stringify(t))}housekeepStorage(){for(let e of this.queues){let t=this.readFromStorage(e.storageKey);for(let[n,r]of Ce.objectEntries(t)){let i=r.filter(N(this.params.config.storageExpiration));i.length?t[n]=i:delete t[n],this.loggerDebugLog({message:`${r.length} retrieved from storage, ${i.length} of them actual (${e.storageKey})`})}M.safeStorage.set(e.storageKey,JSON.stringify(t))}}log(e){for(let t of this.queues)this.addToStorage(t,e),!this.isPaused&&(this.isUrgent(e)?this.flushQueue(t):t.lastVsid===e.custom.vsid?t.debouncedFlush():t.firstFlush(),t.lastVsid=e.custom.vsid)}flush(e={wantBeacon:!1,clearStorage:!0}){for(let t of this.queues)this.flushQueue(t,e)}flushQueue(e,{wantBeacon:t,clearStorage:n}={wantBeacon:!1,clearStorage:!0}){let r=this.getFromStorage(e);r.length!==0&&(e.api.authorized$.getValue()?(t&&this.params.config.useBeacon?(this.loggerDebugLog({message:`Flushing ${r.length} events through beacon (${e.storageKey})`}),e.api.logBeacon(r)):(this.loggerDebugLog({message:`Flushing ${r.length} events (${e.storageKey})`}),e.api.logRequest(r)),n&&this.markStorageSent(e)):e.api.authorize(),e.firstFlush.cancel(),e.debouncedFlush.cancel())}pause(){this.isPaused=!0;for(let e of this.queues)e.debouncedFlush.cancel()}resume(){this.isPaused=!1;for(let e of this.queues)e.debouncedFlush()}destroy(){for(let e of this.queues)e.subscription.unsubscribe(),e.firstFlush.cancel(),e.debouncedFlush.cancel();this.queues=[]}}var P=require(`@vkontakte/videoplayer-core`),Te=require(`@vkontakte/videoplayer-shared`),Ee=e=>e&&{[P.VideoQuality.INVARIANT]:`unknown`,[P.VideoQuality.Q_144P]:`mobile`,[P.VideoQuality.Q_240P]:`lowest`,[P.VideoQuality.Q_360P]:`low`,[P.VideoQuality.Q_480P]:`medium`,[P.VideoQuality.Q_576P]:`unknown`,[P.VideoQuality.Q_720P]:`high`,[P.VideoQuality.Q_1080P]:`fullhd`,[P.VideoQuality.Q_1440P]:`quadhd`,[P.VideoQuality.Q_2160P]:`ultrahd`,[P.VideoQuality.Q_4320P]:`unknown`}[e],De=e=>e&&{[P.HttpConnectionType.HTTP1]:`http1`,[P.HttpConnectionType.HTTP2]:`http2`,[P.HttpConnectionType.QUIC]:`http3`}[e],Oe=e=>{if(e!==void 0)switch(e){case P.VideoFormat.MPEG:return`mp4`;case P.VideoFormat.DASH:case P.VideoFormat.DASH_LIVE:case P.VideoFormat.DASH_STREAMS:return`dash`;case P.VideoFormat.DASH_SEP:return`dash_sep`;case P.VideoFormat.DASH_ONDEMAND:return`ondemand_dash`;case P.VideoFormat.DASH_WEBM:case P.VideoFormat.DASH_LIVE_WEBM:return`webm`;case P.VideoFormat.DASH_WEBM_AV1:return`av1`;case P.VideoFormat.DASH_LIVE_CMAF:return`ondemand_dash_live`;case P.VideoFormat.HLS:case P.VideoFormat.HLS_LIVE:return`hls`;case P.VideoFormat.HLS_FMP4:return`hls_fmp4`;case P.VideoFormat.HLS_ONDEMAND:return`ondemand_hls`;case P.VideoFormat.HLS_LIVE_CMAF:return`ondemand_hls_live`;case P.VideoFormat.WEB_RTC_LIVE:return`webrtc`;default:return Te.assertNever(e)}},ke=(e,t)=>{if(t)return`minimal`;switch(e){case void 0:case P.Surface.NONE:case P.Surface.INLINE:return;case P.Surface.FULLSCREEN:return`fullscreen`;case P.Surface.SECOND_SCREEN:return`chromecast`;case P.Surface.PIP:return`pip`;case P.Surface.INVISIBLE:return`invisible`;default:return Te.assertNever(e)}},Ae=e=>{switch(e){case`slow-2g`:return`poor`;case`2g`:return`poor`;case`3g`:return`good`;case`4g`:return`excellent`}};class je{constructor(e){t(this,`offset`,void 0),this.offset=e}getOffset(){return this.offset??0}setOffset(e){this.offset=e}now(){return Date.now()+(this.offset??0)}date(e=new Date){return e.setTime(e.getTime()+(this.offset??0)),e}addServerTime(e,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 Me=require(`@vkontakte/videoplayer-core`),F=require(`@vkontakte/videoplayer-shared`),Ne=(e,t)=>new F.Observable(n=>{let r=new F.Subscription,i=F.merge(F.fromEvent(window,`beforeunload`),e.events.willDestruct$),a=new F.ValueSubject(void 0),o;r.add(e.info.isLive$.pipe(F.filterChanged()).subscribe(t=>{o&&(o.unsubscribe(),a.next(void 0)),o=t?e.info.liveTime$.pipe(F.map(e=>e&&e/1e3)).subscribe(a):e.info.position$.subscribe(a),r.add(o)}));let{playing$:s,paused$:c,looped$:l}=e.events,u=e.events.willSeek$.pipe(F.filter(()=>e.info.playbackState$.getValue()===Me.PlaybackState.PLAYING)),d=e.events.seeked$.pipe(F.filter(()=>e.info.playbackState$.getValue()===Me.PlaybackState.PLAYING)),f=!1,p=new F.Subject;r.add(u.subscribe(()=>{f||p.next(),f=!0})),r.add(d.subscribe(()=>f=!1));let m=new F.Subject,h=new F.Subject,g=()=>t.watchCoverageExactTime?e.info.isLive$.getValue()?e.getExactLiveTime():e.getExactTime():a.getValue()??0,_=e.info.stallStartTime$.pipe(F.filterChanged(),F.filter(e=>e>0)),v=F.merge(s,d,m).pipe(F.map(()=>g())),y=F.merge(l,F.merge(c,p,i,h,_).pipe(F.map(()=>g()))),b,x=e=>{b=e},S=e=>{let t=e;F.isNullable(b)||b===t||F.isNullable(t)||(n.next({from:b,to:t}),b=void 0)},C=()=>{h.next(),m.next()};if(r.add(v.subscribe(x)),r.add(y.subscribe(S)),t.forceInterval&&isFinite(t.forceInterval))if(t.watchCoverageTimeoutFix){let e,n=()=>{e!==void 0&&(window.clearTimeout(e),e=void 0)};r.add(v.subscribe(()=>{n(),e=window.setTimeout(C,t.forceInterval)})),r.add(y.subscribe(()=>n())),r.add(()=>n())}else{let e=0;r.add(v.subscribe(()=>e=window.setTimeout(C,t.forceInterval))),r.add(y.subscribe(()=>window.clearTimeout(e)))}return r}),I=require(`@vkontakte/videoplayer-core`),L=require(`@vkontakte/videoplayer-shared`),Pe=(e,t,n)=>{let r=new L.Subject,i=r.pipe(L.debounce(0),L.filterChanged()),a=!1,o=!1,s=!1;return t(e.inPiP$,e=>{a=e,r.next(e?I.Surface.PIP:o?I.Surface.FULLSCREEN:s?I.Surface.INLINE:void 0)}),t(e.inFullscreen$,e=>{o=e,r.next(e?I.Surface.FULLSCREEN:a?I.Surface.PIP:s?I.Surface.INLINE:void 0)}),n&&t(n.info.surface$,e=>{switch(e){case I.Surface.SECOND_SCREEN:case I.Surface.NONE:case I.Surface.INLINE:!o&&!a&&(e===I.Surface.INLINE&&(s=!0),r.next(e));break}}),{surface$:i}},Fe=`_one-stat_deviceId`,Ie=(e,t)=>e&&t?`${e}_${t}`:e??t,R=()=>{let e=new T.Subscription;return{subscription:e,subscribe:(t,n)=>{t&&e.add(t.subscribe(n))}}};class Le{get vsid$(){return new T.ValueSubject(E.getVSID())}constructor(e,n){t(this,`apis`,void 0),t(this,`logger`,void 0),t(this,`config`,void 0),t(this,`subscription`,new T.Subscription),t(this,`beforeunloadSubscription`,void 0),t(this,`timeSynchronisation`,void 0),t(this,`debugLogger`,new le.Logger),t(this,`oneStatDebugLog`,this.debugLogger.createComponentLog(`onestat`)),t(this,`loopCounter`,0),t(this,`disabled`,!1),t(this,`experimental`,void 0),t(this,`isid$`,new T.ValueSubject(void 0)),t(this,`zenUid$`,new T.ValueSubject(void 0)),t(this,`statContext`,void 0),t(this,`isEmbed`,void 0),t(this,`embedParent`,void 0),t(this,`uiEvents`,void 0),t(this,`player`,void 0),t(this,`seekAction$`,new T.ValueSubject(`unknown`)),t(this,`deviceId`,void 0),this.statContext=e,this.config=se(n.config??{}),T.isNonNullable(n.apiEnv)&&(this.config.apiEnv=n.apiEnv),this.config.synchronizeTime&&(this.timeSynchronisation=new je);let r=new T.Subject;this.experimental={error$:r};let i=T.safeStorage.get(Fe);this.statContext.deviceId?this.deviceId=this.statContext.deviceId:i?this.deviceId=i:(this.deviceId=ce(),T.safeStorage.set(Fe,this.deviceId)),this.resetViewSession(),n.useIsid&&this.isid$.next(n.isid??fe()),this.zenUid$.next(n.zenUid);let a=new xe({config:this.config,error$:r,timeSynchronisation:this.timeSynchronisation}),o=[];this.config.apiForticom&&o.push(new _e({config:this.config,apiTransport:a,refreshAuthToken:n.refreshAuthToken,mobile:this.statContext.mobile??!1,deviceId:this.deviceId,error$:r,vktvVersion:n.vktvVersion})),this.config.apiUvRest&&(n.getUvRestAuthToken?o.push(new ve({config:this.config,apiTransport:a,error$:r,userId:this.statContext.userId,getAuthToken:n.getUvRestAuthToken,mobile:this.statContext.mobile??!1,vktvVersion:n.vktvVersion})):r.next({id:`OneStat:Init:MissingGetUvRestAuthToken`,category:le.ErrorCategory.WTF,message:`oldStatToUvRest enabled but getUvRestAuthToken callback not provided`})),this.apis=o,this.logger=new we({config:this.config,debugLogger:this.debugLogger,apis:this.apis,error$:r,userSalt:n.userSalt});let{isEmbed:s,topOrigin:c}=le.detectEmbed();this.isEmbed=s,this.embedParent=c?new URL(c).hostname:void 0,this.subscribe()}updateContext(e){this.statContext=n(n({},this.statContext),e)}attachTo(e){let t=new T.Subscription,n=(e,n)=>t.add(e.subscribe(n)),r,i,a,o=!1,s=!1,c=()=>{o||(o=!0,T.isNonNullable(r)&&(r={startedAt:T.now(),liveAtStall:!!this.statContext.liveEdge}))};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.willSeek$,()=>{T.isNonNullable(r)&&o&&this.logEmptyBuffer({duration:T.now()-r.startedAt,liveAtStall:r.liveAtStall}),r=void 0,s=!0}),n(e.events.seeked$,()=>{!s&&T.isNonNullable(r)&&o&&(this.logEmptyBuffer({duration:T.now()-r.startedAt,liveAtStall:r.liveAtStall}),r=void 0),s=!1;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(Ne(e,{forceInterval:this.config.watchCoverageInterval,watchCoverageTimeoutFix:this.config.watchCoverageTimeoutFix,watchCoverageExactTime:this.config.watchCoverageExactTime}),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)}),n(e.info.stallStartTime$,e=>{e>0?r={startedAt:e,liveAtStall:!!this.statContext.liveEdge}:(T.isNonNullable(r)&&o&&this.logEmptyBuffer({duration:Math.round(T.now()-r.startedAt),liveAtStall:r.liveAtStall}),r=void 0)});let l=!1;t.add(e.events.fatalError$.pipe(T.once()).subscribe(()=>l=!0)),n(e.events.willStop$,()=>{if(e.info.isBuffering$.getValue()&&o){let e=T.isNonNullable(r)?T.now()-r.startedAt:void 0;this.logCloseAtEmptyBuffer({duration:e??0,liveAtStall:r?.liveAtStall}),r=void 0}else l||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})}),n(e.events.firstBytes$,e=>{i=T.now(),this.logFirstBytes({time:e})}),n(e.events.willStart$,()=>a=T.now()),n(e.info.currentBuffer$,e=>{!o&&e&&e.end-e.start>0&&T.isNonNullable(i)&&(this.logPlayerReady({duration:T.now()-i}),c())}),n(e.events.firstFrame$,()=>{T.isNonNullable(i)&&!o&&(this.logPlayerReady({duration:T.now()-i}),c()),T.isNonNullable(a)&&this.logFirstFrame({time:T.now()-a})});let u;n(e.info.currentVideoStream$,e=>{e&&(this.updateContext({videoCodec:e.codec}),u&&e.id!==u&&this.logTrackSwitch(e),u=e.id)});let d;n(e.info.currentAudioStream$,e=>{e&&(this.updateContext({audioCodec:e.codec}),d&&e.id!==d&&this.logTrackSwitch(e),d=e.id)}),n(e.info.atLiveEdge$,e=>this.updateContext({liveEdge:e})),n(T.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=Ee(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:Oe(e)})),n(e.info.currentPlaybackRate$,e=>this.updateContext({rate:e})),n(e.info.is3DVideo$,e=>this.updateContext({is3d:e}));let f;return n(e.info.hostname$,e=>{let t=f!==void 0&&f!==e;this.updateContext({cdnHostname:e,failover:t}),t&&this.logFailover(e),f=e}),n(e.info.throughputEstimation$,e=>this.updateContext({downloadSpeed:e})),n(e.info.httpConnectionType$,e=>{this.statContext.firstConnectionType||this.updateContext({firstConnectionType:De(e)}),this.updateContext({connectionType:De(e)})}),n(e.info.httpConnectionReused$,e=>{T.isNullable(this.statContext.firstConnectionReused)&&this.updateContext({firstConnectionReused:e}),this.updateContext({connectionReused:e})}),n(e.info.surface$,e=>{this.uiEvents||this.updateContext({mode:ke(e,this.statContext.isPreviewPlayerView)})}),n(T.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}=R();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}=Pe(this.uiEvents,n,this.player);return n(r,e=>{this.updateContext({mode:ke(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}=R();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}=R();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 Promise.all(this.apis.map(t=>t.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.apis.forEach(e=>e.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)},T.isNonNullable(e.liveAtStall)?{live:e.liveAtStall?1:void 0}:{})}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=T.getWindow().navigator.connection;e&&`onchange`in e&&`effectiveType`in e&&this.subscription.add(T.merge(T.fromEvent(e,`change`),T.observableFrom([`init`])).subscribe(()=>this.updateContext({network:Ae(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=T.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))},T.isNonNullable(e.liveAtStall)?{live:e.liveAtStall?1:void 0}:{})}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(g.arrayIncludes(this.config.disabledOperations,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:r},i={}){let a=this.timeSynchronisation?.now()??T.now(),o=this.vsid$.getValue();T.assertNonNullable(o);let s=this.isid$.getValue(),c=e===`empty_buffer`||e===`close_at_empty_buffer`?this.statContext.connectionType:this.statContext.firstConnectionType,l=this.statContext.firstConnectionReused,u,d;if(this.isEmbed||this.statContext.place===`embed`){u=this.embedParent;let e=[...new URLSearchParams(location.search).entries()].filter(([e,t])=>g.arrayIncludes(this.config.embedUrlParams,e));d=new URLSearchParams(e).toString()}else if(this.statContext.place===`direct`){let e=this.statContext.refDomain||document.referrer;u=e&&_.urlCanParsePolyfilled(URL,e)?new URL(e).hostname:e,d=location.href.substring(0,1024)}let f=n({vsid:o,isid:s,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:c,connection_reused:l===!0?1:l===!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:u,direct_url:d,rate:this.statContext.rate===1||T.isNullable(this.statContext.rate)?void 0:this.statContext.rate.toFixed(2),view_360:this.statContext.is3d?1:void 0,codec_info:Ie(this.statContext.videoCodec,this.statContext.audioCodec),aid:this.statContext.albumId,vk_playlist_id:this.statContext.vkPlaylistId},i);for(let e of this.config.disabledCustomFields)delete f[e];return{operation:e,type:1,time:r,network:this.statContext.network,timestamp:a,custom:f}}}var Re={};m(Re,{VERSION:()=>O,ThinOneStat:()=>Ft,ActionSeekType:()=>Ue});var ze=require(`@vkontakte/videoplayer-shared`),Be=require(`@vkontakte/videoplayer-shared`),z=require(`@vkontakte/videoplayer-shared`),B=require(`@vkontakte/videoplayer-core`),Ve=require(`@vkontakte/videoplayer-shared`),He;(e=>{e.AUTO=`auto`,e.AUTO_POOR=`auto_poor`,e.AUTO_RICH=`auto_rich`})(He||={});var Ue;(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`})(Ue||={});var We=`CIOPGQJGDIHBABABA`,V={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:``},Ge={apiKey:We,apiEnv:`okcdn`,apiBaseUrl:null,apiUvRestBaseUrl:`https://uvapi.okcdn.ru`,apiForticom:!0,apiUvRest:!1,requestRetryCount:3,useVsid64:!1,flushFirstTime:5e3,flushDebounceTime:1e4,flushMaxWait:6e4,flushRetryFirstDelay:3e3,flushRetryMaxDelay:18e5,storageExpiration:2160*60*1e3,clearStorageAtUnload:!1,disabledEvents:[],disabledParams:[],synchronizeTime:!0,useBeacon:!1,alwaysSendDesktop:!1,watchCoverageHeartbeatInterval:3e4,watchCoverageExactTime:!1,watchedNDefaultTargetDuration:1e3,telemetryInterval:3e4,downloadBytesMaxTime:3e4},Ke=e=>Ve.fillWithDefault(e,Ge),qe=require(`@vkontakte/videoplayer-shared`),Je=require(`@vkontakte/videoplayer-shared`),H=require(`@vkontakte/videoplayer-shared`);function Ye(e){let t=Error(`HTTP ${e.status}: ${e.statusText}`);return t.status=e.status,t.statusText=e.statusText,t.response=e,t}function Xe(){let e=Error(`Request timeout`);return e.isTimeout=!0,e}function Ze(e){let t=Error(e.error_msg);return t.errorData=e,t}function Qe(e){if(!(!e||typeof e!=`object`)){if(`errorData`in e)return e.errorData?.error_code;if(`error_code`in e){let t=e.error_code;return typeof t==`number`?t:void 0}}}var $e=t=>{let{application:n,platform:r,product:a}=t;return i(t,e)};class et{constructor(e){t(this,`id`,`forticom`),t(this,`authorized$`,void 0),t(this,`params`,void 0),t(this,`authToken`,void 0),t(this,`sessionKey`,void 0),t(this,`authorizePromise`,void 0),t(this,`refreshAuthTokenPromise`,void 0),t(this,`isDestroyed`,!1),this.params=e,this.authorized$=new H.ValueSubject(!1)}authorize(e){var t=this;return r(function*(){return t.authToken=e??(yield t.refreshAuthToken()),t.doAuthorize()})()}logBeacon(e){if(!e.length)return;let t=this.createLogParams(e),n=this.sessionKey;n&&(this.params.apiTransport.sendBeacon(`log.logUvStat`,t,n)||this.logRequest(e).catch(()=>{}))}logRequest(e){var t=this;return r(function*(){if(!e.length)return;let n=`log.logUvStat`,r=t.createLogParams(e),i={};try{let e=yield t.getValidSessionKey();if(!e){t.params.errors$.next({id:`ThinOneStat:Api:LogRequestNoSession`,category:H.ErrorCategory.NETWORK,message:`No session key available for log request`});return}yield t.params.apiTransport.sendRequest(n,r,e,i)}catch(e){(yield t.handleLogRequestError(e,n,r))&&(yield t.retryLogRequestAfterSessionRecovery(n,r))}})()}getValidSessionKey(){var e=this;return r(function*(){return e.sessionKey?e.sessionKey:e.doAuthorize()})()}handleLogRequestError(e,t,n){var i=this;return r(function*(){let r=Qe(e);return r===void 0?(i.params.errors$.next({id:`ThinOneStat:Api:LogRequestUnknown`,category:H.ErrorCategory.NETWORK,message:`Unknown ${t} error`,thrown:e,data:{params:n}}),!1):i.isSessionExpiredError(r)?(i.params.errors$.next({id:`ThinOneStat:Api:LogRequestSessionError#${r}`,category:H.ErrorCategory.EXTERNAL_API,message:`Session error: ${r}`,data:{error:e,code:r}}),i.authorized$.next(!1),i.sessionKey=void 0,(yield i.doAuthorize())!==void 0):r===401?(i.params.errors$.next({id:`ThinOneStat:Api:LogRequestAuthLogin#${r}`,category:H.ErrorCategory.EXTERNAL_API,message:`Auth token expired`,data:{error:e,code:r}}),i.authorized$.next(!1),i.authToken=yield i.refreshAuthToken(),i.sessionKey=void 0,(yield i.doAuthorize())!==void 0):(i.params.errors$.next({id:`ThinOneStat:Api:LogRequest#${r}`,category:H.ErrorCategory.EXTERNAL_API,message:`${t} error`,data:{error:e,code:r,params:n}}),!1)})()}retryLogRequestAfterSessionRecovery(e,t){var n=this;return r(function*(){let r=n.sessionKey;if(!r){n.params.errors$.next({id:`ThinOneStat:Api:LogRequestRetryFailed`,category:H.ErrorCategory.NETWORK,message:`Cannot retry log request: no session key after recovery`});return}try{yield n.params.apiTransport.sendRequest(e,t,r)}catch(e){let t=Qe(e);n.params.errors$.next({id:`ThinOneStat:Api:LogRequestRetryFailed#${t??`unknown`}`,category:H.ErrorCategory.EXTERNAL_API,message:`Log request failed after session recovery`,thrown:e,data:{originalError:e,retryCode:t}})}})()}isSessionExpiredError(e){return!!e&&qe.arrayIncludes([102,103,104],e)}doAuthorize(e=1){var t=this;return r(function*(){if(!t.isDestroyed)return t.authorizePromise?t.authorizePromise:(t.sessionKey=void 0,t.authorized$.next(!1),t.authorizePromise=Je.promiseFinally(t.executeAuthorize(e),()=>{t.authorizePromise=void 0,t.isDestroyed||t.authorized$.next(t.sessionKey!==void 0)}),t.authorizePromise)})()}executeAuthorize(e){var t=this;return r(function*(){let n=t.buildAuthParams();try{let e=yield t.params.apiTransport.sendRequest(`auth.anonymLogin`,n);if(t.isDestroyed)return;if(!e?.session_key){t.params.errors$.next({id:`ThinOneStat:Api:AuthorizeFailed`,category:H.ErrorCategory.EXTERNAL_API,message:`No session key in response`,data:e});return}return t.sessionKey=e.session_key,t.sessionKey}catch(n){if(t.isDestroyed)return;let r=Qe(n);if(r===401&&t.params.refreshAuthToken){if(t.params.errors$.next({id:`ThinOneStat:Api:AuthorizeAuthLogin`,category:H.ErrorCategory.EXTERNAL_API,message:`Auth token expired during authorization`,data:{error:n,code:r,attempt:e}}),e>=2){t.params.errors$.next({id:`ThinOneStat:Api:AuthorizeMaxAttemptsReached`,category:H.ErrorCategory.EXTERNAL_API,message:`Authorization failed after ${e} attempts`,data:{error:n,code:r}});return}return t.authToken=yield t.refreshAuthToken(),t.doAuthorize(e+1)}r?t.params.errors$.next({id:`ThinOneStat:Api:Authorize#${r}`,category:H.ErrorCategory.EXTERNAL_API,message:`Authorize error`,data:{error:n,code:r}}):t.params.errors$.next({id:`ThinOneStat:Api:AuthorizeUnknown`,category:H.ErrorCategory.NETWORK,message:`Authorize error`,thrown:n});return}})()}buildAuthParams(){let e={session_data:{version:2,device_id:this.params.deviceId,client_version:this.getClientVersion(),client_type:`SDK_JS`}};return this.authToken!==void 0&&(e.session_data.auth_token=this.authToken,e.session_data.version=3),e}getClientVersion(){return O}refreshAuthToken(){var e=this;return r(function*(){if(e.params.refreshAuthToken)return e.refreshAuthTokenPromise||=Je.promiseFinally(e.params.refreshAuthToken().catch(t=>{throw e.params.errors$.next({id:`ThinOneStat:Api:RefreshAuthTokenFailed`,category:H.ErrorCategory.NETWORK,message:`Failed to refresh auth token`,thrown:t}),t}),()=>{e.refreshAuthTokenPromise=void 0}),e.refreshAuthTokenPromise})()}createLogParams(e){let t=e[0],n=t.application??`@vkontakte/videoplayer-statistics:${this.getClientVersion()}`;return this.params.vktvVersion&&(n=this.params.vktvVersion),{collector:`ok.mobile.apps.video`,uv_stat_data:JSON.stringify({application:n,platform:t.platform,product:t.product,events:e.map($e)})}}destroy(){this.isDestroyed=!0,this.authorizePromise=void 0,this.refreshAuthTokenPromise=void 0,this.sessionKey=void 0,this.authorized$.next(!1)}}class tt{constructor(e){t(this,`id`,`uvrest`),t(this,`authorized$`,void 0),t(this,`params`,void 0),t(this,`statToken`,void 0),t(this,`authorizePromise`,void 0),t(this,`isDestroyed`,!1),this.params=e,this.authorized$=new H.ValueSubject(!1)}authorize(e){var t=this;return r(function*(){if(!t.isDestroyed)return e?(t.statToken=e,t.authorized$.next(!0),e):t.authorizePromise?t.authorizePromise:(t.authorized$.next(!1),t.authorizePromise=Je.promiseFinally(t.executeAuthorize(),()=>{t.authorizePromise=void 0,t.isDestroyed||t.authorized$.next(t.statToken!==void 0)}),t.authorizePromise)})()}logRequest(e){var t=this;return r(function*(){if(!e.length)return;let n=t.buildBody(e);try{let e=yield t.getValidToken();if(!e){t.params.errors$.next({id:`ThinOneStat:UvRestApi:LogRequestNoToken`,category:H.ErrorCategory.NETWORK,message:`No stat token available for log request`});return}yield t.params.apiTransport.sendJsonRequest(`/uv/stat/logUvStat`,n,{Authorization:`Bearer ${e}`})}catch(e){(yield t.handleLogRequestError(e))&&(yield t.retryLogRequestAfterRecovery(n))}})()}logBeacon(e){if(!e.length)return;let t=this.statToken;if(!t)return;let n=this.buildBody(e);this.params.apiTransport.sendJsonBeacon(`/uv/stat/logUvStat`,n,{Authorization:`Bearer ${t}`})}destroy(){this.isDestroyed=!0,this.authorizePromise=void 0,this.statToken=void 0,this.authorized$.next(!1)}getValidToken(){var e=this;return r(function*(){return e.statToken?e.statToken:e.authorize()})()}executeAuthorize(){var e=this;return r(function*(){try{let t=yield e.params.getAuthToken();if(e.isDestroyed)return;if(!t){e.params.errors$.next({id:`ThinOneStat:UvRestApi:NoToken`,category:H.ErrorCategory.EXTERNAL_API,message:`getAuthToken returned no token`});return}return e.statToken=t,e.statToken}catch(t){if(e.isDestroyed)return;e.params.errors$.next({id:`ThinOneStat:UvRestApi:AuthorizeFailed`,category:H.ErrorCategory.NETWORK,message:`Failed to get stat token`,thrown:t});return}})()}handleLogRequestError(e){var t=this;return r(function*(){let n=e?.status;return n===401?(t.params.errors$.next({id:`ThinOneStat:UvRestApi:TokenExpired`,category:H.ErrorCategory.EXTERNAL_API,message:`Stat token expired (401), refreshing`,thrown:e}),t.authorized$.next(!1),t.statToken=void 0,(yield t.authorize())!==void 0):(t.params.errors$.next({id:`ThinOneStat:UvRestApi:LogRequestFailed#${n??`unknown`}`,category:H.ErrorCategory.EXTERNAL_API,message:`Log request failed with status ${n}`,thrown:e}),!1)})()}retryLogRequestAfterRecovery(e){var t=this;return r(function*(){let n=t.statToken;if(!n){t.params.errors$.next({id:`ThinOneStat:UvRestApi:RetryNoToken`,category:H.ErrorCategory.NETWORK,message:`Cannot retry log request: no token after recovery`});return}try{yield t.params.apiTransport.sendJsonRequest(`/uv/stat/logUvStat`,e,{Authorization:`Bearer ${n}`})}catch(e){t.params.errors$.next({id:`ThinOneStat:UvRestApi:RetryFailed`,category:H.ErrorCategory.EXTERNAL_API,message:`Log request failed after token refresh`,thrown:e})}})()}buildBody(e){let t=e[0],n=t.application;return this.params.vktvVersion&&(n=this.params.vktvVersion),[{product:t.product,platform:t.platform,application:n,user_id:this.params.userId,events:e.map($e)}]}}var nt=require(`@vkontakte/videoplayer-shared`),rt=require(`@vkontakte/videoplayer-shared`),U=require(`@vkontakte/videoplayer-shared`),it=require(`@vkontakte/videoplayer-shared`),W=require(`@vkontakte/videoplayer-shared`);class at{constructor(e){t(this,`params`,void 0),t(this,`apiKey`,void 0),t(this,`apiBaseUrl`,void 0),t(this,`apiUvRestBaseUrl`,void 0),t(this,`apiEnv`,void 0),t(this,`resolvedApiBaseUrl`,null),t(this,`resolveApiBaseUrlPromise`,null),t(this,`timeSynchronisation`,void 0),t(this,`fetchTimeout`,3e4),t(this,`maxTotalRequestTime`,6e4),t(this,`retryConfig`,void 0),this.params=e,this.apiKey=e.config.apiKey,this.apiEnv=e.config.apiEnv,this.apiBaseUrl=e.config.apiBaseUrl??V[this.apiEnv],this.apiUvRestBaseUrl=e.config.apiUvRestBaseUrl,this.timeSynchronisation=e.timeSynchronisation,this.retryConfig={maxAttempts:e.config.requestRetryCount??3,baseDelay:3e3,maxDelay:3e4,retryableErrors:[`Failed to fetch`,`NetworkError when attempting to fetch resource.`,`Request timeout`,`Network request failed`],retryableStatuses:[408,429,500,502,503,504]}}sendBeacon(e,t,n){if(!W.getWindow().Blob||!W.getWindow().navigator.sendBeacon)return!1;let r=this.resolvedApiBaseUrl??this.apiBaseUrl,i=this.prepareQueryParams({method:e,queryParams:t,sessionKey:n}),a=W.getWindow().Blob,o=new a([i.toString()],{type:`application/x-www-form-urlencoded`});try{return W.getWindow().navigator.sendBeacon(`${r}/fb.do`,o)}catch(n){this.params.errors$.next({id:`ThinOneStat:ApiTransport:sendBeacon`,category:W.ErrorCategory.NETWORK,message:`Unhandled beacon error`,thrown:n,data:{method:e,params:t}})}return!1}sendRequest(e,t,n,i){var a=this;return r(function*(){return a.sendRequestWithRetry(e,t,n,i)})()}sendRequestWithRetry(e,t,n,i,a=1,o){var s=this;return r(function*(){let r=W.now(),c=o??r+s.maxTotalRequestTime;if(W.now()>=c){let i=Error(`Request deadline exceeded`);throw s.handleFinalError(e,t,n,r,i,a),i}try{return yield s.executeRequest(e,t,n,i,r,a,c)}catch(o){if(s.shouldRetry(o,a)&&W.now()<c){let l=s.getRetryDelay(o,a);if(W.now()+l>=c)throw s.handleFinalError(e,t,n,r,o,a),o;return s.logRetryAttempt(e,a,o,l),yield s.sleep(l),s.sendRequestWithRetry(e,t,n,i,a+1,c)}throw s.handleFinalError(e,t,n,r,o,a),o}})()}executeRequest(e,t,i,a,o,s,c){var l=this;return r(function*(){let r=o??W.now(),u=yield l.resolveApiBaseUrl(),d=c===void 0?l.fetchTimeout:c-W.now();if(d<=0)throw Xe();try{let o=yield l.fetchWithTimeout(`${u}/fb.do`,{method:`post`,headers:n({"Content-type":`application/x-www-form-urlencoded`},a),body:l.prepareQueryParams({method:e,queryParams:t,sessionKey:i})},Math.min(l.fetchTimeout,d));return yield l.processResponse(o,r)}catch(t){throw t instanceof Error&&(t.context={method:e,attempt:s,url:`${u}/fb.do`}),t}})()}sendJsonRequest(e,t,n){var i=this;return r(function*(){return i.sendJsonRequestWithRetry(e,t,n)})()}sendJsonBeacon(e,t,r){let i=`${this.apiUvRestBaseUrl}${e}`;try{nt.fetchPolyfilled(i,{method:`POST`,headers:n({"Content-Type":`application/json`},r),body:JSON.stringify(t),keepalive:!0}).catch(t=>{this.params.errors$.next({id:`ThinOneStat:ApiTransport:sendJsonBeacon`,category:W.ErrorCategory.NETWORK,message:`Keepalive request failed`,thrown:t,data:{path:e}})})}catch(t){this.params.errors$.next({id:`ThinOneStat:ApiTransport:sendJsonBeacon`,category:W.ErrorCategory.NETWORK,message:`Failed to initiate keepalive request`,thrown:t,data:{path:e}})}}sendJsonRequestWithRetry(e,t,n,i=1,a){var o=this;return r(function*(){let r=W.now(),s=a??r+o.maxTotalRequestTime;if(W.now()>=s){let t=Error(`Request deadline exceeded`);throw o.handleJsonFinalError(e,r,t,i),t}try{return yield o.executeJsonRequest(e,t,n,r,i,s)}catch(a){if(o.shouldRetry(a,i)&&W.now()<s){let c=o.getRetryDelay(a,i);if(W.now()+c>=s)throw o.handleJsonFinalError(e,r,a,i),a;return o.logRetryAttempt(e,i,a,c),yield o.sleep(c),o.sendJsonRequestWithRetry(e,t,n,i+1,s)}throw o.handleJsonFinalError(e,r,a,i),a}})()}executeJsonRequest(e,t,i,a,o,s){var c=this;return r(function*(){let r=a??W.now(),l=s===void 0?c.fetchTimeout:s-W.now();if(l<=0)throw Xe();let u=`${c.apiUvRestBaseUrl}${e}`;try{let e=yield c.fetchWithTimeout(u,{method:`POST`,headers:n({"Content-Type":`application/json`},i),body:JSON.stringify(t)},Math.min(c.fetchTimeout,l));return yield c.processResponse(e,r)}catch(t){throw t instanceof Error&&(t.context={method:e,attempt:o,url:u}),t}})()}fetchWithTimeout(e,t){return r(function*(e,t,r=this.fetchTimeout){let i=new rt.AbortControllerPolyfilled,a=W.getWindow().setTimeout(()=>i.abort(),r);try{let r=yield nt.fetchPolyfilled(e,n(n({},t),{},{signal:i.signal}));return W.getWindow().clearTimeout(a),r}catch(e){throw W.getWindow().clearTimeout(a),W.isAbortError(e)?Xe():e}}).apply(this,arguments)}processResponse(e,t){var n=this;return r(function*(){if(!e.ok){let t=Ye(e),r=n.parseRetryAfter(e);throw r!==void 0&&(t.retryAfter=r),t}let r=new Date(e.headers.get(`date`)??``).getTime(),i=W.now()-t;isFinite(r)&&n.timeSynchronisation?.addServerTime(r,i);let a=e.headers.get(`content-length`);if(a!==null&&Number(a)===0)return{};let o=yield e.json();if(o&&typeof o==`object`&&`error_msg`in o)throw Ze(o);return o})()}shouldRetry(e,t){if(t>=this.retryConfig.maxAttempts||!(e instanceof Error))return!1;let n=e;return!!(n.isTimeout||n.status&&U.arrayIncludes(this.retryConfig.retryableStatuses,n.status)||U.arrayIncludes(this.retryConfig.retryableErrors,e.message)||U.arrayIncludes(e.message,`network`)||U.arrayIncludes(e.message,`timeout`)||U.arrayIncludes(e.message,`connection`))}logRetryAttempt(e,t,n,r){let i=n instanceof Error?n.message:String(n);this.params.errors$.next({id:`ThinOneStat:ApiTransport:retry`,category:W.ErrorCategory.NETWORK,message:`Retrying request (attempt ${t}/${this.retryConfig.maxAttempts}) after ${Math.round(r)}ms`,thrown:n,data:{method:e,attempt:t,delay:r,errorMessage:i}})}handleFinalError(e,t,n,r,i,a){let o=W.ErrorCategory.NETWORK;this.params.errors$.next({id:`ThinOneStat:ApiTransport:sendRequest`,category:o,message:i instanceof Error?i.message:`Request failed after retries`,thrown:i,data:{method:e,params:t,sessionKey:n,time:W.now()-r,maxAttempts:this.retryConfig.maxAttempts,attempts:a}})}handleJsonFinalError(e,t,n,r){this.params.errors$.next({id:`ThinOneStat:ApiTransport:sendJsonRequest`,category:W.ErrorCategory.NETWORK,message:n instanceof Error?n.message:`JSON request failed after retries`,thrown:n,data:{path:e,time:W.now()-t,maxAttempts:this.retryConfig.maxAttempts,attempts:r}})}sleep(e){return new Promise(t=>W.getWindow().setTimeout(t,e))}resolveApiBaseUrl(){return this.apiEnv===`auto`?(this.resolveApiBaseUrlPromise||=this.fetchApiBaseUrl().then(e=>(e===V.vk_alias&&(this.resolveApiBaseUrlPromise=null),e)),this.resolveApiBaseUrlPromise):Promise.resolve(this.apiBaseUrl)}fetchApiBaseUrl(){var e=this;return r(function*(){try{var t;let n=atob(`aHR0cHM6Ly9kbnMuZ29vZ2xlL3Jlc29sdmU/bmFtZT12aWRlby5fZW5kcG9pbnQub2sucnUmdHlwZT1UWFQ=`),r=yield(yield e.fetchWithTimeout(n,{method:`GET`,mode:`cors`,cache:`no-cache`},5e3)).json(),i=r==null||(t=r.Answer[0])==null?void 0:t.data;if(!i)throw Error(`Wrong DNS response`);return e.resolvedApiBaseUrl=i,i}catch(t){return e.params.errors$.next({id:`ThinOneStat:ApiTransport:resolveApiBaseUrl`,category:W.ErrorCategory.NETWORK,message:`Unhandled resolve api base url error`,thrown:t}),V.vk_alias}})()}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),it.objectEntries(e.queryParams).forEach(([e,n])=>t.append(e,typeof n==`string`?n:JSON.stringify(n))),t}parseRetryAfter(e){let t=e.headers.get(`Retry-After`);if(!t)return;let n=Number(t);if(!isNaN(n)&&n>=0)return n*1e3;let r=new Date(t).getTime();if(!isNaN(r))return Math.max(0,r-Date.now())}getRetryDelay(e,t){let n=e;return n?.retryAfter!==void 0&&n.retryAfter>0?n.retryAfter:W.getExponentialDelay(t,{start:this.retryConfig.baseDelay,max:this.retryConfig.maxDelay,factor:2,random:.2})}}var ot=require(`@vkontakte/videoplayer-shared`),st=require(`@vkontakte/videoplayer-shared`),ct=require(`@vkontakte/videoplayer-shared`),lt=require(`@vkontakte/videoplayer-shared`),ut=require(`@vkontakte/videoplayer-shared`),G=require(`@vkontakte/videoplayer-shared`),dt=e=>t=>(t.client_time??G.now())+e>=G.now();class ft{constructor(e){t(this,`params`,void 0),t(this,`subscription`,void 0),t(this,`userSalt`,void 0),t(this,`unsaltedStorage`,[]),t(this,`lastVsid`,void 0),t(this,`isPaused`,!1),t(this,`firstFlush`,void 0),t(this,`debouncedFlush`,void 0),t(this,`flushRetryCount`,0),t(this,`retryFlushTimerId`,void 0),t(this,`debugLog`,void 0),t(this,`flushPromise`,null),t(this,`flushSnapshotLength`,0),t(this,`onlineListener`,void 0),t(this,`urgentEvents`,[`watch_coverage`,`watch_coverage_live`,`watched_n`,`playback_started`]),t(this,`STORAGE_MAX_ATTEMPTS`,3),t(this,`isUrgent`,e=>ct.arrayIncludes(this.urgentEvents,e.event_name)),this.params=e,this.userSalt=e.userSalt,this.debugLog=e.debugLogger.createComponentLog(`batch-queue:${e.storageKey}`),this.firstFlush=G.debounceFn(()=>this.safeFlush(),this.params.config.flushFirstTime,{maxWait:this.params.config.flushFirstTime});let n=G.safeStorage.isPersistent()?this.params.config.flushMaxWait:0;this.debouncedFlush=G.debounceFn(()=>this.safeFlush(),this.params.config.flushDebounceTime,{maxWait:n}),this.subscription=this.params.canSend$.subscribe(e=>{e&&(this.debugLog({message:`Can send, triggering flush`}),this.debouncedFlush())}),this.onlineListener=()=>{this.debugLog({message:`Network online, triggering flush`}),this.cancelRetry(),this.safeFlush()},G.getWindow().addEventListener(`online`,this.onlineListener),this.housekeepStorage()}scheduleRetry(){this.retryFlushTimerId!==void 0&&G.getWindow().clearTimeout(this.retryFlushTimerId);let e=this.params.config.flushRetryFirstDelay,t=this.params.config.flushRetryMaxDelay,n=Math.min(e*2**this.flushRetryCount,t);this.flushRetryCount++,this.debugLog({message:`Scheduling flush retry #${this.flushRetryCount} in ${n}ms`}),this.retryFlushTimerId=G.getWindow().setTimeout(()=>{this.retryFlushTimerId=void 0,this.safeFlush()},n)}cancelRetry(){this.retryFlushTimerId!==void 0&&(G.getWindow().clearTimeout(this.retryFlushTimerId),this.retryFlushTimerId=void 0),this.flushRetryCount=0}safeFlush(){if(this.flushPromise){this.debugLog({message:`Flush already in progress, skipping`});return}this.flushPromise=lt.promiseFinally(this.flush(),()=>{this.flushPromise=null})}isStorageAvailable(){var e;let t=(e=G.safeStorage).isPersistent?.call(e)??!1;return t||this.debugLog({message:`Storage not available`}),t}readFromStorage(){if(!this.isStorageAvailable())return{};try{let e=G.safeStorage.get(this.params.storageKey),t=e?JSON.parse(e):{};return this.debugLog({message:`Read ${Object.keys(t).length} users from storage`}),t}catch(e){return this.params.errors$.next({id:`ThinOneStat:BatchQueue:ReadStorageError`,category:G.ErrorCategory.WTF,message:`Failed to read from storage`,thrown:e,data:{storageKey:this.params.storageKey}}),this.debugLog({message:`Failed to read from storage`}),{}}}writeToStorage(e){if(!this.isStorageAvailable())return!1;try{return G.safeStorage.set(this.params.storageKey,JSON.stringify(e)),this.debugLog({message:`Written ${Object.keys(e).length} users to storage`}),!0}catch(e){return this.params.errors$.next({id:`ThinOneStat:BatchQueue:WriteStorageError`,category:G.ErrorCategory.WTF,message:`Failed to write to storage`,thrown:e,data:{storageKey:this.params.storageKey}}),this.debugLog({message:`Failed to write to storage`}),!1}}addToStorage(e){if(!this.userSalt){this.unsaltedStorage.push(e),this.debugLog({message:`Added item to unsalted storage, total: ${this.unsaltedStorage.length}`});return}for(let t=0;t<this.STORAGE_MAX_ATTEMPTS;t++)try{let t=this.readFromStorage(),r=t[this.userSalt]??[];if(this.debugLog({message:`Adding item to storage for user ${this.userSalt}`}),this.writeToStorage(n(n({},t),{},{[this.userSalt]:[...r,e]})))return}catch(n){t===this.STORAGE_MAX_ATTEMPTS-1&&(this.params.errors$.next({id:`ThinOneStat:BatchQueue:AddToStorageFailed`,category:G.ErrorCategory.WTF,message:`Failed to add item to storage after retries`,thrown:n,data:{item:e,attempt:t,storageKey:this.params.storageKey}}),this.debugLog({message:`Failed to add item to storage after retries`}))}}getFromStorage(){if(!this.userSalt)return this.debugLog({message:`Retrieved ${this.unsaltedStorage.length} items from unsalted storage`}),this.flushSnapshotLength=this.unsaltedStorage.length,this.unsaltedStorage.slice();let e=this.readFromStorage(),t=e[this.userSalt]??[],r=t.filter(dt(this.params.config.storageExpiration));if(this.debugLog({message:`Retrieved from storage for user ${this.userSalt}`}),r.length!==t.length){let i=t.length-r.length;this.params.errors$.next({id:`ThinOneStat:BatchQueue:DropExpiredEvents`,category:G.ErrorCategory.WTF,message:`Dropped ${i} expired events from storage`,data:{droppedCount:i,expiration:this.params.config.storageExpiration,storageKey:this.params.storageKey}}),this.debugLog({message:`Cleaning ${i} expired items from storage`});let a=n({},e);r.length?a[this.userSalt]=r:delete a[this.userSalt],this.writeToStorage(a)}return this.flushSnapshotLength=r.length,r}markStorageSent(){if(!this.userSalt){let e=this.unsaltedStorage.splice(0,this.flushSnapshotLength);this.debugLog({message:`Cleared unsalted storage, removed ${e.length} items, ${this.unsaltedStorage.length} new items kept`}),this.flushSnapshotLength=0;return}let e=this.flushSnapshotLength;this.flushSnapshotLength=0;for(let t=0;t<this.STORAGE_MAX_ATTEMPTS;t++)try{let t=this.readFromStorage(),r=(t[this.userSalt]??[]).slice(e),i=n({},t);if(r.length?i[this.userSalt]=r:delete i[this.userSalt],this.writeToStorage(i)){this.debugLog({message:`Marked storage as sent for user ${this.userSalt}, removed ${e} items, ${r.length} kept`});return}}catch(e){t===this.STORAGE_MAX_ATTEMPTS-1&&(this.params.errors$.next({id:`ThinOneStat:BatchQueue:MarkStorageSentFailed`,category:G.ErrorCategory.WTF,message:`Failed to mark storage as sent after retries`,thrown:e,data:{storageKey:this.params.storageKey}}),this.debugLog({message:`Failed to mark storage as sent after retries`}))}}housekeepStorage(){if(this.isStorageAvailable())try{let e=this.readFromStorage(),t=!1,n=0;for(let[r,i]of ut.objectEntries(e)){let a=i.filter(dt(this.params.config.storageExpiration)),o=i.length-a.length;n+=o,a.length?a.length!==i.length&&(e[r]=a,t=!0):(delete e[r],t=!0),this.debugLog({message:`${i.length} retrieved from storage, ${a.length} of them actual for ${r}`})}t?(this.debugLog({message:`Housekeeping completed, removed ${n} expired items total`}),this.writeToStorage(e),n>0&&this.params.errors$.next({id:`ThinOneStat:BatchQueue:DropExpiredEvents`,category:G.ErrorCategory.WTF,message:`Dropped ${n} expired events during housekeeping`,data:{droppedCount:n,expiration:this.params.config.storageExpiration,storageKey:this.params.storageKey}})):this.debugLog({message:`Housekeeping completed, no changes needed`})}catch(e){this.params.errors$.next({id:`ThinOneStat:BatchQueue:HousekeepStorageError`,category:G.ErrorCategory.WTF,message:`Failed to housekeep storage`,thrown:e,data:{storageKey:this.params.storageKey}}),this.debugLog({message:`Failed to housekeep storage`})}}log(e){try{if(this.debugLog({message:`Logging item: ${e.event_name}`}),this.addToStorage(e),this.isPaused){this.debugLog({message:`Queue paused, skipping flush`});return}this.isUrgent(e)?(this.debugLog({message:`Urgent item, flushing immediately`}),this.safeFlush()):this.lastVsid===e.vsid?(this.debugLog({message:`Same VSID, scheduling debounced flush`}),this.debouncedFlush()):(this.debugLog({message:`VSID changed, triggering first flush`}),this.firstFlush()),this.lastVsid=e.vsid}catch(t){this.params.errors$.next({id:`ThinOneStat:BatchQueue:LogError`,category:G.ErrorCategory.WTF,message:`Failed to log item`,thrown:t,data:{item:e,storageKey:this.params.storageKey}}),this.debugLog({message:`Failed to log item`})}}flush(e={wantBeacon:!1,clearStorage:!0}){return this.flushPromise?(this.debugLog({message:`Flush already in progress, waiting`}),this.flushPromise):(this.flushPromise=lt.promiseFinally(this.flushInternal(e),()=>{this.flushPromise=null}),this.flushPromise)}flushInternal({wantBeacon:e,clearStorage:t}){var n=this;return r(function*(){n.debugLog({message:`Starting flush`});let r=n.getFromStorage();if(r.length===0){n.debugLog({message:`No items to flush`});return}let i=n.params.canSend$.getValue();if(n.debugLog({message:`Can send status: ${i}`}),!i){n.debugLog({message:`Cannot send, requesting ready state`}),n.params.requestReady();return}if(e&&n.params.config.useBeacon){n.debugLog({message:`Flushing ${r.length} events through beacon`}),n.params.sendBeacon(r),t&&n.markStorageSent(),n.firstFlush.cancel(),n.debouncedFlush.cancel();return}n.debugLog({message:`Flushing ${r.length} events`});try{yield n.params.send(r),n.debugLog({message:`Flush completed successfully`}),n.cancelRetry(),t&&n.markStorageSent(),n.firstFlush.cancel(),n.debouncedFlush.cancel()}catch(e){throw n.params.errors$.next({id:`ThinOneStat:BatchQueue:FlushRequestError`,category:G.ErrorCategory.NETWORK,message:`Failed to send events, will retry later`,thrown:e,data:{itemsCount:r.length,storageKey:n.params.storageKey}}),n.debugLog({message:`Flush failed, scheduling retry`}),n.scheduleRetry(),e}})()}pause(){this.debugLog({message:`Queue paused`}),this.isPaused=!0,this.debouncedFlush.cancel(),this.firstFlush.cancel(),this.cancelRetry()}resume(){this.debugLog({message:`Queue resumed`}),this.isPaused=!1,this.debouncedFlush()}destroy(){var e=this;return r(function*(){e.debugLog({message:`Destroying queue`}),e.flushPromise&&(e.debugLog({message:`Waiting for ongoing flush to complete`}),yield e.flushPromise),e.cancelRetry(),e.onlineListener&&=(G.getWindow().removeEventListener(`online`,e.onlineListener),void 0),e.subscription.unsubscribe(),e.firstFlush.cancel(),e.debouncedFlush.cancel(),e.flushPromise=null,e.debugLog({message:`Queue destroyed`})})()}}class pt{constructor(e){t(this,`params`,void 0),t(this,`queues`,[]),this.params=e;for(let t of e.apis)this.queues.push(this.createQueueForApi(t))}createQueueForApi(e){let t=this.getStorageKeyForApi(e.id);return new ft({config:this.params.config,storageKey:t,debugLogger:this.params.debugLogger,errors$:this.params.errors$,userSalt:this.params.userSalt,send:t=>e.logRequest(t),sendBeacon:t=>e.logBeacon(t),canSend$:e.authorized$,requestReady:()=>{e.authorize().catch(e=>{this.params.errors$.next({id:`ThinOneStat:Logger:RequestReadyFailed`,category:st.ErrorCategory.NETWORK,message:`Failed to authorize on requestReady`,thrown:e,data:{storageKey:t}})})}})}getStorageKeyForApi(e){return`thinonestat_events_${e}`}log(e){this.queues.forEach(t=>t.log(e))}flush(e){var t=this;return r(function*(){let n=yield ot.promiseAllSettled(t.queues.map(t=>t.flush(e)));if(n.length>0&&n.every(e=>e.status===`rejected`))throw n.find(e=>e.status===`rejected`).reason})()}pause(){this.queues.forEach(e=>e.pause())}resume(){this.queues.forEach(e=>e.resume())}destroy(){var e=this;return r(function*(){yield ot.promiseAllSettled(e.queues.map(e=>e.destroy())),e.queues=[]})()}}function mt(){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 ht{constructor(e){t(this,`offset`,void 0),this.offset=e}getOffset(){return this.offset??0}setOffset(e){this.offset=e}now(){return Date.now()+(this.offset??0)}date(e=new Date){return e.setTime(e.getTime()+(this.offset??0)),e}addServerTime(e,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 gt=require(`@vkontakte/videoplayer-core`),K=require(`@vkontakte/videoplayer-shared`),_t=(e,t,n)=>new K.Observable(r=>{let i=new K.Subscription,a,o=new K.ValueSubject(void 0),s;i.add(e.info.isLive$.pipe(K.filterChanged()).subscribe(t=>{s&&(s.unsubscribe(),o.next(void 0)),a=void 0,s=t?e.info.liveTime$.pipe(K.map(e=>e&&e/1e3)).subscribe(o):e.info.position$.subscribe(o),i.add(s)}));let{playing$:c,paused$:l,ended$:u,looped$:d}=e.events,f=e.events.willSeek$.pipe(K.filter(()=>e.info.playbackState$.getValue()===gt.PlaybackState.PLAYING)),p=e.events.seeked$.pipe(K.filter(()=>e.info.playbackState$.getValue()===gt.PlaybackState.PLAYING)),m=e.info.isStalled$.pipe(K.filter(e=>e)),h=!1,g=new K.Subject;i.add(f.subscribe(()=>{h||g.next(),h=!0})).add(p.subscribe(()=>h=!1));let _=K.merge(K.fromEvent(K.getWindow(),`beforeunload`),e.events.willDestruct$),v=e=>{a=e},y=e=>{let t=a;if(a=void 0,!(K.isNullable(t)||K.isNullable(e)||!isFinite(t)||!isFinite(e))){if(Math.round(e*1e3)<=Math.round(t*1e3)){a=e;return}r.next({from:t,to:e})}},b=new K.Subject,x=new K.Subject,S=()=>n.exactTime?e.info.isLive$.getValue()?e.getExactLiveTime():e.getExactTime():o.getValue()??0,C=K.merge(c,p,b).pipe(K.map(()=>S())),w=K.merge(d,K.merge(l,g,_,u,x,m).pipe(K.map(()=>S()))),ee=t.started$&&t.ended$?K.merge(C,t.ended$):C,te=t.started$&&t.ended$?K.merge(w,t.started$):w;if(i.add(ee.subscribe(v)).add(te.subscribe(y)),n.heartbeatInterval&&isFinite(n.heartbeatInterval)){let e=[],t=()=>{x.next(),b.next()};i.add(ee.subscribe(()=>{let r=K.getWindow().setTimeout(t,n.heartbeatInterval);e.push(r)})).add(te.subscribe(()=>{e.forEach(e=>{K.getWindow().clearTimeout(e)}),e=[]}))}return i}),vt=require(`@vkontakte/videoplayer-core`),yt=require(`@vkontakte/videoplayer-shared`),bt=(e,t)=>new yt.Observable(n=>{let r=new vt.Subscription;return r.add(yt.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}),xt=require(`@vkontakte/videoplayer-core`),q=require(`@vkontakte/videoplayer-shared`),St=(e,{maxTimeWindow:t})=>new q.Observable(n=>{let r=new xt.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&&=(q.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=q.getWindow().setTimeout(()=>{a.timeoutId=null,l()},t):t>0&&l()}};return r.add(e.info.httpDownloadMetrics$.pipe(q.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}),J=require(`@vkontakte/videoplayer-shared`),Ct=e=>new J.Observable(t=>{let n=new J.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(J.merge(p,m).subscribe(l)).add(J.merge(h,_,v).subscribe(u)).add(y.subscribe(f)),t.next(()=>{let e=a;return o&&(e+=(Date.now()-r)*i),Math.round(e)}),n}),wt=require(`@vkontakte/videoplayer-shared`),Tt=(e,t)=>new wt.Observable(n=>{let r=new wt.Subscription,i=0;return r.add(wt.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}),Et=require(`@vkontakte/videoplayer-shared`),Y=require(`@vkontakte/videoplayer-core`),Dt=e=>{if(!Et.isNullable(e)){if(typeof e==`string`)return e;try{return JSON.stringify(e)}catch{return String(e)}}},Ot=e=>e&&{[Y.HttpConnectionType.HTTP1]:`http1`,[Y.HttpConnectionType.HTTP2]:`http2`,[Y.HttpConnectionType.QUIC]:`http3`}[e],X=e=>{if(e!==void 0)switch(e){case Y.VideoFormat.MPEG:return`MP4`;case Y.VideoFormat.DASH:case Y.VideoFormat.DASH_LIVE:return`DASH`;case Y.VideoFormat.DASH_SEP:return`DASH_SEP`;case Y.VideoFormat.DASH_ONDEMAND:return`ONDEMAND_DASH`;case Y.VideoFormat.HLS_ONDEMAND:return`ONDEMAND_HLS`;case Y.VideoFormat.HLS:case Y.VideoFormat.HLS_LIVE:return`HLS`;case Y.VideoFormat.HLS_FMP4:return`HLS_FMP4`;case Y.VideoFormat.DASH_WEBM:case Y.VideoFormat.DASH_LIVE_WEBM:return`WEBM`;case Y.VideoFormat.DASH_LIVE_CMAF:return`ONDEMAND_DASH_LIVE`;case Y.VideoFormat.HLS_LIVE_CMAF:return`ONDEMAND_HLS_LIVE`;case Y.VideoFormat.WEB_RTC_LIVE:return`WEBRTC`;case Y.VideoFormat.DASH_WEBM_AV1:return`AV1`;case Y.VideoFormat.DASH_STREAMS:return`MULTI_DASH`;default:return Et.assertNever(e)}},Z=e=>{if(e!==void 0)switch(e){case Y.VideoQuality.Q_144P:return`144p`;case Y.VideoQuality.Q_240P:return`240p`;case Y.VideoQuality.Q_360P:return`360p`;case Y.VideoQuality.Q_480P:return`480p`;case Y.VideoQuality.Q_720P:return`720p`;case Y.VideoQuality.Q_1080P:return`1080p`;case Y.VideoQuality.Q_1440P:return`1440p`;case Y.VideoQuality.Q_2160P:return`2160p`;case Y.VideoQuality.INVARIANT:case Y.VideoQuality.Q_576P:case Y.VideoQuality.Q_4320P:return`UNKNOWN`;default:return Et.assertNever(e)}},kt=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}},Q=(e,t,n)=>{if(e&&t)switch(e){case Y.VideoFormat.MPEG:return n&&t[e]&&t[e][n];default:return t[e]?.url}},At=(e,t=!1)=>{if(t)return`minimal`;switch(e){case void 0:case Y.Surface.NONE:return;case Y.Surface.INLINE:return`inline`;case Y.Surface.FULLSCREEN:return`fullscreen`;case Y.Surface.SECOND_SCREEN:return`chromecast`;case Y.Surface.PIP:return`pip_external`}},jt=e=>{switch(e){case void 0:return;case Y.Surface.INVISIBLE:return`background`;default:return`foreground`}},Mt=`_thin-one-stat_deviceId`,Nt=`2.2.0`,Pt=()=>{let e=new z.Subscription;return{subscription:e,subscribe:(t,n)=>{t&&e.add(t.subscribe(n))}}};class Ft{constructor(e,n){t(this,`apis`,[]),t(this,`logger`,void 0),t(this,`config`,void 0),t(this,`subscription`,void 0),t(this,`lifecycleFlushSubscription`,void 0),t(this,`timeSynchronisation`,void 0),t(this,`statContext`,void 0),t(this,`deviceId`,void 0),t(this,`targetDuration`,void 0),t(this,`debugLogger`,new z.Logger),t(this,`thinOneStatDebugLog`,this.debugLogger.createComponentLog(`ThinOneStat`)),t(this,`eventNumber`,1),t(this,`isStarted`,void 0),t(this,`isSeeking`,void 0),t(this,`inBufferStarvation`,void 0),t(this,`firstByteManifestSent`,void 0),t(this,`firstMediaRequestSent`,void 0),t(this,`firstByteMediaSent`,void 0),t(this,`wasPaused`,void 0),t(this,`isLive`,void 0),t(this,`lastContentType`,void 0),t(this,`cdnHostname`,void 0),t(this,`isEmbed`,void 0),t(this,`embedHostname`,void 0),t(this,`connectionType`,void 0),t(this,`connectionReused`,void 0),t(this,`player`,void 0),t(this,`playerSize`,{width:0,height:0}),t(this,`currentSubtitle`,void 0),t(this,`userQuality`,void 0),t(this,`downloadQuality`,void 0),t(this,`downloadSpeed`,void 0),t(this,`networkType`,void 0),t(this,`uiEvents`,void 0),t(this,`playerSubscription`,void 0),t(this,`uiSubscription`,void 0),t(this,`adsSubscription`,void 0),t(this,`seekAction$`,new z.ValueSubject(`unknown`)),t(this,`vsid$`,new z.ValueSubject(void 0)),t(this,`isid$`,new z.ValueSubject(void 0)),t(this,`errors$`,new z.Subject),t(this,`getTotalViewTime`,()=>0),this.statContext=e,this.config=Ke(n.config??{}),this.subscription=new z.Subscription,this.config.synchronizeTime&&(this.timeSynchronisation=new ht),this.subscription.add(this.errors$.subscribe(e=>{this.thinOneStatDebugLog({message:`[${e.category}] ${e.id}: ${e.message}`})}));let r=z.safeStorage.get(Mt);this.statContext.deviceId?this.deviceId=this.statContext.deviceId:r?this.deviceId=r:(this.deviceId=mt(),z.safeStorage.set(Mt,this.deviceId)),this.statContext.targetDuration?this.targetDuration=this.statContext.targetDuration:this.targetDuration=this.config.watchedNDefaultTargetDuration,this.resetViewSession(),n.useIsid&&this.isid$.next(n.isid??fe());let i=new at({errors$:this.errors$,config:this.config,timeSynchronisation:this.timeSynchronisation});this.config.apiForticom&&this.apis.push(new et({config:this.config,apiTransport:i,errors$:this.errors$,deviceId:this.deviceId,refreshAuthToken:n.refreshAuthToken})),this.config.apiUvRest&&(n.getUvRestAuthToken?this.apis.push(new tt({config:this.config,apiTransport:i,errors$:this.errors$,userId:this.statContext.userId,getAuthToken:n.getUvRestAuthToken})):this.errors$.next({id:`ThinOneStat:Init:MissingGetUvRestAuthToken`,category:z.ErrorCategory.WTF,message:`thinStatToUvRest enabled but getUvRestAuthToken callback not provided`})),this.logger=new pt({config:this.config,debugLogger:this.debugLogger,apis:this.apis,errors$:this.errors$,userSalt:n.userSalt});let{isEmbed:a,topOrigin:o}=z.detectEmbed();this.isEmbed=a,this.embedHostname=o?new URL(o).hostname:void 0}authorize(e){this.apis.forEach(t=>{t.authorize(e).catch(()=>{})})}reportError(e){let t={error_severity:e.severity,error_category:this.mapErrorCategory(e.category),player_error_code:e.code,player_error_trace:e.trace,error_message:e.message,content_type:this.getCurrentContentType()};this.logError(t),e.severity===`critical`&&this.logCannotPlay(),this.logTelemetry(this.collectTelemetryData())}updateContext(e){this.statContext=n(n({},this.statContext),e)}attachTo(e,t){this.playerSubscription&&(this.thinOneStatDebugLog({message:`Re-attaching to player, unsubscribing from previous`}),this.playerSubscription.unsubscribe());let r=new z.Subscription,i=(e,t)=>r.add(e.subscribe(t));i(Ct(e),e=>{this.getTotalViewTime=e}),i(e.info.isLive$,e=>this.isLive=e),i(e.info.currentFormat$,e=>{let t=X(e);t&&(this.lastContentType=t)}),i(e.info.hostname$.pipe(z.filter(e=>e!==void 0)),e=>{this.cdnHostname=e});let a;i(z.combine({hostname:e.info.hostname$,connectionType:e.info.httpConnectionType$,connectionReused:e.info.httpConnectionReused$}).pipe(z.filter(({hostname:e})=>e!==void 0),z.filter(({connectionType:e})=>e!==void 0),z.filter(({connectionReused:e})=>e!==void 0)),({hostname:e,connectionType:t,connectionReused:n})=>{if(a!==void 0&&a!==e){let r={cdn_host:e,connection_type:Ot(t),connection_reused:n,content_type:this.getCurrentContentType()};this.logFailover(r),this.logTelemetry(this.collectTelemetryData())}this.cdnHostname=a=e}),i(e.info.httpConnectionType$,e=>{this.connectionType=Ot(e)}),i(e.info.httpConnectionReused$,e=>{this.connectionReused=e}),i(_t(e,t,{heartbeatInterval:this.config.watchCoverageHeartbeatInterval,exactTime:this.config.watchCoverageExactTime}),t=>{let r={watch_interval:`${Math.round(t.from*1e3)}-${Math.round(t.to*1e3)}`,in_history:!!this.statContext.inHistory,content_type:this.getCurrentContentType(),playback_quality:Z(e.info.currentQuality$.getValue()),recom_info:this.statContext.recomInfo};if(!e.info.isLive$.getValue())this.logWatchCoverage(r);else{let t=e.info.atLiveEdge$.getValue();this.logWatchCoverageLive(n(n({},r),{},{live:!!t}))}}),i(Tt(e,{interval:this.statContext.telemetryInterval??this.config.telemetryInterval,getTotalViewTime:this.getTotalViewTime}),()=>{this.logTelemetry(this.collectTelemetryData())}),i(bt(e,{targetDuration:this.targetDuration,getTotalViewTime:this.getTotalViewTime}),e=>{this.logWatchedN(e)}),i(e.events.willReady$,()=>{let t={isid:this.isid$.getValue(),stream_profile:kt(this.getCurrentContentType()),dpi:Math.round(this.statContext.dpi??96*B.clientChecker.display.pixelRatio),web_layout:this.statContext.isMobile||B.clientChecker.device.isMobile?`mobile`:`desktop`,preloaded:this.statContext.preload,navigation:this.statContext.navigation,recom_info:this.statContext.recomInfo};if(this.isEmbed&&(t.iframe_host=this.embedHostname??`unknown`),this.logStartSession(t),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:Q(t,n,i),playback_quality:Z(i)};this.logPreloadStarted(a)}}),i(z.combine({manifestRequested$:e.events.manifestRequested$,connectionType:e.info.httpConnectionType$,connectionReused:e.info.httpConnectionReused$}).pipe(z.filter(({connectionType:e})=>e!==void 0),z.filter(({connectionReused:e})=>e!==void 0),z.once()),()=>{let t={playback_url:Q(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)}),i(z.combine({firstBytesManifest:e.events.firstBytesManifest$,connectionType:e.info.httpConnectionType$,connectionReused:e.info.httpConnectionReused$}).pipe(z.once()),()=>{if(this.firstByteManifestSent)return;this.firstByteManifestSent=!0;let t={playback_url:Q(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)}),i(e.events.manifestReceived$,()=>{let t={playback_url:Q(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)}),i(e.events.firstBytesRequested$,()=>{if(this.firstMediaRequestSent)return;this.firstMediaRequestSent=!0;let t={playback_url:Q(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)}),i(e.events.firstBytes$,()=>{if(this.firstByteMediaSent)return;this.firstByteMediaSent=!0;let t={playback_url:Q(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)}),i(z.merge(e.events.willStart$,e.events.looped$),e=>{e&&this.resetViewSession(),this.isStarted=!0}),i(e.events.started$,()=>{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:Z(n),user_quality:r?`auto`:Z(n),player_width:Math.round(this.statContext.playerSize?.width??this.playerSize.width),player_height:Math.round(this.statContext.playerSize?.height??this.playerSize.height),muted:i,sound_volume:Math.round(a*100),buffer_time:this.calcBufferTime(t),mode:At(o,this.statContext.isPreviewPlayerView),visibility:jt(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*100,recom_info:this.statContext.recomInfo};this.logPlaybackStarted(d),this.logTelemetry(this.collectTelemetryData())}),i(e.events.willStart$,()=>{this.logPlay()}),i(e.events.playing$,()=>{let t=e.info.currentBuffer$.getValue(),n={buffer_time:this.calcBufferTime(t)};this.logPlaying(n),this.inBufferStarvation=!1,this.wasPaused&&this.logResume()}),i(e.events.paused$,()=>{this.wasPaused=!0,this.logPause()}),i(e.events.ended$,()=>{this.logContentEndReached()}),i(e.events.willStop$,()=>{this.isStarted=!1,this.isSeeking=!1,this.inBufferStarvation=!1,this.logStop()}),i(z.merge(e.events.fetcherRecoverableError$,e.events.fatalError$),()=>{this.statContext.preload&&this.logPreloadError()}),i(e.events.fetcherRecoverableError$,({id:e,category:t,data:n,message:r,httpCode:i,UVBackendErrorCode:a})=>{let o={error_severity:this.mapErrorSeverity(t),error_category:this.mapErrorCategory(t),player_error_code:e,player_error_trace:Dt(n),http_error_code:i,uv_backend_error_code_subcode:a,error_message:r,content_type:this.getCurrentContentType()};this.logError(o),this.mapErrorSeverity(t)===`critical`&&this.logCannotPlay(),this.logTelemetry(this.collectTelemetryData())}),i(e.events.managedError$,({id:e,category:t,data:n,message:r,httpCode:i,UVBackendErrorCode:a})=>{let o={error_severity:this.mapErrorSeverity(t),error_category:this.mapErrorCategory(t),player_error_code:e,player_error_trace:Dt(n),http_error_code:i,uv_backend_error_code_subcode:a,error_message:r,content_type:this.getCurrentContentType()};this.logError(o),this.logTelemetry(this.collectTelemetryData())}),i(e.events.fatalError$,({id:e,category:t,data:n,message:r,httpCode:i,UVBackendErrorCode:a})=>{let o={error_severity:`critical`,error_category:this.mapErrorCategory(t),player_error_code:e,player_error_trace:Dt(n),http_error_code:i,uv_backend_error_code_subcode:a,error_message:r,content_type:this.getCurrentContentType()};this.logError(o),this.logCannotPlay(),this.logTelemetry(this.collectTelemetryData())}),i(z.combine({connectionType:e.info.httpConnectionType$,connectionReused:e.info.httpConnectionReused$,connectionMetrics:e.info.httpConnectionMetrics$}).pipe(z.filter(({connectionReused:e})=>e!==void 0),z.filter(({connectionMetrics:e})=>e!==void 0),z.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=t?.dnsResolveTime,s=t?.tcpHandshakeTime,c=t?.tlsHandshakeTime,l={playback_url:Q(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:o?Math.round(o):void 0,tcp_handshake_time:s?Math.round(s):void 0,tls_handshake_time:c?Math.round(c):void 0};this.logConnectionEstablished(l)}),i(St(e,{maxTimeWindow:this.config.downloadBytesMaxTime}),e=>{this.downloadSpeed=e.download_speed,this.logDownloadBytes(e)}),i(e.events.firstFrame$,()=>{this.logFirstVideoFrameDecoded()}),i(e.events.willSeek$,()=>{this.isSeeking=!0;let e={seek_type:this.seekAction$.getValue()};this.isStarted&&this.logSeeking(e)}),i(e.events.seeked$,()=>{this.isSeeking=!1;let e={seek_type:this.seekAction$.getValue()};this.isStarted&&this.logSeeked(e),this.seekAction$.next(`unknown`)}),i(e.info.stallStartTime$,t=>{if(t<=0){this.inBufferStarvation=!1;return}this.inBufferStarvation||(this.inBufferStarvation=!0,this.logBufferStarvation({buffer_time:this.calcBufferTime(e.info.currentBuffer$.getValue())}),this.logTelemetry(this.collectTelemetryData()))}),i(e.info.currentBuffer$.pipe(z.filter(e=>!!this.calcBufferTime(e)),z.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 o;i(z.combine({videoStream:e.info.currentVideoStream$,audioStream:e.info.currentAudioStream$,quality:e.info.currentQuality$}).pipe(z.filter(({videoStream:e,audioStream:t})=>e!==void 0&&t!==void 0),z.filter(({quality:e})=>e!==void 0)),({videoStream:t,audioStream:n,quality:r})=>{if(o!==r){if(this.userQuality=e.info.isAutoQualityEnabled$.getValue()?`auto`:Z(r),this.downloadQuality=Z(r),this.isStarted){let e=t?.codec,r=n?.codec,i={user_quality:this.userQuality,playback_quality:Z(o),download_quality:this.downloadQuality,codec_info:this.genCodecInfo(e,r)};this.logQualityChanged(i)}o=r}});let s,c;return i(e.info.surface$,e=>{let t=At(e,this.statContext.isPreviewPlayerView);t&&!this.uiEvents&&this.isStarted&&this.logModeChanged({mode:t}),c=jt(e),s!==c&&(this.isStarted&&this.logVisibilityChanged({visibility:c}),s=jt(e))}),i(z.combine({muted:e.info.muted$,volume:e.info.volume$}).pipe(z.debounce(300)),({muted:e,volume:t})=>{if(this.isStarted){let n={muted:e,sound_volume:Math.round(t*100)};this.logSoundChanged(n)}}),i(e.info.currentFormat$.pipe(z.filter(e=>e!==void 0),z.skip(1)),e=>{let t={content_type:X(e),cdn_host:this.cdnHostname,connection_type:this.connectionType,connection_reused:this.connectionReused};this.logContentTypeChange(t)}),i(e.info.currentAudioStream$.pipe(z.filter(e=>e!==void 0),z.skip(1)),e=>{let t={audio_track_lang:e.language,codec_info:e.codec};this.logAudioTrackSwitched(t)}),i(e.info.currentVideoStream$.pipe(z.filter(e=>e!==void 0),z.skip(1)),e=>{let t={hdr:e.hdr,codec_info:e.codec};this.logVideoTrackSwitched(t)}),this.player=e,this.playerSubscription=r,this.resubscribeLifecycleFlush(),this.subscription.add(r),r}attachToUi(e){this.uiSubscription&&(this.thinOneStatDebugLog({message:`Re-attaching to UI, unsubscribing from previous`}),this.uiSubscription.unsubscribe()),this.uiEvents=e;let{subscribe:t,subscription:r}=Pt();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:Math.round(e),player_height:Math.round(t)}))}),t(e.isLoaderVisible$,e=>{if(!e){this.inBufferStarvation=!1;return}this.isStarted&&(this.logShowLoader(),!(this.isSeeking||this.inBufferStarvation||!this.player)&&(this.inBufferStarvation=!0,this.logBufferStarvation({buffer_time:this.calcBufferTime(this.player.info.currentBuffer$.getValue())}),this.logTelemetry(this.collectTelemetryData())))}),t(e.actionSubtitlesSwitched$,e=>{if(this.currentSubtitle=n({},e),this.isStarted){let t={subtitles_enabled:e.enabled,subtitles_track_lang:e.lang,auto_subtitles:e.auto};this.logSubtitlesSwitched(t)}});let{surface$:i}=Pe(this.uiEvents,t,this.player);return t(i,e=>{this.isStarted&&this.logModeChanged({mode:At(e)})}),t(e.actionQuality$,e=>{var t,n,r;let i=e=>Be.arrayIncludes(ze.objectValues(He),e),a=(t=this.player)==null||(t=t.info.currentVideoStream$.getValue())==null?void 0:t.codec,o=(n=this.player)==null||(n=n.info.currentAudioStream$.getValue())==null?void 0:n.codec,s={user_quality:i(e)?`auto`:Z(e),playback_quality:Z(this.player?.info.currentQuality$.getValue()),download_quality:i(e)?Z((r=this.player)==null||(r=r.info.currentQuality$)==null?void 0:r.getValue()):Z(e),codec_info:this.genCodecInfo(a,o)};this.logQualityChangeRequested(s)}),this.uiSubscription=r,this.resubscribeLifecycleFlush(),this.subscription.add(r),r}attachToAds(e){this.adsSubscription&&(this.thinOneStatDebugLog({message:`Re-attaching to ads, unsubscribing from previous`}),this.adsSubscription.unsubscribe());let{subscription:t,subscribe:n}=Pt();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.adsSubscription=t,this.resubscribeLifecycleFlush(),this.subscription.add(t),t}getDeviceId(){return this.deviceId}resetViewSession(){this.thinOneStatDebugLog({message:`VSID reset`}),E.generateVSID(this.config.useVsid64),this.vsid$.next(E.getVSID()),this.eventNumber=0,this.firstByteManifestSent=!1,this.firstMediaRequestSent=!1,this.firstByteMediaSent=!1}destroy(){var e=this;return r(function*(){e.thinOneStatDebugLog({message:`Destroying ThinOneStat`}),e.subscription.unsubscribe(),e.lifecycleFlushSubscription?.unsubscribe(),yield e.logger.destroy(),e.apis.forEach(e=>e.destroy()),e.thinOneStatDebugLog({message:`ThinOneStat destroyed`})})()}calcBufferTime(e){return e?Math.round(((e.end??0)-(e.start??0))*1e3):void 0}mapErrorCategory(e){switch(e){case z.ErrorCategory.NETWORK:return`network`;case z.ErrorCategory.VIDEO_PIPELINE:return`video_pipeline`;case z.ErrorCategory.EXTERNAL_API:return`external_api`;case z.ErrorCategory.PARSER:return`parser`;case z.ErrorCategory.DOM:return`dom`;default:return`wtf`}}mapErrorSeverity(e){return z.ErrorCategory.FATAL===e?`critical`:`informative`}getCurrentContentType(){let e=X(this.player?.info.currentFormat$.getValue());if(e)return e;if(this.lastContentType)return this.lastContentType;let t=this.player?.info.availableSources$.getValue();if(!t)return;let n=Object.keys(t)[0];return X(n)}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=this.getCurrentContentType(),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:Z(this.player.info.currentQuality$.getValue()),download_quality:this.downloadQuality,codec_info:this.genCodecInfo(a,o),bandwidth_from_manifest:s?Math.round(s):void 0,cdn_host:this.cdnHostname,download_speed:this.downloadSpeed?Math.round(this.downloadSpeed):void 0,network_type:this.networkType,rtt:c?Math.round(c):void 0,latency:this.getLatencyInfo()}}isValidPlatform(e=``){return Be.arrayIncludes([`web:desktop`,`web:mobile`,`smart_tv`],e)}createRequiredParams(e){let t=this.vsid$.getValue();z.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:${O}`,platform:this.isValidPlatform(this.statContext.platform)?this.statContext.platform:`web:${this.statContext.isMobile||B.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:Nt,browser:this.statContext.browser??B.clientChecker.browser.current,browser_version:this.statContext.browserVersion??String(B.clientChecker.browser.currentVersion),os:this.statContext.os??B.clientChecker.device.os.name,os_version:this.statContext.osVersion??B.clientChecker.device.os.version,device_type:this.statContext.deviceType??(this.statContext.isMobile||B.clientChecker.device.isMobile?`mobile`:`desktop`),device_manufacturer:this.statContext.deviceManufacturer??B.clientChecker.device.details.vendor,device_model:this.statContext.deviceModel??B.clientChecker.device.details.model,navigation:this.statContext.navigation};for(let t of this.config.disabledParams)delete e[t];return e}log(e,t,r=!1){if(Be.arrayIncludes(this.config.disabledEvents,e))return;let i=this.createRequiredParams(e),a={};r&&(a=this.createRequiredFatParams()),this.logger.log(n(n(n({},i),a),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)}logContentEndReached(){this.log(`content_end_reached`)}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)}resubscribeLifecycleFlush(){this.lifecycleFlushSubscription?.unsubscribe();let e=z.getWindow(),t=()=>{this.logger.flush({wantBeacon:!0,clearStorage:this.config.clearStorageAtUnload}).catch(()=>{})},n=new z.Subscription;n.add(z.fromEvent(e,`beforeunload`).subscribe(t)),n.add(z.fromEvent(e,`pagehide`).subscribe(t)),n.add(z.fromEvent(e.document,`visibilitychange`).subscribe(e=>{e.target?.visibilityState===`hidden`&&t()})),this.lifecycleFlushSubscription=n}}var It=require(`@vkontakte/videoplayer-shared`),Lt=require(`@vkontakte/videoplayer-shared`),$=require(`@vkontakte/videoplayer-core`),Rt=require(`@vkontakte/videoplayer-shared`);class zt{constructor(){t(this,`startTime`,null),t(this,`stopTime`,null),t(this,`accumulatedTime`,0)}get time(){return Math.floor(this.timeMs/1e3)}get timeMs(){return this.startTime===null?0:(this.stopTime??this.now())-this.startTime-this.accumulatedTime}get isRunning(){return this.startTime!==null&&this.stopTime===null}start(){this.isRunning||(this.stopTime===null?this.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 Bt=()=>window.Image?new Image:document.createElement(`img`);class Vt{constructor(e){t(this,`params`,void 0),t(this,`position`,0),t(this,`started`,!1),t(this,`isActiveLive`,void 0),t(this,`heartbeatPixels`,[]),t(this,`heartbeatLastTimeSent`,{}),t(this,`heartbeatInterval`,void 0),t(this,`heartbeatFirstTimeoutId`,void 0),t(this,`idleCallbackIds`,[]),t(this,`log`,void 0),t(this,`stopwatch`,new zt),t(this,`subscription`,new $.Subscription),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=>It.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(Lt.requestIdleCallbackPolyfilled(()=>Bt().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
+ const e=[`application`,`platform`,`product`];var t=require(`@oxc-project/runtime/helpers/defineProperty`),n=require(`@oxc-project/runtime/helpers/objectSpread2`),r=require(`@oxc-project/runtime/helpers/asyncToGenerator`),i=require(`@oxc-project/runtime/helpers/objectWithoutProperties`),a=Object.defineProperty,o=Object.getOwnPropertyNames,s=Object.getOwnPropertyDescriptor,c=Object.prototype.hasOwnProperty;function l(e){return this[e]}var u=e=>{var t=(d??=new WeakMap).get(e),n;if(t)return t;if(t=a({},`__esModule`,{value:!0}),e&&typeof e==`object`||typeof e==`function`)for(var r of o(e))c.call(t,r)||a(t,r,{get:l.bind(e,r),enumerable:!(n=s(e,r))||n.enumerable});return d.set(e,t),t},d,f=e=>e;function p(e,t){this[e]=f.bind(null,t)}var m=(e,t)=>{for(var n in t)a(e,n,{get:t[n],enumerable:!0,configurable:!0,set:p.bind(t,n)})},h={};m(h,{VERSION:()=>O,ThinOneStat:()=>Re,SeekAction:()=>S,Quality:()=>y,OneStat:()=>Le,MediascopePixel:()=>Vt,InteractiveInterfaceClick:()=>C,ContentType:()=>b,ConnectionType:()=>x,ApiEnv:()=>v}),module.exports=u(h);var g=require(`@vkontakte/videoplayer-shared`),_=require(`@vkontakte/videoplayer-shared`),v;(e=>{e.PROD=`prod`,e.VK_ALIAS=`vk_alias`,e.VIDEOTEST=`videotest`,e.TEST=`test`,e.OKCDN=`okcdn`,e.AUTO=`auto`})(v||={});var y;(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`})(y||={});var b;(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`})(b||={});var x;(e=>{e.HTTP1=`http1`,e.HTTP2=`http2`,e.HTTP3=`http3`})(x||={});var S;(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`})(S||={});var C;(e=>{e.GRAPH_SHOW=`iGraphShow`,e.GRAPH_HIDE=`iGraphHide`,e.NEXT_AREA=`iNextChapterArea`,e.NEXT_BUTTON=`iNextChapterBtn`,e.WATCH_AGAIN=`iWatchAgainBtn`})(C||={});var w={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`},ee={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`},te={unknown:`un`,mobile:`m`,lowest:`ls`,low:`l`,medium:`md`,high:`h`,fullhd:`f`,quadhd:`q`,ultrahd:`u`},ne={pip:`pi`,fullscreen:`fs`,external:`ex`,prefetch:`pr`,airplay:`ap`,chromecast:`cc`,invisible:`iv`,minimal:`minimal`},re=require(`@vkontakte/videoplayer-shared`),ie=`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:``},oe={apiEnv:`vk_alias`,apiKey:ie,apiBaseUrl:null,apiUvRestBaseUrl:`https://uvapi.okcdn.ru`,apiCollector:`ok.mobile.apps.video`,apiForticom:!0,apiUvRest:!1,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:!0,watchCoverageExactTime:!1},se=e=>re.fillWithDefault(e,oe);function ce(){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 T=require(`@vkontakte/videoplayer-shared`),le=require(`@vkontakte/videoplayer-shared`),ue=require(`@vkontakte/videoplayer-shared`),de=()=>ue.stringPadStart(Math.floor(Math.random()*2**32).toString(36),13,`0`),fe=()=>ue.stringPadStart(Math.floor(Math.random()*2**64).toString(36),13,`0`);class E{static getVSID(){return E.vsid}static generateVSID(e){return E.vsid=e?fe():de(),E.vsid}}t(E,`vsid`,void 0);var D=require(`@vkontakte/videoplayer-shared`),pe=require(`@vkontakte/videoplayer-shared`),me=require(`@vkontakte/videoplayer-shared`),he=e=>{let{operation:t,custom:r}=e,i=me.objectFromEntries(pe.objectEntries(r).map(([e,t])=>{let n=ee[e]??e,r=t;return t&&(e===`mode`?r=ne[t]??t:e===`quality`&&(r=te[t]??t)),[n,r]}));return n(n({},e),{},{operation:w[t]??t,custom:i})},O=`1.0.110-dev.f2fd80887.0`,k=require(`@vkontakte/videoplayer-shared`),ge=/Mobile|mini|Fennec|Android|iP(ad|od|hone)|opera (mini|mobi)/i;class _e{constructor(e){t(this,`id`,`forticom`),t(this,`params`,void 0),t(this,`authToken`,void 0),t(this,`sessionKey`,void 0),t(this,`authorizePromise`,void 0),t(this,`refreshAuthTokenPromise`,void 0),t(this,`consequentAuthErrors`,0),t(this,`authorized$`,new k.ValueSubject(!1)),t(this,`backoffTimeoutId`,void 0),this.params=e}authorize(e){var t=this;return r(function*(){return t.authToken=e??(yield t.refreshAuthToken()),t._authorizeWithBackoff()})()}logBeacon(e){let t=this.createLogParams(e),n=this.sessionKey;n&&(this.params.apiTransport.sendBeacon(`log.externalLog`,t,n)||this.logRequest(e).catch(()=>{}))}logRequest(e){var t=this;return r(function*(){let n=`log.externalLog`,i=t.createLogParams(e),a=t.sessionKey??(yield t._authorizeWithBackoff());if(!a)return;let o=function(){var e=r(function*(e,r=t.params.config.requestRetryCount){try{return yield t.params.apiTransport.sendRequest(n,i,a)}catch(i){if(!i||!(`error_code`in i)){t.params.error$.next({id:`logRequestUnknown`,category:k.ErrorCategory.NETWORK,message:`Unknown ${n} error`,thrown:i});return}let a=i?.error_code;switch(a){case 102:case 103:case 104:return t.authorized$.next(!1),t.sessionKey=yield t._authorizeWithBackoff(),r>0?o(e,r-1):void 0;case 401:return t.authorized$.next(!1),t.authToken=yield t.refreshAuthToken(),t.sessionKey=yield t._authorizeWithBackoff(),r>0?o(e,r-1):void 0;default:t.params.error$.next({id:`LogRequest#${a}`,category:k.ErrorCategory.EXTERNAL_API,message:`${n} error`,data:i});return}}});return function(t){return e.apply(this,arguments)}}();return o(e)})()}destroy(){k.getWindow().clearTimeout(this.backoffTimeoutId),this.backoffTimeoutId=0}refreshAuthToken(){var e=this;return r(function*(){if(e.params.refreshAuthToken)return e.refreshAuthTokenPromise||=D.promiseFinally(e.params.refreshAuthToken(),()=>{e.refreshAuthTokenPromise=void 0}),e.refreshAuthTokenPromise})()}createLogParams(e){let t=`WEB`,n=!1,r=`@vkontakte/videoplayer-statistics:${O}`;if(this.params.config.useVKComIsMobileLogic){let{appVersion:e}=k.getWindow().navigator;n=ge.test(e)}else this.params.mobile&&(n=!0);return n&&(t=`M_WEB`),this.params.vktvVersion&&(t=`SMART_TV`,r=this.params.vktvVersion),{collector:this.params.config.apiCollector,data:JSON.stringify({application:r,platform:t,items:this.params.config.shorten?e.map(he):e})}}_authorizeWithBackoff(){if(!this.consequentAuthErrors)return this._authorize();let e=k.getExponentialDelay(this.consequentAuthErrors,this.params.config.backoff);return new Promise(t=>{this.backoffTimeoutId||=k.getWindow().setTimeout(()=>{D.promiseFinally(this._authorize().then(t).catch(e=>this.params.error$.next({id:`AuthorizeBackoff`,category:k.ErrorCategory.NETWORK,message:`Otherwise unhandled error in authorization`,thrown:e})),()=>this.backoffTimeoutId=0)},e)})}_authorize(){var e=this;return r(function*(){if(e.authorizePromise)return e.authorizePromise;e.sessionKey=void 0,e.authorized$.next(!1);let t={session_data:{version:2,device_id:e.params.deviceId,client_version:O.split(`-`)[0],client_type:`SDK_JS`}};return e.authToken!==void 0&&(t.session_data.auth_token=e.authToken,t.session_data.version=3),e.authorizePromise=D.promiseFinally(e.params.apiTransport.sendRequest(`auth.anonymLogin`,t).then(t=>((!t||!t.session_key)&&e.params.error$.next({id:`AuthorizeFailed`,category:k.ErrorCategory.EXTERNAL_API,message:`No session key`,data:t}),e.sessionKey=t?.session_key??void 0,e.sessionKey)).catch(function(){var t=r(function*(t){e.sessionKey=void 0;let n=t?.error_code;switch(n){case 401:return e.authToken=yield e.refreshAuthToken(),e._authorizeWithBackoff()}n?e.params.error$.next({id:`Authorize#${n}`,category:k.ErrorCategory.EXTERNAL_API,message:`authorize error`,data:t}):e.params.error$.next({id:`AuthorizeUnknown`,category:k.ErrorCategory.NETWORK,message:`authorize error`,thrown:t})});return function(e){return t.apply(this,arguments)}}()),()=>{e.authorizePromise=void 0,e.consequentAuthErrors=e.sessionKey?0:e.consequentAuthErrors+1,e.authorized$.next(e.sessionKey!==void 0)}),e.authorizePromise})()}}class ve{constructor(e){t(this,`id`,`uvrest`),t(this,`authorized$`,new k.ValueSubject(!1)),t(this,`params`,void 0),t(this,`statToken`,void 0),t(this,`authorizePromise`,void 0),t(this,`isDestroyed`,!1),this.params=e}authorize(e){var t=this;return r(function*(){if(!t.isDestroyed)return e?(t.statToken=e,t.authorized$.next(!0),e):t.authorizePromise?t.authorizePromise:(t.authorized$.next(!1),t.authorizePromise=D.promiseFinally(t.executeAuthorize(),()=>{t.authorizePromise=void 0,t.isDestroyed||t.authorized$.next(t.statToken!==void 0)}),t.authorizePromise)})()}logRequest(e){var t=this;return r(function*(){if(!e.length)return;let n=t.buildBody(e);try{let e=yield t.getValidToken();if(!e){t.params.error$.next({id:`OneStat:UvRestApi:LogRequestNoToken`,category:k.ErrorCategory.NETWORK,message:`No stat token available for log request`});return}yield t.params.apiTransport.sendJsonRequest(`/uv/stat/externalLog`,n,{Authorization:`Bearer ${e}`})}catch(e){(yield t.handleLogRequestError(e))&&(yield t.retryLogRequestAfterRecovery(n))}})()}logBeacon(e){if(!e.length)return;let t=this.statToken;if(!t)return;let n=this.buildBody(e);this.params.apiTransport.sendJsonBeacon(`/uv/stat/externalLog`,n,{Authorization:`Bearer ${t}`})}destroy(){this.isDestroyed=!0,this.authorizePromise=void 0,this.statToken=void 0,this.authorized$.next(!1)}getValidToken(){var e=this;return r(function*(){return e.statToken?e.statToken:e.authorize()})()}executeAuthorize(){var e=this;return r(function*(){try{let t=yield e.params.getAuthToken();if(e.isDestroyed)return;if(!t){e.params.error$.next({id:`OneStat:UvRestApi:NoToken`,category:k.ErrorCategory.EXTERNAL_API,message:`getAuthToken returned no token`});return}return e.statToken=t,e.statToken}catch(t){if(e.isDestroyed)return;e.params.error$.next({id:`OneStat:UvRestApi:AuthorizeFailed`,category:k.ErrorCategory.NETWORK,message:`Failed to get stat token`,thrown:t});return}})()}handleLogRequestError(e){var t=this;return r(function*(){let n=e?.status;return n===401?(t.params.error$.next({id:`OneStat:UvRestApi:TokenExpired`,category:k.ErrorCategory.EXTERNAL_API,message:`Stat token expired (401), refreshing`,thrown:e}),t.authorized$.next(!1),t.statToken=void 0,(yield t.authorize())!==void 0):(t.params.error$.next({id:`OneStat:UvRestApi:LogRequestFailed#${n??`unknown`}`,category:k.ErrorCategory.EXTERNAL_API,message:`Log request failed with status ${n}`,thrown:e}),!1)})()}retryLogRequestAfterRecovery(e){var t=this;return r(function*(){let n=t.statToken;if(!n){t.params.error$.next({id:`OneStat:UvRestApi:RetryNoToken`,category:k.ErrorCategory.NETWORK,message:`Cannot retry log request: no token after recovery`});return}try{yield t.params.apiTransport.sendJsonRequest(`/uv/stat/externalLog`,e,{Authorization:`Bearer ${n}`})}catch(e){t.params.error$.next({id:`OneStat:UvRestApi:RetryFailed`,category:k.ErrorCategory.EXTERNAL_API,message:`Log request failed after token refresh`,thrown:e})}})()}buildBody(e){let t=`WEB`,n=!1,r=`@vkontakte/videoplayer-statistics:${O}`;if(this.params.config.useVKComIsMobileLogic){let{appVersion:e}=k.getWindow().navigator;n=ge.test(e)}else this.params.mobile&&(n=!0);return n&&(t=`M_WEB`),this.params.vktvVersion&&(t=`SMART_TV`,r=this.params.vktvVersion),[{application:r,platform:t,user_id:this.params.userId,items:this.params.config.shorten?e.map(he):e}]}}var A=require(`@vkontakte/videoplayer-shared`),ye=require(`@vkontakte/videoplayer-shared`),be=require(`@vkontakte/videoplayer-shared`),j=require(`@vkontakte/videoplayer-shared`);class xe{constructor(e){t(this,`apiKey`,void 0),t(this,`apiBaseUrl`,void 0),t(this,`apiUvRestBaseUrl`,void 0),t(this,`apiEnv`,void 0),t(this,`timeSynchronisation`,void 0),t(this,`isApiBaseUrlFetched`,void 0),t(this,`params`,void 0),this.params=e,this.apiKey=e.config.apiKey,this.apiEnv=e.config.apiEnv,this.apiBaseUrl=e.config.apiBaseUrl??ae[this.apiEnv],this.apiUvRestBaseUrl=e.config.apiUvRestBaseUrl,this.timeSynchronisation=e.timeSynchronisation,this.isApiBaseUrlFetched=!1}resolveApiBaseUrl(){var e=this;return r(function*(){if(e.apiEnv!==`auto`||e.isApiBaseUrlFetched)return e.apiBaseUrl;try{var t;let e=atob(`aHR0cHM6Ly9kbnMuZ29vZ2xlL3Jlc29sdmU/bmFtZT12aWRlby5fZW5kcG9pbnQub2sucnUmdHlwZT1UWFQ=`),n=yield(yield A.fetchPolyfilled(e,{method:`GET`,mode:`cors`,cache:`no-cache`})).json(),r=n==null||(t=n.Answer[0])==null?void 0:t.data;if(!r)throw Error(`Wrong DNS response`);return r}catch(t){return e.params.error$.next({id:`OneStat:ApiTransport:resolveApiBaseUrl`,category:j.ErrorCategory.NETWORK,message:`Unhandled resolve api base url error`,thrown:t}),ae.vk_alias}finally{e.isApiBaseUrlFetched=!0}})()}sendBeacon(e,t,n){if(!j.getWindow().Blob||!j.getWindow().navigator.sendBeacon)return!1;let r=this._prepareQueryParams({method:e,queryParams:t,sessionKey:n}),i=j.getWindow().Blob,a=new i([r.toString()],{type:`application/x-www-form-urlencoded`});try{return j.getWindow().navigator.sendBeacon(`${this.apiBaseUrl}/fb.do`,a)}catch(n){this.params.error$.next({id:`OneStat:ApiTransport:sendBeacon`,category:j.ErrorCategory.NETWORK,message:`Unhandled beacon error`,thrown:n,data:{method:e,params:t}})}return!1}sendRequest(e,t,n){var i=this;return r(function*(){let r=j.now(),a=a=>{if(a instanceof TypeError&&ye.arrayIncludes([`Failed to fetch`,`NetworkError when attempting to fetch resource.`],a.message)){i.params.error$.next({id:`Network`,category:j.ErrorCategory.NETWORK,message:`Request failed`,thrown:a});return}i.params.error$.next({id:`OneStat:ApiTransport:sendRequest`,category:j.ErrorCategory.NETWORK,message:`Unhandled request error`,thrown:a,data:{method:e,params:t,sessionKey:n,time:j.now()-r}})};i.apiBaseUrl=yield i.resolveApiBaseUrl();let o={method:`post`,headers:{"Content-type":`application/x-www-form-urlencoded`},body:i._prepareQueryParams({method:e,queryParams:t,sessionKey:n})};return i.params.config.useKeepalive&&(o.keepalive=!0),A.fetchPolyfilled(`${i.apiBaseUrl}/fb.do`,o).then(e=>{let t=Number(e.headers.get(`content-length`))===0,n=new Date(e.headers.get(`date`)??``).getTime(),o=j.now()-r;if(isFinite(n)&&i.timeSynchronisation?.addServerTime(n,o),!t)return e.json().then(e=>Object.prototype.hasOwnProperty.call(e,`error_msg`)?Promise.reject(e):e,a)},a)})()}sendJsonBeacon(e,t,r){let i=`${this.apiUvRestBaseUrl}${e}`;try{A.fetchPolyfilled(i,{method:`POST`,headers:n({"Content-Type":`application/json`},r),body:JSON.stringify(t),keepalive:!0}).catch(t=>{this.params.error$.next({id:`OneStat:ApiTransport:sendJsonBeacon`,category:j.ErrorCategory.NETWORK,message:`Keepalive request failed`,thrown:t,data:{path:e}})})}catch(t){this.params.error$.next({id:`OneStat:ApiTransport:sendJsonBeacon`,category:j.ErrorCategory.NETWORK,message:`Failed to initiate keepalive request`,thrown:t,data:{path:e}})}}sendJsonRequest(e,t,i){var a=this;return r(function*(){let r=j.now(),o=t=>{if(t instanceof TypeError&&ye.arrayIncludes([`Failed to fetch`,`NetworkError when attempting to fetch resource.`],t.message)){a.params.error$.next({id:`Network`,category:j.ErrorCategory.NETWORK,message:`JSON request failed`,thrown:t});return}a.params.error$.next({id:`OneStat:ApiTransport:sendJsonRequest`,category:j.ErrorCategory.NETWORK,message:`Unhandled JSON request error`,thrown:t,data:{path:e,time:j.now()-r}})},s={method:`POST`,headers:n({"Content-Type":`application/json`},i),body:JSON.stringify(t)};return a.params.config.useKeepalive&&(s.keepalive=!0),A.fetchPolyfilled(`${a.apiUvRestBaseUrl}${e}`,s).then(e=>{let t=Number(e.headers.get(`content-length`))===0,n=new Date(e.headers.get(`date`)??``).getTime(),i=j.now()-r;if(isFinite(n)&&a.timeSynchronisation?.addServerTime(n,i),!e.ok)return Promise.reject({status:e.status,statusText:e.statusText});if(!t)return e.json().catch(o)},o)})()}_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),be.objectEntries(e.queryParams).forEach(([e,n])=>t.append(e,typeof n==`string`?n:JSON.stringify(n))),t}}var Se=require(`@vkontakte/videoplayer-shared`),Ce=require(`@vkontakte/videoplayer-shared`),M=require(`@vkontakte/videoplayer-shared`),N=e=>t=>t.timestamp+e>=M.now();class we{constructor(e){t(this,`params`,void 0),t(this,`error$`,void 0),t(this,`userSalt`,void 0),t(this,`isPaused`,!1),t(this,`loggerDebugLog`,void 0),t(this,`queues`,[]),t(this,`isUrgent`,e=>{let{operation:t}=e;return Se.arrayIncludes([`action_play`,`action_play_interactive`,`watch_coverage_record`,`watch_coverage_live`,`action_stop`,`close_at_empty_buffer`],t)}),this.params=e,this.error$=e.error$,this.userSalt=e.userSalt,this.loggerDebugLog=e.debugLogger.createComponentLog(`stat logger`);for(let t of e.apis)this.queues.push(this.createQueueState(t));this.housekeepStorage()}createQueueState(e){let t=`onestat_events_${e.id}`,n=M.debounceFn(()=>this.safeFlushQueue(a),this.params.config.firstFlushTime,{maxWait:this.params.config.firstFlushTime}),r=M.safeStorage.isPersistent()?this.params.config.flushMaxWait:0,i=M.debounceFn(()=>this.safeFlushQueue(a),this.params.config.flushDebounceTime,{maxWait:r}),a={api:e,storageKey:t,unsaltedStorage:[],lastVsid:void 0,firstFlush:n,debouncedFlush:i,subscription:e.authorized$.subscribe(e=>{e&&i()})};return a}safeFlushQueue(e){try{this.flushQueue(e)}catch(t){this.error$.next({id:`LoggerError`,category:M.ErrorCategory.WTF,message:t?String(t):`Unknown logger error`,thrown:t,data:{storageKey:e.storageKey}})}}readFromStorage(e){let t=M.safeStorage.get(e);try{return t?JSON.parse(t):{}}catch{}return{}}addToStorage(e,t){if(!this.userSalt){e.unsaltedStorage.push(t);return}let r=this.readFromStorage(e.storageKey),i=(r[this.userSalt]??[]).filter(N(this.params.config.storageExpiration));M.safeStorage.set(e.storageKey,JSON.stringify(n(n({},r),{},{[this.userSalt]:[...i,t]})))}getFromStorage(e){return this.userSalt?(this.readFromStorage(e.storageKey)[this.userSalt]??[]).filter(N(this.params.config.storageExpiration)):e.unsaltedStorage}markStorageSent(e){if(!this.userSalt){e.unsaltedStorage=[];return}let t=this.readFromStorage(e.storageKey);delete t[this.userSalt],M.safeStorage.set(e.storageKey,JSON.stringify(t))}housekeepStorage(){for(let e of this.queues){let t=this.readFromStorage(e.storageKey);for(let[n,r]of Ce.objectEntries(t)){let i=r.filter(N(this.params.config.storageExpiration));i.length?t[n]=i:delete t[n],this.loggerDebugLog({message:`${r.length} retrieved from storage, ${i.length} of them actual (${e.storageKey})`})}M.safeStorage.set(e.storageKey,JSON.stringify(t))}}log(e){for(let t of this.queues)this.addToStorage(t,e),!this.isPaused&&(this.isUrgent(e)?this.flushQueue(t):t.lastVsid===e.custom.vsid?t.debouncedFlush():t.firstFlush(),t.lastVsid=e.custom.vsid)}flush(e={wantBeacon:!1,clearStorage:!0}){for(let t of this.queues)this.flushQueue(t,e)}flushQueue(e,{wantBeacon:t,clearStorage:n}={wantBeacon:!1,clearStorage:!0}){let r=this.getFromStorage(e);r.length!==0&&(e.api.authorized$.getValue()?(t&&this.params.config.useBeacon?(this.loggerDebugLog({message:`Flushing ${r.length} events through beacon (${e.storageKey})`}),e.api.logBeacon(r)):(this.loggerDebugLog({message:`Flushing ${r.length} events (${e.storageKey})`}),e.api.logRequest(r)),n&&this.markStorageSent(e)):e.api.authorize(),e.firstFlush.cancel(),e.debouncedFlush.cancel())}pause(){this.isPaused=!0;for(let e of this.queues)e.debouncedFlush.cancel()}resume(){this.isPaused=!1;for(let e of this.queues)e.debouncedFlush()}destroy(){for(let e of this.queues)e.subscription.unsubscribe(),e.firstFlush.cancel(),e.debouncedFlush.cancel();this.queues=[]}}var P=require(`@vkontakte/videoplayer-core`),Te=require(`@vkontakte/videoplayer-shared`),Ee=e=>e&&{[P.VideoQuality.INVARIANT]:`unknown`,[P.VideoQuality.Q_144P]:`mobile`,[P.VideoQuality.Q_240P]:`lowest`,[P.VideoQuality.Q_360P]:`low`,[P.VideoQuality.Q_480P]:`medium`,[P.VideoQuality.Q_576P]:`unknown`,[P.VideoQuality.Q_720P]:`high`,[P.VideoQuality.Q_1080P]:`fullhd`,[P.VideoQuality.Q_1440P]:`quadhd`,[P.VideoQuality.Q_2160P]:`ultrahd`,[P.VideoQuality.Q_4320P]:`unknown`}[e],De=e=>e&&{[P.HttpConnectionType.HTTP1]:`http1`,[P.HttpConnectionType.HTTP2]:`http2`,[P.HttpConnectionType.QUIC]:`http3`}[e],Oe=e=>{if(e!==void 0)switch(e){case P.VideoFormat.MPEG:return`mp4`;case P.VideoFormat.DASH:case P.VideoFormat.DASH_LIVE:case P.VideoFormat.DASH_STREAMS:return`dash`;case P.VideoFormat.DASH_SEP:return`dash_sep`;case P.VideoFormat.DASH_ONDEMAND:return`ondemand_dash`;case P.VideoFormat.DASH_WEBM:case P.VideoFormat.DASH_LIVE_WEBM:return`webm`;case P.VideoFormat.DASH_WEBM_AV1:return`av1`;case P.VideoFormat.DASH_LIVE_CMAF:return`ondemand_dash_live`;case P.VideoFormat.HLS:case P.VideoFormat.HLS_LIVE:return`hls`;case P.VideoFormat.HLS_FMP4:return`hls_fmp4`;case P.VideoFormat.HLS_ONDEMAND:return`ondemand_hls`;case P.VideoFormat.HLS_LIVE_CMAF:return`ondemand_hls_live`;case P.VideoFormat.WEB_RTC_LIVE:return`webrtc`;default:return Te.assertNever(e)}},ke=(e,t)=>{if(t)return`minimal`;switch(e){case void 0:case P.Surface.NONE:case P.Surface.INLINE:return;case P.Surface.FULLSCREEN:return`fullscreen`;case P.Surface.SECOND_SCREEN:return`chromecast`;case P.Surface.PIP:return`pip`;case P.Surface.INVISIBLE:return`invisible`;default:return Te.assertNever(e)}},Ae=e=>{switch(e){case`slow-2g`:return`poor`;case`2g`:return`poor`;case`3g`:return`good`;case`4g`:return`excellent`}};class je{constructor(e){t(this,`offset`,void 0),this.offset=e}getOffset(){return this.offset??0}setOffset(e){this.offset=e}now(){return Date.now()+(this.offset??0)}date(e=new Date){return e.setTime(e.getTime()+(this.offset??0)),e}addServerTime(e,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 Me=require(`@vkontakte/videoplayer-core`),F=require(`@vkontakte/videoplayer-shared`),Ne=(e,t)=>new F.Observable(n=>{let r=new F.Subscription,i=F.merge(F.fromEvent(window,`beforeunload`),e.events.willDestruct$),a=new F.ValueSubject(void 0),o;r.add(e.info.isLive$.pipe(F.filterChanged()).subscribe(t=>{o&&(o.unsubscribe(),a.next(void 0)),o=t?e.info.liveTime$.pipe(F.map(e=>e&&e/1e3)).subscribe(a):e.info.position$.subscribe(a),r.add(o)}));let{playing$:s,paused$:c,looped$:l}=e.events,u=e.events.willSeek$.pipe(F.filter(()=>e.info.playbackState$.getValue()===Me.PlaybackState.PLAYING)),d=e.events.seeked$.pipe(F.filter(()=>e.info.playbackState$.getValue()===Me.PlaybackState.PLAYING)),f=!1,p=new F.Subject;r.add(u.subscribe(()=>{f||p.next(),f=!0})),r.add(d.subscribe(()=>f=!1));let m=new F.Subject,h=new F.Subject,g=()=>t.watchCoverageExactTime?e.info.isLive$.getValue()?e.getExactLiveTime():e.getExactTime():a.getValue()??0,_=e.info.stallStartTime$.pipe(F.filterChanged(),F.filter(e=>e>0)),v=F.merge(s,d,m).pipe(F.map(()=>g())),y=F.merge(l,F.merge(c,p,i,h,_).pipe(F.map(()=>g()))),b,x=e=>{b=e},S=e=>{let t=e;F.isNullable(b)||b===t||F.isNullable(t)||(n.next({from:b,to:t}),b=void 0)},C=()=>{h.next(),m.next()};if(r.add(v.subscribe(x)),r.add(y.subscribe(S)),t.forceInterval&&isFinite(t.forceInterval))if(t.watchCoverageTimeoutFix){let e,n=()=>{e!==void 0&&(window.clearTimeout(e),e=void 0)};r.add(v.subscribe(()=>{n(),e=window.setTimeout(C,t.forceInterval)})),r.add(y.subscribe(()=>n())),r.add(()=>n())}else{let e=0;r.add(v.subscribe(()=>e=window.setTimeout(C,t.forceInterval))),r.add(y.subscribe(()=>window.clearTimeout(e)))}return r}),I=require(`@vkontakte/videoplayer-core`),L=require(`@vkontakte/videoplayer-shared`),Pe=(e,t,n)=>{let r=new L.Subject,i=r.pipe(L.debounce(0),L.filterChanged()),a=!1,o=!1,s=!1;return t(e.inPiP$,e=>{a=e,r.next(e?I.Surface.PIP:o?I.Surface.FULLSCREEN:s?I.Surface.INLINE:void 0)}),t(e.inFullscreen$,e=>{o=e,r.next(e?I.Surface.FULLSCREEN:a?I.Surface.PIP:s?I.Surface.INLINE:void 0)}),n&&t(n.info.surface$,e=>{switch(e){case I.Surface.SECOND_SCREEN:case I.Surface.NONE:case I.Surface.INLINE:!o&&!a&&(e===I.Surface.INLINE&&(s=!0),r.next(e));break}}),{surface$:i}},Fe=`_one-stat_deviceId`,Ie=(e,t)=>e&&t?`${e}_${t}`:e??t,R=()=>{let e=new T.Subscription;return{subscription:e,subscribe:(t,n)=>{t&&e.add(t.subscribe(n))}}};class Le{get vsid$(){return new T.ValueSubject(E.getVSID())}constructor(e,n){t(this,`apis`,void 0),t(this,`logger`,void 0),t(this,`config`,void 0),t(this,`subscription`,new T.Subscription),t(this,`beforeunloadSubscription`,void 0),t(this,`timeSynchronisation`,void 0),t(this,`debugLogger`,new le.Logger),t(this,`oneStatDebugLog`,this.debugLogger.createComponentLog(`onestat`)),t(this,`loopCounter`,0),t(this,`disabled`,!1),t(this,`experimental`,void 0),t(this,`isid$`,new T.ValueSubject(void 0)),t(this,`zenUid$`,new T.ValueSubject(void 0)),t(this,`statContext`,void 0),t(this,`isEmbed`,void 0),t(this,`embedParent`,void 0),t(this,`uiEvents`,void 0),t(this,`player`,void 0),t(this,`seekAction$`,new T.ValueSubject(`unknown`)),t(this,`deviceId`,void 0),this.statContext=e,this.config=se(n.config??{}),T.isNonNullable(n.apiEnv)&&(this.config.apiEnv=n.apiEnv),this.config.synchronizeTime&&(this.timeSynchronisation=new je);let r=new T.Subject;this.experimental={error$:r};let i=T.safeStorage.get(Fe);this.statContext.deviceId?this.deviceId=this.statContext.deviceId:i?this.deviceId=i:(this.deviceId=ce(),T.safeStorage.set(Fe,this.deviceId)),this.resetViewSession(),n.useIsid&&this.isid$.next(n.isid??fe()),this.zenUid$.next(n.zenUid);let a=new xe({config:this.config,error$:r,timeSynchronisation:this.timeSynchronisation}),o=[];this.config.apiForticom&&o.push(new _e({config:this.config,apiTransport:a,refreshAuthToken:n.refreshAuthToken,mobile:this.statContext.mobile??!1,deviceId:this.deviceId,error$:r,vktvVersion:n.vktvVersion})),this.config.apiUvRest&&(n.getUvRestAuthToken?o.push(new ve({config:this.config,apiTransport:a,error$:r,userId:this.statContext.userId,getAuthToken:n.getUvRestAuthToken,mobile:this.statContext.mobile??!1,vktvVersion:n.vktvVersion})):r.next({id:`OneStat:Init:MissingGetUvRestAuthToken`,category:le.ErrorCategory.WTF,message:`oldStatToUvRest enabled but getUvRestAuthToken callback not provided`})),this.apis=o,this.logger=new we({config:this.config,debugLogger:this.debugLogger,apis:this.apis,error$:r,userSalt:n.userSalt});let{isEmbed:s,topOrigin:c}=le.detectEmbed();this.isEmbed=s,this.embedParent=c?new URL(c).hostname:void 0,this.subscribe()}updateContext(e){this.statContext=n(n({},this.statContext),e)}attachTo(e){let t=new T.Subscription,n=(e,n)=>t.add(e.subscribe(n)),r,i,a,o=!1,s=!1,c=()=>{o||(o=!0,T.isNonNullable(r)&&(r={startedAt:T.now(),liveAtStall:!!this.statContext.liveEdge}))};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.willSeek$,()=>{T.isNonNullable(r)&&o&&this.logEmptyBuffer({duration:T.now()-r.startedAt,liveAtStall:r.liveAtStall}),r=void 0,s=!0}),n(e.events.seeked$,()=>{!s&&T.isNonNullable(r)&&o&&(this.logEmptyBuffer({duration:T.now()-r.startedAt,liveAtStall:r.liveAtStall}),r=void 0),s=!1;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(Ne(e,{forceInterval:this.config.watchCoverageInterval,watchCoverageTimeoutFix:this.config.watchCoverageTimeoutFix,watchCoverageExactTime:this.config.watchCoverageExactTime}),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)}),n(e.info.stallStartTime$,e=>{e>0?r={startedAt:e,liveAtStall:!!this.statContext.liveEdge}:(T.isNonNullable(r)&&o&&this.logEmptyBuffer({duration:Math.round(T.now()-r.startedAt),liveAtStall:r.liveAtStall}),r=void 0)});let l=!1;t.add(e.events.fatalError$.pipe(T.once()).subscribe(()=>l=!0)),n(e.events.willStop$,()=>{if(e.info.isBuffering$.getValue()&&o){let e=T.isNonNullable(r)?T.now()-r.startedAt:void 0;this.logCloseAtEmptyBuffer({duration:e??0,liveAtStall:r?.liveAtStall}),r=void 0}else l||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})}),n(e.events.firstBytes$,e=>{i=T.now(),this.logFirstBytes({time:e})}),n(e.events.willStart$,()=>a=T.now()),n(e.info.currentBuffer$,e=>{!o&&e&&e.end-e.start>0&&T.isNonNullable(i)&&(this.logPlayerReady({duration:T.now()-i}),c())}),n(e.events.firstFrame$,()=>{T.isNonNullable(i)&&!o&&(this.logPlayerReady({duration:T.now()-i}),c()),T.isNonNullable(a)&&this.logFirstFrame({time:T.now()-a})});let u;n(e.info.currentVideoStream$,e=>{e&&(this.updateContext({videoCodec:e.codec}),u&&e.id!==u&&this.logTrackSwitch(e),u=e.id)});let d;n(e.info.currentAudioStream$,e=>{e&&(this.updateContext({audioCodec:e.codec}),d&&e.id!==d&&this.logTrackSwitch(e),d=e.id)}),n(e.info.atLiveEdge$,e=>this.updateContext({liveEdge:e})),n(T.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=Ee(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:Oe(e)})),n(e.info.currentPlaybackRate$,e=>this.updateContext({rate:e})),n(e.info.is3DVideo$,e=>this.updateContext({is3d:e}));let f;return n(e.info.hostname$,e=>{let t=f!==void 0&&f!==e;this.updateContext({cdnHostname:e,failover:t}),t&&this.logFailover(e),f=e}),n(e.info.throughputEstimation$,e=>this.updateContext({downloadSpeed:e})),n(e.info.httpConnectionType$,e=>{this.statContext.firstConnectionType||this.updateContext({firstConnectionType:De(e)}),this.updateContext({connectionType:De(e)})}),n(e.info.httpConnectionReused$,e=>{T.isNullable(this.statContext.firstConnectionReused)&&this.updateContext({firstConnectionReused:e}),this.updateContext({connectionReused:e})}),n(e.info.surface$,e=>{this.uiEvents||this.updateContext({mode:ke(e,this.statContext.isPreviewPlayerView)})}),n(T.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}=R();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}=Pe(this.uiEvents,n,this.player);return n(r,e=>{this.updateContext({mode:ke(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}=R();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}=R();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 Promise.all(this.apis.map(t=>t.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.apis.forEach(e=>e.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)},T.isNonNullable(e.liveAtStall)?{live:e.liveAtStall?1:void 0}:{})}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=T.getWindow().navigator.connection;e&&`onchange`in e&&`effectiveType`in e&&this.subscription.add(T.merge(T.fromEvent(e,`change`),T.observableFrom([`init`])).subscribe(()=>this.updateContext({network:Ae(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=T.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))},T.isNonNullable(e.liveAtStall)?{live:e.liveAtStall?1:void 0}:{})}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(g.arrayIncludes(this.config.disabledOperations,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:r},i={}){let a=this.timeSynchronisation?.now()??T.now(),o=this.vsid$.getValue();T.assertNonNullable(o);let s=this.isid$.getValue(),c=e===`empty_buffer`||e===`close_at_empty_buffer`?this.statContext.connectionType:this.statContext.firstConnectionType,l=this.statContext.firstConnectionReused,u,d;if(this.isEmbed||this.statContext.place===`embed`){u=this.embedParent;let e=[...new URLSearchParams(location.search).entries()].filter(([e,t])=>g.arrayIncludes(this.config.embedUrlParams,e));d=new URLSearchParams(e).toString()}else if(this.statContext.place===`direct`){let e=this.statContext.refDomain||document.referrer;u=e&&_.urlCanParsePolyfilled(URL,e)?new URL(e).hostname:e,d=location.href.substring(0,1024)}let f=n({vsid:o,isid:s,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:c,connection_reused:l===!0?1:l===!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:u,direct_url:d,rate:this.statContext.rate===1||T.isNullable(this.statContext.rate)?void 0:this.statContext.rate.toFixed(2),view_360:this.statContext.is3d?1:void 0,codec_info:Ie(this.statContext.videoCodec,this.statContext.audioCodec),aid:this.statContext.albumId,vk_playlist_id:this.statContext.vkPlaylistId},i);for(let e of this.config.disabledCustomFields)delete f[e];return{operation:e,type:1,time:r,network:this.statContext.network,timestamp:a,custom:f}}}var Re={};m(Re,{VERSION:()=>O,ThinOneStat:()=>Ft,ActionSeekType:()=>Ue});var ze=require(`@vkontakte/videoplayer-shared`),Be=require(`@vkontakte/videoplayer-shared`),z=require(`@vkontakte/videoplayer-shared`),B=require(`@vkontakte/videoplayer-core`),Ve=require(`@vkontakte/videoplayer-shared`),He;(e=>{e.AUTO=`auto`,e.AUTO_POOR=`auto_poor`,e.AUTO_RICH=`auto_rich`})(He||={});var Ue;(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`})(Ue||={});var We=`CIOPGQJGDIHBABABA`,V={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:``},Ge={apiKey:We,apiEnv:`okcdn`,apiBaseUrl:null,apiUvRestBaseUrl:`https://uvapi.okcdn.ru`,apiForticom:!0,apiUvRest:!1,requestRetryCount:3,useVsid64:!1,flushFirstTime:5e3,flushDebounceTime:1e4,flushMaxWait:6e4,flushRetryFirstDelay:3e3,flushRetryMaxDelay:18e5,storageExpiration:2160*60*1e3,clearStorageAtUnload:!1,disabledEvents:[],disabledParams:[],synchronizeTime:!0,useBeacon:!1,alwaysSendDesktop:!1,watchCoverageHeartbeatInterval:3e4,watchCoverageExactTime:!1,watchedNDefaultTargetDuration:1e3,telemetryInterval:3e4,downloadBytesMaxTime:3e4},Ke=e=>Ve.fillWithDefault(e,Ge),qe=require(`@vkontakte/videoplayer-shared`),Je=require(`@vkontakte/videoplayer-shared`),H=require(`@vkontakte/videoplayer-shared`);function Ye(e){let t=Error(`HTTP ${e.status}: ${e.statusText}`);return t.status=e.status,t.statusText=e.statusText,t.response=e,t}function Xe(){let e=Error(`Request timeout`);return e.isTimeout=!0,e}function Ze(e){let t=Error(e.error_msg);return t.errorData=e,t}function Qe(e){if(!(!e||typeof e!=`object`)){if(`errorData`in e)return e.errorData?.error_code;if(`error_code`in e){let t=e.error_code;return typeof t==`number`?t:void 0}}}var $e=t=>{let{application:n,platform:r,product:a}=t;return i(t,e)};class et{constructor(e){t(this,`id`,`forticom`),t(this,`authorized$`,void 0),t(this,`params`,void 0),t(this,`authToken`,void 0),t(this,`sessionKey`,void 0),t(this,`authorizePromise`,void 0),t(this,`refreshAuthTokenPromise`,void 0),t(this,`isDestroyed`,!1),this.params=e,this.authorized$=new H.ValueSubject(!1)}authorize(e){var t=this;return r(function*(){return t.authToken=e??(yield t.refreshAuthToken()),t.doAuthorize()})()}logBeacon(e){if(!e.length)return;let t=this.createLogParams(e),n=this.sessionKey;n&&(this.params.apiTransport.sendBeacon(`log.logUvStat`,t,n)||this.logRequest(e).catch(()=>{}))}logRequest(e){var t=this;return r(function*(){if(!e.length)return;let n=`log.logUvStat`,r=t.createLogParams(e),i={};try{let e=yield t.getValidSessionKey();if(!e){t.params.errors$.next({id:`ThinOneStat:Api:LogRequestNoSession`,category:H.ErrorCategory.NETWORK,message:`No session key available for log request`});return}yield t.params.apiTransport.sendRequest(n,r,e,i)}catch(e){(yield t.handleLogRequestError(e,n,r))&&(yield t.retryLogRequestAfterSessionRecovery(n,r))}})()}getValidSessionKey(){var e=this;return r(function*(){return e.sessionKey?e.sessionKey:e.doAuthorize()})()}handleLogRequestError(e,t,n){var i=this;return r(function*(){let r=Qe(e);return r===void 0?(i.params.errors$.next({id:`ThinOneStat:Api:LogRequestUnknown`,category:H.ErrorCategory.NETWORK,message:`Unknown ${t} error`,thrown:e,data:{params:n}}),!1):i.isSessionExpiredError(r)?(i.params.errors$.next({id:`ThinOneStat:Api:LogRequestSessionError#${r}`,category:H.ErrorCategory.EXTERNAL_API,message:`Session error: ${r}`,data:{error:e,code:r}}),i.authorized$.next(!1),i.sessionKey=void 0,(yield i.doAuthorize())!==void 0):r===401?(i.params.errors$.next({id:`ThinOneStat:Api:LogRequestAuthLogin#${r}`,category:H.ErrorCategory.EXTERNAL_API,message:`Auth token expired`,data:{error:e,code:r}}),i.authorized$.next(!1),i.authToken=yield i.refreshAuthToken(),i.sessionKey=void 0,(yield i.doAuthorize())!==void 0):(i.params.errors$.next({id:`ThinOneStat:Api:LogRequest#${r}`,category:H.ErrorCategory.EXTERNAL_API,message:`${t} error`,data:{error:e,code:r,params:n}}),!1)})()}retryLogRequestAfterSessionRecovery(e,t){var n=this;return r(function*(){let r=n.sessionKey;if(!r){n.params.errors$.next({id:`ThinOneStat:Api:LogRequestRetryFailed`,category:H.ErrorCategory.NETWORK,message:`Cannot retry log request: no session key after recovery`});return}try{yield n.params.apiTransport.sendRequest(e,t,r)}catch(e){let t=Qe(e);n.params.errors$.next({id:`ThinOneStat:Api:LogRequestRetryFailed#${t??`unknown`}`,category:H.ErrorCategory.EXTERNAL_API,message:`Log request failed after session recovery`,thrown:e,data:{originalError:e,retryCode:t}})}})()}isSessionExpiredError(e){return!!e&&qe.arrayIncludes([102,103,104],e)}doAuthorize(e=1){var t=this;return r(function*(){if(!t.isDestroyed)return t.authorizePromise?t.authorizePromise:(t.sessionKey=void 0,t.authorized$.next(!1),t.authorizePromise=Je.promiseFinally(t.executeAuthorize(e),()=>{t.authorizePromise=void 0,t.isDestroyed||t.authorized$.next(t.sessionKey!==void 0)}),t.authorizePromise)})()}executeAuthorize(e){var t=this;return r(function*(){let n=t.buildAuthParams();try{let e=yield t.params.apiTransport.sendRequest(`auth.anonymLogin`,n);if(t.isDestroyed)return;if(!e?.session_key){t.params.errors$.next({id:`ThinOneStat:Api:AuthorizeFailed`,category:H.ErrorCategory.EXTERNAL_API,message:`No session key in response`,data:e});return}return t.sessionKey=e.session_key,t.sessionKey}catch(n){if(t.isDestroyed)return;let r=Qe(n);if(r===401&&t.params.refreshAuthToken){if(t.params.errors$.next({id:`ThinOneStat:Api:AuthorizeAuthLogin`,category:H.ErrorCategory.EXTERNAL_API,message:`Auth token expired during authorization`,data:{error:n,code:r,attempt:e}}),e>=2){t.params.errors$.next({id:`ThinOneStat:Api:AuthorizeMaxAttemptsReached`,category:H.ErrorCategory.EXTERNAL_API,message:`Authorization failed after ${e} attempts`,data:{error:n,code:r}});return}return t.authToken=yield t.refreshAuthToken(),t.doAuthorize(e+1)}r?t.params.errors$.next({id:`ThinOneStat:Api:Authorize#${r}`,category:H.ErrorCategory.EXTERNAL_API,message:`Authorize error`,data:{error:n,code:r}}):t.params.errors$.next({id:`ThinOneStat:Api:AuthorizeUnknown`,category:H.ErrorCategory.NETWORK,message:`Authorize error`,thrown:n});return}})()}buildAuthParams(){let e={session_data:{version:2,device_id:this.params.deviceId,client_version:this.getClientVersion(),client_type:`SDK_JS`}};return this.authToken!==void 0&&(e.session_data.auth_token=this.authToken,e.session_data.version=3),e}getClientVersion(){return O}refreshAuthToken(){var e=this;return r(function*(){if(e.params.refreshAuthToken)return e.refreshAuthTokenPromise||=Je.promiseFinally(e.params.refreshAuthToken().catch(t=>{throw e.params.errors$.next({id:`ThinOneStat:Api:RefreshAuthTokenFailed`,category:H.ErrorCategory.NETWORK,message:`Failed to refresh auth token`,thrown:t}),t}),()=>{e.refreshAuthTokenPromise=void 0}),e.refreshAuthTokenPromise})()}createLogParams(e){let t=e[0],n=t.application??`@vkontakte/videoplayer-statistics:${this.getClientVersion()}`;return this.params.vktvVersion&&(n=this.params.vktvVersion),{collector:`ok.mobile.apps.video`,uv_stat_data:JSON.stringify({application:n,platform:t.platform,product:t.product,events:e.map($e)})}}destroy(){this.isDestroyed=!0,this.authorizePromise=void 0,this.refreshAuthTokenPromise=void 0,this.sessionKey=void 0,this.authorized$.next(!1)}}class tt{constructor(e){t(this,`id`,`uvrest`),t(this,`authorized$`,void 0),t(this,`params`,void 0),t(this,`statToken`,void 0),t(this,`authorizePromise`,void 0),t(this,`isDestroyed`,!1),this.params=e,this.authorized$=new H.ValueSubject(!1)}authorize(e){var t=this;return r(function*(){if(!t.isDestroyed)return e?(t.statToken=e,t.authorized$.next(!0),e):t.authorizePromise?t.authorizePromise:(t.authorized$.next(!1),t.authorizePromise=Je.promiseFinally(t.executeAuthorize(),()=>{t.authorizePromise=void 0,t.isDestroyed||t.authorized$.next(t.statToken!==void 0)}),t.authorizePromise)})()}logRequest(e){var t=this;return r(function*(){if(!e.length)return;let n=t.buildBody(e);try{let e=yield t.getValidToken();if(!e){t.params.errors$.next({id:`ThinOneStat:UvRestApi:LogRequestNoToken`,category:H.ErrorCategory.NETWORK,message:`No stat token available for log request`});return}yield t.params.apiTransport.sendJsonRequest(`/uv/stat/logUvStat`,n,{Authorization:`Bearer ${e}`})}catch(e){(yield t.handleLogRequestError(e))&&(yield t.retryLogRequestAfterRecovery(n))}})()}logBeacon(e){if(!e.length)return;let t=this.statToken;if(!t)return;let n=this.buildBody(e);this.params.apiTransport.sendJsonBeacon(`/uv/stat/logUvStat`,n,{Authorization:`Bearer ${t}`})}destroy(){this.isDestroyed=!0,this.authorizePromise=void 0,this.statToken=void 0,this.authorized$.next(!1)}getValidToken(){var e=this;return r(function*(){return e.statToken?e.statToken:e.authorize()})()}executeAuthorize(){var e=this;return r(function*(){try{let t=yield e.params.getAuthToken();if(e.isDestroyed)return;if(!t){e.params.errors$.next({id:`ThinOneStat:UvRestApi:NoToken`,category:H.ErrorCategory.EXTERNAL_API,message:`getAuthToken returned no token`});return}return e.statToken=t,e.statToken}catch(t){if(e.isDestroyed)return;e.params.errors$.next({id:`ThinOneStat:UvRestApi:AuthorizeFailed`,category:H.ErrorCategory.NETWORK,message:`Failed to get stat token`,thrown:t});return}})()}handleLogRequestError(e){var t=this;return r(function*(){let n=e?.status;return n===401?(t.params.errors$.next({id:`ThinOneStat:UvRestApi:TokenExpired`,category:H.ErrorCategory.EXTERNAL_API,message:`Stat token expired (401), refreshing`,thrown:e}),t.authorized$.next(!1),t.statToken=void 0,(yield t.authorize())!==void 0):(t.params.errors$.next({id:`ThinOneStat:UvRestApi:LogRequestFailed#${n??`unknown`}`,category:H.ErrorCategory.EXTERNAL_API,message:`Log request failed with status ${n}`,thrown:e}),!1)})()}retryLogRequestAfterRecovery(e){var t=this;return r(function*(){let n=t.statToken;if(!n){t.params.errors$.next({id:`ThinOneStat:UvRestApi:RetryNoToken`,category:H.ErrorCategory.NETWORK,message:`Cannot retry log request: no token after recovery`});return}try{yield t.params.apiTransport.sendJsonRequest(`/uv/stat/logUvStat`,e,{Authorization:`Bearer ${n}`})}catch(e){t.params.errors$.next({id:`ThinOneStat:UvRestApi:RetryFailed`,category:H.ErrorCategory.EXTERNAL_API,message:`Log request failed after token refresh`,thrown:e})}})()}buildBody(e){let t=e[0],n=t.application;return this.params.vktvVersion&&(n=this.params.vktvVersion),[{product:t.product,platform:t.platform,application:n,user_id:this.params.userId,events:e.map($e)}]}}var nt=require(`@vkontakte/videoplayer-shared`),rt=require(`@vkontakte/videoplayer-shared`),U=require(`@vkontakte/videoplayer-shared`),it=require(`@vkontakte/videoplayer-shared`),W=require(`@vkontakte/videoplayer-shared`);class at{constructor(e){t(this,`params`,void 0),t(this,`apiKey`,void 0),t(this,`apiBaseUrl`,void 0),t(this,`apiUvRestBaseUrl`,void 0),t(this,`apiEnv`,void 0),t(this,`resolvedApiBaseUrl`,null),t(this,`resolveApiBaseUrlPromise`,null),t(this,`timeSynchronisation`,void 0),t(this,`fetchTimeout`,3e4),t(this,`maxTotalRequestTime`,6e4),t(this,`retryConfig`,void 0),this.params=e,this.apiKey=e.config.apiKey,this.apiEnv=e.config.apiEnv,this.apiBaseUrl=e.config.apiBaseUrl??V[this.apiEnv],this.apiUvRestBaseUrl=e.config.apiUvRestBaseUrl,this.timeSynchronisation=e.timeSynchronisation,this.retryConfig={maxAttempts:e.config.requestRetryCount??3,baseDelay:3e3,maxDelay:3e4,retryableErrors:[`Failed to fetch`,`NetworkError when attempting to fetch resource.`,`Request timeout`,`Network request failed`],retryableStatuses:[408,429,500,502,503,504]}}sendBeacon(e,t,n){if(!W.getWindow().Blob||!W.getWindow().navigator.sendBeacon)return!1;let r=this.resolvedApiBaseUrl??this.apiBaseUrl,i=this.prepareQueryParams({method:e,queryParams:t,sessionKey:n}),a=W.getWindow().Blob,o=new a([i.toString()],{type:`application/x-www-form-urlencoded`});try{return W.getWindow().navigator.sendBeacon(`${r}/fb.do`,o)}catch(n){this.params.errors$.next({id:`ThinOneStat:ApiTransport:sendBeacon`,category:W.ErrorCategory.NETWORK,message:`Unhandled beacon error`,thrown:n,data:{method:e,params:t}})}return!1}sendRequest(e,t,n,i){var a=this;return r(function*(){return a.sendRequestWithRetry(e,t,n,i)})()}sendRequestWithRetry(e,t,n,i,a=1,o){var s=this;return r(function*(){let r=W.now(),c=o??r+s.maxTotalRequestTime;if(W.now()>=c){let i=Error(`Request deadline exceeded`);throw s.handleFinalError(e,t,n,r,i,a),i}try{return yield s.executeRequest(e,t,n,i,r,a,c)}catch(o){if(s.shouldRetry(o,a)&&W.now()<c){let l=s.getRetryDelay(o,a);if(W.now()+l>=c)throw s.handleFinalError(e,t,n,r,o,a),o;return s.logRetryAttempt(e,a,o,l),yield s.sleep(l),s.sendRequestWithRetry(e,t,n,i,a+1,c)}throw s.handleFinalError(e,t,n,r,o,a),o}})()}executeRequest(e,t,i,a,o,s,c){var l=this;return r(function*(){let r=o??W.now(),u=yield l.resolveApiBaseUrl(),d=c===void 0?l.fetchTimeout:c-W.now();if(d<=0)throw Xe();try{let o=yield l.fetchWithTimeout(`${u}/fb.do`,{method:`post`,headers:n({"Content-type":`application/x-www-form-urlencoded`},a),body:l.prepareQueryParams({method:e,queryParams:t,sessionKey:i})},Math.min(l.fetchTimeout,d));return yield l.processResponse(o,r)}catch(t){throw t instanceof Error&&(t.context={method:e,attempt:s,url:`${u}/fb.do`}),t}})()}sendJsonRequest(e,t,n){var i=this;return r(function*(){return i.sendJsonRequestWithRetry(e,t,n)})()}sendJsonBeacon(e,t,r){let i=`${this.apiUvRestBaseUrl}${e}`;try{nt.fetchPolyfilled(i,{method:`POST`,headers:n({"Content-Type":`application/json`},r),body:JSON.stringify(t),keepalive:!0}).catch(t=>{this.params.errors$.next({id:`ThinOneStat:ApiTransport:sendJsonBeacon`,category:W.ErrorCategory.NETWORK,message:`Keepalive request failed`,thrown:t,data:{path:e}})})}catch(t){this.params.errors$.next({id:`ThinOneStat:ApiTransport:sendJsonBeacon`,category:W.ErrorCategory.NETWORK,message:`Failed to initiate keepalive request`,thrown:t,data:{path:e}})}}sendJsonRequestWithRetry(e,t,n,i=1,a){var o=this;return r(function*(){let r=W.now(),s=a??r+o.maxTotalRequestTime;if(W.now()>=s){let t=Error(`Request deadline exceeded`);throw o.handleJsonFinalError(e,r,t,i),t}try{return yield o.executeJsonRequest(e,t,n,r,i,s)}catch(a){if(o.shouldRetry(a,i)&&W.now()<s){let c=o.getRetryDelay(a,i);if(W.now()+c>=s)throw o.handleJsonFinalError(e,r,a,i),a;return o.logRetryAttempt(e,i,a,c),yield o.sleep(c),o.sendJsonRequestWithRetry(e,t,n,i+1,s)}throw o.handleJsonFinalError(e,r,a,i),a}})()}executeJsonRequest(e,t,i,a,o,s){var c=this;return r(function*(){let r=a??W.now(),l=s===void 0?c.fetchTimeout:s-W.now();if(l<=0)throw Xe();let u=`${c.apiUvRestBaseUrl}${e}`;try{let e=yield c.fetchWithTimeout(u,{method:`POST`,headers:n({"Content-Type":`application/json`},i),body:JSON.stringify(t)},Math.min(c.fetchTimeout,l));return yield c.processResponse(e,r)}catch(t){throw t instanceof Error&&(t.context={method:e,attempt:o,url:u}),t}})()}fetchWithTimeout(e,t){return r(function*(e,t,r=this.fetchTimeout){let i=new rt.AbortControllerPolyfilled,a=W.getWindow().setTimeout(()=>i.abort(),r);try{let r=yield nt.fetchPolyfilled(e,n(n({},t),{},{signal:i.signal}));return W.getWindow().clearTimeout(a),r}catch(e){throw W.getWindow().clearTimeout(a),W.isAbortError(e)?Xe():e}}).apply(this,arguments)}processResponse(e,t){var n=this;return r(function*(){if(!e.ok){let t=Ye(e),r=n.parseRetryAfter(e);throw r!==void 0&&(t.retryAfter=r),t}let r=new Date(e.headers.get(`date`)??``).getTime(),i=W.now()-t;isFinite(r)&&n.timeSynchronisation?.addServerTime(r,i);let a=e.headers.get(`content-length`);if(a!==null&&Number(a)===0)return{};let o=yield e.json();if(o&&typeof o==`object`&&`error_msg`in o)throw Ze(o);return o})()}shouldRetry(e,t){if(t>=this.retryConfig.maxAttempts||!(e instanceof Error))return!1;let n=e;return!!(n.isTimeout||n.status&&U.arrayIncludes(this.retryConfig.retryableStatuses,n.status)||U.arrayIncludes(this.retryConfig.retryableErrors,e.message)||U.arrayIncludes(e.message,`network`)||U.arrayIncludes(e.message,`timeout`)||U.arrayIncludes(e.message,`connection`))}logRetryAttempt(e,t,n,r){let i=n instanceof Error?n.message:String(n);this.params.errors$.next({id:`ThinOneStat:ApiTransport:retry`,category:W.ErrorCategory.NETWORK,message:`Retrying request (attempt ${t}/${this.retryConfig.maxAttempts}) after ${Math.round(r)}ms`,thrown:n,data:{method:e,attempt:t,delay:r,errorMessage:i}})}handleFinalError(e,t,n,r,i,a){let o=W.ErrorCategory.NETWORK;this.params.errors$.next({id:`ThinOneStat:ApiTransport:sendRequest`,category:o,message:i instanceof Error?i.message:`Request failed after retries`,thrown:i,data:{method:e,params:t,sessionKey:n,time:W.now()-r,maxAttempts:this.retryConfig.maxAttempts,attempts:a}})}handleJsonFinalError(e,t,n,r){this.params.errors$.next({id:`ThinOneStat:ApiTransport:sendJsonRequest`,category:W.ErrorCategory.NETWORK,message:n instanceof Error?n.message:`JSON request failed after retries`,thrown:n,data:{path:e,time:W.now()-t,maxAttempts:this.retryConfig.maxAttempts,attempts:r}})}sleep(e){return new Promise(t=>W.getWindow().setTimeout(t,e))}resolveApiBaseUrl(){return this.apiEnv===`auto`?(this.resolveApiBaseUrlPromise||=this.fetchApiBaseUrl().then(e=>(e===V.vk_alias&&(this.resolveApiBaseUrlPromise=null),e)),this.resolveApiBaseUrlPromise):Promise.resolve(this.apiBaseUrl)}fetchApiBaseUrl(){var e=this;return r(function*(){try{var t;let n=atob(`aHR0cHM6Ly9kbnMuZ29vZ2xlL3Jlc29sdmU/bmFtZT12aWRlby5fZW5kcG9pbnQub2sucnUmdHlwZT1UWFQ=`),r=yield(yield e.fetchWithTimeout(n,{method:`GET`,mode:`cors`,cache:`no-cache`},5e3)).json(),i=r==null||(t=r.Answer[0])==null?void 0:t.data;if(!i)throw Error(`Wrong DNS response`);return e.resolvedApiBaseUrl=i,i}catch(t){return e.params.errors$.next({id:`ThinOneStat:ApiTransport:resolveApiBaseUrl`,category:W.ErrorCategory.NETWORK,message:`Unhandled resolve api base url error`,thrown:t}),V.vk_alias}})()}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),it.objectEntries(e.queryParams).forEach(([e,n])=>t.append(e,typeof n==`string`?n:JSON.stringify(n))),t}parseRetryAfter(e){let t=e.headers.get(`Retry-After`);if(!t)return;let n=Number(t);if(!isNaN(n)&&n>=0)return n*1e3;let r=new Date(t).getTime();if(!isNaN(r))return Math.max(0,r-Date.now())}getRetryDelay(e,t){let n=e;return n?.retryAfter!==void 0&&n.retryAfter>0?n.retryAfter:W.getExponentialDelay(t,{start:this.retryConfig.baseDelay,max:this.retryConfig.maxDelay,factor:2,random:.2})}}var ot=require(`@vkontakte/videoplayer-shared`),st=require(`@vkontakte/videoplayer-shared`),ct=require(`@vkontakte/videoplayer-shared`),lt=require(`@vkontakte/videoplayer-shared`),ut=require(`@vkontakte/videoplayer-shared`),G=require(`@vkontakte/videoplayer-shared`),dt=e=>t=>(t.client_time??G.now())+e>=G.now();class ft{constructor(e){t(this,`params`,void 0),t(this,`subscription`,void 0),t(this,`userSalt`,void 0),t(this,`unsaltedStorage`,[]),t(this,`lastVsid`,void 0),t(this,`isPaused`,!1),t(this,`firstFlush`,void 0),t(this,`debouncedFlush`,void 0),t(this,`flushRetryCount`,0),t(this,`retryFlushTimerId`,void 0),t(this,`debugLog`,void 0),t(this,`flushPromise`,null),t(this,`flushSnapshotLength`,0),t(this,`onlineListener`,void 0),t(this,`urgentEvents`,[`watch_coverage`,`watch_coverage_live`,`watched_n`,`playback_started`]),t(this,`STORAGE_MAX_ATTEMPTS`,3),t(this,`isUrgent`,e=>ct.arrayIncludes(this.urgentEvents,e.event_name)),this.params=e,this.userSalt=e.userSalt,this.debugLog=e.debugLogger.createComponentLog(`batch-queue:${e.storageKey}`),this.firstFlush=G.debounceFn(()=>this.safeFlush(),this.params.config.flushFirstTime,{maxWait:this.params.config.flushFirstTime});let n=G.safeStorage.isPersistent()?this.params.config.flushMaxWait:0;this.debouncedFlush=G.debounceFn(()=>this.safeFlush(),this.params.config.flushDebounceTime,{maxWait:n}),this.subscription=this.params.canSend$.subscribe(e=>{e&&(this.debugLog({message:`Can send, triggering flush`}),this.debouncedFlush())}),this.onlineListener=()=>{this.debugLog({message:`Network online, triggering flush`}),this.cancelRetry(),this.safeFlush()},G.getWindow().addEventListener(`online`,this.onlineListener),this.housekeepStorage()}scheduleRetry(){this.retryFlushTimerId!==void 0&&G.getWindow().clearTimeout(this.retryFlushTimerId);let e=this.params.config.flushRetryFirstDelay,t=this.params.config.flushRetryMaxDelay,n=Math.min(e*2**this.flushRetryCount,t);this.flushRetryCount++,this.debugLog({message:`Scheduling flush retry #${this.flushRetryCount} in ${n}ms`}),this.retryFlushTimerId=G.getWindow().setTimeout(()=>{this.retryFlushTimerId=void 0,this.safeFlush()},n)}cancelRetry(){this.retryFlushTimerId!==void 0&&(G.getWindow().clearTimeout(this.retryFlushTimerId),this.retryFlushTimerId=void 0),this.flushRetryCount=0}safeFlush(){if(this.flushPromise){this.debugLog({message:`Flush already in progress, skipping`});return}this.flushPromise=lt.promiseFinally(this.flush(),()=>{this.flushPromise=null})}isStorageAvailable(){var e;let t=(e=G.safeStorage).isPersistent?.call(e)??!1;return t||this.debugLog({message:`Storage not available`}),t}readFromStorage(){if(!this.isStorageAvailable())return{};try{let e=G.safeStorage.get(this.params.storageKey),t=e?JSON.parse(e):{};return this.debugLog({message:`Read ${Object.keys(t).length} users from storage`}),t}catch(e){return this.params.errors$.next({id:`ThinOneStat:BatchQueue:ReadStorageError`,category:G.ErrorCategory.WTF,message:`Failed to read from storage`,thrown:e,data:{storageKey:this.params.storageKey}}),this.debugLog({message:`Failed to read from storage`}),{}}}writeToStorage(e){if(!this.isStorageAvailable())return!1;try{return G.safeStorage.set(this.params.storageKey,JSON.stringify(e)),this.debugLog({message:`Written ${Object.keys(e).length} users to storage`}),!0}catch(e){return this.params.errors$.next({id:`ThinOneStat:BatchQueue:WriteStorageError`,category:G.ErrorCategory.WTF,message:`Failed to write to storage`,thrown:e,data:{storageKey:this.params.storageKey}}),this.debugLog({message:`Failed to write to storage`}),!1}}addToStorage(e){if(!this.userSalt){this.unsaltedStorage.push(e),this.debugLog({message:`Added item to unsalted storage, total: ${this.unsaltedStorage.length}`});return}for(let t=0;t<this.STORAGE_MAX_ATTEMPTS;t++)try{let t=this.readFromStorage(),r=t[this.userSalt]??[];if(this.debugLog({message:`Adding item to storage for user ${this.userSalt}`}),this.writeToStorage(n(n({},t),{},{[this.userSalt]:[...r,e]})))return}catch(n){t===this.STORAGE_MAX_ATTEMPTS-1&&(this.params.errors$.next({id:`ThinOneStat:BatchQueue:AddToStorageFailed`,category:G.ErrorCategory.WTF,message:`Failed to add item to storage after retries`,thrown:n,data:{item:e,attempt:t,storageKey:this.params.storageKey}}),this.debugLog({message:`Failed to add item to storage after retries`}))}}getFromStorage(){if(!this.userSalt)return this.debugLog({message:`Retrieved ${this.unsaltedStorage.length} items from unsalted storage`}),this.flushSnapshotLength=this.unsaltedStorage.length,this.unsaltedStorage.slice();let e=this.readFromStorage(),t=e[this.userSalt]??[],r=t.filter(dt(this.params.config.storageExpiration));if(this.debugLog({message:`Retrieved from storage for user ${this.userSalt}`}),r.length!==t.length){let i=t.length-r.length;this.params.errors$.next({id:`ThinOneStat:BatchQueue:DropExpiredEvents`,category:G.ErrorCategory.WTF,message:`Dropped ${i} expired events from storage`,data:{droppedCount:i,expiration:this.params.config.storageExpiration,storageKey:this.params.storageKey}}),this.debugLog({message:`Cleaning ${i} expired items from storage`});let a=n({},e);r.length?a[this.userSalt]=r:delete a[this.userSalt],this.writeToStorage(a)}return this.flushSnapshotLength=r.length,r}markStorageSent(){if(!this.userSalt){let e=this.unsaltedStorage.splice(0,this.flushSnapshotLength);this.debugLog({message:`Cleared unsalted storage, removed ${e.length} items, ${this.unsaltedStorage.length} new items kept`}),this.flushSnapshotLength=0;return}let e=this.flushSnapshotLength;this.flushSnapshotLength=0;for(let t=0;t<this.STORAGE_MAX_ATTEMPTS;t++)try{let t=this.readFromStorage(),r=(t[this.userSalt]??[]).slice(e),i=n({},t);if(r.length?i[this.userSalt]=r:delete i[this.userSalt],this.writeToStorage(i)){this.debugLog({message:`Marked storage as sent for user ${this.userSalt}, removed ${e} items, ${r.length} kept`});return}}catch(e){t===this.STORAGE_MAX_ATTEMPTS-1&&(this.params.errors$.next({id:`ThinOneStat:BatchQueue:MarkStorageSentFailed`,category:G.ErrorCategory.WTF,message:`Failed to mark storage as sent after retries`,thrown:e,data:{storageKey:this.params.storageKey}}),this.debugLog({message:`Failed to mark storage as sent after retries`}))}}housekeepStorage(){if(this.isStorageAvailable())try{let e=this.readFromStorage(),t=!1,n=0;for(let[r,i]of ut.objectEntries(e)){let a=i.filter(dt(this.params.config.storageExpiration)),o=i.length-a.length;n+=o,a.length?a.length!==i.length&&(e[r]=a,t=!0):(delete e[r],t=!0),this.debugLog({message:`${i.length} retrieved from storage, ${a.length} of them actual for ${r}`})}t?(this.debugLog({message:`Housekeeping completed, removed ${n} expired items total`}),this.writeToStorage(e),n>0&&this.params.errors$.next({id:`ThinOneStat:BatchQueue:DropExpiredEvents`,category:G.ErrorCategory.WTF,message:`Dropped ${n} expired events during housekeeping`,data:{droppedCount:n,expiration:this.params.config.storageExpiration,storageKey:this.params.storageKey}})):this.debugLog({message:`Housekeeping completed, no changes needed`})}catch(e){this.params.errors$.next({id:`ThinOneStat:BatchQueue:HousekeepStorageError`,category:G.ErrorCategory.WTF,message:`Failed to housekeep storage`,thrown:e,data:{storageKey:this.params.storageKey}}),this.debugLog({message:`Failed to housekeep storage`})}}log(e){try{if(this.debugLog({message:`Logging item: ${e.event_name}`}),this.addToStorage(e),this.isPaused){this.debugLog({message:`Queue paused, skipping flush`});return}this.isUrgent(e)?(this.debugLog({message:`Urgent item, flushing immediately`}),this.safeFlush()):this.lastVsid===e.vsid?(this.debugLog({message:`Same VSID, scheduling debounced flush`}),this.debouncedFlush()):(this.debugLog({message:`VSID changed, triggering first flush`}),this.firstFlush()),this.lastVsid=e.vsid}catch(t){this.params.errors$.next({id:`ThinOneStat:BatchQueue:LogError`,category:G.ErrorCategory.WTF,message:`Failed to log item`,thrown:t,data:{item:e,storageKey:this.params.storageKey}}),this.debugLog({message:`Failed to log item`})}}flush(e={wantBeacon:!1,clearStorage:!0}){return this.flushPromise?(this.debugLog({message:`Flush already in progress, waiting`}),this.flushPromise):(this.flushPromise=lt.promiseFinally(this.flushInternal(e),()=>{this.flushPromise=null}),this.flushPromise)}flushInternal({wantBeacon:e,clearStorage:t}){var n=this;return r(function*(){n.debugLog({message:`Starting flush`});let r=n.getFromStorage();if(r.length===0){n.debugLog({message:`No items to flush`});return}let i=n.params.canSend$.getValue();if(n.debugLog({message:`Can send status: ${i}`}),!i){n.debugLog({message:`Cannot send, requesting ready state`}),n.params.requestReady();return}if(e&&n.params.config.useBeacon){n.debugLog({message:`Flushing ${r.length} events through beacon`}),n.params.sendBeacon(r),t&&n.markStorageSent(),n.firstFlush.cancel(),n.debouncedFlush.cancel();return}n.debugLog({message:`Flushing ${r.length} events`});try{yield n.params.send(r),n.debugLog({message:`Flush completed successfully`}),n.cancelRetry(),t&&n.markStorageSent(),n.firstFlush.cancel(),n.debouncedFlush.cancel()}catch(e){throw n.params.errors$.next({id:`ThinOneStat:BatchQueue:FlushRequestError`,category:G.ErrorCategory.NETWORK,message:`Failed to send events, will retry later`,thrown:e,data:{itemsCount:r.length,storageKey:n.params.storageKey}}),n.debugLog({message:`Flush failed, scheduling retry`}),n.scheduleRetry(),e}})()}pause(){this.debugLog({message:`Queue paused`}),this.isPaused=!0,this.debouncedFlush.cancel(),this.firstFlush.cancel(),this.cancelRetry()}resume(){this.debugLog({message:`Queue resumed`}),this.isPaused=!1,this.debouncedFlush()}destroy(){var e=this;return r(function*(){e.debugLog({message:`Destroying queue`}),e.flushPromise&&(e.debugLog({message:`Waiting for ongoing flush to complete`}),yield e.flushPromise),e.cancelRetry(),e.onlineListener&&=(G.getWindow().removeEventListener(`online`,e.onlineListener),void 0),e.subscription.unsubscribe(),e.firstFlush.cancel(),e.debouncedFlush.cancel(),e.flushPromise=null,e.debugLog({message:`Queue destroyed`})})()}}class pt{constructor(e){t(this,`params`,void 0),t(this,`queues`,[]),this.params=e;for(let t of e.apis)this.queues.push(this.createQueueForApi(t))}createQueueForApi(e){let t=this.getStorageKeyForApi(e.id);return new ft({config:this.params.config,storageKey:t,debugLogger:this.params.debugLogger,errors$:this.params.errors$,userSalt:this.params.userSalt,send:t=>e.logRequest(t),sendBeacon:t=>e.logBeacon(t),canSend$:e.authorized$,requestReady:()=>{e.authorize().catch(e=>{this.params.errors$.next({id:`ThinOneStat:Logger:RequestReadyFailed`,category:st.ErrorCategory.NETWORK,message:`Failed to authorize on requestReady`,thrown:e,data:{storageKey:t}})})}})}getStorageKeyForApi(e){return`thinonestat_events_${e}`}log(e){this.queues.forEach(t=>t.log(e))}flush(e){var t=this;return r(function*(){let n=yield ot.promiseAllSettled(t.queues.map(t=>t.flush(e)));if(n.length>0&&n.every(e=>e.status===`rejected`))throw n.find(e=>e.status===`rejected`).reason})()}pause(){this.queues.forEach(e=>e.pause())}resume(){this.queues.forEach(e=>e.resume())}destroy(){var e=this;return r(function*(){yield ot.promiseAllSettled(e.queues.map(e=>e.destroy())),e.queues=[]})()}}function mt(){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 ht{constructor(e){t(this,`offset`,void 0),this.offset=e}getOffset(){return this.offset??0}setOffset(e){this.offset=e}now(){return Date.now()+(this.offset??0)}date(e=new Date){return e.setTime(e.getTime()+(this.offset??0)),e}addServerTime(e,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 gt=require(`@vkontakte/videoplayer-core`),K=require(`@vkontakte/videoplayer-shared`),_t=(e,t,n)=>new K.Observable(r=>{let i=new K.Subscription,a,o=new K.ValueSubject(void 0),s;i.add(e.info.isLive$.pipe(K.filterChanged()).subscribe(t=>{s&&(s.unsubscribe(),o.next(void 0)),a=void 0,s=t?e.info.liveTime$.pipe(K.map(e=>e&&e/1e3)).subscribe(o):e.info.position$.subscribe(o),i.add(s)}));let{playing$:c,paused$:l,ended$:u,looped$:d}=e.events,f=e.events.willSeek$.pipe(K.filter(()=>e.info.playbackState$.getValue()===gt.PlaybackState.PLAYING)),p=e.events.seeked$.pipe(K.filter(()=>e.info.playbackState$.getValue()===gt.PlaybackState.PLAYING)),m=e.info.isStalled$.pipe(K.filter(e=>e)),h=!1,g=new K.Subject;i.add(f.subscribe(()=>{h||g.next(),h=!0})).add(p.subscribe(()=>h=!1));let _=K.merge(K.fromEvent(K.getWindow(),`beforeunload`),e.events.willDestruct$),v=e=>{a=e},y=e=>{let t=a;if(a=void 0,!(K.isNullable(t)||K.isNullable(e)||!isFinite(t)||!isFinite(e))){if(Math.round(e*1e3)<=Math.round(t*1e3)){a=e;return}r.next({from:t,to:e})}},b=new K.Subject,x=new K.Subject,S=()=>n.exactTime?e.info.isLive$.getValue()?e.getExactLiveTime():e.getExactTime():o.getValue()??0,C=K.merge(c,p,b).pipe(K.map(()=>S())),w=K.merge(d,K.merge(l,g,_,u,x,m).pipe(K.map(()=>S()))),ee=t.started$&&t.ended$?K.merge(C,t.ended$):C,te=t.started$&&t.ended$?K.merge(w,t.started$):w;if(i.add(ee.subscribe(v)).add(te.subscribe(y)),n.heartbeatInterval&&isFinite(n.heartbeatInterval)){let e=[],t=()=>{x.next(),b.next()};i.add(ee.subscribe(()=>{let r=K.getWindow().setTimeout(t,n.heartbeatInterval);e.push(r)})).add(te.subscribe(()=>{e.forEach(e=>{K.getWindow().clearTimeout(e)}),e=[]}))}return i}),vt=require(`@vkontakte/videoplayer-core`),yt=require(`@vkontakte/videoplayer-shared`),bt=(e,t)=>new yt.Observable(n=>{let r=new vt.Subscription;return r.add(yt.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}),xt=require(`@vkontakte/videoplayer-core`),q=require(`@vkontakte/videoplayer-shared`),St=(e,{maxTimeWindow:t})=>new q.Observable(n=>{let r=new xt.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&&=(q.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=q.getWindow().setTimeout(()=>{a.timeoutId=null,l()},t):t>0&&l()}};return r.add(e.info.httpDownloadMetrics$.pipe(q.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}),J=require(`@vkontakte/videoplayer-shared`),Ct=e=>new J.Observable(t=>{let n=new J.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(J.merge(p,m).subscribe(l)).add(J.merge(h,_,v).subscribe(u)).add(y.subscribe(f)),t.next(()=>{let e=a;return o&&(e+=(Date.now()-r)*i),Math.round(e)}),n}),wt=require(`@vkontakte/videoplayer-shared`),Tt=(e,t)=>new wt.Observable(n=>{let r=new wt.Subscription,i=0;return r.add(wt.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}),Et=require(`@vkontakte/videoplayer-shared`),Y=require(`@vkontakte/videoplayer-core`),Dt=e=>{if(!Et.isNullable(e)){if(typeof e==`string`)return e;try{return JSON.stringify(e)}catch{return String(e)}}},Ot=e=>e&&{[Y.HttpConnectionType.HTTP1]:`http1`,[Y.HttpConnectionType.HTTP2]:`http2`,[Y.HttpConnectionType.QUIC]:`http3`}[e],X=e=>{if(e!==void 0)switch(e){case Y.VideoFormat.MPEG:return`MP4`;case Y.VideoFormat.DASH:case Y.VideoFormat.DASH_LIVE:return`DASH`;case Y.VideoFormat.DASH_SEP:return`DASH_SEP`;case Y.VideoFormat.DASH_ONDEMAND:return`ONDEMAND_DASH`;case Y.VideoFormat.HLS_ONDEMAND:return`ONDEMAND_HLS`;case Y.VideoFormat.HLS:case Y.VideoFormat.HLS_LIVE:return`HLS`;case Y.VideoFormat.HLS_FMP4:return`HLS_FMP4`;case Y.VideoFormat.DASH_WEBM:case Y.VideoFormat.DASH_LIVE_WEBM:return`WEBM`;case Y.VideoFormat.DASH_LIVE_CMAF:return`ONDEMAND_DASH_LIVE`;case Y.VideoFormat.HLS_LIVE_CMAF:return`ONDEMAND_HLS_LIVE`;case Y.VideoFormat.WEB_RTC_LIVE:return`WEBRTC`;case Y.VideoFormat.DASH_WEBM_AV1:return`AV1`;case Y.VideoFormat.DASH_STREAMS:return`MULTI_DASH`;default:return Et.assertNever(e)}},Z=e=>{if(e!==void 0)switch(e){case Y.VideoQuality.Q_144P:return`144p`;case Y.VideoQuality.Q_240P:return`240p`;case Y.VideoQuality.Q_360P:return`360p`;case Y.VideoQuality.Q_480P:return`480p`;case Y.VideoQuality.Q_720P:return`720p`;case Y.VideoQuality.Q_1080P:return`1080p`;case Y.VideoQuality.Q_1440P:return`1440p`;case Y.VideoQuality.Q_2160P:return`2160p`;case Y.VideoQuality.INVARIANT:case Y.VideoQuality.Q_576P:case Y.VideoQuality.Q_4320P:return`UNKNOWN`;default:return Et.assertNever(e)}},kt=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}},Q=(e,t,n)=>{if(e&&t)switch(e){case Y.VideoFormat.MPEG:return n&&t[e]&&t[e][n];default:return t[e]?.url}},At=(e,t=!1)=>{if(t)return`minimal`;switch(e){case void 0:case Y.Surface.NONE:return;case Y.Surface.INLINE:return`inline`;case Y.Surface.FULLSCREEN:return`fullscreen`;case Y.Surface.SECOND_SCREEN:return`chromecast`;case Y.Surface.PIP:return`pip_external`}},jt=e=>{switch(e){case void 0:return;case Y.Surface.INVISIBLE:return`background`;default:return`foreground`}},Mt=`_thin-one-stat_deviceId`,Nt=`2.2.0`,Pt=()=>{let e=new z.Subscription;return{subscription:e,subscribe:(t,n)=>{t&&e.add(t.subscribe(n))}}};class Ft{constructor(e,n){t(this,`apis`,[]),t(this,`logger`,void 0),t(this,`config`,void 0),t(this,`subscription`,void 0),t(this,`lifecycleFlushSubscription`,void 0),t(this,`timeSynchronisation`,void 0),t(this,`statContext`,void 0),t(this,`deviceId`,void 0),t(this,`targetDuration`,void 0),t(this,`debugLogger`,new z.Logger),t(this,`thinOneStatDebugLog`,this.debugLogger.createComponentLog(`ThinOneStat`)),t(this,`eventNumber`,1),t(this,`isStarted`,void 0),t(this,`isSeeking`,void 0),t(this,`inBufferStarvation`,void 0),t(this,`firstByteManifestSent`,void 0),t(this,`firstMediaRequestSent`,void 0),t(this,`firstByteMediaSent`,void 0),t(this,`wasPaused`,void 0),t(this,`isLive`,void 0),t(this,`lastContentType`,void 0),t(this,`cdnHostname`,void 0),t(this,`isEmbed`,void 0),t(this,`embedHostname`,void 0),t(this,`connectionType`,void 0),t(this,`connectionReused`,void 0),t(this,`player`,void 0),t(this,`playerSize`,{width:0,height:0}),t(this,`currentSubtitle`,void 0),t(this,`userQuality`,void 0),t(this,`downloadQuality`,void 0),t(this,`downloadSpeed`,void 0),t(this,`networkType`,void 0),t(this,`uiEvents`,void 0),t(this,`playerSubscription`,void 0),t(this,`uiSubscription`,void 0),t(this,`adsSubscription`,void 0),t(this,`seekAction$`,new z.ValueSubject(`unknown`)),t(this,`vsid$`,new z.ValueSubject(void 0)),t(this,`isid$`,new z.ValueSubject(void 0)),t(this,`errors$`,new z.Subject),t(this,`getTotalViewTime`,()=>0),this.statContext=e,this.config=Ke(n.config??{}),this.subscription=new z.Subscription,this.config.synchronizeTime&&(this.timeSynchronisation=new ht),this.subscription.add(this.errors$.subscribe(e=>{this.thinOneStatDebugLog({message:`[${e.category}] ${e.id}: ${e.message}`})}));let r=z.safeStorage.get(Mt);this.statContext.deviceId?this.deviceId=this.statContext.deviceId:r?this.deviceId=r:(this.deviceId=mt(),z.safeStorage.set(Mt,this.deviceId)),this.statContext.targetDuration?this.targetDuration=this.statContext.targetDuration:this.targetDuration=this.config.watchedNDefaultTargetDuration,this.resetViewSession(),n.useIsid&&this.isid$.next(n.isid??fe());let i=new at({errors$:this.errors$,config:this.config,timeSynchronisation:this.timeSynchronisation});this.config.apiForticom&&this.apis.push(new et({config:this.config,apiTransport:i,errors$:this.errors$,deviceId:this.deviceId,refreshAuthToken:n.refreshAuthToken})),this.config.apiUvRest&&(n.getUvRestAuthToken?this.apis.push(new tt({config:this.config,apiTransport:i,errors$:this.errors$,userId:this.statContext.userId,getAuthToken:n.getUvRestAuthToken})):this.errors$.next({id:`ThinOneStat:Init:MissingGetUvRestAuthToken`,category:z.ErrorCategory.WTF,message:`thinStatToUvRest enabled but getUvRestAuthToken callback not provided`})),this.logger=new pt({config:this.config,debugLogger:this.debugLogger,apis:this.apis,errors$:this.errors$,userSalt:n.userSalt});let{isEmbed:a,topOrigin:o}=z.detectEmbed();this.isEmbed=a,this.embedHostname=o?new URL(o).hostname:void 0}authorize(e){this.apis.forEach(t=>{t.authorize(e).catch(()=>{})})}reportError(e){let t={error_severity:e.severity,error_category:this.mapErrorCategory(e.category),player_error_code:e.code,player_error_trace:e.trace,error_message:e.message,content_type:this.getCurrentContentType()};this.logError(t),e.severity===`critical`&&this.logCannotPlay(),this.logTelemetry(this.collectTelemetryData())}updateContext(e){this.statContext=n(n({},this.statContext),e)}attachTo(e,t){this.playerSubscription&&(this.thinOneStatDebugLog({message:`Re-attaching to player, unsubscribing from previous`}),this.playerSubscription.unsubscribe());let r=new z.Subscription,i=(e,t)=>r.add(e.subscribe(t));i(Ct(e),e=>{this.getTotalViewTime=e}),i(e.info.isLive$,e=>this.isLive=e),i(e.info.currentFormat$,e=>{let t=X(e);t&&(this.lastContentType=t)}),i(e.info.hostname$.pipe(z.filter(e=>e!==void 0)),e=>{this.cdnHostname=e});let a;i(z.combine({hostname:e.info.hostname$,connectionType:e.info.httpConnectionType$,connectionReused:e.info.httpConnectionReused$}).pipe(z.filter(({hostname:e})=>e!==void 0),z.filter(({connectionType:e})=>e!==void 0),z.filter(({connectionReused:e})=>e!==void 0)),({hostname:e,connectionType:t,connectionReused:n})=>{if(a!==void 0&&a!==e){let r={cdn_host:e,connection_type:Ot(t),connection_reused:n,content_type:this.getCurrentContentType()};this.logFailover(r),this.logTelemetry(this.collectTelemetryData())}this.cdnHostname=a=e}),i(e.info.httpConnectionType$,e=>{this.connectionType=Ot(e)}),i(e.info.httpConnectionReused$,e=>{this.connectionReused=e}),i(_t(e,t,{heartbeatInterval:this.config.watchCoverageHeartbeatInterval,exactTime:this.config.watchCoverageExactTime}),t=>{let r={watch_interval:`${Math.round(t.from*1e3)}-${Math.round(t.to*1e3)}`,in_history:!!this.statContext.inHistory,content_type:this.getCurrentContentType(),playback_quality:Z(e.info.currentQuality$.getValue()),recom_info:this.statContext.recomInfo};if(!e.info.isLive$.getValue())this.logWatchCoverage(r);else{let t=e.info.atLiveEdge$.getValue();this.logWatchCoverageLive(n(n({},r),{},{live:!!t}))}}),i(Tt(e,{interval:this.statContext.telemetryInterval??this.config.telemetryInterval,getTotalViewTime:this.getTotalViewTime}),()=>{this.logTelemetry(this.collectTelemetryData())}),i(bt(e,{targetDuration:this.targetDuration,getTotalViewTime:this.getTotalViewTime}),e=>{this.logWatchedN(e)}),i(e.events.willReady$,()=>{let t={isid:this.isid$.getValue(),stream_profile:kt(this.getCurrentContentType()),dpi:Math.round(this.statContext.dpi??96*B.clientChecker.display.pixelRatio),web_layout:this.statContext.isMobile||B.clientChecker.device.isMobile?`mobile`:`desktop`,preloaded:this.statContext.preload,navigation:this.statContext.navigation,recom_info:this.statContext.recomInfo};if(this.isEmbed&&(t.iframe_host=this.embedHostname??`unknown`),this.logStartSession(t),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:Q(t,n,i),playback_quality:Z(i)};this.logPreloadStarted(a)}}),i(z.combine({manifestRequested$:e.events.manifestRequested$,connectionType:e.info.httpConnectionType$,connectionReused:e.info.httpConnectionReused$}).pipe(z.filter(({connectionType:e})=>e!==void 0),z.filter(({connectionReused:e})=>e!==void 0),z.once()),()=>{let t={playback_url:Q(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)}),i(z.combine({firstBytesManifest:e.events.firstBytesManifest$,connectionType:e.info.httpConnectionType$,connectionReused:e.info.httpConnectionReused$}).pipe(z.once()),()=>{if(this.firstByteManifestSent)return;this.firstByteManifestSent=!0;let t={playback_url:Q(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)}),i(e.events.manifestReceived$,()=>{let t={playback_url:Q(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)}),i(e.events.firstBytesRequested$,()=>{if(this.firstMediaRequestSent)return;this.firstMediaRequestSent=!0;let t={playback_url:Q(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)}),i(e.events.firstBytes$,()=>{if(this.firstByteMediaSent)return;this.firstByteMediaSent=!0;let t={playback_url:Q(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)}),i(z.merge(e.events.willStart$,e.events.looped$),e=>{e&&this.resetViewSession(),this.isStarted=!0}),i(e.events.started$,()=>{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:Z(n),user_quality:r?`auto`:Z(n),player_width:Math.round(this.statContext.playerSize?.width??this.playerSize.width),player_height:Math.round(this.statContext.playerSize?.height??this.playerSize.height),muted:i,sound_volume:Math.round(a*100),buffer_time:this.calcBufferTime(t),mode:At(o,this.statContext.isPreviewPlayerView),visibility:jt(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*100,recom_info:this.statContext.recomInfo};this.logPlaybackStarted(d),this.logTelemetry(this.collectTelemetryData())}),i(e.events.willStart$,()=>{this.logPlay()}),i(e.events.playing$,()=>{let t=e.info.currentBuffer$.getValue(),n={buffer_time:this.calcBufferTime(t)};this.logPlaying(n),this.inBufferStarvation=!1,this.wasPaused&&this.logResume()}),i(e.events.paused$,()=>{this.wasPaused=!0,this.logPause()}),i(e.events.ended$,()=>{this.logContentEndReached()}),i(e.events.willStop$,()=>{this.isStarted=!1,this.isSeeking=!1,this.inBufferStarvation=!1,this.logStop()}),i(z.merge(e.events.fetcherRecoverableError$,e.events.fatalError$),()=>{this.statContext.preload&&this.logPreloadError()}),i(e.events.fetcherRecoverableError$,({id:e,category:t,data:n,message:r,httpCode:i,UVBackendErrorCode:a})=>{let o={error_severity:this.mapErrorSeverity(t),error_category:this.mapErrorCategory(t),player_error_code:e,player_error_trace:Dt(n),http_error_code:i,uv_backend_error_code_subcode:a,error_message:r,content_type:this.getCurrentContentType()};this.logError(o),this.mapErrorSeverity(t)===`critical`&&this.logCannotPlay(),this.logTelemetry(this.collectTelemetryData())}),i(e.events.managedError$,({id:e,category:t,data:n,message:r,httpCode:i,UVBackendErrorCode:a})=>{let o={error_severity:this.mapErrorSeverity(t),error_category:this.mapErrorCategory(t),player_error_code:e,player_error_trace:Dt(n),http_error_code:i,uv_backend_error_code_subcode:a,error_message:r,content_type:this.getCurrentContentType()};this.logError(o),this.logTelemetry(this.collectTelemetryData())}),i(e.events.fatalError$,({id:e,category:t,data:n,message:r,httpCode:i,UVBackendErrorCode:a})=>{let o={error_severity:`critical`,error_category:this.mapErrorCategory(t),player_error_code:e,player_error_trace:Dt(n),http_error_code:i,uv_backend_error_code_subcode:a,error_message:r,content_type:this.getCurrentContentType()};this.logError(o),this.logCannotPlay(),this.logTelemetry(this.collectTelemetryData())}),i(z.combine({connectionType:e.info.httpConnectionType$,connectionReused:e.info.httpConnectionReused$,connectionMetrics:e.info.httpConnectionMetrics$}).pipe(z.filter(({connectionReused:e})=>e!==void 0),z.filter(({connectionMetrics:e})=>e!==void 0),z.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=t?.dnsResolveTime,s=t?.tcpHandshakeTime,c=t?.tlsHandshakeTime,l={playback_url:Q(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:o?Math.round(o):void 0,tcp_handshake_time:s?Math.round(s):void 0,tls_handshake_time:c?Math.round(c):void 0};this.logConnectionEstablished(l)}),i(St(e,{maxTimeWindow:this.config.downloadBytesMaxTime}),e=>{this.downloadSpeed=e.download_speed,this.logDownloadBytes(e)}),i(e.events.firstFrame$,()=>{this.logFirstVideoFrameDecoded()}),i(e.events.willSeek$,()=>{this.isSeeking=!0;let e={seek_type:this.seekAction$.getValue()};this.isStarted&&this.logSeeking(e)}),i(e.events.seeked$,()=>{this.isSeeking=!1;let e={seek_type:this.seekAction$.getValue()};this.isStarted&&this.logSeeked(e),this.seekAction$.next(`unknown`)}),i(e.info.stallStartTime$,t=>{if(t<=0){this.inBufferStarvation=!1;return}this.inBufferStarvation||(this.inBufferStarvation=!0,this.logBufferStarvation({buffer_time:this.calcBufferTime(e.info.currentBuffer$.getValue())}),this.logTelemetry(this.collectTelemetryData()))}),i(e.info.currentBuffer$.pipe(z.filter(e=>!!this.calcBufferTime(e)),z.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 o;i(z.combine({videoStream:e.info.currentVideoStream$,audioStream:e.info.currentAudioStream$,quality:e.info.currentQuality$}).pipe(z.filter(({videoStream:e,audioStream:t})=>e!==void 0&&t!==void 0),z.filter(({quality:e})=>e!==void 0)),({videoStream:t,audioStream:n,quality:r})=>{if(o!==r){if(this.userQuality=e.info.isAutoQualityEnabled$.getValue()?`auto`:Z(r),this.downloadQuality=Z(r),this.isStarted){let e=t?.codec,r=n?.codec,i={user_quality:this.userQuality,playback_quality:Z(o),download_quality:this.downloadQuality,codec_info:this.genCodecInfo(e,r)};this.logQualityChanged(i)}o=r}});let s,c;return i(e.info.surface$,e=>{let t=At(e,this.statContext.isPreviewPlayerView);t&&!this.uiEvents&&this.isStarted&&this.logModeChanged({mode:t}),c=jt(e),s!==c&&(this.isStarted&&this.logVisibilityChanged({visibility:c}),s=jt(e))}),i(z.combine({muted:e.info.muted$,volume:e.info.volume$}).pipe(z.debounce(300)),({muted:e,volume:t})=>{if(this.isStarted){let n={muted:e,sound_volume:Math.round(t*100)};this.logSoundChanged(n)}}),i(e.info.currentFormat$.pipe(z.filter(e=>e!==void 0),z.skip(1)),e=>{let t={content_type:X(e),cdn_host:this.cdnHostname,connection_type:this.connectionType,connection_reused:this.connectionReused};this.logContentTypeChange(t)}),i(e.info.currentAudioStream$.pipe(z.filter(e=>e!==void 0),z.skip(1)),e=>{let t={audio_track_lang:e.language,codec_info:e.codec};this.logAudioTrackSwitched(t)}),i(e.info.currentVideoStream$.pipe(z.filter(e=>e!==void 0),z.skip(1)),e=>{let t={hdr:e.hdr,codec_info:e.codec};this.logVideoTrackSwitched(t)}),this.player=e,this.playerSubscription=r,this.resubscribeLifecycleFlush(),this.subscription.add(r),r}attachToUi(e){this.uiSubscription&&(this.thinOneStatDebugLog({message:`Re-attaching to UI, unsubscribing from previous`}),this.uiSubscription.unsubscribe()),this.uiEvents=e;let{subscribe:t,subscription:r}=Pt();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:Math.round(e),player_height:Math.round(t)}))}),t(e.isLoaderVisible$,e=>{if(!e){this.inBufferStarvation=!1;return}this.isStarted&&(this.logShowLoader(),!(this.isSeeking||this.inBufferStarvation||!this.player)&&(this.inBufferStarvation=!0,this.logBufferStarvation({buffer_time:this.calcBufferTime(this.player.info.currentBuffer$.getValue())}),this.logTelemetry(this.collectTelemetryData())))}),t(e.actionSubtitlesSwitched$,e=>{if(this.currentSubtitle=n({},e),this.isStarted){let t={subtitles_enabled:e.enabled,subtitles_track_lang:e.lang,auto_subtitles:e.auto};this.logSubtitlesSwitched(t)}});let{surface$:i}=Pe(this.uiEvents,t,this.player);return t(i,e=>{this.isStarted&&this.logModeChanged({mode:At(e)})}),t(e.actionQuality$,e=>{var t,n,r;let i=e=>Be.arrayIncludes(ze.objectValues(He),e),a=(t=this.player)==null||(t=t.info.currentVideoStream$.getValue())==null?void 0:t.codec,o=(n=this.player)==null||(n=n.info.currentAudioStream$.getValue())==null?void 0:n.codec,s={user_quality:i(e)?`auto`:Z(e),playback_quality:Z(this.player?.info.currentQuality$.getValue()),download_quality:i(e)?Z((r=this.player)==null||(r=r.info.currentQuality$)==null?void 0:r.getValue()):Z(e),codec_info:this.genCodecInfo(a,o)};this.logQualityChangeRequested(s)}),this.uiSubscription=r,this.resubscribeLifecycleFlush(),this.subscription.add(r),r}attachToAds(e){this.adsSubscription&&(this.thinOneStatDebugLog({message:`Re-attaching to ads, unsubscribing from previous`}),this.adsSubscription.unsubscribe());let{subscription:t,subscribe:n}=Pt();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.adsSubscription=t,this.resubscribeLifecycleFlush(),this.subscription.add(t),t}getDeviceId(){return this.deviceId}resetViewSession(){this.thinOneStatDebugLog({message:`VSID reset`}),E.generateVSID(this.config.useVsid64),this.vsid$.next(E.getVSID()),this.eventNumber=0,this.firstByteManifestSent=!1,this.firstMediaRequestSent=!1,this.firstByteMediaSent=!1}destroy(){var e=this;return r(function*(){e.thinOneStatDebugLog({message:`Destroying ThinOneStat`}),e.subscription.unsubscribe(),e.lifecycleFlushSubscription?.unsubscribe(),yield e.logger.destroy(),e.apis.forEach(e=>e.destroy()),e.thinOneStatDebugLog({message:`ThinOneStat destroyed`})})()}calcBufferTime(e){return e?Math.round(((e.end??0)-(e.start??0))*1e3):void 0}mapErrorCategory(e){switch(e){case z.ErrorCategory.NETWORK:return`network`;case z.ErrorCategory.VIDEO_PIPELINE:return`video_pipeline`;case z.ErrorCategory.EXTERNAL_API:return`external_api`;case z.ErrorCategory.PARSER:return`parser`;case z.ErrorCategory.DOM:return`dom`;default:return`wtf`}}mapErrorSeverity(e){return z.ErrorCategory.FATAL===e?`critical`:`informative`}getCurrentContentType(){let e=X(this.player?.info.currentFormat$.getValue());if(e)return e;if(this.lastContentType)return this.lastContentType;let t=this.player?.info.availableSources$.getValue();if(!t)return;let n=Object.keys(t)[0];return X(n)}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=this.getCurrentContentType(),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:Z(this.player.info.currentQuality$.getValue()),download_quality:this.downloadQuality,codec_info:this.genCodecInfo(a,o),bandwidth_from_manifest:s?Math.round(s):void 0,cdn_host:this.cdnHostname,download_speed:this.downloadSpeed?Math.round(this.downloadSpeed):void 0,network_type:this.networkType,rtt:c?Math.round(c):void 0,latency:this.getLatencyInfo()}}isValidPlatform(e=``){return Be.arrayIncludes([`web:desktop`,`web:mobile`,`smart_tv`],e)}createRequiredParams(e){let t=this.vsid$.getValue();z.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:${O}`,platform:this.isValidPlatform(this.statContext.platform)?this.statContext.platform:`web:${this.statContext.isMobile||B.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:Nt,browser:this.statContext.browser??B.clientChecker.browser.current,browser_version:this.statContext.browserVersion??String(B.clientChecker.browser.currentVersion),os:this.statContext.os??B.clientChecker.device.os.name,os_version:this.statContext.osVersion??B.clientChecker.device.os.version,device_type:this.statContext.deviceType??(this.statContext.isMobile||B.clientChecker.device.isMobile?`mobile`:`desktop`),device_manufacturer:this.statContext.deviceManufacturer??B.clientChecker.device.details.vendor,device_model:this.statContext.deviceModel??B.clientChecker.device.details.model,navigation:this.statContext.navigation};for(let t of this.config.disabledParams)delete e[t];return e}log(e,t,r=!1){if(Be.arrayIncludes(this.config.disabledEvents,e))return;let i=this.createRequiredParams(e),a={};r&&(a=this.createRequiredFatParams()),this.logger.log(n(n(n({},i),a),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)}logContentEndReached(){this.log(`content_end_reached`)}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)}resubscribeLifecycleFlush(){this.lifecycleFlushSubscription?.unsubscribe();let e=z.getWindow(),t=()=>{this.logger.flush({wantBeacon:!0,clearStorage:this.config.clearStorageAtUnload}).catch(()=>{})},n=new z.Subscription;n.add(z.fromEvent(e,`beforeunload`).subscribe(t)),n.add(z.fromEvent(e,`pagehide`).subscribe(t)),n.add(z.fromEvent(e.document,`visibilitychange`).subscribe(e=>{e.target?.visibilityState===`hidden`&&t()})),this.lifecycleFlushSubscription=n}}var It=require(`@vkontakte/videoplayer-shared`),Lt=require(`@vkontakte/videoplayer-shared`),$=require(`@vkontakte/videoplayer-core`),Rt=require(`@vkontakte/videoplayer-shared`);class zt{constructor(){t(this,`startTime`,null),t(this,`stopTime`,null),t(this,`accumulatedTime`,0)}get time(){return Math.floor(this.timeMs/1e3)}get timeMs(){return this.startTime===null?0:(this.stopTime??this.now())-this.startTime-this.accumulatedTime}get isRunning(){return this.startTime!==null&&this.stopTime===null}start(){this.isRunning||(this.stopTime===null?this.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 Bt=()=>window.Image?new Image:document.createElement(`img`);class Vt{constructor(e){t(this,`params`,void 0),t(this,`position`,0),t(this,`started`,!1),t(this,`isActiveLive`,void 0),t(this,`heartbeatPixels`,[]),t(this,`heartbeatLastTimeSent`,{}),t(this,`heartbeatInterval`,void 0),t(this,`heartbeatFirstTimeoutId`,void 0),t(this,`idleCallbackIds`,[]),t(this,`log`,void 0),t(this,`stopwatch`,new zt),t(this,`subscription`,new $.Subscription),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=>It.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(Lt.requestIdleCallbackPolyfilled(()=>Bt().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)}}