@vkontakte/videoplayer-statistics 1.0.38 → 1.0.39
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.js +4 -4
- package/es2015.esm.js +4 -4
- package/es2018.cjs.js +4 -4
- package/es2018.esm.js +4 -4
- package/esnext.cjs.js +4 -4
- package/esnext.esm.js +4 -4
- package/evergreen.esm.js +4 -4
- package/index.d.ts +18 -17
- package/package.json +1 -1
package/es2018.cjs.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @vkontakte/videoplayer-statistics v1.0.
|
|
3
|
-
*
|
|
4
|
-
* https://st.mycdn.me/static/vkontakte-videoplayer/1-0-
|
|
2
|
+
* @vkontakte/videoplayer-statistics v1.0.39
|
|
3
|
+
* Tue, 29 Aug 2023 12:33:55 GMT
|
|
4
|
+
* https://st.mycdn.me/static/vkontakte-videoplayer/1-0-39/doc/
|
|
5
5
|
*/
|
|
6
|
-
"use strict";var r=require("@vkontakte/videoplayer-shared/es2018.cjs.js"),O=require("lodash/debounce.js"),l=require("@vkontakte/videoplayer-core/es2018.cjs.js");exports.ApiEnv=void 0;(function(t){t.PROD="prod",t.VK_ALIAS="vk_alias",t.VIDEOTEST="videotest",t.TEST="test",t.AUTO="auto"})(exports.ApiEnv||(exports.ApiEnv={}));exports.Quality=void 0;(function(t){t.Q144P="mobile",t.Q240P="lowest",t.Q360P="low",t.Q480P="medium",t.Q720P="high",t.Q1080P="fullhd",t.Q1440P="quadhd",t.Q2160P="ultrahd",t.UNKNOWN="unknown"})(exports.Quality||(exports.Quality={}));exports.ContentType=void 0;(function(t){t.MP4="mp4",t.DASH="dash",t.DASH_SEP="dash_sep",t.ONDEMAND_DASH="ondemand_dash",t.HLS="hls",t.ONDEMAND_HLS="ondemand_hls",t.WEBM="webm",t.AV1="av1",t.ONDEMAND_DASH_LIVE="ondemand_dash_live",t.ONDEMAND_HLS_LIVE="ondemand_hls_live",t.WEBRTC="webrtc",t.UNKNOWN="unknown",t.RTMP="rtmp"})(exports.ContentType||(exports.ContentType={}));var v;(function(t){t.AUTO="auto",t.MANUAL=""})(v||(v={}));exports.ConnectionType=void 0;(function(t){t.HTTP1="http1",t.HTTP2="http2",t.HTTP3="http3"})(exports.ConnectionType||(exports.ConnectionType={}));var g;(function(t){t[t.YES=1]="YES",t[t.NO=0]="NO"})(g||(g={}));var E;(function(t){t.EXCELLENT="excellent",t.GOOD="good",t.POOR="poor"})(E||(E={}));var S;(function(t){t.PIP="pip",t.FULLSCREEN="fullscreen",t.EXTERNAL="external",t.PREFETCH="prefetch"})(S||(S={}));exports.SeekAction=void 0;(function(t){t.SLIDER="slider",t.DOUBLE_TAP="double_tap",t.TIME_CODE="time_code",t.EPISODE="episode",t.REWIND="rewind",t.LIVE="live",t.UNKNOWN="unknown"})(exports.SeekAction||(exports.SeekAction={}));exports.InteractiveInterfaceClick=void 0;(function(t){t.GRAPH_SHOW="iGraphShow",t.GRAPH_HIDE="iGraphHide",t.NEXT_AREA="iNextChapterArea",t.NEXT_BUTTON="iNextChapterBtn",t.WATCH_AGAIN="iWatchAgainBtn"})(exports.InteractiveInterfaceClick||(exports.InteractiveInterfaceClick={}));const B={apiEnv:exports.ApiEnv.VK_ALIAS,requestRetryCount:1,firstFlushTime:5e3,flushDebounceTime:1e4,flushMaxWait:6e4,storageExpiration:36*60*60*1e3,disabledOperations:[],disabledCustomFields:[],useBeacon:!0,synchronizeTime:!0,backoff:{start:1e3,factor:1.5,max:5*60*1e3,random:.1}},U=t=>r.fillWithDefault(t,B);function H(){const t="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".split(""),e=new Array(36);let s=0,i,o;for(o=0;o<36;o++)o===8||o===13||o===18||o===23?e[o]="-":o===14?e[o]="4":(s<=2&&(s=33554432+Math.random()*16777216|0),i=s&15,s=s>>4,e[o]=t[o===19?i&3|8:i]);return e.join("")}const N="1.0.38",M="CIOPGQJGDIHBABABA",R={[exports.ApiEnv.PROD]:"https://api.ok.ru",[exports.ApiEnv.VK_ALIAS]:"https://api.mycdn.me",[exports.ApiEnv.VIDEOTEST]:"https://videotestapi.ok.ru/api",[exports.ApiEnv.TEST]:"https://apitest.ok.ru",[exports.ApiEnv.AUTO]:""},q="_one-stat_",x=`${q}uuid`;var m;(function(t){t[t.PARAM_SESSION_EXPIRED=102]="PARAM_SESSION_EXPIRED",t[t.PARAM_SESSION_KEY=103]="PARAM_SESSION_KEY",t[t.PARAM_SIGNATURE=104]="PARAM_SIGNATURE",t[t.AUTH_LOGIN=401]="AUTH_LOGIN"})(m||(m={}));class W{constructor(e){this.consequentAuthErrors=0,this.authorized$=new r.ValueSubject(!1),this.params=e;const s=r.safeStorage.get(x);s?this.uuid=String(s):(this.uuid=H(),r.safeStorage.set(x,this.uuid))}async authorize(e){return this.authToken=e!=null?e:await this.refreshAuthToken(),this._authorizeWithBackoff()}logBeacon(e){const s="log.externalLog",i=this.createLogParams(e),o=this.sessionKey;if(!o)return;this.params.apiTransport.sendBeacon(s,i,o)||this.logRequest(e)}async logRequest(e){var s;const i="log.externalLog",o=this.createLogParams(e),a=(s=this.sessionKey)!==null&&s!==void 0?s:await this._authorizeWithBackoff();if(!a)return;const u=async(f,d=this.params.config.requestRetryCount)=>{try{return await this.params.apiTransport.sendRequest(i,o,a)}catch(c){if(!c||!("error_code"in c)){this.params.error$.next({id:"logRequestUnknown",category:r.ErrorCategory.NETWORK,message:`Unknown ${i} error`,thrown:c});return}const n=c==null?void 0:c.error_code;switch(n){case m.PARAM_SESSION_EXPIRED:case m.PARAM_SESSION_KEY:case m.PARAM_SIGNATURE:return this.authorized$.next(!1),this.sessionKey=await this._authorizeWithBackoff(),d>0?u(f,d-1):void 0;case m.AUTH_LOGIN:return this.authorized$.next(!1),this.authToken=await this.refreshAuthToken(),this.sessionKey=await this._authorizeWithBackoff(),d>0?u(f,d-1):void 0;default:{this.params.error$.next({id:`LogRequest#${n}`,category:r.ErrorCategory.EXTERNAL_API,message:`${i} error`,data:c});return}}}};return u(e)}destroy(){window.clearTimeout(this.backoffTimeoutId),this.backoffTimeoutId=0}async refreshAuthToken(){if(this.params.refreshAuthToken)return this.refreshAuthTokenPromise||(this.refreshAuthTokenPromise=this.params.refreshAuthToken().finally(()=>{this.refreshAuthTokenPromise=void 0})),this.refreshAuthTokenPromise}createLogParams(e){return{collector:"ok.mobile.apps.video",data:JSON.stringify({application:`@vkontakte/videoplayer-statistics:${N}`,platform:this.params.mobile?"M_WEB":"WEB",items:e})}}_authorizeWithBackoff(){if(!this.consequentAuthErrors)return this._authorize();const e=r.getExponentialDelay(this.consequentAuthErrors,this.params.config.backoff);return new Promise(s=>{this.backoffTimeoutId||(this.backoffTimeoutId=window.setTimeout(()=>{this._authorize().then(s).catch(i=>this.params.error$.next({id:"AuthorizeBackoff",category:r.ErrorCategory.NETWORK,message:"Otherwise unhandled error in authorization",thrown:i})).finally(()=>this.backoffTimeoutId=0)},e))})}async _authorize(){if(this.authorizePromise)return this.authorizePromise;this.sessionKey=void 0,this.authorized$.next(!1);const e="auth.anonymLogin",s={session_data:{version:2,device_id:this.uuid,client_version:N.split("-")[0],client_type:"SDK_JS"}};return this.authToken!==void 0&&(s.session_data.auth_token=this.authToken,s.session_data.version=3),this.authorizePromise=this.params.apiTransport.sendRequest(e,s).then(i=>{var o;return(!i||!i.session_key)&&this.params.error$.next({id:"AuthorizeFailed",category:r.ErrorCategory.EXTERNAL_API,message:"No session key",data:i}),this.sessionKey=(o=i==null?void 0:i.session_key)!==null&&o!==void 0?o:void 0,this.sessionKey}).catch(async i=>{this.sessionKey=void 0;const o=i==null?void 0:i.error_code;switch(o){case m.AUTH_LOGIN:return this.authToken=await this.refreshAuthToken(),this._authorizeWithBackoff()}o?this.params.error$.next({id:`Authorize#${o}`,category:r.ErrorCategory.EXTERNAL_API,message:"authorize error",data:i}):this.params.error$.next({id:"AuthorizeUnknown",category:r.ErrorCategory.NETWORK,message:"authorize error",thrown:i})}).finally(()=>{this.authorizePromise=void 0,this.consequentAuthErrors=this.sessionKey?0:this.consequentAuthErrors+1,this.authorized$.next(this.sessionKey!==void 0)}),this.authorizePromise}}class ${constructor(){Object.defineProperty(this,"listeners",{value:{},writable:!0,configurable:!0})}addEventListener(e,s,i){e in this.listeners||(this.listeners[e]=[]),this.listeners[e].push({callback:s,options:i})}removeEventListener(e,s){if(!(e in this.listeners))return;const i=this.listeners[e];for(let o=0,a=i.length;o<a;o++)if(i[o].callback===s){i.splice(o,1);return}}dispatchEvent(e){if(!(e.type in this.listeners))return;const i=this.listeners[e.type].slice();for(let o=0,a=i.length;o<a;o++){const u=i[o];try{u.callback.call(this,e)}catch(f){Promise.resolve().then(()=>{throw f})}u.options&&u.options.once&&this.removeEventListener(e.type,u.callback)}return!e.defaultPrevented}}class F extends ${constructor(){super(),this.listeners||$.call(this),Object.defineProperty(this,"aborted",{value:!1,writable:!0,configurable:!0}),Object.defineProperty(this,"onabort",{value:null,writable:!0,configurable:!0}),Object.defineProperty(this,"reason",{value:void 0,writable:!0,configurable:!0})}toString(){return"[object AbortSignal]"}dispatchEvent(e){e.type==="abort"&&(this.aborted=!0,typeof this.onabort=="function"&&this.onabort.call(this,e)),super.dispatchEvent(e)}}class Q{constructor(){Object.defineProperty(this,"signal",{value:new F,writable:!0,configurable:!0})}abort(e){let s;try{s=new Event("abort")}catch(o){typeof document!="undefined"?document.createEvent?(s=document.createEvent("Event"),s.initEvent("abort",!1,!1)):(s=document.createEventObject(),s.type="abort"):s={type:"abort",bubbles:!1,cancelable:!1}}let i=e;if(i===void 0)if(typeof document=="undefined")i=new Error("This operation was aborted"),i.name="AbortError";else try{i=new DOMException("signal is aborted without reason")}catch(o){i=new Error("This operation was aborted"),i.name="AbortError"}this.signal.reason=i,this.signal.dispatchEvent(s)}toString(){return"[object AbortController]"}}typeof Symbol!="undefined"&&Symbol.toStringTag&&(Q.prototype[Symbol.toStringTag]="AbortController",F.prototype[Symbol.toStringTag]="AbortSignal");function D(t){return t.__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL?(console.log("__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL=true is set, will force install polyfill"),!0):typeof t.Request=="function"&&!t.Request.prototype.hasOwnProperty("signal")||!t.AbortController}function K(t){typeof t=="function"&&(t={fetch:t});const{fetch:e,Request:s=e.Request,AbortController:i,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:o=!1}=t;if(!D({fetch:e,Request:s,AbortController:i,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:o}))return{fetch:e,Request:a};let a=s;(a&&!a.prototype.hasOwnProperty("signal")||o)&&(a=function(c,n){let h;n&&n.signal&&(h=n.signal,delete n.signal);const p=new s(c,n);return h&&Object.defineProperty(p,"signal",{writable:!1,enumerable:!1,configurable:!0,value:h}),p},a.prototype=s.prototype);const u=e;return{fetch:(d,c)=>{const n=a&&a.prototype.isPrototypeOf(d)?d.signal:c?c.signal:void 0;if(n){let h;try{h=new DOMException("Aborted","AbortError")}catch(y){h=new Error("Aborted"),h.name="AbortError"}if(n.aborted)return Promise.reject(h);const p=new Promise((y,b)=>{n.addEventListener("abort",()=>b(h),{once:!0})});return c&&c.signal&&delete c.signal,Promise.race([p,u(d,c)])}return u(d,c)},Request:a}}const C=D({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),V=C?K({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,k=C?V.fetch:window.fetch;C?V.Request:window.Request;class z{constructor(e){this.params=e,this.apiKey=e.apiKey,this.apiEnv=e.config.apiEnv,this.apiBaseUrl=R[this.apiEnv],this.timeSynchronisation=e.timeSynchronisation,this.isApiBaseUrlFetched=!1}async resolveApiBaseUrl(){var e;if(this.apiEnv!==exports.ApiEnv.AUTO||this.isApiBaseUrlFetched)return this.apiBaseUrl;try{const s=atob("aHR0cHM6Ly9kbnMuZ29vZ2xlL3Jlc29sdmU/bmFtZT12aWRlby5fZW5kcG9pbnQub2sucnUmdHlwZT1UWFQ="),o=await(await k(s,{method:"GET",mode:"cors",cache:"no-cache"})).json(),a=(e=o==null?void 0:o.Answer[0])===null||e===void 0?void 0:e.data;if(!a)throw new Error("Wrong DNS response");return a}catch(s){return this.params.error$.next({id:"OneStat:ApiTransport:resolveApiBaseUrl",category:r.ErrorCategory.NETWORK,message:"Unhandled resolve api base url error",thrown:s}),R[exports.ApiEnv.VK_ALIAS]}finally{this.isApiBaseUrlFetched=!0}}sendBeacon(e,s,i){if(!window.Blob||!window.navigator.sendBeacon)return!1;const o=this._prepareQueryParams({method:e,queryParams:s,sessionKey:i}),a=new window.Blob([o.toString()],{type:"application/x-www-form-urlencoded"});try{return window.navigator.sendBeacon(`${this.apiBaseUrl}/fb.do`,a)}catch(u){this.params.error$.next({id:"OneStat:ApiTransport:sendBeacon",category:r.ErrorCategory.NETWORK,message:"Unhandled beacon error",thrown:u,data:{method:e,params:s}})}return!1}async sendRequest(e,s,i){const o=r.now(),a=u=>{if(u instanceof TypeError&&["Failed to fetch","NetworkError when attempting to fetch resource."].includes(u.message)){this.params.error$.next({id:"Network",category:r.ErrorCategory.NETWORK,message:"Request failed",thrown:u});return}this.params.error$.next({id:"OneStat:ApiTransport:sendRequest",category:r.ErrorCategory.NETWORK,message:"Unhandled request error",thrown:u,data:{method:e,params:s,sessionKey:i,time:r.now()-o}})};return this.apiBaseUrl=await this.resolveApiBaseUrl(),k(`${this.apiBaseUrl}/fb.do`,{method:"post",headers:{"Content-type":"application/x-www-form-urlencoded"},body:this._prepareQueryParams({method:e,queryParams:s,sessionKey:i})}).then(u=>{var f,d;const c=Number(u.headers.get("content-length"))===0,n=new Date((f=u.headers.get("date"))!==null&&f!==void 0?f:"").getTime(),h=r.now()-o;if(isFinite(n)&&((d=this.timeSynchronisation)===null||d===void 0||d.addServerTime(n,h)),!c)return u.json().then(p=>Object.prototype.hasOwnProperty.call(p,"error_msg")?Promise.reject(p):p,a)},a)}_prepareQueryParams(e){const s=new URLSearchParams({format:"JSON",method:e.method,application_key:this.apiKey});return e.sessionKey!==void 0&&s.append("session_key",e.sessionKey),Object.entries(e.queryParams).forEach(([i,o])=>s.append(i,typeof o=="string"?o:JSON.stringify(o))),s}}const _="onestat_events",T=t=>e=>e.timestamp+t>=r.now();class j{constructor(e){this.unsaltedStorage=[],this.isPaused=!1,this.isUrgent=i=>{const{operation:o,custom:{param:a}}=i;return["action_stop","close_at_empty_buffer"].includes(o)||o==="watch_coverage_record"&&a==="0-0"},this.params=e,this.api=e.api,this.error$=e.error$,this.userSalt=e.userSalt,this.firstFlush=O(()=>this.safeFlush(),this.params.config.firstFlushTime,{maxWait:this.params.config.firstFlushTime});const s=r.safeStorage.isPersistent()?this.params.config.flushMaxWait:0;this.debouncedFlush=O(()=>this.safeFlush(),this.params.config.flushDebounceTime,{maxWait:s}),this.subscription=this.api.authorized$.subscribe(i=>{i&&this.debouncedFlush()}),this.housekeepStorage()}safeFlush(){var e;try{this.flush()}catch(s){this.error$.next({id:"LoggerError",category:r.ErrorCategory.WTF,message:(e=String(s))!==null&&e!==void 0?e:"Unknown logger error",thrown:s})}}readFromStorage(){const e=r.safeStorage.get(_);try{return e?JSON.parse(e):{}}catch(s){}return{}}addToStorage(e){var s;if(!this.userSalt){this.unsaltedStorage.push(e);return}const i=this.readFromStorage(),a=((s=i[this.userSalt])!==null&&s!==void 0?s:[]).filter(T(this.params.config.storageExpiration));r.safeStorage.set(_,JSON.stringify({...i,[this.userSalt]:[...a,e]}))}getFromStorage(){var e;return this.userSalt?((e=this.readFromStorage()[this.userSalt])!==null&&e!==void 0?e:[]).filter(T(this.params.config.storageExpiration)):this.unsaltedStorage}markStorageSent(){if(!this.userSalt){this.unsaltedStorage=[];return}const e=this.readFromStorage();delete e[this.userSalt],r.safeStorage.set(_,JSON.stringify(e))}housekeepStorage(){const e=this.readFromStorage();for(const[s,i]of Object.entries(e)){const o=i.filter(T(this.params.config.storageExpiration));o.length?e[s]=o:delete e[s]}r.safeStorage.set(_,JSON.stringify(e))}log(e){this.addToStorage(e),!this.isPaused&&(this.isUrgent(e)?this.flush():this.lastVsid!==e.custom.vsid?this.firstFlush():this.debouncedFlush(),this.lastVsid=e.custom.vsid)}flush(e=!1){const s=this.getFromStorage();s.length!==0&&(this.api.authorized$.getValue()?(e&&this.params.config.useBeacon?this.api.logBeacon(s):this.api.logRequest(s),this.markStorageSent()):this.api.authorize(),this.firstFlush.cancel(),this.debouncedFlush.cancel())}pause(){this.isPaused=!0,this.debouncedFlush.cancel()}resume(){this.isPaused=!1,this.debouncedFlush()}destroy(){this.subscription.unsubscribe(),this.firstFlush.cancel(),this.debouncedFlush.cancel()}}const G=()=>{let t,e;try{t=window.self!==window.top}catch(i){i instanceof DOMException&&i.name==="SecurityError"?t=!0:(t=!1,console.error(i))}try{window.location.ancestorOrigins&&(e=window.location.ancestorOrigins[window.location.ancestorOrigins.length-1])}catch(i){console.error(i)}try{!e&&document.referrer&&(e=document.referrer)}catch(i){console.error(i)}const s=e?new URL(e).hostname:void 0;return{isEmbed:t,host:s}},Y=t=>t&&{[l.VideoQuality.INVARIANT]:exports.Quality.UNKNOWN,[l.VideoQuality.Q_144P]:exports.Quality.Q144P,[l.VideoQuality.Q_240P]:exports.Quality.Q240P,[l.VideoQuality.Q_360P]:exports.Quality.Q360P,[l.VideoQuality.Q_480P]:exports.Quality.Q480P,[l.VideoQuality.Q_720P]:exports.Quality.Q720P,[l.VideoQuality.Q_1080P]:exports.Quality.Q1080P,[l.VideoQuality.Q_1440P]:exports.Quality.Q1440P,[l.VideoQuality.Q_2160P]:exports.Quality.Q2160P,[l.VideoQuality.Q_4320P]:exports.Quality.UNKNOWN}[t],L=t=>t&&{[l.HttpConnectionType.HTTP1]:exports.ConnectionType.HTTP1,[l.HttpConnectionType.HTTP2]:exports.ConnectionType.HTTP2,[l.HttpConnectionType.QUIC]:exports.ConnectionType.HTTP3}[t],X=t=>{if(t!==void 0)switch(t){case l.VideoFormat.MPEG:return exports.ContentType.MP4;case l.VideoFormat.DASH:case l.VideoFormat.DASH_LIVE:return exports.ContentType.DASH;case l.VideoFormat.DASH_SEP:return exports.ContentType.DASH_SEP;case l.VideoFormat.DASH_ONDEMAND:return exports.ContentType.ONDEMAND_DASH;case l.VideoFormat.DASH_WEBM:case l.VideoFormat.DASH_LIVE_WEBM:return exports.ContentType.WEBM;case l.VideoFormat.DASH_WEBM_AV1:return exports.ContentType.AV1;case l.VideoFormat.DASH_LIVE_CMAF:return exports.ContentType.ONDEMAND_DASH_LIVE;case l.VideoFormat.HLS:case l.VideoFormat.HLS_LIVE:return exports.ContentType.HLS;case l.VideoFormat.HLS_ONDEMAND:return exports.ContentType.ONDEMAND_HLS;case l.VideoFormat.HLS_LIVE_CMAF:return exports.ContentType.ONDEMAND_HLS_LIVE;case l.VideoFormat.WEB_RTC_LIVE:return exports.ContentType.WEBRTC;default:return r.assertNever(t)}},P=t=>{if(t!==void 0)switch(t){case l.Surface.NONE:case l.Surface.INLINE:return;case l.Surface.FULLSCREEN:return S.FULLSCREEN;case l.Surface.SECOND_SCREEN:return S.EXTERNAL;case l.Surface.PIP:return S.PIP;default:return r.assertNever(t)}},J=t=>{switch(t){case"slow-2g":return E.POOR;case"2g":return E.POOR;case"3g":return E.GOOD;case"4g":return E.EXCELLENT}};class Z{constructor(e){this.offset=void 0,this.offset=e}getOffset(){var e;return(e=this.offset)!==null&&e!==void 0?e:0}setOffset(e){this.offset=e}now(){var e;return Date.now()+((e=this.offset)!==null&&e!==void 0?e:0)}date(e=new Date){var s;return e.setTime(e.getTime()+((s=this.offset)!==null&&s!==void 0?s:0)),e}addServerTime(e,s){const i=Date.now(),o=e-i-s/2;if(Math.abs(o)<1e3){this.offset=0;return}this.offset===void 0?this.offset=Math.round(o):this.offset=Math.round(.2*o+(1-.2)*this.offset)}}const I=()=>Math.floor(Math.random()*2**32).toString(36).padStart(8,"0"),ee=t=>new r.Observable(e=>{const s=new r.Subscription,i=r.merge(r.fromEvent(window,"beforeunload"),t.events.willDestruct$),o=new r.ValueSubject(void 0);let a;s.add(t.info.isLive$.pipe(r.filterChanged()).subscribe(A=>{a&&(a.unsubscribe(),o.next(void 0)),A?a=t.info.liveTime$.pipe(r.map(w=>w&&w/1e3)).subscribe(o):a=t.info.position$.subscribe(o),s.add(a)}));const{playing$:u,paused$:f}=t.events,d=t.events.willSeek$.pipe(r.filter(()=>t.info.playbackState$.getValue()===l.PlaybackState.PLAYING)),c=t.events.seeked$.pipe(r.filter(()=>t.info.playbackState$.getValue()===l.PlaybackState.PLAYING));let n=!1;s.add(d.subscribe(()=>n=!0)),s.add(c.subscribe(()=>n=!1));const h=d.pipe(r.filter(()=>!n)),p=r.merge(u,c),y=r.merge(f,h,i,t.events.looped$);let b;return s.add(p.subscribe(()=>b=o.getValue())),s.add(y.subscribe(()=>{const A=o.getValue();r.isNullable(b)||b===A||r.isNullable(A)||(e.next({from:b,to:A}),b=void 0)})),s});class te{constructor(e,s){var i,o;this.subscription=new r.Subscription,this.vsid=I(),this.seekAction$=new r.ValueSubject(exports.SeekAction.UNKNOWN),this.statContext=e,this.config=U((i=s.config)!==null&&i!==void 0?i:{}),r.isNonNullable(s.apiEnv)&&(this.config.apiEnv=s.apiEnv),this.config.synchronizeTime&&(this.timeSynchronisation=new Z);const a=new r.Subject;this.experimental={error$:a};const u=new z({apiKey:M,config:this.config,error$:a,timeSynchronisation:this.timeSynchronisation});this.api=new W({config:this.config,apiTransport:u,refreshAuthToken:s.refreshAuthToken,mobile:(o=this.statContext.mobile)!==null&&o!==void 0?o:!1,error$:a}),this.logger=new j({config:this.config,api:this.api,error$:a,userSalt:s.userSalt});const{isEmbed:f,host:d}=G();this.isEmbed=f,this.embedParent=d,this.subscribe()}updateContext(e){this.statContext={...this.statContext,...e}}attachTo(e){const s=new r.Subscription,i=(n,h)=>s.add(n.subscribe(h));i(e.events.willStart$,()=>{this.logActionPlay({position:e.info.position$.getValue()})}),i(e.events.looped$,()=>{this.resetViewSession(),this.logActionPlay({position:e.info.position$.getValue()})}),i(e.events.seeked$,()=>{this.logSeek({action:this.seekAction$.getValue(),time:e.info.position$.getValue()}),this.seekAction$.next(exports.SeekAction.UNKNOWN)}),i(e.events.paused$,()=>{this.logPause({position:e.info.position$.getValue()})}),i(e.events.willResume$,()=>{this.logPlay()}),i(e.events.started$,()=>{this.statContext.clip&&this.logWatchCoverageRecord({start:0,end:0})}),i(ee(e),n=>{const h=e.info.isLive$.getValue(),p={start:parseFloat(n.from.toFixed(3)),end:parseFloat(n.to.toFixed(3))};h?this.logWatchCoverageLive(p):this.logWatchCoverageRecord(p)});let o;i(e.info.isStalled$,n=>{n?o=r.now():(r.isNonNullable(o)&&this.logEmptyBuffer({duration:r.now()-o}),o=void 0)});let a=!1;s.add(e.events.fatalError$.pipe(r.once()).subscribe(()=>a=!0)),i(e.events.willStop$,()=>{if(e.info.isStalled$.getValue()){const h=r.isNonNullable(o)?r.now()-o:void 0;this.logCloseAtEmptyBuffer({duration:h!=null?h:0}),o=void 0}else a||this.logActionStop()}),i(e.events.managedError$,({id:n})=>{this.logError({fatal:!1,errorType:n})}),i(e.events.fatalError$,({id:n})=>{this.logError({fatal:!0,errorType:n})});let u,f,d=!1;i(e.events.firstBytes$,n=>{u=r.now(),this.logFirstBytes({time:n})}),i(e.events.willStart$,()=>f=r.now()),i(e.info.currentBuffer$,n=>{!d&&n&&n.end-n.start>0&&r.isNonNullable(u)&&(this.logPlayerReady({duration:r.now()-u}),d=!0)}),i(e.events.firstFrame$,()=>{r.isNonNullable(u)&&!d&&(this.logPlayerReady({duration:r.now()-u}),d=!0),r.isNonNullable(f)&&this.logFirstFrame({time:r.now()-f})}),i(e.info.atLiveEdge$,n=>this.updateContext({liveEdge:n})),i(r.combine({muted:e.info.muted$,volume:e.info.volume$}),({muted:n,volume:h})=>this.updateContext({audible:!n&&h>0})),i(e.info.currentQuality$,n=>this.updateContext({quality:Y(n)})),i(e.info.isAutoQualityEnabled$,n=>this.updateContext({autoQuality:n})),i(e.info.currentFormat$,n=>this.updateContext({contentType:X(n)}));let c;return i(e.info.hostname$,n=>{this.updateContext({cdnHostname:n,failover:c!==void 0&&c!==n}),c=n}),i(e.info.throughputEstimation$,n=>this.updateContext({downloadSpeed:n})),i(e.info.httpConnectionType$,n=>{this.statContext.firstConnectionType||this.updateContext({firstConnectionType:L(n)}),this.updateContext({connectionType:L(n)})}),i(e.info.httpConnectionReused$,n=>{r.isNullable(this.statContext.firstConnectionReused)&&this.updateContext({firstConnectionReused:n}),this.updateContext({connectionReused:n})}),i(e.info.surface$,n=>this.updateContext({mode:P(n)})),i(r.combine({current:e.info.currentTextTrack$,available:e.info.availableTextTracks$}),({current:n,available:h})=>{const p=h.find(({id:y})=>y===n);this.updateContext({subtitles:p==null?void 0:p.language})}),this.player=e,this.uiEvents&&this.attachToUi(this.uiEvents),this.resubscribeBeforeunload(),this.subscription.add(s),s}attachToUi(e){this.uiEvents=e;const s=new r.Subscription;return this.player&&(s.add(e.actionRewind$.subscribe(()=>{this.player&&(this.resetViewSession(),this.logActionPlay({position:this.player.info.position$.getValue()}))})),s.add(e.actionSeek$.subscribe(this.seekAction$)),s.add(e.inPiP$.subscribe(i=>{var o;const a=i?S.PIP:P((o=this.player)===null||o===void 0?void 0:o.info.surface$.getValue());this.updateContext({mode:a})})),s.add(e.inFullscreen$.subscribe(i=>{var o;const a=i?S.FULLSCREEN:P((o=this.player)===null||o===void 0?void 0:o.info.surface$.getValue());this.updateContext({mode:a})})),s.add(e.actionSetSubtitle$.subscribe(i=>{this.updateContext({subtitles:i})})),s.add(e.nextMovie$.subscribe(i=>this.logNextMovie(i))),this.resubscribeBeforeunload(),this.subscription.add(s)),s}attachToAds(e){const s=new r.Subscription;return s.add(e.slotRequested$.subscribe(()=>this.logAdSlotRequest())).add(e.started$.subscribe(i=>this.logAdStarted(i))).add(e.paused$.subscribe(()=>this.logAdPaused())).add(e.resumed$.subscribe(()=>this.logAdResumed())).add(e.ended$.subscribe(()=>this.logAdEnded())).add(e.skipped$.subscribe(()=>this.logAdSkipped())).add(e.clicked$.subscribe(()=>this.logAdClicked())),this.resubscribeBeforeunload(),this.subscription.add(s),s}attachToInteractive(e){const s=new r.Subscription;return s.add(e.click$.subscribe(i=>this.logInterfaceClick(i))).add(e.nextMovie$.subscribe(i=>this.logNextMovie(i))),this.resubscribeBeforeunload(),this.subscription.add(s),s}authorize(e){return this.api.authorize(e)}pause(){this.logger.pause()}resume(){this.logger.resume()}destroy(){this.logger.flush(),this.subscription.unsubscribe(),this.api.destroy(),this.logger.destroy()}resetViewSession(){this.vsid=I()}setFieldBlacklist(){}logInited(){}logReady(e){this.log({operation:"player_ready",param:String(e.time)})}logStarted(...e){this.logActionPlay(...e)}logPlay(){this.log({operation:"play_toggle"})}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}`})}logWatchCoverageLive(e){var s,i;const o=(i=(s=this.timeSynchronisation)===null||s===void 0?void 0:s.getOffset())!==null&&i!==void 0?i:0,a=e.start+o,u=e.end+o;this.log({operation:"watch_coverage_live",param:`${a}-${u}`})}logEmptyBuffer(e){this.log({operation:"empty_buffer",param:String(e.duration)})}logDownloadSpeed(){}logAdSlotRequest(){this.log({operation:"adv",param:"slot_request"})}logAdStarted(e){this.log({operation:"adv",param:e})}logAdPaused(){this.log({operation:"adv",param:"pause"})}logAdResumed(){this.log({operation:"adv",param:"resume"})}logAdEnded(){this.log({operation:"adv",param:"ended"})}logAdSkipped(){this.log({operation:"adv",param:"skip"})}logAdClicked(){this.log({operation:"adv",param:"click"})}logInterfaceClick(e){this.log({operation:"player_interface_click",param:e})}logNextMovie(e){this.log({operation:"next_movie",param:String(e)})}subscribe(){this.resubscribeBeforeunload();const e=window.navigator.connection;e&&"onchange"in e&&"effectiveType"in e&&this.subscription.add(r.merge(r.fromEvent(e,"change"),r.observableFrom(["init"])).subscribe(()=>this.updateContext({network:J(e.effectiveType)})))}resubscribeBeforeunload(){var e;(e=this.beforeunloadSubscription)===null||e===void 0||e.unsubscribe(),this.beforeunloadSubscription=r.fromEvent(window,"beforeunload").subscribe(()=>this.logger.flush(!0)),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))})}logCloseAtEmptyBuffer(e){this.log({operation:"close_at_empty_buffer",param:String(Math.round(e.duration))})}logActionStop(){this.log({operation:"action_stop"})}log(e){if(this.config.disabledOperations.includes(e.operation))return;const s=this.createLogItem(e);this.logger.log(s)}createLogItem({operation:e,param:s,time:i}){var o,a;const u=(a=(o=this.timeSynchronisation)===null||o===void 0?void 0:o.now())!==null&&a!==void 0?a:r.now(),f=e==="empty_buffer"||e==="close_at_empty_buffer"?this.statContext.connectionType:this.statContext.firstConnectionType,d=this.statContext.firstConnectionReused,c={vsid:this.vsid,vid:this.statContext.movieId,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?v.AUTO:this.statContext.autoplay===!1?v.MANUAL:void 0,param:s,vk_app_id:this.statContext.vkAppId,track_code:this.statContext.trackCode,connection_type:f,connection_reused:d===!0?g.YES:d===!1?g.NO:void 0,cached_data:this.statContext.cached===!0?g.YES:this.statContext.cached===!1?g.NO:void 0,live:this.statContext.liveEdge?g.YES:void 0,muted:this.statContext.audible===!1?g.YES:void 0,mode:this.statContext.mode,subtitles:this.statContext.subtitles,download_speed:this.statContext.downloadSpeed,manual_quality:this.statContext.autoQuality?void 0:g.YES,ref_domain:this.embedParent,aid:this.statContext.albumId,vk_playlist_id:this.statContext.vkPlaylistId};for(const n of this.config.disabledCustomFields)delete c[n];return{operation:e,type:1,time:i,network:this.statContext.network,timestamp:u,custom:c}}}exports.OneStat=te;exports.VERSION=N;
|
|
6
|
+
"use strict";var a=require("@vkontakte/videoplayer-shared/es2018.cjs.js"),_e=require("lodash/debounce.js"),v=require("@vkontakte/videoplayer-core/es2018.cjs.js");exports.ApiEnv=void 0;(function(t){t.PROD="prod",t.VK_ALIAS="vk_alias",t.VIDEOTEST="videotest",t.TEST="test",t.AUTO="auto"})(exports.ApiEnv||(exports.ApiEnv={}));exports.Quality=void 0;(function(t){t.Q144P="mobile",t.Q240P="lowest",t.Q360P="low",t.Q480P="medium",t.Q720P="high",t.Q1080P="fullhd",t.Q1440P="quadhd",t.Q2160P="ultrahd",t.UNKNOWN="unknown"})(exports.Quality||(exports.Quality={}));exports.ContentType=void 0;(function(t){t.MP4="mp4",t.DASH="dash",t.DASH_SEP="dash_sep",t.ONDEMAND_DASH="ondemand_dash",t.HLS="hls",t.ONDEMAND_HLS="ondemand_hls",t.WEBM="webm",t.AV1="av1",t.ONDEMAND_DASH_LIVE="ondemand_dash_live",t.ONDEMAND_HLS_LIVE="ondemand_hls_live",t.WEBRTC="webrtc",t.UNKNOWN="unknown",t.RTMP="rtmp"})(exports.ContentType||(exports.ContentType={}));var H;(function(t){t.AUTO="auto",t.MANUAL=""})(H||(H={}));exports.ConnectionType=void 0;(function(t){t.HTTP1="http1",t.HTTP2="http2",t.HTTP3="http3"})(exports.ConnectionType||(exports.ConnectionType={}));var S;(function(t){t[t.YES=1]="YES",t[t.NO=0]="NO"})(S||(S={}));var C;(function(t){t.EXCELLENT="excellent",t.GOOD="good",t.POOR="poor"})(C||(C={}));var w;(function(t){t.PIP="pip",t.FULLSCREEN="fullscreen",t.EXTERNAL="external",t.PREFETCH="prefetch"})(w||(w={}));exports.SeekAction=void 0;(function(t){t.SLIDER="slider",t.DOUBLE_TAP="double_tap",t.TIME_CODE="time_code",t.EPISODE="episode",t.REWIND="rewind",t.LIVE="live",t.UNKNOWN="unknown"})(exports.SeekAction||(exports.SeekAction={}));exports.InteractiveInterfaceClick=void 0;(function(t){t.GRAPH_SHOW="iGraphShow",t.GRAPH_HIDE="iGraphHide",t.NEXT_AREA="iNextChapterArea",t.NEXT_BUTTON="iNextChapterBtn",t.WATCH_AGAIN="iWatchAgainBtn"})(exports.InteractiveInterfaceClick||(exports.InteractiveInterfaceClick={}));const It={apiEnv:exports.ApiEnv.VK_ALIAS,requestRetryCount:1,firstFlushTime:5e3,flushDebounceTime:1e4,flushMaxWait:6e4,storageExpiration:36*60*60*1e3,disabledOperations:[],disabledCustomFields:[],useBeacon:!0,synchronizeTime:!0,backoff:{start:1e3,factor:1.5,max:5*60*1e3,random:.1}},xt=t=>a.fillWithDefault(t,It);var z=typeof globalThis!="undefined"?globalThis:typeof window!="undefined"?window:typeof global!="undefined"?global:typeof self!="undefined"?self:{};function Lt(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var F=function(t){return t&&t.Math==Math&&t},$=F(typeof globalThis=="object"&&globalThis)||F(typeof window=="object"&&window)||F(typeof self=="object"&&self)||F(typeof z=="object"&&z)||function(){return this}()||z||Function("return this")(),A=function(t){try{return!!t()}catch(e){return!0}},Dt=A,q=!Dt(function(){var t=function(){}.bind();return typeof t!="function"||t.hasOwnProperty("prototype")}),kt=q,Ze=Function.prototype,Te=Ze.apply,we=Ze.call,Ft=typeof Reflect=="object"&&Reflect.apply||(kt?we.bind(Te):function(){return we.apply(Te,arguments)}),et=q,tt=Function.prototype,ve=tt.call,Bt=et&&tt.bind.bind(ve,ve),_=et?Bt:function(t){return function(){return ve.apply(t,arguments)}},rt=_,jt=rt({}.toString),Ut=rt("".slice),K=function(t){return Ut(jt(t),8,-1)},Mt=K,Vt=_,ot=function(t){if(Mt(t)==="Function")return Vt(t)},pe=typeof document=="object"&&document.all,Ht=typeof pe=="undefined"&&pe!==void 0,it={all:pe,IS_HTMLDDA:Ht},nt=it,Wt=nt.all,E=nt.IS_HTMLDDA?function(t){return typeof t=="function"||t===Wt}:function(t){return typeof t=="function"},at={},qt=A,I=!qt(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!=7}),Kt=q,B=Function.prototype.call,x=Kt?B.bind(B):function(){return B.apply(B,arguments)},st={},lt={}.propertyIsEnumerable,ut=Object.getOwnPropertyDescriptor,Qt=ut&&!lt.call({1:2},1);st.f=Qt?function(e){var r=ut(this,e);return!!r&&r.enumerable}:lt;var ct=function(t,e){return{enumerable:!(t&1),configurable:!(t&2),writable:!(t&4),value:e}},Gt=_,zt=A,Yt=K,Y=Object,Xt=Gt("".split),Jt=zt(function(){return!Y("z").propertyIsEnumerable(0)})?function(t){return Yt(t)=="String"?Xt(t,""):Y(t)}:Y,ye=function(t){return t==null},Zt=ye,er=TypeError,me=function(t){if(Zt(t))throw er("Can't call method on "+t);return t},tr=Jt,rr=me,or=function(t){return tr(rr(t))},Ae=E,dt=it,ir=dt.all,L=dt.IS_HTMLDDA?function(t){return typeof t=="object"?t!==null:Ae(t)||t===ir}:function(t){return typeof t=="object"?t!==null:Ae(t)},ft={},X=ft,J=$,nr=E,Oe=function(t){return nr(t)?t:void 0},ht=function(t,e){return arguments.length<2?Oe(X[t])||Oe(J[t]):X[t]&&X[t][e]||J[t]&&J[t][e]},ar=_,vt=ar({}.isPrototypeOf),sr=typeof navigator!="undefined"&&String(navigator.userAgent)||"",pt=$,Z=sr,Pe=pt.process,Ne=pt.Deno,Ce=Pe&&Pe.versions||Ne&&Ne.version,Re=Ce&&Ce.v8,y,W;Re&&(y=Re.split("."),W=y[0]>0&&y[0]<4?1:+(y[0]+y[1]));!W&&Z&&(y=Z.match(/Edge\/(\d+)/),(!y||y[1]>=74)&&(y=Z.match(/Chrome\/(\d+)/),y&&(W=+y[1])));var lr=W,Ie=lr,ur=A,cr=$,dr=cr.String,gt=!!Object.getOwnPropertySymbols&&!ur(function(){var t=Symbol();return!dr(t)||!(Object(t)instanceof Symbol)||!Symbol.sham&&Ie&&Ie<41}),fr=gt,bt=fr&&!Symbol.sham&&typeof Symbol.iterator=="symbol",hr=ht,vr=E,pr=vt,gr=bt,br=Object,yt=gr?function(t){return typeof t=="symbol"}:function(t){var e=hr("Symbol");return vr(e)&&pr(e.prototype,br(t))},yr=String,mr=function(t){try{return yr(t)}catch(e){return"Object"}},Sr=E,Er=mr,$r=TypeError,mt=function(t){if(Sr(t))return t;throw $r(Er(t)+" is not a function")},_r=mt,Tr=ye,St=function(t,e){var r=t[e];return Tr(r)?void 0:_r(r)},ee=x,te=E,re=L,wr=TypeError,Ar=function(t,e){var r,o;if(e==="string"&&te(r=t.toString)&&!re(o=ee(r,t))||te(r=t.valueOf)&&!re(o=ee(r,t))||e!=="string"&&te(r=t.toString)&&!re(o=ee(r,t)))return o;throw wr("Can't convert object to primitive value")},Et={exports:{}},xe=$,Or=Object.defineProperty,Pr=function(t,e){try{Or(xe,t,{value:e,configurable:!0,writable:!0})}catch(r){xe[t]=e}return e},Nr=$,Cr=Pr,Le="__core-js_shared__",Rr=Nr[Le]||Cr(Le,{}),Ir=Rr,De=Ir;(Et.exports=function(t,e){return De[t]||(De[t]=e!==void 0?e:{})})("versions",[]).push({version:"3.31.0",mode:"pure",copyright:"\xA9 2014-2023 Denis Pushkarev (zloirock.ru)",license:"https://github.com/zloirock/core-js/blob/v3.31.0/LICENSE",source:"https://github.com/zloirock/core-js"});var xr=Et.exports,Lr=me,Dr=Object,$t=function(t){return Dr(Lr(t))},kr=_,Fr=$t,Br=kr({}.hasOwnProperty),Q=Object.hasOwn||function(e,r){return Br(Fr(e),r)},jr=_,Ur=0,Mr=Math.random(),Vr=jr(1 .toString),Hr=function(t){return"Symbol("+(t===void 0?"":t)+")_"+Vr(++Ur+Mr,36)},Wr=$,qr=xr,ke=Q,Kr=Hr,Qr=gt,Gr=bt,R=Wr.Symbol,oe=qr("wks"),zr=Gr?R.for||R:R&&R.withoutSetter||Kr,D=function(t){return ke(oe,t)||(oe[t]=Qr&&ke(R,t)?R[t]:zr("Symbol."+t)),oe[t]},Yr=x,Fe=L,Be=yt,Xr=St,Jr=Ar,Zr=D,eo=TypeError,to=Zr("toPrimitive"),ro=function(t,e){if(!Fe(t)||Be(t))return t;var r=Xr(t,to),o;if(r){if(e===void 0&&(e="default"),o=Yr(r,t,e),!Fe(o)||Be(o))return o;throw eo("Can't convert object to primitive value")}return e===void 0&&(e="number"),Jr(t,e)},oo=ro,io=yt,_t=function(t){var e=oo(t,"string");return io(e)?e:e+""},no=$,je=L,ge=no.document,ao=je(ge)&&je(ge.createElement),so=function(t){return ao?ge.createElement(t):{}},lo=I,uo=A,co=so,Tt=!lo&&!uo(function(){return Object.defineProperty(co("div"),"a",{get:function(){return 7}}).a!=7}),fo=I,ho=x,vo=st,po=ct,go=or,bo=_t,yo=Q,mo=Tt,Ue=Object.getOwnPropertyDescriptor;at.f=fo?Ue:function(e,r){if(e=go(e),r=bo(r),mo)try{return Ue(e,r)}catch(o){}if(yo(e,r))return po(!ho(vo.f,e,r),e[r])};var So=A,Eo=E,$o=/#|\.prototype\./,k=function(t,e){var r=To[_o(t)];return r==Ao?!0:r==wo?!1:Eo(e)?So(e):!!e},_o=k.normalize=function(t){return String(t).replace($o,".").toLowerCase()},To=k.data={},wo=k.NATIVE="N",Ao=k.POLYFILL="P",Oo=k,Me=ot,Po=mt,No=q,Co=Me(Me.bind),Ro=function(t,e){return Po(t),e===void 0?t:No?Co(t,e):function(){return t.apply(e,arguments)}},wt={},Io=I,xo=A,Lo=Io&&xo(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!=42}),Do=L,ko=String,Fo=TypeError,At=function(t){if(Do(t))return t;throw Fo(ko(t)+" is not an object")},Bo=I,jo=Tt,Uo=Lo,j=At,Ve=_t,Mo=TypeError,ie=Object.defineProperty,Vo=Object.getOwnPropertyDescriptor,ne="enumerable",ae="configurable",se="writable";wt.f=Bo?Uo?function(e,r,o){if(j(e),r=Ve(r),j(o),typeof e=="function"&&r==="prototype"&&"value"in o&&se in o&&!o[se]){var i=Vo(e,r);i&&i[se]&&(e[r]=o.value,o={configurable:ae in o?o[ae]:i[ae],enumerable:ne in o?o[ne]:i[ne],writable:!1})}return ie(e,r,o)}:ie:function(e,r,o){if(j(e),r=Ve(r),j(o),jo)try{return ie(e,r,o)}catch(i){}if("get"in o||"set"in o)throw Mo("Accessors not supported");return"value"in o&&(e[r]=o.value),e};var Ho=I,Wo=wt,qo=ct,Ko=Ho?function(t,e,r){return Wo.f(t,e,qo(1,r))}:function(t,e,r){return t[e]=r,t},U=$,Qo=Ft,Go=ot,zo=E,Yo=at.f,Xo=Oo,O=ft,Jo=Ro,P=Ko,He=Q,Zo=function(t){var e=function(r,o,i){if(this instanceof e){switch(arguments.length){case 0:return new t;case 1:return new t(r);case 2:return new t(r,o)}return new t(r,o,i)}return Qo(t,this,arguments)};return e.prototype=t.prototype,e},ei=function(t,e){var r=t.target,o=t.global,i=t.stat,s=t.proto,l=o?U:i?U[r]:(U[r]||{}).prototype,h=o?O:O[r]||P(O,r,{})[r],c=h.prototype,u,n,d,f,p,g,b,m,G;for(f in e)u=Xo(o?f:r+(i?".":"#")+f,t.forced),n=!u&&l&&He(l,f),g=h[f],n&&(t.dontCallGetSet?(G=Yo(l,f),b=G&&G.value):b=l[f]),p=n&&b?b:e[f],!(n&&typeof g==typeof p)&&(t.bind&&n?m=Jo(p,U):t.wrap&&n?m=Zo(p):s&&zo(p)?m=Go(p):m=p,(t.sham||p&&p.sham||g&&g.sham)&&P(m,"sham",!0),P(h,f,m),s&&(d=r+"Prototype",He(O,d)||P(O,d,{}),P(O[d],f,p),t.real&&c&&(u||!c[f])&&P(c,f,p)))},ti=L,ri=K,oi=D,ii=oi("match"),ni=function(t){var e;return ti(t)&&((e=t[ii])!==void 0?!!e:ri(t)=="RegExp")},ai=D,si=ai("toStringTag"),Ot={};Ot[si]="z";var li=String(Ot)==="[object z]",ui=li,ci=E,V=K,di=D,fi=di("toStringTag"),hi=Object,vi=V(function(){return arguments}())=="Arguments",pi=function(t,e){try{return t[e]}catch(r){}},gi=ui?V:function(t){var e,r,o;return t===void 0?"Undefined":t===null?"Null":typeof(r=pi(e=hi(t),fi))=="string"?r:vi?V(e):(o=V(e))=="Object"&&ci(e.callee)?"Arguments":o},bi=gi,yi=String,mi=function(t){if(bi(t)==="Symbol")throw TypeError("Cannot convert a Symbol value to a string");return yi(t)},Si=At,Ei=function(){var t=Si(this),e="";return t.hasIndices&&(e+="d"),t.global&&(e+="g"),t.ignoreCase&&(e+="i"),t.multiline&&(e+="m"),t.dotAll&&(e+="s"),t.unicode&&(e+="u"),t.unicodeSets&&(e+="v"),t.sticky&&(e+="y"),e},$i=x,_i=Q,Ti=vt,wi=Ei,We=RegExp.prototype,Ai=function(t){var e=t.flags;return e===void 0&&!("flags"in We)&&!_i(t,"flags")&&Ti(We,t)?$i(wi,t):e},Se=_,Oi=$t,Pi=Math.floor,le=Se("".charAt),Ni=Se("".replace),ue=Se("".slice),Ci=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,Ri=/\$([$&'`]|\d{1,2})/g,Ii=function(t,e,r,o,i,s){var l=r+t.length,h=o.length,c=Ri;return i!==void 0&&(i=Oi(i),c=Ci),Ni(s,c,function(u,n){var d;switch(le(n,0)){case"$":return"$";case"&":return t;case"`":return ue(e,0,r);case"'":return ue(e,l);case"<":d=i[ue(n,1,-1)];break;default:var f=+n;if(f===0)return u;if(f>h){var p=Pi(f/10);return p===0?u:p<=h?o[p-1]===void 0?le(n,1):o[p-1]+le(n,1):u}d=o[f-1]}return d===void 0?"":d})},xi=ei,Li=x,Ee=_,qe=me,Di=E,ki=ye,Fi=ni,N=mi,Bi=St,ji=Ai,Ui=Ii,Mi=D,Vi=Mi("replace"),Hi=TypeError,Pt=Ee("".indexOf),Wi=Ee("".replace),Ke=Ee("".slice),qi=Math.max,Qe=function(t,e,r){return r>t.length?-1:e===""?r:Pt(t,e,r)};xi({target:"String",proto:!0},{replaceAll:function(e,r){var o=qe(this),i,s,l,h,c,u,n,d,f,p=0,g=0,b="";if(!ki(e)){if(i=Fi(e),i&&(s=N(qe(ji(e))),!~Pt(s,"g")))throw Hi("`.replaceAll` does not allow non-global regexes");if(l=Bi(e,Vi),l)return Li(l,e,o,r);if(i)return Wi(N(o),e,r)}for(h=N(o),c=N(e),u=Di(r),u||(r=N(r)),n=c.length,d=qi(1,n),p=Qe(h,c,0);p!==-1;)f=u?N(r(c,p,h)):Ui(c,h,p,[],void 0,r),b+=Ke(h,g,p)+f,g=p+n,p=Qe(h,c,p+d);return g<h.length&&(b+=Ke(h,g)),b}});var Ki=ht,Qi=Ki,Gi=Qi,zi=Gi("String","replaceAll"),Yi=zi,Xi=Yi,Ji=Xi,Zi=Ji,en=Lt(Zi);function tn(){const t="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".split(""),e=new Array(36);let r=0,o,i;for(i=0;i<36;i++)i===8||i===13||i===18||i===23?e[i]="-":i===14?e[i]="4":(r<=2&&(r=33554432+Math.random()*16777216|0),o=r&15,r=r>>4,e[i]=t[i===19?o&3|8:o]);return e.join("")}const be="1.0.39",rn="CIOPGQJGDIHBABABA",Ge={[exports.ApiEnv.PROD]:"https://api.ok.ru",[exports.ApiEnv.VK_ALIAS]:"https://api.mycdn.me",[exports.ApiEnv.VIDEOTEST]:"https://videotestapi.ok.ru/api",[exports.ApiEnv.TEST]:"https://apitest.ok.ru",[exports.ApiEnv.AUTO]:""},on="_one-stat_",ce=`${on}uuid`;var T;(function(t){t[t.PARAM_SESSION_EXPIRED=102]="PARAM_SESSION_EXPIRED",t[t.PARAM_SESSION_KEY=103]="PARAM_SESSION_KEY",t[t.PARAM_SIGNATURE=104]="PARAM_SIGNATURE",t[t.AUTH_LOGIN=401]="AUTH_LOGIN"})(T||(T={}));class nn{constructor(e){this.consequentAuthErrors=0,this.authorized$=new a.ValueSubject(!1),this.params=e;const r=a.safeStorage.get(ce);r?r.startsWith('"')&&r.endsWith('"')?(this.uuid=en(r,'"',""),a.safeStorage.set(ce,this.uuid)):this.uuid=r:(this.uuid=tn(),a.safeStorage.set(ce,this.uuid))}async authorize(e){return this.authToken=e!=null?e:await this.refreshAuthToken(),this._authorizeWithBackoff()}logBeacon(e){const r="log.externalLog",o=this.createLogParams(e),i=this.sessionKey;if(!i)return;this.params.apiTransport.sendBeacon(r,o,i)||this.logRequest(e)}async logRequest(e){var r;const o="log.externalLog",i=this.createLogParams(e),s=(r=this.sessionKey)!==null&&r!==void 0?r:await this._authorizeWithBackoff();if(!s)return;const l=async(h,c=this.params.config.requestRetryCount)=>{try{return await this.params.apiTransport.sendRequest(o,i,s)}catch(u){if(!u||!("error_code"in u)){this.params.error$.next({id:"logRequestUnknown",category:a.ErrorCategory.NETWORK,message:`Unknown ${o} error`,thrown:u});return}const n=u==null?void 0:u.error_code;switch(n){case T.PARAM_SESSION_EXPIRED:case T.PARAM_SESSION_KEY:case T.PARAM_SIGNATURE:return this.authorized$.next(!1),this.sessionKey=await this._authorizeWithBackoff(),c>0?l(h,c-1):void 0;case T.AUTH_LOGIN:return this.authorized$.next(!1),this.authToken=await this.refreshAuthToken(),this.sessionKey=await this._authorizeWithBackoff(),c>0?l(h,c-1):void 0;default:{this.params.error$.next({id:`LogRequest#${n}`,category:a.ErrorCategory.EXTERNAL_API,message:`${o} error`,data:u});return}}}};return l(e)}destroy(){window.clearTimeout(this.backoffTimeoutId),this.backoffTimeoutId=0}async refreshAuthToken(){if(this.params.refreshAuthToken)return this.refreshAuthTokenPromise||(this.refreshAuthTokenPromise=this.params.refreshAuthToken().finally(()=>{this.refreshAuthTokenPromise=void 0})),this.refreshAuthTokenPromise}createLogParams(e){return{collector:"ok.mobile.apps.video",data:JSON.stringify({application:`@vkontakte/videoplayer-statistics:${be}`,platform:this.params.mobile?"M_WEB":"WEB",items:e})}}_authorizeWithBackoff(){if(!this.consequentAuthErrors)return this._authorize();const e=a.getExponentialDelay(this.consequentAuthErrors,this.params.config.backoff);return new Promise(r=>{this.backoffTimeoutId||(this.backoffTimeoutId=window.setTimeout(()=>{this._authorize().then(r).catch(o=>this.params.error$.next({id:"AuthorizeBackoff",category:a.ErrorCategory.NETWORK,message:"Otherwise unhandled error in authorization",thrown:o})).finally(()=>this.backoffTimeoutId=0)},e))})}async _authorize(){if(this.authorizePromise)return this.authorizePromise;this.sessionKey=void 0,this.authorized$.next(!1);const e="auth.anonymLogin",r={session_data:{version:2,device_id:this.uuid,client_version:be.split("-")[0],client_type:"SDK_JS"}};return this.authToken!==void 0&&(r.session_data.auth_token=this.authToken,r.session_data.version=3),this.authorizePromise=this.params.apiTransport.sendRequest(e,r).then(o=>{var i;return(!o||!o.session_key)&&this.params.error$.next({id:"AuthorizeFailed",category:a.ErrorCategory.EXTERNAL_API,message:"No session key",data:o}),this.sessionKey=(i=o==null?void 0:o.session_key)!==null&&i!==void 0?i:void 0,this.sessionKey}).catch(async o=>{this.sessionKey=void 0;const i=o==null?void 0:o.error_code;switch(i){case T.AUTH_LOGIN:return this.authToken=await this.refreshAuthToken(),this._authorizeWithBackoff()}i?this.params.error$.next({id:`Authorize#${i}`,category:a.ErrorCategory.EXTERNAL_API,message:"authorize error",data:o}):this.params.error$.next({id:"AuthorizeUnknown",category:a.ErrorCategory.NETWORK,message:"authorize error",thrown:o})}).finally(()=>{this.authorizePromise=void 0,this.consequentAuthErrors=this.sessionKey?0:this.consequentAuthErrors+1,this.authorized$.next(this.sessionKey!==void 0)}),this.authorizePromise}}class ze{constructor(){Object.defineProperty(this,"listeners",{value:{},writable:!0,configurable:!0})}addEventListener(e,r,o){e in this.listeners||(this.listeners[e]=[]),this.listeners[e].push({callback:r,options:o})}removeEventListener(e,r){if(!(e in this.listeners))return;const o=this.listeners[e];for(let i=0,s=o.length;i<s;i++)if(o[i].callback===r){o.splice(i,1);return}}dispatchEvent(e){if(!(e.type in this.listeners))return;const o=this.listeners[e.type].slice();for(let i=0,s=o.length;i<s;i++){const l=o[i];try{l.callback.call(this,e)}catch(h){Promise.resolve().then(()=>{throw h})}l.options&&l.options.once&&this.removeEventListener(e.type,l.callback)}return!e.defaultPrevented}}class Nt extends ze{constructor(){super(),this.listeners||ze.call(this),Object.defineProperty(this,"aborted",{value:!1,writable:!0,configurable:!0}),Object.defineProperty(this,"onabort",{value:null,writable:!0,configurable:!0}),Object.defineProperty(this,"reason",{value:void 0,writable:!0,configurable:!0})}toString(){return"[object AbortSignal]"}dispatchEvent(e){e.type==="abort"&&(this.aborted=!0,typeof this.onabort=="function"&&this.onabort.call(this,e)),super.dispatchEvent(e)}}class an{constructor(){Object.defineProperty(this,"signal",{value:new Nt,writable:!0,configurable:!0})}abort(e){let r;try{r=new Event("abort")}catch(i){typeof document!="undefined"?document.createEvent?(r=document.createEvent("Event"),r.initEvent("abort",!1,!1)):(r=document.createEventObject(),r.type="abort"):r={type:"abort",bubbles:!1,cancelable:!1}}let o=e;if(o===void 0)if(typeof document=="undefined")o=new Error("This operation was aborted"),o.name="AbortError";else try{o=new DOMException("signal is aborted without reason")}catch(i){o=new Error("This operation was aborted"),o.name="AbortError"}this.signal.reason=o,this.signal.dispatchEvent(r)}toString(){return"[object AbortController]"}}typeof Symbol!="undefined"&&Symbol.toStringTag&&(an.prototype[Symbol.toStringTag]="AbortController",Nt.prototype[Symbol.toStringTag]="AbortSignal");function Ct(t){return t.__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL?(console.log("__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL=true is set, will force install polyfill"),!0):typeof t.Request=="function"&&!t.Request.prototype.hasOwnProperty("signal")||!t.AbortController}function sn(t){typeof t=="function"&&(t={fetch:t});const{fetch:e,Request:r=e.Request,AbortController:o,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:i=!1}=t;if(!Ct({fetch:e,Request:r,AbortController:o,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:i}))return{fetch:e,Request:s};let s=r;(s&&!s.prototype.hasOwnProperty("signal")||i)&&(s=function(u,n){let d;n&&n.signal&&(d=n.signal,delete n.signal);const f=new r(u,n);return d&&Object.defineProperty(f,"signal",{writable:!1,enumerable:!1,configurable:!0,value:d}),f},s.prototype=r.prototype);const l=e;return{fetch:(c,u)=>{const n=s&&s.prototype.isPrototypeOf(c)?c.signal:u?u.signal:void 0;if(n){let d;try{d=new DOMException("Aborted","AbortError")}catch(p){d=new Error("Aborted"),d.name="AbortError"}if(n.aborted)return Promise.reject(d);const f=new Promise((p,g)=>{n.addEventListener("abort",()=>g(d),{once:!0})});return u&&u.signal&&delete u.signal,Promise.race([f,l(c,u)])}return l(c,u)},Request:s}}const $e=Ct({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),Rt=$e?sn({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,Ye=$e?Rt.fetch:window.fetch;$e?Rt.Request:window.Request;class ln{constructor(e){this.params=e,this.apiKey=e.apiKey,this.apiEnv=e.config.apiEnv,this.apiBaseUrl=Ge[this.apiEnv],this.timeSynchronisation=e.timeSynchronisation,this.isApiBaseUrlFetched=!1}async resolveApiBaseUrl(){var e;if(this.apiEnv!==exports.ApiEnv.AUTO||this.isApiBaseUrlFetched)return this.apiBaseUrl;try{const r=atob("aHR0cHM6Ly9kbnMuZ29vZ2xlL3Jlc29sdmU/bmFtZT12aWRlby5fZW5kcG9pbnQub2sucnUmdHlwZT1UWFQ="),i=await(await Ye(r,{method:"GET",mode:"cors",cache:"no-cache"})).json(),s=(e=i==null?void 0:i.Answer[0])===null||e===void 0?void 0:e.data;if(!s)throw new Error("Wrong DNS response");return s}catch(r){return this.params.error$.next({id:"OneStat:ApiTransport:resolveApiBaseUrl",category:a.ErrorCategory.NETWORK,message:"Unhandled resolve api base url error",thrown:r}),Ge[exports.ApiEnv.VK_ALIAS]}finally{this.isApiBaseUrlFetched=!0}}sendBeacon(e,r,o){if(!window.Blob||!window.navigator.sendBeacon)return!1;const i=this._prepareQueryParams({method:e,queryParams:r,sessionKey:o}),s=new window.Blob([i.toString()],{type:"application/x-www-form-urlencoded"});try{return window.navigator.sendBeacon(`${this.apiBaseUrl}/fb.do`,s)}catch(l){this.params.error$.next({id:"OneStat:ApiTransport:sendBeacon",category:a.ErrorCategory.NETWORK,message:"Unhandled beacon error",thrown:l,data:{method:e,params:r}})}return!1}async sendRequest(e,r,o){const i=a.now(),s=l=>{if(l instanceof TypeError&&["Failed to fetch","NetworkError when attempting to fetch resource."].includes(l.message)){this.params.error$.next({id:"Network",category:a.ErrorCategory.NETWORK,message:"Request failed",thrown:l});return}this.params.error$.next({id:"OneStat:ApiTransport:sendRequest",category:a.ErrorCategory.NETWORK,message:"Unhandled request error",thrown:l,data:{method:e,params:r,sessionKey:o,time:a.now()-i}})};return this.apiBaseUrl=await this.resolveApiBaseUrl(),Ye(`${this.apiBaseUrl}/fb.do`,{method:"post",headers:{"Content-type":"application/x-www-form-urlencoded"},body:this._prepareQueryParams({method:e,queryParams:r,sessionKey:o})}).then(l=>{var h,c;const u=Number(l.headers.get("content-length"))===0,n=new Date((h=l.headers.get("date"))!==null&&h!==void 0?h:"").getTime(),d=a.now()-i;if(isFinite(n)&&((c=this.timeSynchronisation)===null||c===void 0||c.addServerTime(n,d)),!u)return l.json().then(f=>Object.prototype.hasOwnProperty.call(f,"error_msg")?Promise.reject(f):f,s)},s)}_prepareQueryParams(e){const r=new URLSearchParams({format:"JSON",method:e.method,application_key:this.apiKey});return e.sessionKey!==void 0&&r.append("session_key",e.sessionKey),Object.entries(e.queryParams).forEach(([o,i])=>r.append(o,typeof i=="string"?i:JSON.stringify(i))),r}}const M="onestat_events",de=t=>e=>e.timestamp+t>=a.now();class un{constructor(e){this.unsaltedStorage=[],this.isPaused=!1,this.isUrgent=o=>{const{operation:i,custom:{param:s}}=o;return["action_stop","close_at_empty_buffer"].includes(i)||i==="watch_coverage_record"&&s==="0-0"},this.params=e,this.api=e.api,this.error$=e.error$,this.userSalt=e.userSalt,this.firstFlush=_e(()=>this.safeFlush(),this.params.config.firstFlushTime,{maxWait:this.params.config.firstFlushTime});const r=a.safeStorage.isPersistent()?this.params.config.flushMaxWait:0;this.debouncedFlush=_e(()=>this.safeFlush(),this.params.config.flushDebounceTime,{maxWait:r}),this.subscription=this.api.authorized$.subscribe(o=>{o&&this.debouncedFlush()}),this.housekeepStorage()}safeFlush(){var e;try{this.flush()}catch(r){this.error$.next({id:"LoggerError",category:a.ErrorCategory.WTF,message:(e=String(r))!==null&&e!==void 0?e:"Unknown logger error",thrown:r})}}readFromStorage(){const e=a.safeStorage.get(M);try{return e?JSON.parse(e):{}}catch(r){}return{}}addToStorage(e){var r;if(!this.userSalt){this.unsaltedStorage.push(e);return}const o=this.readFromStorage(),s=((r=o[this.userSalt])!==null&&r!==void 0?r:[]).filter(de(this.params.config.storageExpiration));a.safeStorage.set(M,JSON.stringify({...o,[this.userSalt]:[...s,e]}))}getFromStorage(){var e;return this.userSalt?((e=this.readFromStorage()[this.userSalt])!==null&&e!==void 0?e:[]).filter(de(this.params.config.storageExpiration)):this.unsaltedStorage}markStorageSent(){if(!this.userSalt){this.unsaltedStorage=[];return}const e=this.readFromStorage();delete e[this.userSalt],a.safeStorage.set(M,JSON.stringify(e))}housekeepStorage(){const e=this.readFromStorage();for(const[r,o]of Object.entries(e)){const i=o.filter(de(this.params.config.storageExpiration));i.length?e[r]=i:delete e[r]}a.safeStorage.set(M,JSON.stringify(e))}log(e){this.addToStorage(e),!this.isPaused&&(this.isUrgent(e)?this.flush():this.lastVsid!==e.custom.vsid?this.firstFlush():this.debouncedFlush(),this.lastVsid=e.custom.vsid)}flush(e=!1){const r=this.getFromStorage();r.length!==0&&(this.api.authorized$.getValue()?(e&&this.params.config.useBeacon?this.api.logBeacon(r):this.api.logRequest(r),this.markStorageSent()):this.api.authorize(),this.firstFlush.cancel(),this.debouncedFlush.cancel())}pause(){this.isPaused=!0,this.debouncedFlush.cancel()}resume(){this.isPaused=!1,this.debouncedFlush()}destroy(){this.subscription.unsubscribe(),this.firstFlush.cancel(),this.debouncedFlush.cancel()}}const cn=()=>{let t,e;try{t=window.self!==window.top}catch(o){o instanceof DOMException&&o.name==="SecurityError"?t=!0:(t=!1,console.error(o))}try{window.location.ancestorOrigins&&(e=window.location.ancestorOrigins[window.location.ancestorOrigins.length-1])}catch(o){console.error(o)}try{!e&&document.referrer&&(e=document.referrer)}catch(o){console.error(o)}const r=e?new URL(e).hostname:void 0;return{isEmbed:t,host:r}},dn=t=>t&&{[v.VideoQuality.INVARIANT]:exports.Quality.UNKNOWN,[v.VideoQuality.Q_144P]:exports.Quality.Q144P,[v.VideoQuality.Q_240P]:exports.Quality.Q240P,[v.VideoQuality.Q_360P]:exports.Quality.Q360P,[v.VideoQuality.Q_480P]:exports.Quality.Q480P,[v.VideoQuality.Q_720P]:exports.Quality.Q720P,[v.VideoQuality.Q_1080P]:exports.Quality.Q1080P,[v.VideoQuality.Q_1440P]:exports.Quality.Q1440P,[v.VideoQuality.Q_2160P]:exports.Quality.Q2160P,[v.VideoQuality.Q_4320P]:exports.Quality.UNKNOWN}[t],Xe=t=>t&&{[v.HttpConnectionType.HTTP1]:exports.ConnectionType.HTTP1,[v.HttpConnectionType.HTTP2]:exports.ConnectionType.HTTP2,[v.HttpConnectionType.QUIC]:exports.ConnectionType.HTTP3}[t],fn=t=>{if(t!==void 0)switch(t){case v.VideoFormat.MPEG:return exports.ContentType.MP4;case v.VideoFormat.DASH:case v.VideoFormat.DASH_LIVE:return exports.ContentType.DASH;case v.VideoFormat.DASH_SEP:return exports.ContentType.DASH_SEP;case v.VideoFormat.DASH_ONDEMAND:return exports.ContentType.ONDEMAND_DASH;case v.VideoFormat.DASH_WEBM:case v.VideoFormat.DASH_LIVE_WEBM:return exports.ContentType.WEBM;case v.VideoFormat.DASH_WEBM_AV1:return exports.ContentType.AV1;case v.VideoFormat.DASH_LIVE_CMAF:return exports.ContentType.ONDEMAND_DASH_LIVE;case v.VideoFormat.HLS:case v.VideoFormat.HLS_LIVE:return exports.ContentType.HLS;case v.VideoFormat.HLS_ONDEMAND:return exports.ContentType.ONDEMAND_HLS;case v.VideoFormat.HLS_LIVE_CMAF:return exports.ContentType.ONDEMAND_HLS_LIVE;case v.VideoFormat.WEB_RTC_LIVE:return exports.ContentType.WEBRTC;default:return a.assertNever(t)}},fe=t=>{if(t!==void 0)switch(t){case v.Surface.NONE:case v.Surface.INLINE:return;case v.Surface.FULLSCREEN:return w.FULLSCREEN;case v.Surface.SECOND_SCREEN:return w.EXTERNAL;case v.Surface.PIP:return w.PIP;default:return a.assertNever(t)}},hn=t=>{switch(t){case"slow-2g":return C.POOR;case"2g":return C.POOR;case"3g":return C.GOOD;case"4g":return C.EXCELLENT}};class vn{constructor(e){this.offset=void 0,this.offset=e}getOffset(){var e;return(e=this.offset)!==null&&e!==void 0?e:0}setOffset(e){this.offset=e}now(){var e;return Date.now()+((e=this.offset)!==null&&e!==void 0?e:0)}date(e=new Date){var r;return e.setTime(e.getTime()+((r=this.offset)!==null&&r!==void 0?r:0)),e}addServerTime(e,r){const o=Date.now(),i=e-o-r/2;if(Math.abs(i)<1e3){this.offset=0;return}this.offset===void 0?this.offset=Math.round(i):this.offset=Math.round(.2*i+(1-.2)*this.offset)}}const Je=()=>Math.floor(Math.random()*2**32).toString(36).padStart(8,"0"),pn=t=>new a.Observable(e=>{const r=new a.Subscription,o=a.merge(a.fromEvent(window,"beforeunload"),t.events.willDestruct$),i=new a.ValueSubject(void 0);let s;r.add(t.info.isLive$.pipe(a.filterChanged()).subscribe(b=>{s&&(s.unsubscribe(),i.next(void 0)),b?s=t.info.liveTime$.pipe(a.map(m=>m&&m/1e3)).subscribe(i):s=t.info.position$.subscribe(i),r.add(s)}));const{playing$:l,paused$:h}=t.events,c=t.events.willSeek$.pipe(a.filter(()=>t.info.playbackState$.getValue()===v.PlaybackState.PLAYING)),u=t.events.seeked$.pipe(a.filter(()=>t.info.playbackState$.getValue()===v.PlaybackState.PLAYING));let n=!1;const d=new a.Subject;r.add(c.subscribe(()=>{n||d.next(),n=!0})),r.add(u.subscribe(()=>n=!1));const f=a.merge(l,u),p=a.merge(h,d,o,t.events.looped$);let g;return r.add(f.subscribe(()=>g=i.getValue())),r.add(p.subscribe(()=>{const b=i.getValue();a.isNullable(g)||g===b||a.isNullable(b)||(e.next({from:g,to:b}),g=void 0)})),r}),he=()=>{const t=new a.Subscription;return{subscription:t,subscribe:(e,r)=>{e&&t.add(e.subscribe(r))}}};class gn{constructor(e,r){var o,i;this.subscription=new a.Subscription,this.vsid=Je(),this.seekAction$=new a.ValueSubject(exports.SeekAction.UNKNOWN),this.statContext=e,this.config=xt((o=r.config)!==null&&o!==void 0?o:{}),a.isNonNullable(r.apiEnv)&&(this.config.apiEnv=r.apiEnv),this.config.synchronizeTime&&(this.timeSynchronisation=new vn);const s=new a.Subject;this.experimental={error$:s};const l=new ln({apiKey:rn,config:this.config,error$:s,timeSynchronisation:this.timeSynchronisation});this.api=new nn({config:this.config,apiTransport:l,refreshAuthToken:r.refreshAuthToken,mobile:(i=this.statContext.mobile)!==null&&i!==void 0?i:!1,error$:s}),this.logger=new un({config:this.config,api:this.api,error$:s,userSalt:r.userSalt});const{isEmbed:h,host:c}=cn();this.isEmbed=h,this.embedParent=c,this.subscribe()}updateContext(e){this.statContext={...this.statContext,...e}}attachTo(e){const r=new a.Subscription,o=(n,d)=>r.add(n.subscribe(d));o(e.events.willStart$,()=>{this.logActionPlay({position:e.info.position$.getValue()})}),o(e.events.looped$,()=>{this.resetViewSession(),this.logActionPlay({position:e.info.position$.getValue()})}),o(e.events.seeked$,()=>{this.logSeek({action:this.seekAction$.getValue(),time:e.info.position$.getValue()}),this.seekAction$.next(exports.SeekAction.UNKNOWN)}),o(e.events.paused$,()=>{this.logPause({position:e.info.position$.getValue()})}),o(e.events.willResume$,()=>{this.logPlay()}),o(e.events.started$,()=>{this.statContext.clip&&this.logWatchCoverageRecord({start:0,end:0})}),o(pn(e),n=>{const d=e.info.isLive$.getValue(),f={start:parseFloat(n.from.toFixed(3)),end:parseFloat(n.to.toFixed(3))};d?this.logWatchCoverageLive(f):this.logWatchCoverageRecord(f)});let i;o(e.info.isStalled$,n=>{n?i=a.now():(a.isNonNullable(i)&&this.logEmptyBuffer({duration:a.now()-i}),i=void 0)});let s=!1;r.add(e.events.fatalError$.pipe(a.once()).subscribe(()=>s=!0)),o(e.events.willStop$,()=>{if(e.info.isStalled$.getValue()){const d=a.isNonNullable(i)?a.now()-i:void 0;this.logCloseAtEmptyBuffer({duration:d!=null?d:0}),i=void 0}else s||this.logActionStop()}),o(e.events.managedError$,({id:n})=>{this.logError({fatal:!1,errorType:n})}),o(e.events.fatalError$,({id:n})=>{this.logError({fatal:!0,errorType:n})});let l,h,c=!1;o(e.events.firstBytes$,n=>{l=a.now(),this.logFirstBytes({time:n})}),o(e.events.willStart$,()=>h=a.now()),o(e.info.currentBuffer$,n=>{!c&&n&&n.end-n.start>0&&a.isNonNullable(l)&&(this.logPlayerReady({duration:a.now()-l}),c=!0)}),o(e.events.firstFrame$,()=>{a.isNonNullable(l)&&!c&&(this.logPlayerReady({duration:a.now()-l}),c=!0),a.isNonNullable(h)&&this.logFirstFrame({time:a.now()-h})}),o(e.info.atLiveEdge$,n=>this.updateContext({liveEdge:n})),o(a.combine({muted:e.info.muted$,volume:e.info.volume$}),({muted:n,volume:d})=>this.updateContext({audible:!n&&d>0})),o(e.info.currentQuality$,n=>this.updateContext({quality:dn(n)})),o(e.info.isAutoQualityEnabled$,n=>this.updateContext({autoQuality:n})),o(e.info.currentFormat$,n=>this.updateContext({contentType:fn(n)}));let u;return o(e.info.hostname$,n=>{this.updateContext({cdnHostname:n,failover:u!==void 0&&u!==n}),u=n}),o(e.info.throughputEstimation$,n=>this.updateContext({downloadSpeed:n})),o(e.info.httpConnectionType$,n=>{this.statContext.firstConnectionType||this.updateContext({firstConnectionType:Xe(n)}),this.updateContext({connectionType:Xe(n)})}),o(e.info.httpConnectionReused$,n=>{a.isNullable(this.statContext.firstConnectionReused)&&this.updateContext({firstConnectionReused:n}),this.updateContext({connectionReused:n})}),o(e.info.surface$,n=>this.updateContext({mode:fe(n)})),o(a.combine({current:e.info.currentTextTrack$,available:e.info.availableTextTracks$}),({current:n,available:d})=>{const f=d.find(({id:p})=>p===n);this.updateContext({subtitles:f==null?void 0:f.language})}),this.player=e,this.uiEvents&&this.attachToUi(this.uiEvents),this.resubscribeBeforeunload(),this.subscription.add(r),r}attachToUi(e){this.uiEvents=e;const{subscription:r,subscribe:o}=he();return this.player&&(o(e.actionRewind$,()=>{this.player&&(this.resetViewSession(),this.logActionPlay({position:this.player.info.position$.getValue()}))}),o(e.actionSeek$,this.seekAction$),o(e.inPiP$,i=>{var s;const l=i?w.PIP:fe((s=this.player)===null||s===void 0?void 0:s.info.surface$.getValue());this.updateContext({mode:l})}),o(e.inFullscreen$,i=>{var s;const l=i?w.FULLSCREEN:fe((s=this.player)===null||s===void 0?void 0:s.info.surface$.getValue());this.updateContext({mode:l})}),o(e.actionSetSubtitle$,i=>this.updateContext({subtitles:i})),o(e.nextMovie$,i=>this.logNextMovie(i)),this.resubscribeBeforeunload(),this.subscription.add(r)),r}attachToAds(e){const{subscription:r,subscribe:o}=he();return o(e.slotRequested$,()=>this.logAdSlotRequest()),o(e.started$,i=>this.logAdStarted(i)),o(e.paused$,()=>this.logAdPaused()),o(e.resumed$,()=>this.logAdResumed()),o(e.ended$,()=>this.logAdEnded()),o(e.skipped$,()=>this.logAdSkipped()),o(e.clicked$,()=>this.logAdClicked()),this.resubscribeBeforeunload(),this.subscription.add(r),r}attachToInteractive(e){const{subscription:r,subscribe:o}=he();return o(e.click$,i=>this.logInterfaceClick(i)),o(e.nextMovie$,i=>this.logNextMovie(i)),this.resubscribeBeforeunload(),this.subscription.add(r),r}authorize(e){return this.api.authorize(e)}pause(){this.logger.pause()}resume(){this.logger.resume()}destroy(){this.logger.flush(),this.subscription.unsubscribe(),this.api.destroy(),this.logger.destroy()}resetViewSession(){this.vsid=Je()}setFieldBlacklist(){}logInited(){}logReady(e){this.log({operation:"player_ready",param:String(e.time)})}logStarted(...e){this.logActionPlay(...e)}logPlay(){this.log({operation:"play_toggle"})}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}`})}logWatchCoverageLive(e){var r,o;const i=(o=(r=this.timeSynchronisation)===null||r===void 0?void 0:r.getOffset())!==null&&o!==void 0?o:0,s=e.start+i,l=e.end+i;this.log({operation:"watch_coverage_live",param:`${s}-${l}`})}logEmptyBuffer(e){this.log({operation:"empty_buffer",param:String(e.duration)})}logDownloadSpeed(){}logAdSlotRequest(){this.log({operation:"adv",param:"slot_request"})}logAdStarted(e){this.log({operation:"adv",param:e})}logAdPaused(){this.log({operation:"adv",param:"pause"})}logAdResumed(){this.log({operation:"adv",param:"resume"})}logAdEnded(){this.log({operation:"adv",param:"ended"})}logAdSkipped(){this.log({operation:"adv",param:"skip"})}logAdClicked(){this.log({operation:"adv",param:"click"})}logInterfaceClick(e){this.log({operation:"player_interface_click",param:e})}logNextMovie(e){this.log({operation:"next_movie",param:String(e)})}subscribe(){this.resubscribeBeforeunload();const e=window.navigator.connection;e&&"onchange"in e&&"effectiveType"in e&&this.subscription.add(a.merge(a.fromEvent(e,"change"),a.observableFrom(["init"])).subscribe(()=>this.updateContext({network:hn(e.effectiveType)})))}resubscribeBeforeunload(){var e;(e=this.beforeunloadSubscription)===null||e===void 0||e.unsubscribe(),this.beforeunloadSubscription=a.fromEvent(window,"beforeunload").subscribe(()=>this.logger.flush(!0)),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))})}logCloseAtEmptyBuffer(e){this.log({operation:"close_at_empty_buffer",param:String(Math.round(e.duration))})}logActionStop(){this.log({operation:"action_stop"})}log(e){if(this.config.disabledOperations.includes(e.operation))return;const r=this.createLogItem(e);this.logger.log(r)}createLogItem({operation:e,param:r,time:o}){var i,s;const l=(s=(i=this.timeSynchronisation)===null||i===void 0?void 0:i.now())!==null&&s!==void 0?s:a.now(),h=e==="empty_buffer"||e==="close_at_empty_buffer"?this.statContext.connectionType:this.statContext.firstConnectionType,c=this.statContext.firstConnectionReused,u={vsid:this.vsid,vid:this.statContext.movieId,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?H.AUTO:this.statContext.autoplay===!1?H.MANUAL:void 0,param:r,vk_app_id:this.statContext.vkAppId,track_code:this.statContext.trackCode,connection_type:h,connection_reused:c===!0?S.YES:c===!1?S.NO:void 0,cached_data:this.statContext.cached===!0?S.YES:this.statContext.cached===!1?S.NO:void 0,live:this.statContext.liveEdge?S.YES:void 0,muted:this.statContext.audible===!1?S.YES:void 0,mode:this.statContext.mode,subtitles:this.statContext.subtitles,download_speed:this.statContext.downloadSpeed,manual_quality:this.statContext.autoQuality?void 0:S.YES,ref_domain:this.isEmbed?this.embedParent:this.statContext.refUrl,aid:this.statContext.albumId,vk_playlist_id:this.statContext.vkPlaylistId};for(const n of this.config.disabledCustomFields)delete u[n];return{operation:e,type:1,time:o,network:this.statContext.network,timestamp:l,custom:u}}}exports.OneStat=gn;exports.VERSION=be;
|
package/es2018.esm.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @vkontakte/videoplayer-statistics v1.0.
|
|
3
|
-
*
|
|
4
|
-
* https://st.mycdn.me/static/vkontakte-videoplayer/1-0-
|
|
2
|
+
* @vkontakte/videoplayer-statistics v1.0.39
|
|
3
|
+
* Tue, 29 Aug 2023 12:33:55 GMT
|
|
4
|
+
* https://st.mycdn.me/static/vkontakte-videoplayer/1-0-39/doc/
|
|
5
5
|
*/
|
|
6
|
-
import{fillWithDefault as nt,ValueSubject as q,safeStorage as v,getExponentialDelay as at,ErrorCategory as m,now as g,assertNever as st,Observable as ut,Subscription as T,merge as C,fromEvent as H,filterChanged as ct,map as lt,filter as B,isNullable as W,isNonNullable as P,Subject as ht,once as dt,combine as K,observableFrom as ft}from"@vkontakte/videoplayer-shared/es2018.esm.js";import z from"lodash/debounce.js";import{Surface as x,VideoQuality as S,HttpConnectionType as F,VideoFormat as f,PlaybackState as Q}from"@vkontakte/videoplayer-core/es2018.esm.js";var _;(function(e){e.PROD="prod",e.VK_ALIAS="vk_alias",e.VIDEOTEST="videotest",e.TEST="test",e.AUTO="auto"})(_||(_={}));var b;(function(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"})(b||(b={}));var p;(function(e){e.MP4="mp4",e.DASH="dash",e.DASH_SEP="dash_sep",e.ONDEMAND_DASH="ondemand_dash",e.HLS="hls",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"})(p||(p={}));var L;(function(e){e.AUTO="auto",e.MANUAL=""})(L||(L={}));var $;(function(e){e.HTTP1="http1",e.HTTP2="http2",e.HTTP3="http3"})($||($={}));var E;(function(e){e[e.YES=1]="YES",e[e.NO=0]="NO"})(E||(E={}));var N;(function(e){e.EXCELLENT="excellent",e.GOOD="good",e.POOR="poor"})(N||(N={}));var y;(function(e){e.PIP="pip",e.FULLSCREEN="fullscreen",e.EXTERNAL="external",e.PREFETCH="prefetch"})(y||(y={}));var I;(function(e){e.SLIDER="slider",e.DOUBLE_TAP="double_tap",e.TIME_CODE="time_code",e.EPISODE="episode",e.REWIND="rewind",e.LIVE="live",e.UNKNOWN="unknown"})(I||(I={}));var G;(function(e){e.GRAPH_SHOW="iGraphShow",e.GRAPH_HIDE="iGraphHide",e.NEXT_AREA="iNextChapterArea",e.NEXT_BUTTON="iNextChapterBtn",e.WATCH_AGAIN="iWatchAgainBtn"})(G||(G={}));const pt={apiEnv:_.VK_ALIAS,requestRetryCount:1,firstFlushTime:5e3,flushDebounceTime:1e4,flushMaxWait:6e4,storageExpiration:36*60*60*1e3,disabledOperations:[],disabledCustomFields:[],useBeacon:!0,synchronizeTime:!0,backoff:{start:1e3,factor:1.5,max:5*60*1e3,random:.1}},gt=e=>nt(e,pt);function bt(){const e="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".split(""),t=new Array(36);let i=0,s,o;for(o=0;o<36;o++)o===8||o===13||o===18||o===23?t[o]="-":o===14?t[o]="4":(i<=2&&(i=33554432+Math.random()*16777216|0),s=i&15,i=i>>4,t[o]=e[o===19?s&3|8:s]);return t.join("")}const j="1.0.38",mt="CIOPGQJGDIHBABABA",Y={[_.PROD]:"https://api.ok.ru",[_.VK_ALIAS]:"https://api.mycdn.me",[_.VIDEOTEST]:"https://videotestapi.ok.ru/api",[_.TEST]:"https://apitest.ok.ru",[_.AUTO]:""},St="_one-stat_",X=`${St}uuid`;var w;(function(e){e[e.PARAM_SESSION_EXPIRED=102]="PARAM_SESSION_EXPIRED",e[e.PARAM_SESSION_KEY=103]="PARAM_SESSION_KEY",e[e.PARAM_SIGNATURE=104]="PARAM_SIGNATURE",e[e.AUTH_LOGIN=401]="AUTH_LOGIN"})(w||(w={}));class _t{constructor(t){this.consequentAuthErrors=0,this.authorized$=new q(!1),this.params=t;const i=v.get(X);i?this.uuid=String(i):(this.uuid=bt(),v.set(X,this.uuid))}async authorize(t){return this.authToken=t!=null?t:await this.refreshAuthToken(),this._authorizeWithBackoff()}logBeacon(t){const i="log.externalLog",s=this.createLogParams(t),o=this.sessionKey;if(!o)return;this.params.apiTransport.sendBeacon(i,s,o)||this.logRequest(t)}async logRequest(t){var i;const s="log.externalLog",o=this.createLogParams(t),n=(i=this.sessionKey)!==null&&i!==void 0?i:await this._authorizeWithBackoff();if(!n)return;const a=async(h,c=this.params.config.requestRetryCount)=>{try{return await this.params.apiTransport.sendRequest(s,o,n)}catch(u){if(!u||!("error_code"in u)){this.params.error$.next({id:"logRequestUnknown",category:m.NETWORK,message:`Unknown ${s} error`,thrown:u});return}const r=u==null?void 0:u.error_code;switch(r){case w.PARAM_SESSION_EXPIRED:case w.PARAM_SESSION_KEY:case w.PARAM_SIGNATURE:return this.authorized$.next(!1),this.sessionKey=await this._authorizeWithBackoff(),c>0?a(h,c-1):void 0;case w.AUTH_LOGIN:return this.authorized$.next(!1),this.authToken=await this.refreshAuthToken(),this.sessionKey=await this._authorizeWithBackoff(),c>0?a(h,c-1):void 0;default:{this.params.error$.next({id:`LogRequest#${r}`,category:m.EXTERNAL_API,message:`${s} error`,data:u});return}}}};return a(t)}destroy(){window.clearTimeout(this.backoffTimeoutId),this.backoffTimeoutId=0}async refreshAuthToken(){if(this.params.refreshAuthToken)return this.refreshAuthTokenPromise||(this.refreshAuthTokenPromise=this.params.refreshAuthToken().finally(()=>{this.refreshAuthTokenPromise=void 0})),this.refreshAuthTokenPromise}createLogParams(t){return{collector:"ok.mobile.apps.video",data:JSON.stringify({application:`@vkontakte/videoplayer-statistics:${j}`,platform:this.params.mobile?"M_WEB":"WEB",items:t})}}_authorizeWithBackoff(){if(!this.consequentAuthErrors)return this._authorize();const t=at(this.consequentAuthErrors,this.params.config.backoff);return new Promise(i=>{this.backoffTimeoutId||(this.backoffTimeoutId=window.setTimeout(()=>{this._authorize().then(i).catch(s=>this.params.error$.next({id:"AuthorizeBackoff",category:m.NETWORK,message:"Otherwise unhandled error in authorization",thrown:s})).finally(()=>this.backoffTimeoutId=0)},t))})}async _authorize(){if(this.authorizePromise)return this.authorizePromise;this.sessionKey=void 0,this.authorized$.next(!1);const t="auth.anonymLogin",i={session_data:{version:2,device_id:this.uuid,client_version:j.split("-")[0],client_type:"SDK_JS"}};return this.authToken!==void 0&&(i.session_data.auth_token=this.authToken,i.session_data.version=3),this.authorizePromise=this.params.apiTransport.sendRequest(t,i).then(s=>{var o;return(!s||!s.session_key)&&this.params.error$.next({id:"AuthorizeFailed",category:m.EXTERNAL_API,message:"No session key",data:s}),this.sessionKey=(o=s==null?void 0:s.session_key)!==null&&o!==void 0?o:void 0,this.sessionKey}).catch(async s=>{this.sessionKey=void 0;const o=s==null?void 0:s.error_code;switch(o){case w.AUTH_LOGIN:return this.authToken=await this.refreshAuthToken(),this._authorizeWithBackoff()}o?this.params.error$.next({id:`Authorize#${o}`,category:m.EXTERNAL_API,message:"authorize error",data:s}):this.params.error$.next({id:"AuthorizeUnknown",category:m.NETWORK,message:"authorize error",thrown:s})}).finally(()=>{this.authorizePromise=void 0,this.consequentAuthErrors=this.sessionKey?0:this.consequentAuthErrors+1,this.authorized$.next(this.sessionKey!==void 0)}),this.authorizePromise}}class J{constructor(){Object.defineProperty(this,"listeners",{value:{},writable:!0,configurable:!0})}addEventListener(t,i,s){t in this.listeners||(this.listeners[t]=[]),this.listeners[t].push({callback:i,options:s})}removeEventListener(t,i){if(!(t in this.listeners))return;const s=this.listeners[t];for(let o=0,n=s.length;o<n;o++)if(s[o].callback===i){s.splice(o,1);return}}dispatchEvent(t){if(!(t.type in this.listeners))return;const s=this.listeners[t.type].slice();for(let o=0,n=s.length;o<n;o++){const a=s[o];try{a.callback.call(this,t)}catch(h){Promise.resolve().then(()=>{throw h})}a.options&&a.options.once&&this.removeEventListener(t.type,a.callback)}return!t.defaultPrevented}}class it extends J{constructor(){super(),this.listeners||J.call(this),Object.defineProperty(this,"aborted",{value:!1,writable:!0,configurable:!0}),Object.defineProperty(this,"onabort",{value:null,writable:!0,configurable:!0}),Object.defineProperty(this,"reason",{value:void 0,writable:!0,configurable:!0})}toString(){return"[object AbortSignal]"}dispatchEvent(t){t.type==="abort"&&(this.aborted=!0,typeof this.onabort=="function"&&this.onabort.call(this,t)),super.dispatchEvent(t)}}class Et{constructor(){Object.defineProperty(this,"signal",{value:new it,writable:!0,configurable:!0})}abort(t){let i;try{i=new Event("abort")}catch(o){typeof document!="undefined"?document.createEvent?(i=document.createEvent("Event"),i.initEvent("abort",!1,!1)):(i=document.createEventObject(),i.type="abort"):i={type:"abort",bubbles:!1,cancelable:!1}}let s=t;if(s===void 0)if(typeof document=="undefined")s=new Error("This operation was aborted"),s.name="AbortError";else try{s=new DOMException("signal is aborted without reason")}catch(o){s=new Error("This operation was aborted"),s.name="AbortError"}this.signal.reason=s,this.signal.dispatchEvent(i)}toString(){return"[object AbortController]"}}typeof Symbol!="undefined"&&Symbol.toStringTag&&(Et.prototype[Symbol.toStringTag]="AbortController",it.prototype[Symbol.toStringTag]="AbortSignal");function ot(e){return e.__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL?(console.log("__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL=true is set, will force install polyfill"),!0):typeof e.Request=="function"&&!e.Request.prototype.hasOwnProperty("signal")||!e.AbortController}function At(e){typeof e=="function"&&(e={fetch:e});const{fetch:t,Request:i=t.Request,AbortController:s,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:o=!1}=e;if(!ot({fetch:t,Request:i,AbortController:s,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:o}))return{fetch:t,Request:n};let n=i;(n&&!n.prototype.hasOwnProperty("signal")||o)&&(n=function(u,r){let l;r&&r.signal&&(l=r.signal,delete r.signal);const d=new i(u,r);return l&&Object.defineProperty(d,"signal",{writable:!1,enumerable:!1,configurable:!0,value:l}),d},n.prototype=i.prototype);const a=t;return{fetch:(c,u)=>{const r=n&&n.prototype.isPrototypeOf(c)?c.signal:u?u.signal:void 0;if(r){let l;try{l=new DOMException("Aborted","AbortError")}catch(O){l=new Error("Aborted"),l.name="AbortError"}if(r.aborted)return Promise.reject(l);const d=new Promise((O,A)=>{r.addEventListener("abort",()=>A(l),{once:!0})});return u&&u.signal&&delete u.signal,Promise.race([d,a(c,u)])}return a(c,u)},Request:n}}const V=ot({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),rt=V?At({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,Z=V?rt.fetch:window.fetch;V?rt.Request:window.Request;class vt{constructor(t){this.params=t,this.apiKey=t.apiKey,this.apiEnv=t.config.apiEnv,this.apiBaseUrl=Y[this.apiEnv],this.timeSynchronisation=t.timeSynchronisation,this.isApiBaseUrlFetched=!1}async resolveApiBaseUrl(){var t;if(this.apiEnv!==_.AUTO||this.isApiBaseUrlFetched)return this.apiBaseUrl;try{const i=atob("aHR0cHM6Ly9kbnMuZ29vZ2xlL3Jlc29sdmU/bmFtZT12aWRlby5fZW5kcG9pbnQub2sucnUmdHlwZT1UWFQ="),o=await(await Z(i,{method:"GET",mode:"cors",cache:"no-cache"})).json(),n=(t=o==null?void 0:o.Answer[0])===null||t===void 0?void 0:t.data;if(!n)throw new Error("Wrong DNS response");return n}catch(i){return this.params.error$.next({id:"OneStat:ApiTransport:resolveApiBaseUrl",category:m.NETWORK,message:"Unhandled resolve api base url error",thrown:i}),Y[_.VK_ALIAS]}finally{this.isApiBaseUrlFetched=!0}}sendBeacon(t,i,s){if(!window.Blob||!window.navigator.sendBeacon)return!1;const o=this._prepareQueryParams({method:t,queryParams:i,sessionKey:s}),n=new window.Blob([o.toString()],{type:"application/x-www-form-urlencoded"});try{return window.navigator.sendBeacon(`${this.apiBaseUrl}/fb.do`,n)}catch(a){this.params.error$.next({id:"OneStat:ApiTransport:sendBeacon",category:m.NETWORK,message:"Unhandled beacon error",thrown:a,data:{method:t,params:i}})}return!1}async sendRequest(t,i,s){const o=g(),n=a=>{if(a instanceof TypeError&&["Failed to fetch","NetworkError when attempting to fetch resource."].includes(a.message)){this.params.error$.next({id:"Network",category:m.NETWORK,message:"Request failed",thrown:a});return}this.params.error$.next({id:"OneStat:ApiTransport:sendRequest",category:m.NETWORK,message:"Unhandled request error",thrown:a,data:{method:t,params:i,sessionKey:s,time:g()-o}})};return this.apiBaseUrl=await this.resolveApiBaseUrl(),Z(`${this.apiBaseUrl}/fb.do`,{method:"post",headers:{"Content-type":"application/x-www-form-urlencoded"},body:this._prepareQueryParams({method:t,queryParams:i,sessionKey:s})}).then(a=>{var h,c;const u=Number(a.headers.get("content-length"))===0,r=new Date((h=a.headers.get("date"))!==null&&h!==void 0?h:"").getTime(),l=g()-o;if(isFinite(r)&&((c=this.timeSynchronisation)===null||c===void 0||c.addServerTime(r,l)),!u)return a.json().then(d=>Object.prototype.hasOwnProperty.call(d,"error_msg")?Promise.reject(d):d,n)},n)}_prepareQueryParams(t){const i=new URLSearchParams({format:"JSON",method:t.method,application_key:this.apiKey});return t.sessionKey!==void 0&&i.append("session_key",t.sessionKey),Object.entries(t.queryParams).forEach(([s,o])=>i.append(s,typeof o=="string"?o:JSON.stringify(o))),i}}const k="onestat_events",U=e=>t=>t.timestamp+e>=g();class wt{constructor(t){this.unsaltedStorage=[],this.isPaused=!1,this.isUrgent=s=>{const{operation:o,custom:{param:n}}=s;return["action_stop","close_at_empty_buffer"].includes(o)||o==="watch_coverage_record"&&n==="0-0"},this.params=t,this.api=t.api,this.error$=t.error$,this.userSalt=t.userSalt,this.firstFlush=z(()=>this.safeFlush(),this.params.config.firstFlushTime,{maxWait:this.params.config.firstFlushTime});const i=v.isPersistent()?this.params.config.flushMaxWait:0;this.debouncedFlush=z(()=>this.safeFlush(),this.params.config.flushDebounceTime,{maxWait:i}),this.subscription=this.api.authorized$.subscribe(s=>{s&&this.debouncedFlush()}),this.housekeepStorage()}safeFlush(){var t;try{this.flush()}catch(i){this.error$.next({id:"LoggerError",category:m.WTF,message:(t=String(i))!==null&&t!==void 0?t:"Unknown logger error",thrown:i})}}readFromStorage(){const t=v.get(k);try{return t?JSON.parse(t):{}}catch(i){}return{}}addToStorage(t){var i;if(!this.userSalt){this.unsaltedStorage.push(t);return}const s=this.readFromStorage(),n=((i=s[this.userSalt])!==null&&i!==void 0?i:[]).filter(U(this.params.config.storageExpiration));v.set(k,JSON.stringify({...s,[this.userSalt]:[...n,t]}))}getFromStorage(){var t;return this.userSalt?((t=this.readFromStorage()[this.userSalt])!==null&&t!==void 0?t:[]).filter(U(this.params.config.storageExpiration)):this.unsaltedStorage}markStorageSent(){if(!this.userSalt){this.unsaltedStorage=[];return}const t=this.readFromStorage();delete t[this.userSalt],v.set(k,JSON.stringify(t))}housekeepStorage(){const t=this.readFromStorage();for(const[i,s]of Object.entries(t)){const o=s.filter(U(this.params.config.storageExpiration));o.length?t[i]=o:delete t[i]}v.set(k,JSON.stringify(t))}log(t){this.addToStorage(t),!this.isPaused&&(this.isUrgent(t)?this.flush():this.lastVsid!==t.custom.vsid?this.firstFlush():this.debouncedFlush(),this.lastVsid=t.custom.vsid)}flush(t=!1){const i=this.getFromStorage();i.length!==0&&(this.api.authorized$.getValue()?(t&&this.params.config.useBeacon?this.api.logBeacon(i):this.api.logRequest(i),this.markStorageSent()):this.api.authorize(),this.firstFlush.cancel(),this.debouncedFlush.cancel())}pause(){this.isPaused=!0,this.debouncedFlush.cancel()}resume(){this.isPaused=!1,this.debouncedFlush()}destroy(){this.subscription.unsubscribe(),this.firstFlush.cancel(),this.debouncedFlush.cancel()}}const yt=()=>{let e,t;try{e=window.self!==window.top}catch(s){s instanceof DOMException&&s.name==="SecurityError"?e=!0:(e=!1,console.error(s))}try{window.location.ancestorOrigins&&(t=window.location.ancestorOrigins[window.location.ancestorOrigins.length-1])}catch(s){console.error(s)}try{!t&&document.referrer&&(t=document.referrer)}catch(s){console.error(s)}const i=t?new URL(t).hostname:void 0;return{isEmbed:e,host:i}},Pt=e=>e&&{[S.INVARIANT]:b.UNKNOWN,[S.Q_144P]:b.Q144P,[S.Q_240P]:b.Q240P,[S.Q_360P]:b.Q360P,[S.Q_480P]:b.Q480P,[S.Q_720P]:b.Q720P,[S.Q_1080P]:b.Q1080P,[S.Q_1440P]:b.Q1440P,[S.Q_2160P]:b.Q2160P,[S.Q_4320P]:b.UNKNOWN}[e],tt=e=>e&&{[F.HTTP1]:$.HTTP1,[F.HTTP2]:$.HTTP2,[F.QUIC]:$.HTTP3}[e],Tt=e=>{if(e!==void 0)switch(e){case f.MPEG:return p.MP4;case f.DASH:case f.DASH_LIVE:return p.DASH;case f.DASH_SEP:return p.DASH_SEP;case f.DASH_ONDEMAND:return p.ONDEMAND_DASH;case f.DASH_WEBM:case f.DASH_LIVE_WEBM:return p.WEBM;case f.DASH_WEBM_AV1:return p.AV1;case f.DASH_LIVE_CMAF:return p.ONDEMAND_DASH_LIVE;case f.HLS:case f.HLS_LIVE:return p.HLS;case f.HLS_ONDEMAND:return p.ONDEMAND_HLS;case f.HLS_LIVE_CMAF:return p.ONDEMAND_HLS_LIVE;case f.WEB_RTC_LIVE:return p.WEBRTC;default:return st(e)}},M=e=>{if(e!==void 0)switch(e){case x.NONE:case x.INLINE:return;case x.FULLSCREEN:return y.FULLSCREEN;case x.SECOND_SCREEN:return y.EXTERNAL;case x.PIP:return y.PIP;default:return st(e)}},Nt=e=>{switch(e){case"slow-2g":return N.POOR;case"2g":return N.POOR;case"3g":return N.GOOD;case"4g":return N.EXCELLENT}};class Ot{constructor(t){this.offset=void 0,this.offset=t}getOffset(){var t;return(t=this.offset)!==null&&t!==void 0?t:0}setOffset(t){this.offset=t}now(){var t;return Date.now()+((t=this.offset)!==null&&t!==void 0?t:0)}date(t=new Date){var i;return t.setTime(t.getTime()+((i=this.offset)!==null&&i!==void 0?i:0)),t}addServerTime(t,i){const s=Date.now(),o=t-s-i/2;if(Math.abs(o)<1e3){this.offset=0;return}this.offset===void 0?this.offset=Math.round(o):this.offset=Math.round(.2*o+(1-.2)*this.offset)}}const et=()=>Math.floor(Math.random()*2**32).toString(36).padStart(8,"0"),Rt=e=>new ut(t=>{const i=new T,s=C(H(window,"beforeunload"),e.events.willDestruct$),o=new q(void 0);let n;i.add(e.info.isLive$.pipe(ct()).subscribe(R=>{n&&(n.unsubscribe(),o.next(void 0)),R?n=e.info.liveTime$.pipe(lt(D=>D&&D/1e3)).subscribe(o):n=e.info.position$.subscribe(o),i.add(n)}));const{playing$:a,paused$:h}=e.events,c=e.events.willSeek$.pipe(B(()=>e.info.playbackState$.getValue()===Q.PLAYING)),u=e.events.seeked$.pipe(B(()=>e.info.playbackState$.getValue()===Q.PLAYING));let r=!1;i.add(c.subscribe(()=>r=!0)),i.add(u.subscribe(()=>r=!1));const l=c.pipe(B(()=>!r)),d=C(a,u),O=C(h,l,s,e.events.looped$);let A;return i.add(d.subscribe(()=>A=o.getValue())),i.add(O.subscribe(()=>{const R=o.getValue();W(A)||A===R||W(R)||(t.next({from:A,to:R}),A=void 0)})),i});class Ct{constructor(t,i){var s,o;this.subscription=new T,this.vsid=et(),this.seekAction$=new q(I.UNKNOWN),this.statContext=t,this.config=gt((s=i.config)!==null&&s!==void 0?s:{}),P(i.apiEnv)&&(this.config.apiEnv=i.apiEnv),this.config.synchronizeTime&&(this.timeSynchronisation=new Ot);const n=new ht;this.experimental={error$:n};const a=new vt({apiKey:mt,config:this.config,error$:n,timeSynchronisation:this.timeSynchronisation});this.api=new _t({config:this.config,apiTransport:a,refreshAuthToken:i.refreshAuthToken,mobile:(o=this.statContext.mobile)!==null&&o!==void 0?o:!1,error$:n}),this.logger=new wt({config:this.config,api:this.api,error$:n,userSalt:i.userSalt});const{isEmbed:h,host:c}=yt();this.isEmbed=h,this.embedParent=c,this.subscribe()}updateContext(t){this.statContext={...this.statContext,...t}}attachTo(t){const i=new T,s=(r,l)=>i.add(r.subscribe(l));s(t.events.willStart$,()=>{this.logActionPlay({position:t.info.position$.getValue()})}),s(t.events.looped$,()=>{this.resetViewSession(),this.logActionPlay({position:t.info.position$.getValue()})}),s(t.events.seeked$,()=>{this.logSeek({action:this.seekAction$.getValue(),time:t.info.position$.getValue()}),this.seekAction$.next(I.UNKNOWN)}),s(t.events.paused$,()=>{this.logPause({position:t.info.position$.getValue()})}),s(t.events.willResume$,()=>{this.logPlay()}),s(t.events.started$,()=>{this.statContext.clip&&this.logWatchCoverageRecord({start:0,end:0})}),s(Rt(t),r=>{const l=t.info.isLive$.getValue(),d={start:parseFloat(r.from.toFixed(3)),end:parseFloat(r.to.toFixed(3))};l?this.logWatchCoverageLive(d):this.logWatchCoverageRecord(d)});let o;s(t.info.isStalled$,r=>{r?o=g():(P(o)&&this.logEmptyBuffer({duration:g()-o}),o=void 0)});let n=!1;i.add(t.events.fatalError$.pipe(dt()).subscribe(()=>n=!0)),s(t.events.willStop$,()=>{if(t.info.isStalled$.getValue()){const l=P(o)?g()-o:void 0;this.logCloseAtEmptyBuffer({duration:l!=null?l:0}),o=void 0}else n||this.logActionStop()}),s(t.events.managedError$,({id:r})=>{this.logError({fatal:!1,errorType:r})}),s(t.events.fatalError$,({id:r})=>{this.logError({fatal:!0,errorType:r})});let a,h,c=!1;s(t.events.firstBytes$,r=>{a=g(),this.logFirstBytes({time:r})}),s(t.events.willStart$,()=>h=g()),s(t.info.currentBuffer$,r=>{!c&&r&&r.end-r.start>0&&P(a)&&(this.logPlayerReady({duration:g()-a}),c=!0)}),s(t.events.firstFrame$,()=>{P(a)&&!c&&(this.logPlayerReady({duration:g()-a}),c=!0),P(h)&&this.logFirstFrame({time:g()-h})}),s(t.info.atLiveEdge$,r=>this.updateContext({liveEdge:r})),s(K({muted:t.info.muted$,volume:t.info.volume$}),({muted:r,volume:l})=>this.updateContext({audible:!r&&l>0})),s(t.info.currentQuality$,r=>this.updateContext({quality:Pt(r)})),s(t.info.isAutoQualityEnabled$,r=>this.updateContext({autoQuality:r})),s(t.info.currentFormat$,r=>this.updateContext({contentType:Tt(r)}));let u;return s(t.info.hostname$,r=>{this.updateContext({cdnHostname:r,failover:u!==void 0&&u!==r}),u=r}),s(t.info.throughputEstimation$,r=>this.updateContext({downloadSpeed:r})),s(t.info.httpConnectionType$,r=>{this.statContext.firstConnectionType||this.updateContext({firstConnectionType:tt(r)}),this.updateContext({connectionType:tt(r)})}),s(t.info.httpConnectionReused$,r=>{W(this.statContext.firstConnectionReused)&&this.updateContext({firstConnectionReused:r}),this.updateContext({connectionReused:r})}),s(t.info.surface$,r=>this.updateContext({mode:M(r)})),s(K({current:t.info.currentTextTrack$,available:t.info.availableTextTracks$}),({current:r,available:l})=>{const d=l.find(({id:O})=>O===r);this.updateContext({subtitles:d==null?void 0:d.language})}),this.player=t,this.uiEvents&&this.attachToUi(this.uiEvents),this.resubscribeBeforeunload(),this.subscription.add(i),i}attachToUi(t){this.uiEvents=t;const i=new T;return this.player&&(i.add(t.actionRewind$.subscribe(()=>{this.player&&(this.resetViewSession(),this.logActionPlay({position:this.player.info.position$.getValue()}))})),i.add(t.actionSeek$.subscribe(this.seekAction$)),i.add(t.inPiP$.subscribe(s=>{var o;const n=s?y.PIP:M((o=this.player)===null||o===void 0?void 0:o.info.surface$.getValue());this.updateContext({mode:n})})),i.add(t.inFullscreen$.subscribe(s=>{var o;const n=s?y.FULLSCREEN:M((o=this.player)===null||o===void 0?void 0:o.info.surface$.getValue());this.updateContext({mode:n})})),i.add(t.actionSetSubtitle$.subscribe(s=>{this.updateContext({subtitles:s})})),i.add(t.nextMovie$.subscribe(s=>this.logNextMovie(s))),this.resubscribeBeforeunload(),this.subscription.add(i)),i}attachToAds(t){const i=new T;return i.add(t.slotRequested$.subscribe(()=>this.logAdSlotRequest())).add(t.started$.subscribe(s=>this.logAdStarted(s))).add(t.paused$.subscribe(()=>this.logAdPaused())).add(t.resumed$.subscribe(()=>this.logAdResumed())).add(t.ended$.subscribe(()=>this.logAdEnded())).add(t.skipped$.subscribe(()=>this.logAdSkipped())).add(t.clicked$.subscribe(()=>this.logAdClicked())),this.resubscribeBeforeunload(),this.subscription.add(i),i}attachToInteractive(t){const i=new T;return i.add(t.click$.subscribe(s=>this.logInterfaceClick(s))).add(t.nextMovie$.subscribe(s=>this.logNextMovie(s))),this.resubscribeBeforeunload(),this.subscription.add(i),i}authorize(t){return this.api.authorize(t)}pause(){this.logger.pause()}resume(){this.logger.resume()}destroy(){this.logger.flush(),this.subscription.unsubscribe(),this.api.destroy(),this.logger.destroy()}resetViewSession(){this.vsid=et()}setFieldBlacklist(){}logInited(){}logReady(t){this.log({operation:"player_ready",param:String(t.time)})}logStarted(...t){this.logActionPlay(...t)}logPlay(){this.log({operation:"play_toggle"})}logPause(t){this.log({operation:"pause",param:String(Math.round(t.position))})}logSeek(t){this.log({operation:"seek",param:t.action,time:t.time})}logFirstBytes(t){this.log({operation:"first_bytes",param:String(t.time)})}logFirstFrame(t){this.log({operation:"first_frame",param:String(t.time)})}logError(t){this.log({operation:"content_error",param:`${t.fatal?"fatal":"recoverable"}_${t.errorType}`})}logWatchCoverageRecord(t){this.log({operation:"watch_coverage_record",param:`${t.start}-${t.end}`})}logWatchCoverageLive(t){var i,s;const o=(s=(i=this.timeSynchronisation)===null||i===void 0?void 0:i.getOffset())!==null&&s!==void 0?s:0,n=t.start+o,a=t.end+o;this.log({operation:"watch_coverage_live",param:`${n}-${a}`})}logEmptyBuffer(t){this.log({operation:"empty_buffer",param:String(t.duration)})}logDownloadSpeed(){}logAdSlotRequest(){this.log({operation:"adv",param:"slot_request"})}logAdStarted(t){this.log({operation:"adv",param:t})}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(t){this.log({operation:"player_interface_click",param:t})}logNextMovie(t){this.log({operation:"next_movie",param:String(t)})}subscribe(){this.resubscribeBeforeunload();const t=window.navigator.connection;t&&"onchange"in t&&"effectiveType"in t&&this.subscription.add(C(H(t,"change"),ft(["init"])).subscribe(()=>this.updateContext({network:Nt(t.effectiveType)})))}resubscribeBeforeunload(){var t;(t=this.beforeunloadSubscription)===null||t===void 0||t.unsubscribe(),this.beforeunloadSubscription=H(window,"beforeunload").subscribe(()=>this.logger.flush(!0)),this.subscription.add(this.beforeunloadSubscription)}logPlayerReady(t){this.log({operation:"player_ready",param:String(Math.round(t.duration))})}logActionPlay(t){this.log({operation:"action_play",param:String(Math.round(t.position))})}logCloseAtEmptyBuffer(t){this.log({operation:"close_at_empty_buffer",param:String(Math.round(t.duration))})}logActionStop(){this.log({operation:"action_stop"})}log(t){if(this.config.disabledOperations.includes(t.operation))return;const i=this.createLogItem(t);this.logger.log(i)}createLogItem({operation:t,param:i,time:s}){var o,n;const a=(n=(o=this.timeSynchronisation)===null||o===void 0?void 0:o.now())!==null&&n!==void 0?n:g(),h=t==="empty_buffer"||t==="close_at_empty_buffer"?this.statContext.connectionType:this.statContext.firstConnectionType,c=this.statContext.firstConnectionReused,u={vsid:this.vsid,vid:this.statContext.movieId,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?L.AUTO:this.statContext.autoplay===!1?L.MANUAL:void 0,param:i,vk_app_id:this.statContext.vkAppId,track_code:this.statContext.trackCode,connection_type:h,connection_reused:c===!0?E.YES:c===!1?E.NO:void 0,cached_data:this.statContext.cached===!0?E.YES:this.statContext.cached===!1?E.NO:void 0,live:this.statContext.liveEdge?E.YES:void 0,muted:this.statContext.audible===!1?E.YES:void 0,mode:this.statContext.mode,subtitles:this.statContext.subtitles,download_speed:this.statContext.downloadSpeed,manual_quality:this.statContext.autoQuality?void 0:E.YES,ref_domain:this.embedParent,aid:this.statContext.albumId,vk_playlist_id:this.statContext.vkPlaylistId};for(const r of this.config.disabledCustomFields)delete u[r];return{operation:t,type:1,time:s,network:this.statContext.network,timestamp:a,custom:u}}}export{_ as ApiEnv,$ as ConnectionType,p as ContentType,G as InteractiveInterfaceClick,Ct as OneStat,b as Quality,I as SeekAction,j as VERSION};
|
|
6
|
+
import{fillWithDefault as er,ValueSubject as Ce,safeStorage as O,getExponentialDelay as tr,ErrorCategory as S,now as m,assertNever as yt,Observable as rr,Subscription as Z,merge as X,fromEvent as Oe,filterChanged as or,map as ir,filter as Fe,Subject as St,isNullable as Pe,isNonNullable as x,once as nr,combine as Ue,observableFrom as ar}from"@vkontakte/videoplayer-shared/es2018.esm.js";import je from"lodash/debounce.js";import{Surface as U,VideoQuality as _,HttpConnectionType as se,VideoFormat as g,PlaybackState as Me}from"@vkontakte/videoplayer-core/es2018.esm.js";var w;(function(t){t.PROD="prod",t.VK_ALIAS="vk_alias",t.VIDEOTEST="videotest",t.TEST="test",t.AUTO="auto"})(w||(w={}));var y;(function(t){t.Q144P="mobile",t.Q240P="lowest",t.Q360P="low",t.Q480P="medium",t.Q720P="high",t.Q1080P="fullhd",t.Q1440P="quadhd",t.Q2160P="ultrahd",t.UNKNOWN="unknown"})(y||(y={}));var b;(function(t){t.MP4="mp4",t.DASH="dash",t.DASH_SEP="dash_sep",t.ONDEMAND_DASH="ondemand_dash",t.HLS="hls",t.ONDEMAND_HLS="ondemand_hls",t.WEBM="webm",t.AV1="av1",t.ONDEMAND_DASH_LIVE="ondemand_dash_live",t.ONDEMAND_HLS_LIVE="ondemand_hls_live",t.WEBRTC="webrtc",t.UNKNOWN="unknown",t.RTMP="rtmp"})(b||(b={}));var ee;(function(t){t.AUTO="auto",t.MANUAL=""})(ee||(ee={}));var j;(function(t){t.HTTP1="http1",t.HTTP2="http2",t.HTTP3="http3"})(j||(j={}));var T;(function(t){t[t.YES=1]="YES",t[t.NO=0]="NO"})(T||(T={}));var B;(function(t){t.EXCELLENT="excellent",t.GOOD="good",t.POOR="poor"})(B||(B={}));var I;(function(t){t.PIP="pip",t.FULLSCREEN="fullscreen",t.EXTERNAL="external",t.PREFETCH="prefetch"})(I||(I={}));var te;(function(t){t.SLIDER="slider",t.DOUBLE_TAP="double_tap",t.TIME_CODE="time_code",t.EPISODE="episode",t.REWIND="rewind",t.LIVE="live",t.UNKNOWN="unknown"})(te||(te={}));var He;(function(t){t.GRAPH_SHOW="iGraphShow",t.GRAPH_HIDE="iGraphHide",t.NEXT_AREA="iNextChapterArea",t.NEXT_BUTTON="iNextChapterBtn",t.WATCH_AGAIN="iWatchAgainBtn"})(He||(He={}));const sr={apiEnv:w.VK_ALIAS,requestRetryCount:1,firstFlushTime:5e3,flushDebounceTime:1e4,flushMaxWait:6e4,storageExpiration:36*60*60*1e3,disabledOperations:[],disabledCustomFields:[],useBeacon:!0,synchronizeTime:!0,backoff:{start:1e3,factor:1.5,max:5*60*1e3,random:.1}},lr=t=>er(t,sr);var le=typeof globalThis!="undefined"?globalThis:typeof window!="undefined"?window:typeof global!="undefined"?global:typeof self!="undefined"?self:{};function ur(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var V=function(t){return t&&t.Math==Math&&t},P=V(typeof globalThis=="object"&&globalThis)||V(typeof window=="object"&&window)||V(typeof self=="object"&&self)||V(typeof le=="object"&&le)||function(){return this}()||le||Function("return this")(),C=function(t){try{return!!t()}catch(e){return!0}},cr=C,oe=!cr(function(){var t=function(){}.bind();return typeof t!="function"||t.hasOwnProperty("prototype")}),dr=oe,Et=Function.prototype,We=Et.apply,qe=Et.call,fr=typeof Reflect=="object"&&Reflect.apply||(dr?qe.bind(We):function(){return qe.apply(We,arguments)}),$t=oe,_t=Function.prototype,Ne=_t.call,hr=$t&&_t.bind.bind(Ne,Ne),N=$t?hr:function(t){return function(){return Ne.apply(t,arguments)}},wt=N,vr=wt({}.toString),pr=wt("".slice),ie=function(t){return pr(vr(t),8,-1)},gr=ie,br=N,Tt=function(t){if(gr(t)==="Function")return br(t)},Re=typeof document=="object"&&document.all,mr=typeof Re=="undefined"&&Re!==void 0,At={all:Re,IS_HTMLDDA:mr},Ot=At,yr=Ot.all,A=Ot.IS_HTMLDDA?function(t){return typeof t=="function"||t===yr}:function(t){return typeof t=="function"},Pt={},Sr=C,M=!Sr(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!=7}),Er=oe,G=Function.prototype.call,H=Er?G.bind(G):function(){return G.apply(G,arguments)},Nt={},Rt={}.propertyIsEnumerable,It=Object.getOwnPropertyDescriptor,$r=It&&!Rt.call({1:2},1);Nt.f=$r?function(e){var r=It(this,e);return!!r&&r.enumerable}:Rt;var Ct=function(t,e){return{enumerable:!(t&1),configurable:!(t&2),writable:!(t&4),value:e}},_r=N,wr=C,Tr=ie,ue=Object,Ar=_r("".split),Or=wr(function(){return!ue("z").propertyIsEnumerable(0)})?function(t){return Tr(t)=="String"?Ar(t,""):ue(t)}:ue,xe=function(t){return t==null},Pr=xe,Nr=TypeError,Le=function(t){if(Pr(t))throw Nr("Can't call method on "+t);return t},Rr=Or,Ir=Le,Cr=function(t){return Rr(Ir(t))},Ke=A,xt=At,xr=xt.all,W=xt.IS_HTMLDDA?function(t){return typeof t=="object"?t!==null:Ke(t)||t===xr}:function(t){return typeof t=="object"?t!==null:Ke(t)},Lt={},ce=Lt,de=P,Lr=A,Ve=function(t){return Lr(t)?t:void 0},Dt=function(t,e){return arguments.length<2?Ve(ce[t])||Ve(de[t]):ce[t]&&ce[t][e]||de[t]&&de[t][e]},Dr=N,kt=Dr({}.isPrototypeOf),kr=typeof navigator!="undefined"&&String(navigator.userAgent)||"",Bt=P,fe=kr,Ge=Bt.process,ze=Bt.Deno,Qe=Ge&&Ge.versions||ze&&ze.version,Ye=Qe&&Qe.v8,E,re;Ye&&(E=Ye.split("."),re=E[0]>0&&E[0]<4?1:+(E[0]+E[1]));!re&&fe&&(E=fe.match(/Edge\/(\d+)/),(!E||E[1]>=74)&&(E=fe.match(/Chrome\/(\d+)/),E&&(re=+E[1])));var Br=re,Xe=Br,Fr=C,Ur=P,jr=Ur.String,Ft=!!Object.getOwnPropertySymbols&&!Fr(function(){var t=Symbol();return!jr(t)||!(Object(t)instanceof Symbol)||!Symbol.sham&&Xe&&Xe<41}),Mr=Ft,Ut=Mr&&!Symbol.sham&&typeof Symbol.iterator=="symbol",Hr=Dt,Wr=A,qr=kt,Kr=Ut,Vr=Object,jt=Kr?function(t){return typeof t=="symbol"}:function(t){var e=Hr("Symbol");return Wr(e)&&qr(e.prototype,Vr(t))},Gr=String,zr=function(t){try{return Gr(t)}catch(e){return"Object"}},Qr=A,Yr=zr,Xr=TypeError,Mt=function(t){if(Qr(t))return t;throw Xr(Yr(t)+" is not a function")},Jr=Mt,Zr=xe,Ht=function(t,e){var r=t[e];return Zr(r)?void 0:Jr(r)},he=H,ve=A,pe=W,eo=TypeError,to=function(t,e){var r,o;if(e==="string"&&ve(r=t.toString)&&!pe(o=he(r,t))||ve(r=t.valueOf)&&!pe(o=he(r,t))||e!=="string"&&ve(r=t.toString)&&!pe(o=he(r,t)))return o;throw eo("Can't convert object to primitive value")},Wt={exports:{}},Je=P,ro=Object.defineProperty,oo=function(t,e){try{ro(Je,t,{value:e,configurable:!0,writable:!0})}catch(r){Je[t]=e}return e},io=P,no=oo,Ze="__core-js_shared__",ao=io[Ze]||no(Ze,{}),so=ao,et=so;(Wt.exports=function(t,e){return et[t]||(et[t]=e!==void 0?e:{})})("versions",[]).push({version:"3.31.0",mode:"pure",copyright:"\xA9 2014-2023 Denis Pushkarev (zloirock.ru)",license:"https://github.com/zloirock/core-js/blob/v3.31.0/LICENSE",source:"https://github.com/zloirock/core-js"});var lo=Wt.exports,uo=Le,co=Object,qt=function(t){return co(uo(t))},fo=N,ho=qt,vo=fo({}.hasOwnProperty),ne=Object.hasOwn||function(e,r){return vo(ho(e),r)},po=N,go=0,bo=Math.random(),mo=po(1 .toString),yo=function(t){return"Symbol("+(t===void 0?"":t)+")_"+mo(++go+bo,36)},So=P,Eo=lo,tt=ne,$o=yo,_o=Ft,wo=Ut,F=So.Symbol,ge=Eo("wks"),To=wo?F.for||F:F&&F.withoutSetter||$o,q=function(t){return tt(ge,t)||(ge[t]=_o&&tt(F,t)?F[t]:To("Symbol."+t)),ge[t]},Ao=H,rt=W,ot=jt,Oo=Ht,Po=to,No=q,Ro=TypeError,Io=No("toPrimitive"),Co=function(t,e){if(!rt(t)||ot(t))return t;var r=Oo(t,Io),o;if(r){if(e===void 0&&(e="default"),o=Ao(r,t,e),!rt(o)||ot(o))return o;throw Ro("Can't convert object to primitive value")}return e===void 0&&(e="number"),Po(t,e)},xo=Co,Lo=jt,Kt=function(t){var e=xo(t,"string");return Lo(e)?e:e+""},Do=P,it=W,Ie=Do.document,ko=it(Ie)&&it(Ie.createElement),Bo=function(t){return ko?Ie.createElement(t):{}},Fo=M,Uo=C,jo=Bo,Vt=!Fo&&!Uo(function(){return Object.defineProperty(jo("div"),"a",{get:function(){return 7}}).a!=7}),Mo=M,Ho=H,Wo=Nt,qo=Ct,Ko=Cr,Vo=Kt,Go=ne,zo=Vt,nt=Object.getOwnPropertyDescriptor;Pt.f=Mo?nt:function(e,r){if(e=Ko(e),r=Vo(r),zo)try{return nt(e,r)}catch(o){}if(Go(e,r))return qo(!Ho(Wo.f,e,r),e[r])};var Qo=C,Yo=A,Xo=/#|\.prototype\./,K=function(t,e){var r=Zo[Jo(t)];return r==ti?!0:r==ei?!1:Yo(e)?Qo(e):!!e},Jo=K.normalize=function(t){return String(t).replace(Xo,".").toLowerCase()},Zo=K.data={},ei=K.NATIVE="N",ti=K.POLYFILL="P",ri=K,at=Tt,oi=Mt,ii=oe,ni=at(at.bind),ai=function(t,e){return oi(t),e===void 0?t:ii?ni(t,e):function(){return t.apply(e,arguments)}},Gt={},si=M,li=C,ui=si&&li(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!=42}),ci=W,di=String,fi=TypeError,zt=function(t){if(ci(t))return t;throw fi(di(t)+" is not an object")},hi=M,vi=Vt,pi=ui,z=zt,st=Kt,gi=TypeError,be=Object.defineProperty,bi=Object.getOwnPropertyDescriptor,me="enumerable",ye="configurable",Se="writable";Gt.f=hi?pi?function(e,r,o){if(z(e),r=st(r),z(o),typeof e=="function"&&r==="prototype"&&"value"in o&&Se in o&&!o[Se]){var i=bi(e,r);i&&i[Se]&&(e[r]=o.value,o={configurable:ye in o?o[ye]:i[ye],enumerable:me in o?o[me]:i[me],writable:!1})}return be(e,r,o)}:be:function(e,r,o){if(z(e),r=st(r),z(o),vi)try{return be(e,r,o)}catch(i){}if("get"in o||"set"in o)throw gi("Accessors not supported");return"value"in o&&(e[r]=o.value),e};var mi=M,yi=Gt,Si=Ct,Ei=mi?function(t,e,r){return yi.f(t,e,Si(1,r))}:function(t,e,r){return t[e]=r,t},Q=P,$i=fr,_i=Tt,wi=A,Ti=Pt.f,Ai=ri,L=Lt,Oi=ai,D=Ei,lt=ne,Pi=function(t){var e=function(r,o,i){if(this instanceof e){switch(arguments.length){case 0:return new t;case 1:return new t(r);case 2:return new t(r,o)}return new t(r,o,i)}return $i(t,this,arguments)};return e.prototype=t.prototype,e},Ni=function(t,e){var r=t.target,o=t.global,i=t.stat,a=t.proto,s=o?Q:i?Q[r]:(Q[r]||{}).prototype,f=o?L:L[r]||D(L,r,{})[r],u=f.prototype,l,n,c,d,h,v,p,$,ae;for(d in e)l=Ai(o?d:r+(i?".":"#")+d,t.forced),n=!l&&s&<(s,d),v=f[d],n&&(t.dontCallGetSet?(ae=Ti(s,d),p=ae&&ae.value):p=s[d]),h=n&&p?p:e[d],!(n&&typeof v==typeof h)&&(t.bind&&n?$=Oi(h,Q):t.wrap&&n?$=Pi(h):a&&wi(h)?$=_i(h):$=h,(t.sham||h&&h.sham||v&&v.sham)&&D($,"sham",!0),D(f,d,$),a&&(c=r+"Prototype",lt(L,c)||D(L,c,{}),D(L[c],d,h),t.real&&u&&(l||!u[d])&&D(u,d,h)))},Ri=W,Ii=ie,Ci=q,xi=Ci("match"),Li=function(t){var e;return Ri(t)&&((e=t[xi])!==void 0?!!e:Ii(t)=="RegExp")},Di=q,ki=Di("toStringTag"),Qt={};Qt[ki]="z";var Bi=String(Qt)==="[object z]",Fi=Bi,Ui=A,J=ie,ji=q,Mi=ji("toStringTag"),Hi=Object,Wi=J(function(){return arguments}())=="Arguments",qi=function(t,e){try{return t[e]}catch(r){}},Ki=Fi?J:function(t){var e,r,o;return t===void 0?"Undefined":t===null?"Null":typeof(r=qi(e=Hi(t),Mi))=="string"?r:Wi?J(e):(o=J(e))=="Object"&&Ui(e.callee)?"Arguments":o},Vi=Ki,Gi=String,zi=function(t){if(Vi(t)==="Symbol")throw TypeError("Cannot convert a Symbol value to a string");return Gi(t)},Qi=zt,Yi=function(){var t=Qi(this),e="";return t.hasIndices&&(e+="d"),t.global&&(e+="g"),t.ignoreCase&&(e+="i"),t.multiline&&(e+="m"),t.dotAll&&(e+="s"),t.unicode&&(e+="u"),t.unicodeSets&&(e+="v"),t.sticky&&(e+="y"),e},Xi=H,Ji=ne,Zi=kt,en=Yi,ut=RegExp.prototype,tn=function(t){var e=t.flags;return e===void 0&&!("flags"in ut)&&!Ji(t,"flags")&&Zi(ut,t)?Xi(en,t):e},De=N,rn=qt,on=Math.floor,Ee=De("".charAt),nn=De("".replace),$e=De("".slice),an=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,sn=/\$([$&'`]|\d{1,2})/g,ln=function(t,e,r,o,i,a){var s=r+t.length,f=o.length,u=sn;return i!==void 0&&(i=rn(i),u=an),nn(a,u,function(l,n){var c;switch(Ee(n,0)){case"$":return"$";case"&":return t;case"`":return $e(e,0,r);case"'":return $e(e,s);case"<":c=i[$e(n,1,-1)];break;default:var d=+n;if(d===0)return l;if(d>f){var h=on(d/10);return h===0?l:h<=f?o[h-1]===void 0?Ee(n,1):o[h-1]+Ee(n,1):l}c=o[d-1]}return c===void 0?"":c})},un=Ni,cn=H,ke=N,ct=Le,dn=A,fn=xe,hn=Li,k=zi,vn=Ht,pn=tn,gn=ln,bn=q,mn=bn("replace"),yn=TypeError,Yt=ke("".indexOf),Sn=ke("".replace),dt=ke("".slice),En=Math.max,ft=function(t,e,r){return r>t.length?-1:e===""?r:Yt(t,e,r)};un({target:"String",proto:!0},{replaceAll:function(e,r){var o=ct(this),i,a,s,f,u,l,n,c,d,h=0,v=0,p="";if(!fn(e)){if(i=hn(e),i&&(a=k(ct(pn(e))),!~Yt(a,"g")))throw yn("`.replaceAll` does not allow non-global regexes");if(s=vn(e,mn),s)return cn(s,e,o,r);if(i)return Sn(k(o),e,r)}for(f=k(o),u=k(e),l=dn(r),l||(r=k(r)),n=u.length,c=En(1,n),h=ft(f,u,0);h!==-1;)d=l?k(r(u,h,f)):gn(u,f,h,[],void 0,r),p+=dt(f,v,h)+d,v=h+n,h=ft(f,u,h+c);return v<f.length&&(p+=dt(f,v)),p}});var $n=Dt,_n=$n,wn=_n,Tn=wn("String","replaceAll"),An=Tn,On=An,Pn=On,Nn=Pn,Rn=ur(Nn);function In(){const t="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".split(""),e=new Array(36);let r=0,o,i;for(i=0;i<36;i++)i===8||i===13||i===18||i===23?e[i]="-":i===14?e[i]="4":(r<=2&&(r=33554432+Math.random()*16777216|0),o=r&15,r=r>>4,e[i]=t[i===19?o&3|8:o]);return e.join("")}const ht="1.0.39",Cn="CIOPGQJGDIHBABABA",vt={[w.PROD]:"https://api.ok.ru",[w.VK_ALIAS]:"https://api.mycdn.me",[w.VIDEOTEST]:"https://videotestapi.ok.ru/api",[w.TEST]:"https://apitest.ok.ru",[w.AUTO]:""},xn="_one-stat_",_e=`${xn}uuid`;var R;(function(t){t[t.PARAM_SESSION_EXPIRED=102]="PARAM_SESSION_EXPIRED",t[t.PARAM_SESSION_KEY=103]="PARAM_SESSION_KEY",t[t.PARAM_SIGNATURE=104]="PARAM_SIGNATURE",t[t.AUTH_LOGIN=401]="AUTH_LOGIN"})(R||(R={}));class Ln{constructor(e){this.consequentAuthErrors=0,this.authorized$=new Ce(!1),this.params=e;const r=O.get(_e);r?r.startsWith('"')&&r.endsWith('"')?(this.uuid=Rn(r,'"',""),O.set(_e,this.uuid)):this.uuid=r:(this.uuid=In(),O.set(_e,this.uuid))}async authorize(e){return this.authToken=e!=null?e:await this.refreshAuthToken(),this._authorizeWithBackoff()}logBeacon(e){const r="log.externalLog",o=this.createLogParams(e),i=this.sessionKey;if(!i)return;this.params.apiTransport.sendBeacon(r,o,i)||this.logRequest(e)}async logRequest(e){var r;const o="log.externalLog",i=this.createLogParams(e),a=(r=this.sessionKey)!==null&&r!==void 0?r:await this._authorizeWithBackoff();if(!a)return;const s=async(f,u=this.params.config.requestRetryCount)=>{try{return await this.params.apiTransport.sendRequest(o,i,a)}catch(l){if(!l||!("error_code"in l)){this.params.error$.next({id:"logRequestUnknown",category:S.NETWORK,message:`Unknown ${o} error`,thrown:l});return}const n=l==null?void 0:l.error_code;switch(n){case R.PARAM_SESSION_EXPIRED:case R.PARAM_SESSION_KEY:case R.PARAM_SIGNATURE:return this.authorized$.next(!1),this.sessionKey=await this._authorizeWithBackoff(),u>0?s(f,u-1):void 0;case R.AUTH_LOGIN:return this.authorized$.next(!1),this.authToken=await this.refreshAuthToken(),this.sessionKey=await this._authorizeWithBackoff(),u>0?s(f,u-1):void 0;default:{this.params.error$.next({id:`LogRequest#${n}`,category:S.EXTERNAL_API,message:`${o} error`,data:l});return}}}};return s(e)}destroy(){window.clearTimeout(this.backoffTimeoutId),this.backoffTimeoutId=0}async refreshAuthToken(){if(this.params.refreshAuthToken)return this.refreshAuthTokenPromise||(this.refreshAuthTokenPromise=this.params.refreshAuthToken().finally(()=>{this.refreshAuthTokenPromise=void 0})),this.refreshAuthTokenPromise}createLogParams(e){return{collector:"ok.mobile.apps.video",data:JSON.stringify({application:`@vkontakte/videoplayer-statistics:${ht}`,platform:this.params.mobile?"M_WEB":"WEB",items:e})}}_authorizeWithBackoff(){if(!this.consequentAuthErrors)return this._authorize();const e=tr(this.consequentAuthErrors,this.params.config.backoff);return new Promise(r=>{this.backoffTimeoutId||(this.backoffTimeoutId=window.setTimeout(()=>{this._authorize().then(r).catch(o=>this.params.error$.next({id:"AuthorizeBackoff",category:S.NETWORK,message:"Otherwise unhandled error in authorization",thrown:o})).finally(()=>this.backoffTimeoutId=0)},e))})}async _authorize(){if(this.authorizePromise)return this.authorizePromise;this.sessionKey=void 0,this.authorized$.next(!1);const e="auth.anonymLogin",r={session_data:{version:2,device_id:this.uuid,client_version:ht.split("-")[0],client_type:"SDK_JS"}};return this.authToken!==void 0&&(r.session_data.auth_token=this.authToken,r.session_data.version=3),this.authorizePromise=this.params.apiTransport.sendRequest(e,r).then(o=>{var i;return(!o||!o.session_key)&&this.params.error$.next({id:"AuthorizeFailed",category:S.EXTERNAL_API,message:"No session key",data:o}),this.sessionKey=(i=o==null?void 0:o.session_key)!==null&&i!==void 0?i:void 0,this.sessionKey}).catch(async o=>{this.sessionKey=void 0;const i=o==null?void 0:o.error_code;switch(i){case R.AUTH_LOGIN:return this.authToken=await this.refreshAuthToken(),this._authorizeWithBackoff()}i?this.params.error$.next({id:`Authorize#${i}`,category:S.EXTERNAL_API,message:"authorize error",data:o}):this.params.error$.next({id:"AuthorizeUnknown",category:S.NETWORK,message:"authorize error",thrown:o})}).finally(()=>{this.authorizePromise=void 0,this.consequentAuthErrors=this.sessionKey?0:this.consequentAuthErrors+1,this.authorized$.next(this.sessionKey!==void 0)}),this.authorizePromise}}class pt{constructor(){Object.defineProperty(this,"listeners",{value:{},writable:!0,configurable:!0})}addEventListener(e,r,o){e in this.listeners||(this.listeners[e]=[]),this.listeners[e].push({callback:r,options:o})}removeEventListener(e,r){if(!(e in this.listeners))return;const o=this.listeners[e];for(let i=0,a=o.length;i<a;i++)if(o[i].callback===r){o.splice(i,1);return}}dispatchEvent(e){if(!(e.type in this.listeners))return;const o=this.listeners[e.type].slice();for(let i=0,a=o.length;i<a;i++){const s=o[i];try{s.callback.call(this,e)}catch(f){Promise.resolve().then(()=>{throw f})}s.options&&s.options.once&&this.removeEventListener(e.type,s.callback)}return!e.defaultPrevented}}class Xt extends pt{constructor(){super(),this.listeners||pt.call(this),Object.defineProperty(this,"aborted",{value:!1,writable:!0,configurable:!0}),Object.defineProperty(this,"onabort",{value:null,writable:!0,configurable:!0}),Object.defineProperty(this,"reason",{value:void 0,writable:!0,configurable:!0})}toString(){return"[object AbortSignal]"}dispatchEvent(e){e.type==="abort"&&(this.aborted=!0,typeof this.onabort=="function"&&this.onabort.call(this,e)),super.dispatchEvent(e)}}class Dn{constructor(){Object.defineProperty(this,"signal",{value:new Xt,writable:!0,configurable:!0})}abort(e){let r;try{r=new Event("abort")}catch(i){typeof document!="undefined"?document.createEvent?(r=document.createEvent("Event"),r.initEvent("abort",!1,!1)):(r=document.createEventObject(),r.type="abort"):r={type:"abort",bubbles:!1,cancelable:!1}}let o=e;if(o===void 0)if(typeof document=="undefined")o=new Error("This operation was aborted"),o.name="AbortError";else try{o=new DOMException("signal is aborted without reason")}catch(i){o=new Error("This operation was aborted"),o.name="AbortError"}this.signal.reason=o,this.signal.dispatchEvent(r)}toString(){return"[object AbortController]"}}typeof Symbol!="undefined"&&Symbol.toStringTag&&(Dn.prototype[Symbol.toStringTag]="AbortController",Xt.prototype[Symbol.toStringTag]="AbortSignal");function Jt(t){return t.__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL?(console.log("__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL=true is set, will force install polyfill"),!0):typeof t.Request=="function"&&!t.Request.prototype.hasOwnProperty("signal")||!t.AbortController}function kn(t){typeof t=="function"&&(t={fetch:t});const{fetch:e,Request:r=e.Request,AbortController:o,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:i=!1}=t;if(!Jt({fetch:e,Request:r,AbortController:o,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:i}))return{fetch:e,Request:a};let a=r;(a&&!a.prototype.hasOwnProperty("signal")||i)&&(a=function(l,n){let c;n&&n.signal&&(c=n.signal,delete n.signal);const d=new r(l,n);return c&&Object.defineProperty(d,"signal",{writable:!1,enumerable:!1,configurable:!0,value:c}),d},a.prototype=r.prototype);const s=e;return{fetch:(u,l)=>{const n=a&&a.prototype.isPrototypeOf(u)?u.signal:l?l.signal:void 0;if(n){let c;try{c=new DOMException("Aborted","AbortError")}catch(h){c=new Error("Aborted"),c.name="AbortError"}if(n.aborted)return Promise.reject(c);const d=new Promise((h,v)=>{n.addEventListener("abort",()=>v(c),{once:!0})});return l&&l.signal&&delete l.signal,Promise.race([d,s(u,l)])}return s(u,l)},Request:a}}const Be=Jt({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),Zt=Be?kn({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,gt=Be?Zt.fetch:window.fetch;Be?Zt.Request:window.Request;class Bn{constructor(e){this.params=e,this.apiKey=e.apiKey,this.apiEnv=e.config.apiEnv,this.apiBaseUrl=vt[this.apiEnv],this.timeSynchronisation=e.timeSynchronisation,this.isApiBaseUrlFetched=!1}async resolveApiBaseUrl(){var e;if(this.apiEnv!==w.AUTO||this.isApiBaseUrlFetched)return this.apiBaseUrl;try{const r=atob("aHR0cHM6Ly9kbnMuZ29vZ2xlL3Jlc29sdmU/bmFtZT12aWRlby5fZW5kcG9pbnQub2sucnUmdHlwZT1UWFQ="),i=await(await gt(r,{method:"GET",mode:"cors",cache:"no-cache"})).json(),a=(e=i==null?void 0:i.Answer[0])===null||e===void 0?void 0:e.data;if(!a)throw new Error("Wrong DNS response");return a}catch(r){return this.params.error$.next({id:"OneStat:ApiTransport:resolveApiBaseUrl",category:S.NETWORK,message:"Unhandled resolve api base url error",thrown:r}),vt[w.VK_ALIAS]}finally{this.isApiBaseUrlFetched=!0}}sendBeacon(e,r,o){if(!window.Blob||!window.navigator.sendBeacon)return!1;const i=this._prepareQueryParams({method:e,queryParams:r,sessionKey:o}),a=new window.Blob([i.toString()],{type:"application/x-www-form-urlencoded"});try{return window.navigator.sendBeacon(`${this.apiBaseUrl}/fb.do`,a)}catch(s){this.params.error$.next({id:"OneStat:ApiTransport:sendBeacon",category:S.NETWORK,message:"Unhandled beacon error",thrown:s,data:{method:e,params:r}})}return!1}async sendRequest(e,r,o){const i=m(),a=s=>{if(s instanceof TypeError&&["Failed to fetch","NetworkError when attempting to fetch resource."].includes(s.message)){this.params.error$.next({id:"Network",category:S.NETWORK,message:"Request failed",thrown:s});return}this.params.error$.next({id:"OneStat:ApiTransport:sendRequest",category:S.NETWORK,message:"Unhandled request error",thrown:s,data:{method:e,params:r,sessionKey:o,time:m()-i}})};return this.apiBaseUrl=await this.resolveApiBaseUrl(),gt(`${this.apiBaseUrl}/fb.do`,{method:"post",headers:{"Content-type":"application/x-www-form-urlencoded"},body:this._prepareQueryParams({method:e,queryParams:r,sessionKey:o})}).then(s=>{var f,u;const l=Number(s.headers.get("content-length"))===0,n=new Date((f=s.headers.get("date"))!==null&&f!==void 0?f:"").getTime(),c=m()-i;if(isFinite(n)&&((u=this.timeSynchronisation)===null||u===void 0||u.addServerTime(n,c)),!l)return s.json().then(d=>Object.prototype.hasOwnProperty.call(d,"error_msg")?Promise.reject(d):d,a)},a)}_prepareQueryParams(e){const r=new URLSearchParams({format:"JSON",method:e.method,application_key:this.apiKey});return e.sessionKey!==void 0&&r.append("session_key",e.sessionKey),Object.entries(e.queryParams).forEach(([o,i])=>r.append(o,typeof i=="string"?i:JSON.stringify(i))),r}}const Y="onestat_events",we=t=>e=>e.timestamp+t>=m();class Fn{constructor(e){this.unsaltedStorage=[],this.isPaused=!1,this.isUrgent=o=>{const{operation:i,custom:{param:a}}=o;return["action_stop","close_at_empty_buffer"].includes(i)||i==="watch_coverage_record"&&a==="0-0"},this.params=e,this.api=e.api,this.error$=e.error$,this.userSalt=e.userSalt,this.firstFlush=je(()=>this.safeFlush(),this.params.config.firstFlushTime,{maxWait:this.params.config.firstFlushTime});const r=O.isPersistent()?this.params.config.flushMaxWait:0;this.debouncedFlush=je(()=>this.safeFlush(),this.params.config.flushDebounceTime,{maxWait:r}),this.subscription=this.api.authorized$.subscribe(o=>{o&&this.debouncedFlush()}),this.housekeepStorage()}safeFlush(){var e;try{this.flush()}catch(r){this.error$.next({id:"LoggerError",category:S.WTF,message:(e=String(r))!==null&&e!==void 0?e:"Unknown logger error",thrown:r})}}readFromStorage(){const e=O.get(Y);try{return e?JSON.parse(e):{}}catch(r){}return{}}addToStorage(e){var r;if(!this.userSalt){this.unsaltedStorage.push(e);return}const o=this.readFromStorage(),a=((r=o[this.userSalt])!==null&&r!==void 0?r:[]).filter(we(this.params.config.storageExpiration));O.set(Y,JSON.stringify({...o,[this.userSalt]:[...a,e]}))}getFromStorage(){var e;return this.userSalt?((e=this.readFromStorage()[this.userSalt])!==null&&e!==void 0?e:[]).filter(we(this.params.config.storageExpiration)):this.unsaltedStorage}markStorageSent(){if(!this.userSalt){this.unsaltedStorage=[];return}const e=this.readFromStorage();delete e[this.userSalt],O.set(Y,JSON.stringify(e))}housekeepStorage(){const e=this.readFromStorage();for(const[r,o]of Object.entries(e)){const i=o.filter(we(this.params.config.storageExpiration));i.length?e[r]=i:delete e[r]}O.set(Y,JSON.stringify(e))}log(e){this.addToStorage(e),!this.isPaused&&(this.isUrgent(e)?this.flush():this.lastVsid!==e.custom.vsid?this.firstFlush():this.debouncedFlush(),this.lastVsid=e.custom.vsid)}flush(e=!1){const r=this.getFromStorage();r.length!==0&&(this.api.authorized$.getValue()?(e&&this.params.config.useBeacon?this.api.logBeacon(r):this.api.logRequest(r),this.markStorageSent()):this.api.authorize(),this.firstFlush.cancel(),this.debouncedFlush.cancel())}pause(){this.isPaused=!0,this.debouncedFlush.cancel()}resume(){this.isPaused=!1,this.debouncedFlush()}destroy(){this.subscription.unsubscribe(),this.firstFlush.cancel(),this.debouncedFlush.cancel()}}const Un=()=>{let t,e;try{t=window.self!==window.top}catch(o){o instanceof DOMException&&o.name==="SecurityError"?t=!0:(t=!1,console.error(o))}try{window.location.ancestorOrigins&&(e=window.location.ancestorOrigins[window.location.ancestorOrigins.length-1])}catch(o){console.error(o)}try{!e&&document.referrer&&(e=document.referrer)}catch(o){console.error(o)}const r=e?new URL(e).hostname:void 0;return{isEmbed:t,host:r}},jn=t=>t&&{[_.INVARIANT]:y.UNKNOWN,[_.Q_144P]:y.Q144P,[_.Q_240P]:y.Q240P,[_.Q_360P]:y.Q360P,[_.Q_480P]:y.Q480P,[_.Q_720P]:y.Q720P,[_.Q_1080P]:y.Q1080P,[_.Q_1440P]:y.Q1440P,[_.Q_2160P]:y.Q2160P,[_.Q_4320P]:y.UNKNOWN}[t],bt=t=>t&&{[se.HTTP1]:j.HTTP1,[se.HTTP2]:j.HTTP2,[se.QUIC]:j.HTTP3}[t],Mn=t=>{if(t!==void 0)switch(t){case g.MPEG:return b.MP4;case g.DASH:case g.DASH_LIVE:return b.DASH;case g.DASH_SEP:return b.DASH_SEP;case g.DASH_ONDEMAND:return b.ONDEMAND_DASH;case g.DASH_WEBM:case g.DASH_LIVE_WEBM:return b.WEBM;case g.DASH_WEBM_AV1:return b.AV1;case g.DASH_LIVE_CMAF:return b.ONDEMAND_DASH_LIVE;case g.HLS:case g.HLS_LIVE:return b.HLS;case g.HLS_ONDEMAND:return b.ONDEMAND_HLS;case g.HLS_LIVE_CMAF:return b.ONDEMAND_HLS_LIVE;case g.WEB_RTC_LIVE:return b.WEBRTC;default:return yt(t)}},Te=t=>{if(t!==void 0)switch(t){case U.NONE:case U.INLINE:return;case U.FULLSCREEN:return I.FULLSCREEN;case U.SECOND_SCREEN:return I.EXTERNAL;case U.PIP:return I.PIP;default:return yt(t)}},Hn=t=>{switch(t){case"slow-2g":return B.POOR;case"2g":return B.POOR;case"3g":return B.GOOD;case"4g":return B.EXCELLENT}};class Wn{constructor(e){this.offset=void 0,this.offset=e}getOffset(){var e;return(e=this.offset)!==null&&e!==void 0?e:0}setOffset(e){this.offset=e}now(){var e;return Date.now()+((e=this.offset)!==null&&e!==void 0?e:0)}date(e=new Date){var r;return e.setTime(e.getTime()+((r=this.offset)!==null&&r!==void 0?r:0)),e}addServerTime(e,r){const o=Date.now(),i=e-o-r/2;if(Math.abs(i)<1e3){this.offset=0;return}this.offset===void 0?this.offset=Math.round(i):this.offset=Math.round(.2*i+(1-.2)*this.offset)}}const mt=()=>Math.floor(Math.random()*2**32).toString(36).padStart(8,"0"),qn=t=>new rr(e=>{const r=new Z,o=X(Oe(window,"beforeunload"),t.events.willDestruct$),i=new Ce(void 0);let a;r.add(t.info.isLive$.pipe(or()).subscribe(p=>{a&&(a.unsubscribe(),i.next(void 0)),p?a=t.info.liveTime$.pipe(ir($=>$&&$/1e3)).subscribe(i):a=t.info.position$.subscribe(i),r.add(a)}));const{playing$:s,paused$:f}=t.events,u=t.events.willSeek$.pipe(Fe(()=>t.info.playbackState$.getValue()===Me.PLAYING)),l=t.events.seeked$.pipe(Fe(()=>t.info.playbackState$.getValue()===Me.PLAYING));let n=!1;const c=new St;r.add(u.subscribe(()=>{n||c.next(),n=!0})),r.add(l.subscribe(()=>n=!1));const d=X(s,l),h=X(f,c,o,t.events.looped$);let v;return r.add(d.subscribe(()=>v=i.getValue())),r.add(h.subscribe(()=>{const p=i.getValue();Pe(v)||v===p||Pe(p)||(e.next({from:v,to:p}),v=void 0)})),r}),Ae=()=>{const t=new Z;return{subscription:t,subscribe:(e,r)=>{e&&t.add(e.subscribe(r))}}};class zn{constructor(e,r){var o,i;this.subscription=new Z,this.vsid=mt(),this.seekAction$=new Ce(te.UNKNOWN),this.statContext=e,this.config=lr((o=r.config)!==null&&o!==void 0?o:{}),x(r.apiEnv)&&(this.config.apiEnv=r.apiEnv),this.config.synchronizeTime&&(this.timeSynchronisation=new Wn);const a=new St;this.experimental={error$:a};const s=new Bn({apiKey:Cn,config:this.config,error$:a,timeSynchronisation:this.timeSynchronisation});this.api=new Ln({config:this.config,apiTransport:s,refreshAuthToken:r.refreshAuthToken,mobile:(i=this.statContext.mobile)!==null&&i!==void 0?i:!1,error$:a}),this.logger=new Fn({config:this.config,api:this.api,error$:a,userSalt:r.userSalt});const{isEmbed:f,host:u}=Un();this.isEmbed=f,this.embedParent=u,this.subscribe()}updateContext(e){this.statContext={...this.statContext,...e}}attachTo(e){const r=new Z,o=(n,c)=>r.add(n.subscribe(c));o(e.events.willStart$,()=>{this.logActionPlay({position:e.info.position$.getValue()})}),o(e.events.looped$,()=>{this.resetViewSession(),this.logActionPlay({position:e.info.position$.getValue()})}),o(e.events.seeked$,()=>{this.logSeek({action:this.seekAction$.getValue(),time:e.info.position$.getValue()}),this.seekAction$.next(te.UNKNOWN)}),o(e.events.paused$,()=>{this.logPause({position:e.info.position$.getValue()})}),o(e.events.willResume$,()=>{this.logPlay()}),o(e.events.started$,()=>{this.statContext.clip&&this.logWatchCoverageRecord({start:0,end:0})}),o(qn(e),n=>{const c=e.info.isLive$.getValue(),d={start:parseFloat(n.from.toFixed(3)),end:parseFloat(n.to.toFixed(3))};c?this.logWatchCoverageLive(d):this.logWatchCoverageRecord(d)});let i;o(e.info.isStalled$,n=>{n?i=m():(x(i)&&this.logEmptyBuffer({duration:m()-i}),i=void 0)});let a=!1;r.add(e.events.fatalError$.pipe(nr()).subscribe(()=>a=!0)),o(e.events.willStop$,()=>{if(e.info.isStalled$.getValue()){const c=x(i)?m()-i:void 0;this.logCloseAtEmptyBuffer({duration:c!=null?c:0}),i=void 0}else a||this.logActionStop()}),o(e.events.managedError$,({id:n})=>{this.logError({fatal:!1,errorType:n})}),o(e.events.fatalError$,({id:n})=>{this.logError({fatal:!0,errorType:n})});let s,f,u=!1;o(e.events.firstBytes$,n=>{s=m(),this.logFirstBytes({time:n})}),o(e.events.willStart$,()=>f=m()),o(e.info.currentBuffer$,n=>{!u&&n&&n.end-n.start>0&&x(s)&&(this.logPlayerReady({duration:m()-s}),u=!0)}),o(e.events.firstFrame$,()=>{x(s)&&!u&&(this.logPlayerReady({duration:m()-s}),u=!0),x(f)&&this.logFirstFrame({time:m()-f})}),o(e.info.atLiveEdge$,n=>this.updateContext({liveEdge:n})),o(Ue({muted:e.info.muted$,volume:e.info.volume$}),({muted:n,volume:c})=>this.updateContext({audible:!n&&c>0})),o(e.info.currentQuality$,n=>this.updateContext({quality:jn(n)})),o(e.info.isAutoQualityEnabled$,n=>this.updateContext({autoQuality:n})),o(e.info.currentFormat$,n=>this.updateContext({contentType:Mn(n)}));let l;return o(e.info.hostname$,n=>{this.updateContext({cdnHostname:n,failover:l!==void 0&&l!==n}),l=n}),o(e.info.throughputEstimation$,n=>this.updateContext({downloadSpeed:n})),o(e.info.httpConnectionType$,n=>{this.statContext.firstConnectionType||this.updateContext({firstConnectionType:bt(n)}),this.updateContext({connectionType:bt(n)})}),o(e.info.httpConnectionReused$,n=>{Pe(this.statContext.firstConnectionReused)&&this.updateContext({firstConnectionReused:n}),this.updateContext({connectionReused:n})}),o(e.info.surface$,n=>this.updateContext({mode:Te(n)})),o(Ue({current:e.info.currentTextTrack$,available:e.info.availableTextTracks$}),({current:n,available:c})=>{const d=c.find(({id:h})=>h===n);this.updateContext({subtitles:d==null?void 0:d.language})}),this.player=e,this.uiEvents&&this.attachToUi(this.uiEvents),this.resubscribeBeforeunload(),this.subscription.add(r),r}attachToUi(e){this.uiEvents=e;const{subscription:r,subscribe:o}=Ae();return this.player&&(o(e.actionRewind$,()=>{this.player&&(this.resetViewSession(),this.logActionPlay({position:this.player.info.position$.getValue()}))}),o(e.actionSeek$,this.seekAction$),o(e.inPiP$,i=>{var a;const s=i?I.PIP:Te((a=this.player)===null||a===void 0?void 0:a.info.surface$.getValue());this.updateContext({mode:s})}),o(e.inFullscreen$,i=>{var a;const s=i?I.FULLSCREEN:Te((a=this.player)===null||a===void 0?void 0:a.info.surface$.getValue());this.updateContext({mode:s})}),o(e.actionSetSubtitle$,i=>this.updateContext({subtitles:i})),o(e.nextMovie$,i=>this.logNextMovie(i)),this.resubscribeBeforeunload(),this.subscription.add(r)),r}attachToAds(e){const{subscription:r,subscribe:o}=Ae();return o(e.slotRequested$,()=>this.logAdSlotRequest()),o(e.started$,i=>this.logAdStarted(i)),o(e.paused$,()=>this.logAdPaused()),o(e.resumed$,()=>this.logAdResumed()),o(e.ended$,()=>this.logAdEnded()),o(e.skipped$,()=>this.logAdSkipped()),o(e.clicked$,()=>this.logAdClicked()),this.resubscribeBeforeunload(),this.subscription.add(r),r}attachToInteractive(e){const{subscription:r,subscribe:o}=Ae();return o(e.click$,i=>this.logInterfaceClick(i)),o(e.nextMovie$,i=>this.logNextMovie(i)),this.resubscribeBeforeunload(),this.subscription.add(r),r}authorize(e){return this.api.authorize(e)}pause(){this.logger.pause()}resume(){this.logger.resume()}destroy(){this.logger.flush(),this.subscription.unsubscribe(),this.api.destroy(),this.logger.destroy()}resetViewSession(){this.vsid=mt()}setFieldBlacklist(){}logInited(){}logReady(e){this.log({operation:"player_ready",param:String(e.time)})}logStarted(...e){this.logActionPlay(...e)}logPlay(){this.log({operation:"play_toggle"})}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}`})}logWatchCoverageLive(e){var r,o;const i=(o=(r=this.timeSynchronisation)===null||r===void 0?void 0:r.getOffset())!==null&&o!==void 0?o:0,a=e.start+i,s=e.end+i;this.log({operation:"watch_coverage_live",param:`${a}-${s}`})}logEmptyBuffer(e){this.log({operation:"empty_buffer",param:String(e.duration)})}logDownloadSpeed(){}logAdSlotRequest(){this.log({operation:"adv",param:"slot_request"})}logAdStarted(e){this.log({operation:"adv",param:e})}logAdPaused(){this.log({operation:"adv",param:"pause"})}logAdResumed(){this.log({operation:"adv",param:"resume"})}logAdEnded(){this.log({operation:"adv",param:"ended"})}logAdSkipped(){this.log({operation:"adv",param:"skip"})}logAdClicked(){this.log({operation:"adv",param:"click"})}logInterfaceClick(e){this.log({operation:"player_interface_click",param:e})}logNextMovie(e){this.log({operation:"next_movie",param:String(e)})}subscribe(){this.resubscribeBeforeunload();const e=window.navigator.connection;e&&"onchange"in e&&"effectiveType"in e&&this.subscription.add(X(Oe(e,"change"),ar(["init"])).subscribe(()=>this.updateContext({network:Hn(e.effectiveType)})))}resubscribeBeforeunload(){var e;(e=this.beforeunloadSubscription)===null||e===void 0||e.unsubscribe(),this.beforeunloadSubscription=Oe(window,"beforeunload").subscribe(()=>this.logger.flush(!0)),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))})}logCloseAtEmptyBuffer(e){this.log({operation:"close_at_empty_buffer",param:String(Math.round(e.duration))})}logActionStop(){this.log({operation:"action_stop"})}log(e){if(this.config.disabledOperations.includes(e.operation))return;const r=this.createLogItem(e);this.logger.log(r)}createLogItem({operation:e,param:r,time:o}){var i,a;const s=(a=(i=this.timeSynchronisation)===null||i===void 0?void 0:i.now())!==null&&a!==void 0?a:m(),f=e==="empty_buffer"||e==="close_at_empty_buffer"?this.statContext.connectionType:this.statContext.firstConnectionType,u=this.statContext.firstConnectionReused,l={vsid:this.vsid,vid:this.statContext.movieId,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?ee.AUTO:this.statContext.autoplay===!1?ee.MANUAL:void 0,param:r,vk_app_id:this.statContext.vkAppId,track_code:this.statContext.trackCode,connection_type:f,connection_reused:u===!0?T.YES:u===!1?T.NO:void 0,cached_data:this.statContext.cached===!0?T.YES:this.statContext.cached===!1?T.NO:void 0,live:this.statContext.liveEdge?T.YES:void 0,muted:this.statContext.audible===!1?T.YES:void 0,mode:this.statContext.mode,subtitles:this.statContext.subtitles,download_speed:this.statContext.downloadSpeed,manual_quality:this.statContext.autoQuality?void 0:T.YES,ref_domain:this.isEmbed?this.embedParent:this.statContext.refUrl,aid:this.statContext.albumId,vk_playlist_id:this.statContext.vkPlaylistId};for(const n of this.config.disabledCustomFields)delete l[n];return{operation:e,type:1,time:o,network:this.statContext.network,timestamp:s,custom:l}}}export{w as ApiEnv,j as ConnectionType,b as ContentType,He as InteractiveInterfaceClick,zn as OneStat,y as Quality,te as SeekAction,ht as VERSION};
|
package/esnext.cjs.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @vkontakte/videoplayer-statistics v1.0.
|
|
3
|
-
*
|
|
4
|
-
* https://st.mycdn.me/static/vkontakte-videoplayer/1-0-
|
|
2
|
+
* @vkontakte/videoplayer-statistics v1.0.39
|
|
3
|
+
* Tue, 29 Aug 2023 12:33:55 GMT
|
|
4
|
+
* https://st.mycdn.me/static/vkontakte-videoplayer/1-0-39/doc/
|
|
5
5
|
*/
|
|
6
|
-
"use strict";var r=require("@vkontakte/videoplayer-shared/esnext.cjs.js"),O=require("lodash/debounce.js"),c=require("@vkontakte/videoplayer-core/esnext.cjs.js");exports.ApiEnv=void 0;(function(t){t.PROD="prod",t.VK_ALIAS="vk_alias",t.VIDEOTEST="videotest",t.TEST="test",t.AUTO="auto"})(exports.ApiEnv||(exports.ApiEnv={}));exports.Quality=void 0;(function(t){t.Q144P="mobile",t.Q240P="lowest",t.Q360P="low",t.Q480P="medium",t.Q720P="high",t.Q1080P="fullhd",t.Q1440P="quadhd",t.Q2160P="ultrahd",t.UNKNOWN="unknown"})(exports.Quality||(exports.Quality={}));exports.ContentType=void 0;(function(t){t.MP4="mp4",t.DASH="dash",t.DASH_SEP="dash_sep",t.ONDEMAND_DASH="ondemand_dash",t.HLS="hls",t.ONDEMAND_HLS="ondemand_hls",t.WEBM="webm",t.AV1="av1",t.ONDEMAND_DASH_LIVE="ondemand_dash_live",t.ONDEMAND_HLS_LIVE="ondemand_hls_live",t.WEBRTC="webrtc",t.UNKNOWN="unknown",t.RTMP="rtmp"})(exports.ContentType||(exports.ContentType={}));var w;(function(t){t.AUTO="auto",t.MANUAL=""})(w||(w={}));exports.ConnectionType=void 0;(function(t){t.HTTP1="http1",t.HTTP2="http2",t.HTTP3="http3"})(exports.ConnectionType||(exports.ConnectionType={}));var g;(function(t){t[t.YES=1]="YES",t[t.NO=0]="NO"})(g||(g={}));var E;(function(t){t.EXCELLENT="excellent",t.GOOD="good",t.POOR="poor"})(E||(E={}));var S;(function(t){t.PIP="pip",t.FULLSCREEN="fullscreen",t.EXTERNAL="external",t.PREFETCH="prefetch"})(S||(S={}));exports.SeekAction=void 0;(function(t){t.SLIDER="slider",t.DOUBLE_TAP="double_tap",t.TIME_CODE="time_code",t.EPISODE="episode",t.REWIND="rewind",t.LIVE="live",t.UNKNOWN="unknown"})(exports.SeekAction||(exports.SeekAction={}));exports.InteractiveInterfaceClick=void 0;(function(t){t.GRAPH_SHOW="iGraphShow",t.GRAPH_HIDE="iGraphHide",t.NEXT_AREA="iNextChapterArea",t.NEXT_BUTTON="iNextChapterBtn",t.WATCH_AGAIN="iWatchAgainBtn"})(exports.InteractiveInterfaceClick||(exports.InteractiveInterfaceClick={}));const V={apiEnv:exports.ApiEnv.VK_ALIAS,requestRetryCount:1,firstFlushTime:5e3,flushDebounceTime:1e4,flushMaxWait:6e4,storageExpiration:36*60*60*1e3,disabledOperations:[],disabledCustomFields:[],useBeacon:!0,synchronizeTime:!0,backoff:{start:1e3,factor:1.5,max:5*60*1e3,random:.1}},U=t=>r.fillWithDefault(t,V);function H(){const t="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".split(""),e=new Array(36);let i=0,s,o;for(o=0;o<36;o++)o===8||o===13||o===18||o===23?e[o]="-":o===14?e[o]="4":(i<=2&&(i=33554432+Math.random()*16777216|0),s=i&15,i=i>>4,e[o]=t[o===19?s&3|8:s]);return e.join("")}const N="1.0.38",M="CIOPGQJGDIHBABABA",R={[exports.ApiEnv.PROD]:"https://api.ok.ru",[exports.ApiEnv.VK_ALIAS]:"https://api.mycdn.me",[exports.ApiEnv.VIDEOTEST]:"https://videotestapi.ok.ru/api",[exports.ApiEnv.TEST]:"https://apitest.ok.ru",[exports.ApiEnv.AUTO]:""},q="_one-stat_",x=`${q}uuid`;var m;(function(t){t[t.PARAM_SESSION_EXPIRED=102]="PARAM_SESSION_EXPIRED",t[t.PARAM_SESSION_KEY=103]="PARAM_SESSION_KEY",t[t.PARAM_SIGNATURE=104]="PARAM_SIGNATURE",t[t.AUTH_LOGIN=401]="AUTH_LOGIN"})(m||(m={}));class W{params;uuid;authToken;sessionKey;authorizePromise;refreshAuthTokenPromise;consequentAuthErrors=0;authorized$=new r.ValueSubject(!1);backoffTimeoutId;constructor(e){this.params=e;const i=r.safeStorage.get(x);i?this.uuid=String(i):(this.uuid=H(),r.safeStorage.set(x,this.uuid))}async authorize(e){return this.authToken=e??await this.refreshAuthToken(),this._authorizeWithBackoff()}logBeacon(e){const i="log.externalLog",s=this.createLogParams(e),o=this.sessionKey;if(!o)return;this.params.apiTransport.sendBeacon(i,s,o)||this.logRequest(e)}async logRequest(e){const i="log.externalLog",s=this.createLogParams(e),o=this.sessionKey??await this._authorizeWithBackoff();if(!o)return;const a=async(u,f=this.params.config.requestRetryCount)=>{try{return await this.params.apiTransport.sendRequest(i,s,o)}catch(l){if(!l||!("error_code"in l)){this.params.error$.next({id:"logRequestUnknown",category:r.ErrorCategory.NETWORK,message:`Unknown ${i} error`,thrown:l});return}const h=l?.error_code;switch(h){case m.PARAM_SESSION_EXPIRED:case m.PARAM_SESSION_KEY:case m.PARAM_SIGNATURE:return this.authorized$.next(!1),this.sessionKey=await this._authorizeWithBackoff(),f>0?a(u,f-1):void 0;case m.AUTH_LOGIN:return this.authorized$.next(!1),this.authToken=await this.refreshAuthToken(),this.sessionKey=await this._authorizeWithBackoff(),f>0?a(u,f-1):void 0;default:{this.params.error$.next({id:`LogRequest#${h}`,category:r.ErrorCategory.EXTERNAL_API,message:`${i} error`,data:l});return}}}};return a(e)}destroy(){window.clearTimeout(this.backoffTimeoutId),this.backoffTimeoutId=0}async refreshAuthToken(){if(this.params.refreshAuthToken)return this.refreshAuthTokenPromise||(this.refreshAuthTokenPromise=this.params.refreshAuthToken().finally(()=>{this.refreshAuthTokenPromise=void 0})),this.refreshAuthTokenPromise}createLogParams(e){return{collector:"ok.mobile.apps.video",data:JSON.stringify({application:`@vkontakte/videoplayer-statistics:${N}`,platform:this.params.mobile?"M_WEB":"WEB",items:e})}}_authorizeWithBackoff(){if(!this.consequentAuthErrors)return this._authorize();const e=r.getExponentialDelay(this.consequentAuthErrors,this.params.config.backoff);return new Promise(i=>{this.backoffTimeoutId||(this.backoffTimeoutId=window.setTimeout(()=>{this._authorize().then(i).catch(s=>this.params.error$.next({id:"AuthorizeBackoff",category:r.ErrorCategory.NETWORK,message:"Otherwise unhandled error in authorization",thrown:s})).finally(()=>this.backoffTimeoutId=0)},e))})}async _authorize(){if(this.authorizePromise)return this.authorizePromise;this.sessionKey=void 0,this.authorized$.next(!1);const e="auth.anonymLogin",i={session_data:{version:2,device_id:this.uuid,client_version:N.split("-")[0],client_type:"SDK_JS"}};return this.authToken!==void 0&&(i.session_data.auth_token=this.authToken,i.session_data.version=3),this.authorizePromise=this.params.apiTransport.sendRequest(e,i).then(s=>((!s||!s.session_key)&&this.params.error$.next({id:"AuthorizeFailed",category:r.ErrorCategory.EXTERNAL_API,message:"No session key",data:s}),this.sessionKey=s?.session_key??void 0,this.sessionKey)).catch(async s=>{this.sessionKey=void 0;const o=s?.error_code;switch(o){case m.AUTH_LOGIN:return this.authToken=await this.refreshAuthToken(),this._authorizeWithBackoff()}o?this.params.error$.next({id:`Authorize#${o}`,category:r.ErrorCategory.EXTERNAL_API,message:"authorize error",data:s}):this.params.error$.next({id:"AuthorizeUnknown",category:r.ErrorCategory.NETWORK,message:"authorize error",thrown:s})}).finally(()=>{this.authorizePromise=void 0,this.consequentAuthErrors=this.sessionKey?0:this.consequentAuthErrors+1,this.authorized$.next(this.sessionKey!==void 0)}),this.authorizePromise}}class k{constructor(){Object.defineProperty(this,"listeners",{value:{},writable:!0,configurable:!0})}addEventListener(e,i,s){e in this.listeners||(this.listeners[e]=[]),this.listeners[e].push({callback:i,options:s})}removeEventListener(e,i){if(!(e in this.listeners))return;const s=this.listeners[e];for(let o=0,a=s.length;o<a;o++)if(s[o].callback===i){s.splice(o,1);return}}dispatchEvent(e){if(!(e.type in this.listeners))return;const s=this.listeners[e.type].slice();for(let o=0,a=s.length;o<a;o++){const u=s[o];try{u.callback.call(this,e)}catch(f){Promise.resolve().then(()=>{throw f})}u.options&&u.options.once&&this.removeEventListener(e.type,u.callback)}return!e.defaultPrevented}}class F extends k{constructor(){super(),this.listeners||k.call(this),Object.defineProperty(this,"aborted",{value:!1,writable:!0,configurable:!0}),Object.defineProperty(this,"onabort",{value:null,writable:!0,configurable:!0}),Object.defineProperty(this,"reason",{value:void 0,writable:!0,configurable:!0})}toString(){return"[object AbortSignal]"}dispatchEvent(e){e.type==="abort"&&(this.aborted=!0,typeof this.onabort=="function"&&this.onabort.call(this,e)),super.dispatchEvent(e)}}class Q{constructor(){Object.defineProperty(this,"signal",{value:new F,writable:!0,configurable:!0})}abort(e){let i;try{i=new Event("abort")}catch{typeof document<"u"?document.createEvent?(i=document.createEvent("Event"),i.initEvent("abort",!1,!1)):(i=document.createEventObject(),i.type="abort"):i={type:"abort",bubbles:!1,cancelable:!1}}let s=e;if(s===void 0)if(typeof document>"u")s=new Error("This operation was aborted"),s.name="AbortError";else try{s=new DOMException("signal is aborted without reason")}catch{s=new Error("This operation was aborted"),s.name="AbortError"}this.signal.reason=s,this.signal.dispatchEvent(i)}toString(){return"[object AbortController]"}}typeof Symbol<"u"&&Symbol.toStringTag&&(Q.prototype[Symbol.toStringTag]="AbortController",F.prototype[Symbol.toStringTag]="AbortSignal");function D(t){return t.__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL?(console.log("__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL=true is set, will force install polyfill"),!0):typeof t.Request=="function"&&!t.Request.prototype.hasOwnProperty("signal")||!t.AbortController}function K(t){typeof t=="function"&&(t={fetch:t});const{fetch:e,Request:i=e.Request,AbortController:s,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:o=!1}=t;if(!D({fetch:e,Request:i,AbortController:s,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:o}))return{fetch:e,Request:a};let a=i;(a&&!a.prototype.hasOwnProperty("signal")||o)&&(a=function(h,n){let d;n&&n.signal&&(d=n.signal,delete n.signal);const p=new i(h,n);return d&&Object.defineProperty(p,"signal",{writable:!1,enumerable:!1,configurable:!0,value:d}),p},a.prototype=i.prototype);const u=e;return{fetch:(l,h)=>{const n=a&&a.prototype.isPrototypeOf(l)?l.signal:h?h.signal:void 0;if(n){let d;try{d=new DOMException("Aborted","AbortError")}catch{d=new Error("Aborted"),d.name="AbortError"}if(n.aborted)return Promise.reject(d);const p=new Promise((y,b)=>{n.addEventListener("abort",()=>b(d),{once:!0})});return h&&h.signal&&delete h.signal,Promise.race([p,u(l,h)])}return u(l,h)},Request:a}}const C=D({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),B=C?K({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,$=C?B.fetch:window.fetch;C?B.Request:window.Request;class z{apiKey;apiBaseUrl;apiEnv;timeSynchronisation;isApiBaseUrlFetched;params;constructor(e){this.params=e,this.apiKey=e.apiKey,this.apiEnv=e.config.apiEnv,this.apiBaseUrl=R[this.apiEnv],this.timeSynchronisation=e.timeSynchronisation,this.isApiBaseUrlFetched=!1}async resolveApiBaseUrl(){if(this.apiEnv!==exports.ApiEnv.AUTO||this.isApiBaseUrlFetched)return this.apiBaseUrl;try{const e=atob("aHR0cHM6Ly9kbnMuZ29vZ2xlL3Jlc29sdmU/bmFtZT12aWRlby5fZW5kcG9pbnQub2sucnUmdHlwZT1UWFQ="),o=(await(await $(e,{method:"GET",mode:"cors",cache:"no-cache"})).json())?.Answer[0]?.data;if(!o)throw new Error("Wrong DNS response");return o}catch(e){return this.params.error$.next({id:"OneStat:ApiTransport:resolveApiBaseUrl",category:r.ErrorCategory.NETWORK,message:"Unhandled resolve api base url error",thrown:e}),R[exports.ApiEnv.VK_ALIAS]}finally{this.isApiBaseUrlFetched=!0}}sendBeacon(e,i,s){if(!window.Blob||!window.navigator.sendBeacon)return!1;const o=this._prepareQueryParams({method:e,queryParams:i,sessionKey:s}),a=new window.Blob([o.toString()],{type:"application/x-www-form-urlencoded"});try{return window.navigator.sendBeacon(`${this.apiBaseUrl}/fb.do`,a)}catch(u){this.params.error$.next({id:"OneStat:ApiTransport:sendBeacon",category:r.ErrorCategory.NETWORK,message:"Unhandled beacon error",thrown:u,data:{method:e,params:i}})}return!1}async sendRequest(e,i,s){const o=r.now(),a=u=>{if(u instanceof TypeError&&["Failed to fetch","NetworkError when attempting to fetch resource."].includes(u.message)){this.params.error$.next({id:"Network",category:r.ErrorCategory.NETWORK,message:"Request failed",thrown:u});return}this.params.error$.next({id:"OneStat:ApiTransport:sendRequest",category:r.ErrorCategory.NETWORK,message:"Unhandled request error",thrown:u,data:{method:e,params:i,sessionKey:s,time:r.now()-o}})};return this.apiBaseUrl=await this.resolveApiBaseUrl(),$(`${this.apiBaseUrl}/fb.do`,{method:"post",headers:{"Content-type":"application/x-www-form-urlencoded"},body:this._prepareQueryParams({method:e,queryParams:i,sessionKey:s})}).then(u=>{const f=Number(u.headers.get("content-length"))===0,l=new Date(u.headers.get("date")??"").getTime(),h=r.now()-o;if(isFinite(l)&&this.timeSynchronisation?.addServerTime(l,h),!f)return u.json().then(n=>Object.prototype.hasOwnProperty.call(n,"error_msg")?Promise.reject(n):n,a)},a)}_prepareQueryParams(e){const i=new URLSearchParams({format:"JSON",method:e.method,application_key:this.apiKey});return e.sessionKey!==void 0&&i.append("session_key",e.sessionKey),Object.entries(e.queryParams).forEach(([s,o])=>i.append(s,typeof o=="string"?o:JSON.stringify(o))),i}}const _="onestat_events",v=t=>e=>e.timestamp+t>=r.now();class j{params;api;error$;subscription;userSalt;unsaltedStorage=[];lastVsid;isPaused=!1;firstFlush;debouncedFlush;constructor(e){this.params=e,this.api=e.api,this.error$=e.error$,this.userSalt=e.userSalt,this.firstFlush=O(()=>this.safeFlush(),this.params.config.firstFlushTime,{maxWait:this.params.config.firstFlushTime});const i=r.safeStorage.isPersistent()?this.params.config.flushMaxWait:0;this.debouncedFlush=O(()=>this.safeFlush(),this.params.config.flushDebounceTime,{maxWait:i}),this.subscription=this.api.authorized$.subscribe(s=>{s&&this.debouncedFlush()}),this.housekeepStorage()}isUrgent=e=>{const{operation:i,custom:{param:s}}=e;return["action_stop","close_at_empty_buffer"].includes(i)||i==="watch_coverage_record"&&s==="0-0"};safeFlush(){try{this.flush()}catch(e){this.error$.next({id:"LoggerError",category:r.ErrorCategory.WTF,message:String(e)??"Unknown logger error",thrown:e})}}readFromStorage(){const e=r.safeStorage.get(_);try{return e?JSON.parse(e):{}}catch{}return{}}addToStorage(e){if(!this.userSalt){this.unsaltedStorage.push(e);return}const i=this.readFromStorage(),o=(i[this.userSalt]??[]).filter(v(this.params.config.storageExpiration));r.safeStorage.set(_,JSON.stringify({...i,[this.userSalt]:[...o,e]}))}getFromStorage(){return this.userSalt?(this.readFromStorage()[this.userSalt]??[]).filter(v(this.params.config.storageExpiration)):this.unsaltedStorage}markStorageSent(){if(!this.userSalt){this.unsaltedStorage=[];return}const e=this.readFromStorage();delete e[this.userSalt],r.safeStorage.set(_,JSON.stringify(e))}housekeepStorage(){const e=this.readFromStorage();for(const[i,s]of Object.entries(e)){const o=s.filter(v(this.params.config.storageExpiration));o.length?e[i]=o:delete e[i]}r.safeStorage.set(_,JSON.stringify(e))}log(e){this.addToStorage(e),!this.isPaused&&(this.isUrgent(e)?this.flush():this.lastVsid!==e.custom.vsid?this.firstFlush():this.debouncedFlush(),this.lastVsid=e.custom.vsid)}flush(e=!1){const i=this.getFromStorage();i.length!==0&&(this.api.authorized$.getValue()?(e&&this.params.config.useBeacon?this.api.logBeacon(i):this.api.logRequest(i),this.markStorageSent()):this.api.authorize(),this.firstFlush.cancel(),this.debouncedFlush.cancel())}pause(){this.isPaused=!0,this.debouncedFlush.cancel()}resume(){this.isPaused=!1,this.debouncedFlush()}destroy(){this.subscription.unsubscribe(),this.firstFlush.cancel(),this.debouncedFlush.cancel()}}const G=()=>{let t,e;try{t=window.self!==window.top}catch(s){s instanceof DOMException&&s.name==="SecurityError"?t=!0:(t=!1,console.error(s))}try{window.location.ancestorOrigins&&(e=window.location.ancestorOrigins[window.location.ancestorOrigins.length-1])}catch(s){console.error(s)}try{!e&&document.referrer&&(e=document.referrer)}catch(s){console.error(s)}const i=e?new URL(e).hostname:void 0;return{isEmbed:t,host:i}},Y=t=>t&&{[c.VideoQuality.INVARIANT]:exports.Quality.UNKNOWN,[c.VideoQuality.Q_144P]:exports.Quality.Q144P,[c.VideoQuality.Q_240P]:exports.Quality.Q240P,[c.VideoQuality.Q_360P]:exports.Quality.Q360P,[c.VideoQuality.Q_480P]:exports.Quality.Q480P,[c.VideoQuality.Q_720P]:exports.Quality.Q720P,[c.VideoQuality.Q_1080P]:exports.Quality.Q1080P,[c.VideoQuality.Q_1440P]:exports.Quality.Q1440P,[c.VideoQuality.Q_2160P]:exports.Quality.Q2160P,[c.VideoQuality.Q_4320P]:exports.Quality.UNKNOWN}[t],L=t=>t&&{[c.HttpConnectionType.HTTP1]:exports.ConnectionType.HTTP1,[c.HttpConnectionType.HTTP2]:exports.ConnectionType.HTTP2,[c.HttpConnectionType.QUIC]:exports.ConnectionType.HTTP3}[t],X=t=>{if(t!==void 0)switch(t){case c.VideoFormat.MPEG:return exports.ContentType.MP4;case c.VideoFormat.DASH:case c.VideoFormat.DASH_LIVE:return exports.ContentType.DASH;case c.VideoFormat.DASH_SEP:return exports.ContentType.DASH_SEP;case c.VideoFormat.DASH_ONDEMAND:return exports.ContentType.ONDEMAND_DASH;case c.VideoFormat.DASH_WEBM:case c.VideoFormat.DASH_LIVE_WEBM:return exports.ContentType.WEBM;case c.VideoFormat.DASH_WEBM_AV1:return exports.ContentType.AV1;case c.VideoFormat.DASH_LIVE_CMAF:return exports.ContentType.ONDEMAND_DASH_LIVE;case c.VideoFormat.HLS:case c.VideoFormat.HLS_LIVE:return exports.ContentType.HLS;case c.VideoFormat.HLS_ONDEMAND:return exports.ContentType.ONDEMAND_HLS;case c.VideoFormat.HLS_LIVE_CMAF:return exports.ContentType.ONDEMAND_HLS_LIVE;case c.VideoFormat.WEB_RTC_LIVE:return exports.ContentType.WEBRTC;default:return r.assertNever(t)}},P=t=>{if(t!==void 0)switch(t){case c.Surface.NONE:case c.Surface.INLINE:return;case c.Surface.FULLSCREEN:return S.FULLSCREEN;case c.Surface.SECOND_SCREEN:return S.EXTERNAL;case c.Surface.PIP:return S.PIP;default:return r.assertNever(t)}},J=t=>{switch(t){case"slow-2g":return E.POOR;case"2g":return E.POOR;case"3g":return E.GOOD;case"4g":return E.EXCELLENT}};class Z{offset=void 0;constructor(e){this.offset=e}getOffset(){return this.offset??0}setOffset(e){this.offset=e}now(){return Date.now()+(this.offset??0)}date(e=new Date){return e.setTime(e.getTime()+(this.offset??0)),e}addServerTime(e,i){const s=Date.now(),o=e-s-i/2;if(Math.abs(o)<1e3){this.offset=0;return}this.offset===void 0?this.offset=Math.round(o):this.offset=Math.round(.2*o+(1-.2)*this.offset)}}const I=()=>Math.floor(Math.random()*2**32).toString(36).padStart(8,"0"),ee=t=>new r.Observable(e=>{const i=new r.Subscription,s=r.merge(r.fromEvent(window,"beforeunload"),t.events.willDestruct$),o=new r.ValueSubject(void 0);let a;i.add(t.info.isLive$.pipe(r.filterChanged()).subscribe(A=>{a&&(a.unsubscribe(),o.next(void 0)),A?a=t.info.liveTime$.pipe(r.map(T=>T&&T/1e3)).subscribe(o):a=t.info.position$.subscribe(o),i.add(a)}));const{playing$:u,paused$:f}=t.events,l=t.events.willSeek$.pipe(r.filter(()=>t.info.playbackState$.getValue()===c.PlaybackState.PLAYING)),h=t.events.seeked$.pipe(r.filter(()=>t.info.playbackState$.getValue()===c.PlaybackState.PLAYING));let n=!1;i.add(l.subscribe(()=>n=!0)),i.add(h.subscribe(()=>n=!1));const d=l.pipe(r.filter(()=>!n)),p=r.merge(u,h),y=r.merge(f,d,s,t.events.looped$);let b;return i.add(p.subscribe(()=>b=o.getValue())),i.add(y.subscribe(()=>{const A=o.getValue();r.isNullable(b)||b===A||r.isNullable(A)||(e.next({from:b,to:A}),b=void 0)})),i});class te{api;logger;config;subscription=new r.Subscription;beforeunloadSubscription;timeSynchronisation;experimental;statContext;vsid=I();isEmbed;embedParent;uiEvents;player;seekAction$=new r.ValueSubject(exports.SeekAction.UNKNOWN);constructor(e,i){this.statContext=e,this.config=U(i.config??{}),r.isNonNullable(i.apiEnv)&&(this.config.apiEnv=i.apiEnv),this.config.synchronizeTime&&(this.timeSynchronisation=new Z);const s=new r.Subject;this.experimental={error$:s};const o=new z({apiKey:M,config:this.config,error$:s,timeSynchronisation:this.timeSynchronisation});this.api=new W({config:this.config,apiTransport:o,refreshAuthToken:i.refreshAuthToken,mobile:this.statContext.mobile??!1,error$:s}),this.logger=new j({config:this.config,api:this.api,error$:s,userSalt:i.userSalt});const{isEmbed:a,host:u}=G();this.isEmbed=a,this.embedParent=u,this.subscribe()}updateContext(e){this.statContext={...this.statContext,...e}}attachTo(e){const i=new r.Subscription,s=(n,d)=>i.add(n.subscribe(d));s(e.events.willStart$,()=>{this.logActionPlay({position:e.info.position$.getValue()})}),s(e.events.looped$,()=>{this.resetViewSession(),this.logActionPlay({position:e.info.position$.getValue()})}),s(e.events.seeked$,()=>{this.logSeek({action:this.seekAction$.getValue(),time:e.info.position$.getValue()}),this.seekAction$.next(exports.SeekAction.UNKNOWN)}),s(e.events.paused$,()=>{this.logPause({position:e.info.position$.getValue()})}),s(e.events.willResume$,()=>{this.logPlay()}),s(e.events.started$,()=>{this.statContext.clip&&this.logWatchCoverageRecord({start:0,end:0})}),s(ee(e),n=>{const d=e.info.isLive$.getValue(),p={start:parseFloat(n.from.toFixed(3)),end:parseFloat(n.to.toFixed(3))};d?this.logWatchCoverageLive(p):this.logWatchCoverageRecord(p)});let o;s(e.info.isStalled$,n=>{n?o=r.now():(r.isNonNullable(o)&&this.logEmptyBuffer({duration:r.now()-o}),o=void 0)});let a=!1;i.add(e.events.fatalError$.pipe(r.once()).subscribe(()=>a=!0)),s(e.events.willStop$,()=>{if(e.info.isStalled$.getValue()){const d=r.isNonNullable(o)?r.now()-o:void 0;this.logCloseAtEmptyBuffer({duration:d??0}),o=void 0}else a||this.logActionStop()}),s(e.events.managedError$,({id:n})=>{this.logError({fatal:!1,errorType:n})}),s(e.events.fatalError$,({id:n})=>{this.logError({fatal:!0,errorType:n})});let u,f,l=!1;s(e.events.firstBytes$,n=>{u=r.now(),this.logFirstBytes({time:n})}),s(e.events.willStart$,()=>f=r.now()),s(e.info.currentBuffer$,n=>{!l&&n&&n.end-n.start>0&&r.isNonNullable(u)&&(this.logPlayerReady({duration:r.now()-u}),l=!0)}),s(e.events.firstFrame$,()=>{r.isNonNullable(u)&&!l&&(this.logPlayerReady({duration:r.now()-u}),l=!0),r.isNonNullable(f)&&this.logFirstFrame({time:r.now()-f})}),s(e.info.atLiveEdge$,n=>this.updateContext({liveEdge:n})),s(r.combine({muted:e.info.muted$,volume:e.info.volume$}),({muted:n,volume:d})=>this.updateContext({audible:!n&&d>0})),s(e.info.currentQuality$,n=>this.updateContext({quality:Y(n)})),s(e.info.isAutoQualityEnabled$,n=>this.updateContext({autoQuality:n})),s(e.info.currentFormat$,n=>this.updateContext({contentType:X(n)}));let h;return s(e.info.hostname$,n=>{this.updateContext({cdnHostname:n,failover:h!==void 0&&h!==n}),h=n}),s(e.info.throughputEstimation$,n=>this.updateContext({downloadSpeed:n})),s(e.info.httpConnectionType$,n=>{this.statContext.firstConnectionType||this.updateContext({firstConnectionType:L(n)}),this.updateContext({connectionType:L(n)})}),s(e.info.httpConnectionReused$,n=>{r.isNullable(this.statContext.firstConnectionReused)&&this.updateContext({firstConnectionReused:n}),this.updateContext({connectionReused:n})}),s(e.info.surface$,n=>this.updateContext({mode:P(n)})),s(r.combine({current:e.info.currentTextTrack$,available:e.info.availableTextTracks$}),({current:n,available:d})=>{const p=d.find(({id:y})=>y===n);this.updateContext({subtitles:p?.language})}),this.player=e,this.uiEvents&&this.attachToUi(this.uiEvents),this.resubscribeBeforeunload(),this.subscription.add(i),i}attachToUi(e){this.uiEvents=e;const i=new r.Subscription;return this.player&&(i.add(e.actionRewind$.subscribe(()=>{this.player&&(this.resetViewSession(),this.logActionPlay({position:this.player.info.position$.getValue()}))})),i.add(e.actionSeek$.subscribe(this.seekAction$)),i.add(e.inPiP$.subscribe(s=>{const o=s?S.PIP:P(this.player?.info.surface$.getValue());this.updateContext({mode:o})})),i.add(e.inFullscreen$.subscribe(s=>{const o=s?S.FULLSCREEN:P(this.player?.info.surface$.getValue());this.updateContext({mode:o})})),i.add(e.actionSetSubtitle$.subscribe(s=>{this.updateContext({subtitles:s})})),i.add(e.nextMovie$.subscribe(s=>this.logNextMovie(s))),this.resubscribeBeforeunload(),this.subscription.add(i)),i}attachToAds(e){const i=new r.Subscription;return i.add(e.slotRequested$.subscribe(()=>this.logAdSlotRequest())).add(e.started$.subscribe(s=>this.logAdStarted(s))).add(e.paused$.subscribe(()=>this.logAdPaused())).add(e.resumed$.subscribe(()=>this.logAdResumed())).add(e.ended$.subscribe(()=>this.logAdEnded())).add(e.skipped$.subscribe(()=>this.logAdSkipped())).add(e.clicked$.subscribe(()=>this.logAdClicked())),this.resubscribeBeforeunload(),this.subscription.add(i),i}attachToInteractive(e){const i=new r.Subscription;return i.add(e.click$.subscribe(s=>this.logInterfaceClick(s))).add(e.nextMovie$.subscribe(s=>this.logNextMovie(s))),this.resubscribeBeforeunload(),this.subscription.add(i),i}authorize(e){return this.api.authorize(e)}pause(){this.logger.pause()}resume(){this.logger.resume()}destroy(){this.logger.flush(),this.subscription.unsubscribe(),this.api.destroy(),this.logger.destroy()}resetViewSession(){this.vsid=I()}setFieldBlacklist(){}logInited(){}logReady(e){this.log({operation:"player_ready",param:String(e.time)})}logStarted(...e){this.logActionPlay(...e)}logPlay(){this.log({operation:"play_toggle"})}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}`})}logWatchCoverageLive(e){const i=this.timeSynchronisation?.getOffset()??0,s=e.start+i,o=e.end+i;this.log({operation:"watch_coverage_live",param:`${s}-${o}`})}logEmptyBuffer(e){this.log({operation:"empty_buffer",param:String(e.duration)})}logDownloadSpeed(){}logAdSlotRequest(){this.log({operation:"adv",param:"slot_request"})}logAdStarted(e){this.log({operation:"adv",param:e})}logAdPaused(){this.log({operation:"adv",param:"pause"})}logAdResumed(){this.log({operation:"adv",param:"resume"})}logAdEnded(){this.log({operation:"adv",param:"ended"})}logAdSkipped(){this.log({operation:"adv",param:"skip"})}logAdClicked(){this.log({operation:"adv",param:"click"})}logInterfaceClick(e){this.log({operation:"player_interface_click",param:e})}logNextMovie(e){this.log({operation:"next_movie",param:String(e)})}subscribe(){this.resubscribeBeforeunload();const e=window.navigator.connection;e&&"onchange"in e&&"effectiveType"in e&&this.subscription.add(r.merge(r.fromEvent(e,"change"),r.observableFrom(["init"])).subscribe(()=>this.updateContext({network:J(e.effectiveType)})))}resubscribeBeforeunload(){this.beforeunloadSubscription?.unsubscribe(),this.beforeunloadSubscription=r.fromEvent(window,"beforeunload").subscribe(()=>this.logger.flush(!0)),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))})}logCloseAtEmptyBuffer(e){this.log({operation:"close_at_empty_buffer",param:String(Math.round(e.duration))})}logActionStop(){this.log({operation:"action_stop"})}log(e){if(this.config.disabledOperations.includes(e.operation))return;const i=this.createLogItem(e);this.logger.log(i)}createLogItem({operation:e,param:i,time:s}){const o=this.timeSynchronisation?.now()??r.now(),a=e==="empty_buffer"||e==="close_at_empty_buffer"?this.statContext.connectionType:this.statContext.firstConnectionType,u=this.statContext.firstConnectionReused,f={vsid:this.vsid,vid:this.statContext.movieId,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?w.AUTO:this.statContext.autoplay===!1?w.MANUAL:void 0,param:i,vk_app_id:this.statContext.vkAppId,track_code:this.statContext.trackCode,connection_type:a,connection_reused:u===!0?g.YES:u===!1?g.NO:void 0,cached_data:this.statContext.cached===!0?g.YES:this.statContext.cached===!1?g.NO:void 0,live:this.statContext.liveEdge?g.YES:void 0,muted:this.statContext.audible===!1?g.YES:void 0,mode:this.statContext.mode,subtitles:this.statContext.subtitles,download_speed:this.statContext.downloadSpeed,manual_quality:this.statContext.autoQuality?void 0:g.YES,ref_domain:this.embedParent,aid:this.statContext.albumId,vk_playlist_id:this.statContext.vkPlaylistId};for(const l of this.config.disabledCustomFields)delete f[l];return{operation:e,type:1,time:s,network:this.statContext.network,timestamp:o,custom:f}}}exports.OneStat=te;exports.VERSION=N;
|
|
6
|
+
"use strict";var r=require("@vkontakte/videoplayer-shared/esnext.cjs.js"),R=require("lodash/debounce.js"),c=require("@vkontakte/videoplayer-core/esnext.cjs.js");exports.ApiEnv=void 0;(function(t){t.PROD="prod",t.VK_ALIAS="vk_alias",t.VIDEOTEST="videotest",t.TEST="test",t.AUTO="auto"})(exports.ApiEnv||(exports.ApiEnv={}));exports.Quality=void 0;(function(t){t.Q144P="mobile",t.Q240P="lowest",t.Q360P="low",t.Q480P="medium",t.Q720P="high",t.Q1080P="fullhd",t.Q1440P="quadhd",t.Q2160P="ultrahd",t.UNKNOWN="unknown"})(exports.Quality||(exports.Quality={}));exports.ContentType=void 0;(function(t){t.MP4="mp4",t.DASH="dash",t.DASH_SEP="dash_sep",t.ONDEMAND_DASH="ondemand_dash",t.HLS="hls",t.ONDEMAND_HLS="ondemand_hls",t.WEBM="webm",t.AV1="av1",t.ONDEMAND_DASH_LIVE="ondemand_dash_live",t.ONDEMAND_HLS_LIVE="ondemand_hls_live",t.WEBRTC="webrtc",t.UNKNOWN="unknown",t.RTMP="rtmp"})(exports.ContentType||(exports.ContentType={}));var w;(function(t){t.AUTO="auto",t.MANUAL=""})(w||(w={}));exports.ConnectionType=void 0;(function(t){t.HTTP1="http1",t.HTTP2="http2",t.HTTP3="http3"})(exports.ConnectionType||(exports.ConnectionType={}));var g;(function(t){t[t.YES=1]="YES",t[t.NO=0]="NO"})(g||(g={}));var E;(function(t){t.EXCELLENT="excellent",t.GOOD="good",t.POOR="poor"})(E||(E={}));var S;(function(t){t.PIP="pip",t.FULLSCREEN="fullscreen",t.EXTERNAL="external",t.PREFETCH="prefetch"})(S||(S={}));exports.SeekAction=void 0;(function(t){t.SLIDER="slider",t.DOUBLE_TAP="double_tap",t.TIME_CODE="time_code",t.EPISODE="episode",t.REWIND="rewind",t.LIVE="live",t.UNKNOWN="unknown"})(exports.SeekAction||(exports.SeekAction={}));exports.InteractiveInterfaceClick=void 0;(function(t){t.GRAPH_SHOW="iGraphShow",t.GRAPH_HIDE="iGraphHide",t.NEXT_AREA="iNextChapterArea",t.NEXT_BUTTON="iNextChapterBtn",t.WATCH_AGAIN="iWatchAgainBtn"})(exports.InteractiveInterfaceClick||(exports.InteractiveInterfaceClick={}));const U={apiEnv:exports.ApiEnv.VK_ALIAS,requestRetryCount:1,firstFlushTime:5e3,flushDebounceTime:1e4,flushMaxWait:6e4,storageExpiration:36*60*60*1e3,disabledOperations:[],disabledCustomFields:[],useBeacon:!0,synchronizeTime:!0,backoff:{start:1e3,factor:1.5,max:5*60*1e3,random:.1}},H=t=>r.fillWithDefault(t,U);function M(){const t="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".split(""),e=new Array(36);let s=0,i,o;for(o=0;o<36;o++)o===8||o===13||o===18||o===23?e[o]="-":o===14?e[o]="4":(s<=2&&(s=33554432+Math.random()*16777216|0),i=s&15,s=s>>4,e[o]=t[o===19?i&3|8:i]);return e.join("")}const O="1.0.39",W="CIOPGQJGDIHBABABA",k={[exports.ApiEnv.PROD]:"https://api.ok.ru",[exports.ApiEnv.VK_ALIAS]:"https://api.mycdn.me",[exports.ApiEnv.VIDEOTEST]:"https://videotestapi.ok.ru/api",[exports.ApiEnv.TEST]:"https://apitest.ok.ru",[exports.ApiEnv.AUTO]:""},q="_one-stat_",v=`${q}uuid`;var b;(function(t){t[t.PARAM_SESSION_EXPIRED=102]="PARAM_SESSION_EXPIRED",t[t.PARAM_SESSION_KEY=103]="PARAM_SESSION_KEY",t[t.PARAM_SIGNATURE=104]="PARAM_SIGNATURE",t[t.AUTH_LOGIN=401]="AUTH_LOGIN"})(b||(b={}));class Q{params;uuid;authToken;sessionKey;authorizePromise;refreshAuthTokenPromise;consequentAuthErrors=0;authorized$=new r.ValueSubject(!1);backoffTimeoutId;constructor(e){this.params=e;const s=r.safeStorage.get(v);s?s.startsWith('"')&&s.endsWith('"')?(this.uuid=s.replaceAll('"',""),r.safeStorage.set(v,this.uuid)):this.uuid=s:(this.uuid=M(),r.safeStorage.set(v,this.uuid))}async authorize(e){return this.authToken=e??await this.refreshAuthToken(),this._authorizeWithBackoff()}logBeacon(e){const s="log.externalLog",i=this.createLogParams(e),o=this.sessionKey;if(!o)return;this.params.apiTransport.sendBeacon(s,i,o)||this.logRequest(e)}async logRequest(e){const s="log.externalLog",i=this.createLogParams(e),o=this.sessionKey??await this._authorizeWithBackoff();if(!o)return;const a=async(u,f=this.params.config.requestRetryCount)=>{try{return await this.params.apiTransport.sendRequest(s,i,o)}catch(l){if(!l||!("error_code"in l)){this.params.error$.next({id:"logRequestUnknown",category:r.ErrorCategory.NETWORK,message:`Unknown ${s} error`,thrown:l});return}const d=l?.error_code;switch(d){case b.PARAM_SESSION_EXPIRED:case b.PARAM_SESSION_KEY:case b.PARAM_SIGNATURE:return this.authorized$.next(!1),this.sessionKey=await this._authorizeWithBackoff(),f>0?a(u,f-1):void 0;case b.AUTH_LOGIN:return this.authorized$.next(!1),this.authToken=await this.refreshAuthToken(),this.sessionKey=await this._authorizeWithBackoff(),f>0?a(u,f-1):void 0;default:{this.params.error$.next({id:`LogRequest#${d}`,category:r.ErrorCategory.EXTERNAL_API,message:`${s} error`,data:l});return}}}};return a(e)}destroy(){window.clearTimeout(this.backoffTimeoutId),this.backoffTimeoutId=0}async refreshAuthToken(){if(this.params.refreshAuthToken)return this.refreshAuthTokenPromise||(this.refreshAuthTokenPromise=this.params.refreshAuthToken().finally(()=>{this.refreshAuthTokenPromise=void 0})),this.refreshAuthTokenPromise}createLogParams(e){return{collector:"ok.mobile.apps.video",data:JSON.stringify({application:`@vkontakte/videoplayer-statistics:${O}`,platform:this.params.mobile?"M_WEB":"WEB",items:e})}}_authorizeWithBackoff(){if(!this.consequentAuthErrors)return this._authorize();const e=r.getExponentialDelay(this.consequentAuthErrors,this.params.config.backoff);return new Promise(s=>{this.backoffTimeoutId||(this.backoffTimeoutId=window.setTimeout(()=>{this._authorize().then(s).catch(i=>this.params.error$.next({id:"AuthorizeBackoff",category:r.ErrorCategory.NETWORK,message:"Otherwise unhandled error in authorization",thrown:i})).finally(()=>this.backoffTimeoutId=0)},e))})}async _authorize(){if(this.authorizePromise)return this.authorizePromise;this.sessionKey=void 0,this.authorized$.next(!1);const e="auth.anonymLogin",s={session_data:{version:2,device_id:this.uuid,client_version:O.split("-")[0],client_type:"SDK_JS"}};return this.authToken!==void 0&&(s.session_data.auth_token=this.authToken,s.session_data.version=3),this.authorizePromise=this.params.apiTransport.sendRequest(e,s).then(i=>((!i||!i.session_key)&&this.params.error$.next({id:"AuthorizeFailed",category:r.ErrorCategory.EXTERNAL_API,message:"No session key",data:i}),this.sessionKey=i?.session_key??void 0,this.sessionKey)).catch(async i=>{this.sessionKey=void 0;const o=i?.error_code;switch(o){case b.AUTH_LOGIN:return this.authToken=await this.refreshAuthToken(),this._authorizeWithBackoff()}o?this.params.error$.next({id:`Authorize#${o}`,category:r.ErrorCategory.EXTERNAL_API,message:"authorize error",data:i}):this.params.error$.next({id:"AuthorizeUnknown",category:r.ErrorCategory.NETWORK,message:"authorize error",thrown:i})}).finally(()=>{this.authorizePromise=void 0,this.consequentAuthErrors=this.sessionKey?0:this.consequentAuthErrors+1,this.authorized$.next(this.sessionKey!==void 0)}),this.authorizePromise}}class ${constructor(){Object.defineProperty(this,"listeners",{value:{},writable:!0,configurable:!0})}addEventListener(e,s,i){e in this.listeners||(this.listeners[e]=[]),this.listeners[e].push({callback:s,options:i})}removeEventListener(e,s){if(!(e in this.listeners))return;const i=this.listeners[e];for(let o=0,a=i.length;o<a;o++)if(i[o].callback===s){i.splice(o,1);return}}dispatchEvent(e){if(!(e.type in this.listeners))return;const i=this.listeners[e.type].slice();for(let o=0,a=i.length;o<a;o++){const u=i[o];try{u.callback.call(this,e)}catch(f){Promise.resolve().then(()=>{throw f})}u.options&&u.options.once&&this.removeEventListener(e.type,u.callback)}return!e.defaultPrevented}}class D extends ${constructor(){super(),this.listeners||$.call(this),Object.defineProperty(this,"aborted",{value:!1,writable:!0,configurable:!0}),Object.defineProperty(this,"onabort",{value:null,writable:!0,configurable:!0}),Object.defineProperty(this,"reason",{value:void 0,writable:!0,configurable:!0})}toString(){return"[object AbortSignal]"}dispatchEvent(e){e.type==="abort"&&(this.aborted=!0,typeof this.onabort=="function"&&this.onabort.call(this,e)),super.dispatchEvent(e)}}class K{constructor(){Object.defineProperty(this,"signal",{value:new D,writable:!0,configurable:!0})}abort(e){let s;try{s=new Event("abort")}catch{typeof document<"u"?document.createEvent?(s=document.createEvent("Event"),s.initEvent("abort",!1,!1)):(s=document.createEventObject(),s.type="abort"):s={type:"abort",bubbles:!1,cancelable:!1}}let i=e;if(i===void 0)if(typeof document>"u")i=new Error("This operation was aborted"),i.name="AbortError";else try{i=new DOMException("signal is aborted without reason")}catch{i=new Error("This operation was aborted"),i.name="AbortError"}this.signal.reason=i,this.signal.dispatchEvent(s)}toString(){return"[object AbortController]"}}typeof Symbol<"u"&&Symbol.toStringTag&&(K.prototype[Symbol.toStringTag]="AbortController",D.prototype[Symbol.toStringTag]="AbortSignal");function B(t){return t.__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL?(console.log("__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL=true is set, will force install polyfill"),!0):typeof t.Request=="function"&&!t.Request.prototype.hasOwnProperty("signal")||!t.AbortController}function z(t){typeof t=="function"&&(t={fetch:t});const{fetch:e,Request:s=e.Request,AbortController:i,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:o=!1}=t;if(!B({fetch:e,Request:s,AbortController:i,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:o}))return{fetch:e,Request:a};let a=s;(a&&!a.prototype.hasOwnProperty("signal")||o)&&(a=function(d,n){let h;n&&n.signal&&(h=n.signal,delete n.signal);const p=new s(d,n);return h&&Object.defineProperty(p,"signal",{writable:!1,enumerable:!1,configurable:!0,value:h}),p},a.prototype=s.prototype);const u=e;return{fetch:(l,d)=>{const n=a&&a.prototype.isPrototypeOf(l)?l.signal:d?d.signal:void 0;if(n){let h;try{h=new DOMException("Aborted","AbortError")}catch{h=new Error("Aborted"),h.name="AbortError"}if(n.aborted)return Promise.reject(h);const p=new Promise((y,m)=>{n.addEventListener("abort",()=>m(h),{once:!0})});return d&&d.signal&&delete d.signal,Promise.race([p,u(l,d)])}return u(l,d)},Request:a}}const x=B({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),V=x?z({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,L=x?V.fetch:window.fetch;x?V.Request:window.Request;class j{apiKey;apiBaseUrl;apiEnv;timeSynchronisation;isApiBaseUrlFetched;params;constructor(e){this.params=e,this.apiKey=e.apiKey,this.apiEnv=e.config.apiEnv,this.apiBaseUrl=k[this.apiEnv],this.timeSynchronisation=e.timeSynchronisation,this.isApiBaseUrlFetched=!1}async resolveApiBaseUrl(){if(this.apiEnv!==exports.ApiEnv.AUTO||this.isApiBaseUrlFetched)return this.apiBaseUrl;try{const e=atob("aHR0cHM6Ly9kbnMuZ29vZ2xlL3Jlc29sdmU/bmFtZT12aWRlby5fZW5kcG9pbnQub2sucnUmdHlwZT1UWFQ="),o=(await(await L(e,{method:"GET",mode:"cors",cache:"no-cache"})).json())?.Answer[0]?.data;if(!o)throw new Error("Wrong DNS response");return o}catch(e){return this.params.error$.next({id:"OneStat:ApiTransport:resolveApiBaseUrl",category:r.ErrorCategory.NETWORK,message:"Unhandled resolve api base url error",thrown:e}),k[exports.ApiEnv.VK_ALIAS]}finally{this.isApiBaseUrlFetched=!0}}sendBeacon(e,s,i){if(!window.Blob||!window.navigator.sendBeacon)return!1;const o=this._prepareQueryParams({method:e,queryParams:s,sessionKey:i}),a=new window.Blob([o.toString()],{type:"application/x-www-form-urlencoded"});try{return window.navigator.sendBeacon(`${this.apiBaseUrl}/fb.do`,a)}catch(u){this.params.error$.next({id:"OneStat:ApiTransport:sendBeacon",category:r.ErrorCategory.NETWORK,message:"Unhandled beacon error",thrown:u,data:{method:e,params:s}})}return!1}async sendRequest(e,s,i){const o=r.now(),a=u=>{if(u instanceof TypeError&&["Failed to fetch","NetworkError when attempting to fetch resource."].includes(u.message)){this.params.error$.next({id:"Network",category:r.ErrorCategory.NETWORK,message:"Request failed",thrown:u});return}this.params.error$.next({id:"OneStat:ApiTransport:sendRequest",category:r.ErrorCategory.NETWORK,message:"Unhandled request error",thrown:u,data:{method:e,params:s,sessionKey:i,time:r.now()-o}})};return this.apiBaseUrl=await this.resolveApiBaseUrl(),L(`${this.apiBaseUrl}/fb.do`,{method:"post",headers:{"Content-type":"application/x-www-form-urlencoded"},body:this._prepareQueryParams({method:e,queryParams:s,sessionKey:i})}).then(u=>{const f=Number(u.headers.get("content-length"))===0,l=new Date(u.headers.get("date")??"").getTime(),d=r.now()-o;if(isFinite(l)&&this.timeSynchronisation?.addServerTime(l,d),!f)return u.json().then(n=>Object.prototype.hasOwnProperty.call(n,"error_msg")?Promise.reject(n):n,a)},a)}_prepareQueryParams(e){const s=new URLSearchParams({format:"JSON",method:e.method,application_key:this.apiKey});return e.sessionKey!==void 0&&s.append("session_key",e.sessionKey),Object.entries(e.queryParams).forEach(([i,o])=>s.append(i,typeof o=="string"?o:JSON.stringify(o))),s}}const _="onestat_events",P=t=>e=>e.timestamp+t>=r.now();class G{params;api;error$;subscription;userSalt;unsaltedStorage=[];lastVsid;isPaused=!1;firstFlush;debouncedFlush;constructor(e){this.params=e,this.api=e.api,this.error$=e.error$,this.userSalt=e.userSalt,this.firstFlush=R(()=>this.safeFlush(),this.params.config.firstFlushTime,{maxWait:this.params.config.firstFlushTime});const s=r.safeStorage.isPersistent()?this.params.config.flushMaxWait:0;this.debouncedFlush=R(()=>this.safeFlush(),this.params.config.flushDebounceTime,{maxWait:s}),this.subscription=this.api.authorized$.subscribe(i=>{i&&this.debouncedFlush()}),this.housekeepStorage()}isUrgent=e=>{const{operation:s,custom:{param:i}}=e;return["action_stop","close_at_empty_buffer"].includes(s)||s==="watch_coverage_record"&&i==="0-0"};safeFlush(){try{this.flush()}catch(e){this.error$.next({id:"LoggerError",category:r.ErrorCategory.WTF,message:String(e)??"Unknown logger error",thrown:e})}}readFromStorage(){const e=r.safeStorage.get(_);try{return e?JSON.parse(e):{}}catch{}return{}}addToStorage(e){if(!this.userSalt){this.unsaltedStorage.push(e);return}const s=this.readFromStorage(),o=(s[this.userSalt]??[]).filter(P(this.params.config.storageExpiration));r.safeStorage.set(_,JSON.stringify({...s,[this.userSalt]:[...o,e]}))}getFromStorage(){return this.userSalt?(this.readFromStorage()[this.userSalt]??[]).filter(P(this.params.config.storageExpiration)):this.unsaltedStorage}markStorageSent(){if(!this.userSalt){this.unsaltedStorage=[];return}const e=this.readFromStorage();delete e[this.userSalt],r.safeStorage.set(_,JSON.stringify(e))}housekeepStorage(){const e=this.readFromStorage();for(const[s,i]of Object.entries(e)){const o=i.filter(P(this.params.config.storageExpiration));o.length?e[s]=o:delete e[s]}r.safeStorage.set(_,JSON.stringify(e))}log(e){this.addToStorage(e),!this.isPaused&&(this.isUrgent(e)?this.flush():this.lastVsid!==e.custom.vsid?this.firstFlush():this.debouncedFlush(),this.lastVsid=e.custom.vsid)}flush(e=!1){const s=this.getFromStorage();s.length!==0&&(this.api.authorized$.getValue()?(e&&this.params.config.useBeacon?this.api.logBeacon(s):this.api.logRequest(s),this.markStorageSent()):this.api.authorize(),this.firstFlush.cancel(),this.debouncedFlush.cancel())}pause(){this.isPaused=!0,this.debouncedFlush.cancel()}resume(){this.isPaused=!1,this.debouncedFlush()}destroy(){this.subscription.unsubscribe(),this.firstFlush.cancel(),this.debouncedFlush.cancel()}}const Y=()=>{let t,e;try{t=window.self!==window.top}catch(i){i instanceof DOMException&&i.name==="SecurityError"?t=!0:(t=!1,console.error(i))}try{window.location.ancestorOrigins&&(e=window.location.ancestorOrigins[window.location.ancestorOrigins.length-1])}catch(i){console.error(i)}try{!e&&document.referrer&&(e=document.referrer)}catch(i){console.error(i)}const s=e?new URL(e).hostname:void 0;return{isEmbed:t,host:s}},X=t=>t&&{[c.VideoQuality.INVARIANT]:exports.Quality.UNKNOWN,[c.VideoQuality.Q_144P]:exports.Quality.Q144P,[c.VideoQuality.Q_240P]:exports.Quality.Q240P,[c.VideoQuality.Q_360P]:exports.Quality.Q360P,[c.VideoQuality.Q_480P]:exports.Quality.Q480P,[c.VideoQuality.Q_720P]:exports.Quality.Q720P,[c.VideoQuality.Q_1080P]:exports.Quality.Q1080P,[c.VideoQuality.Q_1440P]:exports.Quality.Q1440P,[c.VideoQuality.Q_2160P]:exports.Quality.Q2160P,[c.VideoQuality.Q_4320P]:exports.Quality.UNKNOWN}[t],I=t=>t&&{[c.HttpConnectionType.HTTP1]:exports.ConnectionType.HTTP1,[c.HttpConnectionType.HTTP2]:exports.ConnectionType.HTTP2,[c.HttpConnectionType.QUIC]:exports.ConnectionType.HTTP3}[t],J=t=>{if(t!==void 0)switch(t){case c.VideoFormat.MPEG:return exports.ContentType.MP4;case c.VideoFormat.DASH:case c.VideoFormat.DASH_LIVE:return exports.ContentType.DASH;case c.VideoFormat.DASH_SEP:return exports.ContentType.DASH_SEP;case c.VideoFormat.DASH_ONDEMAND:return exports.ContentType.ONDEMAND_DASH;case c.VideoFormat.DASH_WEBM:case c.VideoFormat.DASH_LIVE_WEBM:return exports.ContentType.WEBM;case c.VideoFormat.DASH_WEBM_AV1:return exports.ContentType.AV1;case c.VideoFormat.DASH_LIVE_CMAF:return exports.ContentType.ONDEMAND_DASH_LIVE;case c.VideoFormat.HLS:case c.VideoFormat.HLS_LIVE:return exports.ContentType.HLS;case c.VideoFormat.HLS_ONDEMAND:return exports.ContentType.ONDEMAND_HLS;case c.VideoFormat.HLS_LIVE_CMAF:return exports.ContentType.ONDEMAND_HLS_LIVE;case c.VideoFormat.WEB_RTC_LIVE:return exports.ContentType.WEBRTC;default:return r.assertNever(t)}},N=t=>{if(t!==void 0)switch(t){case c.Surface.NONE:case c.Surface.INLINE:return;case c.Surface.FULLSCREEN:return S.FULLSCREEN;case c.Surface.SECOND_SCREEN:return S.EXTERNAL;case c.Surface.PIP:return S.PIP;default:return r.assertNever(t)}},Z=t=>{switch(t){case"slow-2g":return E.POOR;case"2g":return E.POOR;case"3g":return E.GOOD;case"4g":return E.EXCELLENT}};class ee{offset=void 0;constructor(e){this.offset=e}getOffset(){return this.offset??0}setOffset(e){this.offset=e}now(){return Date.now()+(this.offset??0)}date(e=new Date){return e.setTime(e.getTime()+(this.offset??0)),e}addServerTime(e,s){const i=Date.now(),o=e-i-s/2;if(Math.abs(o)<1e3){this.offset=0;return}this.offset===void 0?this.offset=Math.round(o):this.offset=Math.round(.2*o+(1-.2)*this.offset)}}const F=()=>Math.floor(Math.random()*2**32).toString(36).padStart(8,"0"),te=t=>new r.Observable(e=>{const s=new r.Subscription,i=r.merge(r.fromEvent(window,"beforeunload"),t.events.willDestruct$),o=new r.ValueSubject(void 0);let a;s.add(t.info.isLive$.pipe(r.filterChanged()).subscribe(A=>{a&&(a.unsubscribe(),o.next(void 0)),A?a=t.info.liveTime$.pipe(r.map(T=>T&&T/1e3)).subscribe(o):a=t.info.position$.subscribe(o),s.add(a)}));const{playing$:u,paused$:f}=t.events,l=t.events.willSeek$.pipe(r.filter(()=>t.info.playbackState$.getValue()===c.PlaybackState.PLAYING)),d=t.events.seeked$.pipe(r.filter(()=>t.info.playbackState$.getValue()===c.PlaybackState.PLAYING));let n=!1;const h=new r.Subject;s.add(l.subscribe(()=>{n||h.next(),n=!0})),s.add(d.subscribe(()=>n=!1));const p=r.merge(u,d),y=r.merge(f,h,i,t.events.looped$);let m;return s.add(p.subscribe(()=>m=o.getValue())),s.add(y.subscribe(()=>{const A=o.getValue();r.isNullable(m)||m===A||r.isNullable(A)||(e.next({from:m,to:A}),m=void 0)})),s}),C=()=>{const t=new r.Subscription;return{subscription:t,subscribe:(e,s)=>{e&&t.add(e.subscribe(s))}}};class ie{api;logger;config;subscription=new r.Subscription;beforeunloadSubscription;timeSynchronisation;experimental;statContext;vsid=F();isEmbed;embedParent;uiEvents;player;seekAction$=new r.ValueSubject(exports.SeekAction.UNKNOWN);constructor(e,s){this.statContext=e,this.config=H(s.config??{}),r.isNonNullable(s.apiEnv)&&(this.config.apiEnv=s.apiEnv),this.config.synchronizeTime&&(this.timeSynchronisation=new ee);const i=new r.Subject;this.experimental={error$:i};const o=new j({apiKey:W,config:this.config,error$:i,timeSynchronisation:this.timeSynchronisation});this.api=new Q({config:this.config,apiTransport:o,refreshAuthToken:s.refreshAuthToken,mobile:this.statContext.mobile??!1,error$:i}),this.logger=new G({config:this.config,api:this.api,error$:i,userSalt:s.userSalt});const{isEmbed:a,host:u}=Y();this.isEmbed=a,this.embedParent=u,this.subscribe()}updateContext(e){this.statContext={...this.statContext,...e}}attachTo(e){const s=new r.Subscription,i=(n,h)=>s.add(n.subscribe(h));i(e.events.willStart$,()=>{this.logActionPlay({position:e.info.position$.getValue()})}),i(e.events.looped$,()=>{this.resetViewSession(),this.logActionPlay({position:e.info.position$.getValue()})}),i(e.events.seeked$,()=>{this.logSeek({action:this.seekAction$.getValue(),time:e.info.position$.getValue()}),this.seekAction$.next(exports.SeekAction.UNKNOWN)}),i(e.events.paused$,()=>{this.logPause({position:e.info.position$.getValue()})}),i(e.events.willResume$,()=>{this.logPlay()}),i(e.events.started$,()=>{this.statContext.clip&&this.logWatchCoverageRecord({start:0,end:0})}),i(te(e),n=>{const h=e.info.isLive$.getValue(),p={start:parseFloat(n.from.toFixed(3)),end:parseFloat(n.to.toFixed(3))};h?this.logWatchCoverageLive(p):this.logWatchCoverageRecord(p)});let o;i(e.info.isStalled$,n=>{n?o=r.now():(r.isNonNullable(o)&&this.logEmptyBuffer({duration:r.now()-o}),o=void 0)});let a=!1;s.add(e.events.fatalError$.pipe(r.once()).subscribe(()=>a=!0)),i(e.events.willStop$,()=>{if(e.info.isStalled$.getValue()){const h=r.isNonNullable(o)?r.now()-o:void 0;this.logCloseAtEmptyBuffer({duration:h??0}),o=void 0}else a||this.logActionStop()}),i(e.events.managedError$,({id:n})=>{this.logError({fatal:!1,errorType:n})}),i(e.events.fatalError$,({id:n})=>{this.logError({fatal:!0,errorType:n})});let u,f,l=!1;i(e.events.firstBytes$,n=>{u=r.now(),this.logFirstBytes({time:n})}),i(e.events.willStart$,()=>f=r.now()),i(e.info.currentBuffer$,n=>{!l&&n&&n.end-n.start>0&&r.isNonNullable(u)&&(this.logPlayerReady({duration:r.now()-u}),l=!0)}),i(e.events.firstFrame$,()=>{r.isNonNullable(u)&&!l&&(this.logPlayerReady({duration:r.now()-u}),l=!0),r.isNonNullable(f)&&this.logFirstFrame({time:r.now()-f})}),i(e.info.atLiveEdge$,n=>this.updateContext({liveEdge:n})),i(r.combine({muted:e.info.muted$,volume:e.info.volume$}),({muted:n,volume:h})=>this.updateContext({audible:!n&&h>0})),i(e.info.currentQuality$,n=>this.updateContext({quality:X(n)})),i(e.info.isAutoQualityEnabled$,n=>this.updateContext({autoQuality:n})),i(e.info.currentFormat$,n=>this.updateContext({contentType:J(n)}));let d;return i(e.info.hostname$,n=>{this.updateContext({cdnHostname:n,failover:d!==void 0&&d!==n}),d=n}),i(e.info.throughputEstimation$,n=>this.updateContext({downloadSpeed:n})),i(e.info.httpConnectionType$,n=>{this.statContext.firstConnectionType||this.updateContext({firstConnectionType:I(n)}),this.updateContext({connectionType:I(n)})}),i(e.info.httpConnectionReused$,n=>{r.isNullable(this.statContext.firstConnectionReused)&&this.updateContext({firstConnectionReused:n}),this.updateContext({connectionReused:n})}),i(e.info.surface$,n=>this.updateContext({mode:N(n)})),i(r.combine({current:e.info.currentTextTrack$,available:e.info.availableTextTracks$}),({current:n,available:h})=>{const p=h.find(({id:y})=>y===n);this.updateContext({subtitles:p?.language})}),this.player=e,this.uiEvents&&this.attachToUi(this.uiEvents),this.resubscribeBeforeunload(),this.subscription.add(s),s}attachToUi(e){this.uiEvents=e;const{subscription:s,subscribe:i}=C();return this.player&&(i(e.actionRewind$,()=>{this.player&&(this.resetViewSession(),this.logActionPlay({position:this.player.info.position$.getValue()}))}),i(e.actionSeek$,this.seekAction$),i(e.inPiP$,o=>{const a=o?S.PIP:N(this.player?.info.surface$.getValue());this.updateContext({mode:a})}),i(e.inFullscreen$,o=>{const a=o?S.FULLSCREEN:N(this.player?.info.surface$.getValue());this.updateContext({mode:a})}),i(e.actionSetSubtitle$,o=>this.updateContext({subtitles:o})),i(e.nextMovie$,o=>this.logNextMovie(o)),this.resubscribeBeforeunload(),this.subscription.add(s)),s}attachToAds(e){const{subscription:s,subscribe:i}=C();return i(e.slotRequested$,()=>this.logAdSlotRequest()),i(e.started$,o=>this.logAdStarted(o)),i(e.paused$,()=>this.logAdPaused()),i(e.resumed$,()=>this.logAdResumed()),i(e.ended$,()=>this.logAdEnded()),i(e.skipped$,()=>this.logAdSkipped()),i(e.clicked$,()=>this.logAdClicked()),this.resubscribeBeforeunload(),this.subscription.add(s),s}attachToInteractive(e){const{subscription:s,subscribe:i}=C();return i(e.click$,o=>this.logInterfaceClick(o)),i(e.nextMovie$,o=>this.logNextMovie(o)),this.resubscribeBeforeunload(),this.subscription.add(s),s}authorize(e){return this.api.authorize(e)}pause(){this.logger.pause()}resume(){this.logger.resume()}destroy(){this.logger.flush(),this.subscription.unsubscribe(),this.api.destroy(),this.logger.destroy()}resetViewSession(){this.vsid=F()}setFieldBlacklist(){}logInited(){}logReady(e){this.log({operation:"player_ready",param:String(e.time)})}logStarted(...e){this.logActionPlay(...e)}logPlay(){this.log({operation:"play_toggle"})}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}`})}logWatchCoverageLive(e){const s=this.timeSynchronisation?.getOffset()??0,i=e.start+s,o=e.end+s;this.log({operation:"watch_coverage_live",param:`${i}-${o}`})}logEmptyBuffer(e){this.log({operation:"empty_buffer",param:String(e.duration)})}logDownloadSpeed(){}logAdSlotRequest(){this.log({operation:"adv",param:"slot_request"})}logAdStarted(e){this.log({operation:"adv",param:e})}logAdPaused(){this.log({operation:"adv",param:"pause"})}logAdResumed(){this.log({operation:"adv",param:"resume"})}logAdEnded(){this.log({operation:"adv",param:"ended"})}logAdSkipped(){this.log({operation:"adv",param:"skip"})}logAdClicked(){this.log({operation:"adv",param:"click"})}logInterfaceClick(e){this.log({operation:"player_interface_click",param:e})}logNextMovie(e){this.log({operation:"next_movie",param:String(e)})}subscribe(){this.resubscribeBeforeunload();const e=window.navigator.connection;e&&"onchange"in e&&"effectiveType"in e&&this.subscription.add(r.merge(r.fromEvent(e,"change"),r.observableFrom(["init"])).subscribe(()=>this.updateContext({network:Z(e.effectiveType)})))}resubscribeBeforeunload(){this.beforeunloadSubscription?.unsubscribe(),this.beforeunloadSubscription=r.fromEvent(window,"beforeunload").subscribe(()=>this.logger.flush(!0)),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))})}logCloseAtEmptyBuffer(e){this.log({operation:"close_at_empty_buffer",param:String(Math.round(e.duration))})}logActionStop(){this.log({operation:"action_stop"})}log(e){if(this.config.disabledOperations.includes(e.operation))return;const s=this.createLogItem(e);this.logger.log(s)}createLogItem({operation:e,param:s,time:i}){const o=this.timeSynchronisation?.now()??r.now(),a=e==="empty_buffer"||e==="close_at_empty_buffer"?this.statContext.connectionType:this.statContext.firstConnectionType,u=this.statContext.firstConnectionReused,f={vsid:this.vsid,vid:this.statContext.movieId,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?w.AUTO:this.statContext.autoplay===!1?w.MANUAL:void 0,param:s,vk_app_id:this.statContext.vkAppId,track_code:this.statContext.trackCode,connection_type:a,connection_reused:u===!0?g.YES:u===!1?g.NO:void 0,cached_data:this.statContext.cached===!0?g.YES:this.statContext.cached===!1?g.NO:void 0,live:this.statContext.liveEdge?g.YES:void 0,muted:this.statContext.audible===!1?g.YES:void 0,mode:this.statContext.mode,subtitles:this.statContext.subtitles,download_speed:this.statContext.downloadSpeed,manual_quality:this.statContext.autoQuality?void 0:g.YES,ref_domain:this.isEmbed?this.embedParent:this.statContext.refUrl,aid:this.statContext.albumId,vk_playlist_id:this.statContext.vkPlaylistId};for(const l of this.config.disabledCustomFields)delete f[l];return{operation:e,type:1,time:i,network:this.statContext.network,timestamp:o,custom:f}}}exports.OneStat=ie;exports.VERSION=O;
|