@vkontakte/videoplayer-statistics 1.0.52-dev.22c05d5f.0 → 1.0.52-dev.a5f6699f.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/es2015.cjs.js CHANGED
@@ -1,6 +1,6 @@
1
1
  /**
2
- * @vkontakte/videoplayer-statistics v1.0.52-dev.22c05d5f.0
3
- * Tue, 30 Jul 2024 08:28:10 GMT
2
+ * @vkontakte/videoplayer-statistics v1.0.52-dev.a5f6699f.0
3
+ * Tue, 30 Jul 2024 10:43:01 GMT
4
4
  * https://st.mycdn.me/static/vkontakte-videoplayer/1-0-52/doc/
5
5
  */
6
- "use strict";var L=Object.defineProperty,Ie=Object.defineProperties,Se=Object.getOwnPropertyDescriptor,ye=Object.getOwnPropertyDescriptors,Pe=Object.getOwnPropertyNames,Z=Object.getOwnPropertySymbols;var te=Object.prototype.hasOwnProperty,Ae=Object.prototype.propertyIsEnumerable;var ee=(r,e,i)=>e in r?L(r,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):r[e]=i,E=(r,e)=>{for(var i in e||(e={}))te.call(e,i)&&ee(r,i,e[i]);if(Z)for(var i of Z(e))Ae.call(e,i)&&ee(r,i,e[i]);return r},$=(r,e)=>Ie(r,ye(e));var Ee=(r,e)=>{for(var i in e)L(r,i,{get:e[i],enumerable:!0})},_e=(r,e,i,t)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Pe(e))!te.call(r,o)&&o!==i&&L(r,o,{get:()=>e[o],enumerable:!(t=Se(e,o))||t.enumerable});return r};var xe=r=>_e(L({},"__esModule",{value:!0}),r);var S=(r,e,i)=>new Promise((t,o)=>{var n=l=>{try{h(i.next(l))}catch(p){o(p)}},a=l=>{try{h(i.throw(l))}catch(p){o(p)}},h=l=>l.done?t(l.value):Promise.resolve(l.value).then(n,a);h((i=i.apply(r,e)).next())});var ke={};Ee(ke,{ApiEnv:()=>C,ConnectionType:()=>N,ContentType:()=>O,InteractiveInterfaceClick:()=>K,OneStat:()=>U,Quality:()=>R,SeekAction:()=>D,VERSION:()=>T});module.exports=xe(ke);var C=(n=>(n.PROD="prod",n.VK_ALIAS="vk_alias",n.VIDEOTEST="videotest",n.TEST="test",n.AUTO="auto",n))(C||{}),R=(p=>(p.Q144P="mobile",p.Q240P="lowest",p.Q360P="low",p.Q480P="medium",p.Q720P="high",p.Q1080P="fullhd",p.Q1440P="quadhd",p.Q2160P="ultrahd",p.UNKNOWN="unknown",p))(R||{}),O=(c=>(c.MP4="mp4",c.DASH="dash",c.DASH_SEP="dash_sep",c.ONDEMAND_DASH="ondemand_dash",c.HLS="hls",c.ONDEMAND_HLS="ondemand_hls",c.WEBM="webm",c.AV1="av1",c.ONDEMAND_DASH_LIVE="ondemand_dash_live",c.ONDEMAND_HLS_LIVE="ondemand_hls_live",c.WEBRTC="webrtc",c.UNKNOWN="unknown",c.RTMP="rtmp",c))(O||{});var N=(t=>(t.HTTP1="http1",t.HTTP2="http2",t.HTTP3="http3",t))(N||{});var D=(h=>(h.SLIDER="slider",h.DOUBLE_TAP="double_tap",h.TIME_CODE="time_code",h.EPISODE="episode",h.REWIND="rewind",h.LIVE="live",h.UNKNOWN="unknown",h))(D||{}),K=(n=>(n.GRAPH_SHOW="iGraphShow",n.GRAPH_HIDE="iGraphHide",n.NEXT_AREA="iNextChapterArea",n.NEXT_BUTTON="iNextChapterBtn",n.WATCH_AGAIN="iWatchAgainBtn",n))(K||{}),ie={action_play:"ap",action_play_interactive:"api",first_bytes:"fb",player_ready:"pr",first_frame:"ff",seek:"sk",watch_coverage_record:"wr",watch_coverage_live:"wl",empty_buffer:"eb",action_stop:"as",close_at_empty_buffer:"cb",content_error:"er",player_interface_click:"pc",next_movie:"nm",track_switch:"ts",failover:"fo"},oe={vsid:"si",isid:"is",vid:"vi",place:"pl",quality:"qt",cdn_host:"ch",stat_type:"st",param:"pm",vk_app_id:"va",track_code:"tc",connection_type:"cnt",connection_reused:"cr",cached_data:"cd",live:"lv",muted:"mu",mode:"mo",subtitles:"sb",failover:"fo",download_speed:"ds",manual_quality:"mq",ref_domain:"rd",direct_url:"du"},se={unknown:"un",mobile:"m",lowest:"ls",low:"l",medium:"md",high:"h",fullhd:"f",quadhd:"q",ultrahd:"u"},re={pip:"pi",fullscreen:"fs",external:"ex",prefetch:"pr",airplay:"ap",chromecast:"cc",invisible:"iv"};var ne=require("@vkontakte/videoplayer-shared"),Ce={apiEnv:"vk_alias",requestRetryCount:1,firstFlushTime:5e3,flushDebounceTime:1e4,flushMaxWait:6e4,storageExpiration:36*60*60*1e3,watchCoverageInterval:15e3,disabledOperations:[],disabledCustomFields:[],shorten:!0,maxLoops:100,embedUrlParams:[],useBeacon:!0,synchronizeTime:!0,debugLog:!1,backoff:{start:1e3,factor:1.5,max:5*60*1e3,random:.1}},ae=r=>(0,ne.fillWithDefault)(r,Ce);function q(){let r="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".split(""),e=new Array(36),i=0,t,o;for(o=0;o<36;o++)o===8||o===13||o===18||o===23?e[o]="-":o===14?e[o]="4":(i<=2&&(i=33554432+Math.random()*16777216|0),t=i&15,i=i>>4,e[o]=r[o===19?t&3|8:t]);return e.join("")}var d=require("@vkontakte/videoplayer-shared"),W=require("@vkontakte/videoplayer-shared");var de=r=>{var o;let{operation:e,custom:i}=r,t=Object.fromEntries(Object.entries(i).map(([n,a])=>{var p,m,g;let h=(p=oe[n])!=null?p:n,l=a;return a&&(n==="mode"?l=(m=re[a])!=null?m:a:n==="quality"&&(l=(g=se[a])!=null?g:a)),[h,l]}));return $(E({},r),{operation:(o=ie[e])!=null?o:e,custom:t})};var T="1.0.52-dev.22c05d5f.0",ue="CIOPGQJGDIHBABABA",z={prod:"https://api.ok.ru",vk_alias:"https://api.mycdn.me",videotest:"https://videotestapi.ok.ru/api",test:"https://apitest.ok.ru",auto:""};var I=require("@vkontakte/videoplayer-shared");var w=class{constructor(e){this.consequentAuthErrors=0;this.authorized$=new I.ValueSubject(!1);this.params=e}authorize(e){return S(this,null,function*(){return this.authToken=e!=null?e:yield this.refreshAuthToken(),this._authorizeWithBackoff()})}logBeacon(e){let i="log.externalLog",t=this.createLogParams(e),o=this.sessionKey;if(!o)return;this.params.apiTransport.sendBeacon(i,t,o)||this.logRequest(e)}logRequest(e){return S(this,null,function*(){var a;let i="log.externalLog",t=this.createLogParams(e),o=(a=this.sessionKey)!=null?a:yield this._authorizeWithBackoff();if(!o)return;let n=(p,...m)=>S(this,[p,...m],function*(h,l=this.params.config.requestRetryCount){try{return yield this.params.apiTransport.sendRequest(i,t,o)}catch(g){if(!g||!("error_code"in g)){this.params.error$.next({id:"logRequestUnknown",category:I.ErrorCategory.NETWORK,message:`Unknown ${i} error`,thrown:g});return}let s=g==null?void 0:g.error_code;switch(s){case 102:case 103:case 104:return this.authorized$.next(!1),this.sessionKey=yield this._authorizeWithBackoff(),l>0?n(h,l-1):void 0;case 401:return this.authorized$.next(!1),this.authToken=yield this.refreshAuthToken(),this.sessionKey=yield this._authorizeWithBackoff(),l>0?n(h,l-1):void 0;default:{this.params.error$.next({id:`LogRequest#${s}`,category:I.ErrorCategory.EXTERNAL_API,message:`${i} error`,data:g});return}}}});return n(e)})}destroy(){window.clearTimeout(this.backoffTimeoutId),this.backoffTimeoutId=0}refreshAuthToken(){return S(this,null,function*(){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:${T}`,platform:this.params.mobile?"M_WEB":"WEB",items:this.params.config.shorten?e.map(de):e})}}_authorizeWithBackoff(){if(!this.consequentAuthErrors)return this._authorize();let e=(0,I.getExponentialDelay)(this.consequentAuthErrors,this.params.config.backoff);return new Promise(i=>{this.backoffTimeoutId||(this.backoffTimeoutId=window.setTimeout(()=>{this._authorize().then(i).catch(t=>this.params.error$.next({id:"AuthorizeBackoff",category:I.ErrorCategory.NETWORK,message:"Otherwise unhandled error in authorization",thrown:t})).finally(()=>this.backoffTimeoutId=0)},e))})}_authorize(){return S(this,null,function*(){if(this.authorizePromise)return this.authorizePromise;this.sessionKey=void 0,this.authorized$.next(!1);let e="auth.anonymLogin",i={session_data:{version:2,device_id:this.params.uuid,client_version:T.split("-")[0],client_type:"SDK_JS"}};return this.authToken!==void 0&&(i.session_data.auth_token=this.authToken,i.session_data.version=3),this.authorizePromise=this.params.apiTransport.sendRequest(e,i).then(t=>{var o;return(!t||!t.session_key)&&this.params.error$.next({id:"AuthorizeFailed",category:I.ErrorCategory.EXTERNAL_API,message:"No session key",data:t}),this.sessionKey=(o=t==null?void 0:t.session_key)!=null?o:void 0,this.sessionKey}).catch(t=>S(this,null,function*(){this.sessionKey=void 0;let o=t==null?void 0:t.error_code;switch(o){case 401:return this.authToken=yield this.refreshAuthToken(),this._authorizeWithBackoff()}o?this.params.error$.next({id:`Authorize#${o}`,category:I.ErrorCategory.EXTERNAL_API,message:"authorize error",data:t}):this.params.error$.next({id:"AuthorizeUnknown",category:I.ErrorCategory.NETWORK,message:"authorize error",thrown:t})})).finally(()=>{this.authorizePromise=void 0,this.consequentAuthErrors=this.sessionKey?0:this.consequentAuthErrors+1,this.authorized$.next(this.sessionKey!==void 0)}),this.authorizePromise})}};var y=require("@vkontakte/videoplayer-shared");var k=class{constructor(e){this.params=e,this.apiKey=e.apiKey,this.apiEnv=e.config.apiEnv,this.apiBaseUrl=z[this.apiEnv],this.timeSynchronisation=e.timeSynchronisation,this.isApiBaseUrlFetched=!1}resolveApiBaseUrl(){return S(this,null,function*(){var e;if(this.apiEnv!=="auto"||this.isApiBaseUrlFetched)return this.apiBaseUrl;try{let i=atob("aHR0cHM6Ly9kbnMuZ29vZ2xlL3Jlc29sdmU/bmFtZT12aWRlby5fZW5kcG9pbnQub2sucnUmdHlwZT1UWFQ="),o=yield(yield fetch(i,{method:"GET",mode:"cors",cache:"no-cache"})).json(),n=(e=o==null?void 0:o.Answer[0])==null?void 0:e.data;if(!n)throw new Error("Wrong DNS response");return n}catch(i){return this.params.error$.next({id:"OneStat:ApiTransport:resolveApiBaseUrl",category:y.ErrorCategory.NETWORK,message:"Unhandled resolve api base url error",thrown:i}),z.vk_alias}finally{this.isApiBaseUrlFetched=!0}})}sendBeacon(e,i,t){if(!window.Blob||!window.navigator.sendBeacon)return!1;let o=this._prepareQueryParams({method:e,queryParams:i,sessionKey:t}),n=new window.Blob([o.toString()],{type:"application/x-www-form-urlencoded"});try{return window.navigator.sendBeacon(`${this.apiBaseUrl}/fb.do`,n)}catch(a){this.params.error$.next({id:"OneStat:ApiTransport:sendBeacon",category:y.ErrorCategory.NETWORK,message:"Unhandled beacon error",thrown:a,data:{method:e,params:i}})}return!1}sendRequest(e,i,t){return S(this,null,function*(){let o=(0,y.now)(),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:y.ErrorCategory.NETWORK,message:"Request failed",thrown:a});return}this.params.error$.next({id:"OneStat:ApiTransport:sendRequest",category:y.ErrorCategory.NETWORK,message:"Unhandled request error",thrown:a,data:{method:e,params:i,sessionKey:t,time:(0,y.now)()-o}})};return this.apiBaseUrl=yield this.resolveApiBaseUrl(),fetch(`${this.apiBaseUrl}/fb.do`,{method:"post",headers:{"Content-type":"application/x-www-form-urlencoded"},body:this._prepareQueryParams({method:e,queryParams:i,sessionKey:t})}).then(a=>{var m,g;let h=Number(a.headers.get("content-length"))===0,l=new Date((m=a.headers.get("date"))!=null?m:"").getTime(),p=(0,y.now)()-o;if(isFinite(l)&&((g=this.timeSynchronisation)==null||g.addServerTime(l,p)),!h)return a.json().then(s=>Object.prototype.hasOwnProperty.call(s,"error_msg")?Promise.reject(s):s,n)},n)})}_prepareQueryParams(e){let i=new URLSearchParams({format:"JSON",method:e.method,application_key:this.apiKey});return e.sessionKey!==void 0&&i.append("session_key",e.sessionKey),Object.entries(e.queryParams).forEach(([t,o])=>i.append(t,typeof o=="string"?o:JSON.stringify(o))),i}};var v=require("@vkontakte/videoplayer-shared");var M="onestat_events",Q=r=>e=>e.timestamp+r>=(0,v.now)(),B=class{constructor(e){this.unsaltedStorage=[];this.isPaused=!1;this.isUrgent=e=>{let{operation:i}=e;return["action_play","watch_coverage_record","watch_coverage_live"].includes(i)};this.params=e,this.api=e.api,this.error$=e.error$,this.userSalt=e.userSalt,this.loggerDebugLog=e.debugLogger.createComponentLog("stat logger"),this.firstFlush=(0,v.debounceFn)(()=>this.safeFlush(),this.params.config.firstFlushTime,{maxWait:this.params.config.firstFlushTime});let i=v.safeStorage.isPersistent()?this.params.config.flushMaxWait:0;this.debouncedFlush=(0,v.debounceFn)(()=>this.safeFlush(),this.params.config.flushDebounceTime,{maxWait:i}),this.subscription=this.api.authorized$.subscribe(t=>{t&&this.debouncedFlush()}),this.housekeepStorage()}safeFlush(){var e;try{this.flush()}catch(i){this.error$.next({id:"LoggerError",category:v.ErrorCategory.WTF,message:(e=String(i))!=null?e:"Unknown logger error",thrown:i})}}readFromStorage(){let e=v.safeStorage.get(M);try{return e?JSON.parse(e):{}}catch(i){}return{}}addToStorage(e){var n;if(!this.userSalt){this.unsaltedStorage.push(e);return}let i=this.readFromStorage(),o=((n=i[this.userSalt])!=null?n:[]).filter(Q(this.params.config.storageExpiration));v.safeStorage.set(M,JSON.stringify($(E({},i),{[this.userSalt]:[...o,e]})))}getFromStorage(){var t;return this.userSalt?((t=this.readFromStorage()[this.userSalt])!=null?t:[]).filter(Q(this.params.config.storageExpiration)):this.unsaltedStorage}markStorageSent(){if(!this.userSalt){this.unsaltedStorage=[];return}let e=this.readFromStorage();delete e[this.userSalt],v.safeStorage.set(M,JSON.stringify(e))}housekeepStorage(){let e=this.readFromStorage();for(let[i,t]of Object.entries(e)){let o=t.filter(Q(this.params.config.storageExpiration));o.length?e[i]=o:delete e[i],this.loggerDebugLog({message:`${t.length} retrieved from storage, ${o.length} of them actual`})}v.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){let i=this.getFromStorage();i.length!==0&&(this.api.authorized$.getValue()?(e&&this.params.config.useBeacon?(this.loggerDebugLog({message:`Flushing ${i.length} events through beacon`}),this.api.logBeacon(i)):(this.loggerDebugLog({message:`Flushing ${i.length} events`}),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()}};var u=require("@vkontakte/videoplayer-core"),j=require("@vkontakte/videoplayer-shared");var ce=r=>r&&{[u.VideoQuality.INVARIANT]:"unknown",[u.VideoQuality.Q_144P]:"mobile",[u.VideoQuality.Q_240P]:"lowest",[u.VideoQuality.Q_360P]:"low",[u.VideoQuality.Q_480P]:"medium",[u.VideoQuality.Q_720P]:"high",[u.VideoQuality.Q_1080P]:"fullhd",[u.VideoQuality.Q_1440P]:"quadhd",[u.VideoQuality.Q_2160P]:"ultrahd",[u.VideoQuality.Q_4320P]:"unknown"}[r],G=r=>r&&{[u.HttpConnectionType.HTTP1]:"http1",[u.HttpConnectionType.HTTP2]:"http2",[u.HttpConnectionType.QUIC]:"http3"}[r],le=r=>{if(r!==void 0)switch(r){case u.VideoFormat.MPEG:return"mp4";case u.VideoFormat.DASH:case u.VideoFormat.DASH_LIVE:case u.VideoFormat.DASH_STREAMS:return"dash";case u.VideoFormat.DASH_SEP:return"dash_sep";case u.VideoFormat.DASH_ONDEMAND:return"ondemand_dash";case u.VideoFormat.DASH_WEBM:case u.VideoFormat.DASH_LIVE_WEBM:return"webm";case u.VideoFormat.DASH_WEBM_AV1:return"av1";case u.VideoFormat.DASH_LIVE_CMAF:return"ondemand_dash_live";case u.VideoFormat.HLS:case u.VideoFormat.HLS_LIVE:return"hls";case u.VideoFormat.HLS_ONDEMAND:return"ondemand_hls";case u.VideoFormat.HLS_LIVE_CMAF:return"ondemand_hls_live";case u.VideoFormat.WEB_RTC_LIVE:return"webrtc";default:return(0,j.assertNever)(r)}},F=r=>{if(r!==void 0)switch(r){case u.Surface.NONE:case u.Surface.INLINE:return;case u.Surface.FULLSCREEN:return"fullscreen";case u.Surface.SECOND_SCREEN:return"chromecast";case u.Surface.PIP:return"pip";case u.Surface.INVISIBLE:return"invisible";default:return(0,j.assertNever)(r)}},pe=r=>{switch(r){case"slow-2g":return"poor";case"2g":return"poor";case"3g":return"good";case"4g":return"excellent"}};var V=class{constructor(e){this.offset=void 0;this.offset=e}getOffset(){var e;return(e=this.offset)!=null?e:0}setOffset(e){this.offset=e}now(){var e;return Date.now()+((e=this.offset)!=null?e:0)}date(e=new Date){var i;return e.setTime(e.getTime()+((i=this.offset)!=null?i:0)),e}addServerTime(e,i){let t=Date.now(),o=e-t-i/2;if(Math.abs(o)<1e3){this.offset=0;return}this.offset===void 0?this.offset=Math.round(o):this.offset=Math.round(.2*o+(1-.2)*this.offset)}};var he=()=>Math.floor(Math.random()*4294967296).toString(36).padStart(7,"0"),fe=()=>Math.floor(Math.random()*18446744073709552e3).toString(36).padStart(13,"0");var Y=require("@vkontakte/videoplayer-core"),f=require("@vkontakte/videoplayer-shared"),ge=(r,e)=>new f.Observable(i=>{let t=new f.Subscription,o=(0,f.merge)((0,f.fromEvent)(window,"beforeunload"),r.events.willDestruct$),n=new f.ValueSubject(void 0),a;t.add(r.info.isLive$.pipe((0,f.filterChanged)()).subscribe(A=>{a&&(a.unsubscribe(),n.next(void 0)),A?a=r.info.liveTime$.pipe((0,f.map)(H=>H&&H/1e3)).subscribe(n):a=r.info.position$.subscribe(n),t.add(a)}));let{playing$:h,paused$:l}=r.events,p=r.events.willSeek$.pipe((0,f.filter)(()=>r.info.playbackState$.getValue()===Y.PlaybackState.PLAYING)),m=r.events.seeked$.pipe((0,f.filter)(()=>r.info.playbackState$.getValue()===Y.PlaybackState.PLAYING)),g=!1,s=new f.Subject;t.add(p.subscribe(()=>{g||s.next(),g=!0})),t.add(m.subscribe(()=>g=!1));let c=new f.Subject,b=new f.Subject,P=(0,f.merge)(h,m,c),_=(0,f.merge)(l,s,o,r.events.looped$,b),x,me=()=>x=n.getValue(),be=()=>{let A=n.getValue();(0,f.isNullable)(x)||x===A||(0,f.isNullable)(A)||(i.next({from:x,to:A}),x=void 0)},ve=()=>{b.next(),c.next()};if(t.add(P.subscribe(me)),t.add(_.subscribe(be)),e.forceInterval&&isFinite(e.forceInterval)){let A=0;t.add(P.subscribe(()=>A=window.setTimeout(ve,e.forceInterval))),t.add(_.subscribe(()=>window.clearTimeout(A)))}return t});var we="_one-stat_",X=`${we}uuid`,J=()=>{let r=new d.Subscription;return{subscription:r,subscribe:(e,i)=>{e&&r.add(e.subscribe(i))}}},U=class{constructor(e,i){this.subscription=new d.Subscription;this.debugLogger=new W.Logger;this.oneStatDebugLog=this.debugLogger.createComponentLog("onestat");this.loopCounter=0;this.disabled=!1;this.vsid$=new d.ValueSubject(void 0);this.isid$=new d.ValueSubject(void 0);this.seekAction$=new d.ValueSubject("unknown");var l,p,m;this.statContext=e,this.config=ae((l=i.config)!=null?l:{}),(0,d.isNonNullable)(i.apiEnv)&&(this.config.apiEnv=i.apiEnv),this.config.synchronizeTime&&(this.timeSynchronisation=new V);let t=new d.Subject;this.experimental={error$:t};let o=d.safeStorage.get(X);o?o.startsWith('"')&&o.endsWith('"')?(this.uuid=o.replaceAll('"',""),d.safeStorage.set(X,this.uuid)):this.uuid=o:(this.uuid=q(),d.safeStorage.set(X,this.uuid)),this.resetViewSession(),i.useIsid&&this.isid$.next((p=i.isid)!=null?p:fe());let n=new k({apiKey:ue,config:this.config,error$:t,timeSynchronisation:this.timeSynchronisation});this.api=new w({config:this.config,apiTransport:n,refreshAuthToken:i.refreshAuthToken,mobile:(m=this.statContext.mobile)!=null?m:!1,uuid:this.uuid,error$:t}),this.logger=new B({config:this.config,debugLogger:this.debugLogger,api:this.api,error$:t,userSalt:i.userSalt});let{isEmbed:a,host:h}=(0,W.detectEmbed)();this.isEmbed=a,this.embedParent=h,this.subscribe()}updateContext(e){this.statContext=E(E({},this.statContext),e)}attachTo(e){let i=new d.Subscription,t=(s,c)=>i.add(s.subscribe(c));t(e.events.willStart$,()=>{let s=e.info.position$.getValue();this.logActionPlay({position:s}),this.statContext.projectId&&this.logActionPlayInteractive()}),t(e.events.looped$,()=>{this.resetViewSession(),++this.loopCounter>this.config.maxLoops&&(this.disabled=!0),this.logActionPlay({position:e.info.position$.getValue()})}),t(e.events.seeked$,()=>{this.logSeek({action:this.seekAction$.getValue(),time:e.info.position$.getValue()}),this.seekAction$.next("unknown")}),t(e.events.paused$,()=>{this.logPause({position:e.info.position$.getValue()})}),t(e.events.willResume$,()=>{this.logPlay()}),t(e.events.started$,()=>{this.statContext.clip&&this.logWatchCoverageRecord({start:0,end:0})}),t(e.events.playing$,()=>{this.logPlaying()}),t(ge(e,{forceInterval:this.config.watchCoverageInterval}),s=>{let c=e.info.isLive$.getValue(),b={start:parseFloat(s.from.toFixed(3)),end:parseFloat(s.to.toFixed(3))};c?this.logWatchCoverageLive(b):this.logWatchCoverageRecord(b)});let o;t(e.info.isStalled$,s=>{s?o=(0,d.now)():((0,d.isNonNullable)(o)&&this.logEmptyBuffer({duration:(0,d.now)()-o}),o=void 0)});let n=!1;i.add(e.events.fatalError$.pipe((0,d.once)()).subscribe(()=>n=!0)),t(e.events.willStop$,()=>{if(e.info.isStalled$.getValue()){let c=(0,d.isNonNullable)(o)?(0,d.now)()-o:void 0;this.logCloseAtEmptyBuffer({duration:c!=null?c:0}),o=void 0}else n||this.logActionStop()}),t(e.events.managedError$,({id:s})=>{this.logError({fatal:!1,errorType:s})}),t(e.events.fatalError$,({id:s})=>{this.logError({fatal:!0,errorType:s})});let a,h,l=!1;t(e.events.firstBytes$,s=>{a=(0,d.now)(),this.logFirstBytes({time:s})}),t(e.events.willStart$,()=>h=(0,d.now)()),t(e.info.currentBuffer$,s=>{!l&&s&&s.end-s.start>0&&(0,d.isNonNullable)(a)&&(this.logPlayerReady({duration:(0,d.now)()-a}),l=!0)}),t(e.events.firstFrame$,()=>{(0,d.isNonNullable)(a)&&!l&&(this.logPlayerReady({duration:(0,d.now)()-a}),l=!0),(0,d.isNonNullable)(h)&&this.logFirstFrame({time:(0,d.now)()-h})});let p;t(e.info.currentVideoStream$,s=>{s&&(p&&s.id!==p&&this.logTrackSwitch(s),p=s.id)});let m;t(e.info.currentAudioStream$,s=>{s&&(m&&s.id!==m&&this.logTrackSwitch(s),m=s.id)}),t(e.info.atLiveEdge$,s=>this.updateContext({liveEdge:s})),t((0,d.combine)({muted:e.info.muted$,volume:e.info.volume$}),({muted:s,volume:c})=>this.updateContext({audible:!s&&c>0})),t(e.info.currentQuality$,s=>this.updateContext({quality:ce(s)})),t(e.info.isAutoQualityEnabled$,s=>this.updateContext({autoQuality:s})),t(e.info.currentFormat$,s=>this.updateContext({contentType:le(s)})),t(e.info.currentPlaybackRate$,s=>this.updateContext({rate:s})),t(e.info.is3DVideo$,s=>this.updateContext({is3d:s}));let g;return t(e.info.hostname$,s=>{let c=g!==void 0&&g!==s;this.updateContext({cdnHostname:s,failover:c}),c&&this.logFailover(s),g=s}),t(e.info.throughputEstimation$,s=>this.updateContext({downloadSpeed:s})),t(e.info.httpConnectionType$,s=>{this.statContext.firstConnectionType||this.updateContext({firstConnectionType:G(s)}),this.updateContext({connectionType:G(s)})}),t(e.info.httpConnectionReused$,s=>{(0,d.isNullable)(this.statContext.firstConnectionReused)&&this.updateContext({firstConnectionReused:s}),this.updateContext({connectionReused:s})}),t(e.info.surface$,s=>this.updateContext({mode:F(s)})),t((0,d.combine)({current:e.info.currentTextTrack$,available:e.info.availableTextTracks$}),({current:s,available:c})=>{let b=c.find(({id:_})=>_===s),P=b&&(b.isAuto?`${b.language}_auto`:b.language);this.updateContext({subtitles:P})}),this.player=e,this.uiEvents&&this.attachToUi(this.uiEvents),this.resubscribeBeforeunload(),this.subscription.add(i),i}attachToUi(e){this.uiEvents=e;let{subscription:i,subscribe:t}=J();return this.player&&(t(e.actionRewind$,()=>{this.player&&(this.resetViewSession(),this.logActionPlay({position:this.player.info.position$.getValue()}))}),t(e.actionSeek$,this.seekAction$),t(e.inPiP$,o=>{var a;let n=o?"pip":F((a=this.player)==null?void 0:a.info.surface$.getValue());this.updateContext({mode:n})}),t(e.inFullscreen$,o=>{var a;let n=o?"fullscreen":F((a=this.player)==null?void 0:a.info.surface$.getValue());this.updateContext({mode:n})}),t(e.actionSetSubtitle$,o=>this.updateContext({subtitles:o})),t(e.nextMovie$,o=>this.logNextMovie(o)),this.resubscribeBeforeunload(),this.subscription.add(i)),i}attachToAds(e){let{subscription:i,subscribe:t}=J();return t(e.slotRequested$,()=>this.logAdSlotRequest()),t(e.started$,o=>this.logAdStarted(o)),t(e.paused$,()=>this.logAdPaused()),t(e.resumed$,()=>this.logAdResumed()),t(e.ended$,()=>this.logAdEnded()),t(e.skipped$,()=>this.logAdSkipped()),t(e.clicked$,()=>this.logAdClicked()),this.resubscribeBeforeunload(),this.subscription.add(i),i}attachToInteractive(e){let{subscription:i,subscribe:t}=J();return t(e.click$,o=>this.logInterfaceClick(o)),t(e.nextMovie$,o=>this.logNextMovie(o)),this.resubscribeBeforeunload(),this.subscription.add(i),i}authorize(e){return this.api.authorize(e)}pause(){this.logger.pause(),this.oneStatDebugLog({message:"paused"})}resume(){this.logger.resume(),this.oneStatDebugLog({message:"resumed"})}destroy(){this.logger.flush(),this.subscription.unsubscribe(),this.api.destroy(),this.logger.destroy()}resetViewSession(){this.oneStatDebugLog({message:"VSID reset"}),this.vsid$.next(he())}getDeviceId(){return this.uuid}setFieldBlacklist(){}logInited(){}logReady(e){this.log({operation:"player_ready",param:String(e.time)})}logStarted(...e){this.logActionPlay(...e)}logPlay(){this.log({operation:"play_toggle"})}logPlaying(){this.log({operation:"playing"})}logPause(e){this.log({operation:"pause",param:String(Math.round(e.position))})}logSeek(e){this.log({operation:"seek",param:e.action,time:e.time})}logFirstBytes(e){this.log({operation:"first_bytes",param:String(e.time)})}logFirstFrame(e){this.log({operation:"first_frame",param:String(e.time)})}logError(e){this.log({operation:"content_error",param:`${e.fatal?"fatal":"recoverable"}_${e.errorType}`})}logWatchCoverageRecord(e){this.log({operation:"watch_coverage_record",param:`${e.start}-${e.end}`})}logWatchCoverageLive(e){var n,a;let i=(a=(n=this.timeSynchronisation)==null?void 0:n.getOffset())!=null?a:0,t=e.start+i,o=e.end+i;this.log({operation:"watch_coverage_live",param:`${t}-${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();let e=window.navigator.connection;e&&"onchange"in e&&"effectiveType"in e&&this.subscription.add((0,d.merge)((0,d.fromEvent)(e,"change"),(0,d.observableFrom)(["init"])).subscribe(()=>this.updateContext({network:pe(e.effectiveType)}))),this.config.debugLog&&this.debugLogger.log$.subscribe(i=>{console.debug("%c stat ","background:#fa6470;",`component: ${i.component}.`,i.message)})}resubscribeBeforeunload(){var e;(e=this.beforeunloadSubscription)==null||e.unsubscribe(),this.beforeunloadSubscription=(0,d.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))})}logActionPlayInteractive(){this.statContext.projectId&&this.log({operation:"action_play_interactive",param:String(this.statContext.movieId)},{vid:this.statContext.projectId})}logFailover(e){this.log({operation:"failover",param:e})}logCloseAtEmptyBuffer(e){this.log({operation:"close_at_empty_buffer",param:String(Math.round(e.duration))})}logActionStop(){this.log({operation:"action_stop"})}logTrackSwitch(e){this.log({operation:"track_switch",param:e.id})}log(e,i={}){if(this.disabled){this.oneStatDebugLog({message:`operation ${e.operation} but statistics is disabled`});return}if(this.config.disabledOperations.includes(e.operation)){this.oneStatDebugLog({message:`operation ${e.operation} but it is disabled`});return}this.oneStatDebugLog({message:`operation ${e.operation} ${e.param}`});let t=this.createLogItem(e,i);this.logger.log(t)}createLogItem({operation:e,param:i,time:t},o={}){var c,b;let n=(b=(c=this.timeSynchronisation)==null?void 0:c.now())!=null?b:(0,d.now)(),a=this.vsid$.getValue();(0,d.assertNonNullable)(a);let h=this.isid$.getValue(),l=e==="empty_buffer"||e==="close_at_empty_buffer"?this.statContext.connectionType:this.statContext.firstConnectionType,p=this.statContext.firstConnectionReused,m,g;if(this.isEmbed){m=this.embedParent;let P=[...new URLSearchParams(location.search).entries()].filter(([_,x])=>this.config.embedUrlParams.includes(_));g=new URLSearchParams(P).toString()}else this.statContext.place==="direct"&&((this.statContext.refDomain||document.referrer)&&(m=new URL(this.statContext.refDomain||document.referrer).hostname),g=location.href.substring(0,1024));let s=E({vsid:a,isid:h,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?"auto":this.statContext.autoplay===!1?"":void 0,param:i,vk_app_id:this.statContext.vkAppId,track_code:this.statContext.trackCode,connection_type:l,connection_reused:p===!0?1:p===!1?0:void 0,cached_data:this.statContext.cached===!0?1:this.statContext.cached===!1?0:void 0,live:this.statContext.liveEdge?1:void 0,muted:this.statContext.audible===!1?1:void 0,mode:this.statContext.mode,subtitles:this.statContext.subtitles,download_speed:this.statContext.downloadSpeed,manual_quality:this.statContext.autoQuality?void 0:1,ref_domain:m,direct_url:g,rate:this.statContext.rate===1||(0,d.isNullable)(this.statContext.rate)?void 0:this.statContext.rate.toFixed(2),view_360:this.statContext.is3d?1:void 0,aid:this.statContext.albumId,vk_playlist_id:this.statContext.vkPlaylistId},o);for(let P of this.config.disabledCustomFields)delete s[P];return{operation:e,type:1,time:t,network:this.statContext.network,timestamp:n,custom:s}}};
6
+ "use strict";var L=Object.defineProperty,Ie=Object.defineProperties,Se=Object.getOwnPropertyDescriptor,ye=Object.getOwnPropertyDescriptors,Pe=Object.getOwnPropertyNames,Z=Object.getOwnPropertySymbols;var te=Object.prototype.hasOwnProperty,Ae=Object.prototype.propertyIsEnumerable;var ee=(r,e,i)=>e in r?L(r,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):r[e]=i,E=(r,e)=>{for(var i in e||(e={}))te.call(e,i)&&ee(r,i,e[i]);if(Z)for(var i of Z(e))Ae.call(e,i)&&ee(r,i,e[i]);return r},$=(r,e)=>Ie(r,ye(e));var Ee=(r,e)=>{for(var i in e)L(r,i,{get:e[i],enumerable:!0})},_e=(r,e,i,t)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Pe(e))!te.call(r,o)&&o!==i&&L(r,o,{get:()=>e[o],enumerable:!(t=Se(e,o))||t.enumerable});return r};var xe=r=>_e(L({},"__esModule",{value:!0}),r);var S=(r,e,i)=>new Promise((t,o)=>{var n=l=>{try{h(i.next(l))}catch(p){o(p)}},a=l=>{try{h(i.throw(l))}catch(p){o(p)}},h=l=>l.done?t(l.value):Promise.resolve(l.value).then(n,a);h((i=i.apply(r,e)).next())});var ke={};Ee(ke,{ApiEnv:()=>C,ConnectionType:()=>N,ContentType:()=>O,InteractiveInterfaceClick:()=>K,OneStat:()=>U,Quality:()=>R,SeekAction:()=>D,VERSION:()=>T});module.exports=xe(ke);var C=(n=>(n.PROD="prod",n.VK_ALIAS="vk_alias",n.VIDEOTEST="videotest",n.TEST="test",n.AUTO="auto",n))(C||{}),R=(p=>(p.Q144P="mobile",p.Q240P="lowest",p.Q360P="low",p.Q480P="medium",p.Q720P="high",p.Q1080P="fullhd",p.Q1440P="quadhd",p.Q2160P="ultrahd",p.UNKNOWN="unknown",p))(R||{}),O=(c=>(c.MP4="mp4",c.DASH="dash",c.DASH_SEP="dash_sep",c.ONDEMAND_DASH="ondemand_dash",c.HLS="hls",c.ONDEMAND_HLS="ondemand_hls",c.WEBM="webm",c.AV1="av1",c.ONDEMAND_DASH_LIVE="ondemand_dash_live",c.ONDEMAND_HLS_LIVE="ondemand_hls_live",c.WEBRTC="webrtc",c.UNKNOWN="unknown",c.RTMP="rtmp",c))(O||{});var N=(t=>(t.HTTP1="http1",t.HTTP2="http2",t.HTTP3="http3",t))(N||{});var D=(h=>(h.SLIDER="slider",h.DOUBLE_TAP="double_tap",h.TIME_CODE="time_code",h.EPISODE="episode",h.REWIND="rewind",h.LIVE="live",h.UNKNOWN="unknown",h))(D||{}),K=(n=>(n.GRAPH_SHOW="iGraphShow",n.GRAPH_HIDE="iGraphHide",n.NEXT_AREA="iNextChapterArea",n.NEXT_BUTTON="iNextChapterBtn",n.WATCH_AGAIN="iWatchAgainBtn",n))(K||{}),ie={action_play:"ap",action_play_interactive:"api",first_bytes:"fb",player_ready:"pr",first_frame:"ff",seek:"sk",watch_coverage_record:"wr",watch_coverage_live:"wl",empty_buffer:"eb",action_stop:"as",close_at_empty_buffer:"cb",content_error:"er",player_interface_click:"pc",next_movie:"nm",track_switch:"ts",failover:"fo"},oe={vsid:"si",isid:"is",vid:"vi",place:"pl",quality:"qt",cdn_host:"ch",stat_type:"st",param:"pm",vk_app_id:"va",track_code:"tc",connection_type:"cnt",connection_reused:"cr",cached_data:"cd",live:"lv",muted:"mu",mode:"mo",subtitles:"sb",failover:"fo",download_speed:"ds",manual_quality:"mq",ref_domain:"rd",direct_url:"du"},se={unknown:"un",mobile:"m",lowest:"ls",low:"l",medium:"md",high:"h",fullhd:"f",quadhd:"q",ultrahd:"u"},re={pip:"pi",fullscreen:"fs",external:"ex",prefetch:"pr",airplay:"ap",chromecast:"cc",invisible:"iv"};var ne=require("@vkontakte/videoplayer-shared"),Ce={apiEnv:"vk_alias",requestRetryCount:1,firstFlushTime:5e3,flushDebounceTime:1e4,flushMaxWait:6e4,storageExpiration:36*60*60*1e3,watchCoverageInterval:15e3,disabledOperations:[],disabledCustomFields:[],shorten:!0,maxLoops:100,embedUrlParams:[],useBeacon:!0,synchronizeTime:!0,debugLog:!1,backoff:{start:1e3,factor:1.5,max:5*60*1e3,random:.1}},ae=r=>(0,ne.fillWithDefault)(r,Ce);function q(){let r="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".split(""),e=new Array(36),i=0,t,o;for(o=0;o<36;o++)o===8||o===13||o===18||o===23?e[o]="-":o===14?e[o]="4":(i<=2&&(i=33554432+Math.random()*16777216|0),t=i&15,i=i>>4,e[o]=r[o===19?t&3|8:t]);return e.join("")}var d=require("@vkontakte/videoplayer-shared"),W=require("@vkontakte/videoplayer-shared");var de=r=>{var o;let{operation:e,custom:i}=r,t=Object.fromEntries(Object.entries(i).map(([n,a])=>{var p,m,g;let h=(p=oe[n])!=null?p:n,l=a;return a&&(n==="mode"?l=(m=re[a])!=null?m:a:n==="quality"&&(l=(g=se[a])!=null?g:a)),[h,l]}));return $(E({},r),{operation:(o=ie[e])!=null?o:e,custom:t})};var T="1.0.52-dev.a5f6699f.0",ue="CIOPGQJGDIHBABABA",z={prod:"https://api.ok.ru",vk_alias:"https://api.mycdn.me",videotest:"https://videotestapi.ok.ru/api",test:"https://apitest.ok.ru",auto:""};var I=require("@vkontakte/videoplayer-shared");var w=class{constructor(e){this.consequentAuthErrors=0;this.authorized$=new I.ValueSubject(!1);this.params=e}authorize(e){return S(this,null,function*(){return this.authToken=e!=null?e:yield this.refreshAuthToken(),this._authorizeWithBackoff()})}logBeacon(e){let i="log.externalLog",t=this.createLogParams(e),o=this.sessionKey;if(!o)return;this.params.apiTransport.sendBeacon(i,t,o)||this.logRequest(e)}logRequest(e){return S(this,null,function*(){var a;let i="log.externalLog",t=this.createLogParams(e),o=(a=this.sessionKey)!=null?a:yield this._authorizeWithBackoff();if(!o)return;let n=(p,...m)=>S(this,[p,...m],function*(h,l=this.params.config.requestRetryCount){try{return yield this.params.apiTransport.sendRequest(i,t,o)}catch(g){if(!g||!("error_code"in g)){this.params.error$.next({id:"logRequestUnknown",category:I.ErrorCategory.NETWORK,message:`Unknown ${i} error`,thrown:g});return}let s=g==null?void 0:g.error_code;switch(s){case 102:case 103:case 104:return this.authorized$.next(!1),this.sessionKey=yield this._authorizeWithBackoff(),l>0?n(h,l-1):void 0;case 401:return this.authorized$.next(!1),this.authToken=yield this.refreshAuthToken(),this.sessionKey=yield this._authorizeWithBackoff(),l>0?n(h,l-1):void 0;default:{this.params.error$.next({id:`LogRequest#${s}`,category:I.ErrorCategory.EXTERNAL_API,message:`${i} error`,data:g});return}}}});return n(e)})}destroy(){window.clearTimeout(this.backoffTimeoutId),this.backoffTimeoutId=0}refreshAuthToken(){return S(this,null,function*(){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:${T}`,platform:this.params.mobile?"M_WEB":"WEB",items:this.params.config.shorten?e.map(de):e})}}_authorizeWithBackoff(){if(!this.consequentAuthErrors)return this._authorize();let e=(0,I.getExponentialDelay)(this.consequentAuthErrors,this.params.config.backoff);return new Promise(i=>{this.backoffTimeoutId||(this.backoffTimeoutId=window.setTimeout(()=>{this._authorize().then(i).catch(t=>this.params.error$.next({id:"AuthorizeBackoff",category:I.ErrorCategory.NETWORK,message:"Otherwise unhandled error in authorization",thrown:t})).finally(()=>this.backoffTimeoutId=0)},e))})}_authorize(){return S(this,null,function*(){if(this.authorizePromise)return this.authorizePromise;this.sessionKey=void 0,this.authorized$.next(!1);let e="auth.anonymLogin",i={session_data:{version:2,device_id:this.params.uuid,client_version:T.split("-")[0],client_type:"SDK_JS"}};return this.authToken!==void 0&&(i.session_data.auth_token=this.authToken,i.session_data.version=3),this.authorizePromise=this.params.apiTransport.sendRequest(e,i).then(t=>{var o;return(!t||!t.session_key)&&this.params.error$.next({id:"AuthorizeFailed",category:I.ErrorCategory.EXTERNAL_API,message:"No session key",data:t}),this.sessionKey=(o=t==null?void 0:t.session_key)!=null?o:void 0,this.sessionKey}).catch(t=>S(this,null,function*(){this.sessionKey=void 0;let o=t==null?void 0:t.error_code;switch(o){case 401:return this.authToken=yield this.refreshAuthToken(),this._authorizeWithBackoff()}o?this.params.error$.next({id:`Authorize#${o}`,category:I.ErrorCategory.EXTERNAL_API,message:"authorize error",data:t}):this.params.error$.next({id:"AuthorizeUnknown",category:I.ErrorCategory.NETWORK,message:"authorize error",thrown:t})})).finally(()=>{this.authorizePromise=void 0,this.consequentAuthErrors=this.sessionKey?0:this.consequentAuthErrors+1,this.authorized$.next(this.sessionKey!==void 0)}),this.authorizePromise})}};var y=require("@vkontakte/videoplayer-shared");var k=class{constructor(e){this.params=e,this.apiKey=e.apiKey,this.apiEnv=e.config.apiEnv,this.apiBaseUrl=z[this.apiEnv],this.timeSynchronisation=e.timeSynchronisation,this.isApiBaseUrlFetched=!1}resolveApiBaseUrl(){return S(this,null,function*(){var e;if(this.apiEnv!=="auto"||this.isApiBaseUrlFetched)return this.apiBaseUrl;try{let i=atob("aHR0cHM6Ly9kbnMuZ29vZ2xlL3Jlc29sdmU/bmFtZT12aWRlby5fZW5kcG9pbnQub2sucnUmdHlwZT1UWFQ="),o=yield(yield fetch(i,{method:"GET",mode:"cors",cache:"no-cache"})).json(),n=(e=o==null?void 0:o.Answer[0])==null?void 0:e.data;if(!n)throw new Error("Wrong DNS response");return n}catch(i){return this.params.error$.next({id:"OneStat:ApiTransport:resolveApiBaseUrl",category:y.ErrorCategory.NETWORK,message:"Unhandled resolve api base url error",thrown:i}),z.vk_alias}finally{this.isApiBaseUrlFetched=!0}})}sendBeacon(e,i,t){if(!window.Blob||!window.navigator.sendBeacon)return!1;let o=this._prepareQueryParams({method:e,queryParams:i,sessionKey:t}),n=new window.Blob([o.toString()],{type:"application/x-www-form-urlencoded"});try{return window.navigator.sendBeacon(`${this.apiBaseUrl}/fb.do`,n)}catch(a){this.params.error$.next({id:"OneStat:ApiTransport:sendBeacon",category:y.ErrorCategory.NETWORK,message:"Unhandled beacon error",thrown:a,data:{method:e,params:i}})}return!1}sendRequest(e,i,t){return S(this,null,function*(){let o=(0,y.now)(),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:y.ErrorCategory.NETWORK,message:"Request failed",thrown:a});return}this.params.error$.next({id:"OneStat:ApiTransport:sendRequest",category:y.ErrorCategory.NETWORK,message:"Unhandled request error",thrown:a,data:{method:e,params:i,sessionKey:t,time:(0,y.now)()-o}})};return this.apiBaseUrl=yield this.resolveApiBaseUrl(),fetch(`${this.apiBaseUrl}/fb.do`,{method:"post",headers:{"Content-type":"application/x-www-form-urlencoded"},body:this._prepareQueryParams({method:e,queryParams:i,sessionKey:t})}).then(a=>{var m,g;let h=Number(a.headers.get("content-length"))===0,l=new Date((m=a.headers.get("date"))!=null?m:"").getTime(),p=(0,y.now)()-o;if(isFinite(l)&&((g=this.timeSynchronisation)==null||g.addServerTime(l,p)),!h)return a.json().then(s=>Object.prototype.hasOwnProperty.call(s,"error_msg")?Promise.reject(s):s,n)},n)})}_prepareQueryParams(e){let i=new URLSearchParams({format:"JSON",method:e.method,application_key:this.apiKey});return e.sessionKey!==void 0&&i.append("session_key",e.sessionKey),Object.entries(e.queryParams).forEach(([t,o])=>i.append(t,typeof o=="string"?o:JSON.stringify(o))),i}};var v=require("@vkontakte/videoplayer-shared");var M="onestat_events",Q=r=>e=>e.timestamp+r>=(0,v.now)(),B=class{constructor(e){this.unsaltedStorage=[];this.isPaused=!1;this.isUrgent=e=>{let{operation:i}=e;return["action_play","watch_coverage_record","watch_coverage_live"].includes(i)};this.params=e,this.api=e.api,this.error$=e.error$,this.userSalt=e.userSalt,this.loggerDebugLog=e.debugLogger.createComponentLog("stat logger"),this.firstFlush=(0,v.debounceFn)(()=>this.safeFlush(),this.params.config.firstFlushTime,{maxWait:this.params.config.firstFlushTime});let i=v.safeStorage.isPersistent()?this.params.config.flushMaxWait:0;this.debouncedFlush=(0,v.debounceFn)(()=>this.safeFlush(),this.params.config.flushDebounceTime,{maxWait:i}),this.subscription=this.api.authorized$.subscribe(t=>{t&&this.debouncedFlush()}),this.housekeepStorage()}safeFlush(){var e;try{this.flush()}catch(i){this.error$.next({id:"LoggerError",category:v.ErrorCategory.WTF,message:(e=String(i))!=null?e:"Unknown logger error",thrown:i})}}readFromStorage(){let e=v.safeStorage.get(M);try{return e?JSON.parse(e):{}}catch(i){}return{}}addToStorage(e){var n;if(!this.userSalt){this.unsaltedStorage.push(e);return}let i=this.readFromStorage(),o=((n=i[this.userSalt])!=null?n:[]).filter(Q(this.params.config.storageExpiration));v.safeStorage.set(M,JSON.stringify($(E({},i),{[this.userSalt]:[...o,e]})))}getFromStorage(){var t;return this.userSalt?((t=this.readFromStorage()[this.userSalt])!=null?t:[]).filter(Q(this.params.config.storageExpiration)):this.unsaltedStorage}markStorageSent(){if(!this.userSalt){this.unsaltedStorage=[];return}let e=this.readFromStorage();delete e[this.userSalt],v.safeStorage.set(M,JSON.stringify(e))}housekeepStorage(){let e=this.readFromStorage();for(let[i,t]of Object.entries(e)){let o=t.filter(Q(this.params.config.storageExpiration));o.length?e[i]=o:delete e[i],this.loggerDebugLog({message:`${t.length} retrieved from storage, ${o.length} of them actual`})}v.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){let i=this.getFromStorage();i.length!==0&&(this.api.authorized$.getValue()?(e&&this.params.config.useBeacon?(this.loggerDebugLog({message:`Flushing ${i.length} events through beacon`}),this.api.logBeacon(i)):(this.loggerDebugLog({message:`Flushing ${i.length} events`}),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()}};var u=require("@vkontakte/videoplayer-core"),j=require("@vkontakte/videoplayer-shared");var ce=r=>r&&{[u.VideoQuality.INVARIANT]:"unknown",[u.VideoQuality.Q_144P]:"mobile",[u.VideoQuality.Q_240P]:"lowest",[u.VideoQuality.Q_360P]:"low",[u.VideoQuality.Q_480P]:"medium",[u.VideoQuality.Q_720P]:"high",[u.VideoQuality.Q_1080P]:"fullhd",[u.VideoQuality.Q_1440P]:"quadhd",[u.VideoQuality.Q_2160P]:"ultrahd",[u.VideoQuality.Q_4320P]:"unknown"}[r],G=r=>r&&{[u.HttpConnectionType.HTTP1]:"http1",[u.HttpConnectionType.HTTP2]:"http2",[u.HttpConnectionType.QUIC]:"http3"}[r],le=r=>{if(r!==void 0)switch(r){case u.VideoFormat.MPEG:return"mp4";case u.VideoFormat.DASH:case u.VideoFormat.DASH_LIVE:case u.VideoFormat.DASH_STREAMS:return"dash";case u.VideoFormat.DASH_SEP:return"dash_sep";case u.VideoFormat.DASH_ONDEMAND:return"ondemand_dash";case u.VideoFormat.DASH_WEBM:case u.VideoFormat.DASH_LIVE_WEBM:return"webm";case u.VideoFormat.DASH_WEBM_AV1:return"av1";case u.VideoFormat.DASH_LIVE_CMAF:return"ondemand_dash_live";case u.VideoFormat.HLS:case u.VideoFormat.HLS_LIVE:return"hls";case u.VideoFormat.HLS_ONDEMAND:return"ondemand_hls";case u.VideoFormat.HLS_LIVE_CMAF:return"ondemand_hls_live";case u.VideoFormat.WEB_RTC_LIVE:return"webrtc";default:return(0,j.assertNever)(r)}},F=r=>{if(r!==void 0)switch(r){case u.Surface.NONE:case u.Surface.INLINE:return;case u.Surface.FULLSCREEN:return"fullscreen";case u.Surface.SECOND_SCREEN:return"chromecast";case u.Surface.PIP:return"pip";case u.Surface.INVISIBLE:return"invisible";default:return(0,j.assertNever)(r)}},pe=r=>{switch(r){case"slow-2g":return"poor";case"2g":return"poor";case"3g":return"good";case"4g":return"excellent"}};var V=class{constructor(e){this.offset=void 0;this.offset=e}getOffset(){var e;return(e=this.offset)!=null?e:0}setOffset(e){this.offset=e}now(){var e;return Date.now()+((e=this.offset)!=null?e:0)}date(e=new Date){var i;return e.setTime(e.getTime()+((i=this.offset)!=null?i:0)),e}addServerTime(e,i){let t=Date.now(),o=e-t-i/2;if(Math.abs(o)<1e3){this.offset=0;return}this.offset===void 0?this.offset=Math.round(o):this.offset=Math.round(.2*o+(1-.2)*this.offset)}};var he=()=>Math.floor(Math.random()*4294967296).toString(36).padStart(7,"0"),fe=()=>Math.floor(Math.random()*18446744073709552e3).toString(36).padStart(13,"0");var Y=require("@vkontakte/videoplayer-core"),f=require("@vkontakte/videoplayer-shared"),ge=(r,e)=>new f.Observable(i=>{let t=new f.Subscription,o=(0,f.merge)((0,f.fromEvent)(window,"beforeunload"),r.events.willDestruct$),n=new f.ValueSubject(void 0),a;t.add(r.info.isLive$.pipe((0,f.filterChanged)()).subscribe(A=>{a&&(a.unsubscribe(),n.next(void 0)),A?a=r.info.liveTime$.pipe((0,f.map)(H=>H&&H/1e3)).subscribe(n):a=r.info.position$.subscribe(n),t.add(a)}));let{playing$:h,paused$:l}=r.events,p=r.events.willSeek$.pipe((0,f.filter)(()=>r.info.playbackState$.getValue()===Y.PlaybackState.PLAYING)),m=r.events.seeked$.pipe((0,f.filter)(()=>r.info.playbackState$.getValue()===Y.PlaybackState.PLAYING)),g=!1,s=new f.Subject;t.add(p.subscribe(()=>{g||s.next(),g=!0})),t.add(m.subscribe(()=>g=!1));let c=new f.Subject,b=new f.Subject,P=(0,f.merge)(h,m,c),_=(0,f.merge)(l,s,o,r.events.looped$,b),x,me=()=>x=n.getValue(),be=()=>{let A=n.getValue();(0,f.isNullable)(x)||x===A||(0,f.isNullable)(A)||(i.next({from:x,to:A}),x=void 0)},ve=()=>{b.next(),c.next()};if(t.add(P.subscribe(me)),t.add(_.subscribe(be)),e.forceInterval&&isFinite(e.forceInterval)){let A=0;t.add(P.subscribe(()=>A=window.setTimeout(ve,e.forceInterval))),t.add(_.subscribe(()=>window.clearTimeout(A)))}return t});var we="_one-stat_",X=`${we}uuid`,J=()=>{let r=new d.Subscription;return{subscription:r,subscribe:(e,i)=>{e&&r.add(e.subscribe(i))}}},U=class{constructor(e,i){this.subscription=new d.Subscription;this.debugLogger=new W.Logger;this.oneStatDebugLog=this.debugLogger.createComponentLog("onestat");this.loopCounter=0;this.disabled=!1;this.vsid$=new d.ValueSubject(void 0);this.isid$=new d.ValueSubject(void 0);this.seekAction$=new d.ValueSubject("unknown");var l,p,m;this.statContext=e,this.config=ae((l=i.config)!=null?l:{}),(0,d.isNonNullable)(i.apiEnv)&&(this.config.apiEnv=i.apiEnv),this.config.synchronizeTime&&(this.timeSynchronisation=new V);let t=new d.Subject;this.experimental={error$:t};let o=d.safeStorage.get(X);o?o.startsWith('"')&&o.endsWith('"')?(this.uuid=o.replaceAll('"',""),d.safeStorage.set(X,this.uuid)):this.uuid=o:(this.uuid=q(),d.safeStorage.set(X,this.uuid)),this.resetViewSession(),i.useIsid&&this.isid$.next((p=i.isid)!=null?p:fe());let n=new k({apiKey:ue,config:this.config,error$:t,timeSynchronisation:this.timeSynchronisation});this.api=new w({config:this.config,apiTransport:n,refreshAuthToken:i.refreshAuthToken,mobile:(m=this.statContext.mobile)!=null?m:!1,uuid:this.uuid,error$:t}),this.logger=new B({config:this.config,debugLogger:this.debugLogger,api:this.api,error$:t,userSalt:i.userSalt});let{isEmbed:a,host:h}=(0,W.detectEmbed)();this.isEmbed=a,this.embedParent=h,this.subscribe()}updateContext(e){this.statContext=E(E({},this.statContext),e)}attachTo(e){let i=new d.Subscription,t=(s,c)=>i.add(s.subscribe(c));t(e.events.willStart$,()=>{let s=e.info.position$.getValue();this.logActionPlay({position:s}),this.statContext.projectId&&this.logActionPlayInteractive()}),t(e.events.looped$,()=>{this.resetViewSession(),++this.loopCounter>this.config.maxLoops&&(this.disabled=!0),this.logActionPlay({position:e.info.position$.getValue()})}),t(e.events.seeked$,()=>{this.logSeek({action:this.seekAction$.getValue(),time:e.info.position$.getValue()}),this.seekAction$.next("unknown")}),t(e.events.paused$,()=>{this.logPause({position:e.info.position$.getValue()})}),t(e.events.willResume$,()=>{this.logPlay()}),t(e.events.started$,()=>{this.statContext.clip&&this.logWatchCoverageRecord({start:0,end:0})}),t(e.events.playing$,()=>{this.logPlaying()}),t(ge(e,{forceInterval:this.config.watchCoverageInterval}),s=>{let c=e.info.isLive$.getValue(),b={start:parseFloat(s.from.toFixed(3)),end:parseFloat(s.to.toFixed(3))};c?this.logWatchCoverageLive(b):this.logWatchCoverageRecord(b)});let o;t(e.info.isStalled$,s=>{s?o=(0,d.now)():((0,d.isNonNullable)(o)&&this.logEmptyBuffer({duration:(0,d.now)()-o}),o=void 0)});let n=!1;i.add(e.events.fatalError$.pipe((0,d.once)()).subscribe(()=>n=!0)),t(e.events.willStop$,()=>{if(e.info.isStalled$.getValue()){let c=(0,d.isNonNullable)(o)?(0,d.now)()-o:void 0;this.logCloseAtEmptyBuffer({duration:c!=null?c:0}),o=void 0}else n||this.logActionStop()}),t(e.events.managedError$,({id:s})=>{this.logError({fatal:!1,errorType:s})}),t(e.events.fatalError$,({id:s})=>{this.logError({fatal:!0,errorType:s})});let a,h,l=!1;t(e.events.firstBytes$,s=>{a=(0,d.now)(),this.logFirstBytes({time:s})}),t(e.events.willStart$,()=>h=(0,d.now)()),t(e.info.currentBuffer$,s=>{!l&&s&&s.end-s.start>0&&(0,d.isNonNullable)(a)&&(this.logPlayerReady({duration:(0,d.now)()-a}),l=!0)}),t(e.events.firstFrame$,()=>{(0,d.isNonNullable)(a)&&!l&&(this.logPlayerReady({duration:(0,d.now)()-a}),l=!0),(0,d.isNonNullable)(h)&&this.logFirstFrame({time:(0,d.now)()-h})});let p;t(e.info.currentVideoStream$,s=>{s&&(p&&s.id!==p&&this.logTrackSwitch(s),p=s.id)});let m;t(e.info.currentAudioStream$,s=>{s&&(m&&s.id!==m&&this.logTrackSwitch(s),m=s.id)}),t(e.info.atLiveEdge$,s=>this.updateContext({liveEdge:s})),t((0,d.combine)({muted:e.info.muted$,volume:e.info.volume$}),({muted:s,volume:c})=>this.updateContext({audible:!s&&c>0})),t(e.info.currentQuality$,s=>this.updateContext({quality:ce(s)})),t(e.info.isAutoQualityEnabled$,s=>this.updateContext({autoQuality:s})),t(e.info.currentFormat$,s=>this.updateContext({contentType:le(s)})),t(e.info.currentPlaybackRate$,s=>this.updateContext({rate:s})),t(e.info.is3DVideo$,s=>this.updateContext({is3d:s}));let g;return t(e.info.hostname$,s=>{let c=g!==void 0&&g!==s;this.updateContext({cdnHostname:s,failover:c}),c&&this.logFailover(s),g=s}),t(e.info.throughputEstimation$,s=>this.updateContext({downloadSpeed:s})),t(e.info.httpConnectionType$,s=>{this.statContext.firstConnectionType||this.updateContext({firstConnectionType:G(s)}),this.updateContext({connectionType:G(s)})}),t(e.info.httpConnectionReused$,s=>{(0,d.isNullable)(this.statContext.firstConnectionReused)&&this.updateContext({firstConnectionReused:s}),this.updateContext({connectionReused:s})}),t(e.info.surface$,s=>this.updateContext({mode:F(s)})),t((0,d.combine)({current:e.info.currentTextTrack$,available:e.info.availableTextTracks$}),({current:s,available:c})=>{let b=c.find(({id:_})=>_===s),P=b&&(b.isAuto?`${b.language}_auto`:b.language);this.updateContext({subtitles:P})}),this.player=e,this.uiEvents&&this.attachToUi(this.uiEvents),this.resubscribeBeforeunload(),this.subscription.add(i),i}attachToUi(e){this.uiEvents=e;let{subscription:i,subscribe:t}=J();return this.player&&(t(e.actionRewind$,()=>{this.player&&(this.resetViewSession(),this.logActionPlay({position:this.player.info.position$.getValue()}))}),t(e.actionSeek$,this.seekAction$),t(e.inPiP$,o=>{var a;let n=o?"pip":F((a=this.player)==null?void 0:a.info.surface$.getValue());this.updateContext({mode:n})}),t(e.inFullscreen$,o=>{var a;let n=o?"fullscreen":F((a=this.player)==null?void 0:a.info.surface$.getValue());this.updateContext({mode:n})}),t(e.actionSetSubtitle$,o=>this.updateContext({subtitles:o})),t(e.nextMovie$,o=>this.logNextMovie(o)),this.resubscribeBeforeunload(),this.subscription.add(i)),i}attachToAds(e){let{subscription:i,subscribe:t}=J();return t(e.slotRequested$,()=>this.logAdSlotRequest()),t(e.started$,o=>this.logAdStarted(o)),t(e.paused$,()=>this.logAdPaused()),t(e.resumed$,()=>this.logAdResumed()),t(e.ended$,()=>this.logAdEnded()),t(e.skipped$,()=>this.logAdSkipped()),t(e.clicked$,()=>this.logAdClicked()),this.resubscribeBeforeunload(),this.subscription.add(i),i}attachToInteractive(e){let{subscription:i,subscribe:t}=J();return t(e.click$,o=>this.logInterfaceClick(o)),t(e.nextMovie$,o=>this.logNextMovie(o)),this.resubscribeBeforeunload(),this.subscription.add(i),i}authorize(e){return this.api.authorize(e)}pause(){this.logger.pause(),this.oneStatDebugLog({message:"paused"})}resume(){this.logger.resume(),this.oneStatDebugLog({message:"resumed"})}destroy(){this.logger.flush(),this.subscription.unsubscribe(),this.api.destroy(),this.logger.destroy()}resetViewSession(){this.oneStatDebugLog({message:"VSID reset"}),this.vsid$.next(he())}getDeviceId(){return this.uuid}setFieldBlacklist(){}logInited(){}logReady(e){this.log({operation:"player_ready",param:String(e.time)})}logStarted(...e){this.logActionPlay(...e)}logPlay(){this.log({operation:"play_toggle"})}logPlaying(){this.log({operation:"playing"})}logPause(e){this.log({operation:"pause",param:String(Math.round(e.position))})}logSeek(e){this.log({operation:"seek",param:e.action,time:e.time})}logFirstBytes(e){this.log({operation:"first_bytes",param:String(e.time)})}logFirstFrame(e){this.log({operation:"first_frame",param:String(e.time)})}logError(e){this.log({operation:"content_error",param:`${e.fatal?"fatal":"recoverable"}_${e.errorType}`})}logWatchCoverageRecord(e){this.log({operation:"watch_coverage_record",param:`${e.start}-${e.end}`})}logWatchCoverageLive(e){var n,a;let i=(a=(n=this.timeSynchronisation)==null?void 0:n.getOffset())!=null?a:0,t=e.start+i,o=e.end+i;this.log({operation:"watch_coverage_live",param:`${t}-${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();let e=window.navigator.connection;e&&"onchange"in e&&"effectiveType"in e&&this.subscription.add((0,d.merge)((0,d.fromEvent)(e,"change"),(0,d.observableFrom)(["init"])).subscribe(()=>this.updateContext({network:pe(e.effectiveType)}))),this.config.debugLog&&this.debugLogger.log$.subscribe(i=>{console.debug("%c stat ","background:#fa6470;",`component: ${i.component}.`,i.message)})}resubscribeBeforeunload(){var e;(e=this.beforeunloadSubscription)==null||e.unsubscribe(),this.beforeunloadSubscription=(0,d.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))})}logActionPlayInteractive(){this.statContext.projectId&&this.log({operation:"action_play_interactive",param:String(this.statContext.movieId)},{vid:this.statContext.projectId})}logFailover(e){this.log({operation:"failover",param:e})}logCloseAtEmptyBuffer(e){this.log({operation:"close_at_empty_buffer",param:String(Math.round(e.duration))})}logActionStop(){this.log({operation:"action_stop"})}logTrackSwitch(e){this.log({operation:"track_switch",param:e.id})}log(e,i={}){if(this.disabled){this.oneStatDebugLog({message:`operation ${e.operation} but statistics is disabled`});return}if(this.config.disabledOperations.includes(e.operation)){this.oneStatDebugLog({message:`operation ${e.operation} but it is disabled`});return}this.oneStatDebugLog({message:`operation ${e.operation} ${e.param}`});let t=this.createLogItem(e,i);this.logger.log(t)}createLogItem({operation:e,param:i,time:t},o={}){var c,b;let n=(b=(c=this.timeSynchronisation)==null?void 0:c.now())!=null?b:(0,d.now)(),a=this.vsid$.getValue();(0,d.assertNonNullable)(a);let h=this.isid$.getValue(),l=e==="empty_buffer"||e==="close_at_empty_buffer"?this.statContext.connectionType:this.statContext.firstConnectionType,p=this.statContext.firstConnectionReused,m,g;if(this.isEmbed){m=this.embedParent;let P=[...new URLSearchParams(location.search).entries()].filter(([_,x])=>this.config.embedUrlParams.includes(_));g=new URLSearchParams(P).toString()}else this.statContext.place==="direct"&&((this.statContext.refDomain||document.referrer)&&(m=new URL(this.statContext.refDomain||document.referrer).hostname),g=location.href.substring(0,1024));let s=E({vsid:a,isid:h,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?"auto":this.statContext.autoplay===!1?"":void 0,param:i,vk_app_id:this.statContext.vkAppId,track_code:this.statContext.trackCode,connection_type:l,connection_reused:p===!0?1:p===!1?0:void 0,cached_data:this.statContext.cached===!0?1:this.statContext.cached===!1?0:void 0,live:this.statContext.liveEdge?1:void 0,muted:this.statContext.audible===!1?1:void 0,mode:this.statContext.mode,subtitles:this.statContext.subtitles,download_speed:this.statContext.downloadSpeed,manual_quality:this.statContext.autoQuality?void 0:1,ref_domain:m,direct_url:g,rate:this.statContext.rate===1||(0,d.isNullable)(this.statContext.rate)?void 0:this.statContext.rate.toFixed(2),view_360:this.statContext.is3d?1:void 0,aid:this.statContext.albumId,vk_playlist_id:this.statContext.vkPlaylistId},o);for(let P of this.config.disabledCustomFields)delete s[P];return{operation:e,type:1,time:t,network:this.statContext.network,timestamp:n,custom:s}}};
package/es2015.esm.js CHANGED
@@ -1,6 +1,6 @@
1
1
  /**
2
- * @vkontakte/videoplayer-statistics v1.0.52-dev.22c05d5f.0
3
- * Tue, 30 Jul 2024 08:28:10 GMT
2
+ * @vkontakte/videoplayer-statistics v1.0.52-dev.a5f6699f.0
3
+ * Tue, 30 Jul 2024 10:43:01 GMT
4
4
  * https://st.mycdn.me/static/vkontakte-videoplayer/1-0-52/doc/
5
5
  */
6
- var ke=Object.defineProperty,Le=Object.defineProperties;var $e=Object.getOwnPropertyDescriptors;var oe=Object.getOwnPropertySymbols;var Re=Object.prototype.hasOwnProperty,Oe=Object.prototype.propertyIsEnumerable;var se=(r,e,i)=>e in r?ke(r,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):r[e]=i,y=(r,e)=>{for(var i in e||(e={}))Re.call(e,i)&&se(r,i,e[i]);if(oe)for(var i of oe(e))Oe.call(e,i)&&se(r,i,e[i]);return r},L=(r,e)=>Le(r,$e(e));var m=(r,e,i)=>new Promise((t,o)=>{var n=u=>{try{l(i.next(u))}catch(c){o(c)}},a=u=>{try{l(i.throw(u))}catch(c){o(c)}},l=u=>u.done?t(u.value):Promise.resolve(u.value).then(n,a);l((i=i.apply(r,e)).next())});var C=(n=>(n.PROD="prod",n.VK_ALIAS="vk_alias",n.VIDEOTEST="videotest",n.TEST="test",n.AUTO="auto",n))(C||{}),F=(c=>(c.Q144P="mobile",c.Q240P="lowest",c.Q360P="low",c.Q480P="medium",c.Q720P="high",c.Q1080P="fullhd",c.Q1440P="quadhd",c.Q2160P="ultrahd",c.UNKNOWN="unknown",c))(F||{}),V=(d=>(d.MP4="mp4",d.DASH="dash",d.DASH_SEP="dash_sep",d.ONDEMAND_DASH="ondemand_dash",d.HLS="hls",d.ONDEMAND_HLS="ondemand_hls",d.WEBM="webm",d.AV1="av1",d.ONDEMAND_DASH_LIVE="ondemand_dash_live",d.ONDEMAND_HLS_LIVE="ondemand_hls_live",d.WEBRTC="webrtc",d.UNKNOWN="unknown",d.RTMP="rtmp",d))(V||{});var U=(t=>(t.HTTP1="http1",t.HTTP2="http2",t.HTTP3="http3",t))(U||{});var W=(l=>(l.SLIDER="slider",l.DOUBLE_TAP="double_tap",l.TIME_CODE="time_code",l.EPISODE="episode",l.REWIND="rewind",l.LIVE="live",l.UNKNOWN="unknown",l))(W||{}),re=(n=>(n.GRAPH_SHOW="iGraphShow",n.GRAPH_HIDE="iGraphHide",n.NEXT_AREA="iNextChapterArea",n.NEXT_BUTTON="iNextChapterBtn",n.WATCH_AGAIN="iWatchAgainBtn",n))(re||{}),ne={action_play:"ap",action_play_interactive:"api",first_bytes:"fb",player_ready:"pr",first_frame:"ff",seek:"sk",watch_coverage_record:"wr",watch_coverage_live:"wl",empty_buffer:"eb",action_stop:"as",close_at_empty_buffer:"cb",content_error:"er",player_interface_click:"pc",next_movie:"nm",track_switch:"ts",failover:"fo"},ae={vsid:"si",isid:"is",vid:"vi",place:"pl",quality:"qt",cdn_host:"ch",stat_type:"st",param:"pm",vk_app_id:"va",track_code:"tc",connection_type:"cnt",connection_reused:"cr",cached_data:"cd",live:"lv",muted:"mu",mode:"mo",subtitles:"sb",failover:"fo",download_speed:"ds",manual_quality:"mq",ref_domain:"rd",direct_url:"du"},de={unknown:"un",mobile:"m",lowest:"ls",low:"l",medium:"md",high:"h",fullhd:"f",quadhd:"q",ultrahd:"u"},ue={pip:"pi",fullscreen:"fs",external:"ex",prefetch:"pr",airplay:"ap",chromecast:"cc",invisible:"iv"};import{fillWithDefault as Ne}from"@vkontakte/videoplayer-shared";var De={apiEnv:"vk_alias",requestRetryCount:1,firstFlushTime:5e3,flushDebounceTime:1e4,flushMaxWait:6e4,storageExpiration:36*60*60*1e3,watchCoverageInterval:15e3,disabledOperations:[],disabledCustomFields:[],shorten:!0,maxLoops:100,embedUrlParams:[],useBeacon:!0,synchronizeTime:!0,debugLog:!1,backoff:{start:1e3,factor:1.5,max:5*60*1e3,random:.1}},ce=r=>Ne(r,De);function H(){let r="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".split(""),e=new Array(36),i=0,t,o;for(o=0;o<36;o++)o===8||o===13||o===18||o===23?e[o]="-":o===14?e[o]="4":(i<=2&&(i=33554432+Math.random()*16777216|0),t=i&15,i=i>>4,e[o]=r[o===19?t&3|8:t]);return e.join("")}import{assertNonNullable as je,combine as Ee,fromEvent as _e,isNonNullable as x,isNullable as xe,merge as Ge,now as v,observableFrom as Ye,once as Xe,safeStorage as X,Subject as Je,Subscription as te,ValueSubject as J}from"@vkontakte/videoplayer-shared";import{Logger as Ze,detectEmbed as et}from"@vkontakte/videoplayer-shared";var le=r=>{var o;let{operation:e,custom:i}=r,t=Object.fromEntries(Object.entries(i).map(([n,a])=>{var c,h,p;let l=(c=ae[n])!=null?c:n,u=a;return a&&(n==="mode"?u=(h=ue[a])!=null?h:a:n==="quality"&&(u=(p=de[a])!=null?p:a)),[l,u]}));return L(y({},r),{operation:(o=ne[e])!=null?o:e,custom:t})};var $="1.0.52-dev.22c05d5f.0",pe="CIOPGQJGDIHBABABA",K={prod:"https://api.ok.ru",vk_alias:"https://api.mycdn.me",videotest:"https://videotestapi.ok.ru/api",test:"https://apitest.ok.ru",auto:""};import{ValueSubject as Me,getExponentialDelay as Be,ErrorCategory as E}from"@vkontakte/videoplayer-shared";var T=class{constructor(e){this.consequentAuthErrors=0;this.authorized$=new Me(!1);this.params=e}authorize(e){return m(this,null,function*(){return this.authToken=e!=null?e:yield this.refreshAuthToken(),this._authorizeWithBackoff()})}logBeacon(e){let i="log.externalLog",t=this.createLogParams(e),o=this.sessionKey;if(!o)return;this.params.apiTransport.sendBeacon(i,t,o)||this.logRequest(e)}logRequest(e){return m(this,null,function*(){var a;let i="log.externalLog",t=this.createLogParams(e),o=(a=this.sessionKey)!=null?a:yield this._authorizeWithBackoff();if(!o)return;let n=(c,...h)=>m(this,[c,...h],function*(l,u=this.params.config.requestRetryCount){try{return yield this.params.apiTransport.sendRequest(i,t,o)}catch(p){if(!p||!("error_code"in p)){this.params.error$.next({id:"logRequestUnknown",category:E.NETWORK,message:`Unknown ${i} error`,thrown:p});return}let s=p==null?void 0:p.error_code;switch(s){case 102:case 103:case 104:return this.authorized$.next(!1),this.sessionKey=yield this._authorizeWithBackoff(),u>0?n(l,u-1):void 0;case 401:return this.authorized$.next(!1),this.authToken=yield this.refreshAuthToken(),this.sessionKey=yield this._authorizeWithBackoff(),u>0?n(l,u-1):void 0;default:{this.params.error$.next({id:`LogRequest#${s}`,category:E.EXTERNAL_API,message:`${i} error`,data:p});return}}}});return n(e)})}destroy(){window.clearTimeout(this.backoffTimeoutId),this.backoffTimeoutId=0}refreshAuthToken(){return m(this,null,function*(){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:${$}`,platform:this.params.mobile?"M_WEB":"WEB",items:this.params.config.shorten?e.map(le):e})}}_authorizeWithBackoff(){if(!this.consequentAuthErrors)return this._authorize();let e=Be(this.consequentAuthErrors,this.params.config.backoff);return new Promise(i=>{this.backoffTimeoutId||(this.backoffTimeoutId=window.setTimeout(()=>{this._authorize().then(i).catch(t=>this.params.error$.next({id:"AuthorizeBackoff",category:E.NETWORK,message:"Otherwise unhandled error in authorization",thrown:t})).finally(()=>this.backoffTimeoutId=0)},e))})}_authorize(){return m(this,null,function*(){if(this.authorizePromise)return this.authorizePromise;this.sessionKey=void 0,this.authorized$.next(!1);let e="auth.anonymLogin",i={session_data:{version:2,device_id:this.params.uuid,client_version:$.split("-")[0],client_type:"SDK_JS"}};return this.authToken!==void 0&&(i.session_data.auth_token=this.authToken,i.session_data.version=3),this.authorizePromise=this.params.apiTransport.sendRequest(e,i).then(t=>{var o;return(!t||!t.session_key)&&this.params.error$.next({id:"AuthorizeFailed",category:E.EXTERNAL_API,message:"No session key",data:t}),this.sessionKey=(o=t==null?void 0:t.session_key)!=null?o:void 0,this.sessionKey}).catch(t=>m(this,null,function*(){this.sessionKey=void 0;let o=t==null?void 0:t.error_code;switch(o){case 401:return this.authToken=yield this.refreshAuthToken(),this._authorizeWithBackoff()}o?this.params.error$.next({id:`Authorize#${o}`,category:E.EXTERNAL_API,message:"authorize error",data:t}):this.params.error$.next({id:"AuthorizeUnknown",category:E.NETWORK,message:"authorize error",thrown:t})})).finally(()=>{this.authorizePromise=void 0,this.consequentAuthErrors=this.sessionKey?0:this.consequentAuthErrors+1,this.authorized$.next(this.sessionKey!==void 0)}),this.authorizePromise})}};import{ErrorCategory as R,now as q}from"@vkontakte/videoplayer-shared";var w=class{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}resolveApiBaseUrl(){return m(this,null,function*(){var e;if(this.apiEnv!=="auto"||this.isApiBaseUrlFetched)return this.apiBaseUrl;try{let i=atob("aHR0cHM6Ly9kbnMuZ29vZ2xlL3Jlc29sdmU/bmFtZT12aWRlby5fZW5kcG9pbnQub2sucnUmdHlwZT1UWFQ="),o=yield(yield fetch(i,{method:"GET",mode:"cors",cache:"no-cache"})).json(),n=(e=o==null?void 0:o.Answer[0])==null?void 0:e.data;if(!n)throw new Error("Wrong DNS response");return n}catch(i){return this.params.error$.next({id:"OneStat:ApiTransport:resolveApiBaseUrl",category:R.NETWORK,message:"Unhandled resolve api base url error",thrown:i}),K.vk_alias}finally{this.isApiBaseUrlFetched=!0}})}sendBeacon(e,i,t){if(!window.Blob||!window.navigator.sendBeacon)return!1;let o=this._prepareQueryParams({method:e,queryParams:i,sessionKey:t}),n=new window.Blob([o.toString()],{type:"application/x-www-form-urlencoded"});try{return window.navigator.sendBeacon(`${this.apiBaseUrl}/fb.do`,n)}catch(a){this.params.error$.next({id:"OneStat:ApiTransport:sendBeacon",category:R.NETWORK,message:"Unhandled beacon error",thrown:a,data:{method:e,params:i}})}return!1}sendRequest(e,i,t){return m(this,null,function*(){let o=q(),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:R.NETWORK,message:"Request failed",thrown:a});return}this.params.error$.next({id:"OneStat:ApiTransport:sendRequest",category:R.NETWORK,message:"Unhandled request error",thrown:a,data:{method:e,params:i,sessionKey:t,time:q()-o}})};return this.apiBaseUrl=yield this.resolveApiBaseUrl(),fetch(`${this.apiBaseUrl}/fb.do`,{method:"post",headers:{"Content-type":"application/x-www-form-urlencoded"},body:this._prepareQueryParams({method:e,queryParams:i,sessionKey:t})}).then(a=>{var h,p;let l=Number(a.headers.get("content-length"))===0,u=new Date((h=a.headers.get("date"))!=null?h:"").getTime(),c=q()-o;if(isFinite(u)&&((p=this.timeSynchronisation)==null||p.addServerTime(u,c)),!l)return a.json().then(s=>Object.prototype.hasOwnProperty.call(s,"error_msg")?Promise.reject(s):s,n)},n)})}_prepareQueryParams(e){let i=new URLSearchParams({format:"JSON",method:e.method,application_key:this.apiKey});return e.sessionKey!==void 0&&i.append("session_key",e.sessionKey),Object.entries(e.queryParams).forEach(([t,o])=>i.append(t,typeof o=="string"?o:JSON.stringify(o))),i}};import{ErrorCategory as Fe,now as Ve,safeStorage as k,debounceFn as he}from"@vkontakte/videoplayer-shared";var O="onestat_events",z=r=>e=>e.timestamp+r>=Ve(),N=class{constructor(e){this.unsaltedStorage=[];this.isPaused=!1;this.isUrgent=e=>{let{operation:i}=e;return["action_play","watch_coverage_record","watch_coverage_live"].includes(i)};this.params=e,this.api=e.api,this.error$=e.error$,this.userSalt=e.userSalt,this.loggerDebugLog=e.debugLogger.createComponentLog("stat logger"),this.firstFlush=he(()=>this.safeFlush(),this.params.config.firstFlushTime,{maxWait:this.params.config.firstFlushTime});let i=k.isPersistent()?this.params.config.flushMaxWait:0;this.debouncedFlush=he(()=>this.safeFlush(),this.params.config.flushDebounceTime,{maxWait:i}),this.subscription=this.api.authorized$.subscribe(t=>{t&&this.debouncedFlush()}),this.housekeepStorage()}safeFlush(){var e;try{this.flush()}catch(i){this.error$.next({id:"LoggerError",category:Fe.WTF,message:(e=String(i))!=null?e:"Unknown logger error",thrown:i})}}readFromStorage(){let e=k.get(O);try{return e?JSON.parse(e):{}}catch(i){}return{}}addToStorage(e){var n;if(!this.userSalt){this.unsaltedStorage.push(e);return}let i=this.readFromStorage(),o=((n=i[this.userSalt])!=null?n:[]).filter(z(this.params.config.storageExpiration));k.set(O,JSON.stringify(L(y({},i),{[this.userSalt]:[...o,e]})))}getFromStorage(){var t;return this.userSalt?((t=this.readFromStorage()[this.userSalt])!=null?t:[]).filter(z(this.params.config.storageExpiration)):this.unsaltedStorage}markStorageSent(){if(!this.userSalt){this.unsaltedStorage=[];return}let e=this.readFromStorage();delete e[this.userSalt],k.set(O,JSON.stringify(e))}housekeepStorage(){let e=this.readFromStorage();for(let[i,t]of Object.entries(e)){let o=t.filter(z(this.params.config.storageExpiration));o.length?e[i]=o:delete e[i],this.loggerDebugLog({message:`${t.length} retrieved from storage, ${o.length} of them actual`})}k.set(O,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){let i=this.getFromStorage();i.length!==0&&(this.api.authorized$.getValue()?(e&&this.params.config.useBeacon?(this.loggerDebugLog({message:`Flushing ${i.length} events through beacon`}),this.api.logBeacon(i)):(this.loggerDebugLog({message:`Flushing ${i.length} events`}),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()}};import{HttpConnectionType as Q,Surface as _,VideoFormat as f,VideoQuality as b}from"@vkontakte/videoplayer-core";import{assertNever as fe}from"@vkontakte/videoplayer-shared";var ge=r=>r&&{[b.INVARIANT]:"unknown",[b.Q_144P]:"mobile",[b.Q_240P]:"lowest",[b.Q_360P]:"low",[b.Q_480P]:"medium",[b.Q_720P]:"high",[b.Q_1080P]:"fullhd",[b.Q_1440P]:"quadhd",[b.Q_2160P]:"ultrahd",[b.Q_4320P]:"unknown"}[r],j=r=>r&&{[Q.HTTP1]:"http1",[Q.HTTP2]:"http2",[Q.QUIC]:"http3"}[r],me=r=>{if(r!==void 0)switch(r){case f.MPEG:return"mp4";case f.DASH:case f.DASH_LIVE:case f.DASH_STREAMS:return"dash";case f.DASH_SEP:return"dash_sep";case f.DASH_ONDEMAND:return"ondemand_dash";case f.DASH_WEBM:case f.DASH_LIVE_WEBM:return"webm";case f.DASH_WEBM_AV1:return"av1";case f.DASH_LIVE_CMAF:return"ondemand_dash_live";case f.HLS:case f.HLS_LIVE:return"hls";case f.HLS_ONDEMAND:return"ondemand_hls";case f.HLS_LIVE_CMAF:return"ondemand_hls_live";case f.WEB_RTC_LIVE:return"webrtc";default:return fe(r)}},D=r=>{if(r!==void 0)switch(r){case _.NONE:case _.INLINE:return;case _.FULLSCREEN:return"fullscreen";case _.SECOND_SCREEN:return"chromecast";case _.PIP:return"pip";case _.INVISIBLE:return"invisible";default:return fe(r)}},be=r=>{switch(r){case"slow-2g":return"poor";case"2g":return"poor";case"3g":return"good";case"4g":return"excellent"}};var M=class{constructor(e){this.offset=void 0;this.offset=e}getOffset(){var e;return(e=this.offset)!=null?e:0}setOffset(e){this.offset=e}now(){var e;return Date.now()+((e=this.offset)!=null?e:0)}date(e=new Date){var i;return e.setTime(e.getTime()+((i=this.offset)!=null?i:0)),e}addServerTime(e,i){let t=Date.now(),o=e-t-i/2;if(Math.abs(o)<1e3){this.offset=0;return}this.offset===void 0?this.offset=Math.round(o):this.offset=Math.round(.2*o+(1-.2)*this.offset)}};var ve=()=>Math.floor(Math.random()*4294967296).toString(36).padStart(7,"0"),Ie=()=>Math.floor(Math.random()*18446744073709552e3).toString(36).padStart(13,"0");import{PlaybackState as Se}from"@vkontakte/videoplayer-core";import{filter as ye,filterChanged as We,fromEvent as He,isNullable as Pe,map as Ke,merge as G,Observable as qe,Subject as Y,Subscription as ze,ValueSubject as Qe}from"@vkontakte/videoplayer-shared";var Ae=(r,e)=>new qe(i=>{let t=new ze,o=G(He(window,"beforeunload"),r.events.willDestruct$),n=new Qe(void 0),a;t.add(r.info.isLive$.pipe(We()).subscribe(S=>{a&&(a.unsubscribe(),n.next(void 0)),S?a=r.info.liveTime$.pipe(Ke(B=>B&&B/1e3)).subscribe(n):a=r.info.position$.subscribe(n),t.add(a)}));let{playing$:l,paused$:u}=r.events,c=r.events.willSeek$.pipe(ye(()=>r.info.playbackState$.getValue()===Se.PLAYING)),h=r.events.seeked$.pipe(ye(()=>r.info.playbackState$.getValue()===Se.PLAYING)),p=!1,s=new Y;t.add(c.subscribe(()=>{p||s.next(),p=!0})),t.add(h.subscribe(()=>p=!1));let d=new Y,g=new Y,I=G(l,h,d),P=G(u,s,o,r.events.looped$,g),A,Ce=()=>A=n.getValue(),Te=()=>{let S=n.getValue();Pe(A)||A===S||Pe(S)||(i.next({from:A,to:S}),A=void 0)},we=()=>{g.next(),d.next()};if(t.add(I.subscribe(Ce)),t.add(P.subscribe(Te)),e.forceInterval&&isFinite(e.forceInterval)){let S=0;t.add(I.subscribe(()=>S=window.setTimeout(we,e.forceInterval))),t.add(P.subscribe(()=>window.clearTimeout(S)))}return t});var tt="_one-stat_",Z=`${tt}uuid`,ee=()=>{let r=new te;return{subscription:r,subscribe:(e,i)=>{e&&r.add(e.subscribe(i))}}},ie=class{constructor(e,i){this.subscription=new te;this.debugLogger=new Ze;this.oneStatDebugLog=this.debugLogger.createComponentLog("onestat");this.loopCounter=0;this.disabled=!1;this.vsid$=new J(void 0);this.isid$=new J(void 0);this.seekAction$=new J("unknown");var u,c,h;this.statContext=e,this.config=ce((u=i.config)!=null?u:{}),x(i.apiEnv)&&(this.config.apiEnv=i.apiEnv),this.config.synchronizeTime&&(this.timeSynchronisation=new M);let t=new Je;this.experimental={error$:t};let o=X.get(Z);o?o.startsWith('"')&&o.endsWith('"')?(this.uuid=o.replaceAll('"',""),X.set(Z,this.uuid)):this.uuid=o:(this.uuid=H(),X.set(Z,this.uuid)),this.resetViewSession(),i.useIsid&&this.isid$.next((c=i.isid)!=null?c:Ie());let n=new w({apiKey:pe,config:this.config,error$:t,timeSynchronisation:this.timeSynchronisation});this.api=new T({config:this.config,apiTransport:n,refreshAuthToken:i.refreshAuthToken,mobile:(h=this.statContext.mobile)!=null?h:!1,uuid:this.uuid,error$:t}),this.logger=new N({config:this.config,debugLogger:this.debugLogger,api:this.api,error$:t,userSalt:i.userSalt});let{isEmbed:a,host:l}=et();this.isEmbed=a,this.embedParent=l,this.subscribe()}updateContext(e){this.statContext=y(y({},this.statContext),e)}attachTo(e){let i=new te,t=(s,d)=>i.add(s.subscribe(d));t(e.events.willStart$,()=>{let s=e.info.position$.getValue();this.logActionPlay({position:s}),this.statContext.projectId&&this.logActionPlayInteractive()}),t(e.events.looped$,()=>{this.resetViewSession(),++this.loopCounter>this.config.maxLoops&&(this.disabled=!0),this.logActionPlay({position:e.info.position$.getValue()})}),t(e.events.seeked$,()=>{this.logSeek({action:this.seekAction$.getValue(),time:e.info.position$.getValue()}),this.seekAction$.next("unknown")}),t(e.events.paused$,()=>{this.logPause({position:e.info.position$.getValue()})}),t(e.events.willResume$,()=>{this.logPlay()}),t(e.events.started$,()=>{this.statContext.clip&&this.logWatchCoverageRecord({start:0,end:0})}),t(e.events.playing$,()=>{this.logPlaying()}),t(Ae(e,{forceInterval:this.config.watchCoverageInterval}),s=>{let d=e.info.isLive$.getValue(),g={start:parseFloat(s.from.toFixed(3)),end:parseFloat(s.to.toFixed(3))};d?this.logWatchCoverageLive(g):this.logWatchCoverageRecord(g)});let o;t(e.info.isStalled$,s=>{s?o=v():(x(o)&&this.logEmptyBuffer({duration:v()-o}),o=void 0)});let n=!1;i.add(e.events.fatalError$.pipe(Xe()).subscribe(()=>n=!0)),t(e.events.willStop$,()=>{if(e.info.isStalled$.getValue()){let d=x(o)?v()-o:void 0;this.logCloseAtEmptyBuffer({duration:d!=null?d:0}),o=void 0}else n||this.logActionStop()}),t(e.events.managedError$,({id:s})=>{this.logError({fatal:!1,errorType:s})}),t(e.events.fatalError$,({id:s})=>{this.logError({fatal:!0,errorType:s})});let a,l,u=!1;t(e.events.firstBytes$,s=>{a=v(),this.logFirstBytes({time:s})}),t(e.events.willStart$,()=>l=v()),t(e.info.currentBuffer$,s=>{!u&&s&&s.end-s.start>0&&x(a)&&(this.logPlayerReady({duration:v()-a}),u=!0)}),t(e.events.firstFrame$,()=>{x(a)&&!u&&(this.logPlayerReady({duration:v()-a}),u=!0),x(l)&&this.logFirstFrame({time:v()-l})});let c;t(e.info.currentVideoStream$,s=>{s&&(c&&s.id!==c&&this.logTrackSwitch(s),c=s.id)});let h;t(e.info.currentAudioStream$,s=>{s&&(h&&s.id!==h&&this.logTrackSwitch(s),h=s.id)}),t(e.info.atLiveEdge$,s=>this.updateContext({liveEdge:s})),t(Ee({muted:e.info.muted$,volume:e.info.volume$}),({muted:s,volume:d})=>this.updateContext({audible:!s&&d>0})),t(e.info.currentQuality$,s=>this.updateContext({quality:ge(s)})),t(e.info.isAutoQualityEnabled$,s=>this.updateContext({autoQuality:s})),t(e.info.currentFormat$,s=>this.updateContext({contentType:me(s)})),t(e.info.currentPlaybackRate$,s=>this.updateContext({rate:s})),t(e.info.is3DVideo$,s=>this.updateContext({is3d:s}));let p;return t(e.info.hostname$,s=>{let d=p!==void 0&&p!==s;this.updateContext({cdnHostname:s,failover:d}),d&&this.logFailover(s),p=s}),t(e.info.throughputEstimation$,s=>this.updateContext({downloadSpeed:s})),t(e.info.httpConnectionType$,s=>{this.statContext.firstConnectionType||this.updateContext({firstConnectionType:j(s)}),this.updateContext({connectionType:j(s)})}),t(e.info.httpConnectionReused$,s=>{xe(this.statContext.firstConnectionReused)&&this.updateContext({firstConnectionReused:s}),this.updateContext({connectionReused:s})}),t(e.info.surface$,s=>this.updateContext({mode:D(s)})),t(Ee({current:e.info.currentTextTrack$,available:e.info.availableTextTracks$}),({current:s,available:d})=>{let g=d.find(({id:P})=>P===s),I=g&&(g.isAuto?`${g.language}_auto`:g.language);this.updateContext({subtitles:I})}),this.player=e,this.uiEvents&&this.attachToUi(this.uiEvents),this.resubscribeBeforeunload(),this.subscription.add(i),i}attachToUi(e){this.uiEvents=e;let{subscription:i,subscribe:t}=ee();return this.player&&(t(e.actionRewind$,()=>{this.player&&(this.resetViewSession(),this.logActionPlay({position:this.player.info.position$.getValue()}))}),t(e.actionSeek$,this.seekAction$),t(e.inPiP$,o=>{var a;let n=o?"pip":D((a=this.player)==null?void 0:a.info.surface$.getValue());this.updateContext({mode:n})}),t(e.inFullscreen$,o=>{var a;let n=o?"fullscreen":D((a=this.player)==null?void 0:a.info.surface$.getValue());this.updateContext({mode:n})}),t(e.actionSetSubtitle$,o=>this.updateContext({subtitles:o})),t(e.nextMovie$,o=>this.logNextMovie(o)),this.resubscribeBeforeunload(),this.subscription.add(i)),i}attachToAds(e){let{subscription:i,subscribe:t}=ee();return t(e.slotRequested$,()=>this.logAdSlotRequest()),t(e.started$,o=>this.logAdStarted(o)),t(e.paused$,()=>this.logAdPaused()),t(e.resumed$,()=>this.logAdResumed()),t(e.ended$,()=>this.logAdEnded()),t(e.skipped$,()=>this.logAdSkipped()),t(e.clicked$,()=>this.logAdClicked()),this.resubscribeBeforeunload(),this.subscription.add(i),i}attachToInteractive(e){let{subscription:i,subscribe:t}=ee();return t(e.click$,o=>this.logInterfaceClick(o)),t(e.nextMovie$,o=>this.logNextMovie(o)),this.resubscribeBeforeunload(),this.subscription.add(i),i}authorize(e){return this.api.authorize(e)}pause(){this.logger.pause(),this.oneStatDebugLog({message:"paused"})}resume(){this.logger.resume(),this.oneStatDebugLog({message:"resumed"})}destroy(){this.logger.flush(),this.subscription.unsubscribe(),this.api.destroy(),this.logger.destroy()}resetViewSession(){this.oneStatDebugLog({message:"VSID reset"}),this.vsid$.next(ve())}getDeviceId(){return this.uuid}setFieldBlacklist(){}logInited(){}logReady(e){this.log({operation:"player_ready",param:String(e.time)})}logStarted(...e){this.logActionPlay(...e)}logPlay(){this.log({operation:"play_toggle"})}logPlaying(){this.log({operation:"playing"})}logPause(e){this.log({operation:"pause",param:String(Math.round(e.position))})}logSeek(e){this.log({operation:"seek",param:e.action,time:e.time})}logFirstBytes(e){this.log({operation:"first_bytes",param:String(e.time)})}logFirstFrame(e){this.log({operation:"first_frame",param:String(e.time)})}logError(e){this.log({operation:"content_error",param:`${e.fatal?"fatal":"recoverable"}_${e.errorType}`})}logWatchCoverageRecord(e){this.log({operation:"watch_coverage_record",param:`${e.start}-${e.end}`})}logWatchCoverageLive(e){var n,a;let i=(a=(n=this.timeSynchronisation)==null?void 0:n.getOffset())!=null?a:0,t=e.start+i,o=e.end+i;this.log({operation:"watch_coverage_live",param:`${t}-${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();let e=window.navigator.connection;e&&"onchange"in e&&"effectiveType"in e&&this.subscription.add(Ge(_e(e,"change"),Ye(["init"])).subscribe(()=>this.updateContext({network:be(e.effectiveType)}))),this.config.debugLog&&this.debugLogger.log$.subscribe(i=>{console.debug("%c stat ","background:#fa6470;",`component: ${i.component}.`,i.message)})}resubscribeBeforeunload(){var e;(e=this.beforeunloadSubscription)==null||e.unsubscribe(),this.beforeunloadSubscription=_e(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))})}logActionPlayInteractive(){this.statContext.projectId&&this.log({operation:"action_play_interactive",param:String(this.statContext.movieId)},{vid:this.statContext.projectId})}logFailover(e){this.log({operation:"failover",param:e})}logCloseAtEmptyBuffer(e){this.log({operation:"close_at_empty_buffer",param:String(Math.round(e.duration))})}logActionStop(){this.log({operation:"action_stop"})}logTrackSwitch(e){this.log({operation:"track_switch",param:e.id})}log(e,i={}){if(this.disabled){this.oneStatDebugLog({message:`operation ${e.operation} but statistics is disabled`});return}if(this.config.disabledOperations.includes(e.operation)){this.oneStatDebugLog({message:`operation ${e.operation} but it is disabled`});return}this.oneStatDebugLog({message:`operation ${e.operation} ${e.param}`});let t=this.createLogItem(e,i);this.logger.log(t)}createLogItem({operation:e,param:i,time:t},o={}){var d,g;let n=(g=(d=this.timeSynchronisation)==null?void 0:d.now())!=null?g:v(),a=this.vsid$.getValue();je(a);let l=this.isid$.getValue(),u=e==="empty_buffer"||e==="close_at_empty_buffer"?this.statContext.connectionType:this.statContext.firstConnectionType,c=this.statContext.firstConnectionReused,h,p;if(this.isEmbed){h=this.embedParent;let I=[...new URLSearchParams(location.search).entries()].filter(([P,A])=>this.config.embedUrlParams.includes(P));p=new URLSearchParams(I).toString()}else this.statContext.place==="direct"&&((this.statContext.refDomain||document.referrer)&&(h=new URL(this.statContext.refDomain||document.referrer).hostname),p=location.href.substring(0,1024));let s=y({vsid:a,isid:l,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?"auto":this.statContext.autoplay===!1?"":void 0,param:i,vk_app_id:this.statContext.vkAppId,track_code:this.statContext.trackCode,connection_type:u,connection_reused:c===!0?1:c===!1?0:void 0,cached_data:this.statContext.cached===!0?1:this.statContext.cached===!1?0:void 0,live:this.statContext.liveEdge?1:void 0,muted:this.statContext.audible===!1?1:void 0,mode:this.statContext.mode,subtitles:this.statContext.subtitles,download_speed:this.statContext.downloadSpeed,manual_quality:this.statContext.autoQuality?void 0:1,ref_domain:h,direct_url:p,rate:this.statContext.rate===1||xe(this.statContext.rate)?void 0:this.statContext.rate.toFixed(2),view_360:this.statContext.is3d?1:void 0,aid:this.statContext.albumId,vk_playlist_id:this.statContext.vkPlaylistId},o);for(let I of this.config.disabledCustomFields)delete s[I];return{operation:e,type:1,time:t,network:this.statContext.network,timestamp:n,custom:s}}};export{C as ApiEnv,U as ConnectionType,V as ContentType,re as InteractiveInterfaceClick,ie as OneStat,F as Quality,W as SeekAction,$ as VERSION};
6
+ var ke=Object.defineProperty,Le=Object.defineProperties;var $e=Object.getOwnPropertyDescriptors;var oe=Object.getOwnPropertySymbols;var Re=Object.prototype.hasOwnProperty,Oe=Object.prototype.propertyIsEnumerable;var se=(r,e,i)=>e in r?ke(r,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):r[e]=i,y=(r,e)=>{for(var i in e||(e={}))Re.call(e,i)&&se(r,i,e[i]);if(oe)for(var i of oe(e))Oe.call(e,i)&&se(r,i,e[i]);return r},L=(r,e)=>Le(r,$e(e));var m=(r,e,i)=>new Promise((t,o)=>{var n=u=>{try{l(i.next(u))}catch(c){o(c)}},a=u=>{try{l(i.throw(u))}catch(c){o(c)}},l=u=>u.done?t(u.value):Promise.resolve(u.value).then(n,a);l((i=i.apply(r,e)).next())});var C=(n=>(n.PROD="prod",n.VK_ALIAS="vk_alias",n.VIDEOTEST="videotest",n.TEST="test",n.AUTO="auto",n))(C||{}),F=(c=>(c.Q144P="mobile",c.Q240P="lowest",c.Q360P="low",c.Q480P="medium",c.Q720P="high",c.Q1080P="fullhd",c.Q1440P="quadhd",c.Q2160P="ultrahd",c.UNKNOWN="unknown",c))(F||{}),V=(d=>(d.MP4="mp4",d.DASH="dash",d.DASH_SEP="dash_sep",d.ONDEMAND_DASH="ondemand_dash",d.HLS="hls",d.ONDEMAND_HLS="ondemand_hls",d.WEBM="webm",d.AV1="av1",d.ONDEMAND_DASH_LIVE="ondemand_dash_live",d.ONDEMAND_HLS_LIVE="ondemand_hls_live",d.WEBRTC="webrtc",d.UNKNOWN="unknown",d.RTMP="rtmp",d))(V||{});var U=(t=>(t.HTTP1="http1",t.HTTP2="http2",t.HTTP3="http3",t))(U||{});var W=(l=>(l.SLIDER="slider",l.DOUBLE_TAP="double_tap",l.TIME_CODE="time_code",l.EPISODE="episode",l.REWIND="rewind",l.LIVE="live",l.UNKNOWN="unknown",l))(W||{}),re=(n=>(n.GRAPH_SHOW="iGraphShow",n.GRAPH_HIDE="iGraphHide",n.NEXT_AREA="iNextChapterArea",n.NEXT_BUTTON="iNextChapterBtn",n.WATCH_AGAIN="iWatchAgainBtn",n))(re||{}),ne={action_play:"ap",action_play_interactive:"api",first_bytes:"fb",player_ready:"pr",first_frame:"ff",seek:"sk",watch_coverage_record:"wr",watch_coverage_live:"wl",empty_buffer:"eb",action_stop:"as",close_at_empty_buffer:"cb",content_error:"er",player_interface_click:"pc",next_movie:"nm",track_switch:"ts",failover:"fo"},ae={vsid:"si",isid:"is",vid:"vi",place:"pl",quality:"qt",cdn_host:"ch",stat_type:"st",param:"pm",vk_app_id:"va",track_code:"tc",connection_type:"cnt",connection_reused:"cr",cached_data:"cd",live:"lv",muted:"mu",mode:"mo",subtitles:"sb",failover:"fo",download_speed:"ds",manual_quality:"mq",ref_domain:"rd",direct_url:"du"},de={unknown:"un",mobile:"m",lowest:"ls",low:"l",medium:"md",high:"h",fullhd:"f",quadhd:"q",ultrahd:"u"},ue={pip:"pi",fullscreen:"fs",external:"ex",prefetch:"pr",airplay:"ap",chromecast:"cc",invisible:"iv"};import{fillWithDefault as Ne}from"@vkontakte/videoplayer-shared";var De={apiEnv:"vk_alias",requestRetryCount:1,firstFlushTime:5e3,flushDebounceTime:1e4,flushMaxWait:6e4,storageExpiration:36*60*60*1e3,watchCoverageInterval:15e3,disabledOperations:[],disabledCustomFields:[],shorten:!0,maxLoops:100,embedUrlParams:[],useBeacon:!0,synchronizeTime:!0,debugLog:!1,backoff:{start:1e3,factor:1.5,max:5*60*1e3,random:.1}},ce=r=>Ne(r,De);function H(){let r="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".split(""),e=new Array(36),i=0,t,o;for(o=0;o<36;o++)o===8||o===13||o===18||o===23?e[o]="-":o===14?e[o]="4":(i<=2&&(i=33554432+Math.random()*16777216|0),t=i&15,i=i>>4,e[o]=r[o===19?t&3|8:t]);return e.join("")}import{assertNonNullable as je,combine as Ee,fromEvent as _e,isNonNullable as x,isNullable as xe,merge as Ge,now as v,observableFrom as Ye,once as Xe,safeStorage as X,Subject as Je,Subscription as te,ValueSubject as J}from"@vkontakte/videoplayer-shared";import{Logger as Ze,detectEmbed as et}from"@vkontakte/videoplayer-shared";var le=r=>{var o;let{operation:e,custom:i}=r,t=Object.fromEntries(Object.entries(i).map(([n,a])=>{var c,h,p;let l=(c=ae[n])!=null?c:n,u=a;return a&&(n==="mode"?u=(h=ue[a])!=null?h:a:n==="quality"&&(u=(p=de[a])!=null?p:a)),[l,u]}));return L(y({},r),{operation:(o=ne[e])!=null?o:e,custom:t})};var $="1.0.52-dev.a5f6699f.0",pe="CIOPGQJGDIHBABABA",K={prod:"https://api.ok.ru",vk_alias:"https://api.mycdn.me",videotest:"https://videotestapi.ok.ru/api",test:"https://apitest.ok.ru",auto:""};import{ValueSubject as Me,getExponentialDelay as Be,ErrorCategory as E}from"@vkontakte/videoplayer-shared";var T=class{constructor(e){this.consequentAuthErrors=0;this.authorized$=new Me(!1);this.params=e}authorize(e){return m(this,null,function*(){return this.authToken=e!=null?e:yield this.refreshAuthToken(),this._authorizeWithBackoff()})}logBeacon(e){let i="log.externalLog",t=this.createLogParams(e),o=this.sessionKey;if(!o)return;this.params.apiTransport.sendBeacon(i,t,o)||this.logRequest(e)}logRequest(e){return m(this,null,function*(){var a;let i="log.externalLog",t=this.createLogParams(e),o=(a=this.sessionKey)!=null?a:yield this._authorizeWithBackoff();if(!o)return;let n=(c,...h)=>m(this,[c,...h],function*(l,u=this.params.config.requestRetryCount){try{return yield this.params.apiTransport.sendRequest(i,t,o)}catch(p){if(!p||!("error_code"in p)){this.params.error$.next({id:"logRequestUnknown",category:E.NETWORK,message:`Unknown ${i} error`,thrown:p});return}let s=p==null?void 0:p.error_code;switch(s){case 102:case 103:case 104:return this.authorized$.next(!1),this.sessionKey=yield this._authorizeWithBackoff(),u>0?n(l,u-1):void 0;case 401:return this.authorized$.next(!1),this.authToken=yield this.refreshAuthToken(),this.sessionKey=yield this._authorizeWithBackoff(),u>0?n(l,u-1):void 0;default:{this.params.error$.next({id:`LogRequest#${s}`,category:E.EXTERNAL_API,message:`${i} error`,data:p});return}}}});return n(e)})}destroy(){window.clearTimeout(this.backoffTimeoutId),this.backoffTimeoutId=0}refreshAuthToken(){return m(this,null,function*(){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:${$}`,platform:this.params.mobile?"M_WEB":"WEB",items:this.params.config.shorten?e.map(le):e})}}_authorizeWithBackoff(){if(!this.consequentAuthErrors)return this._authorize();let e=Be(this.consequentAuthErrors,this.params.config.backoff);return new Promise(i=>{this.backoffTimeoutId||(this.backoffTimeoutId=window.setTimeout(()=>{this._authorize().then(i).catch(t=>this.params.error$.next({id:"AuthorizeBackoff",category:E.NETWORK,message:"Otherwise unhandled error in authorization",thrown:t})).finally(()=>this.backoffTimeoutId=0)},e))})}_authorize(){return m(this,null,function*(){if(this.authorizePromise)return this.authorizePromise;this.sessionKey=void 0,this.authorized$.next(!1);let e="auth.anonymLogin",i={session_data:{version:2,device_id:this.params.uuid,client_version:$.split("-")[0],client_type:"SDK_JS"}};return this.authToken!==void 0&&(i.session_data.auth_token=this.authToken,i.session_data.version=3),this.authorizePromise=this.params.apiTransport.sendRequest(e,i).then(t=>{var o;return(!t||!t.session_key)&&this.params.error$.next({id:"AuthorizeFailed",category:E.EXTERNAL_API,message:"No session key",data:t}),this.sessionKey=(o=t==null?void 0:t.session_key)!=null?o:void 0,this.sessionKey}).catch(t=>m(this,null,function*(){this.sessionKey=void 0;let o=t==null?void 0:t.error_code;switch(o){case 401:return this.authToken=yield this.refreshAuthToken(),this._authorizeWithBackoff()}o?this.params.error$.next({id:`Authorize#${o}`,category:E.EXTERNAL_API,message:"authorize error",data:t}):this.params.error$.next({id:"AuthorizeUnknown",category:E.NETWORK,message:"authorize error",thrown:t})})).finally(()=>{this.authorizePromise=void 0,this.consequentAuthErrors=this.sessionKey?0:this.consequentAuthErrors+1,this.authorized$.next(this.sessionKey!==void 0)}),this.authorizePromise})}};import{ErrorCategory as R,now as q}from"@vkontakte/videoplayer-shared";var w=class{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}resolveApiBaseUrl(){return m(this,null,function*(){var e;if(this.apiEnv!=="auto"||this.isApiBaseUrlFetched)return this.apiBaseUrl;try{let i=atob("aHR0cHM6Ly9kbnMuZ29vZ2xlL3Jlc29sdmU/bmFtZT12aWRlby5fZW5kcG9pbnQub2sucnUmdHlwZT1UWFQ="),o=yield(yield fetch(i,{method:"GET",mode:"cors",cache:"no-cache"})).json(),n=(e=o==null?void 0:o.Answer[0])==null?void 0:e.data;if(!n)throw new Error("Wrong DNS response");return n}catch(i){return this.params.error$.next({id:"OneStat:ApiTransport:resolveApiBaseUrl",category:R.NETWORK,message:"Unhandled resolve api base url error",thrown:i}),K.vk_alias}finally{this.isApiBaseUrlFetched=!0}})}sendBeacon(e,i,t){if(!window.Blob||!window.navigator.sendBeacon)return!1;let o=this._prepareQueryParams({method:e,queryParams:i,sessionKey:t}),n=new window.Blob([o.toString()],{type:"application/x-www-form-urlencoded"});try{return window.navigator.sendBeacon(`${this.apiBaseUrl}/fb.do`,n)}catch(a){this.params.error$.next({id:"OneStat:ApiTransport:sendBeacon",category:R.NETWORK,message:"Unhandled beacon error",thrown:a,data:{method:e,params:i}})}return!1}sendRequest(e,i,t){return m(this,null,function*(){let o=q(),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:R.NETWORK,message:"Request failed",thrown:a});return}this.params.error$.next({id:"OneStat:ApiTransport:sendRequest",category:R.NETWORK,message:"Unhandled request error",thrown:a,data:{method:e,params:i,sessionKey:t,time:q()-o}})};return this.apiBaseUrl=yield this.resolveApiBaseUrl(),fetch(`${this.apiBaseUrl}/fb.do`,{method:"post",headers:{"Content-type":"application/x-www-form-urlencoded"},body:this._prepareQueryParams({method:e,queryParams:i,sessionKey:t})}).then(a=>{var h,p;let l=Number(a.headers.get("content-length"))===0,u=new Date((h=a.headers.get("date"))!=null?h:"").getTime(),c=q()-o;if(isFinite(u)&&((p=this.timeSynchronisation)==null||p.addServerTime(u,c)),!l)return a.json().then(s=>Object.prototype.hasOwnProperty.call(s,"error_msg")?Promise.reject(s):s,n)},n)})}_prepareQueryParams(e){let i=new URLSearchParams({format:"JSON",method:e.method,application_key:this.apiKey});return e.sessionKey!==void 0&&i.append("session_key",e.sessionKey),Object.entries(e.queryParams).forEach(([t,o])=>i.append(t,typeof o=="string"?o:JSON.stringify(o))),i}};import{ErrorCategory as Fe,now as Ve,safeStorage as k,debounceFn as he}from"@vkontakte/videoplayer-shared";var O="onestat_events",z=r=>e=>e.timestamp+r>=Ve(),N=class{constructor(e){this.unsaltedStorage=[];this.isPaused=!1;this.isUrgent=e=>{let{operation:i}=e;return["action_play","watch_coverage_record","watch_coverage_live"].includes(i)};this.params=e,this.api=e.api,this.error$=e.error$,this.userSalt=e.userSalt,this.loggerDebugLog=e.debugLogger.createComponentLog("stat logger"),this.firstFlush=he(()=>this.safeFlush(),this.params.config.firstFlushTime,{maxWait:this.params.config.firstFlushTime});let i=k.isPersistent()?this.params.config.flushMaxWait:0;this.debouncedFlush=he(()=>this.safeFlush(),this.params.config.flushDebounceTime,{maxWait:i}),this.subscription=this.api.authorized$.subscribe(t=>{t&&this.debouncedFlush()}),this.housekeepStorage()}safeFlush(){var e;try{this.flush()}catch(i){this.error$.next({id:"LoggerError",category:Fe.WTF,message:(e=String(i))!=null?e:"Unknown logger error",thrown:i})}}readFromStorage(){let e=k.get(O);try{return e?JSON.parse(e):{}}catch(i){}return{}}addToStorage(e){var n;if(!this.userSalt){this.unsaltedStorage.push(e);return}let i=this.readFromStorage(),o=((n=i[this.userSalt])!=null?n:[]).filter(z(this.params.config.storageExpiration));k.set(O,JSON.stringify(L(y({},i),{[this.userSalt]:[...o,e]})))}getFromStorage(){var t;return this.userSalt?((t=this.readFromStorage()[this.userSalt])!=null?t:[]).filter(z(this.params.config.storageExpiration)):this.unsaltedStorage}markStorageSent(){if(!this.userSalt){this.unsaltedStorage=[];return}let e=this.readFromStorage();delete e[this.userSalt],k.set(O,JSON.stringify(e))}housekeepStorage(){let e=this.readFromStorage();for(let[i,t]of Object.entries(e)){let o=t.filter(z(this.params.config.storageExpiration));o.length?e[i]=o:delete e[i],this.loggerDebugLog({message:`${t.length} retrieved from storage, ${o.length} of them actual`})}k.set(O,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){let i=this.getFromStorage();i.length!==0&&(this.api.authorized$.getValue()?(e&&this.params.config.useBeacon?(this.loggerDebugLog({message:`Flushing ${i.length} events through beacon`}),this.api.logBeacon(i)):(this.loggerDebugLog({message:`Flushing ${i.length} events`}),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()}};import{HttpConnectionType as Q,Surface as _,VideoFormat as f,VideoQuality as b}from"@vkontakte/videoplayer-core";import{assertNever as fe}from"@vkontakte/videoplayer-shared";var ge=r=>r&&{[b.INVARIANT]:"unknown",[b.Q_144P]:"mobile",[b.Q_240P]:"lowest",[b.Q_360P]:"low",[b.Q_480P]:"medium",[b.Q_720P]:"high",[b.Q_1080P]:"fullhd",[b.Q_1440P]:"quadhd",[b.Q_2160P]:"ultrahd",[b.Q_4320P]:"unknown"}[r],j=r=>r&&{[Q.HTTP1]:"http1",[Q.HTTP2]:"http2",[Q.QUIC]:"http3"}[r],me=r=>{if(r!==void 0)switch(r){case f.MPEG:return"mp4";case f.DASH:case f.DASH_LIVE:case f.DASH_STREAMS:return"dash";case f.DASH_SEP:return"dash_sep";case f.DASH_ONDEMAND:return"ondemand_dash";case f.DASH_WEBM:case f.DASH_LIVE_WEBM:return"webm";case f.DASH_WEBM_AV1:return"av1";case f.DASH_LIVE_CMAF:return"ondemand_dash_live";case f.HLS:case f.HLS_LIVE:return"hls";case f.HLS_ONDEMAND:return"ondemand_hls";case f.HLS_LIVE_CMAF:return"ondemand_hls_live";case f.WEB_RTC_LIVE:return"webrtc";default:return fe(r)}},D=r=>{if(r!==void 0)switch(r){case _.NONE:case _.INLINE:return;case _.FULLSCREEN:return"fullscreen";case _.SECOND_SCREEN:return"chromecast";case _.PIP:return"pip";case _.INVISIBLE:return"invisible";default:return fe(r)}},be=r=>{switch(r){case"slow-2g":return"poor";case"2g":return"poor";case"3g":return"good";case"4g":return"excellent"}};var M=class{constructor(e){this.offset=void 0;this.offset=e}getOffset(){var e;return(e=this.offset)!=null?e:0}setOffset(e){this.offset=e}now(){var e;return Date.now()+((e=this.offset)!=null?e:0)}date(e=new Date){var i;return e.setTime(e.getTime()+((i=this.offset)!=null?i:0)),e}addServerTime(e,i){let t=Date.now(),o=e-t-i/2;if(Math.abs(o)<1e3){this.offset=0;return}this.offset===void 0?this.offset=Math.round(o):this.offset=Math.round(.2*o+(1-.2)*this.offset)}};var ve=()=>Math.floor(Math.random()*4294967296).toString(36).padStart(7,"0"),Ie=()=>Math.floor(Math.random()*18446744073709552e3).toString(36).padStart(13,"0");import{PlaybackState as Se}from"@vkontakte/videoplayer-core";import{filter as ye,filterChanged as We,fromEvent as He,isNullable as Pe,map as Ke,merge as G,Observable as qe,Subject as Y,Subscription as ze,ValueSubject as Qe}from"@vkontakte/videoplayer-shared";var Ae=(r,e)=>new qe(i=>{let t=new ze,o=G(He(window,"beforeunload"),r.events.willDestruct$),n=new Qe(void 0),a;t.add(r.info.isLive$.pipe(We()).subscribe(S=>{a&&(a.unsubscribe(),n.next(void 0)),S?a=r.info.liveTime$.pipe(Ke(B=>B&&B/1e3)).subscribe(n):a=r.info.position$.subscribe(n),t.add(a)}));let{playing$:l,paused$:u}=r.events,c=r.events.willSeek$.pipe(ye(()=>r.info.playbackState$.getValue()===Se.PLAYING)),h=r.events.seeked$.pipe(ye(()=>r.info.playbackState$.getValue()===Se.PLAYING)),p=!1,s=new Y;t.add(c.subscribe(()=>{p||s.next(),p=!0})),t.add(h.subscribe(()=>p=!1));let d=new Y,g=new Y,I=G(l,h,d),P=G(u,s,o,r.events.looped$,g),A,Ce=()=>A=n.getValue(),Te=()=>{let S=n.getValue();Pe(A)||A===S||Pe(S)||(i.next({from:A,to:S}),A=void 0)},we=()=>{g.next(),d.next()};if(t.add(I.subscribe(Ce)),t.add(P.subscribe(Te)),e.forceInterval&&isFinite(e.forceInterval)){let S=0;t.add(I.subscribe(()=>S=window.setTimeout(we,e.forceInterval))),t.add(P.subscribe(()=>window.clearTimeout(S)))}return t});var tt="_one-stat_",Z=`${tt}uuid`,ee=()=>{let r=new te;return{subscription:r,subscribe:(e,i)=>{e&&r.add(e.subscribe(i))}}},ie=class{constructor(e,i){this.subscription=new te;this.debugLogger=new Ze;this.oneStatDebugLog=this.debugLogger.createComponentLog("onestat");this.loopCounter=0;this.disabled=!1;this.vsid$=new J(void 0);this.isid$=new J(void 0);this.seekAction$=new J("unknown");var u,c,h;this.statContext=e,this.config=ce((u=i.config)!=null?u:{}),x(i.apiEnv)&&(this.config.apiEnv=i.apiEnv),this.config.synchronizeTime&&(this.timeSynchronisation=new M);let t=new Je;this.experimental={error$:t};let o=X.get(Z);o?o.startsWith('"')&&o.endsWith('"')?(this.uuid=o.replaceAll('"',""),X.set(Z,this.uuid)):this.uuid=o:(this.uuid=H(),X.set(Z,this.uuid)),this.resetViewSession(),i.useIsid&&this.isid$.next((c=i.isid)!=null?c:Ie());let n=new w({apiKey:pe,config:this.config,error$:t,timeSynchronisation:this.timeSynchronisation});this.api=new T({config:this.config,apiTransport:n,refreshAuthToken:i.refreshAuthToken,mobile:(h=this.statContext.mobile)!=null?h:!1,uuid:this.uuid,error$:t}),this.logger=new N({config:this.config,debugLogger:this.debugLogger,api:this.api,error$:t,userSalt:i.userSalt});let{isEmbed:a,host:l}=et();this.isEmbed=a,this.embedParent=l,this.subscribe()}updateContext(e){this.statContext=y(y({},this.statContext),e)}attachTo(e){let i=new te,t=(s,d)=>i.add(s.subscribe(d));t(e.events.willStart$,()=>{let s=e.info.position$.getValue();this.logActionPlay({position:s}),this.statContext.projectId&&this.logActionPlayInteractive()}),t(e.events.looped$,()=>{this.resetViewSession(),++this.loopCounter>this.config.maxLoops&&(this.disabled=!0),this.logActionPlay({position:e.info.position$.getValue()})}),t(e.events.seeked$,()=>{this.logSeek({action:this.seekAction$.getValue(),time:e.info.position$.getValue()}),this.seekAction$.next("unknown")}),t(e.events.paused$,()=>{this.logPause({position:e.info.position$.getValue()})}),t(e.events.willResume$,()=>{this.logPlay()}),t(e.events.started$,()=>{this.statContext.clip&&this.logWatchCoverageRecord({start:0,end:0})}),t(e.events.playing$,()=>{this.logPlaying()}),t(Ae(e,{forceInterval:this.config.watchCoverageInterval}),s=>{let d=e.info.isLive$.getValue(),g={start:parseFloat(s.from.toFixed(3)),end:parseFloat(s.to.toFixed(3))};d?this.logWatchCoverageLive(g):this.logWatchCoverageRecord(g)});let o;t(e.info.isStalled$,s=>{s?o=v():(x(o)&&this.logEmptyBuffer({duration:v()-o}),o=void 0)});let n=!1;i.add(e.events.fatalError$.pipe(Xe()).subscribe(()=>n=!0)),t(e.events.willStop$,()=>{if(e.info.isStalled$.getValue()){let d=x(o)?v()-o:void 0;this.logCloseAtEmptyBuffer({duration:d!=null?d:0}),o=void 0}else n||this.logActionStop()}),t(e.events.managedError$,({id:s})=>{this.logError({fatal:!1,errorType:s})}),t(e.events.fatalError$,({id:s})=>{this.logError({fatal:!0,errorType:s})});let a,l,u=!1;t(e.events.firstBytes$,s=>{a=v(),this.logFirstBytes({time:s})}),t(e.events.willStart$,()=>l=v()),t(e.info.currentBuffer$,s=>{!u&&s&&s.end-s.start>0&&x(a)&&(this.logPlayerReady({duration:v()-a}),u=!0)}),t(e.events.firstFrame$,()=>{x(a)&&!u&&(this.logPlayerReady({duration:v()-a}),u=!0),x(l)&&this.logFirstFrame({time:v()-l})});let c;t(e.info.currentVideoStream$,s=>{s&&(c&&s.id!==c&&this.logTrackSwitch(s),c=s.id)});let h;t(e.info.currentAudioStream$,s=>{s&&(h&&s.id!==h&&this.logTrackSwitch(s),h=s.id)}),t(e.info.atLiveEdge$,s=>this.updateContext({liveEdge:s})),t(Ee({muted:e.info.muted$,volume:e.info.volume$}),({muted:s,volume:d})=>this.updateContext({audible:!s&&d>0})),t(e.info.currentQuality$,s=>this.updateContext({quality:ge(s)})),t(e.info.isAutoQualityEnabled$,s=>this.updateContext({autoQuality:s})),t(e.info.currentFormat$,s=>this.updateContext({contentType:me(s)})),t(e.info.currentPlaybackRate$,s=>this.updateContext({rate:s})),t(e.info.is3DVideo$,s=>this.updateContext({is3d:s}));let p;return t(e.info.hostname$,s=>{let d=p!==void 0&&p!==s;this.updateContext({cdnHostname:s,failover:d}),d&&this.logFailover(s),p=s}),t(e.info.throughputEstimation$,s=>this.updateContext({downloadSpeed:s})),t(e.info.httpConnectionType$,s=>{this.statContext.firstConnectionType||this.updateContext({firstConnectionType:j(s)}),this.updateContext({connectionType:j(s)})}),t(e.info.httpConnectionReused$,s=>{xe(this.statContext.firstConnectionReused)&&this.updateContext({firstConnectionReused:s}),this.updateContext({connectionReused:s})}),t(e.info.surface$,s=>this.updateContext({mode:D(s)})),t(Ee({current:e.info.currentTextTrack$,available:e.info.availableTextTracks$}),({current:s,available:d})=>{let g=d.find(({id:P})=>P===s),I=g&&(g.isAuto?`${g.language}_auto`:g.language);this.updateContext({subtitles:I})}),this.player=e,this.uiEvents&&this.attachToUi(this.uiEvents),this.resubscribeBeforeunload(),this.subscription.add(i),i}attachToUi(e){this.uiEvents=e;let{subscription:i,subscribe:t}=ee();return this.player&&(t(e.actionRewind$,()=>{this.player&&(this.resetViewSession(),this.logActionPlay({position:this.player.info.position$.getValue()}))}),t(e.actionSeek$,this.seekAction$),t(e.inPiP$,o=>{var a;let n=o?"pip":D((a=this.player)==null?void 0:a.info.surface$.getValue());this.updateContext({mode:n})}),t(e.inFullscreen$,o=>{var a;let n=o?"fullscreen":D((a=this.player)==null?void 0:a.info.surface$.getValue());this.updateContext({mode:n})}),t(e.actionSetSubtitle$,o=>this.updateContext({subtitles:o})),t(e.nextMovie$,o=>this.logNextMovie(o)),this.resubscribeBeforeunload(),this.subscription.add(i)),i}attachToAds(e){let{subscription:i,subscribe:t}=ee();return t(e.slotRequested$,()=>this.logAdSlotRequest()),t(e.started$,o=>this.logAdStarted(o)),t(e.paused$,()=>this.logAdPaused()),t(e.resumed$,()=>this.logAdResumed()),t(e.ended$,()=>this.logAdEnded()),t(e.skipped$,()=>this.logAdSkipped()),t(e.clicked$,()=>this.logAdClicked()),this.resubscribeBeforeunload(),this.subscription.add(i),i}attachToInteractive(e){let{subscription:i,subscribe:t}=ee();return t(e.click$,o=>this.logInterfaceClick(o)),t(e.nextMovie$,o=>this.logNextMovie(o)),this.resubscribeBeforeunload(),this.subscription.add(i),i}authorize(e){return this.api.authorize(e)}pause(){this.logger.pause(),this.oneStatDebugLog({message:"paused"})}resume(){this.logger.resume(),this.oneStatDebugLog({message:"resumed"})}destroy(){this.logger.flush(),this.subscription.unsubscribe(),this.api.destroy(),this.logger.destroy()}resetViewSession(){this.oneStatDebugLog({message:"VSID reset"}),this.vsid$.next(ve())}getDeviceId(){return this.uuid}setFieldBlacklist(){}logInited(){}logReady(e){this.log({operation:"player_ready",param:String(e.time)})}logStarted(...e){this.logActionPlay(...e)}logPlay(){this.log({operation:"play_toggle"})}logPlaying(){this.log({operation:"playing"})}logPause(e){this.log({operation:"pause",param:String(Math.round(e.position))})}logSeek(e){this.log({operation:"seek",param:e.action,time:e.time})}logFirstBytes(e){this.log({operation:"first_bytes",param:String(e.time)})}logFirstFrame(e){this.log({operation:"first_frame",param:String(e.time)})}logError(e){this.log({operation:"content_error",param:`${e.fatal?"fatal":"recoverable"}_${e.errorType}`})}logWatchCoverageRecord(e){this.log({operation:"watch_coverage_record",param:`${e.start}-${e.end}`})}logWatchCoverageLive(e){var n,a;let i=(a=(n=this.timeSynchronisation)==null?void 0:n.getOffset())!=null?a:0,t=e.start+i,o=e.end+i;this.log({operation:"watch_coverage_live",param:`${t}-${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();let e=window.navigator.connection;e&&"onchange"in e&&"effectiveType"in e&&this.subscription.add(Ge(_e(e,"change"),Ye(["init"])).subscribe(()=>this.updateContext({network:be(e.effectiveType)}))),this.config.debugLog&&this.debugLogger.log$.subscribe(i=>{console.debug("%c stat ","background:#fa6470;",`component: ${i.component}.`,i.message)})}resubscribeBeforeunload(){var e;(e=this.beforeunloadSubscription)==null||e.unsubscribe(),this.beforeunloadSubscription=_e(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))})}logActionPlayInteractive(){this.statContext.projectId&&this.log({operation:"action_play_interactive",param:String(this.statContext.movieId)},{vid:this.statContext.projectId})}logFailover(e){this.log({operation:"failover",param:e})}logCloseAtEmptyBuffer(e){this.log({operation:"close_at_empty_buffer",param:String(Math.round(e.duration))})}logActionStop(){this.log({operation:"action_stop"})}logTrackSwitch(e){this.log({operation:"track_switch",param:e.id})}log(e,i={}){if(this.disabled){this.oneStatDebugLog({message:`operation ${e.operation} but statistics is disabled`});return}if(this.config.disabledOperations.includes(e.operation)){this.oneStatDebugLog({message:`operation ${e.operation} but it is disabled`});return}this.oneStatDebugLog({message:`operation ${e.operation} ${e.param}`});let t=this.createLogItem(e,i);this.logger.log(t)}createLogItem({operation:e,param:i,time:t},o={}){var d,g;let n=(g=(d=this.timeSynchronisation)==null?void 0:d.now())!=null?g:v(),a=this.vsid$.getValue();je(a);let l=this.isid$.getValue(),u=e==="empty_buffer"||e==="close_at_empty_buffer"?this.statContext.connectionType:this.statContext.firstConnectionType,c=this.statContext.firstConnectionReused,h,p;if(this.isEmbed){h=this.embedParent;let I=[...new URLSearchParams(location.search).entries()].filter(([P,A])=>this.config.embedUrlParams.includes(P));p=new URLSearchParams(I).toString()}else this.statContext.place==="direct"&&((this.statContext.refDomain||document.referrer)&&(h=new URL(this.statContext.refDomain||document.referrer).hostname),p=location.href.substring(0,1024));let s=y({vsid:a,isid:l,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?"auto":this.statContext.autoplay===!1?"":void 0,param:i,vk_app_id:this.statContext.vkAppId,track_code:this.statContext.trackCode,connection_type:u,connection_reused:c===!0?1:c===!1?0:void 0,cached_data:this.statContext.cached===!0?1:this.statContext.cached===!1?0:void 0,live:this.statContext.liveEdge?1:void 0,muted:this.statContext.audible===!1?1:void 0,mode:this.statContext.mode,subtitles:this.statContext.subtitles,download_speed:this.statContext.downloadSpeed,manual_quality:this.statContext.autoQuality?void 0:1,ref_domain:h,direct_url:p,rate:this.statContext.rate===1||xe(this.statContext.rate)?void 0:this.statContext.rate.toFixed(2),view_360:this.statContext.is3d?1:void 0,aid:this.statContext.albumId,vk_playlist_id:this.statContext.vkPlaylistId},o);for(let I of this.config.disabledCustomFields)delete s[I];return{operation:e,type:1,time:t,network:this.statContext.network,timestamp:n,custom:s}}};export{C as ApiEnv,U as ConnectionType,V as ContentType,re as InteractiveInterfaceClick,ie as OneStat,F as Quality,W as SeekAction,$ as VERSION};
package/es2018.cjs.js CHANGED
@@ -1,6 +1,6 @@
1
1
  /**
2
- * @vkontakte/videoplayer-statistics v1.0.52-dev.22c05d5f.0
3
- * Tue, 30 Jul 2024 08:28:10 GMT
2
+ * @vkontakte/videoplayer-statistics v1.0.52-dev.a5f6699f.0
3
+ * Tue, 30 Jul 2024 10:43:01 GMT
4
4
  * https://st.mycdn.me/static/vkontakte-videoplayer/1-0-52/doc/
5
5
  */
6
- "use strict";var V=Object.defineProperty;var he=Object.getOwnPropertyDescriptor;var fe=Object.getOwnPropertyNames;var ge=Object.prototype.hasOwnProperty;var me=(n,e)=>{for(var i in e)V(n,i,{get:e[i],enumerable:!0})},be=(n,e,i,t)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of fe(e))!ge.call(n,o)&&o!==i&&V(n,o,{get:()=>e[o],enumerable:!(t=he(e,o))||t.enumerable});return n};var ve=n=>be(V({},"__esModule",{value:!0}),n);var Pe={};me(Pe,{ApiEnv:()=>_,ConnectionType:()=>L,ContentType:()=>k,InteractiveInterfaceClick:()=>U,OneStat:()=>M,Quality:()=>w,SeekAction:()=>$,VERSION:()=>x});module.exports=ve(Pe);var _=(r=>(r.PROD="prod",r.VK_ALIAS="vk_alias",r.VIDEOTEST="videotest",r.TEST="test",r.AUTO="auto",r))(_||{}),w=(c=>(c.Q144P="mobile",c.Q240P="lowest",c.Q360P="low",c.Q480P="medium",c.Q720P="high",c.Q1080P="fullhd",c.Q1440P="quadhd",c.Q2160P="ultrahd",c.UNKNOWN="unknown",c))(w||{}),k=(l=>(l.MP4="mp4",l.DASH="dash",l.DASH_SEP="dash_sep",l.ONDEMAND_DASH="ondemand_dash",l.HLS="hls",l.ONDEMAND_HLS="ondemand_hls",l.WEBM="webm",l.AV1="av1",l.ONDEMAND_DASH_LIVE="ondemand_dash_live",l.ONDEMAND_HLS_LIVE="ondemand_hls_live",l.WEBRTC="webrtc",l.UNKNOWN="unknown",l.RTMP="rtmp",l))(k||{});var L=(t=>(t.HTTP1="http1",t.HTTP2="http2",t.HTTP3="http3",t))(L||{});var $=(h=>(h.SLIDER="slider",h.DOUBLE_TAP="double_tap",h.TIME_CODE="time_code",h.EPISODE="episode",h.REWIND="rewind",h.LIVE="live",h.UNKNOWN="unknown",h))($||{}),U=(r=>(r.GRAPH_SHOW="iGraphShow",r.GRAPH_HIDE="iGraphHide",r.NEXT_AREA="iNextChapterArea",r.NEXT_BUTTON="iNextChapterBtn",r.WATCH_AGAIN="iWatchAgainBtn",r))(U||{}),Y={action_play:"ap",action_play_interactive:"api",first_bytes:"fb",player_ready:"pr",first_frame:"ff",seek:"sk",watch_coverage_record:"wr",watch_coverage_live:"wl",empty_buffer:"eb",action_stop:"as",close_at_empty_buffer:"cb",content_error:"er",player_interface_click:"pc",next_movie:"nm",track_switch:"ts",failover:"fo"},X={vsid:"si",isid:"is",vid:"vi",place:"pl",quality:"qt",cdn_host:"ch",stat_type:"st",param:"pm",vk_app_id:"va",track_code:"tc",connection_type:"cnt",connection_reused:"cr",cached_data:"cd",live:"lv",muted:"mu",mode:"mo",subtitles:"sb",failover:"fo",download_speed:"ds",manual_quality:"mq",ref_domain:"rd",direct_url:"du"},J={unknown:"un",mobile:"m",lowest:"ls",low:"l",medium:"md",high:"h",fullhd:"f",quadhd:"q",ultrahd:"u"},Z={pip:"pi",fullscreen:"fs",external:"ex",prefetch:"pr",airplay:"ap",chromecast:"cc",invisible:"iv"};var ee=require("@vkontakte/videoplayer-shared"),Ie={apiEnv:"vk_alias",requestRetryCount:1,firstFlushTime:5e3,flushDebounceTime:1e4,flushMaxWait:6e4,storageExpiration:36*60*60*1e3,watchCoverageInterval:15e3,disabledOperations:[],disabledCustomFields:[],shorten:!0,maxLoops:100,embedUrlParams:[],useBeacon:!0,synchronizeTime:!0,debugLog:!1,backoff:{start:1e3,factor:1.5,max:5*60*1e3,random:.1}},te=n=>(0,ee.fillWithDefault)(n,Ie);function W(){let n="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".split(""),e=new Array(36),i=0,t,o;for(o=0;o<36;o++)o===8||o===13||o===18||o===23?e[o]="-":o===14?e[o]="4":(i<=2&&(i=33554432+Math.random()*16777216|0),t=i&15,i=i>>4,e[o]=n[o===19?t&3|8:t]);return e.join("")}var a=require("@vkontakte/videoplayer-shared"),B=require("@vkontakte/videoplayer-shared");var ie=n=>{var o;let{operation:e,custom:i}=n,t=Object.fromEntries(Object.entries(i).map(([r,d])=>{var c,g,m;let h=(c=X[r])!=null?c:r,f=d;return d&&(r==="mode"?f=(g=Z[d])!=null?g:d:r==="quality"&&(f=(m=J[d])!=null?m:d)),[h,f]}));return{...n,operation:(o=Y[e])!=null?o:e,custom:t}};var x="1.0.52-dev.22c05d5f.0",oe="CIOPGQJGDIHBABABA",H={prod:"https://api.ok.ru",vk_alias:"https://api.mycdn.me",videotest:"https://videotestapi.ok.ru/api",test:"https://apitest.ok.ru",auto:""};var I=require("@vkontakte/videoplayer-shared");var C=class{constructor(e){this.consequentAuthErrors=0;this.authorized$=new I.ValueSubject(!1);this.params=e}async authorize(e){return this.authToken=e!=null?e:await this.refreshAuthToken(),this._authorizeWithBackoff()}logBeacon(e){let i="log.externalLog",t=this.createLogParams(e),o=this.sessionKey;if(!o)return;this.params.apiTransport.sendBeacon(i,t,o)||this.logRequest(e)}async logRequest(e){var d;let i="log.externalLog",t=this.createLogParams(e),o=(d=this.sessionKey)!=null?d:await this._authorizeWithBackoff();if(!o)return;let r=async(h,f=this.params.config.requestRetryCount)=>{try{return await this.params.apiTransport.sendRequest(i,t,o)}catch(c){if(!c||!("error_code"in c)){this.params.error$.next({id:"logRequestUnknown",category:I.ErrorCategory.NETWORK,message:`Unknown ${i} error`,thrown:c});return}let g=c==null?void 0:c.error_code;switch(g){case 102:case 103:case 104:return this.authorized$.next(!1),this.sessionKey=await this._authorizeWithBackoff(),f>0?r(h,f-1):void 0;case 401:return this.authorized$.next(!1),this.authToken=await this.refreshAuthToken(),this.sessionKey=await this._authorizeWithBackoff(),f>0?r(h,f-1):void 0;default:{this.params.error$.next({id:`LogRequest#${g}`,category:I.ErrorCategory.EXTERNAL_API,message:`${i} error`,data:c});return}}}};return r(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:${x}`,platform:this.params.mobile?"M_WEB":"WEB",items:this.params.config.shorten?e.map(ie):e})}}_authorizeWithBackoff(){if(!this.consequentAuthErrors)return this._authorize();let e=(0,I.getExponentialDelay)(this.consequentAuthErrors,this.params.config.backoff);return new Promise(i=>{this.backoffTimeoutId||(this.backoffTimeoutId=window.setTimeout(()=>{this._authorize().then(i).catch(t=>this.params.error$.next({id:"AuthorizeBackoff",category:I.ErrorCategory.NETWORK,message:"Otherwise unhandled error in authorization",thrown:t})).finally(()=>this.backoffTimeoutId=0)},e))})}async _authorize(){if(this.authorizePromise)return this.authorizePromise;this.sessionKey=void 0,this.authorized$.next(!1);let e="auth.anonymLogin",i={session_data:{version:2,device_id:this.params.uuid,client_version:x.split("-")[0],client_type:"SDK_JS"}};return this.authToken!==void 0&&(i.session_data.auth_token=this.authToken,i.session_data.version=3),this.authorizePromise=this.params.apiTransport.sendRequest(e,i).then(t=>{var o;return(!t||!t.session_key)&&this.params.error$.next({id:"AuthorizeFailed",category:I.ErrorCategory.EXTERNAL_API,message:"No session key",data:t}),this.sessionKey=(o=t==null?void 0:t.session_key)!=null?o:void 0,this.sessionKey}).catch(async t=>{this.sessionKey=void 0;let o=t==null?void 0:t.error_code;switch(o){case 401:return this.authToken=await this.refreshAuthToken(),this._authorizeWithBackoff()}o?this.params.error$.next({id:`Authorize#${o}`,category:I.ErrorCategory.EXTERNAL_API,message:"authorize error",data:t}):this.params.error$.next({id:"AuthorizeUnknown",category:I.ErrorCategory.NETWORK,message:"authorize error",thrown:t})}).finally(()=>{this.authorizePromise=void 0,this.consequentAuthErrors=this.sessionKey?0:this.consequentAuthErrors+1,this.authorized$.next(this.sessionKey!==void 0)}),this.authorizePromise}};var S=require("@vkontakte/videoplayer-shared");var T=class{constructor(e){this.params=e,this.apiKey=e.apiKey,this.apiEnv=e.config.apiEnv,this.apiBaseUrl=H[this.apiEnv],this.timeSynchronisation=e.timeSynchronisation,this.isApiBaseUrlFetched=!1}async resolveApiBaseUrl(){var e;if(this.apiEnv!=="auto"||this.isApiBaseUrlFetched)return this.apiBaseUrl;try{let i=atob("aHR0cHM6Ly9kbnMuZ29vZ2xlL3Jlc29sdmU/bmFtZT12aWRlby5fZW5kcG9pbnQub2sucnUmdHlwZT1UWFQ="),o=await(await fetch(i,{method:"GET",mode:"cors",cache:"no-cache"})).json(),r=(e=o==null?void 0:o.Answer[0])==null?void 0:e.data;if(!r)throw new Error("Wrong DNS response");return r}catch(i){return this.params.error$.next({id:"OneStat:ApiTransport:resolveApiBaseUrl",category:S.ErrorCategory.NETWORK,message:"Unhandled resolve api base url error",thrown:i}),H.vk_alias}finally{this.isApiBaseUrlFetched=!0}}sendBeacon(e,i,t){if(!window.Blob||!window.navigator.sendBeacon)return!1;let o=this._prepareQueryParams({method:e,queryParams:i,sessionKey:t}),r=new window.Blob([o.toString()],{type:"application/x-www-form-urlencoded"});try{return window.navigator.sendBeacon(`${this.apiBaseUrl}/fb.do`,r)}catch(d){this.params.error$.next({id:"OneStat:ApiTransport:sendBeacon",category:S.ErrorCategory.NETWORK,message:"Unhandled beacon error",thrown:d,data:{method:e,params:i}})}return!1}async sendRequest(e,i,t){let o=(0,S.now)(),r=d=>{if(d instanceof TypeError&&["Failed to fetch","NetworkError when attempting to fetch resource."].includes(d.message)){this.params.error$.next({id:"Network",category:S.ErrorCategory.NETWORK,message:"Request failed",thrown:d});return}this.params.error$.next({id:"OneStat:ApiTransport:sendRequest",category:S.ErrorCategory.NETWORK,message:"Unhandled request error",thrown:d,data:{method:e,params:i,sessionKey:t,time:(0,S.now)()-o}})};return this.apiBaseUrl=await this.resolveApiBaseUrl(),fetch(`${this.apiBaseUrl}/fb.do`,{method:"post",headers:{"Content-type":"application/x-www-form-urlencoded"},body:this._prepareQueryParams({method:e,queryParams:i,sessionKey:t})}).then(d=>{var g,m;let h=Number(d.headers.get("content-length"))===0,f=new Date((g=d.headers.get("date"))!=null?g:"").getTime(),c=(0,S.now)()-o;if(isFinite(f)&&((m=this.timeSynchronisation)==null||m.addServerTime(f,c)),!h)return d.json().then(s=>Object.prototype.hasOwnProperty.call(s,"error_msg")?Promise.reject(s):s,r)},r)}_prepareQueryParams(e){let i=new URLSearchParams({format:"JSON",method:e.method,application_key:this.apiKey});return e.sessionKey!==void 0&&i.append("session_key",e.sessionKey),Object.entries(e.queryParams).forEach(([t,o])=>i.append(t,typeof o=="string"?o:JSON.stringify(o))),i}};var v=require("@vkontakte/videoplayer-shared"),R="onestat_events",K=n=>e=>e.timestamp+n>=(0,v.now)(),O=class{constructor(e){this.unsaltedStorage=[];this.isPaused=!1;this.isUrgent=e=>{let{operation:i}=e;return["action_play","watch_coverage_record","watch_coverage_live"].includes(i)};this.params=e,this.api=e.api,this.error$=e.error$,this.userSalt=e.userSalt,this.loggerDebugLog=e.debugLogger.createComponentLog("stat logger"),this.firstFlush=(0,v.debounceFn)(()=>this.safeFlush(),this.params.config.firstFlushTime,{maxWait:this.params.config.firstFlushTime});let i=v.safeStorage.isPersistent()?this.params.config.flushMaxWait:0;this.debouncedFlush=(0,v.debounceFn)(()=>this.safeFlush(),this.params.config.flushDebounceTime,{maxWait:i}),this.subscription=this.api.authorized$.subscribe(t=>{t&&this.debouncedFlush()}),this.housekeepStorage()}safeFlush(){var e;try{this.flush()}catch(i){this.error$.next({id:"LoggerError",category:v.ErrorCategory.WTF,message:(e=String(i))!=null?e:"Unknown logger error",thrown:i})}}readFromStorage(){let e=v.safeStorage.get(R);try{return e?JSON.parse(e):{}}catch(i){}return{}}addToStorage(e){var r;if(!this.userSalt){this.unsaltedStorage.push(e);return}let i=this.readFromStorage(),o=((r=i[this.userSalt])!=null?r:[]).filter(K(this.params.config.storageExpiration));v.safeStorage.set(R,JSON.stringify({...i,[this.userSalt]:[...o,e]}))}getFromStorage(){var t;return this.userSalt?((t=this.readFromStorage()[this.userSalt])!=null?t:[]).filter(K(this.params.config.storageExpiration)):this.unsaltedStorage}markStorageSent(){if(!this.userSalt){this.unsaltedStorage=[];return}let e=this.readFromStorage();delete e[this.userSalt],v.safeStorage.set(R,JSON.stringify(e))}housekeepStorage(){let e=this.readFromStorage();for(let[i,t]of Object.entries(e)){let o=t.filter(K(this.params.config.storageExpiration));o.length?e[i]=o:delete e[i],this.loggerDebugLog({message:`${t.length} retrieved from storage, ${o.length} of them actual`})}v.safeStorage.set(R,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){let i=this.getFromStorage();i.length!==0&&(this.api.authorized$.getValue()?(e&&this.params.config.useBeacon?(this.loggerDebugLog({message:`Flushing ${i.length} events through beacon`}),this.api.logBeacon(i)):(this.loggerDebugLog({message:`Flushing ${i.length} events`}),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()}};var u=require("@vkontakte/videoplayer-core"),q=require("@vkontakte/videoplayer-shared");var se=n=>n&&{[u.VideoQuality.INVARIANT]:"unknown",[u.VideoQuality.Q_144P]:"mobile",[u.VideoQuality.Q_240P]:"lowest",[u.VideoQuality.Q_360P]:"low",[u.VideoQuality.Q_480P]:"medium",[u.VideoQuality.Q_720P]:"high",[u.VideoQuality.Q_1080P]:"fullhd",[u.VideoQuality.Q_1440P]:"quadhd",[u.VideoQuality.Q_2160P]:"ultrahd",[u.VideoQuality.Q_4320P]:"unknown"}[n],z=n=>n&&{[u.HttpConnectionType.HTTP1]:"http1",[u.HttpConnectionType.HTTP2]:"http2",[u.HttpConnectionType.QUIC]:"http3"}[n],re=n=>{if(n!==void 0)switch(n){case u.VideoFormat.MPEG:return"mp4";case u.VideoFormat.DASH:case u.VideoFormat.DASH_LIVE:case u.VideoFormat.DASH_STREAMS:return"dash";case u.VideoFormat.DASH_SEP:return"dash_sep";case u.VideoFormat.DASH_ONDEMAND:return"ondemand_dash";case u.VideoFormat.DASH_WEBM:case u.VideoFormat.DASH_LIVE_WEBM:return"webm";case u.VideoFormat.DASH_WEBM_AV1:return"av1";case u.VideoFormat.DASH_LIVE_CMAF:return"ondemand_dash_live";case u.VideoFormat.HLS:case u.VideoFormat.HLS_LIVE:return"hls";case u.VideoFormat.HLS_ONDEMAND:return"ondemand_hls";case u.VideoFormat.HLS_LIVE_CMAF:return"ondemand_hls_live";case u.VideoFormat.WEB_RTC_LIVE:return"webrtc";default:return(0,q.assertNever)(n)}},N=n=>{if(n!==void 0)switch(n){case u.Surface.NONE:case u.Surface.INLINE:return;case u.Surface.FULLSCREEN:return"fullscreen";case u.Surface.SECOND_SCREEN:return"chromecast";case u.Surface.PIP:return"pip";case u.Surface.INVISIBLE:return"invisible";default:return(0,q.assertNever)(n)}},ne=n=>{switch(n){case"slow-2g":return"poor";case"2g":return"poor";case"3g":return"good";case"4g":return"excellent"}};var D=class{constructor(e){this.offset=void 0;this.offset=e}getOffset(){var e;return(e=this.offset)!=null?e:0}setOffset(e){this.offset=e}now(){var e;return Date.now()+((e=this.offset)!=null?e:0)}date(e=new Date){var i;return e.setTime(e.getTime()+((i=this.offset)!=null?i:0)),e}addServerTime(e,i){let t=Date.now(),o=e-t-i/2;if(Math.abs(o)<1e3){this.offset=0;return}this.offset===void 0?this.offset=Math.round(o):this.offset=Math.round(.2*o+(1-.2)*this.offset)}};var ae=()=>Math.floor(Math.random()*4294967296).toString(36).padStart(7,"0"),de=()=>Math.floor(Math.random()*18446744073709552e3).toString(36).padStart(13,"0");var Q=require("@vkontakte/videoplayer-core"),p=require("@vkontakte/videoplayer-shared"),ue=(n,e)=>new p.Observable(i=>{let t=new p.Subscription,o=(0,p.merge)((0,p.fromEvent)(window,"beforeunload"),n.events.willDestruct$),r=new p.ValueSubject(void 0),d;t.add(n.info.isLive$.pipe((0,p.filterChanged)()).subscribe(P=>{d&&(d.unsubscribe(),r.next(void 0)),P?d=n.info.liveTime$.pipe((0,p.map)(F=>F&&F/1e3)).subscribe(r):d=n.info.position$.subscribe(r),t.add(d)}));let{playing$:h,paused$:f}=n.events,c=n.events.willSeek$.pipe((0,p.filter)(()=>n.info.playbackState$.getValue()===Q.PlaybackState.PLAYING)),g=n.events.seeked$.pipe((0,p.filter)(()=>n.info.playbackState$.getValue()===Q.PlaybackState.PLAYING)),m=!1,s=new p.Subject;t.add(c.subscribe(()=>{m||s.next(),m=!0})),t.add(g.subscribe(()=>m=!1));let l=new p.Subject,b=new p.Subject,y=(0,p.merge)(h,g,l),A=(0,p.merge)(f,s,o,n.events.looped$,b),E,ce=()=>E=r.getValue(),le=()=>{let P=r.getValue();(0,p.isNullable)(E)||E===P||(0,p.isNullable)(P)||(i.next({from:E,to:P}),E=void 0)},pe=()=>{b.next(),l.next()};if(t.add(y.subscribe(ce)),t.add(A.subscribe(le)),e.forceInterval&&isFinite(e.forceInterval)){let P=0;t.add(y.subscribe(()=>P=window.setTimeout(pe,e.forceInterval))),t.add(A.subscribe(()=>window.clearTimeout(P)))}return t});var ye="_one-stat_",j=`${ye}uuid`,G=()=>{let n=new a.Subscription;return{subscription:n,subscribe:(e,i)=>{e&&n.add(e.subscribe(i))}}},M=class{constructor(e,i){this.subscription=new a.Subscription;this.debugLogger=new B.Logger;this.oneStatDebugLog=this.debugLogger.createComponentLog("onestat");this.loopCounter=0;this.disabled=!1;this.vsid$=new a.ValueSubject(void 0);this.isid$=new a.ValueSubject(void 0);this.seekAction$=new a.ValueSubject("unknown");var f,c,g;this.statContext=e,this.config=te((f=i.config)!=null?f:{}),(0,a.isNonNullable)(i.apiEnv)&&(this.config.apiEnv=i.apiEnv),this.config.synchronizeTime&&(this.timeSynchronisation=new D);let t=new a.Subject;this.experimental={error$:t};let o=a.safeStorage.get(j);o?o.startsWith('"')&&o.endsWith('"')?(this.uuid=o.replaceAll('"',""),a.safeStorage.set(j,this.uuid)):this.uuid=o:(this.uuid=W(),a.safeStorage.set(j,this.uuid)),this.resetViewSession(),i.useIsid&&this.isid$.next((c=i.isid)!=null?c:de());let r=new T({apiKey:oe,config:this.config,error$:t,timeSynchronisation:this.timeSynchronisation});this.api=new C({config:this.config,apiTransport:r,refreshAuthToken:i.refreshAuthToken,mobile:(g=this.statContext.mobile)!=null?g:!1,uuid:this.uuid,error$:t}),this.logger=new O({config:this.config,debugLogger:this.debugLogger,api:this.api,error$:t,userSalt:i.userSalt});let{isEmbed:d,host:h}=(0,B.detectEmbed)();this.isEmbed=d,this.embedParent=h,this.subscribe()}updateContext(e){this.statContext={...this.statContext,...e}}attachTo(e){let i=new a.Subscription,t=(s,l)=>i.add(s.subscribe(l));t(e.events.willStart$,()=>{let s=e.info.position$.getValue();this.logActionPlay({position:s}),this.statContext.projectId&&this.logActionPlayInteractive()}),t(e.events.looped$,()=>{this.resetViewSession(),++this.loopCounter>this.config.maxLoops&&(this.disabled=!0),this.logActionPlay({position:e.info.position$.getValue()})}),t(e.events.seeked$,()=>{this.logSeek({action:this.seekAction$.getValue(),time:e.info.position$.getValue()}),this.seekAction$.next("unknown")}),t(e.events.paused$,()=>{this.logPause({position:e.info.position$.getValue()})}),t(e.events.willResume$,()=>{this.logPlay()}),t(e.events.started$,()=>{this.statContext.clip&&this.logWatchCoverageRecord({start:0,end:0})}),t(e.events.playing$,()=>{this.logPlaying()}),t(ue(e,{forceInterval:this.config.watchCoverageInterval}),s=>{let l=e.info.isLive$.getValue(),b={start:parseFloat(s.from.toFixed(3)),end:parseFloat(s.to.toFixed(3))};l?this.logWatchCoverageLive(b):this.logWatchCoverageRecord(b)});let o;t(e.info.isStalled$,s=>{s?o=(0,a.now)():((0,a.isNonNullable)(o)&&this.logEmptyBuffer({duration:(0,a.now)()-o}),o=void 0)});let r=!1;i.add(e.events.fatalError$.pipe((0,a.once)()).subscribe(()=>r=!0)),t(e.events.willStop$,()=>{if(e.info.isStalled$.getValue()){let l=(0,a.isNonNullable)(o)?(0,a.now)()-o:void 0;this.logCloseAtEmptyBuffer({duration:l!=null?l:0}),o=void 0}else r||this.logActionStop()}),t(e.events.managedError$,({id:s})=>{this.logError({fatal:!1,errorType:s})}),t(e.events.fatalError$,({id:s})=>{this.logError({fatal:!0,errorType:s})});let d,h,f=!1;t(e.events.firstBytes$,s=>{d=(0,a.now)(),this.logFirstBytes({time:s})}),t(e.events.willStart$,()=>h=(0,a.now)()),t(e.info.currentBuffer$,s=>{!f&&s&&s.end-s.start>0&&(0,a.isNonNullable)(d)&&(this.logPlayerReady({duration:(0,a.now)()-d}),f=!0)}),t(e.events.firstFrame$,()=>{(0,a.isNonNullable)(d)&&!f&&(this.logPlayerReady({duration:(0,a.now)()-d}),f=!0),(0,a.isNonNullable)(h)&&this.logFirstFrame({time:(0,a.now)()-h})});let c;t(e.info.currentVideoStream$,s=>{s&&(c&&s.id!==c&&this.logTrackSwitch(s),c=s.id)});let g;t(e.info.currentAudioStream$,s=>{s&&(g&&s.id!==g&&this.logTrackSwitch(s),g=s.id)}),t(e.info.atLiveEdge$,s=>this.updateContext({liveEdge:s})),t((0,a.combine)({muted:e.info.muted$,volume:e.info.volume$}),({muted:s,volume:l})=>this.updateContext({audible:!s&&l>0})),t(e.info.currentQuality$,s=>this.updateContext({quality:se(s)})),t(e.info.isAutoQualityEnabled$,s=>this.updateContext({autoQuality:s})),t(e.info.currentFormat$,s=>this.updateContext({contentType:re(s)})),t(e.info.currentPlaybackRate$,s=>this.updateContext({rate:s})),t(e.info.is3DVideo$,s=>this.updateContext({is3d:s}));let m;return t(e.info.hostname$,s=>{let l=m!==void 0&&m!==s;this.updateContext({cdnHostname:s,failover:l}),l&&this.logFailover(s),m=s}),t(e.info.throughputEstimation$,s=>this.updateContext({downloadSpeed:s})),t(e.info.httpConnectionType$,s=>{this.statContext.firstConnectionType||this.updateContext({firstConnectionType:z(s)}),this.updateContext({connectionType:z(s)})}),t(e.info.httpConnectionReused$,s=>{(0,a.isNullable)(this.statContext.firstConnectionReused)&&this.updateContext({firstConnectionReused:s}),this.updateContext({connectionReused:s})}),t(e.info.surface$,s=>this.updateContext({mode:N(s)})),t((0,a.combine)({current:e.info.currentTextTrack$,available:e.info.availableTextTracks$}),({current:s,available:l})=>{let b=l.find(({id:A})=>A===s),y=b&&(b.isAuto?`${b.language}_auto`:b.language);this.updateContext({subtitles:y})}),this.player=e,this.uiEvents&&this.attachToUi(this.uiEvents),this.resubscribeBeforeunload(),this.subscription.add(i),i}attachToUi(e){this.uiEvents=e;let{subscription:i,subscribe:t}=G();return this.player&&(t(e.actionRewind$,()=>{this.player&&(this.resetViewSession(),this.logActionPlay({position:this.player.info.position$.getValue()}))}),t(e.actionSeek$,this.seekAction$),t(e.inPiP$,o=>{var d;let r=o?"pip":N((d=this.player)==null?void 0:d.info.surface$.getValue());this.updateContext({mode:r})}),t(e.inFullscreen$,o=>{var d;let r=o?"fullscreen":N((d=this.player)==null?void 0:d.info.surface$.getValue());this.updateContext({mode:r})}),t(e.actionSetSubtitle$,o=>this.updateContext({subtitles:o})),t(e.nextMovie$,o=>this.logNextMovie(o)),this.resubscribeBeforeunload(),this.subscription.add(i)),i}attachToAds(e){let{subscription:i,subscribe:t}=G();return t(e.slotRequested$,()=>this.logAdSlotRequest()),t(e.started$,o=>this.logAdStarted(o)),t(e.paused$,()=>this.logAdPaused()),t(e.resumed$,()=>this.logAdResumed()),t(e.ended$,()=>this.logAdEnded()),t(e.skipped$,()=>this.logAdSkipped()),t(e.clicked$,()=>this.logAdClicked()),this.resubscribeBeforeunload(),this.subscription.add(i),i}attachToInteractive(e){let{subscription:i,subscribe:t}=G();return t(e.click$,o=>this.logInterfaceClick(o)),t(e.nextMovie$,o=>this.logNextMovie(o)),this.resubscribeBeforeunload(),this.subscription.add(i),i}authorize(e){return this.api.authorize(e)}pause(){this.logger.pause(),this.oneStatDebugLog({message:"paused"})}resume(){this.logger.resume(),this.oneStatDebugLog({message:"resumed"})}destroy(){this.logger.flush(),this.subscription.unsubscribe(),this.api.destroy(),this.logger.destroy()}resetViewSession(){this.oneStatDebugLog({message:"VSID reset"}),this.vsid$.next(ae())}getDeviceId(){return this.uuid}setFieldBlacklist(){}logInited(){}logReady(e){this.log({operation:"player_ready",param:String(e.time)})}logStarted(...e){this.logActionPlay(...e)}logPlay(){this.log({operation:"play_toggle"})}logPlaying(){this.log({operation:"playing"})}logPause(e){this.log({operation:"pause",param:String(Math.round(e.position))})}logSeek(e){this.log({operation:"seek",param:e.action,time:e.time})}logFirstBytes(e){this.log({operation:"first_bytes",param:String(e.time)})}logFirstFrame(e){this.log({operation:"first_frame",param:String(e.time)})}logError(e){this.log({operation:"content_error",param:`${e.fatal?"fatal":"recoverable"}_${e.errorType}`})}logWatchCoverageRecord(e){this.log({operation:"watch_coverage_record",param:`${e.start}-${e.end}`})}logWatchCoverageLive(e){var r,d;let i=(d=(r=this.timeSynchronisation)==null?void 0:r.getOffset())!=null?d:0,t=e.start+i,o=e.end+i;this.log({operation:"watch_coverage_live",param:`${t}-${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();let e=window.navigator.connection;e&&"onchange"in e&&"effectiveType"in e&&this.subscription.add((0,a.merge)((0,a.fromEvent)(e,"change"),(0,a.observableFrom)(["init"])).subscribe(()=>this.updateContext({network:ne(e.effectiveType)}))),this.config.debugLog&&this.debugLogger.log$.subscribe(i=>{console.debug("%c stat ","background:#fa6470;",`component: ${i.component}.`,i.message)})}resubscribeBeforeunload(){var e;(e=this.beforeunloadSubscription)==null||e.unsubscribe(),this.beforeunloadSubscription=(0,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))})}logActionPlayInteractive(){this.statContext.projectId&&this.log({operation:"action_play_interactive",param:String(this.statContext.movieId)},{vid:this.statContext.projectId})}logFailover(e){this.log({operation:"failover",param:e})}logCloseAtEmptyBuffer(e){this.log({operation:"close_at_empty_buffer",param:String(Math.round(e.duration))})}logActionStop(){this.log({operation:"action_stop"})}logTrackSwitch(e){this.log({operation:"track_switch",param:e.id})}log(e,i={}){if(this.disabled){this.oneStatDebugLog({message:`operation ${e.operation} but statistics is disabled`});return}if(this.config.disabledOperations.includes(e.operation)){this.oneStatDebugLog({message:`operation ${e.operation} but it is disabled`});return}this.oneStatDebugLog({message:`operation ${e.operation} ${e.param}`});let t=this.createLogItem(e,i);this.logger.log(t)}createLogItem({operation:e,param:i,time:t},o={}){var l,b;let r=(b=(l=this.timeSynchronisation)==null?void 0:l.now())!=null?b:(0,a.now)(),d=this.vsid$.getValue();(0,a.assertNonNullable)(d);let h=this.isid$.getValue(),f=e==="empty_buffer"||e==="close_at_empty_buffer"?this.statContext.connectionType:this.statContext.firstConnectionType,c=this.statContext.firstConnectionReused,g,m;if(this.isEmbed){g=this.embedParent;let y=[...new URLSearchParams(location.search).entries()].filter(([A,E])=>this.config.embedUrlParams.includes(A));m=new URLSearchParams(y).toString()}else this.statContext.place==="direct"&&((this.statContext.refDomain||document.referrer)&&(g=new URL(this.statContext.refDomain||document.referrer).hostname),m=location.href.substring(0,1024));let s={vsid:d,isid:h,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?"auto":this.statContext.autoplay===!1?"":void 0,param:i,vk_app_id:this.statContext.vkAppId,track_code:this.statContext.trackCode,connection_type:f,connection_reused:c===!0?1:c===!1?0:void 0,cached_data:this.statContext.cached===!0?1:this.statContext.cached===!1?0:void 0,live:this.statContext.liveEdge?1:void 0,muted:this.statContext.audible===!1?1:void 0,mode:this.statContext.mode,subtitles:this.statContext.subtitles,download_speed:this.statContext.downloadSpeed,manual_quality:this.statContext.autoQuality?void 0:1,ref_domain:g,direct_url:m,rate:this.statContext.rate===1||(0,a.isNullable)(this.statContext.rate)?void 0:this.statContext.rate.toFixed(2),view_360:this.statContext.is3d?1:void 0,aid:this.statContext.albumId,vk_playlist_id:this.statContext.vkPlaylistId,...o};for(let y of this.config.disabledCustomFields)delete s[y];return{operation:e,type:1,time:t,network:this.statContext.network,timestamp:r,custom:s}}};
6
+ "use strict";var V=Object.defineProperty;var he=Object.getOwnPropertyDescriptor;var fe=Object.getOwnPropertyNames;var ge=Object.prototype.hasOwnProperty;var me=(n,e)=>{for(var i in e)V(n,i,{get:e[i],enumerable:!0})},be=(n,e,i,t)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of fe(e))!ge.call(n,o)&&o!==i&&V(n,o,{get:()=>e[o],enumerable:!(t=he(e,o))||t.enumerable});return n};var ve=n=>be(V({},"__esModule",{value:!0}),n);var Pe={};me(Pe,{ApiEnv:()=>_,ConnectionType:()=>L,ContentType:()=>k,InteractiveInterfaceClick:()=>U,OneStat:()=>M,Quality:()=>w,SeekAction:()=>$,VERSION:()=>x});module.exports=ve(Pe);var _=(r=>(r.PROD="prod",r.VK_ALIAS="vk_alias",r.VIDEOTEST="videotest",r.TEST="test",r.AUTO="auto",r))(_||{}),w=(c=>(c.Q144P="mobile",c.Q240P="lowest",c.Q360P="low",c.Q480P="medium",c.Q720P="high",c.Q1080P="fullhd",c.Q1440P="quadhd",c.Q2160P="ultrahd",c.UNKNOWN="unknown",c))(w||{}),k=(l=>(l.MP4="mp4",l.DASH="dash",l.DASH_SEP="dash_sep",l.ONDEMAND_DASH="ondemand_dash",l.HLS="hls",l.ONDEMAND_HLS="ondemand_hls",l.WEBM="webm",l.AV1="av1",l.ONDEMAND_DASH_LIVE="ondemand_dash_live",l.ONDEMAND_HLS_LIVE="ondemand_hls_live",l.WEBRTC="webrtc",l.UNKNOWN="unknown",l.RTMP="rtmp",l))(k||{});var L=(t=>(t.HTTP1="http1",t.HTTP2="http2",t.HTTP3="http3",t))(L||{});var $=(h=>(h.SLIDER="slider",h.DOUBLE_TAP="double_tap",h.TIME_CODE="time_code",h.EPISODE="episode",h.REWIND="rewind",h.LIVE="live",h.UNKNOWN="unknown",h))($||{}),U=(r=>(r.GRAPH_SHOW="iGraphShow",r.GRAPH_HIDE="iGraphHide",r.NEXT_AREA="iNextChapterArea",r.NEXT_BUTTON="iNextChapterBtn",r.WATCH_AGAIN="iWatchAgainBtn",r))(U||{}),Y={action_play:"ap",action_play_interactive:"api",first_bytes:"fb",player_ready:"pr",first_frame:"ff",seek:"sk",watch_coverage_record:"wr",watch_coverage_live:"wl",empty_buffer:"eb",action_stop:"as",close_at_empty_buffer:"cb",content_error:"er",player_interface_click:"pc",next_movie:"nm",track_switch:"ts",failover:"fo"},X={vsid:"si",isid:"is",vid:"vi",place:"pl",quality:"qt",cdn_host:"ch",stat_type:"st",param:"pm",vk_app_id:"va",track_code:"tc",connection_type:"cnt",connection_reused:"cr",cached_data:"cd",live:"lv",muted:"mu",mode:"mo",subtitles:"sb",failover:"fo",download_speed:"ds",manual_quality:"mq",ref_domain:"rd",direct_url:"du"},J={unknown:"un",mobile:"m",lowest:"ls",low:"l",medium:"md",high:"h",fullhd:"f",quadhd:"q",ultrahd:"u"},Z={pip:"pi",fullscreen:"fs",external:"ex",prefetch:"pr",airplay:"ap",chromecast:"cc",invisible:"iv"};var ee=require("@vkontakte/videoplayer-shared"),Ie={apiEnv:"vk_alias",requestRetryCount:1,firstFlushTime:5e3,flushDebounceTime:1e4,flushMaxWait:6e4,storageExpiration:36*60*60*1e3,watchCoverageInterval:15e3,disabledOperations:[],disabledCustomFields:[],shorten:!0,maxLoops:100,embedUrlParams:[],useBeacon:!0,synchronizeTime:!0,debugLog:!1,backoff:{start:1e3,factor:1.5,max:5*60*1e3,random:.1}},te=n=>(0,ee.fillWithDefault)(n,Ie);function W(){let n="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".split(""),e=new Array(36),i=0,t,o;for(o=0;o<36;o++)o===8||o===13||o===18||o===23?e[o]="-":o===14?e[o]="4":(i<=2&&(i=33554432+Math.random()*16777216|0),t=i&15,i=i>>4,e[o]=n[o===19?t&3|8:t]);return e.join("")}var a=require("@vkontakte/videoplayer-shared"),B=require("@vkontakte/videoplayer-shared");var ie=n=>{var o;let{operation:e,custom:i}=n,t=Object.fromEntries(Object.entries(i).map(([r,d])=>{var c,g,m;let h=(c=X[r])!=null?c:r,f=d;return d&&(r==="mode"?f=(g=Z[d])!=null?g:d:r==="quality"&&(f=(m=J[d])!=null?m:d)),[h,f]}));return{...n,operation:(o=Y[e])!=null?o:e,custom:t}};var x="1.0.52-dev.a5f6699f.0",oe="CIOPGQJGDIHBABABA",H={prod:"https://api.ok.ru",vk_alias:"https://api.mycdn.me",videotest:"https://videotestapi.ok.ru/api",test:"https://apitest.ok.ru",auto:""};var I=require("@vkontakte/videoplayer-shared");var C=class{constructor(e){this.consequentAuthErrors=0;this.authorized$=new I.ValueSubject(!1);this.params=e}async authorize(e){return this.authToken=e!=null?e:await this.refreshAuthToken(),this._authorizeWithBackoff()}logBeacon(e){let i="log.externalLog",t=this.createLogParams(e),o=this.sessionKey;if(!o)return;this.params.apiTransport.sendBeacon(i,t,o)||this.logRequest(e)}async logRequest(e){var d;let i="log.externalLog",t=this.createLogParams(e),o=(d=this.sessionKey)!=null?d:await this._authorizeWithBackoff();if(!o)return;let r=async(h,f=this.params.config.requestRetryCount)=>{try{return await this.params.apiTransport.sendRequest(i,t,o)}catch(c){if(!c||!("error_code"in c)){this.params.error$.next({id:"logRequestUnknown",category:I.ErrorCategory.NETWORK,message:`Unknown ${i} error`,thrown:c});return}let g=c==null?void 0:c.error_code;switch(g){case 102:case 103:case 104:return this.authorized$.next(!1),this.sessionKey=await this._authorizeWithBackoff(),f>0?r(h,f-1):void 0;case 401:return this.authorized$.next(!1),this.authToken=await this.refreshAuthToken(),this.sessionKey=await this._authorizeWithBackoff(),f>0?r(h,f-1):void 0;default:{this.params.error$.next({id:`LogRequest#${g}`,category:I.ErrorCategory.EXTERNAL_API,message:`${i} error`,data:c});return}}}};return r(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:${x}`,platform:this.params.mobile?"M_WEB":"WEB",items:this.params.config.shorten?e.map(ie):e})}}_authorizeWithBackoff(){if(!this.consequentAuthErrors)return this._authorize();let e=(0,I.getExponentialDelay)(this.consequentAuthErrors,this.params.config.backoff);return new Promise(i=>{this.backoffTimeoutId||(this.backoffTimeoutId=window.setTimeout(()=>{this._authorize().then(i).catch(t=>this.params.error$.next({id:"AuthorizeBackoff",category:I.ErrorCategory.NETWORK,message:"Otherwise unhandled error in authorization",thrown:t})).finally(()=>this.backoffTimeoutId=0)},e))})}async _authorize(){if(this.authorizePromise)return this.authorizePromise;this.sessionKey=void 0,this.authorized$.next(!1);let e="auth.anonymLogin",i={session_data:{version:2,device_id:this.params.uuid,client_version:x.split("-")[0],client_type:"SDK_JS"}};return this.authToken!==void 0&&(i.session_data.auth_token=this.authToken,i.session_data.version=3),this.authorizePromise=this.params.apiTransport.sendRequest(e,i).then(t=>{var o;return(!t||!t.session_key)&&this.params.error$.next({id:"AuthorizeFailed",category:I.ErrorCategory.EXTERNAL_API,message:"No session key",data:t}),this.sessionKey=(o=t==null?void 0:t.session_key)!=null?o:void 0,this.sessionKey}).catch(async t=>{this.sessionKey=void 0;let o=t==null?void 0:t.error_code;switch(o){case 401:return this.authToken=await this.refreshAuthToken(),this._authorizeWithBackoff()}o?this.params.error$.next({id:`Authorize#${o}`,category:I.ErrorCategory.EXTERNAL_API,message:"authorize error",data:t}):this.params.error$.next({id:"AuthorizeUnknown",category:I.ErrorCategory.NETWORK,message:"authorize error",thrown:t})}).finally(()=>{this.authorizePromise=void 0,this.consequentAuthErrors=this.sessionKey?0:this.consequentAuthErrors+1,this.authorized$.next(this.sessionKey!==void 0)}),this.authorizePromise}};var S=require("@vkontakte/videoplayer-shared");var T=class{constructor(e){this.params=e,this.apiKey=e.apiKey,this.apiEnv=e.config.apiEnv,this.apiBaseUrl=H[this.apiEnv],this.timeSynchronisation=e.timeSynchronisation,this.isApiBaseUrlFetched=!1}async resolveApiBaseUrl(){var e;if(this.apiEnv!=="auto"||this.isApiBaseUrlFetched)return this.apiBaseUrl;try{let i=atob("aHR0cHM6Ly9kbnMuZ29vZ2xlL3Jlc29sdmU/bmFtZT12aWRlby5fZW5kcG9pbnQub2sucnUmdHlwZT1UWFQ="),o=await(await fetch(i,{method:"GET",mode:"cors",cache:"no-cache"})).json(),r=(e=o==null?void 0:o.Answer[0])==null?void 0:e.data;if(!r)throw new Error("Wrong DNS response");return r}catch(i){return this.params.error$.next({id:"OneStat:ApiTransport:resolveApiBaseUrl",category:S.ErrorCategory.NETWORK,message:"Unhandled resolve api base url error",thrown:i}),H.vk_alias}finally{this.isApiBaseUrlFetched=!0}}sendBeacon(e,i,t){if(!window.Blob||!window.navigator.sendBeacon)return!1;let o=this._prepareQueryParams({method:e,queryParams:i,sessionKey:t}),r=new window.Blob([o.toString()],{type:"application/x-www-form-urlencoded"});try{return window.navigator.sendBeacon(`${this.apiBaseUrl}/fb.do`,r)}catch(d){this.params.error$.next({id:"OneStat:ApiTransport:sendBeacon",category:S.ErrorCategory.NETWORK,message:"Unhandled beacon error",thrown:d,data:{method:e,params:i}})}return!1}async sendRequest(e,i,t){let o=(0,S.now)(),r=d=>{if(d instanceof TypeError&&["Failed to fetch","NetworkError when attempting to fetch resource."].includes(d.message)){this.params.error$.next({id:"Network",category:S.ErrorCategory.NETWORK,message:"Request failed",thrown:d});return}this.params.error$.next({id:"OneStat:ApiTransport:sendRequest",category:S.ErrorCategory.NETWORK,message:"Unhandled request error",thrown:d,data:{method:e,params:i,sessionKey:t,time:(0,S.now)()-o}})};return this.apiBaseUrl=await this.resolveApiBaseUrl(),fetch(`${this.apiBaseUrl}/fb.do`,{method:"post",headers:{"Content-type":"application/x-www-form-urlencoded"},body:this._prepareQueryParams({method:e,queryParams:i,sessionKey:t})}).then(d=>{var g,m;let h=Number(d.headers.get("content-length"))===0,f=new Date((g=d.headers.get("date"))!=null?g:"").getTime(),c=(0,S.now)()-o;if(isFinite(f)&&((m=this.timeSynchronisation)==null||m.addServerTime(f,c)),!h)return d.json().then(s=>Object.prototype.hasOwnProperty.call(s,"error_msg")?Promise.reject(s):s,r)},r)}_prepareQueryParams(e){let i=new URLSearchParams({format:"JSON",method:e.method,application_key:this.apiKey});return e.sessionKey!==void 0&&i.append("session_key",e.sessionKey),Object.entries(e.queryParams).forEach(([t,o])=>i.append(t,typeof o=="string"?o:JSON.stringify(o))),i}};var v=require("@vkontakte/videoplayer-shared"),R="onestat_events",K=n=>e=>e.timestamp+n>=(0,v.now)(),O=class{constructor(e){this.unsaltedStorage=[];this.isPaused=!1;this.isUrgent=e=>{let{operation:i}=e;return["action_play","watch_coverage_record","watch_coverage_live"].includes(i)};this.params=e,this.api=e.api,this.error$=e.error$,this.userSalt=e.userSalt,this.loggerDebugLog=e.debugLogger.createComponentLog("stat logger"),this.firstFlush=(0,v.debounceFn)(()=>this.safeFlush(),this.params.config.firstFlushTime,{maxWait:this.params.config.firstFlushTime});let i=v.safeStorage.isPersistent()?this.params.config.flushMaxWait:0;this.debouncedFlush=(0,v.debounceFn)(()=>this.safeFlush(),this.params.config.flushDebounceTime,{maxWait:i}),this.subscription=this.api.authorized$.subscribe(t=>{t&&this.debouncedFlush()}),this.housekeepStorage()}safeFlush(){var e;try{this.flush()}catch(i){this.error$.next({id:"LoggerError",category:v.ErrorCategory.WTF,message:(e=String(i))!=null?e:"Unknown logger error",thrown:i})}}readFromStorage(){let e=v.safeStorage.get(R);try{return e?JSON.parse(e):{}}catch(i){}return{}}addToStorage(e){var r;if(!this.userSalt){this.unsaltedStorage.push(e);return}let i=this.readFromStorage(),o=((r=i[this.userSalt])!=null?r:[]).filter(K(this.params.config.storageExpiration));v.safeStorage.set(R,JSON.stringify({...i,[this.userSalt]:[...o,e]}))}getFromStorage(){var t;return this.userSalt?((t=this.readFromStorage()[this.userSalt])!=null?t:[]).filter(K(this.params.config.storageExpiration)):this.unsaltedStorage}markStorageSent(){if(!this.userSalt){this.unsaltedStorage=[];return}let e=this.readFromStorage();delete e[this.userSalt],v.safeStorage.set(R,JSON.stringify(e))}housekeepStorage(){let e=this.readFromStorage();for(let[i,t]of Object.entries(e)){let o=t.filter(K(this.params.config.storageExpiration));o.length?e[i]=o:delete e[i],this.loggerDebugLog({message:`${t.length} retrieved from storage, ${o.length} of them actual`})}v.safeStorage.set(R,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){let i=this.getFromStorage();i.length!==0&&(this.api.authorized$.getValue()?(e&&this.params.config.useBeacon?(this.loggerDebugLog({message:`Flushing ${i.length} events through beacon`}),this.api.logBeacon(i)):(this.loggerDebugLog({message:`Flushing ${i.length} events`}),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()}};var u=require("@vkontakte/videoplayer-core"),q=require("@vkontakte/videoplayer-shared");var se=n=>n&&{[u.VideoQuality.INVARIANT]:"unknown",[u.VideoQuality.Q_144P]:"mobile",[u.VideoQuality.Q_240P]:"lowest",[u.VideoQuality.Q_360P]:"low",[u.VideoQuality.Q_480P]:"medium",[u.VideoQuality.Q_720P]:"high",[u.VideoQuality.Q_1080P]:"fullhd",[u.VideoQuality.Q_1440P]:"quadhd",[u.VideoQuality.Q_2160P]:"ultrahd",[u.VideoQuality.Q_4320P]:"unknown"}[n],z=n=>n&&{[u.HttpConnectionType.HTTP1]:"http1",[u.HttpConnectionType.HTTP2]:"http2",[u.HttpConnectionType.QUIC]:"http3"}[n],re=n=>{if(n!==void 0)switch(n){case u.VideoFormat.MPEG:return"mp4";case u.VideoFormat.DASH:case u.VideoFormat.DASH_LIVE:case u.VideoFormat.DASH_STREAMS:return"dash";case u.VideoFormat.DASH_SEP:return"dash_sep";case u.VideoFormat.DASH_ONDEMAND:return"ondemand_dash";case u.VideoFormat.DASH_WEBM:case u.VideoFormat.DASH_LIVE_WEBM:return"webm";case u.VideoFormat.DASH_WEBM_AV1:return"av1";case u.VideoFormat.DASH_LIVE_CMAF:return"ondemand_dash_live";case u.VideoFormat.HLS:case u.VideoFormat.HLS_LIVE:return"hls";case u.VideoFormat.HLS_ONDEMAND:return"ondemand_hls";case u.VideoFormat.HLS_LIVE_CMAF:return"ondemand_hls_live";case u.VideoFormat.WEB_RTC_LIVE:return"webrtc";default:return(0,q.assertNever)(n)}},N=n=>{if(n!==void 0)switch(n){case u.Surface.NONE:case u.Surface.INLINE:return;case u.Surface.FULLSCREEN:return"fullscreen";case u.Surface.SECOND_SCREEN:return"chromecast";case u.Surface.PIP:return"pip";case u.Surface.INVISIBLE:return"invisible";default:return(0,q.assertNever)(n)}},ne=n=>{switch(n){case"slow-2g":return"poor";case"2g":return"poor";case"3g":return"good";case"4g":return"excellent"}};var D=class{constructor(e){this.offset=void 0;this.offset=e}getOffset(){var e;return(e=this.offset)!=null?e:0}setOffset(e){this.offset=e}now(){var e;return Date.now()+((e=this.offset)!=null?e:0)}date(e=new Date){var i;return e.setTime(e.getTime()+((i=this.offset)!=null?i:0)),e}addServerTime(e,i){let t=Date.now(),o=e-t-i/2;if(Math.abs(o)<1e3){this.offset=0;return}this.offset===void 0?this.offset=Math.round(o):this.offset=Math.round(.2*o+(1-.2)*this.offset)}};var ae=()=>Math.floor(Math.random()*4294967296).toString(36).padStart(7,"0"),de=()=>Math.floor(Math.random()*18446744073709552e3).toString(36).padStart(13,"0");var Q=require("@vkontakte/videoplayer-core"),p=require("@vkontakte/videoplayer-shared"),ue=(n,e)=>new p.Observable(i=>{let t=new p.Subscription,o=(0,p.merge)((0,p.fromEvent)(window,"beforeunload"),n.events.willDestruct$),r=new p.ValueSubject(void 0),d;t.add(n.info.isLive$.pipe((0,p.filterChanged)()).subscribe(P=>{d&&(d.unsubscribe(),r.next(void 0)),P?d=n.info.liveTime$.pipe((0,p.map)(F=>F&&F/1e3)).subscribe(r):d=n.info.position$.subscribe(r),t.add(d)}));let{playing$:h,paused$:f}=n.events,c=n.events.willSeek$.pipe((0,p.filter)(()=>n.info.playbackState$.getValue()===Q.PlaybackState.PLAYING)),g=n.events.seeked$.pipe((0,p.filter)(()=>n.info.playbackState$.getValue()===Q.PlaybackState.PLAYING)),m=!1,s=new p.Subject;t.add(c.subscribe(()=>{m||s.next(),m=!0})),t.add(g.subscribe(()=>m=!1));let l=new p.Subject,b=new p.Subject,y=(0,p.merge)(h,g,l),A=(0,p.merge)(f,s,o,n.events.looped$,b),E,ce=()=>E=r.getValue(),le=()=>{let P=r.getValue();(0,p.isNullable)(E)||E===P||(0,p.isNullable)(P)||(i.next({from:E,to:P}),E=void 0)},pe=()=>{b.next(),l.next()};if(t.add(y.subscribe(ce)),t.add(A.subscribe(le)),e.forceInterval&&isFinite(e.forceInterval)){let P=0;t.add(y.subscribe(()=>P=window.setTimeout(pe,e.forceInterval))),t.add(A.subscribe(()=>window.clearTimeout(P)))}return t});var ye="_one-stat_",j=`${ye}uuid`,G=()=>{let n=new a.Subscription;return{subscription:n,subscribe:(e,i)=>{e&&n.add(e.subscribe(i))}}},M=class{constructor(e,i){this.subscription=new a.Subscription;this.debugLogger=new B.Logger;this.oneStatDebugLog=this.debugLogger.createComponentLog("onestat");this.loopCounter=0;this.disabled=!1;this.vsid$=new a.ValueSubject(void 0);this.isid$=new a.ValueSubject(void 0);this.seekAction$=new a.ValueSubject("unknown");var f,c,g;this.statContext=e,this.config=te((f=i.config)!=null?f:{}),(0,a.isNonNullable)(i.apiEnv)&&(this.config.apiEnv=i.apiEnv),this.config.synchronizeTime&&(this.timeSynchronisation=new D);let t=new a.Subject;this.experimental={error$:t};let o=a.safeStorage.get(j);o?o.startsWith('"')&&o.endsWith('"')?(this.uuid=o.replaceAll('"',""),a.safeStorage.set(j,this.uuid)):this.uuid=o:(this.uuid=W(),a.safeStorage.set(j,this.uuid)),this.resetViewSession(),i.useIsid&&this.isid$.next((c=i.isid)!=null?c:de());let r=new T({apiKey:oe,config:this.config,error$:t,timeSynchronisation:this.timeSynchronisation});this.api=new C({config:this.config,apiTransport:r,refreshAuthToken:i.refreshAuthToken,mobile:(g=this.statContext.mobile)!=null?g:!1,uuid:this.uuid,error$:t}),this.logger=new O({config:this.config,debugLogger:this.debugLogger,api:this.api,error$:t,userSalt:i.userSalt});let{isEmbed:d,host:h}=(0,B.detectEmbed)();this.isEmbed=d,this.embedParent=h,this.subscribe()}updateContext(e){this.statContext={...this.statContext,...e}}attachTo(e){let i=new a.Subscription,t=(s,l)=>i.add(s.subscribe(l));t(e.events.willStart$,()=>{let s=e.info.position$.getValue();this.logActionPlay({position:s}),this.statContext.projectId&&this.logActionPlayInteractive()}),t(e.events.looped$,()=>{this.resetViewSession(),++this.loopCounter>this.config.maxLoops&&(this.disabled=!0),this.logActionPlay({position:e.info.position$.getValue()})}),t(e.events.seeked$,()=>{this.logSeek({action:this.seekAction$.getValue(),time:e.info.position$.getValue()}),this.seekAction$.next("unknown")}),t(e.events.paused$,()=>{this.logPause({position:e.info.position$.getValue()})}),t(e.events.willResume$,()=>{this.logPlay()}),t(e.events.started$,()=>{this.statContext.clip&&this.logWatchCoverageRecord({start:0,end:0})}),t(e.events.playing$,()=>{this.logPlaying()}),t(ue(e,{forceInterval:this.config.watchCoverageInterval}),s=>{let l=e.info.isLive$.getValue(),b={start:parseFloat(s.from.toFixed(3)),end:parseFloat(s.to.toFixed(3))};l?this.logWatchCoverageLive(b):this.logWatchCoverageRecord(b)});let o;t(e.info.isStalled$,s=>{s?o=(0,a.now)():((0,a.isNonNullable)(o)&&this.logEmptyBuffer({duration:(0,a.now)()-o}),o=void 0)});let r=!1;i.add(e.events.fatalError$.pipe((0,a.once)()).subscribe(()=>r=!0)),t(e.events.willStop$,()=>{if(e.info.isStalled$.getValue()){let l=(0,a.isNonNullable)(o)?(0,a.now)()-o:void 0;this.logCloseAtEmptyBuffer({duration:l!=null?l:0}),o=void 0}else r||this.logActionStop()}),t(e.events.managedError$,({id:s})=>{this.logError({fatal:!1,errorType:s})}),t(e.events.fatalError$,({id:s})=>{this.logError({fatal:!0,errorType:s})});let d,h,f=!1;t(e.events.firstBytes$,s=>{d=(0,a.now)(),this.logFirstBytes({time:s})}),t(e.events.willStart$,()=>h=(0,a.now)()),t(e.info.currentBuffer$,s=>{!f&&s&&s.end-s.start>0&&(0,a.isNonNullable)(d)&&(this.logPlayerReady({duration:(0,a.now)()-d}),f=!0)}),t(e.events.firstFrame$,()=>{(0,a.isNonNullable)(d)&&!f&&(this.logPlayerReady({duration:(0,a.now)()-d}),f=!0),(0,a.isNonNullable)(h)&&this.logFirstFrame({time:(0,a.now)()-h})});let c;t(e.info.currentVideoStream$,s=>{s&&(c&&s.id!==c&&this.logTrackSwitch(s),c=s.id)});let g;t(e.info.currentAudioStream$,s=>{s&&(g&&s.id!==g&&this.logTrackSwitch(s),g=s.id)}),t(e.info.atLiveEdge$,s=>this.updateContext({liveEdge:s})),t((0,a.combine)({muted:e.info.muted$,volume:e.info.volume$}),({muted:s,volume:l})=>this.updateContext({audible:!s&&l>0})),t(e.info.currentQuality$,s=>this.updateContext({quality:se(s)})),t(e.info.isAutoQualityEnabled$,s=>this.updateContext({autoQuality:s})),t(e.info.currentFormat$,s=>this.updateContext({contentType:re(s)})),t(e.info.currentPlaybackRate$,s=>this.updateContext({rate:s})),t(e.info.is3DVideo$,s=>this.updateContext({is3d:s}));let m;return t(e.info.hostname$,s=>{let l=m!==void 0&&m!==s;this.updateContext({cdnHostname:s,failover:l}),l&&this.logFailover(s),m=s}),t(e.info.throughputEstimation$,s=>this.updateContext({downloadSpeed:s})),t(e.info.httpConnectionType$,s=>{this.statContext.firstConnectionType||this.updateContext({firstConnectionType:z(s)}),this.updateContext({connectionType:z(s)})}),t(e.info.httpConnectionReused$,s=>{(0,a.isNullable)(this.statContext.firstConnectionReused)&&this.updateContext({firstConnectionReused:s}),this.updateContext({connectionReused:s})}),t(e.info.surface$,s=>this.updateContext({mode:N(s)})),t((0,a.combine)({current:e.info.currentTextTrack$,available:e.info.availableTextTracks$}),({current:s,available:l})=>{let b=l.find(({id:A})=>A===s),y=b&&(b.isAuto?`${b.language}_auto`:b.language);this.updateContext({subtitles:y})}),this.player=e,this.uiEvents&&this.attachToUi(this.uiEvents),this.resubscribeBeforeunload(),this.subscription.add(i),i}attachToUi(e){this.uiEvents=e;let{subscription:i,subscribe:t}=G();return this.player&&(t(e.actionRewind$,()=>{this.player&&(this.resetViewSession(),this.logActionPlay({position:this.player.info.position$.getValue()}))}),t(e.actionSeek$,this.seekAction$),t(e.inPiP$,o=>{var d;let r=o?"pip":N((d=this.player)==null?void 0:d.info.surface$.getValue());this.updateContext({mode:r})}),t(e.inFullscreen$,o=>{var d;let r=o?"fullscreen":N((d=this.player)==null?void 0:d.info.surface$.getValue());this.updateContext({mode:r})}),t(e.actionSetSubtitle$,o=>this.updateContext({subtitles:o})),t(e.nextMovie$,o=>this.logNextMovie(o)),this.resubscribeBeforeunload(),this.subscription.add(i)),i}attachToAds(e){let{subscription:i,subscribe:t}=G();return t(e.slotRequested$,()=>this.logAdSlotRequest()),t(e.started$,o=>this.logAdStarted(o)),t(e.paused$,()=>this.logAdPaused()),t(e.resumed$,()=>this.logAdResumed()),t(e.ended$,()=>this.logAdEnded()),t(e.skipped$,()=>this.logAdSkipped()),t(e.clicked$,()=>this.logAdClicked()),this.resubscribeBeforeunload(),this.subscription.add(i),i}attachToInteractive(e){let{subscription:i,subscribe:t}=G();return t(e.click$,o=>this.logInterfaceClick(o)),t(e.nextMovie$,o=>this.logNextMovie(o)),this.resubscribeBeforeunload(),this.subscription.add(i),i}authorize(e){return this.api.authorize(e)}pause(){this.logger.pause(),this.oneStatDebugLog({message:"paused"})}resume(){this.logger.resume(),this.oneStatDebugLog({message:"resumed"})}destroy(){this.logger.flush(),this.subscription.unsubscribe(),this.api.destroy(),this.logger.destroy()}resetViewSession(){this.oneStatDebugLog({message:"VSID reset"}),this.vsid$.next(ae())}getDeviceId(){return this.uuid}setFieldBlacklist(){}logInited(){}logReady(e){this.log({operation:"player_ready",param:String(e.time)})}logStarted(...e){this.logActionPlay(...e)}logPlay(){this.log({operation:"play_toggle"})}logPlaying(){this.log({operation:"playing"})}logPause(e){this.log({operation:"pause",param:String(Math.round(e.position))})}logSeek(e){this.log({operation:"seek",param:e.action,time:e.time})}logFirstBytes(e){this.log({operation:"first_bytes",param:String(e.time)})}logFirstFrame(e){this.log({operation:"first_frame",param:String(e.time)})}logError(e){this.log({operation:"content_error",param:`${e.fatal?"fatal":"recoverable"}_${e.errorType}`})}logWatchCoverageRecord(e){this.log({operation:"watch_coverage_record",param:`${e.start}-${e.end}`})}logWatchCoverageLive(e){var r,d;let i=(d=(r=this.timeSynchronisation)==null?void 0:r.getOffset())!=null?d:0,t=e.start+i,o=e.end+i;this.log({operation:"watch_coverage_live",param:`${t}-${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();let e=window.navigator.connection;e&&"onchange"in e&&"effectiveType"in e&&this.subscription.add((0,a.merge)((0,a.fromEvent)(e,"change"),(0,a.observableFrom)(["init"])).subscribe(()=>this.updateContext({network:ne(e.effectiveType)}))),this.config.debugLog&&this.debugLogger.log$.subscribe(i=>{console.debug("%c stat ","background:#fa6470;",`component: ${i.component}.`,i.message)})}resubscribeBeforeunload(){var e;(e=this.beforeunloadSubscription)==null||e.unsubscribe(),this.beforeunloadSubscription=(0,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))})}logActionPlayInteractive(){this.statContext.projectId&&this.log({operation:"action_play_interactive",param:String(this.statContext.movieId)},{vid:this.statContext.projectId})}logFailover(e){this.log({operation:"failover",param:e})}logCloseAtEmptyBuffer(e){this.log({operation:"close_at_empty_buffer",param:String(Math.round(e.duration))})}logActionStop(){this.log({operation:"action_stop"})}logTrackSwitch(e){this.log({operation:"track_switch",param:e.id})}log(e,i={}){if(this.disabled){this.oneStatDebugLog({message:`operation ${e.operation} but statistics is disabled`});return}if(this.config.disabledOperations.includes(e.operation)){this.oneStatDebugLog({message:`operation ${e.operation} but it is disabled`});return}this.oneStatDebugLog({message:`operation ${e.operation} ${e.param}`});let t=this.createLogItem(e,i);this.logger.log(t)}createLogItem({operation:e,param:i,time:t},o={}){var l,b;let r=(b=(l=this.timeSynchronisation)==null?void 0:l.now())!=null?b:(0,a.now)(),d=this.vsid$.getValue();(0,a.assertNonNullable)(d);let h=this.isid$.getValue(),f=e==="empty_buffer"||e==="close_at_empty_buffer"?this.statContext.connectionType:this.statContext.firstConnectionType,c=this.statContext.firstConnectionReused,g,m;if(this.isEmbed){g=this.embedParent;let y=[...new URLSearchParams(location.search).entries()].filter(([A,E])=>this.config.embedUrlParams.includes(A));m=new URLSearchParams(y).toString()}else this.statContext.place==="direct"&&((this.statContext.refDomain||document.referrer)&&(g=new URL(this.statContext.refDomain||document.referrer).hostname),m=location.href.substring(0,1024));let s={vsid:d,isid:h,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?"auto":this.statContext.autoplay===!1?"":void 0,param:i,vk_app_id:this.statContext.vkAppId,track_code:this.statContext.trackCode,connection_type:f,connection_reused:c===!0?1:c===!1?0:void 0,cached_data:this.statContext.cached===!0?1:this.statContext.cached===!1?0:void 0,live:this.statContext.liveEdge?1:void 0,muted:this.statContext.audible===!1?1:void 0,mode:this.statContext.mode,subtitles:this.statContext.subtitles,download_speed:this.statContext.downloadSpeed,manual_quality:this.statContext.autoQuality?void 0:1,ref_domain:g,direct_url:m,rate:this.statContext.rate===1||(0,a.isNullable)(this.statContext.rate)?void 0:this.statContext.rate.toFixed(2),view_360:this.statContext.is3d?1:void 0,aid:this.statContext.albumId,vk_playlist_id:this.statContext.vkPlaylistId,...o};for(let y of this.config.disabledCustomFields)delete s[y];return{operation:e,type:1,time:t,network:this.statContext.network,timestamp:r,custom:s}}};
package/es2018.esm.js CHANGED
@@ -1,6 +1,6 @@
1
1
  /**
2
- * @vkontakte/videoplayer-statistics v1.0.52-dev.22c05d5f.0
3
- * Tue, 30 Jul 2024 08:28:10 GMT
2
+ * @vkontakte/videoplayer-statistics v1.0.52-dev.a5f6699f.0
3
+ * Tue, 30 Jul 2024 10:43:01 GMT
4
4
  * https://st.mycdn.me/static/vkontakte-videoplayer/1-0-52/doc/
5
5
  */
6
- var _=(r=>(r.PROD="prod",r.VK_ALIAS="vk_alias",r.VIDEOTEST="videotest",r.TEST="test",r.AUTO="auto",r))(_||{}),D=(d=>(d.Q144P="mobile",d.Q240P="lowest",d.Q360P="low",d.Q480P="medium",d.Q720P="high",d.Q1080P="fullhd",d.Q1440P="quadhd",d.Q2160P="ultrahd",d.UNKNOWN="unknown",d))(D||{}),M=(u=>(u.MP4="mp4",u.DASH="dash",u.DASH_SEP="dash_sep",u.ONDEMAND_DASH="ondemand_dash",u.HLS="hls",u.ONDEMAND_HLS="ondemand_hls",u.WEBM="webm",u.AV1="av1",u.ONDEMAND_DASH_LIVE="ondemand_dash_live",u.ONDEMAND_HLS_LIVE="ondemand_hls_live",u.WEBRTC="webrtc",u.UNKNOWN="unknown",u.RTMP="rtmp",u))(M||{});var B=(t=>(t.HTTP1="http1",t.HTTP2="http2",t.HTTP3="http3",t))(B||{});var F=(c=>(c.SLIDER="slider",c.DOUBLE_TAP="double_tap",c.TIME_CODE="time_code",c.EPISODE="episode",c.REWIND="rewind",c.LIVE="live",c.UNKNOWN="unknown",c))(F||{}),ee=(r=>(r.GRAPH_SHOW="iGraphShow",r.GRAPH_HIDE="iGraphHide",r.NEXT_AREA="iNextChapterArea",r.NEXT_BUTTON="iNextChapterBtn",r.WATCH_AGAIN="iWatchAgainBtn",r))(ee||{}),te={action_play:"ap",action_play_interactive:"api",first_bytes:"fb",player_ready:"pr",first_frame:"ff",seek:"sk",watch_coverage_record:"wr",watch_coverage_live:"wl",empty_buffer:"eb",action_stop:"as",close_at_empty_buffer:"cb",content_error:"er",player_interface_click:"pc",next_movie:"nm",track_switch:"ts",failover:"fo"},ie={vsid:"si",isid:"is",vid:"vi",place:"pl",quality:"qt",cdn_host:"ch",stat_type:"st",param:"pm",vk_app_id:"va",track_code:"tc",connection_type:"cnt",connection_reused:"cr",cached_data:"cd",live:"lv",muted:"mu",mode:"mo",subtitles:"sb",failover:"fo",download_speed:"ds",manual_quality:"mq",ref_domain:"rd",direct_url:"du"},oe={unknown:"un",mobile:"m",lowest:"ls",low:"l",medium:"md",high:"h",fullhd:"f",quadhd:"q",ultrahd:"u"},se={pip:"pi",fullscreen:"fs",external:"ex",prefetch:"pr",airplay:"ap",chromecast:"cc",invisible:"iv"};import{fillWithDefault as _e}from"@vkontakte/videoplayer-shared";var xe={apiEnv:"vk_alias",requestRetryCount:1,firstFlushTime:5e3,flushDebounceTime:1e4,flushMaxWait:6e4,storageExpiration:36*60*60*1e3,watchCoverageInterval:15e3,disabledOperations:[],disabledCustomFields:[],shorten:!0,maxLoops:100,embedUrlParams:[],useBeacon:!0,synchronizeTime:!0,debugLog:!1,backoff:{start:1e3,factor:1.5,max:5*60*1e3,random:.1}},re=a=>_e(a,xe);function V(){let a="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".split(""),e=new Array(36),i=0,t,o;for(o=0;o<36;o++)o===8||o===13||o===18||o===23?e[o]="-":o===14?e[o]="4":(i<=2&&(i=33554432+Math.random()*16777216|0),t=i&15,i=i>>4,e[o]=a[o===19?t&3|8:t]);return e.join("")}import{assertNonNullable as Be,combine as Ie,fromEvent as Se,isNonNullable as E,isNullable as ye,merge as Fe,now as b,observableFrom as Ve,once as Ue,safeStorage as j,Subject as We,Subscription as J,ValueSubject as G}from"@vkontakte/videoplayer-shared";import{Logger as He,detectEmbed as Ke}from"@vkontakte/videoplayer-shared";var ne=a=>{var o;let{operation:e,custom:i}=a,t=Object.fromEntries(Object.entries(i).map(([r,n])=>{var d,p,h;let c=(d=ie[r])!=null?d:r,l=n;return n&&(r==="mode"?l=(p=se[n])!=null?p:n:r==="quality"&&(l=(h=oe[n])!=null?h:n)),[c,l]}));return{...a,operation:(o=te[e])!=null?o:e,custom:t}};var w="1.0.52-dev.22c05d5f.0",ae="CIOPGQJGDIHBABABA",U={prod:"https://api.ok.ru",vk_alias:"https://api.mycdn.me",videotest:"https://videotestapi.ok.ru/api",test:"https://apitest.ok.ru",auto:""};import{ValueSubject as Ce,getExponentialDelay as Te,ErrorCategory as P}from"@vkontakte/videoplayer-shared";var x=class{constructor(e){this.consequentAuthErrors=0;this.authorized$=new Ce(!1);this.params=e}async authorize(e){return this.authToken=e!=null?e:await this.refreshAuthToken(),this._authorizeWithBackoff()}logBeacon(e){let i="log.externalLog",t=this.createLogParams(e),o=this.sessionKey;if(!o)return;this.params.apiTransport.sendBeacon(i,t,o)||this.logRequest(e)}async logRequest(e){var n;let i="log.externalLog",t=this.createLogParams(e),o=(n=this.sessionKey)!=null?n:await this._authorizeWithBackoff();if(!o)return;let r=async(c,l=this.params.config.requestRetryCount)=>{try{return await this.params.apiTransport.sendRequest(i,t,o)}catch(d){if(!d||!("error_code"in d)){this.params.error$.next({id:"logRequestUnknown",category:P.NETWORK,message:`Unknown ${i} error`,thrown:d});return}let p=d==null?void 0:d.error_code;switch(p){case 102:case 103:case 104:return this.authorized$.next(!1),this.sessionKey=await this._authorizeWithBackoff(),l>0?r(c,l-1):void 0;case 401:return this.authorized$.next(!1),this.authToken=await this.refreshAuthToken(),this.sessionKey=await this._authorizeWithBackoff(),l>0?r(c,l-1):void 0;default:{this.params.error$.next({id:`LogRequest#${p}`,category:P.EXTERNAL_API,message:`${i} error`,data:d});return}}}};return r(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:${w}`,platform:this.params.mobile?"M_WEB":"WEB",items:this.params.config.shorten?e.map(ne):e})}}_authorizeWithBackoff(){if(!this.consequentAuthErrors)return this._authorize();let e=Te(this.consequentAuthErrors,this.params.config.backoff);return new Promise(i=>{this.backoffTimeoutId||(this.backoffTimeoutId=window.setTimeout(()=>{this._authorize().then(i).catch(t=>this.params.error$.next({id:"AuthorizeBackoff",category:P.NETWORK,message:"Otherwise unhandled error in authorization",thrown:t})).finally(()=>this.backoffTimeoutId=0)},e))})}async _authorize(){if(this.authorizePromise)return this.authorizePromise;this.sessionKey=void 0,this.authorized$.next(!1);let e="auth.anonymLogin",i={session_data:{version:2,device_id:this.params.uuid,client_version:w.split("-")[0],client_type:"SDK_JS"}};return this.authToken!==void 0&&(i.session_data.auth_token=this.authToken,i.session_data.version=3),this.authorizePromise=this.params.apiTransport.sendRequest(e,i).then(t=>{var o;return(!t||!t.session_key)&&this.params.error$.next({id:"AuthorizeFailed",category:P.EXTERNAL_API,message:"No session key",data:t}),this.sessionKey=(o=t==null?void 0:t.session_key)!=null?o:void 0,this.sessionKey}).catch(async t=>{this.sessionKey=void 0;let o=t==null?void 0:t.error_code;switch(o){case 401:return this.authToken=await this.refreshAuthToken(),this._authorizeWithBackoff()}o?this.params.error$.next({id:`Authorize#${o}`,category:P.EXTERNAL_API,message:"authorize error",data:t}):this.params.error$.next({id:"AuthorizeUnknown",category:P.NETWORK,message:"authorize error",thrown:t})}).finally(()=>{this.authorizePromise=void 0,this.consequentAuthErrors=this.sessionKey?0:this.consequentAuthErrors+1,this.authorized$.next(this.sessionKey!==void 0)}),this.authorizePromise}};import{ErrorCategory as k,now as W}from"@vkontakte/videoplayer-shared";var C=class{constructor(e){this.params=e,this.apiKey=e.apiKey,this.apiEnv=e.config.apiEnv,this.apiBaseUrl=U[this.apiEnv],this.timeSynchronisation=e.timeSynchronisation,this.isApiBaseUrlFetched=!1}async resolveApiBaseUrl(){var e;if(this.apiEnv!=="auto"||this.isApiBaseUrlFetched)return this.apiBaseUrl;try{let i=atob("aHR0cHM6Ly9kbnMuZ29vZ2xlL3Jlc29sdmU/bmFtZT12aWRlby5fZW5kcG9pbnQub2sucnUmdHlwZT1UWFQ="),o=await(await fetch(i,{method:"GET",mode:"cors",cache:"no-cache"})).json(),r=(e=o==null?void 0:o.Answer[0])==null?void 0:e.data;if(!r)throw new Error("Wrong DNS response");return r}catch(i){return this.params.error$.next({id:"OneStat:ApiTransport:resolveApiBaseUrl",category:k.NETWORK,message:"Unhandled resolve api base url error",thrown:i}),U.vk_alias}finally{this.isApiBaseUrlFetched=!0}}sendBeacon(e,i,t){if(!window.Blob||!window.navigator.sendBeacon)return!1;let o=this._prepareQueryParams({method:e,queryParams:i,sessionKey:t}),r=new window.Blob([o.toString()],{type:"application/x-www-form-urlencoded"});try{return window.navigator.sendBeacon(`${this.apiBaseUrl}/fb.do`,r)}catch(n){this.params.error$.next({id:"OneStat:ApiTransport:sendBeacon",category:k.NETWORK,message:"Unhandled beacon error",thrown:n,data:{method:e,params:i}})}return!1}async sendRequest(e,i,t){let o=W(),r=n=>{if(n instanceof TypeError&&["Failed to fetch","NetworkError when attempting to fetch resource."].includes(n.message)){this.params.error$.next({id:"Network",category:k.NETWORK,message:"Request failed",thrown:n});return}this.params.error$.next({id:"OneStat:ApiTransport:sendRequest",category:k.NETWORK,message:"Unhandled request error",thrown:n,data:{method:e,params:i,sessionKey:t,time:W()-o}})};return this.apiBaseUrl=await this.resolveApiBaseUrl(),fetch(`${this.apiBaseUrl}/fb.do`,{method:"post",headers:{"Content-type":"application/x-www-form-urlencoded"},body:this._prepareQueryParams({method:e,queryParams:i,sessionKey:t})}).then(n=>{var p,h;let c=Number(n.headers.get("content-length"))===0,l=new Date((p=n.headers.get("date"))!=null?p:"").getTime(),d=W()-o;if(isFinite(l)&&((h=this.timeSynchronisation)==null||h.addServerTime(l,d)),!c)return n.json().then(s=>Object.prototype.hasOwnProperty.call(s,"error_msg")?Promise.reject(s):s,r)},r)}_prepareQueryParams(e){let i=new URLSearchParams({format:"JSON",method:e.method,application_key:this.apiKey});return e.sessionKey!==void 0&&i.append("session_key",e.sessionKey),Object.entries(e.queryParams).forEach(([t,o])=>i.append(t,typeof o=="string"?o:JSON.stringify(o))),i}};import{ErrorCategory as we,now as ke,safeStorage as T,debounceFn as de}from"@vkontakte/videoplayer-shared";var L="onestat_events",H=a=>e=>e.timestamp+a>=ke(),$=class{constructor(e){this.unsaltedStorage=[];this.isPaused=!1;this.isUrgent=e=>{let{operation:i}=e;return["action_play","watch_coverage_record","watch_coverage_live"].includes(i)};this.params=e,this.api=e.api,this.error$=e.error$,this.userSalt=e.userSalt,this.loggerDebugLog=e.debugLogger.createComponentLog("stat logger"),this.firstFlush=de(()=>this.safeFlush(),this.params.config.firstFlushTime,{maxWait:this.params.config.firstFlushTime});let i=T.isPersistent()?this.params.config.flushMaxWait:0;this.debouncedFlush=de(()=>this.safeFlush(),this.params.config.flushDebounceTime,{maxWait:i}),this.subscription=this.api.authorized$.subscribe(t=>{t&&this.debouncedFlush()}),this.housekeepStorage()}safeFlush(){var e;try{this.flush()}catch(i){this.error$.next({id:"LoggerError",category:we.WTF,message:(e=String(i))!=null?e:"Unknown logger error",thrown:i})}}readFromStorage(){let e=T.get(L);try{return e?JSON.parse(e):{}}catch(i){}return{}}addToStorage(e){var r;if(!this.userSalt){this.unsaltedStorage.push(e);return}let i=this.readFromStorage(),o=((r=i[this.userSalt])!=null?r:[]).filter(H(this.params.config.storageExpiration));T.set(L,JSON.stringify({...i,[this.userSalt]:[...o,e]}))}getFromStorage(){var t;return this.userSalt?((t=this.readFromStorage()[this.userSalt])!=null?t:[]).filter(H(this.params.config.storageExpiration)):this.unsaltedStorage}markStorageSent(){if(!this.userSalt){this.unsaltedStorage=[];return}let e=this.readFromStorage();delete e[this.userSalt],T.set(L,JSON.stringify(e))}housekeepStorage(){let e=this.readFromStorage();for(let[i,t]of Object.entries(e)){let o=t.filter(H(this.params.config.storageExpiration));o.length?e[i]=o:delete e[i],this.loggerDebugLog({message:`${t.length} retrieved from storage, ${o.length} of them actual`})}T.set(L,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){let i=this.getFromStorage();i.length!==0&&(this.api.authorized$.getValue()?(e&&this.params.config.useBeacon?(this.loggerDebugLog({message:`Flushing ${i.length} events through beacon`}),this.api.logBeacon(i)):(this.loggerDebugLog({message:`Flushing ${i.length} events`}),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()}};import{HttpConnectionType as K,Surface as A,VideoFormat as f,VideoQuality as m}from"@vkontakte/videoplayer-core";import{assertNever as ue}from"@vkontakte/videoplayer-shared";var ce=a=>a&&{[m.INVARIANT]:"unknown",[m.Q_144P]:"mobile",[m.Q_240P]:"lowest",[m.Q_360P]:"low",[m.Q_480P]:"medium",[m.Q_720P]:"high",[m.Q_1080P]:"fullhd",[m.Q_1440P]:"quadhd",[m.Q_2160P]:"ultrahd",[m.Q_4320P]:"unknown"}[a],q=a=>a&&{[K.HTTP1]:"http1",[K.HTTP2]:"http2",[K.QUIC]:"http3"}[a],le=a=>{if(a!==void 0)switch(a){case f.MPEG:return"mp4";case f.DASH:case f.DASH_LIVE:case f.DASH_STREAMS:return"dash";case f.DASH_SEP:return"dash_sep";case f.DASH_ONDEMAND:return"ondemand_dash";case f.DASH_WEBM:case f.DASH_LIVE_WEBM:return"webm";case f.DASH_WEBM_AV1:return"av1";case f.DASH_LIVE_CMAF:return"ondemand_dash_live";case f.HLS:case f.HLS_LIVE:return"hls";case f.HLS_ONDEMAND:return"ondemand_hls";case f.HLS_LIVE_CMAF:return"ondemand_hls_live";case f.WEB_RTC_LIVE:return"webrtc";default:return ue(a)}},R=a=>{if(a!==void 0)switch(a){case A.NONE:case A.INLINE:return;case A.FULLSCREEN:return"fullscreen";case A.SECOND_SCREEN:return"chromecast";case A.PIP:return"pip";case A.INVISIBLE:return"invisible";default:return ue(a)}},pe=a=>{switch(a){case"slow-2g":return"poor";case"2g":return"poor";case"3g":return"good";case"4g":return"excellent"}};var O=class{constructor(e){this.offset=void 0;this.offset=e}getOffset(){var e;return(e=this.offset)!=null?e:0}setOffset(e){this.offset=e}now(){var e;return Date.now()+((e=this.offset)!=null?e:0)}date(e=new Date){var i;return e.setTime(e.getTime()+((i=this.offset)!=null?i:0)),e}addServerTime(e,i){let t=Date.now(),o=e-t-i/2;if(Math.abs(o)<1e3){this.offset=0;return}this.offset===void 0?this.offset=Math.round(o):this.offset=Math.round(.2*o+(1-.2)*this.offset)}};var he=()=>Math.floor(Math.random()*4294967296).toString(36).padStart(7,"0"),fe=()=>Math.floor(Math.random()*18446744073709552e3).toString(36).padStart(13,"0");import{PlaybackState as ge}from"@vkontakte/videoplayer-core";import{filter as me,filterChanged as $e,fromEvent as Re,isNullable as be,map as Oe,merge as z,Observable as Ne,Subject as Q,Subscription as De,ValueSubject as Me}from"@vkontakte/videoplayer-shared";var ve=(a,e)=>new Ne(i=>{let t=new De,o=z(Re(window,"beforeunload"),a.events.willDestruct$),r=new Me(void 0),n;t.add(a.info.isLive$.pipe($e()).subscribe(I=>{n&&(n.unsubscribe(),r.next(void 0)),I?n=a.info.liveTime$.pipe(Oe(N=>N&&N/1e3)).subscribe(r):n=a.info.position$.subscribe(r),t.add(n)}));let{playing$:c,paused$:l}=a.events,d=a.events.willSeek$.pipe(me(()=>a.info.playbackState$.getValue()===ge.PLAYING)),p=a.events.seeked$.pipe(me(()=>a.info.playbackState$.getValue()===ge.PLAYING)),h=!1,s=new Q;t.add(d.subscribe(()=>{h||s.next(),h=!0})),t.add(p.subscribe(()=>h=!1));let u=new Q,g=new Q,v=z(c,p,u),S=z(l,s,o,a.events.looped$,g),y,Pe=()=>y=r.getValue(),Ae=()=>{let I=r.getValue();be(y)||y===I||be(I)||(i.next({from:y,to:I}),y=void 0)},Ee=()=>{g.next(),u.next()};if(t.add(v.subscribe(Pe)),t.add(S.subscribe(Ae)),e.forceInterval&&isFinite(e.forceInterval)){let I=0;t.add(v.subscribe(()=>I=window.setTimeout(Ee,e.forceInterval))),t.add(S.subscribe(()=>window.clearTimeout(I)))}return t});var qe="_one-stat_",Y=`${qe}uuid`,X=()=>{let a=new J;return{subscription:a,subscribe:(e,i)=>{e&&a.add(e.subscribe(i))}}},Z=class{constructor(e,i){this.subscription=new J;this.debugLogger=new He;this.oneStatDebugLog=this.debugLogger.createComponentLog("onestat");this.loopCounter=0;this.disabled=!1;this.vsid$=new G(void 0);this.isid$=new G(void 0);this.seekAction$=new G("unknown");var l,d,p;this.statContext=e,this.config=re((l=i.config)!=null?l:{}),E(i.apiEnv)&&(this.config.apiEnv=i.apiEnv),this.config.synchronizeTime&&(this.timeSynchronisation=new O);let t=new We;this.experimental={error$:t};let o=j.get(Y);o?o.startsWith('"')&&o.endsWith('"')?(this.uuid=o.replaceAll('"',""),j.set(Y,this.uuid)):this.uuid=o:(this.uuid=V(),j.set(Y,this.uuid)),this.resetViewSession(),i.useIsid&&this.isid$.next((d=i.isid)!=null?d:fe());let r=new C({apiKey:ae,config:this.config,error$:t,timeSynchronisation:this.timeSynchronisation});this.api=new x({config:this.config,apiTransport:r,refreshAuthToken:i.refreshAuthToken,mobile:(p=this.statContext.mobile)!=null?p:!1,uuid:this.uuid,error$:t}),this.logger=new $({config:this.config,debugLogger:this.debugLogger,api:this.api,error$:t,userSalt:i.userSalt});let{isEmbed:n,host:c}=Ke();this.isEmbed=n,this.embedParent=c,this.subscribe()}updateContext(e){this.statContext={...this.statContext,...e}}attachTo(e){let i=new J,t=(s,u)=>i.add(s.subscribe(u));t(e.events.willStart$,()=>{let s=e.info.position$.getValue();this.logActionPlay({position:s}),this.statContext.projectId&&this.logActionPlayInteractive()}),t(e.events.looped$,()=>{this.resetViewSession(),++this.loopCounter>this.config.maxLoops&&(this.disabled=!0),this.logActionPlay({position:e.info.position$.getValue()})}),t(e.events.seeked$,()=>{this.logSeek({action:this.seekAction$.getValue(),time:e.info.position$.getValue()}),this.seekAction$.next("unknown")}),t(e.events.paused$,()=>{this.logPause({position:e.info.position$.getValue()})}),t(e.events.willResume$,()=>{this.logPlay()}),t(e.events.started$,()=>{this.statContext.clip&&this.logWatchCoverageRecord({start:0,end:0})}),t(e.events.playing$,()=>{this.logPlaying()}),t(ve(e,{forceInterval:this.config.watchCoverageInterval}),s=>{let u=e.info.isLive$.getValue(),g={start:parseFloat(s.from.toFixed(3)),end:parseFloat(s.to.toFixed(3))};u?this.logWatchCoverageLive(g):this.logWatchCoverageRecord(g)});let o;t(e.info.isStalled$,s=>{s?o=b():(E(o)&&this.logEmptyBuffer({duration:b()-o}),o=void 0)});let r=!1;i.add(e.events.fatalError$.pipe(Ue()).subscribe(()=>r=!0)),t(e.events.willStop$,()=>{if(e.info.isStalled$.getValue()){let u=E(o)?b()-o:void 0;this.logCloseAtEmptyBuffer({duration:u!=null?u:0}),o=void 0}else r||this.logActionStop()}),t(e.events.managedError$,({id:s})=>{this.logError({fatal:!1,errorType:s})}),t(e.events.fatalError$,({id:s})=>{this.logError({fatal:!0,errorType:s})});let n,c,l=!1;t(e.events.firstBytes$,s=>{n=b(),this.logFirstBytes({time:s})}),t(e.events.willStart$,()=>c=b()),t(e.info.currentBuffer$,s=>{!l&&s&&s.end-s.start>0&&E(n)&&(this.logPlayerReady({duration:b()-n}),l=!0)}),t(e.events.firstFrame$,()=>{E(n)&&!l&&(this.logPlayerReady({duration:b()-n}),l=!0),E(c)&&this.logFirstFrame({time:b()-c})});let d;t(e.info.currentVideoStream$,s=>{s&&(d&&s.id!==d&&this.logTrackSwitch(s),d=s.id)});let p;t(e.info.currentAudioStream$,s=>{s&&(p&&s.id!==p&&this.logTrackSwitch(s),p=s.id)}),t(e.info.atLiveEdge$,s=>this.updateContext({liveEdge:s})),t(Ie({muted:e.info.muted$,volume:e.info.volume$}),({muted:s,volume:u})=>this.updateContext({audible:!s&&u>0})),t(e.info.currentQuality$,s=>this.updateContext({quality:ce(s)})),t(e.info.isAutoQualityEnabled$,s=>this.updateContext({autoQuality:s})),t(e.info.currentFormat$,s=>this.updateContext({contentType:le(s)})),t(e.info.currentPlaybackRate$,s=>this.updateContext({rate:s})),t(e.info.is3DVideo$,s=>this.updateContext({is3d:s}));let h;return t(e.info.hostname$,s=>{let u=h!==void 0&&h!==s;this.updateContext({cdnHostname:s,failover:u}),u&&this.logFailover(s),h=s}),t(e.info.throughputEstimation$,s=>this.updateContext({downloadSpeed:s})),t(e.info.httpConnectionType$,s=>{this.statContext.firstConnectionType||this.updateContext({firstConnectionType:q(s)}),this.updateContext({connectionType:q(s)})}),t(e.info.httpConnectionReused$,s=>{ye(this.statContext.firstConnectionReused)&&this.updateContext({firstConnectionReused:s}),this.updateContext({connectionReused:s})}),t(e.info.surface$,s=>this.updateContext({mode:R(s)})),t(Ie({current:e.info.currentTextTrack$,available:e.info.availableTextTracks$}),({current:s,available:u})=>{let g=u.find(({id:S})=>S===s),v=g&&(g.isAuto?`${g.language}_auto`:g.language);this.updateContext({subtitles:v})}),this.player=e,this.uiEvents&&this.attachToUi(this.uiEvents),this.resubscribeBeforeunload(),this.subscription.add(i),i}attachToUi(e){this.uiEvents=e;let{subscription:i,subscribe:t}=X();return this.player&&(t(e.actionRewind$,()=>{this.player&&(this.resetViewSession(),this.logActionPlay({position:this.player.info.position$.getValue()}))}),t(e.actionSeek$,this.seekAction$),t(e.inPiP$,o=>{var n;let r=o?"pip":R((n=this.player)==null?void 0:n.info.surface$.getValue());this.updateContext({mode:r})}),t(e.inFullscreen$,o=>{var n;let r=o?"fullscreen":R((n=this.player)==null?void 0:n.info.surface$.getValue());this.updateContext({mode:r})}),t(e.actionSetSubtitle$,o=>this.updateContext({subtitles:o})),t(e.nextMovie$,o=>this.logNextMovie(o)),this.resubscribeBeforeunload(),this.subscription.add(i)),i}attachToAds(e){let{subscription:i,subscribe:t}=X();return t(e.slotRequested$,()=>this.logAdSlotRequest()),t(e.started$,o=>this.logAdStarted(o)),t(e.paused$,()=>this.logAdPaused()),t(e.resumed$,()=>this.logAdResumed()),t(e.ended$,()=>this.logAdEnded()),t(e.skipped$,()=>this.logAdSkipped()),t(e.clicked$,()=>this.logAdClicked()),this.resubscribeBeforeunload(),this.subscription.add(i),i}attachToInteractive(e){let{subscription:i,subscribe:t}=X();return t(e.click$,o=>this.logInterfaceClick(o)),t(e.nextMovie$,o=>this.logNextMovie(o)),this.resubscribeBeforeunload(),this.subscription.add(i),i}authorize(e){return this.api.authorize(e)}pause(){this.logger.pause(),this.oneStatDebugLog({message:"paused"})}resume(){this.logger.resume(),this.oneStatDebugLog({message:"resumed"})}destroy(){this.logger.flush(),this.subscription.unsubscribe(),this.api.destroy(),this.logger.destroy()}resetViewSession(){this.oneStatDebugLog({message:"VSID reset"}),this.vsid$.next(he())}getDeviceId(){return this.uuid}setFieldBlacklist(){}logInited(){}logReady(e){this.log({operation:"player_ready",param:String(e.time)})}logStarted(...e){this.logActionPlay(...e)}logPlay(){this.log({operation:"play_toggle"})}logPlaying(){this.log({operation:"playing"})}logPause(e){this.log({operation:"pause",param:String(Math.round(e.position))})}logSeek(e){this.log({operation:"seek",param:e.action,time:e.time})}logFirstBytes(e){this.log({operation:"first_bytes",param:String(e.time)})}logFirstFrame(e){this.log({operation:"first_frame",param:String(e.time)})}logError(e){this.log({operation:"content_error",param:`${e.fatal?"fatal":"recoverable"}_${e.errorType}`})}logWatchCoverageRecord(e){this.log({operation:"watch_coverage_record",param:`${e.start}-${e.end}`})}logWatchCoverageLive(e){var r,n;let i=(n=(r=this.timeSynchronisation)==null?void 0:r.getOffset())!=null?n:0,t=e.start+i,o=e.end+i;this.log({operation:"watch_coverage_live",param:`${t}-${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();let e=window.navigator.connection;e&&"onchange"in e&&"effectiveType"in e&&this.subscription.add(Fe(Se(e,"change"),Ve(["init"])).subscribe(()=>this.updateContext({network:pe(e.effectiveType)}))),this.config.debugLog&&this.debugLogger.log$.subscribe(i=>{console.debug("%c stat ","background:#fa6470;",`component: ${i.component}.`,i.message)})}resubscribeBeforeunload(){var e;(e=this.beforeunloadSubscription)==null||e.unsubscribe(),this.beforeunloadSubscription=Se(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))})}logActionPlayInteractive(){this.statContext.projectId&&this.log({operation:"action_play_interactive",param:String(this.statContext.movieId)},{vid:this.statContext.projectId})}logFailover(e){this.log({operation:"failover",param:e})}logCloseAtEmptyBuffer(e){this.log({operation:"close_at_empty_buffer",param:String(Math.round(e.duration))})}logActionStop(){this.log({operation:"action_stop"})}logTrackSwitch(e){this.log({operation:"track_switch",param:e.id})}log(e,i={}){if(this.disabled){this.oneStatDebugLog({message:`operation ${e.operation} but statistics is disabled`});return}if(this.config.disabledOperations.includes(e.operation)){this.oneStatDebugLog({message:`operation ${e.operation} but it is disabled`});return}this.oneStatDebugLog({message:`operation ${e.operation} ${e.param}`});let t=this.createLogItem(e,i);this.logger.log(t)}createLogItem({operation:e,param:i,time:t},o={}){var u,g;let r=(g=(u=this.timeSynchronisation)==null?void 0:u.now())!=null?g:b(),n=this.vsid$.getValue();Be(n);let c=this.isid$.getValue(),l=e==="empty_buffer"||e==="close_at_empty_buffer"?this.statContext.connectionType:this.statContext.firstConnectionType,d=this.statContext.firstConnectionReused,p,h;if(this.isEmbed){p=this.embedParent;let v=[...new URLSearchParams(location.search).entries()].filter(([S,y])=>this.config.embedUrlParams.includes(S));h=new URLSearchParams(v).toString()}else this.statContext.place==="direct"&&((this.statContext.refDomain||document.referrer)&&(p=new URL(this.statContext.refDomain||document.referrer).hostname),h=location.href.substring(0,1024));let s={vsid:n,isid:c,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?"auto":this.statContext.autoplay===!1?"":void 0,param:i,vk_app_id:this.statContext.vkAppId,track_code:this.statContext.trackCode,connection_type:l,connection_reused:d===!0?1:d===!1?0:void 0,cached_data:this.statContext.cached===!0?1:this.statContext.cached===!1?0:void 0,live:this.statContext.liveEdge?1:void 0,muted:this.statContext.audible===!1?1:void 0,mode:this.statContext.mode,subtitles:this.statContext.subtitles,download_speed:this.statContext.downloadSpeed,manual_quality:this.statContext.autoQuality?void 0:1,ref_domain:p,direct_url:h,rate:this.statContext.rate===1||ye(this.statContext.rate)?void 0:this.statContext.rate.toFixed(2),view_360:this.statContext.is3d?1:void 0,aid:this.statContext.albumId,vk_playlist_id:this.statContext.vkPlaylistId,...o};for(let v of this.config.disabledCustomFields)delete s[v];return{operation:e,type:1,time:t,network:this.statContext.network,timestamp:r,custom:s}}};export{_ as ApiEnv,B as ConnectionType,M as ContentType,ee as InteractiveInterfaceClick,Z as OneStat,D as Quality,F as SeekAction,w as VERSION};
6
+ var _=(r=>(r.PROD="prod",r.VK_ALIAS="vk_alias",r.VIDEOTEST="videotest",r.TEST="test",r.AUTO="auto",r))(_||{}),D=(d=>(d.Q144P="mobile",d.Q240P="lowest",d.Q360P="low",d.Q480P="medium",d.Q720P="high",d.Q1080P="fullhd",d.Q1440P="quadhd",d.Q2160P="ultrahd",d.UNKNOWN="unknown",d))(D||{}),M=(u=>(u.MP4="mp4",u.DASH="dash",u.DASH_SEP="dash_sep",u.ONDEMAND_DASH="ondemand_dash",u.HLS="hls",u.ONDEMAND_HLS="ondemand_hls",u.WEBM="webm",u.AV1="av1",u.ONDEMAND_DASH_LIVE="ondemand_dash_live",u.ONDEMAND_HLS_LIVE="ondemand_hls_live",u.WEBRTC="webrtc",u.UNKNOWN="unknown",u.RTMP="rtmp",u))(M||{});var B=(t=>(t.HTTP1="http1",t.HTTP2="http2",t.HTTP3="http3",t))(B||{});var F=(c=>(c.SLIDER="slider",c.DOUBLE_TAP="double_tap",c.TIME_CODE="time_code",c.EPISODE="episode",c.REWIND="rewind",c.LIVE="live",c.UNKNOWN="unknown",c))(F||{}),ee=(r=>(r.GRAPH_SHOW="iGraphShow",r.GRAPH_HIDE="iGraphHide",r.NEXT_AREA="iNextChapterArea",r.NEXT_BUTTON="iNextChapterBtn",r.WATCH_AGAIN="iWatchAgainBtn",r))(ee||{}),te={action_play:"ap",action_play_interactive:"api",first_bytes:"fb",player_ready:"pr",first_frame:"ff",seek:"sk",watch_coverage_record:"wr",watch_coverage_live:"wl",empty_buffer:"eb",action_stop:"as",close_at_empty_buffer:"cb",content_error:"er",player_interface_click:"pc",next_movie:"nm",track_switch:"ts",failover:"fo"},ie={vsid:"si",isid:"is",vid:"vi",place:"pl",quality:"qt",cdn_host:"ch",stat_type:"st",param:"pm",vk_app_id:"va",track_code:"tc",connection_type:"cnt",connection_reused:"cr",cached_data:"cd",live:"lv",muted:"mu",mode:"mo",subtitles:"sb",failover:"fo",download_speed:"ds",manual_quality:"mq",ref_domain:"rd",direct_url:"du"},oe={unknown:"un",mobile:"m",lowest:"ls",low:"l",medium:"md",high:"h",fullhd:"f",quadhd:"q",ultrahd:"u"},se={pip:"pi",fullscreen:"fs",external:"ex",prefetch:"pr",airplay:"ap",chromecast:"cc",invisible:"iv"};import{fillWithDefault as _e}from"@vkontakte/videoplayer-shared";var xe={apiEnv:"vk_alias",requestRetryCount:1,firstFlushTime:5e3,flushDebounceTime:1e4,flushMaxWait:6e4,storageExpiration:36*60*60*1e3,watchCoverageInterval:15e3,disabledOperations:[],disabledCustomFields:[],shorten:!0,maxLoops:100,embedUrlParams:[],useBeacon:!0,synchronizeTime:!0,debugLog:!1,backoff:{start:1e3,factor:1.5,max:5*60*1e3,random:.1}},re=a=>_e(a,xe);function V(){let a="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".split(""),e=new Array(36),i=0,t,o;for(o=0;o<36;o++)o===8||o===13||o===18||o===23?e[o]="-":o===14?e[o]="4":(i<=2&&(i=33554432+Math.random()*16777216|0),t=i&15,i=i>>4,e[o]=a[o===19?t&3|8:t]);return e.join("")}import{assertNonNullable as Be,combine as Ie,fromEvent as Se,isNonNullable as E,isNullable as ye,merge as Fe,now as b,observableFrom as Ve,once as Ue,safeStorage as j,Subject as We,Subscription as J,ValueSubject as G}from"@vkontakte/videoplayer-shared";import{Logger as He,detectEmbed as Ke}from"@vkontakte/videoplayer-shared";var ne=a=>{var o;let{operation:e,custom:i}=a,t=Object.fromEntries(Object.entries(i).map(([r,n])=>{var d,p,h;let c=(d=ie[r])!=null?d:r,l=n;return n&&(r==="mode"?l=(p=se[n])!=null?p:n:r==="quality"&&(l=(h=oe[n])!=null?h:n)),[c,l]}));return{...a,operation:(o=te[e])!=null?o:e,custom:t}};var w="1.0.52-dev.a5f6699f.0",ae="CIOPGQJGDIHBABABA",U={prod:"https://api.ok.ru",vk_alias:"https://api.mycdn.me",videotest:"https://videotestapi.ok.ru/api",test:"https://apitest.ok.ru",auto:""};import{ValueSubject as Ce,getExponentialDelay as Te,ErrorCategory as P}from"@vkontakte/videoplayer-shared";var x=class{constructor(e){this.consequentAuthErrors=0;this.authorized$=new Ce(!1);this.params=e}async authorize(e){return this.authToken=e!=null?e:await this.refreshAuthToken(),this._authorizeWithBackoff()}logBeacon(e){let i="log.externalLog",t=this.createLogParams(e),o=this.sessionKey;if(!o)return;this.params.apiTransport.sendBeacon(i,t,o)||this.logRequest(e)}async logRequest(e){var n;let i="log.externalLog",t=this.createLogParams(e),o=(n=this.sessionKey)!=null?n:await this._authorizeWithBackoff();if(!o)return;let r=async(c,l=this.params.config.requestRetryCount)=>{try{return await this.params.apiTransport.sendRequest(i,t,o)}catch(d){if(!d||!("error_code"in d)){this.params.error$.next({id:"logRequestUnknown",category:P.NETWORK,message:`Unknown ${i} error`,thrown:d});return}let p=d==null?void 0:d.error_code;switch(p){case 102:case 103:case 104:return this.authorized$.next(!1),this.sessionKey=await this._authorizeWithBackoff(),l>0?r(c,l-1):void 0;case 401:return this.authorized$.next(!1),this.authToken=await this.refreshAuthToken(),this.sessionKey=await this._authorizeWithBackoff(),l>0?r(c,l-1):void 0;default:{this.params.error$.next({id:`LogRequest#${p}`,category:P.EXTERNAL_API,message:`${i} error`,data:d});return}}}};return r(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:${w}`,platform:this.params.mobile?"M_WEB":"WEB",items:this.params.config.shorten?e.map(ne):e})}}_authorizeWithBackoff(){if(!this.consequentAuthErrors)return this._authorize();let e=Te(this.consequentAuthErrors,this.params.config.backoff);return new Promise(i=>{this.backoffTimeoutId||(this.backoffTimeoutId=window.setTimeout(()=>{this._authorize().then(i).catch(t=>this.params.error$.next({id:"AuthorizeBackoff",category:P.NETWORK,message:"Otherwise unhandled error in authorization",thrown:t})).finally(()=>this.backoffTimeoutId=0)},e))})}async _authorize(){if(this.authorizePromise)return this.authorizePromise;this.sessionKey=void 0,this.authorized$.next(!1);let e="auth.anonymLogin",i={session_data:{version:2,device_id:this.params.uuid,client_version:w.split("-")[0],client_type:"SDK_JS"}};return this.authToken!==void 0&&(i.session_data.auth_token=this.authToken,i.session_data.version=3),this.authorizePromise=this.params.apiTransport.sendRequest(e,i).then(t=>{var o;return(!t||!t.session_key)&&this.params.error$.next({id:"AuthorizeFailed",category:P.EXTERNAL_API,message:"No session key",data:t}),this.sessionKey=(o=t==null?void 0:t.session_key)!=null?o:void 0,this.sessionKey}).catch(async t=>{this.sessionKey=void 0;let o=t==null?void 0:t.error_code;switch(o){case 401:return this.authToken=await this.refreshAuthToken(),this._authorizeWithBackoff()}o?this.params.error$.next({id:`Authorize#${o}`,category:P.EXTERNAL_API,message:"authorize error",data:t}):this.params.error$.next({id:"AuthorizeUnknown",category:P.NETWORK,message:"authorize error",thrown:t})}).finally(()=>{this.authorizePromise=void 0,this.consequentAuthErrors=this.sessionKey?0:this.consequentAuthErrors+1,this.authorized$.next(this.sessionKey!==void 0)}),this.authorizePromise}};import{ErrorCategory as k,now as W}from"@vkontakte/videoplayer-shared";var C=class{constructor(e){this.params=e,this.apiKey=e.apiKey,this.apiEnv=e.config.apiEnv,this.apiBaseUrl=U[this.apiEnv],this.timeSynchronisation=e.timeSynchronisation,this.isApiBaseUrlFetched=!1}async resolveApiBaseUrl(){var e;if(this.apiEnv!=="auto"||this.isApiBaseUrlFetched)return this.apiBaseUrl;try{let i=atob("aHR0cHM6Ly9kbnMuZ29vZ2xlL3Jlc29sdmU/bmFtZT12aWRlby5fZW5kcG9pbnQub2sucnUmdHlwZT1UWFQ="),o=await(await fetch(i,{method:"GET",mode:"cors",cache:"no-cache"})).json(),r=(e=o==null?void 0:o.Answer[0])==null?void 0:e.data;if(!r)throw new Error("Wrong DNS response");return r}catch(i){return this.params.error$.next({id:"OneStat:ApiTransport:resolveApiBaseUrl",category:k.NETWORK,message:"Unhandled resolve api base url error",thrown:i}),U.vk_alias}finally{this.isApiBaseUrlFetched=!0}}sendBeacon(e,i,t){if(!window.Blob||!window.navigator.sendBeacon)return!1;let o=this._prepareQueryParams({method:e,queryParams:i,sessionKey:t}),r=new window.Blob([o.toString()],{type:"application/x-www-form-urlencoded"});try{return window.navigator.sendBeacon(`${this.apiBaseUrl}/fb.do`,r)}catch(n){this.params.error$.next({id:"OneStat:ApiTransport:sendBeacon",category:k.NETWORK,message:"Unhandled beacon error",thrown:n,data:{method:e,params:i}})}return!1}async sendRequest(e,i,t){let o=W(),r=n=>{if(n instanceof TypeError&&["Failed to fetch","NetworkError when attempting to fetch resource."].includes(n.message)){this.params.error$.next({id:"Network",category:k.NETWORK,message:"Request failed",thrown:n});return}this.params.error$.next({id:"OneStat:ApiTransport:sendRequest",category:k.NETWORK,message:"Unhandled request error",thrown:n,data:{method:e,params:i,sessionKey:t,time:W()-o}})};return this.apiBaseUrl=await this.resolveApiBaseUrl(),fetch(`${this.apiBaseUrl}/fb.do`,{method:"post",headers:{"Content-type":"application/x-www-form-urlencoded"},body:this._prepareQueryParams({method:e,queryParams:i,sessionKey:t})}).then(n=>{var p,h;let c=Number(n.headers.get("content-length"))===0,l=new Date((p=n.headers.get("date"))!=null?p:"").getTime(),d=W()-o;if(isFinite(l)&&((h=this.timeSynchronisation)==null||h.addServerTime(l,d)),!c)return n.json().then(s=>Object.prototype.hasOwnProperty.call(s,"error_msg")?Promise.reject(s):s,r)},r)}_prepareQueryParams(e){let i=new URLSearchParams({format:"JSON",method:e.method,application_key:this.apiKey});return e.sessionKey!==void 0&&i.append("session_key",e.sessionKey),Object.entries(e.queryParams).forEach(([t,o])=>i.append(t,typeof o=="string"?o:JSON.stringify(o))),i}};import{ErrorCategory as we,now as ke,safeStorage as T,debounceFn as de}from"@vkontakte/videoplayer-shared";var L="onestat_events",H=a=>e=>e.timestamp+a>=ke(),$=class{constructor(e){this.unsaltedStorage=[];this.isPaused=!1;this.isUrgent=e=>{let{operation:i}=e;return["action_play","watch_coverage_record","watch_coverage_live"].includes(i)};this.params=e,this.api=e.api,this.error$=e.error$,this.userSalt=e.userSalt,this.loggerDebugLog=e.debugLogger.createComponentLog("stat logger"),this.firstFlush=de(()=>this.safeFlush(),this.params.config.firstFlushTime,{maxWait:this.params.config.firstFlushTime});let i=T.isPersistent()?this.params.config.flushMaxWait:0;this.debouncedFlush=de(()=>this.safeFlush(),this.params.config.flushDebounceTime,{maxWait:i}),this.subscription=this.api.authorized$.subscribe(t=>{t&&this.debouncedFlush()}),this.housekeepStorage()}safeFlush(){var e;try{this.flush()}catch(i){this.error$.next({id:"LoggerError",category:we.WTF,message:(e=String(i))!=null?e:"Unknown logger error",thrown:i})}}readFromStorage(){let e=T.get(L);try{return e?JSON.parse(e):{}}catch(i){}return{}}addToStorage(e){var r;if(!this.userSalt){this.unsaltedStorage.push(e);return}let i=this.readFromStorage(),o=((r=i[this.userSalt])!=null?r:[]).filter(H(this.params.config.storageExpiration));T.set(L,JSON.stringify({...i,[this.userSalt]:[...o,e]}))}getFromStorage(){var t;return this.userSalt?((t=this.readFromStorage()[this.userSalt])!=null?t:[]).filter(H(this.params.config.storageExpiration)):this.unsaltedStorage}markStorageSent(){if(!this.userSalt){this.unsaltedStorage=[];return}let e=this.readFromStorage();delete e[this.userSalt],T.set(L,JSON.stringify(e))}housekeepStorage(){let e=this.readFromStorage();for(let[i,t]of Object.entries(e)){let o=t.filter(H(this.params.config.storageExpiration));o.length?e[i]=o:delete e[i],this.loggerDebugLog({message:`${t.length} retrieved from storage, ${o.length} of them actual`})}T.set(L,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){let i=this.getFromStorage();i.length!==0&&(this.api.authorized$.getValue()?(e&&this.params.config.useBeacon?(this.loggerDebugLog({message:`Flushing ${i.length} events through beacon`}),this.api.logBeacon(i)):(this.loggerDebugLog({message:`Flushing ${i.length} events`}),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()}};import{HttpConnectionType as K,Surface as A,VideoFormat as f,VideoQuality as m}from"@vkontakte/videoplayer-core";import{assertNever as ue}from"@vkontakte/videoplayer-shared";var ce=a=>a&&{[m.INVARIANT]:"unknown",[m.Q_144P]:"mobile",[m.Q_240P]:"lowest",[m.Q_360P]:"low",[m.Q_480P]:"medium",[m.Q_720P]:"high",[m.Q_1080P]:"fullhd",[m.Q_1440P]:"quadhd",[m.Q_2160P]:"ultrahd",[m.Q_4320P]:"unknown"}[a],q=a=>a&&{[K.HTTP1]:"http1",[K.HTTP2]:"http2",[K.QUIC]:"http3"}[a],le=a=>{if(a!==void 0)switch(a){case f.MPEG:return"mp4";case f.DASH:case f.DASH_LIVE:case f.DASH_STREAMS:return"dash";case f.DASH_SEP:return"dash_sep";case f.DASH_ONDEMAND:return"ondemand_dash";case f.DASH_WEBM:case f.DASH_LIVE_WEBM:return"webm";case f.DASH_WEBM_AV1:return"av1";case f.DASH_LIVE_CMAF:return"ondemand_dash_live";case f.HLS:case f.HLS_LIVE:return"hls";case f.HLS_ONDEMAND:return"ondemand_hls";case f.HLS_LIVE_CMAF:return"ondemand_hls_live";case f.WEB_RTC_LIVE:return"webrtc";default:return ue(a)}},R=a=>{if(a!==void 0)switch(a){case A.NONE:case A.INLINE:return;case A.FULLSCREEN:return"fullscreen";case A.SECOND_SCREEN:return"chromecast";case A.PIP:return"pip";case A.INVISIBLE:return"invisible";default:return ue(a)}},pe=a=>{switch(a){case"slow-2g":return"poor";case"2g":return"poor";case"3g":return"good";case"4g":return"excellent"}};var O=class{constructor(e){this.offset=void 0;this.offset=e}getOffset(){var e;return(e=this.offset)!=null?e:0}setOffset(e){this.offset=e}now(){var e;return Date.now()+((e=this.offset)!=null?e:0)}date(e=new Date){var i;return e.setTime(e.getTime()+((i=this.offset)!=null?i:0)),e}addServerTime(e,i){let t=Date.now(),o=e-t-i/2;if(Math.abs(o)<1e3){this.offset=0;return}this.offset===void 0?this.offset=Math.round(o):this.offset=Math.round(.2*o+(1-.2)*this.offset)}};var he=()=>Math.floor(Math.random()*4294967296).toString(36).padStart(7,"0"),fe=()=>Math.floor(Math.random()*18446744073709552e3).toString(36).padStart(13,"0");import{PlaybackState as ge}from"@vkontakte/videoplayer-core";import{filter as me,filterChanged as $e,fromEvent as Re,isNullable as be,map as Oe,merge as z,Observable as Ne,Subject as Q,Subscription as De,ValueSubject as Me}from"@vkontakte/videoplayer-shared";var ve=(a,e)=>new Ne(i=>{let t=new De,o=z(Re(window,"beforeunload"),a.events.willDestruct$),r=new Me(void 0),n;t.add(a.info.isLive$.pipe($e()).subscribe(I=>{n&&(n.unsubscribe(),r.next(void 0)),I?n=a.info.liveTime$.pipe(Oe(N=>N&&N/1e3)).subscribe(r):n=a.info.position$.subscribe(r),t.add(n)}));let{playing$:c,paused$:l}=a.events,d=a.events.willSeek$.pipe(me(()=>a.info.playbackState$.getValue()===ge.PLAYING)),p=a.events.seeked$.pipe(me(()=>a.info.playbackState$.getValue()===ge.PLAYING)),h=!1,s=new Q;t.add(d.subscribe(()=>{h||s.next(),h=!0})),t.add(p.subscribe(()=>h=!1));let u=new Q,g=new Q,v=z(c,p,u),S=z(l,s,o,a.events.looped$,g),y,Pe=()=>y=r.getValue(),Ae=()=>{let I=r.getValue();be(y)||y===I||be(I)||(i.next({from:y,to:I}),y=void 0)},Ee=()=>{g.next(),u.next()};if(t.add(v.subscribe(Pe)),t.add(S.subscribe(Ae)),e.forceInterval&&isFinite(e.forceInterval)){let I=0;t.add(v.subscribe(()=>I=window.setTimeout(Ee,e.forceInterval))),t.add(S.subscribe(()=>window.clearTimeout(I)))}return t});var qe="_one-stat_",Y=`${qe}uuid`,X=()=>{let a=new J;return{subscription:a,subscribe:(e,i)=>{e&&a.add(e.subscribe(i))}}},Z=class{constructor(e,i){this.subscription=new J;this.debugLogger=new He;this.oneStatDebugLog=this.debugLogger.createComponentLog("onestat");this.loopCounter=0;this.disabled=!1;this.vsid$=new G(void 0);this.isid$=new G(void 0);this.seekAction$=new G("unknown");var l,d,p;this.statContext=e,this.config=re((l=i.config)!=null?l:{}),E(i.apiEnv)&&(this.config.apiEnv=i.apiEnv),this.config.synchronizeTime&&(this.timeSynchronisation=new O);let t=new We;this.experimental={error$:t};let o=j.get(Y);o?o.startsWith('"')&&o.endsWith('"')?(this.uuid=o.replaceAll('"',""),j.set(Y,this.uuid)):this.uuid=o:(this.uuid=V(),j.set(Y,this.uuid)),this.resetViewSession(),i.useIsid&&this.isid$.next((d=i.isid)!=null?d:fe());let r=new C({apiKey:ae,config:this.config,error$:t,timeSynchronisation:this.timeSynchronisation});this.api=new x({config:this.config,apiTransport:r,refreshAuthToken:i.refreshAuthToken,mobile:(p=this.statContext.mobile)!=null?p:!1,uuid:this.uuid,error$:t}),this.logger=new $({config:this.config,debugLogger:this.debugLogger,api:this.api,error$:t,userSalt:i.userSalt});let{isEmbed:n,host:c}=Ke();this.isEmbed=n,this.embedParent=c,this.subscribe()}updateContext(e){this.statContext={...this.statContext,...e}}attachTo(e){let i=new J,t=(s,u)=>i.add(s.subscribe(u));t(e.events.willStart$,()=>{let s=e.info.position$.getValue();this.logActionPlay({position:s}),this.statContext.projectId&&this.logActionPlayInteractive()}),t(e.events.looped$,()=>{this.resetViewSession(),++this.loopCounter>this.config.maxLoops&&(this.disabled=!0),this.logActionPlay({position:e.info.position$.getValue()})}),t(e.events.seeked$,()=>{this.logSeek({action:this.seekAction$.getValue(),time:e.info.position$.getValue()}),this.seekAction$.next("unknown")}),t(e.events.paused$,()=>{this.logPause({position:e.info.position$.getValue()})}),t(e.events.willResume$,()=>{this.logPlay()}),t(e.events.started$,()=>{this.statContext.clip&&this.logWatchCoverageRecord({start:0,end:0})}),t(e.events.playing$,()=>{this.logPlaying()}),t(ve(e,{forceInterval:this.config.watchCoverageInterval}),s=>{let u=e.info.isLive$.getValue(),g={start:parseFloat(s.from.toFixed(3)),end:parseFloat(s.to.toFixed(3))};u?this.logWatchCoverageLive(g):this.logWatchCoverageRecord(g)});let o;t(e.info.isStalled$,s=>{s?o=b():(E(o)&&this.logEmptyBuffer({duration:b()-o}),o=void 0)});let r=!1;i.add(e.events.fatalError$.pipe(Ue()).subscribe(()=>r=!0)),t(e.events.willStop$,()=>{if(e.info.isStalled$.getValue()){let u=E(o)?b()-o:void 0;this.logCloseAtEmptyBuffer({duration:u!=null?u:0}),o=void 0}else r||this.logActionStop()}),t(e.events.managedError$,({id:s})=>{this.logError({fatal:!1,errorType:s})}),t(e.events.fatalError$,({id:s})=>{this.logError({fatal:!0,errorType:s})});let n,c,l=!1;t(e.events.firstBytes$,s=>{n=b(),this.logFirstBytes({time:s})}),t(e.events.willStart$,()=>c=b()),t(e.info.currentBuffer$,s=>{!l&&s&&s.end-s.start>0&&E(n)&&(this.logPlayerReady({duration:b()-n}),l=!0)}),t(e.events.firstFrame$,()=>{E(n)&&!l&&(this.logPlayerReady({duration:b()-n}),l=!0),E(c)&&this.logFirstFrame({time:b()-c})});let d;t(e.info.currentVideoStream$,s=>{s&&(d&&s.id!==d&&this.logTrackSwitch(s),d=s.id)});let p;t(e.info.currentAudioStream$,s=>{s&&(p&&s.id!==p&&this.logTrackSwitch(s),p=s.id)}),t(e.info.atLiveEdge$,s=>this.updateContext({liveEdge:s})),t(Ie({muted:e.info.muted$,volume:e.info.volume$}),({muted:s,volume:u})=>this.updateContext({audible:!s&&u>0})),t(e.info.currentQuality$,s=>this.updateContext({quality:ce(s)})),t(e.info.isAutoQualityEnabled$,s=>this.updateContext({autoQuality:s})),t(e.info.currentFormat$,s=>this.updateContext({contentType:le(s)})),t(e.info.currentPlaybackRate$,s=>this.updateContext({rate:s})),t(e.info.is3DVideo$,s=>this.updateContext({is3d:s}));let h;return t(e.info.hostname$,s=>{let u=h!==void 0&&h!==s;this.updateContext({cdnHostname:s,failover:u}),u&&this.logFailover(s),h=s}),t(e.info.throughputEstimation$,s=>this.updateContext({downloadSpeed:s})),t(e.info.httpConnectionType$,s=>{this.statContext.firstConnectionType||this.updateContext({firstConnectionType:q(s)}),this.updateContext({connectionType:q(s)})}),t(e.info.httpConnectionReused$,s=>{ye(this.statContext.firstConnectionReused)&&this.updateContext({firstConnectionReused:s}),this.updateContext({connectionReused:s})}),t(e.info.surface$,s=>this.updateContext({mode:R(s)})),t(Ie({current:e.info.currentTextTrack$,available:e.info.availableTextTracks$}),({current:s,available:u})=>{let g=u.find(({id:S})=>S===s),v=g&&(g.isAuto?`${g.language}_auto`:g.language);this.updateContext({subtitles:v})}),this.player=e,this.uiEvents&&this.attachToUi(this.uiEvents),this.resubscribeBeforeunload(),this.subscription.add(i),i}attachToUi(e){this.uiEvents=e;let{subscription:i,subscribe:t}=X();return this.player&&(t(e.actionRewind$,()=>{this.player&&(this.resetViewSession(),this.logActionPlay({position:this.player.info.position$.getValue()}))}),t(e.actionSeek$,this.seekAction$),t(e.inPiP$,o=>{var n;let r=o?"pip":R((n=this.player)==null?void 0:n.info.surface$.getValue());this.updateContext({mode:r})}),t(e.inFullscreen$,o=>{var n;let r=o?"fullscreen":R((n=this.player)==null?void 0:n.info.surface$.getValue());this.updateContext({mode:r})}),t(e.actionSetSubtitle$,o=>this.updateContext({subtitles:o})),t(e.nextMovie$,o=>this.logNextMovie(o)),this.resubscribeBeforeunload(),this.subscription.add(i)),i}attachToAds(e){let{subscription:i,subscribe:t}=X();return t(e.slotRequested$,()=>this.logAdSlotRequest()),t(e.started$,o=>this.logAdStarted(o)),t(e.paused$,()=>this.logAdPaused()),t(e.resumed$,()=>this.logAdResumed()),t(e.ended$,()=>this.logAdEnded()),t(e.skipped$,()=>this.logAdSkipped()),t(e.clicked$,()=>this.logAdClicked()),this.resubscribeBeforeunload(),this.subscription.add(i),i}attachToInteractive(e){let{subscription:i,subscribe:t}=X();return t(e.click$,o=>this.logInterfaceClick(o)),t(e.nextMovie$,o=>this.logNextMovie(o)),this.resubscribeBeforeunload(),this.subscription.add(i),i}authorize(e){return this.api.authorize(e)}pause(){this.logger.pause(),this.oneStatDebugLog({message:"paused"})}resume(){this.logger.resume(),this.oneStatDebugLog({message:"resumed"})}destroy(){this.logger.flush(),this.subscription.unsubscribe(),this.api.destroy(),this.logger.destroy()}resetViewSession(){this.oneStatDebugLog({message:"VSID reset"}),this.vsid$.next(he())}getDeviceId(){return this.uuid}setFieldBlacklist(){}logInited(){}logReady(e){this.log({operation:"player_ready",param:String(e.time)})}logStarted(...e){this.logActionPlay(...e)}logPlay(){this.log({operation:"play_toggle"})}logPlaying(){this.log({operation:"playing"})}logPause(e){this.log({operation:"pause",param:String(Math.round(e.position))})}logSeek(e){this.log({operation:"seek",param:e.action,time:e.time})}logFirstBytes(e){this.log({operation:"first_bytes",param:String(e.time)})}logFirstFrame(e){this.log({operation:"first_frame",param:String(e.time)})}logError(e){this.log({operation:"content_error",param:`${e.fatal?"fatal":"recoverable"}_${e.errorType}`})}logWatchCoverageRecord(e){this.log({operation:"watch_coverage_record",param:`${e.start}-${e.end}`})}logWatchCoverageLive(e){var r,n;let i=(n=(r=this.timeSynchronisation)==null?void 0:r.getOffset())!=null?n:0,t=e.start+i,o=e.end+i;this.log({operation:"watch_coverage_live",param:`${t}-${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();let e=window.navigator.connection;e&&"onchange"in e&&"effectiveType"in e&&this.subscription.add(Fe(Se(e,"change"),Ve(["init"])).subscribe(()=>this.updateContext({network:pe(e.effectiveType)}))),this.config.debugLog&&this.debugLogger.log$.subscribe(i=>{console.debug("%c stat ","background:#fa6470;",`component: ${i.component}.`,i.message)})}resubscribeBeforeunload(){var e;(e=this.beforeunloadSubscription)==null||e.unsubscribe(),this.beforeunloadSubscription=Se(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))})}logActionPlayInteractive(){this.statContext.projectId&&this.log({operation:"action_play_interactive",param:String(this.statContext.movieId)},{vid:this.statContext.projectId})}logFailover(e){this.log({operation:"failover",param:e})}logCloseAtEmptyBuffer(e){this.log({operation:"close_at_empty_buffer",param:String(Math.round(e.duration))})}logActionStop(){this.log({operation:"action_stop"})}logTrackSwitch(e){this.log({operation:"track_switch",param:e.id})}log(e,i={}){if(this.disabled){this.oneStatDebugLog({message:`operation ${e.operation} but statistics is disabled`});return}if(this.config.disabledOperations.includes(e.operation)){this.oneStatDebugLog({message:`operation ${e.operation} but it is disabled`});return}this.oneStatDebugLog({message:`operation ${e.operation} ${e.param}`});let t=this.createLogItem(e,i);this.logger.log(t)}createLogItem({operation:e,param:i,time:t},o={}){var u,g;let r=(g=(u=this.timeSynchronisation)==null?void 0:u.now())!=null?g:b(),n=this.vsid$.getValue();Be(n);let c=this.isid$.getValue(),l=e==="empty_buffer"||e==="close_at_empty_buffer"?this.statContext.connectionType:this.statContext.firstConnectionType,d=this.statContext.firstConnectionReused,p,h;if(this.isEmbed){p=this.embedParent;let v=[...new URLSearchParams(location.search).entries()].filter(([S,y])=>this.config.embedUrlParams.includes(S));h=new URLSearchParams(v).toString()}else this.statContext.place==="direct"&&((this.statContext.refDomain||document.referrer)&&(p=new URL(this.statContext.refDomain||document.referrer).hostname),h=location.href.substring(0,1024));let s={vsid:n,isid:c,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?"auto":this.statContext.autoplay===!1?"":void 0,param:i,vk_app_id:this.statContext.vkAppId,track_code:this.statContext.trackCode,connection_type:l,connection_reused:d===!0?1:d===!1?0:void 0,cached_data:this.statContext.cached===!0?1:this.statContext.cached===!1?0:void 0,live:this.statContext.liveEdge?1:void 0,muted:this.statContext.audible===!1?1:void 0,mode:this.statContext.mode,subtitles:this.statContext.subtitles,download_speed:this.statContext.downloadSpeed,manual_quality:this.statContext.autoQuality?void 0:1,ref_domain:p,direct_url:h,rate:this.statContext.rate===1||ye(this.statContext.rate)?void 0:this.statContext.rate.toFixed(2),view_360:this.statContext.is3d?1:void 0,aid:this.statContext.albumId,vk_playlist_id:this.statContext.vkPlaylistId,...o};for(let v of this.config.disabledCustomFields)delete s[v];return{operation:e,type:1,time:t,network:this.statContext.network,timestamp:r,custom:s}}};export{_ as ApiEnv,B as ConnectionType,M as ContentType,ee as InteractiveInterfaceClick,Z as OneStat,D as Quality,F as SeekAction,w as VERSION};
package/esnext.cjs.js CHANGED
@@ -1,6 +1,6 @@
1
1
  /**
2
- * @vkontakte/videoplayer-statistics v1.0.52-dev.22c05d5f.0
3
- * Tue, 30 Jul 2024 08:28:10 GMT
2
+ * @vkontakte/videoplayer-statistics v1.0.52-dev.a5f6699f.0
3
+ * Tue, 30 Jul 2024 10:43:01 GMT
4
4
  * https://st.mycdn.me/static/vkontakte-videoplayer/1-0-52/doc/
5
5
  */
6
- "use strict";var V=Object.defineProperty;var he=Object.getOwnPropertyDescriptor;var fe=Object.getOwnPropertyNames;var ge=Object.prototype.hasOwnProperty;var me=(r,e)=>{for(var i in e)V(r,i,{get:e[i],enumerable:!0})},be=(r,e,i,t)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of fe(e))!ge.call(r,o)&&o!==i&&V(r,o,{get:()=>e[o],enumerable:!(t=he(e,o))||t.enumerable});return r};var ve=r=>be(V({},"__esModule",{value:!0}),r);var Pe={};me(Pe,{ApiEnv:()=>P,ConnectionType:()=>L,ContentType:()=>k,InteractiveInterfaceClick:()=>U,OneStat:()=>M,Quality:()=>w,SeekAction:()=>$,VERSION:()=>_});module.exports=ve(Pe);var P=(a=>(a.PROD="prod",a.VK_ALIAS="vk_alias",a.VIDEOTEST="videotest",a.TEST="test",a.AUTO="auto",a))(P||{}),w=(h=>(h.Q144P="mobile",h.Q240P="lowest",h.Q360P="low",h.Q480P="medium",h.Q720P="high",h.Q1080P="fullhd",h.Q1440P="quadhd",h.Q2160P="ultrahd",h.UNKNOWN="unknown",h))(w||{}),k=(u=>(u.MP4="mp4",u.DASH="dash",u.DASH_SEP="dash_sep",u.ONDEMAND_DASH="ondemand_dash",u.HLS="hls",u.ONDEMAND_HLS="ondemand_hls",u.WEBM="webm",u.AV1="av1",u.ONDEMAND_DASH_LIVE="ondemand_dash_live",u.ONDEMAND_HLS_LIVE="ondemand_hls_live",u.WEBRTC="webrtc",u.UNKNOWN="unknown",u.RTMP="rtmp",u))(k||{});var L=(t=>(t.HTTP1="http1",t.HTTP2="http2",t.HTTP3="http3",t))(L||{});var $=(l=>(l.SLIDER="slider",l.DOUBLE_TAP="double_tap",l.TIME_CODE="time_code",l.EPISODE="episode",l.REWIND="rewind",l.LIVE="live",l.UNKNOWN="unknown",l))($||{}),U=(a=>(a.GRAPH_SHOW="iGraphShow",a.GRAPH_HIDE="iGraphHide",a.NEXT_AREA="iNextChapterArea",a.NEXT_BUTTON="iNextChapterBtn",a.WATCH_AGAIN="iWatchAgainBtn",a))(U||{}),Y={action_play:"ap",action_play_interactive:"api",first_bytes:"fb",player_ready:"pr",first_frame:"ff",seek:"sk",watch_coverage_record:"wr",watch_coverage_live:"wl",empty_buffer:"eb",action_stop:"as",close_at_empty_buffer:"cb",content_error:"er",player_interface_click:"pc",next_movie:"nm",track_switch:"ts",failover:"fo"},X={vsid:"si",isid:"is",vid:"vi",place:"pl",quality:"qt",cdn_host:"ch",stat_type:"st",param:"pm",vk_app_id:"va",track_code:"tc",connection_type:"cnt",connection_reused:"cr",cached_data:"cd",live:"lv",muted:"mu",mode:"mo",subtitles:"sb",failover:"fo",download_speed:"ds",manual_quality:"mq",ref_domain:"rd",direct_url:"du"},J={unknown:"un",mobile:"m",lowest:"ls",low:"l",medium:"md",high:"h",fullhd:"f",quadhd:"q",ultrahd:"u"},Z={pip:"pi",fullscreen:"fs",external:"ex",prefetch:"pr",airplay:"ap",chromecast:"cc",invisible:"iv"};var ee=require("@vkontakte/videoplayer-shared"),Ie={apiEnv:"vk_alias",requestRetryCount:1,firstFlushTime:5e3,flushDebounceTime:1e4,flushMaxWait:6e4,storageExpiration:36*60*60*1e3,watchCoverageInterval:15e3,disabledOperations:[],disabledCustomFields:[],shorten:!0,maxLoops:100,embedUrlParams:[],useBeacon:!0,synchronizeTime:!0,debugLog:!1,backoff:{start:1e3,factor:1.5,max:5*60*1e3,random:.1}},te=r=>(0,ee.fillWithDefault)(r,Ie);function W(){let r="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".split(""),e=new Array(36),i=0,t,o;for(o=0;o<36;o++)o===8||o===13||o===18||o===23?e[o]="-":o===14?e[o]="4":(i<=2&&(i=33554432+Math.random()*16777216|0),t=i&15,i=i>>4,e[o]=r[o===19?t&3|8:t]);return e.join("")}var n=require("@vkontakte/videoplayer-shared"),B=require("@vkontakte/videoplayer-shared");var ie=r=>{let{operation:e,custom:i}=r,t=Object.fromEntries(Object.entries(i).map(([o,a])=>{let c=X[o]??o,l=a;return a&&(o==="mode"?l=Z[a]??a:o==="quality"&&(l=J[a]??a)),[c,l]}));return{...r,operation:Y[e]??e,custom:t}};var _="1.0.52-dev.22c05d5f.0",oe="CIOPGQJGDIHBABABA",H={prod:"https://api.ok.ru",vk_alias:"https://api.mycdn.me",videotest:"https://videotestapi.ok.ru/api",test:"https://apitest.ok.ru",auto:""};var I=require("@vkontakte/videoplayer-shared");var x=class{constructor(e){this.consequentAuthErrors=0;this.authorized$=new I.ValueSubject(!1);this.params=e}async authorize(e){return this.authToken=e??await this.refreshAuthToken(),this._authorizeWithBackoff()}logBeacon(e){let i="log.externalLog",t=this.createLogParams(e),o=this.sessionKey;if(!o)return;this.params.apiTransport.sendBeacon(i,t,o)||this.logRequest(e)}async logRequest(e){let i="log.externalLog",t=this.createLogParams(e),o=this.sessionKey??await this._authorizeWithBackoff();if(!o)return;let a=async(c,l=this.params.config.requestRetryCount)=>{try{return await this.params.apiTransport.sendRequest(i,t,o)}catch(f){if(!f||!("error_code"in f)){this.params.error$.next({id:"logRequestUnknown",category:I.ErrorCategory.NETWORK,message:`Unknown ${i} error`,thrown:f});return}let h=f?.error_code;switch(h){case 102:case 103:case 104:return this.authorized$.next(!1),this.sessionKey=await this._authorizeWithBackoff(),l>0?a(c,l-1):void 0;case 401:return this.authorized$.next(!1),this.authToken=await this.refreshAuthToken(),this.sessionKey=await this._authorizeWithBackoff(),l>0?a(c,l-1):void 0;default:{this.params.error$.next({id:`LogRequest#${h}`,category:I.ErrorCategory.EXTERNAL_API,message:`${i} error`,data:f});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:${_}`,platform:this.params.mobile?"M_WEB":"WEB",items:this.params.config.shorten?e.map(ie):e})}}_authorizeWithBackoff(){if(!this.consequentAuthErrors)return this._authorize();let e=(0,I.getExponentialDelay)(this.consequentAuthErrors,this.params.config.backoff);return new Promise(i=>{this.backoffTimeoutId||(this.backoffTimeoutId=window.setTimeout(()=>{this._authorize().then(i).catch(t=>this.params.error$.next({id:"AuthorizeBackoff",category:I.ErrorCategory.NETWORK,message:"Otherwise unhandled error in authorization",thrown:t})).finally(()=>this.backoffTimeoutId=0)},e))})}async _authorize(){if(this.authorizePromise)return this.authorizePromise;this.sessionKey=void 0,this.authorized$.next(!1);let e="auth.anonymLogin",i={session_data:{version:2,device_id:this.params.uuid,client_version:_.split("-")[0],client_type:"SDK_JS"}};return this.authToken!==void 0&&(i.session_data.auth_token=this.authToken,i.session_data.version=3),this.authorizePromise=this.params.apiTransport.sendRequest(e,i).then(t=>((!t||!t.session_key)&&this.params.error$.next({id:"AuthorizeFailed",category:I.ErrorCategory.EXTERNAL_API,message:"No session key",data:t}),this.sessionKey=t?.session_key??void 0,this.sessionKey)).catch(async t=>{this.sessionKey=void 0;let o=t?.error_code;switch(o){case 401:return this.authToken=await this.refreshAuthToken(),this._authorizeWithBackoff()}o?this.params.error$.next({id:`Authorize#${o}`,category:I.ErrorCategory.EXTERNAL_API,message:"authorize error",data:t}):this.params.error$.next({id:"AuthorizeUnknown",category:I.ErrorCategory.NETWORK,message:"authorize error",thrown:t})}).finally(()=>{this.authorizePromise=void 0,this.consequentAuthErrors=this.sessionKey?0:this.consequentAuthErrors+1,this.authorized$.next(this.sessionKey!==void 0)}),this.authorizePromise}};var S=require("@vkontakte/videoplayer-shared");var T=class{constructor(e){this.params=e,this.apiKey=e.apiKey,this.apiEnv=e.config.apiEnv,this.apiBaseUrl=H[this.apiEnv],this.timeSynchronisation=e.timeSynchronisation,this.isApiBaseUrlFetched=!1}async resolveApiBaseUrl(){if(this.apiEnv!=="auto"||this.isApiBaseUrlFetched)return this.apiBaseUrl;try{let e=atob("aHR0cHM6Ly9kbnMuZ29vZ2xlL3Jlc29sdmU/bmFtZT12aWRlby5fZW5kcG9pbnQub2sucnUmdHlwZT1UWFQ="),o=(await(await fetch(e,{method:"GET",mode:"cors",cache:"no-cache"})).json())?.Answer[0]?.data;if(!o)throw new Error("Wrong DNS response");return o}catch(e){return this.params.error$.next({id:"OneStat:ApiTransport:resolveApiBaseUrl",category:S.ErrorCategory.NETWORK,message:"Unhandled resolve api base url error",thrown:e}),H.vk_alias}finally{this.isApiBaseUrlFetched=!0}}sendBeacon(e,i,t){if(!window.Blob||!window.navigator.sendBeacon)return!1;let o=this._prepareQueryParams({method:e,queryParams:i,sessionKey:t}),a=new window.Blob([o.toString()],{type:"application/x-www-form-urlencoded"});try{return window.navigator.sendBeacon(`${this.apiBaseUrl}/fb.do`,a)}catch(c){this.params.error$.next({id:"OneStat:ApiTransport:sendBeacon",category:S.ErrorCategory.NETWORK,message:"Unhandled beacon error",thrown:c,data:{method:e,params:i}})}return!1}async sendRequest(e,i,t){let o=(0,S.now)(),a=c=>{if(c instanceof TypeError&&["Failed to fetch","NetworkError when attempting to fetch resource."].includes(c.message)){this.params.error$.next({id:"Network",category:S.ErrorCategory.NETWORK,message:"Request failed",thrown:c});return}this.params.error$.next({id:"OneStat:ApiTransport:sendRequest",category:S.ErrorCategory.NETWORK,message:"Unhandled request error",thrown:c,data:{method:e,params:i,sessionKey:t,time:(0,S.now)()-o}})};return this.apiBaseUrl=await this.resolveApiBaseUrl(),fetch(`${this.apiBaseUrl}/fb.do`,{method:"post",headers:{"Content-type":"application/x-www-form-urlencoded"},body:this._prepareQueryParams({method:e,queryParams:i,sessionKey:t})}).then(c=>{let l=Number(c.headers.get("content-length"))===0,f=new Date(c.headers.get("date")??"").getTime(),h=(0,S.now)()-o;if(isFinite(f)&&this.timeSynchronisation?.addServerTime(f,h),!l)return c.json().then(g=>Object.prototype.hasOwnProperty.call(g,"error_msg")?Promise.reject(g):g,a)},a)}_prepareQueryParams(e){let i=new URLSearchParams({format:"JSON",method:e.method,application_key:this.apiKey});return e.sessionKey!==void 0&&i.append("session_key",e.sessionKey),Object.entries(e.queryParams).forEach(([t,o])=>i.append(t,typeof o=="string"?o:JSON.stringify(o))),i}};var m=require("@vkontakte/videoplayer-shared"),R="onestat_events",K=r=>e=>e.timestamp+r>=(0,m.now)(),O=class{constructor(e){this.unsaltedStorage=[];this.isPaused=!1;this.isUrgent=e=>{let{operation:i}=e;return["action_play","watch_coverage_record","watch_coverage_live"].includes(i)};this.params=e,this.api=e.api,this.error$=e.error$,this.userSalt=e.userSalt,this.loggerDebugLog=e.debugLogger.createComponentLog("stat logger"),this.firstFlush=(0,m.debounceFn)(()=>this.safeFlush(),this.params.config.firstFlushTime,{maxWait:this.params.config.firstFlushTime});let i=m.safeStorage.isPersistent()?this.params.config.flushMaxWait:0;this.debouncedFlush=(0,m.debounceFn)(()=>this.safeFlush(),this.params.config.flushDebounceTime,{maxWait:i}),this.subscription=this.api.authorized$.subscribe(t=>{t&&this.debouncedFlush()}),this.housekeepStorage()}safeFlush(){try{this.flush()}catch(e){this.error$.next({id:"LoggerError",category:m.ErrorCategory.WTF,message:String(e)??"Unknown logger error",thrown:e})}}readFromStorage(){let e=m.safeStorage.get(R);try{return e?JSON.parse(e):{}}catch{}return{}}addToStorage(e){if(!this.userSalt){this.unsaltedStorage.push(e);return}let i=this.readFromStorage(),o=(i[this.userSalt]??[]).filter(K(this.params.config.storageExpiration));m.safeStorage.set(R,JSON.stringify({...i,[this.userSalt]:[...o,e]}))}getFromStorage(){return this.userSalt?(this.readFromStorage()[this.userSalt]??[]).filter(K(this.params.config.storageExpiration)):this.unsaltedStorage}markStorageSent(){if(!this.userSalt){this.unsaltedStorage=[];return}let e=this.readFromStorage();delete e[this.userSalt],m.safeStorage.set(R,JSON.stringify(e))}housekeepStorage(){let e=this.readFromStorage();for(let[i,t]of Object.entries(e)){let o=t.filter(K(this.params.config.storageExpiration));o.length?e[i]=o:delete e[i],this.loggerDebugLog({message:`${t.length} retrieved from storage, ${o.length} of them actual`})}m.safeStorage.set(R,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){let i=this.getFromStorage();i.length!==0&&(this.api.authorized$.getValue()?(e&&this.params.config.useBeacon?(this.loggerDebugLog({message:`Flushing ${i.length} events through beacon`}),this.api.logBeacon(i)):(this.loggerDebugLog({message:`Flushing ${i.length} events`}),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()}};var d=require("@vkontakte/videoplayer-core"),q=require("@vkontakte/videoplayer-shared");var se=r=>r&&{[d.VideoQuality.INVARIANT]:"unknown",[d.VideoQuality.Q_144P]:"mobile",[d.VideoQuality.Q_240P]:"lowest",[d.VideoQuality.Q_360P]:"low",[d.VideoQuality.Q_480P]:"medium",[d.VideoQuality.Q_720P]:"high",[d.VideoQuality.Q_1080P]:"fullhd",[d.VideoQuality.Q_1440P]:"quadhd",[d.VideoQuality.Q_2160P]:"ultrahd",[d.VideoQuality.Q_4320P]:"unknown"}[r],z=r=>r&&{[d.HttpConnectionType.HTTP1]:"http1",[d.HttpConnectionType.HTTP2]:"http2",[d.HttpConnectionType.QUIC]:"http3"}[r],re=r=>{if(r!==void 0)switch(r){case d.VideoFormat.MPEG:return"mp4";case d.VideoFormat.DASH:case d.VideoFormat.DASH_LIVE:case d.VideoFormat.DASH_STREAMS:return"dash";case d.VideoFormat.DASH_SEP:return"dash_sep";case d.VideoFormat.DASH_ONDEMAND:return"ondemand_dash";case d.VideoFormat.DASH_WEBM:case d.VideoFormat.DASH_LIVE_WEBM:return"webm";case d.VideoFormat.DASH_WEBM_AV1:return"av1";case d.VideoFormat.DASH_LIVE_CMAF:return"ondemand_dash_live";case d.VideoFormat.HLS:case d.VideoFormat.HLS_LIVE:return"hls";case d.VideoFormat.HLS_ONDEMAND:return"ondemand_hls";case d.VideoFormat.HLS_LIVE_CMAF:return"ondemand_hls_live";case d.VideoFormat.WEB_RTC_LIVE:return"webrtc";default:return(0,q.assertNever)(r)}},N=r=>{if(r!==void 0)switch(r){case d.Surface.NONE:case d.Surface.INLINE:return;case d.Surface.FULLSCREEN:return"fullscreen";case d.Surface.SECOND_SCREEN:return"chromecast";case d.Surface.PIP:return"pip";case d.Surface.INVISIBLE:return"invisible";default:return(0,q.assertNever)(r)}},ne=r=>{switch(r){case"slow-2g":return"poor";case"2g":return"poor";case"3g":return"good";case"4g":return"excellent"}};var D=class{constructor(e){this.offset=void 0;this.offset=e}getOffset(){return this.offset??0}setOffset(e){this.offset=e}now(){return Date.now()+(this.offset??0)}date(e=new Date){return e.setTime(e.getTime()+(this.offset??0)),e}addServerTime(e,i){let t=Date.now(),o=e-t-i/2;if(Math.abs(o)<1e3){this.offset=0;return}this.offset===void 0?this.offset=Math.round(o):this.offset=Math.round(.2*o+(1-.2)*this.offset)}};var ae=()=>Math.floor(Math.random()*4294967296).toString(36).padStart(7,"0"),de=()=>Math.floor(Math.random()*18446744073709552e3).toString(36).padStart(13,"0");var Q=require("@vkontakte/videoplayer-core"),p=require("@vkontakte/videoplayer-shared"),ue=(r,e)=>new p.Observable(i=>{let t=new p.Subscription,o=(0,p.merge)((0,p.fromEvent)(window,"beforeunload"),r.events.willDestruct$),a=new p.ValueSubject(void 0),c;t.add(r.info.isLive$.pipe((0,p.filterChanged)()).subscribe(y=>{c&&(c.unsubscribe(),a.next(void 0)),y?c=r.info.liveTime$.pipe((0,p.map)(F=>F&&F/1e3)).subscribe(a):c=r.info.position$.subscribe(a),t.add(c)}));let{playing$:l,paused$:f}=r.events,h=r.events.willSeek$.pipe((0,p.filter)(()=>r.info.playbackState$.getValue()===Q.PlaybackState.PLAYING)),g=r.events.seeked$.pipe((0,p.filter)(()=>r.info.playbackState$.getValue()===Q.PlaybackState.PLAYING)),v=!1,s=new p.Subject;t.add(h.subscribe(()=>{v||s.next(),v=!0})),t.add(g.subscribe(()=>v=!1));let u=new p.Subject,b=new p.Subject,A=(0,p.merge)(l,g,u),C=(0,p.merge)(f,s,o,r.events.looped$,b),E,ce=()=>E=a.getValue(),le=()=>{let y=a.getValue();(0,p.isNullable)(E)||E===y||(0,p.isNullable)(y)||(i.next({from:E,to:y}),E=void 0)},pe=()=>{b.next(),u.next()};if(t.add(A.subscribe(ce)),t.add(C.subscribe(le)),e.forceInterval&&isFinite(e.forceInterval)){let y=0;t.add(A.subscribe(()=>y=window.setTimeout(pe,e.forceInterval))),t.add(C.subscribe(()=>window.clearTimeout(y)))}return t});var ye="_one-stat_",j=`${ye}uuid`,G=()=>{let r=new n.Subscription;return{subscription:r,subscribe:(e,i)=>{e&&r.add(e.subscribe(i))}}},M=class{constructor(e,i){this.subscription=new n.Subscription;this.debugLogger=new B.Logger;this.oneStatDebugLog=this.debugLogger.createComponentLog("onestat");this.loopCounter=0;this.disabled=!1;this.vsid$=new n.ValueSubject(void 0);this.isid$=new n.ValueSubject(void 0);this.seekAction$=new n.ValueSubject("unknown");this.statContext=e,this.config=te(i.config??{}),(0,n.isNonNullable)(i.apiEnv)&&(this.config.apiEnv=i.apiEnv),this.config.synchronizeTime&&(this.timeSynchronisation=new D);let t=new n.Subject;this.experimental={error$:t};let o=n.safeStorage.get(j);o?o.startsWith('"')&&o.endsWith('"')?(this.uuid=o.replaceAll('"',""),n.safeStorage.set(j,this.uuid)):this.uuid=o:(this.uuid=W(),n.safeStorage.set(j,this.uuid)),this.resetViewSession(),i.useIsid&&this.isid$.next(i.isid??de());let a=new T({apiKey:oe,config:this.config,error$:t,timeSynchronisation:this.timeSynchronisation});this.api=new x({config:this.config,apiTransport:a,refreshAuthToken:i.refreshAuthToken,mobile:this.statContext.mobile??!1,uuid:this.uuid,error$:t}),this.logger=new O({config:this.config,debugLogger:this.debugLogger,api:this.api,error$:t,userSalt:i.userSalt});let{isEmbed:c,host:l}=(0,B.detectEmbed)();this.isEmbed=c,this.embedParent=l,this.subscribe()}updateContext(e){this.statContext={...this.statContext,...e}}attachTo(e){let i=new n.Subscription,t=(s,u)=>i.add(s.subscribe(u));t(e.events.willStart$,()=>{let s=e.info.position$.getValue();this.logActionPlay({position:s}),this.statContext.projectId&&this.logActionPlayInteractive()}),t(e.events.looped$,()=>{this.resetViewSession(),++this.loopCounter>this.config.maxLoops&&(this.disabled=!0),this.logActionPlay({position:e.info.position$.getValue()})}),t(e.events.seeked$,()=>{this.logSeek({action:this.seekAction$.getValue(),time:e.info.position$.getValue()}),this.seekAction$.next("unknown")}),t(e.events.paused$,()=>{this.logPause({position:e.info.position$.getValue()})}),t(e.events.willResume$,()=>{this.logPlay()}),t(e.events.started$,()=>{this.statContext.clip&&this.logWatchCoverageRecord({start:0,end:0})}),t(e.events.playing$,()=>{this.logPlaying()}),t(ue(e,{forceInterval:this.config.watchCoverageInterval}),s=>{let u=e.info.isLive$.getValue(),b={start:parseFloat(s.from.toFixed(3)),end:parseFloat(s.to.toFixed(3))};u?this.logWatchCoverageLive(b):this.logWatchCoverageRecord(b)});let o;t(e.info.isStalled$,s=>{s?o=(0,n.now)():((0,n.isNonNullable)(o)&&this.logEmptyBuffer({duration:(0,n.now)()-o}),o=void 0)});let a=!1;i.add(e.events.fatalError$.pipe((0,n.once)()).subscribe(()=>a=!0)),t(e.events.willStop$,()=>{if(e.info.isStalled$.getValue()){let u=(0,n.isNonNullable)(o)?(0,n.now)()-o:void 0;this.logCloseAtEmptyBuffer({duration:u??0}),o=void 0}else a||this.logActionStop()}),t(e.events.managedError$,({id:s})=>{this.logError({fatal:!1,errorType:s})}),t(e.events.fatalError$,({id:s})=>{this.logError({fatal:!0,errorType:s})});let c,l,f=!1;t(e.events.firstBytes$,s=>{c=(0,n.now)(),this.logFirstBytes({time:s})}),t(e.events.willStart$,()=>l=(0,n.now)()),t(e.info.currentBuffer$,s=>{!f&&s&&s.end-s.start>0&&(0,n.isNonNullable)(c)&&(this.logPlayerReady({duration:(0,n.now)()-c}),f=!0)}),t(e.events.firstFrame$,()=>{(0,n.isNonNullable)(c)&&!f&&(this.logPlayerReady({duration:(0,n.now)()-c}),f=!0),(0,n.isNonNullable)(l)&&this.logFirstFrame({time:(0,n.now)()-l})});let h;t(e.info.currentVideoStream$,s=>{s&&(h&&s.id!==h&&this.logTrackSwitch(s),h=s.id)});let g;t(e.info.currentAudioStream$,s=>{s&&(g&&s.id!==g&&this.logTrackSwitch(s),g=s.id)}),t(e.info.atLiveEdge$,s=>this.updateContext({liveEdge:s})),t((0,n.combine)({muted:e.info.muted$,volume:e.info.volume$}),({muted:s,volume:u})=>this.updateContext({audible:!s&&u>0})),t(e.info.currentQuality$,s=>this.updateContext({quality:se(s)})),t(e.info.isAutoQualityEnabled$,s=>this.updateContext({autoQuality:s})),t(e.info.currentFormat$,s=>this.updateContext({contentType:re(s)})),t(e.info.currentPlaybackRate$,s=>this.updateContext({rate:s})),t(e.info.is3DVideo$,s=>this.updateContext({is3d:s}));let v;return t(e.info.hostname$,s=>{let u=v!==void 0&&v!==s;this.updateContext({cdnHostname:s,failover:u}),u&&this.logFailover(s),v=s}),t(e.info.throughputEstimation$,s=>this.updateContext({downloadSpeed:s})),t(e.info.httpConnectionType$,s=>{this.statContext.firstConnectionType||this.updateContext({firstConnectionType:z(s)}),this.updateContext({connectionType:z(s)})}),t(e.info.httpConnectionReused$,s=>{(0,n.isNullable)(this.statContext.firstConnectionReused)&&this.updateContext({firstConnectionReused:s}),this.updateContext({connectionReused:s})}),t(e.info.surface$,s=>this.updateContext({mode:N(s)})),t((0,n.combine)({current:e.info.currentTextTrack$,available:e.info.availableTextTracks$}),({current:s,available:u})=>{let b=u.find(({id:C})=>C===s),A=b&&(b.isAuto?`${b.language}_auto`:b.language);this.updateContext({subtitles:A})}),this.player=e,this.uiEvents&&this.attachToUi(this.uiEvents),this.resubscribeBeforeunload(),this.subscription.add(i),i}attachToUi(e){this.uiEvents=e;let{subscription:i,subscribe:t}=G();return this.player&&(t(e.actionRewind$,()=>{this.player&&(this.resetViewSession(),this.logActionPlay({position:this.player.info.position$.getValue()}))}),t(e.actionSeek$,this.seekAction$),t(e.inPiP$,o=>{let a=o?"pip":N(this.player?.info.surface$.getValue());this.updateContext({mode:a})}),t(e.inFullscreen$,o=>{let a=o?"fullscreen":N(this.player?.info.surface$.getValue());this.updateContext({mode:a})}),t(e.actionSetSubtitle$,o=>this.updateContext({subtitles:o})),t(e.nextMovie$,o=>this.logNextMovie(o)),this.resubscribeBeforeunload(),this.subscription.add(i)),i}attachToAds(e){let{subscription:i,subscribe:t}=G();return t(e.slotRequested$,()=>this.logAdSlotRequest()),t(e.started$,o=>this.logAdStarted(o)),t(e.paused$,()=>this.logAdPaused()),t(e.resumed$,()=>this.logAdResumed()),t(e.ended$,()=>this.logAdEnded()),t(e.skipped$,()=>this.logAdSkipped()),t(e.clicked$,()=>this.logAdClicked()),this.resubscribeBeforeunload(),this.subscription.add(i),i}attachToInteractive(e){let{subscription:i,subscribe:t}=G();return t(e.click$,o=>this.logInterfaceClick(o)),t(e.nextMovie$,o=>this.logNextMovie(o)),this.resubscribeBeforeunload(),this.subscription.add(i),i}authorize(e){return this.api.authorize(e)}pause(){this.logger.pause(),this.oneStatDebugLog({message:"paused"})}resume(){this.logger.resume(),this.oneStatDebugLog({message:"resumed"})}destroy(){this.logger.flush(),this.subscription.unsubscribe(),this.api.destroy(),this.logger.destroy()}resetViewSession(){this.oneStatDebugLog({message:"VSID reset"}),this.vsid$.next(ae())}getDeviceId(){return this.uuid}setFieldBlacklist(){}logInited(){}logReady(e){this.log({operation:"player_ready",param:String(e.time)})}logStarted(...e){this.logActionPlay(...e)}logPlay(){this.log({operation:"play_toggle"})}logPlaying(){this.log({operation:"playing"})}logPause(e){this.log({operation:"pause",param:String(Math.round(e.position))})}logSeek(e){this.log({operation:"seek",param:e.action,time:e.time})}logFirstBytes(e){this.log({operation:"first_bytes",param:String(e.time)})}logFirstFrame(e){this.log({operation:"first_frame",param:String(e.time)})}logError(e){this.log({operation:"content_error",param:`${e.fatal?"fatal":"recoverable"}_${e.errorType}`})}logWatchCoverageRecord(e){this.log({operation:"watch_coverage_record",param:`${e.start}-${e.end}`})}logWatchCoverageLive(e){let i=this.timeSynchronisation?.getOffset()??0,t=e.start+i,o=e.end+i;this.log({operation:"watch_coverage_live",param:`${t}-${o}`})}logEmptyBuffer(e){this.log({operation:"empty_buffer",param:String(e.duration)})}logDownloadSpeed(){}logAdSlotRequest(){this.log({operation:"adv",param:"slot_request"})}logAdStarted(e){this.log({operation:"adv",param:e})}logAdPaused(){this.log({operation:"adv",param:"pause"})}logAdResumed(){this.log({operation:"adv",param:"resume"})}logAdEnded(){this.log({operation:"adv",param:"ended"})}logAdSkipped(){this.log({operation:"adv",param:"skip"})}logAdClicked(){this.log({operation:"adv",param:"click"})}logInterfaceClick(e){this.log({operation:"player_interface_click",param:e})}logNextMovie(e){this.log({operation:"next_movie",param:String(e)})}subscribe(){this.resubscribeBeforeunload();let e=window.navigator.connection;e&&"onchange"in e&&"effectiveType"in e&&this.subscription.add((0,n.merge)((0,n.fromEvent)(e,"change"),(0,n.observableFrom)(["init"])).subscribe(()=>this.updateContext({network:ne(e.effectiveType)}))),this.config.debugLog&&this.debugLogger.log$.subscribe(i=>{console.debug("%c stat ","background:#fa6470;",`component: ${i.component}.`,i.message)})}resubscribeBeforeunload(){this.beforeunloadSubscription?.unsubscribe(),this.beforeunloadSubscription=(0,n.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))})}logActionPlayInteractive(){this.statContext.projectId&&this.log({operation:"action_play_interactive",param:String(this.statContext.movieId)},{vid:this.statContext.projectId})}logFailover(e){this.log({operation:"failover",param:e})}logCloseAtEmptyBuffer(e){this.log({operation:"close_at_empty_buffer",param:String(Math.round(e.duration))})}logActionStop(){this.log({operation:"action_stop"})}logTrackSwitch(e){this.log({operation:"track_switch",param:e.id})}log(e,i={}){if(this.disabled){this.oneStatDebugLog({message:`operation ${e.operation} but statistics is disabled`});return}if(this.config.disabledOperations.includes(e.operation)){this.oneStatDebugLog({message:`operation ${e.operation} but it is disabled`});return}this.oneStatDebugLog({message:`operation ${e.operation} ${e.param}`});let t=this.createLogItem(e,i);this.logger.log(t)}createLogItem({operation:e,param:i,time:t},o={}){let a=this.timeSynchronisation?.now()??(0,n.now)(),c=this.vsid$.getValue();(0,n.assertNonNullable)(c);let l=this.isid$.getValue(),f=e==="empty_buffer"||e==="close_at_empty_buffer"?this.statContext.connectionType:this.statContext.firstConnectionType,h=this.statContext.firstConnectionReused,g,v;if(this.isEmbed){g=this.embedParent;let u=[...new URLSearchParams(location.search).entries()].filter(([b,A])=>this.config.embedUrlParams.includes(b));v=new URLSearchParams(u).toString()}else this.statContext.place==="direct"&&((this.statContext.refDomain||document.referrer)&&(g=new URL(this.statContext.refDomain||document.referrer).hostname),v=location.href.substring(0,1024));let s={vsid:c,isid:l,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?"auto":this.statContext.autoplay===!1?"":void 0,param:i,vk_app_id:this.statContext.vkAppId,track_code:this.statContext.trackCode,connection_type:f,connection_reused:h===!0?1:h===!1?0:void 0,cached_data:this.statContext.cached===!0?1:this.statContext.cached===!1?0:void 0,live:this.statContext.liveEdge?1:void 0,muted:this.statContext.audible===!1?1:void 0,mode:this.statContext.mode,subtitles:this.statContext.subtitles,download_speed:this.statContext.downloadSpeed,manual_quality:this.statContext.autoQuality?void 0:1,ref_domain:g,direct_url:v,rate:this.statContext.rate===1||(0,n.isNullable)(this.statContext.rate)?void 0:this.statContext.rate.toFixed(2),view_360:this.statContext.is3d?1:void 0,aid:this.statContext.albumId,vk_playlist_id:this.statContext.vkPlaylistId,...o};for(let u of this.config.disabledCustomFields)delete s[u];return{operation:e,type:1,time:t,network:this.statContext.network,timestamp:a,custom:s}}};
6
+ "use strict";var V=Object.defineProperty;var he=Object.getOwnPropertyDescriptor;var fe=Object.getOwnPropertyNames;var ge=Object.prototype.hasOwnProperty;var me=(r,e)=>{for(var i in e)V(r,i,{get:e[i],enumerable:!0})},be=(r,e,i,t)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of fe(e))!ge.call(r,o)&&o!==i&&V(r,o,{get:()=>e[o],enumerable:!(t=he(e,o))||t.enumerable});return r};var ve=r=>be(V({},"__esModule",{value:!0}),r);var Pe={};me(Pe,{ApiEnv:()=>P,ConnectionType:()=>L,ContentType:()=>k,InteractiveInterfaceClick:()=>U,OneStat:()=>M,Quality:()=>w,SeekAction:()=>$,VERSION:()=>_});module.exports=ve(Pe);var P=(a=>(a.PROD="prod",a.VK_ALIAS="vk_alias",a.VIDEOTEST="videotest",a.TEST="test",a.AUTO="auto",a))(P||{}),w=(h=>(h.Q144P="mobile",h.Q240P="lowest",h.Q360P="low",h.Q480P="medium",h.Q720P="high",h.Q1080P="fullhd",h.Q1440P="quadhd",h.Q2160P="ultrahd",h.UNKNOWN="unknown",h))(w||{}),k=(u=>(u.MP4="mp4",u.DASH="dash",u.DASH_SEP="dash_sep",u.ONDEMAND_DASH="ondemand_dash",u.HLS="hls",u.ONDEMAND_HLS="ondemand_hls",u.WEBM="webm",u.AV1="av1",u.ONDEMAND_DASH_LIVE="ondemand_dash_live",u.ONDEMAND_HLS_LIVE="ondemand_hls_live",u.WEBRTC="webrtc",u.UNKNOWN="unknown",u.RTMP="rtmp",u))(k||{});var L=(t=>(t.HTTP1="http1",t.HTTP2="http2",t.HTTP3="http3",t))(L||{});var $=(l=>(l.SLIDER="slider",l.DOUBLE_TAP="double_tap",l.TIME_CODE="time_code",l.EPISODE="episode",l.REWIND="rewind",l.LIVE="live",l.UNKNOWN="unknown",l))($||{}),U=(a=>(a.GRAPH_SHOW="iGraphShow",a.GRAPH_HIDE="iGraphHide",a.NEXT_AREA="iNextChapterArea",a.NEXT_BUTTON="iNextChapterBtn",a.WATCH_AGAIN="iWatchAgainBtn",a))(U||{}),Y={action_play:"ap",action_play_interactive:"api",first_bytes:"fb",player_ready:"pr",first_frame:"ff",seek:"sk",watch_coverage_record:"wr",watch_coverage_live:"wl",empty_buffer:"eb",action_stop:"as",close_at_empty_buffer:"cb",content_error:"er",player_interface_click:"pc",next_movie:"nm",track_switch:"ts",failover:"fo"},X={vsid:"si",isid:"is",vid:"vi",place:"pl",quality:"qt",cdn_host:"ch",stat_type:"st",param:"pm",vk_app_id:"va",track_code:"tc",connection_type:"cnt",connection_reused:"cr",cached_data:"cd",live:"lv",muted:"mu",mode:"mo",subtitles:"sb",failover:"fo",download_speed:"ds",manual_quality:"mq",ref_domain:"rd",direct_url:"du"},J={unknown:"un",mobile:"m",lowest:"ls",low:"l",medium:"md",high:"h",fullhd:"f",quadhd:"q",ultrahd:"u"},Z={pip:"pi",fullscreen:"fs",external:"ex",prefetch:"pr",airplay:"ap",chromecast:"cc",invisible:"iv"};var ee=require("@vkontakte/videoplayer-shared"),Ie={apiEnv:"vk_alias",requestRetryCount:1,firstFlushTime:5e3,flushDebounceTime:1e4,flushMaxWait:6e4,storageExpiration:36*60*60*1e3,watchCoverageInterval:15e3,disabledOperations:[],disabledCustomFields:[],shorten:!0,maxLoops:100,embedUrlParams:[],useBeacon:!0,synchronizeTime:!0,debugLog:!1,backoff:{start:1e3,factor:1.5,max:5*60*1e3,random:.1}},te=r=>(0,ee.fillWithDefault)(r,Ie);function W(){let r="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".split(""),e=new Array(36),i=0,t,o;for(o=0;o<36;o++)o===8||o===13||o===18||o===23?e[o]="-":o===14?e[o]="4":(i<=2&&(i=33554432+Math.random()*16777216|0),t=i&15,i=i>>4,e[o]=r[o===19?t&3|8:t]);return e.join("")}var n=require("@vkontakte/videoplayer-shared"),B=require("@vkontakte/videoplayer-shared");var ie=r=>{let{operation:e,custom:i}=r,t=Object.fromEntries(Object.entries(i).map(([o,a])=>{let c=X[o]??o,l=a;return a&&(o==="mode"?l=Z[a]??a:o==="quality"&&(l=J[a]??a)),[c,l]}));return{...r,operation:Y[e]??e,custom:t}};var _="1.0.52-dev.a5f6699f.0",oe="CIOPGQJGDIHBABABA",H={prod:"https://api.ok.ru",vk_alias:"https://api.mycdn.me",videotest:"https://videotestapi.ok.ru/api",test:"https://apitest.ok.ru",auto:""};var I=require("@vkontakte/videoplayer-shared");var x=class{constructor(e){this.consequentAuthErrors=0;this.authorized$=new I.ValueSubject(!1);this.params=e}async authorize(e){return this.authToken=e??await this.refreshAuthToken(),this._authorizeWithBackoff()}logBeacon(e){let i="log.externalLog",t=this.createLogParams(e),o=this.sessionKey;if(!o)return;this.params.apiTransport.sendBeacon(i,t,o)||this.logRequest(e)}async logRequest(e){let i="log.externalLog",t=this.createLogParams(e),o=this.sessionKey??await this._authorizeWithBackoff();if(!o)return;let a=async(c,l=this.params.config.requestRetryCount)=>{try{return await this.params.apiTransport.sendRequest(i,t,o)}catch(f){if(!f||!("error_code"in f)){this.params.error$.next({id:"logRequestUnknown",category:I.ErrorCategory.NETWORK,message:`Unknown ${i} error`,thrown:f});return}let h=f?.error_code;switch(h){case 102:case 103:case 104:return this.authorized$.next(!1),this.sessionKey=await this._authorizeWithBackoff(),l>0?a(c,l-1):void 0;case 401:return this.authorized$.next(!1),this.authToken=await this.refreshAuthToken(),this.sessionKey=await this._authorizeWithBackoff(),l>0?a(c,l-1):void 0;default:{this.params.error$.next({id:`LogRequest#${h}`,category:I.ErrorCategory.EXTERNAL_API,message:`${i} error`,data:f});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:${_}`,platform:this.params.mobile?"M_WEB":"WEB",items:this.params.config.shorten?e.map(ie):e})}}_authorizeWithBackoff(){if(!this.consequentAuthErrors)return this._authorize();let e=(0,I.getExponentialDelay)(this.consequentAuthErrors,this.params.config.backoff);return new Promise(i=>{this.backoffTimeoutId||(this.backoffTimeoutId=window.setTimeout(()=>{this._authorize().then(i).catch(t=>this.params.error$.next({id:"AuthorizeBackoff",category:I.ErrorCategory.NETWORK,message:"Otherwise unhandled error in authorization",thrown:t})).finally(()=>this.backoffTimeoutId=0)},e))})}async _authorize(){if(this.authorizePromise)return this.authorizePromise;this.sessionKey=void 0,this.authorized$.next(!1);let e="auth.anonymLogin",i={session_data:{version:2,device_id:this.params.uuid,client_version:_.split("-")[0],client_type:"SDK_JS"}};return this.authToken!==void 0&&(i.session_data.auth_token=this.authToken,i.session_data.version=3),this.authorizePromise=this.params.apiTransport.sendRequest(e,i).then(t=>((!t||!t.session_key)&&this.params.error$.next({id:"AuthorizeFailed",category:I.ErrorCategory.EXTERNAL_API,message:"No session key",data:t}),this.sessionKey=t?.session_key??void 0,this.sessionKey)).catch(async t=>{this.sessionKey=void 0;let o=t?.error_code;switch(o){case 401:return this.authToken=await this.refreshAuthToken(),this._authorizeWithBackoff()}o?this.params.error$.next({id:`Authorize#${o}`,category:I.ErrorCategory.EXTERNAL_API,message:"authorize error",data:t}):this.params.error$.next({id:"AuthorizeUnknown",category:I.ErrorCategory.NETWORK,message:"authorize error",thrown:t})}).finally(()=>{this.authorizePromise=void 0,this.consequentAuthErrors=this.sessionKey?0:this.consequentAuthErrors+1,this.authorized$.next(this.sessionKey!==void 0)}),this.authorizePromise}};var S=require("@vkontakte/videoplayer-shared");var T=class{constructor(e){this.params=e,this.apiKey=e.apiKey,this.apiEnv=e.config.apiEnv,this.apiBaseUrl=H[this.apiEnv],this.timeSynchronisation=e.timeSynchronisation,this.isApiBaseUrlFetched=!1}async resolveApiBaseUrl(){if(this.apiEnv!=="auto"||this.isApiBaseUrlFetched)return this.apiBaseUrl;try{let e=atob("aHR0cHM6Ly9kbnMuZ29vZ2xlL3Jlc29sdmU/bmFtZT12aWRlby5fZW5kcG9pbnQub2sucnUmdHlwZT1UWFQ="),o=(await(await fetch(e,{method:"GET",mode:"cors",cache:"no-cache"})).json())?.Answer[0]?.data;if(!o)throw new Error("Wrong DNS response");return o}catch(e){return this.params.error$.next({id:"OneStat:ApiTransport:resolveApiBaseUrl",category:S.ErrorCategory.NETWORK,message:"Unhandled resolve api base url error",thrown:e}),H.vk_alias}finally{this.isApiBaseUrlFetched=!0}}sendBeacon(e,i,t){if(!window.Blob||!window.navigator.sendBeacon)return!1;let o=this._prepareQueryParams({method:e,queryParams:i,sessionKey:t}),a=new window.Blob([o.toString()],{type:"application/x-www-form-urlencoded"});try{return window.navigator.sendBeacon(`${this.apiBaseUrl}/fb.do`,a)}catch(c){this.params.error$.next({id:"OneStat:ApiTransport:sendBeacon",category:S.ErrorCategory.NETWORK,message:"Unhandled beacon error",thrown:c,data:{method:e,params:i}})}return!1}async sendRequest(e,i,t){let o=(0,S.now)(),a=c=>{if(c instanceof TypeError&&["Failed to fetch","NetworkError when attempting to fetch resource."].includes(c.message)){this.params.error$.next({id:"Network",category:S.ErrorCategory.NETWORK,message:"Request failed",thrown:c});return}this.params.error$.next({id:"OneStat:ApiTransport:sendRequest",category:S.ErrorCategory.NETWORK,message:"Unhandled request error",thrown:c,data:{method:e,params:i,sessionKey:t,time:(0,S.now)()-o}})};return this.apiBaseUrl=await this.resolveApiBaseUrl(),fetch(`${this.apiBaseUrl}/fb.do`,{method:"post",headers:{"Content-type":"application/x-www-form-urlencoded"},body:this._prepareQueryParams({method:e,queryParams:i,sessionKey:t})}).then(c=>{let l=Number(c.headers.get("content-length"))===0,f=new Date(c.headers.get("date")??"").getTime(),h=(0,S.now)()-o;if(isFinite(f)&&this.timeSynchronisation?.addServerTime(f,h),!l)return c.json().then(g=>Object.prototype.hasOwnProperty.call(g,"error_msg")?Promise.reject(g):g,a)},a)}_prepareQueryParams(e){let i=new URLSearchParams({format:"JSON",method:e.method,application_key:this.apiKey});return e.sessionKey!==void 0&&i.append("session_key",e.sessionKey),Object.entries(e.queryParams).forEach(([t,o])=>i.append(t,typeof o=="string"?o:JSON.stringify(o))),i}};var m=require("@vkontakte/videoplayer-shared"),R="onestat_events",K=r=>e=>e.timestamp+r>=(0,m.now)(),O=class{constructor(e){this.unsaltedStorage=[];this.isPaused=!1;this.isUrgent=e=>{let{operation:i}=e;return["action_play","watch_coverage_record","watch_coverage_live"].includes(i)};this.params=e,this.api=e.api,this.error$=e.error$,this.userSalt=e.userSalt,this.loggerDebugLog=e.debugLogger.createComponentLog("stat logger"),this.firstFlush=(0,m.debounceFn)(()=>this.safeFlush(),this.params.config.firstFlushTime,{maxWait:this.params.config.firstFlushTime});let i=m.safeStorage.isPersistent()?this.params.config.flushMaxWait:0;this.debouncedFlush=(0,m.debounceFn)(()=>this.safeFlush(),this.params.config.flushDebounceTime,{maxWait:i}),this.subscription=this.api.authorized$.subscribe(t=>{t&&this.debouncedFlush()}),this.housekeepStorage()}safeFlush(){try{this.flush()}catch(e){this.error$.next({id:"LoggerError",category:m.ErrorCategory.WTF,message:String(e)??"Unknown logger error",thrown:e})}}readFromStorage(){let e=m.safeStorage.get(R);try{return e?JSON.parse(e):{}}catch{}return{}}addToStorage(e){if(!this.userSalt){this.unsaltedStorage.push(e);return}let i=this.readFromStorage(),o=(i[this.userSalt]??[]).filter(K(this.params.config.storageExpiration));m.safeStorage.set(R,JSON.stringify({...i,[this.userSalt]:[...o,e]}))}getFromStorage(){return this.userSalt?(this.readFromStorage()[this.userSalt]??[]).filter(K(this.params.config.storageExpiration)):this.unsaltedStorage}markStorageSent(){if(!this.userSalt){this.unsaltedStorage=[];return}let e=this.readFromStorage();delete e[this.userSalt],m.safeStorage.set(R,JSON.stringify(e))}housekeepStorage(){let e=this.readFromStorage();for(let[i,t]of Object.entries(e)){let o=t.filter(K(this.params.config.storageExpiration));o.length?e[i]=o:delete e[i],this.loggerDebugLog({message:`${t.length} retrieved from storage, ${o.length} of them actual`})}m.safeStorage.set(R,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){let i=this.getFromStorage();i.length!==0&&(this.api.authorized$.getValue()?(e&&this.params.config.useBeacon?(this.loggerDebugLog({message:`Flushing ${i.length} events through beacon`}),this.api.logBeacon(i)):(this.loggerDebugLog({message:`Flushing ${i.length} events`}),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()}};var d=require("@vkontakte/videoplayer-core"),q=require("@vkontakte/videoplayer-shared");var se=r=>r&&{[d.VideoQuality.INVARIANT]:"unknown",[d.VideoQuality.Q_144P]:"mobile",[d.VideoQuality.Q_240P]:"lowest",[d.VideoQuality.Q_360P]:"low",[d.VideoQuality.Q_480P]:"medium",[d.VideoQuality.Q_720P]:"high",[d.VideoQuality.Q_1080P]:"fullhd",[d.VideoQuality.Q_1440P]:"quadhd",[d.VideoQuality.Q_2160P]:"ultrahd",[d.VideoQuality.Q_4320P]:"unknown"}[r],z=r=>r&&{[d.HttpConnectionType.HTTP1]:"http1",[d.HttpConnectionType.HTTP2]:"http2",[d.HttpConnectionType.QUIC]:"http3"}[r],re=r=>{if(r!==void 0)switch(r){case d.VideoFormat.MPEG:return"mp4";case d.VideoFormat.DASH:case d.VideoFormat.DASH_LIVE:case d.VideoFormat.DASH_STREAMS:return"dash";case d.VideoFormat.DASH_SEP:return"dash_sep";case d.VideoFormat.DASH_ONDEMAND:return"ondemand_dash";case d.VideoFormat.DASH_WEBM:case d.VideoFormat.DASH_LIVE_WEBM:return"webm";case d.VideoFormat.DASH_WEBM_AV1:return"av1";case d.VideoFormat.DASH_LIVE_CMAF:return"ondemand_dash_live";case d.VideoFormat.HLS:case d.VideoFormat.HLS_LIVE:return"hls";case d.VideoFormat.HLS_ONDEMAND:return"ondemand_hls";case d.VideoFormat.HLS_LIVE_CMAF:return"ondemand_hls_live";case d.VideoFormat.WEB_RTC_LIVE:return"webrtc";default:return(0,q.assertNever)(r)}},N=r=>{if(r!==void 0)switch(r){case d.Surface.NONE:case d.Surface.INLINE:return;case d.Surface.FULLSCREEN:return"fullscreen";case d.Surface.SECOND_SCREEN:return"chromecast";case d.Surface.PIP:return"pip";case d.Surface.INVISIBLE:return"invisible";default:return(0,q.assertNever)(r)}},ne=r=>{switch(r){case"slow-2g":return"poor";case"2g":return"poor";case"3g":return"good";case"4g":return"excellent"}};var D=class{constructor(e){this.offset=void 0;this.offset=e}getOffset(){return this.offset??0}setOffset(e){this.offset=e}now(){return Date.now()+(this.offset??0)}date(e=new Date){return e.setTime(e.getTime()+(this.offset??0)),e}addServerTime(e,i){let t=Date.now(),o=e-t-i/2;if(Math.abs(o)<1e3){this.offset=0;return}this.offset===void 0?this.offset=Math.round(o):this.offset=Math.round(.2*o+(1-.2)*this.offset)}};var ae=()=>Math.floor(Math.random()*4294967296).toString(36).padStart(7,"0"),de=()=>Math.floor(Math.random()*18446744073709552e3).toString(36).padStart(13,"0");var Q=require("@vkontakte/videoplayer-core"),p=require("@vkontakte/videoplayer-shared"),ue=(r,e)=>new p.Observable(i=>{let t=new p.Subscription,o=(0,p.merge)((0,p.fromEvent)(window,"beforeunload"),r.events.willDestruct$),a=new p.ValueSubject(void 0),c;t.add(r.info.isLive$.pipe((0,p.filterChanged)()).subscribe(y=>{c&&(c.unsubscribe(),a.next(void 0)),y?c=r.info.liveTime$.pipe((0,p.map)(F=>F&&F/1e3)).subscribe(a):c=r.info.position$.subscribe(a),t.add(c)}));let{playing$:l,paused$:f}=r.events,h=r.events.willSeek$.pipe((0,p.filter)(()=>r.info.playbackState$.getValue()===Q.PlaybackState.PLAYING)),g=r.events.seeked$.pipe((0,p.filter)(()=>r.info.playbackState$.getValue()===Q.PlaybackState.PLAYING)),v=!1,s=new p.Subject;t.add(h.subscribe(()=>{v||s.next(),v=!0})),t.add(g.subscribe(()=>v=!1));let u=new p.Subject,b=new p.Subject,A=(0,p.merge)(l,g,u),C=(0,p.merge)(f,s,o,r.events.looped$,b),E,ce=()=>E=a.getValue(),le=()=>{let y=a.getValue();(0,p.isNullable)(E)||E===y||(0,p.isNullable)(y)||(i.next({from:E,to:y}),E=void 0)},pe=()=>{b.next(),u.next()};if(t.add(A.subscribe(ce)),t.add(C.subscribe(le)),e.forceInterval&&isFinite(e.forceInterval)){let y=0;t.add(A.subscribe(()=>y=window.setTimeout(pe,e.forceInterval))),t.add(C.subscribe(()=>window.clearTimeout(y)))}return t});var ye="_one-stat_",j=`${ye}uuid`,G=()=>{let r=new n.Subscription;return{subscription:r,subscribe:(e,i)=>{e&&r.add(e.subscribe(i))}}},M=class{constructor(e,i){this.subscription=new n.Subscription;this.debugLogger=new B.Logger;this.oneStatDebugLog=this.debugLogger.createComponentLog("onestat");this.loopCounter=0;this.disabled=!1;this.vsid$=new n.ValueSubject(void 0);this.isid$=new n.ValueSubject(void 0);this.seekAction$=new n.ValueSubject("unknown");this.statContext=e,this.config=te(i.config??{}),(0,n.isNonNullable)(i.apiEnv)&&(this.config.apiEnv=i.apiEnv),this.config.synchronizeTime&&(this.timeSynchronisation=new D);let t=new n.Subject;this.experimental={error$:t};let o=n.safeStorage.get(j);o?o.startsWith('"')&&o.endsWith('"')?(this.uuid=o.replaceAll('"',""),n.safeStorage.set(j,this.uuid)):this.uuid=o:(this.uuid=W(),n.safeStorage.set(j,this.uuid)),this.resetViewSession(),i.useIsid&&this.isid$.next(i.isid??de());let a=new T({apiKey:oe,config:this.config,error$:t,timeSynchronisation:this.timeSynchronisation});this.api=new x({config:this.config,apiTransport:a,refreshAuthToken:i.refreshAuthToken,mobile:this.statContext.mobile??!1,uuid:this.uuid,error$:t}),this.logger=new O({config:this.config,debugLogger:this.debugLogger,api:this.api,error$:t,userSalt:i.userSalt});let{isEmbed:c,host:l}=(0,B.detectEmbed)();this.isEmbed=c,this.embedParent=l,this.subscribe()}updateContext(e){this.statContext={...this.statContext,...e}}attachTo(e){let i=new n.Subscription,t=(s,u)=>i.add(s.subscribe(u));t(e.events.willStart$,()=>{let s=e.info.position$.getValue();this.logActionPlay({position:s}),this.statContext.projectId&&this.logActionPlayInteractive()}),t(e.events.looped$,()=>{this.resetViewSession(),++this.loopCounter>this.config.maxLoops&&(this.disabled=!0),this.logActionPlay({position:e.info.position$.getValue()})}),t(e.events.seeked$,()=>{this.logSeek({action:this.seekAction$.getValue(),time:e.info.position$.getValue()}),this.seekAction$.next("unknown")}),t(e.events.paused$,()=>{this.logPause({position:e.info.position$.getValue()})}),t(e.events.willResume$,()=>{this.logPlay()}),t(e.events.started$,()=>{this.statContext.clip&&this.logWatchCoverageRecord({start:0,end:0})}),t(e.events.playing$,()=>{this.logPlaying()}),t(ue(e,{forceInterval:this.config.watchCoverageInterval}),s=>{let u=e.info.isLive$.getValue(),b={start:parseFloat(s.from.toFixed(3)),end:parseFloat(s.to.toFixed(3))};u?this.logWatchCoverageLive(b):this.logWatchCoverageRecord(b)});let o;t(e.info.isStalled$,s=>{s?o=(0,n.now)():((0,n.isNonNullable)(o)&&this.logEmptyBuffer({duration:(0,n.now)()-o}),o=void 0)});let a=!1;i.add(e.events.fatalError$.pipe((0,n.once)()).subscribe(()=>a=!0)),t(e.events.willStop$,()=>{if(e.info.isStalled$.getValue()){let u=(0,n.isNonNullable)(o)?(0,n.now)()-o:void 0;this.logCloseAtEmptyBuffer({duration:u??0}),o=void 0}else a||this.logActionStop()}),t(e.events.managedError$,({id:s})=>{this.logError({fatal:!1,errorType:s})}),t(e.events.fatalError$,({id:s})=>{this.logError({fatal:!0,errorType:s})});let c,l,f=!1;t(e.events.firstBytes$,s=>{c=(0,n.now)(),this.logFirstBytes({time:s})}),t(e.events.willStart$,()=>l=(0,n.now)()),t(e.info.currentBuffer$,s=>{!f&&s&&s.end-s.start>0&&(0,n.isNonNullable)(c)&&(this.logPlayerReady({duration:(0,n.now)()-c}),f=!0)}),t(e.events.firstFrame$,()=>{(0,n.isNonNullable)(c)&&!f&&(this.logPlayerReady({duration:(0,n.now)()-c}),f=!0),(0,n.isNonNullable)(l)&&this.logFirstFrame({time:(0,n.now)()-l})});let h;t(e.info.currentVideoStream$,s=>{s&&(h&&s.id!==h&&this.logTrackSwitch(s),h=s.id)});let g;t(e.info.currentAudioStream$,s=>{s&&(g&&s.id!==g&&this.logTrackSwitch(s),g=s.id)}),t(e.info.atLiveEdge$,s=>this.updateContext({liveEdge:s})),t((0,n.combine)({muted:e.info.muted$,volume:e.info.volume$}),({muted:s,volume:u})=>this.updateContext({audible:!s&&u>0})),t(e.info.currentQuality$,s=>this.updateContext({quality:se(s)})),t(e.info.isAutoQualityEnabled$,s=>this.updateContext({autoQuality:s})),t(e.info.currentFormat$,s=>this.updateContext({contentType:re(s)})),t(e.info.currentPlaybackRate$,s=>this.updateContext({rate:s})),t(e.info.is3DVideo$,s=>this.updateContext({is3d:s}));let v;return t(e.info.hostname$,s=>{let u=v!==void 0&&v!==s;this.updateContext({cdnHostname:s,failover:u}),u&&this.logFailover(s),v=s}),t(e.info.throughputEstimation$,s=>this.updateContext({downloadSpeed:s})),t(e.info.httpConnectionType$,s=>{this.statContext.firstConnectionType||this.updateContext({firstConnectionType:z(s)}),this.updateContext({connectionType:z(s)})}),t(e.info.httpConnectionReused$,s=>{(0,n.isNullable)(this.statContext.firstConnectionReused)&&this.updateContext({firstConnectionReused:s}),this.updateContext({connectionReused:s})}),t(e.info.surface$,s=>this.updateContext({mode:N(s)})),t((0,n.combine)({current:e.info.currentTextTrack$,available:e.info.availableTextTracks$}),({current:s,available:u})=>{let b=u.find(({id:C})=>C===s),A=b&&(b.isAuto?`${b.language}_auto`:b.language);this.updateContext({subtitles:A})}),this.player=e,this.uiEvents&&this.attachToUi(this.uiEvents),this.resubscribeBeforeunload(),this.subscription.add(i),i}attachToUi(e){this.uiEvents=e;let{subscription:i,subscribe:t}=G();return this.player&&(t(e.actionRewind$,()=>{this.player&&(this.resetViewSession(),this.logActionPlay({position:this.player.info.position$.getValue()}))}),t(e.actionSeek$,this.seekAction$),t(e.inPiP$,o=>{let a=o?"pip":N(this.player?.info.surface$.getValue());this.updateContext({mode:a})}),t(e.inFullscreen$,o=>{let a=o?"fullscreen":N(this.player?.info.surface$.getValue());this.updateContext({mode:a})}),t(e.actionSetSubtitle$,o=>this.updateContext({subtitles:o})),t(e.nextMovie$,o=>this.logNextMovie(o)),this.resubscribeBeforeunload(),this.subscription.add(i)),i}attachToAds(e){let{subscription:i,subscribe:t}=G();return t(e.slotRequested$,()=>this.logAdSlotRequest()),t(e.started$,o=>this.logAdStarted(o)),t(e.paused$,()=>this.logAdPaused()),t(e.resumed$,()=>this.logAdResumed()),t(e.ended$,()=>this.logAdEnded()),t(e.skipped$,()=>this.logAdSkipped()),t(e.clicked$,()=>this.logAdClicked()),this.resubscribeBeforeunload(),this.subscription.add(i),i}attachToInteractive(e){let{subscription:i,subscribe:t}=G();return t(e.click$,o=>this.logInterfaceClick(o)),t(e.nextMovie$,o=>this.logNextMovie(o)),this.resubscribeBeforeunload(),this.subscription.add(i),i}authorize(e){return this.api.authorize(e)}pause(){this.logger.pause(),this.oneStatDebugLog({message:"paused"})}resume(){this.logger.resume(),this.oneStatDebugLog({message:"resumed"})}destroy(){this.logger.flush(),this.subscription.unsubscribe(),this.api.destroy(),this.logger.destroy()}resetViewSession(){this.oneStatDebugLog({message:"VSID reset"}),this.vsid$.next(ae())}getDeviceId(){return this.uuid}setFieldBlacklist(){}logInited(){}logReady(e){this.log({operation:"player_ready",param:String(e.time)})}logStarted(...e){this.logActionPlay(...e)}logPlay(){this.log({operation:"play_toggle"})}logPlaying(){this.log({operation:"playing"})}logPause(e){this.log({operation:"pause",param:String(Math.round(e.position))})}logSeek(e){this.log({operation:"seek",param:e.action,time:e.time})}logFirstBytes(e){this.log({operation:"first_bytes",param:String(e.time)})}logFirstFrame(e){this.log({operation:"first_frame",param:String(e.time)})}logError(e){this.log({operation:"content_error",param:`${e.fatal?"fatal":"recoverable"}_${e.errorType}`})}logWatchCoverageRecord(e){this.log({operation:"watch_coverage_record",param:`${e.start}-${e.end}`})}logWatchCoverageLive(e){let i=this.timeSynchronisation?.getOffset()??0,t=e.start+i,o=e.end+i;this.log({operation:"watch_coverage_live",param:`${t}-${o}`})}logEmptyBuffer(e){this.log({operation:"empty_buffer",param:String(e.duration)})}logDownloadSpeed(){}logAdSlotRequest(){this.log({operation:"adv",param:"slot_request"})}logAdStarted(e){this.log({operation:"adv",param:e})}logAdPaused(){this.log({operation:"adv",param:"pause"})}logAdResumed(){this.log({operation:"adv",param:"resume"})}logAdEnded(){this.log({operation:"adv",param:"ended"})}logAdSkipped(){this.log({operation:"adv",param:"skip"})}logAdClicked(){this.log({operation:"adv",param:"click"})}logInterfaceClick(e){this.log({operation:"player_interface_click",param:e})}logNextMovie(e){this.log({operation:"next_movie",param:String(e)})}subscribe(){this.resubscribeBeforeunload();let e=window.navigator.connection;e&&"onchange"in e&&"effectiveType"in e&&this.subscription.add((0,n.merge)((0,n.fromEvent)(e,"change"),(0,n.observableFrom)(["init"])).subscribe(()=>this.updateContext({network:ne(e.effectiveType)}))),this.config.debugLog&&this.debugLogger.log$.subscribe(i=>{console.debug("%c stat ","background:#fa6470;",`component: ${i.component}.`,i.message)})}resubscribeBeforeunload(){this.beforeunloadSubscription?.unsubscribe(),this.beforeunloadSubscription=(0,n.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))})}logActionPlayInteractive(){this.statContext.projectId&&this.log({operation:"action_play_interactive",param:String(this.statContext.movieId)},{vid:this.statContext.projectId})}logFailover(e){this.log({operation:"failover",param:e})}logCloseAtEmptyBuffer(e){this.log({operation:"close_at_empty_buffer",param:String(Math.round(e.duration))})}logActionStop(){this.log({operation:"action_stop"})}logTrackSwitch(e){this.log({operation:"track_switch",param:e.id})}log(e,i={}){if(this.disabled){this.oneStatDebugLog({message:`operation ${e.operation} but statistics is disabled`});return}if(this.config.disabledOperations.includes(e.operation)){this.oneStatDebugLog({message:`operation ${e.operation} but it is disabled`});return}this.oneStatDebugLog({message:`operation ${e.operation} ${e.param}`});let t=this.createLogItem(e,i);this.logger.log(t)}createLogItem({operation:e,param:i,time:t},o={}){let a=this.timeSynchronisation?.now()??(0,n.now)(),c=this.vsid$.getValue();(0,n.assertNonNullable)(c);let l=this.isid$.getValue(),f=e==="empty_buffer"||e==="close_at_empty_buffer"?this.statContext.connectionType:this.statContext.firstConnectionType,h=this.statContext.firstConnectionReused,g,v;if(this.isEmbed){g=this.embedParent;let u=[...new URLSearchParams(location.search).entries()].filter(([b,A])=>this.config.embedUrlParams.includes(b));v=new URLSearchParams(u).toString()}else this.statContext.place==="direct"&&((this.statContext.refDomain||document.referrer)&&(g=new URL(this.statContext.refDomain||document.referrer).hostname),v=location.href.substring(0,1024));let s={vsid:c,isid:l,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?"auto":this.statContext.autoplay===!1?"":void 0,param:i,vk_app_id:this.statContext.vkAppId,track_code:this.statContext.trackCode,connection_type:f,connection_reused:h===!0?1:h===!1?0:void 0,cached_data:this.statContext.cached===!0?1:this.statContext.cached===!1?0:void 0,live:this.statContext.liveEdge?1:void 0,muted:this.statContext.audible===!1?1:void 0,mode:this.statContext.mode,subtitles:this.statContext.subtitles,download_speed:this.statContext.downloadSpeed,manual_quality:this.statContext.autoQuality?void 0:1,ref_domain:g,direct_url:v,rate:this.statContext.rate===1||(0,n.isNullable)(this.statContext.rate)?void 0:this.statContext.rate.toFixed(2),view_360:this.statContext.is3d?1:void 0,aid:this.statContext.albumId,vk_playlist_id:this.statContext.vkPlaylistId,...o};for(let u of this.config.disabledCustomFields)delete s[u];return{operation:e,type:1,time:t,network:this.statContext.network,timestamp:a,custom:s}}};
package/esnext.esm.js CHANGED
@@ -1,6 +1,6 @@
1
1
  /**
2
- * @vkontakte/videoplayer-statistics v1.0.52-dev.22c05d5f.0
3
- * Tue, 30 Jul 2024 08:28:10 GMT
2
+ * @vkontakte/videoplayer-statistics v1.0.52-dev.a5f6699f.0
3
+ * Tue, 30 Jul 2024 10:43:01 GMT
4
4
  * https://st.mycdn.me/static/vkontakte-videoplayer/1-0-52/doc/
5
5
  */
6
- var E=(r=>(r.PROD="prod",r.VK_ALIAS="vk_alias",r.VIDEOTEST="videotest",r.TEST="test",r.AUTO="auto",r))(E||{}),D=(c=>(c.Q144P="mobile",c.Q240P="lowest",c.Q360P="low",c.Q480P="medium",c.Q720P="high",c.Q1080P="fullhd",c.Q1440P="quadhd",c.Q2160P="ultrahd",c.UNKNOWN="unknown",c))(D||{}),M=(a=>(a.MP4="mp4",a.DASH="dash",a.DASH_SEP="dash_sep",a.ONDEMAND_DASH="ondemand_dash",a.HLS="hls",a.ONDEMAND_HLS="ondemand_hls",a.WEBM="webm",a.AV1="av1",a.ONDEMAND_DASH_LIVE="ondemand_dash_live",a.ONDEMAND_HLS_LIVE="ondemand_hls_live",a.WEBRTC="webrtc",a.UNKNOWN="unknown",a.RTMP="rtmp",a))(M||{});var B=(t=>(t.HTTP1="http1",t.HTTP2="http2",t.HTTP3="http3",t))(B||{});var F=(u=>(u.SLIDER="slider",u.DOUBLE_TAP="double_tap",u.TIME_CODE="time_code",u.EPISODE="episode",u.REWIND="rewind",u.LIVE="live",u.UNKNOWN="unknown",u))(F||{}),ee=(r=>(r.GRAPH_SHOW="iGraphShow",r.GRAPH_HIDE="iGraphHide",r.NEXT_AREA="iNextChapterArea",r.NEXT_BUTTON="iNextChapterBtn",r.WATCH_AGAIN="iWatchAgainBtn",r))(ee||{}),te={action_play:"ap",action_play_interactive:"api",first_bytes:"fb",player_ready:"pr",first_frame:"ff",seek:"sk",watch_coverage_record:"wr",watch_coverage_live:"wl",empty_buffer:"eb",action_stop:"as",close_at_empty_buffer:"cb",content_error:"er",player_interface_click:"pc",next_movie:"nm",track_switch:"ts",failover:"fo"},ie={vsid:"si",isid:"is",vid:"vi",place:"pl",quality:"qt",cdn_host:"ch",stat_type:"st",param:"pm",vk_app_id:"va",track_code:"tc",connection_type:"cnt",connection_reused:"cr",cached_data:"cd",live:"lv",muted:"mu",mode:"mo",subtitles:"sb",failover:"fo",download_speed:"ds",manual_quality:"mq",ref_domain:"rd",direct_url:"du"},oe={unknown:"un",mobile:"m",lowest:"ls",low:"l",medium:"md",high:"h",fullhd:"f",quadhd:"q",ultrahd:"u"},se={pip:"pi",fullscreen:"fs",external:"ex",prefetch:"pr",airplay:"ap",chromecast:"cc",invisible:"iv"};import{fillWithDefault as _e}from"@vkontakte/videoplayer-shared";var xe={apiEnv:"vk_alias",requestRetryCount:1,firstFlushTime:5e3,flushDebounceTime:1e4,flushMaxWait:6e4,storageExpiration:36*60*60*1e3,watchCoverageInterval:15e3,disabledOperations:[],disabledCustomFields:[],shorten:!0,maxLoops:100,embedUrlParams:[],useBeacon:!0,synchronizeTime:!0,debugLog:!1,backoff:{start:1e3,factor:1.5,max:5*60*1e3,random:.1}},re=n=>_e(n,xe);function V(){let n="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".split(""),e=new Array(36),i=0,t,o;for(o=0;o<36;o++)o===8||o===13||o===18||o===23?e[o]="-":o===14?e[o]="4":(i<=2&&(i=33554432+Math.random()*16777216|0),t=i&15,i=i>>4,e[o]=n[o===19?t&3|8:t]);return e.join("")}import{assertNonNullable as Be,combine as Ie,fromEvent as Se,isNonNullable as y,isNullable as ye,merge as Fe,now as b,observableFrom as Ve,once as Ue,safeStorage as j,Subject as We,Subscription as J,ValueSubject as G}from"@vkontakte/videoplayer-shared";import{Logger as He,detectEmbed as Ke}from"@vkontakte/videoplayer-shared";var ne=n=>{let{operation:e,custom:i}=n,t=Object.fromEntries(Object.entries(i).map(([o,r])=>{let d=ie[o]??o,u=r;return r&&(o==="mode"?u=se[r]??r:o==="quality"&&(u=oe[r]??r)),[d,u]}));return{...n,operation:te[e]??e,custom:t}};var w="1.0.52-dev.22c05d5f.0",ae="CIOPGQJGDIHBABABA",U={prod:"https://api.ok.ru",vk_alias:"https://api.mycdn.me",videotest:"https://videotestapi.ok.ru/api",test:"https://apitest.ok.ru",auto:""};import{ValueSubject as Te,getExponentialDelay as Ce,ErrorCategory as I}from"@vkontakte/videoplayer-shared";var _=class{constructor(e){this.consequentAuthErrors=0;this.authorized$=new Te(!1);this.params=e}async authorize(e){return this.authToken=e??await this.refreshAuthToken(),this._authorizeWithBackoff()}logBeacon(e){let i="log.externalLog",t=this.createLogParams(e),o=this.sessionKey;if(!o)return;this.params.apiTransport.sendBeacon(i,t,o)||this.logRequest(e)}async logRequest(e){let i="log.externalLog",t=this.createLogParams(e),o=this.sessionKey??await this._authorizeWithBackoff();if(!o)return;let r=async(d,u=this.params.config.requestRetryCount)=>{try{return await this.params.apiTransport.sendRequest(i,t,o)}catch(l){if(!l||!("error_code"in l)){this.params.error$.next({id:"logRequestUnknown",category:I.NETWORK,message:`Unknown ${i} error`,thrown:l});return}let c=l?.error_code;switch(c){case 102:case 103:case 104:return this.authorized$.next(!1),this.sessionKey=await this._authorizeWithBackoff(),u>0?r(d,u-1):void 0;case 401:return this.authorized$.next(!1),this.authToken=await this.refreshAuthToken(),this.sessionKey=await this._authorizeWithBackoff(),u>0?r(d,u-1):void 0;default:{this.params.error$.next({id:`LogRequest#${c}`,category:I.EXTERNAL_API,message:`${i} error`,data:l});return}}}};return r(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:${w}`,platform:this.params.mobile?"M_WEB":"WEB",items:this.params.config.shorten?e.map(ne):e})}}_authorizeWithBackoff(){if(!this.consequentAuthErrors)return this._authorize();let e=Ce(this.consequentAuthErrors,this.params.config.backoff);return new Promise(i=>{this.backoffTimeoutId||(this.backoffTimeoutId=window.setTimeout(()=>{this._authorize().then(i).catch(t=>this.params.error$.next({id:"AuthorizeBackoff",category:I.NETWORK,message:"Otherwise unhandled error in authorization",thrown:t})).finally(()=>this.backoffTimeoutId=0)},e))})}async _authorize(){if(this.authorizePromise)return this.authorizePromise;this.sessionKey=void 0,this.authorized$.next(!1);let e="auth.anonymLogin",i={session_data:{version:2,device_id:this.params.uuid,client_version:w.split("-")[0],client_type:"SDK_JS"}};return this.authToken!==void 0&&(i.session_data.auth_token=this.authToken,i.session_data.version=3),this.authorizePromise=this.params.apiTransport.sendRequest(e,i).then(t=>((!t||!t.session_key)&&this.params.error$.next({id:"AuthorizeFailed",category:I.EXTERNAL_API,message:"No session key",data:t}),this.sessionKey=t?.session_key??void 0,this.sessionKey)).catch(async t=>{this.sessionKey=void 0;let o=t?.error_code;switch(o){case 401:return this.authToken=await this.refreshAuthToken(),this._authorizeWithBackoff()}o?this.params.error$.next({id:`Authorize#${o}`,category:I.EXTERNAL_API,message:"authorize error",data:t}):this.params.error$.next({id:"AuthorizeUnknown",category:I.NETWORK,message:"authorize error",thrown:t})}).finally(()=>{this.authorizePromise=void 0,this.consequentAuthErrors=this.sessionKey?0:this.consequentAuthErrors+1,this.authorized$.next(this.sessionKey!==void 0)}),this.authorizePromise}};import{ErrorCategory as k,now as W}from"@vkontakte/videoplayer-shared";var x=class{constructor(e){this.params=e,this.apiKey=e.apiKey,this.apiEnv=e.config.apiEnv,this.apiBaseUrl=U[this.apiEnv],this.timeSynchronisation=e.timeSynchronisation,this.isApiBaseUrlFetched=!1}async resolveApiBaseUrl(){if(this.apiEnv!=="auto"||this.isApiBaseUrlFetched)return this.apiBaseUrl;try{let e=atob("aHR0cHM6Ly9kbnMuZ29vZ2xlL3Jlc29sdmU/bmFtZT12aWRlby5fZW5kcG9pbnQub2sucnUmdHlwZT1UWFQ="),o=(await(await fetch(e,{method:"GET",mode:"cors",cache:"no-cache"})).json())?.Answer[0]?.data;if(!o)throw new Error("Wrong DNS response");return o}catch(e){return this.params.error$.next({id:"OneStat:ApiTransport:resolveApiBaseUrl",category:k.NETWORK,message:"Unhandled resolve api base url error",thrown:e}),U.vk_alias}finally{this.isApiBaseUrlFetched=!0}}sendBeacon(e,i,t){if(!window.Blob||!window.navigator.sendBeacon)return!1;let o=this._prepareQueryParams({method:e,queryParams:i,sessionKey:t}),r=new window.Blob([o.toString()],{type:"application/x-www-form-urlencoded"});try{return window.navigator.sendBeacon(`${this.apiBaseUrl}/fb.do`,r)}catch(d){this.params.error$.next({id:"OneStat:ApiTransport:sendBeacon",category:k.NETWORK,message:"Unhandled beacon error",thrown:d,data:{method:e,params:i}})}return!1}async sendRequest(e,i,t){let o=W(),r=d=>{if(d instanceof TypeError&&["Failed to fetch","NetworkError when attempting to fetch resource."].includes(d.message)){this.params.error$.next({id:"Network",category:k.NETWORK,message:"Request failed",thrown:d});return}this.params.error$.next({id:"OneStat:ApiTransport:sendRequest",category:k.NETWORK,message:"Unhandled request error",thrown:d,data:{method:e,params:i,sessionKey:t,time:W()-o}})};return this.apiBaseUrl=await this.resolveApiBaseUrl(),fetch(`${this.apiBaseUrl}/fb.do`,{method:"post",headers:{"Content-type":"application/x-www-form-urlencoded"},body:this._prepareQueryParams({method:e,queryParams:i,sessionKey:t})}).then(d=>{let u=Number(d.headers.get("content-length"))===0,l=new Date(d.headers.get("date")??"").getTime(),c=W()-o;if(isFinite(l)&&this.timeSynchronisation?.addServerTime(l,c),!u)return d.json().then(h=>Object.prototype.hasOwnProperty.call(h,"error_msg")?Promise.reject(h):h,r)},r)}_prepareQueryParams(e){let i=new URLSearchParams({format:"JSON",method:e.method,application_key:this.apiKey});return e.sessionKey!==void 0&&i.append("session_key",e.sessionKey),Object.entries(e.queryParams).forEach(([t,o])=>i.append(t,typeof o=="string"?o:JSON.stringify(o))),i}};import{ErrorCategory as we,now as ke,safeStorage as T,debounceFn as de}from"@vkontakte/videoplayer-shared";var L="onestat_events",H=n=>e=>e.timestamp+n>=ke(),$=class{constructor(e){this.unsaltedStorage=[];this.isPaused=!1;this.isUrgent=e=>{let{operation:i}=e;return["action_play","watch_coverage_record","watch_coverage_live"].includes(i)};this.params=e,this.api=e.api,this.error$=e.error$,this.userSalt=e.userSalt,this.loggerDebugLog=e.debugLogger.createComponentLog("stat logger"),this.firstFlush=de(()=>this.safeFlush(),this.params.config.firstFlushTime,{maxWait:this.params.config.firstFlushTime});let i=T.isPersistent()?this.params.config.flushMaxWait:0;this.debouncedFlush=de(()=>this.safeFlush(),this.params.config.flushDebounceTime,{maxWait:i}),this.subscription=this.api.authorized$.subscribe(t=>{t&&this.debouncedFlush()}),this.housekeepStorage()}safeFlush(){try{this.flush()}catch(e){this.error$.next({id:"LoggerError",category:we.WTF,message:String(e)??"Unknown logger error",thrown:e})}}readFromStorage(){let e=T.get(L);try{return e?JSON.parse(e):{}}catch{}return{}}addToStorage(e){if(!this.userSalt){this.unsaltedStorage.push(e);return}let i=this.readFromStorage(),o=(i[this.userSalt]??[]).filter(H(this.params.config.storageExpiration));T.set(L,JSON.stringify({...i,[this.userSalt]:[...o,e]}))}getFromStorage(){return this.userSalt?(this.readFromStorage()[this.userSalt]??[]).filter(H(this.params.config.storageExpiration)):this.unsaltedStorage}markStorageSent(){if(!this.userSalt){this.unsaltedStorage=[];return}let e=this.readFromStorage();delete e[this.userSalt],T.set(L,JSON.stringify(e))}housekeepStorage(){let e=this.readFromStorage();for(let[i,t]of Object.entries(e)){let o=t.filter(H(this.params.config.storageExpiration));o.length?e[i]=o:delete e[i],this.loggerDebugLog({message:`${t.length} retrieved from storage, ${o.length} of them actual`})}T.set(L,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){let i=this.getFromStorage();i.length!==0&&(this.api.authorized$.getValue()?(e&&this.params.config.useBeacon?(this.loggerDebugLog({message:`Flushing ${i.length} events through beacon`}),this.api.logBeacon(i)):(this.loggerDebugLog({message:`Flushing ${i.length} events`}),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()}};import{HttpConnectionType as K,Surface as S,VideoFormat as p,VideoQuality as m}from"@vkontakte/videoplayer-core";import{assertNever as ue}from"@vkontakte/videoplayer-shared";var ce=n=>n&&{[m.INVARIANT]:"unknown",[m.Q_144P]:"mobile",[m.Q_240P]:"lowest",[m.Q_360P]:"low",[m.Q_480P]:"medium",[m.Q_720P]:"high",[m.Q_1080P]:"fullhd",[m.Q_1440P]:"quadhd",[m.Q_2160P]:"ultrahd",[m.Q_4320P]:"unknown"}[n],q=n=>n&&{[K.HTTP1]:"http1",[K.HTTP2]:"http2",[K.QUIC]:"http3"}[n],le=n=>{if(n!==void 0)switch(n){case p.MPEG:return"mp4";case p.DASH:case p.DASH_LIVE:case p.DASH_STREAMS:return"dash";case p.DASH_SEP:return"dash_sep";case p.DASH_ONDEMAND:return"ondemand_dash";case p.DASH_WEBM:case p.DASH_LIVE_WEBM:return"webm";case p.DASH_WEBM_AV1:return"av1";case p.DASH_LIVE_CMAF:return"ondemand_dash_live";case p.HLS:case p.HLS_LIVE:return"hls";case p.HLS_ONDEMAND:return"ondemand_hls";case p.HLS_LIVE_CMAF:return"ondemand_hls_live";case p.WEB_RTC_LIVE:return"webrtc";default:return ue(n)}},R=n=>{if(n!==void 0)switch(n){case S.NONE:case S.INLINE:return;case S.FULLSCREEN:return"fullscreen";case S.SECOND_SCREEN:return"chromecast";case S.PIP:return"pip";case S.INVISIBLE:return"invisible";default:return ue(n)}},pe=n=>{switch(n){case"slow-2g":return"poor";case"2g":return"poor";case"3g":return"good";case"4g":return"excellent"}};var O=class{constructor(e){this.offset=void 0;this.offset=e}getOffset(){return this.offset??0}setOffset(e){this.offset=e}now(){return Date.now()+(this.offset??0)}date(e=new Date){return e.setTime(e.getTime()+(this.offset??0)),e}addServerTime(e,i){let t=Date.now(),o=e-t-i/2;if(Math.abs(o)<1e3){this.offset=0;return}this.offset===void 0?this.offset=Math.round(o):this.offset=Math.round(.2*o+(1-.2)*this.offset)}};var he=()=>Math.floor(Math.random()*4294967296).toString(36).padStart(7,"0"),fe=()=>Math.floor(Math.random()*18446744073709552e3).toString(36).padStart(13,"0");import{PlaybackState as ge}from"@vkontakte/videoplayer-core";import{filter as me,filterChanged as $e,fromEvent as Re,isNullable as be,map as Oe,merge as z,Observable as Ne,Subject as Q,Subscription as De,ValueSubject as Me}from"@vkontakte/videoplayer-shared";var ve=(n,e)=>new Ne(i=>{let t=new De,o=z(Re(window,"beforeunload"),n.events.willDestruct$),r=new Me(void 0),d;t.add(n.info.isLive$.pipe($e()).subscribe(v=>{d&&(d.unsubscribe(),r.next(void 0)),v?d=n.info.liveTime$.pipe(Oe(N=>N&&N/1e3)).subscribe(r):d=n.info.position$.subscribe(r),t.add(d)}));let{playing$:u,paused$:l}=n.events,c=n.events.willSeek$.pipe(me(()=>n.info.playbackState$.getValue()===ge.PLAYING)),h=n.events.seeked$.pipe(me(()=>n.info.playbackState$.getValue()===ge.PLAYING)),g=!1,s=new Q;t.add(c.subscribe(()=>{g||s.next(),g=!0})),t.add(h.subscribe(()=>g=!1));let a=new Q,f=new Q,P=z(u,h,a),C=z(l,s,o,n.events.looped$,f),A,Pe=()=>A=r.getValue(),Ae=()=>{let v=r.getValue();be(A)||A===v||be(v)||(i.next({from:A,to:v}),A=void 0)},Ee=()=>{f.next(),a.next()};if(t.add(P.subscribe(Pe)),t.add(C.subscribe(Ae)),e.forceInterval&&isFinite(e.forceInterval)){let v=0;t.add(P.subscribe(()=>v=window.setTimeout(Ee,e.forceInterval))),t.add(C.subscribe(()=>window.clearTimeout(v)))}return t});var qe="_one-stat_",Y=`${qe}uuid`,X=()=>{let n=new J;return{subscription:n,subscribe:(e,i)=>{e&&n.add(e.subscribe(i))}}},Z=class{constructor(e,i){this.subscription=new J;this.debugLogger=new He;this.oneStatDebugLog=this.debugLogger.createComponentLog("onestat");this.loopCounter=0;this.disabled=!1;this.vsid$=new G(void 0);this.isid$=new G(void 0);this.seekAction$=new G("unknown");this.statContext=e,this.config=re(i.config??{}),y(i.apiEnv)&&(this.config.apiEnv=i.apiEnv),this.config.synchronizeTime&&(this.timeSynchronisation=new O);let t=new We;this.experimental={error$:t};let o=j.get(Y);o?o.startsWith('"')&&o.endsWith('"')?(this.uuid=o.replaceAll('"',""),j.set(Y,this.uuid)):this.uuid=o:(this.uuid=V(),j.set(Y,this.uuid)),this.resetViewSession(),i.useIsid&&this.isid$.next(i.isid??fe());let r=new x({apiKey:ae,config:this.config,error$:t,timeSynchronisation:this.timeSynchronisation});this.api=new _({config:this.config,apiTransport:r,refreshAuthToken:i.refreshAuthToken,mobile:this.statContext.mobile??!1,uuid:this.uuid,error$:t}),this.logger=new $({config:this.config,debugLogger:this.debugLogger,api:this.api,error$:t,userSalt:i.userSalt});let{isEmbed:d,host:u}=Ke();this.isEmbed=d,this.embedParent=u,this.subscribe()}updateContext(e){this.statContext={...this.statContext,...e}}attachTo(e){let i=new J,t=(s,a)=>i.add(s.subscribe(a));t(e.events.willStart$,()=>{let s=e.info.position$.getValue();this.logActionPlay({position:s}),this.statContext.projectId&&this.logActionPlayInteractive()}),t(e.events.looped$,()=>{this.resetViewSession(),++this.loopCounter>this.config.maxLoops&&(this.disabled=!0),this.logActionPlay({position:e.info.position$.getValue()})}),t(e.events.seeked$,()=>{this.logSeek({action:this.seekAction$.getValue(),time:e.info.position$.getValue()}),this.seekAction$.next("unknown")}),t(e.events.paused$,()=>{this.logPause({position:e.info.position$.getValue()})}),t(e.events.willResume$,()=>{this.logPlay()}),t(e.events.started$,()=>{this.statContext.clip&&this.logWatchCoverageRecord({start:0,end:0})}),t(e.events.playing$,()=>{this.logPlaying()}),t(ve(e,{forceInterval:this.config.watchCoverageInterval}),s=>{let a=e.info.isLive$.getValue(),f={start:parseFloat(s.from.toFixed(3)),end:parseFloat(s.to.toFixed(3))};a?this.logWatchCoverageLive(f):this.logWatchCoverageRecord(f)});let o;t(e.info.isStalled$,s=>{s?o=b():(y(o)&&this.logEmptyBuffer({duration:b()-o}),o=void 0)});let r=!1;i.add(e.events.fatalError$.pipe(Ue()).subscribe(()=>r=!0)),t(e.events.willStop$,()=>{if(e.info.isStalled$.getValue()){let a=y(o)?b()-o:void 0;this.logCloseAtEmptyBuffer({duration:a??0}),o=void 0}else r||this.logActionStop()}),t(e.events.managedError$,({id:s})=>{this.logError({fatal:!1,errorType:s})}),t(e.events.fatalError$,({id:s})=>{this.logError({fatal:!0,errorType:s})});let d,u,l=!1;t(e.events.firstBytes$,s=>{d=b(),this.logFirstBytes({time:s})}),t(e.events.willStart$,()=>u=b()),t(e.info.currentBuffer$,s=>{!l&&s&&s.end-s.start>0&&y(d)&&(this.logPlayerReady({duration:b()-d}),l=!0)}),t(e.events.firstFrame$,()=>{y(d)&&!l&&(this.logPlayerReady({duration:b()-d}),l=!0),y(u)&&this.logFirstFrame({time:b()-u})});let c;t(e.info.currentVideoStream$,s=>{s&&(c&&s.id!==c&&this.logTrackSwitch(s),c=s.id)});let h;t(e.info.currentAudioStream$,s=>{s&&(h&&s.id!==h&&this.logTrackSwitch(s),h=s.id)}),t(e.info.atLiveEdge$,s=>this.updateContext({liveEdge:s})),t(Ie({muted:e.info.muted$,volume:e.info.volume$}),({muted:s,volume:a})=>this.updateContext({audible:!s&&a>0})),t(e.info.currentQuality$,s=>this.updateContext({quality:ce(s)})),t(e.info.isAutoQualityEnabled$,s=>this.updateContext({autoQuality:s})),t(e.info.currentFormat$,s=>this.updateContext({contentType:le(s)})),t(e.info.currentPlaybackRate$,s=>this.updateContext({rate:s})),t(e.info.is3DVideo$,s=>this.updateContext({is3d:s}));let g;return t(e.info.hostname$,s=>{let a=g!==void 0&&g!==s;this.updateContext({cdnHostname:s,failover:a}),a&&this.logFailover(s),g=s}),t(e.info.throughputEstimation$,s=>this.updateContext({downloadSpeed:s})),t(e.info.httpConnectionType$,s=>{this.statContext.firstConnectionType||this.updateContext({firstConnectionType:q(s)}),this.updateContext({connectionType:q(s)})}),t(e.info.httpConnectionReused$,s=>{ye(this.statContext.firstConnectionReused)&&this.updateContext({firstConnectionReused:s}),this.updateContext({connectionReused:s})}),t(e.info.surface$,s=>this.updateContext({mode:R(s)})),t(Ie({current:e.info.currentTextTrack$,available:e.info.availableTextTracks$}),({current:s,available:a})=>{let f=a.find(({id:C})=>C===s),P=f&&(f.isAuto?`${f.language}_auto`:f.language);this.updateContext({subtitles:P})}),this.player=e,this.uiEvents&&this.attachToUi(this.uiEvents),this.resubscribeBeforeunload(),this.subscription.add(i),i}attachToUi(e){this.uiEvents=e;let{subscription:i,subscribe:t}=X();return this.player&&(t(e.actionRewind$,()=>{this.player&&(this.resetViewSession(),this.logActionPlay({position:this.player.info.position$.getValue()}))}),t(e.actionSeek$,this.seekAction$),t(e.inPiP$,o=>{let r=o?"pip":R(this.player?.info.surface$.getValue());this.updateContext({mode:r})}),t(e.inFullscreen$,o=>{let r=o?"fullscreen":R(this.player?.info.surface$.getValue());this.updateContext({mode:r})}),t(e.actionSetSubtitle$,o=>this.updateContext({subtitles:o})),t(e.nextMovie$,o=>this.logNextMovie(o)),this.resubscribeBeforeunload(),this.subscription.add(i)),i}attachToAds(e){let{subscription:i,subscribe:t}=X();return t(e.slotRequested$,()=>this.logAdSlotRequest()),t(e.started$,o=>this.logAdStarted(o)),t(e.paused$,()=>this.logAdPaused()),t(e.resumed$,()=>this.logAdResumed()),t(e.ended$,()=>this.logAdEnded()),t(e.skipped$,()=>this.logAdSkipped()),t(e.clicked$,()=>this.logAdClicked()),this.resubscribeBeforeunload(),this.subscription.add(i),i}attachToInteractive(e){let{subscription:i,subscribe:t}=X();return t(e.click$,o=>this.logInterfaceClick(o)),t(e.nextMovie$,o=>this.logNextMovie(o)),this.resubscribeBeforeunload(),this.subscription.add(i),i}authorize(e){return this.api.authorize(e)}pause(){this.logger.pause(),this.oneStatDebugLog({message:"paused"})}resume(){this.logger.resume(),this.oneStatDebugLog({message:"resumed"})}destroy(){this.logger.flush(),this.subscription.unsubscribe(),this.api.destroy(),this.logger.destroy()}resetViewSession(){this.oneStatDebugLog({message:"VSID reset"}),this.vsid$.next(he())}getDeviceId(){return this.uuid}setFieldBlacklist(){}logInited(){}logReady(e){this.log({operation:"player_ready",param:String(e.time)})}logStarted(...e){this.logActionPlay(...e)}logPlay(){this.log({operation:"play_toggle"})}logPlaying(){this.log({operation:"playing"})}logPause(e){this.log({operation:"pause",param:String(Math.round(e.position))})}logSeek(e){this.log({operation:"seek",param:e.action,time:e.time})}logFirstBytes(e){this.log({operation:"first_bytes",param:String(e.time)})}logFirstFrame(e){this.log({operation:"first_frame",param:String(e.time)})}logError(e){this.log({operation:"content_error",param:`${e.fatal?"fatal":"recoverable"}_${e.errorType}`})}logWatchCoverageRecord(e){this.log({operation:"watch_coverage_record",param:`${e.start}-${e.end}`})}logWatchCoverageLive(e){let i=this.timeSynchronisation?.getOffset()??0,t=e.start+i,o=e.end+i;this.log({operation:"watch_coverage_live",param:`${t}-${o}`})}logEmptyBuffer(e){this.log({operation:"empty_buffer",param:String(e.duration)})}logDownloadSpeed(){}logAdSlotRequest(){this.log({operation:"adv",param:"slot_request"})}logAdStarted(e){this.log({operation:"adv",param:e})}logAdPaused(){this.log({operation:"adv",param:"pause"})}logAdResumed(){this.log({operation:"adv",param:"resume"})}logAdEnded(){this.log({operation:"adv",param:"ended"})}logAdSkipped(){this.log({operation:"adv",param:"skip"})}logAdClicked(){this.log({operation:"adv",param:"click"})}logInterfaceClick(e){this.log({operation:"player_interface_click",param:e})}logNextMovie(e){this.log({operation:"next_movie",param:String(e)})}subscribe(){this.resubscribeBeforeunload();let e=window.navigator.connection;e&&"onchange"in e&&"effectiveType"in e&&this.subscription.add(Fe(Se(e,"change"),Ve(["init"])).subscribe(()=>this.updateContext({network:pe(e.effectiveType)}))),this.config.debugLog&&this.debugLogger.log$.subscribe(i=>{console.debug("%c stat ","background:#fa6470;",`component: ${i.component}.`,i.message)})}resubscribeBeforeunload(){this.beforeunloadSubscription?.unsubscribe(),this.beforeunloadSubscription=Se(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))})}logActionPlayInteractive(){this.statContext.projectId&&this.log({operation:"action_play_interactive",param:String(this.statContext.movieId)},{vid:this.statContext.projectId})}logFailover(e){this.log({operation:"failover",param:e})}logCloseAtEmptyBuffer(e){this.log({operation:"close_at_empty_buffer",param:String(Math.round(e.duration))})}logActionStop(){this.log({operation:"action_stop"})}logTrackSwitch(e){this.log({operation:"track_switch",param:e.id})}log(e,i={}){if(this.disabled){this.oneStatDebugLog({message:`operation ${e.operation} but statistics is disabled`});return}if(this.config.disabledOperations.includes(e.operation)){this.oneStatDebugLog({message:`operation ${e.operation} but it is disabled`});return}this.oneStatDebugLog({message:`operation ${e.operation} ${e.param}`});let t=this.createLogItem(e,i);this.logger.log(t)}createLogItem({operation:e,param:i,time:t},o={}){let r=this.timeSynchronisation?.now()??b(),d=this.vsid$.getValue();Be(d);let u=this.isid$.getValue(),l=e==="empty_buffer"||e==="close_at_empty_buffer"?this.statContext.connectionType:this.statContext.firstConnectionType,c=this.statContext.firstConnectionReused,h,g;if(this.isEmbed){h=this.embedParent;let a=[...new URLSearchParams(location.search).entries()].filter(([f,P])=>this.config.embedUrlParams.includes(f));g=new URLSearchParams(a).toString()}else this.statContext.place==="direct"&&((this.statContext.refDomain||document.referrer)&&(h=new URL(this.statContext.refDomain||document.referrer).hostname),g=location.href.substring(0,1024));let s={vsid:d,isid:u,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?"auto":this.statContext.autoplay===!1?"":void 0,param:i,vk_app_id:this.statContext.vkAppId,track_code:this.statContext.trackCode,connection_type:l,connection_reused:c===!0?1:c===!1?0:void 0,cached_data:this.statContext.cached===!0?1:this.statContext.cached===!1?0:void 0,live:this.statContext.liveEdge?1:void 0,muted:this.statContext.audible===!1?1:void 0,mode:this.statContext.mode,subtitles:this.statContext.subtitles,download_speed:this.statContext.downloadSpeed,manual_quality:this.statContext.autoQuality?void 0:1,ref_domain:h,direct_url:g,rate:this.statContext.rate===1||ye(this.statContext.rate)?void 0:this.statContext.rate.toFixed(2),view_360:this.statContext.is3d?1:void 0,aid:this.statContext.albumId,vk_playlist_id:this.statContext.vkPlaylistId,...o};for(let a of this.config.disabledCustomFields)delete s[a];return{operation:e,type:1,time:t,network:this.statContext.network,timestamp:r,custom:s}}};export{E as ApiEnv,B as ConnectionType,M as ContentType,ee as InteractiveInterfaceClick,Z as OneStat,D as Quality,F as SeekAction,w as VERSION};
6
+ var E=(r=>(r.PROD="prod",r.VK_ALIAS="vk_alias",r.VIDEOTEST="videotest",r.TEST="test",r.AUTO="auto",r))(E||{}),D=(c=>(c.Q144P="mobile",c.Q240P="lowest",c.Q360P="low",c.Q480P="medium",c.Q720P="high",c.Q1080P="fullhd",c.Q1440P="quadhd",c.Q2160P="ultrahd",c.UNKNOWN="unknown",c))(D||{}),M=(a=>(a.MP4="mp4",a.DASH="dash",a.DASH_SEP="dash_sep",a.ONDEMAND_DASH="ondemand_dash",a.HLS="hls",a.ONDEMAND_HLS="ondemand_hls",a.WEBM="webm",a.AV1="av1",a.ONDEMAND_DASH_LIVE="ondemand_dash_live",a.ONDEMAND_HLS_LIVE="ondemand_hls_live",a.WEBRTC="webrtc",a.UNKNOWN="unknown",a.RTMP="rtmp",a))(M||{});var B=(t=>(t.HTTP1="http1",t.HTTP2="http2",t.HTTP3="http3",t))(B||{});var F=(u=>(u.SLIDER="slider",u.DOUBLE_TAP="double_tap",u.TIME_CODE="time_code",u.EPISODE="episode",u.REWIND="rewind",u.LIVE="live",u.UNKNOWN="unknown",u))(F||{}),ee=(r=>(r.GRAPH_SHOW="iGraphShow",r.GRAPH_HIDE="iGraphHide",r.NEXT_AREA="iNextChapterArea",r.NEXT_BUTTON="iNextChapterBtn",r.WATCH_AGAIN="iWatchAgainBtn",r))(ee||{}),te={action_play:"ap",action_play_interactive:"api",first_bytes:"fb",player_ready:"pr",first_frame:"ff",seek:"sk",watch_coverage_record:"wr",watch_coverage_live:"wl",empty_buffer:"eb",action_stop:"as",close_at_empty_buffer:"cb",content_error:"er",player_interface_click:"pc",next_movie:"nm",track_switch:"ts",failover:"fo"},ie={vsid:"si",isid:"is",vid:"vi",place:"pl",quality:"qt",cdn_host:"ch",stat_type:"st",param:"pm",vk_app_id:"va",track_code:"tc",connection_type:"cnt",connection_reused:"cr",cached_data:"cd",live:"lv",muted:"mu",mode:"mo",subtitles:"sb",failover:"fo",download_speed:"ds",manual_quality:"mq",ref_domain:"rd",direct_url:"du"},oe={unknown:"un",mobile:"m",lowest:"ls",low:"l",medium:"md",high:"h",fullhd:"f",quadhd:"q",ultrahd:"u"},se={pip:"pi",fullscreen:"fs",external:"ex",prefetch:"pr",airplay:"ap",chromecast:"cc",invisible:"iv"};import{fillWithDefault as _e}from"@vkontakte/videoplayer-shared";var xe={apiEnv:"vk_alias",requestRetryCount:1,firstFlushTime:5e3,flushDebounceTime:1e4,flushMaxWait:6e4,storageExpiration:36*60*60*1e3,watchCoverageInterval:15e3,disabledOperations:[],disabledCustomFields:[],shorten:!0,maxLoops:100,embedUrlParams:[],useBeacon:!0,synchronizeTime:!0,debugLog:!1,backoff:{start:1e3,factor:1.5,max:5*60*1e3,random:.1}},re=n=>_e(n,xe);function V(){let n="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".split(""),e=new Array(36),i=0,t,o;for(o=0;o<36;o++)o===8||o===13||o===18||o===23?e[o]="-":o===14?e[o]="4":(i<=2&&(i=33554432+Math.random()*16777216|0),t=i&15,i=i>>4,e[o]=n[o===19?t&3|8:t]);return e.join("")}import{assertNonNullable as Be,combine as Ie,fromEvent as Se,isNonNullable as y,isNullable as ye,merge as Fe,now as b,observableFrom as Ve,once as Ue,safeStorage as j,Subject as We,Subscription as J,ValueSubject as G}from"@vkontakte/videoplayer-shared";import{Logger as He,detectEmbed as Ke}from"@vkontakte/videoplayer-shared";var ne=n=>{let{operation:e,custom:i}=n,t=Object.fromEntries(Object.entries(i).map(([o,r])=>{let d=ie[o]??o,u=r;return r&&(o==="mode"?u=se[r]??r:o==="quality"&&(u=oe[r]??r)),[d,u]}));return{...n,operation:te[e]??e,custom:t}};var w="1.0.52-dev.a5f6699f.0",ae="CIOPGQJGDIHBABABA",U={prod:"https://api.ok.ru",vk_alias:"https://api.mycdn.me",videotest:"https://videotestapi.ok.ru/api",test:"https://apitest.ok.ru",auto:""};import{ValueSubject as Te,getExponentialDelay as Ce,ErrorCategory as I}from"@vkontakte/videoplayer-shared";var _=class{constructor(e){this.consequentAuthErrors=0;this.authorized$=new Te(!1);this.params=e}async authorize(e){return this.authToken=e??await this.refreshAuthToken(),this._authorizeWithBackoff()}logBeacon(e){let i="log.externalLog",t=this.createLogParams(e),o=this.sessionKey;if(!o)return;this.params.apiTransport.sendBeacon(i,t,o)||this.logRequest(e)}async logRequest(e){let i="log.externalLog",t=this.createLogParams(e),o=this.sessionKey??await this._authorizeWithBackoff();if(!o)return;let r=async(d,u=this.params.config.requestRetryCount)=>{try{return await this.params.apiTransport.sendRequest(i,t,o)}catch(l){if(!l||!("error_code"in l)){this.params.error$.next({id:"logRequestUnknown",category:I.NETWORK,message:`Unknown ${i} error`,thrown:l});return}let c=l?.error_code;switch(c){case 102:case 103:case 104:return this.authorized$.next(!1),this.sessionKey=await this._authorizeWithBackoff(),u>0?r(d,u-1):void 0;case 401:return this.authorized$.next(!1),this.authToken=await this.refreshAuthToken(),this.sessionKey=await this._authorizeWithBackoff(),u>0?r(d,u-1):void 0;default:{this.params.error$.next({id:`LogRequest#${c}`,category:I.EXTERNAL_API,message:`${i} error`,data:l});return}}}};return r(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:${w}`,platform:this.params.mobile?"M_WEB":"WEB",items:this.params.config.shorten?e.map(ne):e})}}_authorizeWithBackoff(){if(!this.consequentAuthErrors)return this._authorize();let e=Ce(this.consequentAuthErrors,this.params.config.backoff);return new Promise(i=>{this.backoffTimeoutId||(this.backoffTimeoutId=window.setTimeout(()=>{this._authorize().then(i).catch(t=>this.params.error$.next({id:"AuthorizeBackoff",category:I.NETWORK,message:"Otherwise unhandled error in authorization",thrown:t})).finally(()=>this.backoffTimeoutId=0)},e))})}async _authorize(){if(this.authorizePromise)return this.authorizePromise;this.sessionKey=void 0,this.authorized$.next(!1);let e="auth.anonymLogin",i={session_data:{version:2,device_id:this.params.uuid,client_version:w.split("-")[0],client_type:"SDK_JS"}};return this.authToken!==void 0&&(i.session_data.auth_token=this.authToken,i.session_data.version=3),this.authorizePromise=this.params.apiTransport.sendRequest(e,i).then(t=>((!t||!t.session_key)&&this.params.error$.next({id:"AuthorizeFailed",category:I.EXTERNAL_API,message:"No session key",data:t}),this.sessionKey=t?.session_key??void 0,this.sessionKey)).catch(async t=>{this.sessionKey=void 0;let o=t?.error_code;switch(o){case 401:return this.authToken=await this.refreshAuthToken(),this._authorizeWithBackoff()}o?this.params.error$.next({id:`Authorize#${o}`,category:I.EXTERNAL_API,message:"authorize error",data:t}):this.params.error$.next({id:"AuthorizeUnknown",category:I.NETWORK,message:"authorize error",thrown:t})}).finally(()=>{this.authorizePromise=void 0,this.consequentAuthErrors=this.sessionKey?0:this.consequentAuthErrors+1,this.authorized$.next(this.sessionKey!==void 0)}),this.authorizePromise}};import{ErrorCategory as k,now as W}from"@vkontakte/videoplayer-shared";var x=class{constructor(e){this.params=e,this.apiKey=e.apiKey,this.apiEnv=e.config.apiEnv,this.apiBaseUrl=U[this.apiEnv],this.timeSynchronisation=e.timeSynchronisation,this.isApiBaseUrlFetched=!1}async resolveApiBaseUrl(){if(this.apiEnv!=="auto"||this.isApiBaseUrlFetched)return this.apiBaseUrl;try{let e=atob("aHR0cHM6Ly9kbnMuZ29vZ2xlL3Jlc29sdmU/bmFtZT12aWRlby5fZW5kcG9pbnQub2sucnUmdHlwZT1UWFQ="),o=(await(await fetch(e,{method:"GET",mode:"cors",cache:"no-cache"})).json())?.Answer[0]?.data;if(!o)throw new Error("Wrong DNS response");return o}catch(e){return this.params.error$.next({id:"OneStat:ApiTransport:resolveApiBaseUrl",category:k.NETWORK,message:"Unhandled resolve api base url error",thrown:e}),U.vk_alias}finally{this.isApiBaseUrlFetched=!0}}sendBeacon(e,i,t){if(!window.Blob||!window.navigator.sendBeacon)return!1;let o=this._prepareQueryParams({method:e,queryParams:i,sessionKey:t}),r=new window.Blob([o.toString()],{type:"application/x-www-form-urlencoded"});try{return window.navigator.sendBeacon(`${this.apiBaseUrl}/fb.do`,r)}catch(d){this.params.error$.next({id:"OneStat:ApiTransport:sendBeacon",category:k.NETWORK,message:"Unhandled beacon error",thrown:d,data:{method:e,params:i}})}return!1}async sendRequest(e,i,t){let o=W(),r=d=>{if(d instanceof TypeError&&["Failed to fetch","NetworkError when attempting to fetch resource."].includes(d.message)){this.params.error$.next({id:"Network",category:k.NETWORK,message:"Request failed",thrown:d});return}this.params.error$.next({id:"OneStat:ApiTransport:sendRequest",category:k.NETWORK,message:"Unhandled request error",thrown:d,data:{method:e,params:i,sessionKey:t,time:W()-o}})};return this.apiBaseUrl=await this.resolveApiBaseUrl(),fetch(`${this.apiBaseUrl}/fb.do`,{method:"post",headers:{"Content-type":"application/x-www-form-urlencoded"},body:this._prepareQueryParams({method:e,queryParams:i,sessionKey:t})}).then(d=>{let u=Number(d.headers.get("content-length"))===0,l=new Date(d.headers.get("date")??"").getTime(),c=W()-o;if(isFinite(l)&&this.timeSynchronisation?.addServerTime(l,c),!u)return d.json().then(h=>Object.prototype.hasOwnProperty.call(h,"error_msg")?Promise.reject(h):h,r)},r)}_prepareQueryParams(e){let i=new URLSearchParams({format:"JSON",method:e.method,application_key:this.apiKey});return e.sessionKey!==void 0&&i.append("session_key",e.sessionKey),Object.entries(e.queryParams).forEach(([t,o])=>i.append(t,typeof o=="string"?o:JSON.stringify(o))),i}};import{ErrorCategory as we,now as ke,safeStorage as T,debounceFn as de}from"@vkontakte/videoplayer-shared";var L="onestat_events",H=n=>e=>e.timestamp+n>=ke(),$=class{constructor(e){this.unsaltedStorage=[];this.isPaused=!1;this.isUrgent=e=>{let{operation:i}=e;return["action_play","watch_coverage_record","watch_coverage_live"].includes(i)};this.params=e,this.api=e.api,this.error$=e.error$,this.userSalt=e.userSalt,this.loggerDebugLog=e.debugLogger.createComponentLog("stat logger"),this.firstFlush=de(()=>this.safeFlush(),this.params.config.firstFlushTime,{maxWait:this.params.config.firstFlushTime});let i=T.isPersistent()?this.params.config.flushMaxWait:0;this.debouncedFlush=de(()=>this.safeFlush(),this.params.config.flushDebounceTime,{maxWait:i}),this.subscription=this.api.authorized$.subscribe(t=>{t&&this.debouncedFlush()}),this.housekeepStorage()}safeFlush(){try{this.flush()}catch(e){this.error$.next({id:"LoggerError",category:we.WTF,message:String(e)??"Unknown logger error",thrown:e})}}readFromStorage(){let e=T.get(L);try{return e?JSON.parse(e):{}}catch{}return{}}addToStorage(e){if(!this.userSalt){this.unsaltedStorage.push(e);return}let i=this.readFromStorage(),o=(i[this.userSalt]??[]).filter(H(this.params.config.storageExpiration));T.set(L,JSON.stringify({...i,[this.userSalt]:[...o,e]}))}getFromStorage(){return this.userSalt?(this.readFromStorage()[this.userSalt]??[]).filter(H(this.params.config.storageExpiration)):this.unsaltedStorage}markStorageSent(){if(!this.userSalt){this.unsaltedStorage=[];return}let e=this.readFromStorage();delete e[this.userSalt],T.set(L,JSON.stringify(e))}housekeepStorage(){let e=this.readFromStorage();for(let[i,t]of Object.entries(e)){let o=t.filter(H(this.params.config.storageExpiration));o.length?e[i]=o:delete e[i],this.loggerDebugLog({message:`${t.length} retrieved from storage, ${o.length} of them actual`})}T.set(L,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){let i=this.getFromStorage();i.length!==0&&(this.api.authorized$.getValue()?(e&&this.params.config.useBeacon?(this.loggerDebugLog({message:`Flushing ${i.length} events through beacon`}),this.api.logBeacon(i)):(this.loggerDebugLog({message:`Flushing ${i.length} events`}),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()}};import{HttpConnectionType as K,Surface as S,VideoFormat as p,VideoQuality as m}from"@vkontakte/videoplayer-core";import{assertNever as ue}from"@vkontakte/videoplayer-shared";var ce=n=>n&&{[m.INVARIANT]:"unknown",[m.Q_144P]:"mobile",[m.Q_240P]:"lowest",[m.Q_360P]:"low",[m.Q_480P]:"medium",[m.Q_720P]:"high",[m.Q_1080P]:"fullhd",[m.Q_1440P]:"quadhd",[m.Q_2160P]:"ultrahd",[m.Q_4320P]:"unknown"}[n],q=n=>n&&{[K.HTTP1]:"http1",[K.HTTP2]:"http2",[K.QUIC]:"http3"}[n],le=n=>{if(n!==void 0)switch(n){case p.MPEG:return"mp4";case p.DASH:case p.DASH_LIVE:case p.DASH_STREAMS:return"dash";case p.DASH_SEP:return"dash_sep";case p.DASH_ONDEMAND:return"ondemand_dash";case p.DASH_WEBM:case p.DASH_LIVE_WEBM:return"webm";case p.DASH_WEBM_AV1:return"av1";case p.DASH_LIVE_CMAF:return"ondemand_dash_live";case p.HLS:case p.HLS_LIVE:return"hls";case p.HLS_ONDEMAND:return"ondemand_hls";case p.HLS_LIVE_CMAF:return"ondemand_hls_live";case p.WEB_RTC_LIVE:return"webrtc";default:return ue(n)}},R=n=>{if(n!==void 0)switch(n){case S.NONE:case S.INLINE:return;case S.FULLSCREEN:return"fullscreen";case S.SECOND_SCREEN:return"chromecast";case S.PIP:return"pip";case S.INVISIBLE:return"invisible";default:return ue(n)}},pe=n=>{switch(n){case"slow-2g":return"poor";case"2g":return"poor";case"3g":return"good";case"4g":return"excellent"}};var O=class{constructor(e){this.offset=void 0;this.offset=e}getOffset(){return this.offset??0}setOffset(e){this.offset=e}now(){return Date.now()+(this.offset??0)}date(e=new Date){return e.setTime(e.getTime()+(this.offset??0)),e}addServerTime(e,i){let t=Date.now(),o=e-t-i/2;if(Math.abs(o)<1e3){this.offset=0;return}this.offset===void 0?this.offset=Math.round(o):this.offset=Math.round(.2*o+(1-.2)*this.offset)}};var he=()=>Math.floor(Math.random()*4294967296).toString(36).padStart(7,"0"),fe=()=>Math.floor(Math.random()*18446744073709552e3).toString(36).padStart(13,"0");import{PlaybackState as ge}from"@vkontakte/videoplayer-core";import{filter as me,filterChanged as $e,fromEvent as Re,isNullable as be,map as Oe,merge as z,Observable as Ne,Subject as Q,Subscription as De,ValueSubject as Me}from"@vkontakte/videoplayer-shared";var ve=(n,e)=>new Ne(i=>{let t=new De,o=z(Re(window,"beforeunload"),n.events.willDestruct$),r=new Me(void 0),d;t.add(n.info.isLive$.pipe($e()).subscribe(v=>{d&&(d.unsubscribe(),r.next(void 0)),v?d=n.info.liveTime$.pipe(Oe(N=>N&&N/1e3)).subscribe(r):d=n.info.position$.subscribe(r),t.add(d)}));let{playing$:u,paused$:l}=n.events,c=n.events.willSeek$.pipe(me(()=>n.info.playbackState$.getValue()===ge.PLAYING)),h=n.events.seeked$.pipe(me(()=>n.info.playbackState$.getValue()===ge.PLAYING)),g=!1,s=new Q;t.add(c.subscribe(()=>{g||s.next(),g=!0})),t.add(h.subscribe(()=>g=!1));let a=new Q,f=new Q,P=z(u,h,a),C=z(l,s,o,n.events.looped$,f),A,Pe=()=>A=r.getValue(),Ae=()=>{let v=r.getValue();be(A)||A===v||be(v)||(i.next({from:A,to:v}),A=void 0)},Ee=()=>{f.next(),a.next()};if(t.add(P.subscribe(Pe)),t.add(C.subscribe(Ae)),e.forceInterval&&isFinite(e.forceInterval)){let v=0;t.add(P.subscribe(()=>v=window.setTimeout(Ee,e.forceInterval))),t.add(C.subscribe(()=>window.clearTimeout(v)))}return t});var qe="_one-stat_",Y=`${qe}uuid`,X=()=>{let n=new J;return{subscription:n,subscribe:(e,i)=>{e&&n.add(e.subscribe(i))}}},Z=class{constructor(e,i){this.subscription=new J;this.debugLogger=new He;this.oneStatDebugLog=this.debugLogger.createComponentLog("onestat");this.loopCounter=0;this.disabled=!1;this.vsid$=new G(void 0);this.isid$=new G(void 0);this.seekAction$=new G("unknown");this.statContext=e,this.config=re(i.config??{}),y(i.apiEnv)&&(this.config.apiEnv=i.apiEnv),this.config.synchronizeTime&&(this.timeSynchronisation=new O);let t=new We;this.experimental={error$:t};let o=j.get(Y);o?o.startsWith('"')&&o.endsWith('"')?(this.uuid=o.replaceAll('"',""),j.set(Y,this.uuid)):this.uuid=o:(this.uuid=V(),j.set(Y,this.uuid)),this.resetViewSession(),i.useIsid&&this.isid$.next(i.isid??fe());let r=new x({apiKey:ae,config:this.config,error$:t,timeSynchronisation:this.timeSynchronisation});this.api=new _({config:this.config,apiTransport:r,refreshAuthToken:i.refreshAuthToken,mobile:this.statContext.mobile??!1,uuid:this.uuid,error$:t}),this.logger=new $({config:this.config,debugLogger:this.debugLogger,api:this.api,error$:t,userSalt:i.userSalt});let{isEmbed:d,host:u}=Ke();this.isEmbed=d,this.embedParent=u,this.subscribe()}updateContext(e){this.statContext={...this.statContext,...e}}attachTo(e){let i=new J,t=(s,a)=>i.add(s.subscribe(a));t(e.events.willStart$,()=>{let s=e.info.position$.getValue();this.logActionPlay({position:s}),this.statContext.projectId&&this.logActionPlayInteractive()}),t(e.events.looped$,()=>{this.resetViewSession(),++this.loopCounter>this.config.maxLoops&&(this.disabled=!0),this.logActionPlay({position:e.info.position$.getValue()})}),t(e.events.seeked$,()=>{this.logSeek({action:this.seekAction$.getValue(),time:e.info.position$.getValue()}),this.seekAction$.next("unknown")}),t(e.events.paused$,()=>{this.logPause({position:e.info.position$.getValue()})}),t(e.events.willResume$,()=>{this.logPlay()}),t(e.events.started$,()=>{this.statContext.clip&&this.logWatchCoverageRecord({start:0,end:0})}),t(e.events.playing$,()=>{this.logPlaying()}),t(ve(e,{forceInterval:this.config.watchCoverageInterval}),s=>{let a=e.info.isLive$.getValue(),f={start:parseFloat(s.from.toFixed(3)),end:parseFloat(s.to.toFixed(3))};a?this.logWatchCoverageLive(f):this.logWatchCoverageRecord(f)});let o;t(e.info.isStalled$,s=>{s?o=b():(y(o)&&this.logEmptyBuffer({duration:b()-o}),o=void 0)});let r=!1;i.add(e.events.fatalError$.pipe(Ue()).subscribe(()=>r=!0)),t(e.events.willStop$,()=>{if(e.info.isStalled$.getValue()){let a=y(o)?b()-o:void 0;this.logCloseAtEmptyBuffer({duration:a??0}),o=void 0}else r||this.logActionStop()}),t(e.events.managedError$,({id:s})=>{this.logError({fatal:!1,errorType:s})}),t(e.events.fatalError$,({id:s})=>{this.logError({fatal:!0,errorType:s})});let d,u,l=!1;t(e.events.firstBytes$,s=>{d=b(),this.logFirstBytes({time:s})}),t(e.events.willStart$,()=>u=b()),t(e.info.currentBuffer$,s=>{!l&&s&&s.end-s.start>0&&y(d)&&(this.logPlayerReady({duration:b()-d}),l=!0)}),t(e.events.firstFrame$,()=>{y(d)&&!l&&(this.logPlayerReady({duration:b()-d}),l=!0),y(u)&&this.logFirstFrame({time:b()-u})});let c;t(e.info.currentVideoStream$,s=>{s&&(c&&s.id!==c&&this.logTrackSwitch(s),c=s.id)});let h;t(e.info.currentAudioStream$,s=>{s&&(h&&s.id!==h&&this.logTrackSwitch(s),h=s.id)}),t(e.info.atLiveEdge$,s=>this.updateContext({liveEdge:s})),t(Ie({muted:e.info.muted$,volume:e.info.volume$}),({muted:s,volume:a})=>this.updateContext({audible:!s&&a>0})),t(e.info.currentQuality$,s=>this.updateContext({quality:ce(s)})),t(e.info.isAutoQualityEnabled$,s=>this.updateContext({autoQuality:s})),t(e.info.currentFormat$,s=>this.updateContext({contentType:le(s)})),t(e.info.currentPlaybackRate$,s=>this.updateContext({rate:s})),t(e.info.is3DVideo$,s=>this.updateContext({is3d:s}));let g;return t(e.info.hostname$,s=>{let a=g!==void 0&&g!==s;this.updateContext({cdnHostname:s,failover:a}),a&&this.logFailover(s),g=s}),t(e.info.throughputEstimation$,s=>this.updateContext({downloadSpeed:s})),t(e.info.httpConnectionType$,s=>{this.statContext.firstConnectionType||this.updateContext({firstConnectionType:q(s)}),this.updateContext({connectionType:q(s)})}),t(e.info.httpConnectionReused$,s=>{ye(this.statContext.firstConnectionReused)&&this.updateContext({firstConnectionReused:s}),this.updateContext({connectionReused:s})}),t(e.info.surface$,s=>this.updateContext({mode:R(s)})),t(Ie({current:e.info.currentTextTrack$,available:e.info.availableTextTracks$}),({current:s,available:a})=>{let f=a.find(({id:C})=>C===s),P=f&&(f.isAuto?`${f.language}_auto`:f.language);this.updateContext({subtitles:P})}),this.player=e,this.uiEvents&&this.attachToUi(this.uiEvents),this.resubscribeBeforeunload(),this.subscription.add(i),i}attachToUi(e){this.uiEvents=e;let{subscription:i,subscribe:t}=X();return this.player&&(t(e.actionRewind$,()=>{this.player&&(this.resetViewSession(),this.logActionPlay({position:this.player.info.position$.getValue()}))}),t(e.actionSeek$,this.seekAction$),t(e.inPiP$,o=>{let r=o?"pip":R(this.player?.info.surface$.getValue());this.updateContext({mode:r})}),t(e.inFullscreen$,o=>{let r=o?"fullscreen":R(this.player?.info.surface$.getValue());this.updateContext({mode:r})}),t(e.actionSetSubtitle$,o=>this.updateContext({subtitles:o})),t(e.nextMovie$,o=>this.logNextMovie(o)),this.resubscribeBeforeunload(),this.subscription.add(i)),i}attachToAds(e){let{subscription:i,subscribe:t}=X();return t(e.slotRequested$,()=>this.logAdSlotRequest()),t(e.started$,o=>this.logAdStarted(o)),t(e.paused$,()=>this.logAdPaused()),t(e.resumed$,()=>this.logAdResumed()),t(e.ended$,()=>this.logAdEnded()),t(e.skipped$,()=>this.logAdSkipped()),t(e.clicked$,()=>this.logAdClicked()),this.resubscribeBeforeunload(),this.subscription.add(i),i}attachToInteractive(e){let{subscription:i,subscribe:t}=X();return t(e.click$,o=>this.logInterfaceClick(o)),t(e.nextMovie$,o=>this.logNextMovie(o)),this.resubscribeBeforeunload(),this.subscription.add(i),i}authorize(e){return this.api.authorize(e)}pause(){this.logger.pause(),this.oneStatDebugLog({message:"paused"})}resume(){this.logger.resume(),this.oneStatDebugLog({message:"resumed"})}destroy(){this.logger.flush(),this.subscription.unsubscribe(),this.api.destroy(),this.logger.destroy()}resetViewSession(){this.oneStatDebugLog({message:"VSID reset"}),this.vsid$.next(he())}getDeviceId(){return this.uuid}setFieldBlacklist(){}logInited(){}logReady(e){this.log({operation:"player_ready",param:String(e.time)})}logStarted(...e){this.logActionPlay(...e)}logPlay(){this.log({operation:"play_toggle"})}logPlaying(){this.log({operation:"playing"})}logPause(e){this.log({operation:"pause",param:String(Math.round(e.position))})}logSeek(e){this.log({operation:"seek",param:e.action,time:e.time})}logFirstBytes(e){this.log({operation:"first_bytes",param:String(e.time)})}logFirstFrame(e){this.log({operation:"first_frame",param:String(e.time)})}logError(e){this.log({operation:"content_error",param:`${e.fatal?"fatal":"recoverable"}_${e.errorType}`})}logWatchCoverageRecord(e){this.log({operation:"watch_coverage_record",param:`${e.start}-${e.end}`})}logWatchCoverageLive(e){let i=this.timeSynchronisation?.getOffset()??0,t=e.start+i,o=e.end+i;this.log({operation:"watch_coverage_live",param:`${t}-${o}`})}logEmptyBuffer(e){this.log({operation:"empty_buffer",param:String(e.duration)})}logDownloadSpeed(){}logAdSlotRequest(){this.log({operation:"adv",param:"slot_request"})}logAdStarted(e){this.log({operation:"adv",param:e})}logAdPaused(){this.log({operation:"adv",param:"pause"})}logAdResumed(){this.log({operation:"adv",param:"resume"})}logAdEnded(){this.log({operation:"adv",param:"ended"})}logAdSkipped(){this.log({operation:"adv",param:"skip"})}logAdClicked(){this.log({operation:"adv",param:"click"})}logInterfaceClick(e){this.log({operation:"player_interface_click",param:e})}logNextMovie(e){this.log({operation:"next_movie",param:String(e)})}subscribe(){this.resubscribeBeforeunload();let e=window.navigator.connection;e&&"onchange"in e&&"effectiveType"in e&&this.subscription.add(Fe(Se(e,"change"),Ve(["init"])).subscribe(()=>this.updateContext({network:pe(e.effectiveType)}))),this.config.debugLog&&this.debugLogger.log$.subscribe(i=>{console.debug("%c stat ","background:#fa6470;",`component: ${i.component}.`,i.message)})}resubscribeBeforeunload(){this.beforeunloadSubscription?.unsubscribe(),this.beforeunloadSubscription=Se(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))})}logActionPlayInteractive(){this.statContext.projectId&&this.log({operation:"action_play_interactive",param:String(this.statContext.movieId)},{vid:this.statContext.projectId})}logFailover(e){this.log({operation:"failover",param:e})}logCloseAtEmptyBuffer(e){this.log({operation:"close_at_empty_buffer",param:String(Math.round(e.duration))})}logActionStop(){this.log({operation:"action_stop"})}logTrackSwitch(e){this.log({operation:"track_switch",param:e.id})}log(e,i={}){if(this.disabled){this.oneStatDebugLog({message:`operation ${e.operation} but statistics is disabled`});return}if(this.config.disabledOperations.includes(e.operation)){this.oneStatDebugLog({message:`operation ${e.operation} but it is disabled`});return}this.oneStatDebugLog({message:`operation ${e.operation} ${e.param}`});let t=this.createLogItem(e,i);this.logger.log(t)}createLogItem({operation:e,param:i,time:t},o={}){let r=this.timeSynchronisation?.now()??b(),d=this.vsid$.getValue();Be(d);let u=this.isid$.getValue(),l=e==="empty_buffer"||e==="close_at_empty_buffer"?this.statContext.connectionType:this.statContext.firstConnectionType,c=this.statContext.firstConnectionReused,h,g;if(this.isEmbed){h=this.embedParent;let a=[...new URLSearchParams(location.search).entries()].filter(([f,P])=>this.config.embedUrlParams.includes(f));g=new URLSearchParams(a).toString()}else this.statContext.place==="direct"&&((this.statContext.refDomain||document.referrer)&&(h=new URL(this.statContext.refDomain||document.referrer).hostname),g=location.href.substring(0,1024));let s={vsid:d,isid:u,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?"auto":this.statContext.autoplay===!1?"":void 0,param:i,vk_app_id:this.statContext.vkAppId,track_code:this.statContext.trackCode,connection_type:l,connection_reused:c===!0?1:c===!1?0:void 0,cached_data:this.statContext.cached===!0?1:this.statContext.cached===!1?0:void 0,live:this.statContext.liveEdge?1:void 0,muted:this.statContext.audible===!1?1:void 0,mode:this.statContext.mode,subtitles:this.statContext.subtitles,download_speed:this.statContext.downloadSpeed,manual_quality:this.statContext.autoQuality?void 0:1,ref_domain:h,direct_url:g,rate:this.statContext.rate===1||ye(this.statContext.rate)?void 0:this.statContext.rate.toFixed(2),view_360:this.statContext.is3d?1:void 0,aid:this.statContext.albumId,vk_playlist_id:this.statContext.vkPlaylistId,...o};for(let a of this.config.disabledCustomFields)delete s[a];return{operation:e,type:1,time:t,network:this.statContext.network,timestamp:r,custom:s}}};export{E as ApiEnv,B as ConnectionType,M as ContentType,ee as InteractiveInterfaceClick,Z as OneStat,D as Quality,F as SeekAction,w as VERSION};
package/evergreen.esm.js CHANGED
@@ -1,6 +1,6 @@
1
1
  /**
2
- * @vkontakte/videoplayer-statistics v1.0.52-dev.22c05d5f.0
3
- * Tue, 30 Jul 2024 08:28:10 GMT
2
+ * @vkontakte/videoplayer-statistics v1.0.52-dev.a5f6699f.0
3
+ * Tue, 30 Jul 2024 10:43:01 GMT
4
4
  * https://st.mycdn.me/static/vkontakte-videoplayer/1-0-52/doc/
5
5
  */
6
- var E=(r=>(r.PROD="prod",r.VK_ALIAS="vk_alias",r.VIDEOTEST="videotest",r.TEST="test",r.AUTO="auto",r))(E||{}),D=(c=>(c.Q144P="mobile",c.Q240P="lowest",c.Q360P="low",c.Q480P="medium",c.Q720P="high",c.Q1080P="fullhd",c.Q1440P="quadhd",c.Q2160P="ultrahd",c.UNKNOWN="unknown",c))(D||{}),M=(a=>(a.MP4="mp4",a.DASH="dash",a.DASH_SEP="dash_sep",a.ONDEMAND_DASH="ondemand_dash",a.HLS="hls",a.ONDEMAND_HLS="ondemand_hls",a.WEBM="webm",a.AV1="av1",a.ONDEMAND_DASH_LIVE="ondemand_dash_live",a.ONDEMAND_HLS_LIVE="ondemand_hls_live",a.WEBRTC="webrtc",a.UNKNOWN="unknown",a.RTMP="rtmp",a))(M||{});var B=(t=>(t.HTTP1="http1",t.HTTP2="http2",t.HTTP3="http3",t))(B||{});var F=(u=>(u.SLIDER="slider",u.DOUBLE_TAP="double_tap",u.TIME_CODE="time_code",u.EPISODE="episode",u.REWIND="rewind",u.LIVE="live",u.UNKNOWN="unknown",u))(F||{}),ee=(r=>(r.GRAPH_SHOW="iGraphShow",r.GRAPH_HIDE="iGraphHide",r.NEXT_AREA="iNextChapterArea",r.NEXT_BUTTON="iNextChapterBtn",r.WATCH_AGAIN="iWatchAgainBtn",r))(ee||{}),te={action_play:"ap",action_play_interactive:"api",first_bytes:"fb",player_ready:"pr",first_frame:"ff",seek:"sk",watch_coverage_record:"wr",watch_coverage_live:"wl",empty_buffer:"eb",action_stop:"as",close_at_empty_buffer:"cb",content_error:"er",player_interface_click:"pc",next_movie:"nm",track_switch:"ts",failover:"fo"},ie={vsid:"si",isid:"is",vid:"vi",place:"pl",quality:"qt",cdn_host:"ch",stat_type:"st",param:"pm",vk_app_id:"va",track_code:"tc",connection_type:"cnt",connection_reused:"cr",cached_data:"cd",live:"lv",muted:"mu",mode:"mo",subtitles:"sb",failover:"fo",download_speed:"ds",manual_quality:"mq",ref_domain:"rd",direct_url:"du"},oe={unknown:"un",mobile:"m",lowest:"ls",low:"l",medium:"md",high:"h",fullhd:"f",quadhd:"q",ultrahd:"u"},se={pip:"pi",fullscreen:"fs",external:"ex",prefetch:"pr",airplay:"ap",chromecast:"cc",invisible:"iv"};import{fillWithDefault as _e}from"@vkontakte/videoplayer-shared";var xe={apiEnv:"vk_alias",requestRetryCount:1,firstFlushTime:5e3,flushDebounceTime:1e4,flushMaxWait:6e4,storageExpiration:36*60*60*1e3,watchCoverageInterval:15e3,disabledOperations:[],disabledCustomFields:[],shorten:!0,maxLoops:100,embedUrlParams:[],useBeacon:!0,synchronizeTime:!0,debugLog:!1,backoff:{start:1e3,factor:1.5,max:5*60*1e3,random:.1}},re=n=>_e(n,xe);function V(){let n="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".split(""),e=new Array(36),i=0,t,o;for(o=0;o<36;o++)o===8||o===13||o===18||o===23?e[o]="-":o===14?e[o]="4":(i<=2&&(i=33554432+Math.random()*16777216|0),t=i&15,i=i>>4,e[o]=n[o===19?t&3|8:t]);return e.join("")}import{assertNonNullable as Be,combine as Ie,fromEvent as Se,isNonNullable as y,isNullable as ye,merge as Fe,now as b,observableFrom as Ve,once as Ue,safeStorage as j,Subject as We,Subscription as J,ValueSubject as G}from"@vkontakte/videoplayer-shared";import{Logger as He,detectEmbed as Ke}from"@vkontakte/videoplayer-shared";var ne=n=>{let{operation:e,custom:i}=n,t=Object.fromEntries(Object.entries(i).map(([o,r])=>{let d=ie[o]??o,u=r;return r&&(o==="mode"?u=se[r]??r:o==="quality"&&(u=oe[r]??r)),[d,u]}));return{...n,operation:te[e]??e,custom:t}};var w="1.0.52-dev.22c05d5f.0",ae="CIOPGQJGDIHBABABA",U={prod:"https://api.ok.ru",vk_alias:"https://api.mycdn.me",videotest:"https://videotestapi.ok.ru/api",test:"https://apitest.ok.ru",auto:""};import{ValueSubject as Te,getExponentialDelay as Ce,ErrorCategory as I}from"@vkontakte/videoplayer-shared";var _=class{constructor(e){this.consequentAuthErrors=0;this.authorized$=new Te(!1);this.params=e}async authorize(e){return this.authToken=e??await this.refreshAuthToken(),this._authorizeWithBackoff()}logBeacon(e){let i="log.externalLog",t=this.createLogParams(e),o=this.sessionKey;if(!o)return;this.params.apiTransport.sendBeacon(i,t,o)||this.logRequest(e)}async logRequest(e){let i="log.externalLog",t=this.createLogParams(e),o=this.sessionKey??await this._authorizeWithBackoff();if(!o)return;let r=async(d,u=this.params.config.requestRetryCount)=>{try{return await this.params.apiTransport.sendRequest(i,t,o)}catch(l){if(!l||!("error_code"in l)){this.params.error$.next({id:"logRequestUnknown",category:I.NETWORK,message:`Unknown ${i} error`,thrown:l});return}let c=l?.error_code;switch(c){case 102:case 103:case 104:return this.authorized$.next(!1),this.sessionKey=await this._authorizeWithBackoff(),u>0?r(d,u-1):void 0;case 401:return this.authorized$.next(!1),this.authToken=await this.refreshAuthToken(),this.sessionKey=await this._authorizeWithBackoff(),u>0?r(d,u-1):void 0;default:{this.params.error$.next({id:`LogRequest#${c}`,category:I.EXTERNAL_API,message:`${i} error`,data:l});return}}}};return r(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:${w}`,platform:this.params.mobile?"M_WEB":"WEB",items:this.params.config.shorten?e.map(ne):e})}}_authorizeWithBackoff(){if(!this.consequentAuthErrors)return this._authorize();let e=Ce(this.consequentAuthErrors,this.params.config.backoff);return new Promise(i=>{this.backoffTimeoutId||(this.backoffTimeoutId=window.setTimeout(()=>{this._authorize().then(i).catch(t=>this.params.error$.next({id:"AuthorizeBackoff",category:I.NETWORK,message:"Otherwise unhandled error in authorization",thrown:t})).finally(()=>this.backoffTimeoutId=0)},e))})}async _authorize(){if(this.authorizePromise)return this.authorizePromise;this.sessionKey=void 0,this.authorized$.next(!1);let e="auth.anonymLogin",i={session_data:{version:2,device_id:this.params.uuid,client_version:w.split("-")[0],client_type:"SDK_JS"}};return this.authToken!==void 0&&(i.session_data.auth_token=this.authToken,i.session_data.version=3),this.authorizePromise=this.params.apiTransport.sendRequest(e,i).then(t=>((!t||!t.session_key)&&this.params.error$.next({id:"AuthorizeFailed",category:I.EXTERNAL_API,message:"No session key",data:t}),this.sessionKey=t?.session_key??void 0,this.sessionKey)).catch(async t=>{this.sessionKey=void 0;let o=t?.error_code;switch(o){case 401:return this.authToken=await this.refreshAuthToken(),this._authorizeWithBackoff()}o?this.params.error$.next({id:`Authorize#${o}`,category:I.EXTERNAL_API,message:"authorize error",data:t}):this.params.error$.next({id:"AuthorizeUnknown",category:I.NETWORK,message:"authorize error",thrown:t})}).finally(()=>{this.authorizePromise=void 0,this.consequentAuthErrors=this.sessionKey?0:this.consequentAuthErrors+1,this.authorized$.next(this.sessionKey!==void 0)}),this.authorizePromise}};import{ErrorCategory as k,now as W}from"@vkontakte/videoplayer-shared";var x=class{constructor(e){this.params=e,this.apiKey=e.apiKey,this.apiEnv=e.config.apiEnv,this.apiBaseUrl=U[this.apiEnv],this.timeSynchronisation=e.timeSynchronisation,this.isApiBaseUrlFetched=!1}async resolveApiBaseUrl(){if(this.apiEnv!=="auto"||this.isApiBaseUrlFetched)return this.apiBaseUrl;try{let e=atob("aHR0cHM6Ly9kbnMuZ29vZ2xlL3Jlc29sdmU/bmFtZT12aWRlby5fZW5kcG9pbnQub2sucnUmdHlwZT1UWFQ="),o=(await(await fetch(e,{method:"GET",mode:"cors",cache:"no-cache"})).json())?.Answer[0]?.data;if(!o)throw new Error("Wrong DNS response");return o}catch(e){return this.params.error$.next({id:"OneStat:ApiTransport:resolveApiBaseUrl",category:k.NETWORK,message:"Unhandled resolve api base url error",thrown:e}),U.vk_alias}finally{this.isApiBaseUrlFetched=!0}}sendBeacon(e,i,t){if(!window.Blob||!window.navigator.sendBeacon)return!1;let o=this._prepareQueryParams({method:e,queryParams:i,sessionKey:t}),r=new window.Blob([o.toString()],{type:"application/x-www-form-urlencoded"});try{return window.navigator.sendBeacon(`${this.apiBaseUrl}/fb.do`,r)}catch(d){this.params.error$.next({id:"OneStat:ApiTransport:sendBeacon",category:k.NETWORK,message:"Unhandled beacon error",thrown:d,data:{method:e,params:i}})}return!1}async sendRequest(e,i,t){let o=W(),r=d=>{if(d instanceof TypeError&&["Failed to fetch","NetworkError when attempting to fetch resource."].includes(d.message)){this.params.error$.next({id:"Network",category:k.NETWORK,message:"Request failed",thrown:d});return}this.params.error$.next({id:"OneStat:ApiTransport:sendRequest",category:k.NETWORK,message:"Unhandled request error",thrown:d,data:{method:e,params:i,sessionKey:t,time:W()-o}})};return this.apiBaseUrl=await this.resolveApiBaseUrl(),fetch(`${this.apiBaseUrl}/fb.do`,{method:"post",headers:{"Content-type":"application/x-www-form-urlencoded"},body:this._prepareQueryParams({method:e,queryParams:i,sessionKey:t})}).then(d=>{let u=Number(d.headers.get("content-length"))===0,l=new Date(d.headers.get("date")??"").getTime(),c=W()-o;if(isFinite(l)&&this.timeSynchronisation?.addServerTime(l,c),!u)return d.json().then(h=>Object.prototype.hasOwnProperty.call(h,"error_msg")?Promise.reject(h):h,r)},r)}_prepareQueryParams(e){let i=new URLSearchParams({format:"JSON",method:e.method,application_key:this.apiKey});return e.sessionKey!==void 0&&i.append("session_key",e.sessionKey),Object.entries(e.queryParams).forEach(([t,o])=>i.append(t,typeof o=="string"?o:JSON.stringify(o))),i}};import{ErrorCategory as we,now as ke,safeStorage as T,debounceFn as de}from"@vkontakte/videoplayer-shared";var L="onestat_events",H=n=>e=>e.timestamp+n>=ke(),$=class{constructor(e){this.unsaltedStorage=[];this.isPaused=!1;this.isUrgent=e=>{let{operation:i}=e;return["action_play","watch_coverage_record","watch_coverage_live"].includes(i)};this.params=e,this.api=e.api,this.error$=e.error$,this.userSalt=e.userSalt,this.loggerDebugLog=e.debugLogger.createComponentLog("stat logger"),this.firstFlush=de(()=>this.safeFlush(),this.params.config.firstFlushTime,{maxWait:this.params.config.firstFlushTime});let i=T.isPersistent()?this.params.config.flushMaxWait:0;this.debouncedFlush=de(()=>this.safeFlush(),this.params.config.flushDebounceTime,{maxWait:i}),this.subscription=this.api.authorized$.subscribe(t=>{t&&this.debouncedFlush()}),this.housekeepStorage()}safeFlush(){try{this.flush()}catch(e){this.error$.next({id:"LoggerError",category:we.WTF,message:String(e)??"Unknown logger error",thrown:e})}}readFromStorage(){let e=T.get(L);try{return e?JSON.parse(e):{}}catch{}return{}}addToStorage(e){if(!this.userSalt){this.unsaltedStorage.push(e);return}let i=this.readFromStorage(),o=(i[this.userSalt]??[]).filter(H(this.params.config.storageExpiration));T.set(L,JSON.stringify({...i,[this.userSalt]:[...o,e]}))}getFromStorage(){return this.userSalt?(this.readFromStorage()[this.userSalt]??[]).filter(H(this.params.config.storageExpiration)):this.unsaltedStorage}markStorageSent(){if(!this.userSalt){this.unsaltedStorage=[];return}let e=this.readFromStorage();delete e[this.userSalt],T.set(L,JSON.stringify(e))}housekeepStorage(){let e=this.readFromStorage();for(let[i,t]of Object.entries(e)){let o=t.filter(H(this.params.config.storageExpiration));o.length?e[i]=o:delete e[i],this.loggerDebugLog({message:`${t.length} retrieved from storage, ${o.length} of them actual`})}T.set(L,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){let i=this.getFromStorage();i.length!==0&&(this.api.authorized$.getValue()?(e&&this.params.config.useBeacon?(this.loggerDebugLog({message:`Flushing ${i.length} events through beacon`}),this.api.logBeacon(i)):(this.loggerDebugLog({message:`Flushing ${i.length} events`}),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()}};import{HttpConnectionType as K,Surface as S,VideoFormat as p,VideoQuality as m}from"@vkontakte/videoplayer-core";import{assertNever as ue}from"@vkontakte/videoplayer-shared";var ce=n=>n&&{[m.INVARIANT]:"unknown",[m.Q_144P]:"mobile",[m.Q_240P]:"lowest",[m.Q_360P]:"low",[m.Q_480P]:"medium",[m.Q_720P]:"high",[m.Q_1080P]:"fullhd",[m.Q_1440P]:"quadhd",[m.Q_2160P]:"ultrahd",[m.Q_4320P]:"unknown"}[n],q=n=>n&&{[K.HTTP1]:"http1",[K.HTTP2]:"http2",[K.QUIC]:"http3"}[n],le=n=>{if(n!==void 0)switch(n){case p.MPEG:return"mp4";case p.DASH:case p.DASH_LIVE:case p.DASH_STREAMS:return"dash";case p.DASH_SEP:return"dash_sep";case p.DASH_ONDEMAND:return"ondemand_dash";case p.DASH_WEBM:case p.DASH_LIVE_WEBM:return"webm";case p.DASH_WEBM_AV1:return"av1";case p.DASH_LIVE_CMAF:return"ondemand_dash_live";case p.HLS:case p.HLS_LIVE:return"hls";case p.HLS_ONDEMAND:return"ondemand_hls";case p.HLS_LIVE_CMAF:return"ondemand_hls_live";case p.WEB_RTC_LIVE:return"webrtc";default:return ue(n)}},R=n=>{if(n!==void 0)switch(n){case S.NONE:case S.INLINE:return;case S.FULLSCREEN:return"fullscreen";case S.SECOND_SCREEN:return"chromecast";case S.PIP:return"pip";case S.INVISIBLE:return"invisible";default:return ue(n)}},pe=n=>{switch(n){case"slow-2g":return"poor";case"2g":return"poor";case"3g":return"good";case"4g":return"excellent"}};var O=class{constructor(e){this.offset=void 0;this.offset=e}getOffset(){return this.offset??0}setOffset(e){this.offset=e}now(){return Date.now()+(this.offset??0)}date(e=new Date){return e.setTime(e.getTime()+(this.offset??0)),e}addServerTime(e,i){let t=Date.now(),o=e-t-i/2;if(Math.abs(o)<1e3){this.offset=0;return}this.offset===void 0?this.offset=Math.round(o):this.offset=Math.round(.2*o+(1-.2)*this.offset)}};var he=()=>Math.floor(Math.random()*4294967296).toString(36).padStart(7,"0"),fe=()=>Math.floor(Math.random()*18446744073709552e3).toString(36).padStart(13,"0");import{PlaybackState as ge}from"@vkontakte/videoplayer-core";import{filter as me,filterChanged as $e,fromEvent as Re,isNullable as be,map as Oe,merge as z,Observable as Ne,Subject as Q,Subscription as De,ValueSubject as Me}from"@vkontakte/videoplayer-shared";var ve=(n,e)=>new Ne(i=>{let t=new De,o=z(Re(window,"beforeunload"),n.events.willDestruct$),r=new Me(void 0),d;t.add(n.info.isLive$.pipe($e()).subscribe(v=>{d&&(d.unsubscribe(),r.next(void 0)),v?d=n.info.liveTime$.pipe(Oe(N=>N&&N/1e3)).subscribe(r):d=n.info.position$.subscribe(r),t.add(d)}));let{playing$:u,paused$:l}=n.events,c=n.events.willSeek$.pipe(me(()=>n.info.playbackState$.getValue()===ge.PLAYING)),h=n.events.seeked$.pipe(me(()=>n.info.playbackState$.getValue()===ge.PLAYING)),g=!1,s=new Q;t.add(c.subscribe(()=>{g||s.next(),g=!0})),t.add(h.subscribe(()=>g=!1));let a=new Q,f=new Q,P=z(u,h,a),C=z(l,s,o,n.events.looped$,f),A,Pe=()=>A=r.getValue(),Ae=()=>{let v=r.getValue();be(A)||A===v||be(v)||(i.next({from:A,to:v}),A=void 0)},Ee=()=>{f.next(),a.next()};if(t.add(P.subscribe(Pe)),t.add(C.subscribe(Ae)),e.forceInterval&&isFinite(e.forceInterval)){let v=0;t.add(P.subscribe(()=>v=window.setTimeout(Ee,e.forceInterval))),t.add(C.subscribe(()=>window.clearTimeout(v)))}return t});var qe="_one-stat_",Y=`${qe}uuid`,X=()=>{let n=new J;return{subscription:n,subscribe:(e,i)=>{e&&n.add(e.subscribe(i))}}},Z=class{constructor(e,i){this.subscription=new J;this.debugLogger=new He;this.oneStatDebugLog=this.debugLogger.createComponentLog("onestat");this.loopCounter=0;this.disabled=!1;this.vsid$=new G(void 0);this.isid$=new G(void 0);this.seekAction$=new G("unknown");this.statContext=e,this.config=re(i.config??{}),y(i.apiEnv)&&(this.config.apiEnv=i.apiEnv),this.config.synchronizeTime&&(this.timeSynchronisation=new O);let t=new We;this.experimental={error$:t};let o=j.get(Y);o?o.startsWith('"')&&o.endsWith('"')?(this.uuid=o.replaceAll('"',""),j.set(Y,this.uuid)):this.uuid=o:(this.uuid=V(),j.set(Y,this.uuid)),this.resetViewSession(),i.useIsid&&this.isid$.next(i.isid??fe());let r=new x({apiKey:ae,config:this.config,error$:t,timeSynchronisation:this.timeSynchronisation});this.api=new _({config:this.config,apiTransport:r,refreshAuthToken:i.refreshAuthToken,mobile:this.statContext.mobile??!1,uuid:this.uuid,error$:t}),this.logger=new $({config:this.config,debugLogger:this.debugLogger,api:this.api,error$:t,userSalt:i.userSalt});let{isEmbed:d,host:u}=Ke();this.isEmbed=d,this.embedParent=u,this.subscribe()}updateContext(e){this.statContext={...this.statContext,...e}}attachTo(e){let i=new J,t=(s,a)=>i.add(s.subscribe(a));t(e.events.willStart$,()=>{let s=e.info.position$.getValue();this.logActionPlay({position:s}),this.statContext.projectId&&this.logActionPlayInteractive()}),t(e.events.looped$,()=>{this.resetViewSession(),++this.loopCounter>this.config.maxLoops&&(this.disabled=!0),this.logActionPlay({position:e.info.position$.getValue()})}),t(e.events.seeked$,()=>{this.logSeek({action:this.seekAction$.getValue(),time:e.info.position$.getValue()}),this.seekAction$.next("unknown")}),t(e.events.paused$,()=>{this.logPause({position:e.info.position$.getValue()})}),t(e.events.willResume$,()=>{this.logPlay()}),t(e.events.started$,()=>{this.statContext.clip&&this.logWatchCoverageRecord({start:0,end:0})}),t(e.events.playing$,()=>{this.logPlaying()}),t(ve(e,{forceInterval:this.config.watchCoverageInterval}),s=>{let a=e.info.isLive$.getValue(),f={start:parseFloat(s.from.toFixed(3)),end:parseFloat(s.to.toFixed(3))};a?this.logWatchCoverageLive(f):this.logWatchCoverageRecord(f)});let o;t(e.info.isStalled$,s=>{s?o=b():(y(o)&&this.logEmptyBuffer({duration:b()-o}),o=void 0)});let r=!1;i.add(e.events.fatalError$.pipe(Ue()).subscribe(()=>r=!0)),t(e.events.willStop$,()=>{if(e.info.isStalled$.getValue()){let a=y(o)?b()-o:void 0;this.logCloseAtEmptyBuffer({duration:a??0}),o=void 0}else r||this.logActionStop()}),t(e.events.managedError$,({id:s})=>{this.logError({fatal:!1,errorType:s})}),t(e.events.fatalError$,({id:s})=>{this.logError({fatal:!0,errorType:s})});let d,u,l=!1;t(e.events.firstBytes$,s=>{d=b(),this.logFirstBytes({time:s})}),t(e.events.willStart$,()=>u=b()),t(e.info.currentBuffer$,s=>{!l&&s&&s.end-s.start>0&&y(d)&&(this.logPlayerReady({duration:b()-d}),l=!0)}),t(e.events.firstFrame$,()=>{y(d)&&!l&&(this.logPlayerReady({duration:b()-d}),l=!0),y(u)&&this.logFirstFrame({time:b()-u})});let c;t(e.info.currentVideoStream$,s=>{s&&(c&&s.id!==c&&this.logTrackSwitch(s),c=s.id)});let h;t(e.info.currentAudioStream$,s=>{s&&(h&&s.id!==h&&this.logTrackSwitch(s),h=s.id)}),t(e.info.atLiveEdge$,s=>this.updateContext({liveEdge:s})),t(Ie({muted:e.info.muted$,volume:e.info.volume$}),({muted:s,volume:a})=>this.updateContext({audible:!s&&a>0})),t(e.info.currentQuality$,s=>this.updateContext({quality:ce(s)})),t(e.info.isAutoQualityEnabled$,s=>this.updateContext({autoQuality:s})),t(e.info.currentFormat$,s=>this.updateContext({contentType:le(s)})),t(e.info.currentPlaybackRate$,s=>this.updateContext({rate:s})),t(e.info.is3DVideo$,s=>this.updateContext({is3d:s}));let g;return t(e.info.hostname$,s=>{let a=g!==void 0&&g!==s;this.updateContext({cdnHostname:s,failover:a}),a&&this.logFailover(s),g=s}),t(e.info.throughputEstimation$,s=>this.updateContext({downloadSpeed:s})),t(e.info.httpConnectionType$,s=>{this.statContext.firstConnectionType||this.updateContext({firstConnectionType:q(s)}),this.updateContext({connectionType:q(s)})}),t(e.info.httpConnectionReused$,s=>{ye(this.statContext.firstConnectionReused)&&this.updateContext({firstConnectionReused:s}),this.updateContext({connectionReused:s})}),t(e.info.surface$,s=>this.updateContext({mode:R(s)})),t(Ie({current:e.info.currentTextTrack$,available:e.info.availableTextTracks$}),({current:s,available:a})=>{let f=a.find(({id:C})=>C===s),P=f&&(f.isAuto?`${f.language}_auto`:f.language);this.updateContext({subtitles:P})}),this.player=e,this.uiEvents&&this.attachToUi(this.uiEvents),this.resubscribeBeforeunload(),this.subscription.add(i),i}attachToUi(e){this.uiEvents=e;let{subscription:i,subscribe:t}=X();return this.player&&(t(e.actionRewind$,()=>{this.player&&(this.resetViewSession(),this.logActionPlay({position:this.player.info.position$.getValue()}))}),t(e.actionSeek$,this.seekAction$),t(e.inPiP$,o=>{let r=o?"pip":R(this.player?.info.surface$.getValue());this.updateContext({mode:r})}),t(e.inFullscreen$,o=>{let r=o?"fullscreen":R(this.player?.info.surface$.getValue());this.updateContext({mode:r})}),t(e.actionSetSubtitle$,o=>this.updateContext({subtitles:o})),t(e.nextMovie$,o=>this.logNextMovie(o)),this.resubscribeBeforeunload(),this.subscription.add(i)),i}attachToAds(e){let{subscription:i,subscribe:t}=X();return t(e.slotRequested$,()=>this.logAdSlotRequest()),t(e.started$,o=>this.logAdStarted(o)),t(e.paused$,()=>this.logAdPaused()),t(e.resumed$,()=>this.logAdResumed()),t(e.ended$,()=>this.logAdEnded()),t(e.skipped$,()=>this.logAdSkipped()),t(e.clicked$,()=>this.logAdClicked()),this.resubscribeBeforeunload(),this.subscription.add(i),i}attachToInteractive(e){let{subscription:i,subscribe:t}=X();return t(e.click$,o=>this.logInterfaceClick(o)),t(e.nextMovie$,o=>this.logNextMovie(o)),this.resubscribeBeforeunload(),this.subscription.add(i),i}authorize(e){return this.api.authorize(e)}pause(){this.logger.pause(),this.oneStatDebugLog({message:"paused"})}resume(){this.logger.resume(),this.oneStatDebugLog({message:"resumed"})}destroy(){this.logger.flush(),this.subscription.unsubscribe(),this.api.destroy(),this.logger.destroy()}resetViewSession(){this.oneStatDebugLog({message:"VSID reset"}),this.vsid$.next(he())}getDeviceId(){return this.uuid}setFieldBlacklist(){}logInited(){}logReady(e){this.log({operation:"player_ready",param:String(e.time)})}logStarted(...e){this.logActionPlay(...e)}logPlay(){this.log({operation:"play_toggle"})}logPlaying(){this.log({operation:"playing"})}logPause(e){this.log({operation:"pause",param:String(Math.round(e.position))})}logSeek(e){this.log({operation:"seek",param:e.action,time:e.time})}logFirstBytes(e){this.log({operation:"first_bytes",param:String(e.time)})}logFirstFrame(e){this.log({operation:"first_frame",param:String(e.time)})}logError(e){this.log({operation:"content_error",param:`${e.fatal?"fatal":"recoverable"}_${e.errorType}`})}logWatchCoverageRecord(e){this.log({operation:"watch_coverage_record",param:`${e.start}-${e.end}`})}logWatchCoverageLive(e){let i=this.timeSynchronisation?.getOffset()??0,t=e.start+i,o=e.end+i;this.log({operation:"watch_coverage_live",param:`${t}-${o}`})}logEmptyBuffer(e){this.log({operation:"empty_buffer",param:String(e.duration)})}logDownloadSpeed(){}logAdSlotRequest(){this.log({operation:"adv",param:"slot_request"})}logAdStarted(e){this.log({operation:"adv",param:e})}logAdPaused(){this.log({operation:"adv",param:"pause"})}logAdResumed(){this.log({operation:"adv",param:"resume"})}logAdEnded(){this.log({operation:"adv",param:"ended"})}logAdSkipped(){this.log({operation:"adv",param:"skip"})}logAdClicked(){this.log({operation:"adv",param:"click"})}logInterfaceClick(e){this.log({operation:"player_interface_click",param:e})}logNextMovie(e){this.log({operation:"next_movie",param:String(e)})}subscribe(){this.resubscribeBeforeunload();let e=window.navigator.connection;e&&"onchange"in e&&"effectiveType"in e&&this.subscription.add(Fe(Se(e,"change"),Ve(["init"])).subscribe(()=>this.updateContext({network:pe(e.effectiveType)}))),this.config.debugLog&&this.debugLogger.log$.subscribe(i=>{console.debug("%c stat ","background:#fa6470;",`component: ${i.component}.`,i.message)})}resubscribeBeforeunload(){this.beforeunloadSubscription?.unsubscribe(),this.beforeunloadSubscription=Se(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))})}logActionPlayInteractive(){this.statContext.projectId&&this.log({operation:"action_play_interactive",param:String(this.statContext.movieId)},{vid:this.statContext.projectId})}logFailover(e){this.log({operation:"failover",param:e})}logCloseAtEmptyBuffer(e){this.log({operation:"close_at_empty_buffer",param:String(Math.round(e.duration))})}logActionStop(){this.log({operation:"action_stop"})}logTrackSwitch(e){this.log({operation:"track_switch",param:e.id})}log(e,i={}){if(this.disabled){this.oneStatDebugLog({message:`operation ${e.operation} but statistics is disabled`});return}if(this.config.disabledOperations.includes(e.operation)){this.oneStatDebugLog({message:`operation ${e.operation} but it is disabled`});return}this.oneStatDebugLog({message:`operation ${e.operation} ${e.param}`});let t=this.createLogItem(e,i);this.logger.log(t)}createLogItem({operation:e,param:i,time:t},o={}){let r=this.timeSynchronisation?.now()??b(),d=this.vsid$.getValue();Be(d);let u=this.isid$.getValue(),l=e==="empty_buffer"||e==="close_at_empty_buffer"?this.statContext.connectionType:this.statContext.firstConnectionType,c=this.statContext.firstConnectionReused,h,g;if(this.isEmbed){h=this.embedParent;let a=[...new URLSearchParams(location.search).entries()].filter(([f,P])=>this.config.embedUrlParams.includes(f));g=new URLSearchParams(a).toString()}else this.statContext.place==="direct"&&((this.statContext.refDomain||document.referrer)&&(h=new URL(this.statContext.refDomain||document.referrer).hostname),g=location.href.substring(0,1024));let s={vsid:d,isid:u,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?"auto":this.statContext.autoplay===!1?"":void 0,param:i,vk_app_id:this.statContext.vkAppId,track_code:this.statContext.trackCode,connection_type:l,connection_reused:c===!0?1:c===!1?0:void 0,cached_data:this.statContext.cached===!0?1:this.statContext.cached===!1?0:void 0,live:this.statContext.liveEdge?1:void 0,muted:this.statContext.audible===!1?1:void 0,mode:this.statContext.mode,subtitles:this.statContext.subtitles,download_speed:this.statContext.downloadSpeed,manual_quality:this.statContext.autoQuality?void 0:1,ref_domain:h,direct_url:g,rate:this.statContext.rate===1||ye(this.statContext.rate)?void 0:this.statContext.rate.toFixed(2),view_360:this.statContext.is3d?1:void 0,aid:this.statContext.albumId,vk_playlist_id:this.statContext.vkPlaylistId,...o};for(let a of this.config.disabledCustomFields)delete s[a];return{operation:e,type:1,time:t,network:this.statContext.network,timestamp:r,custom:s}}};export{E as ApiEnv,B as ConnectionType,M as ContentType,ee as InteractiveInterfaceClick,Z as OneStat,D as Quality,F as SeekAction,w as VERSION};
6
+ var E=(r=>(r.PROD="prod",r.VK_ALIAS="vk_alias",r.VIDEOTEST="videotest",r.TEST="test",r.AUTO="auto",r))(E||{}),D=(c=>(c.Q144P="mobile",c.Q240P="lowest",c.Q360P="low",c.Q480P="medium",c.Q720P="high",c.Q1080P="fullhd",c.Q1440P="quadhd",c.Q2160P="ultrahd",c.UNKNOWN="unknown",c))(D||{}),M=(a=>(a.MP4="mp4",a.DASH="dash",a.DASH_SEP="dash_sep",a.ONDEMAND_DASH="ondemand_dash",a.HLS="hls",a.ONDEMAND_HLS="ondemand_hls",a.WEBM="webm",a.AV1="av1",a.ONDEMAND_DASH_LIVE="ondemand_dash_live",a.ONDEMAND_HLS_LIVE="ondemand_hls_live",a.WEBRTC="webrtc",a.UNKNOWN="unknown",a.RTMP="rtmp",a))(M||{});var B=(t=>(t.HTTP1="http1",t.HTTP2="http2",t.HTTP3="http3",t))(B||{});var F=(u=>(u.SLIDER="slider",u.DOUBLE_TAP="double_tap",u.TIME_CODE="time_code",u.EPISODE="episode",u.REWIND="rewind",u.LIVE="live",u.UNKNOWN="unknown",u))(F||{}),ee=(r=>(r.GRAPH_SHOW="iGraphShow",r.GRAPH_HIDE="iGraphHide",r.NEXT_AREA="iNextChapterArea",r.NEXT_BUTTON="iNextChapterBtn",r.WATCH_AGAIN="iWatchAgainBtn",r))(ee||{}),te={action_play:"ap",action_play_interactive:"api",first_bytes:"fb",player_ready:"pr",first_frame:"ff",seek:"sk",watch_coverage_record:"wr",watch_coverage_live:"wl",empty_buffer:"eb",action_stop:"as",close_at_empty_buffer:"cb",content_error:"er",player_interface_click:"pc",next_movie:"nm",track_switch:"ts",failover:"fo"},ie={vsid:"si",isid:"is",vid:"vi",place:"pl",quality:"qt",cdn_host:"ch",stat_type:"st",param:"pm",vk_app_id:"va",track_code:"tc",connection_type:"cnt",connection_reused:"cr",cached_data:"cd",live:"lv",muted:"mu",mode:"mo",subtitles:"sb",failover:"fo",download_speed:"ds",manual_quality:"mq",ref_domain:"rd",direct_url:"du"},oe={unknown:"un",mobile:"m",lowest:"ls",low:"l",medium:"md",high:"h",fullhd:"f",quadhd:"q",ultrahd:"u"},se={pip:"pi",fullscreen:"fs",external:"ex",prefetch:"pr",airplay:"ap",chromecast:"cc",invisible:"iv"};import{fillWithDefault as _e}from"@vkontakte/videoplayer-shared";var xe={apiEnv:"vk_alias",requestRetryCount:1,firstFlushTime:5e3,flushDebounceTime:1e4,flushMaxWait:6e4,storageExpiration:36*60*60*1e3,watchCoverageInterval:15e3,disabledOperations:[],disabledCustomFields:[],shorten:!0,maxLoops:100,embedUrlParams:[],useBeacon:!0,synchronizeTime:!0,debugLog:!1,backoff:{start:1e3,factor:1.5,max:5*60*1e3,random:.1}},re=n=>_e(n,xe);function V(){let n="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".split(""),e=new Array(36),i=0,t,o;for(o=0;o<36;o++)o===8||o===13||o===18||o===23?e[o]="-":o===14?e[o]="4":(i<=2&&(i=33554432+Math.random()*16777216|0),t=i&15,i=i>>4,e[o]=n[o===19?t&3|8:t]);return e.join("")}import{assertNonNullable as Be,combine as Ie,fromEvent as Se,isNonNullable as y,isNullable as ye,merge as Fe,now as b,observableFrom as Ve,once as Ue,safeStorage as j,Subject as We,Subscription as J,ValueSubject as G}from"@vkontakte/videoplayer-shared";import{Logger as He,detectEmbed as Ke}from"@vkontakte/videoplayer-shared";var ne=n=>{let{operation:e,custom:i}=n,t=Object.fromEntries(Object.entries(i).map(([o,r])=>{let d=ie[o]??o,u=r;return r&&(o==="mode"?u=se[r]??r:o==="quality"&&(u=oe[r]??r)),[d,u]}));return{...n,operation:te[e]??e,custom:t}};var w="1.0.52-dev.a5f6699f.0",ae="CIOPGQJGDIHBABABA",U={prod:"https://api.ok.ru",vk_alias:"https://api.mycdn.me",videotest:"https://videotestapi.ok.ru/api",test:"https://apitest.ok.ru",auto:""};import{ValueSubject as Te,getExponentialDelay as Ce,ErrorCategory as I}from"@vkontakte/videoplayer-shared";var _=class{constructor(e){this.consequentAuthErrors=0;this.authorized$=new Te(!1);this.params=e}async authorize(e){return this.authToken=e??await this.refreshAuthToken(),this._authorizeWithBackoff()}logBeacon(e){let i="log.externalLog",t=this.createLogParams(e),o=this.sessionKey;if(!o)return;this.params.apiTransport.sendBeacon(i,t,o)||this.logRequest(e)}async logRequest(e){let i="log.externalLog",t=this.createLogParams(e),o=this.sessionKey??await this._authorizeWithBackoff();if(!o)return;let r=async(d,u=this.params.config.requestRetryCount)=>{try{return await this.params.apiTransport.sendRequest(i,t,o)}catch(l){if(!l||!("error_code"in l)){this.params.error$.next({id:"logRequestUnknown",category:I.NETWORK,message:`Unknown ${i} error`,thrown:l});return}let c=l?.error_code;switch(c){case 102:case 103:case 104:return this.authorized$.next(!1),this.sessionKey=await this._authorizeWithBackoff(),u>0?r(d,u-1):void 0;case 401:return this.authorized$.next(!1),this.authToken=await this.refreshAuthToken(),this.sessionKey=await this._authorizeWithBackoff(),u>0?r(d,u-1):void 0;default:{this.params.error$.next({id:`LogRequest#${c}`,category:I.EXTERNAL_API,message:`${i} error`,data:l});return}}}};return r(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:${w}`,platform:this.params.mobile?"M_WEB":"WEB",items:this.params.config.shorten?e.map(ne):e})}}_authorizeWithBackoff(){if(!this.consequentAuthErrors)return this._authorize();let e=Ce(this.consequentAuthErrors,this.params.config.backoff);return new Promise(i=>{this.backoffTimeoutId||(this.backoffTimeoutId=window.setTimeout(()=>{this._authorize().then(i).catch(t=>this.params.error$.next({id:"AuthorizeBackoff",category:I.NETWORK,message:"Otherwise unhandled error in authorization",thrown:t})).finally(()=>this.backoffTimeoutId=0)},e))})}async _authorize(){if(this.authorizePromise)return this.authorizePromise;this.sessionKey=void 0,this.authorized$.next(!1);let e="auth.anonymLogin",i={session_data:{version:2,device_id:this.params.uuid,client_version:w.split("-")[0],client_type:"SDK_JS"}};return this.authToken!==void 0&&(i.session_data.auth_token=this.authToken,i.session_data.version=3),this.authorizePromise=this.params.apiTransport.sendRequest(e,i).then(t=>((!t||!t.session_key)&&this.params.error$.next({id:"AuthorizeFailed",category:I.EXTERNAL_API,message:"No session key",data:t}),this.sessionKey=t?.session_key??void 0,this.sessionKey)).catch(async t=>{this.sessionKey=void 0;let o=t?.error_code;switch(o){case 401:return this.authToken=await this.refreshAuthToken(),this._authorizeWithBackoff()}o?this.params.error$.next({id:`Authorize#${o}`,category:I.EXTERNAL_API,message:"authorize error",data:t}):this.params.error$.next({id:"AuthorizeUnknown",category:I.NETWORK,message:"authorize error",thrown:t})}).finally(()=>{this.authorizePromise=void 0,this.consequentAuthErrors=this.sessionKey?0:this.consequentAuthErrors+1,this.authorized$.next(this.sessionKey!==void 0)}),this.authorizePromise}};import{ErrorCategory as k,now as W}from"@vkontakte/videoplayer-shared";var x=class{constructor(e){this.params=e,this.apiKey=e.apiKey,this.apiEnv=e.config.apiEnv,this.apiBaseUrl=U[this.apiEnv],this.timeSynchronisation=e.timeSynchronisation,this.isApiBaseUrlFetched=!1}async resolveApiBaseUrl(){if(this.apiEnv!=="auto"||this.isApiBaseUrlFetched)return this.apiBaseUrl;try{let e=atob("aHR0cHM6Ly9kbnMuZ29vZ2xlL3Jlc29sdmU/bmFtZT12aWRlby5fZW5kcG9pbnQub2sucnUmdHlwZT1UWFQ="),o=(await(await fetch(e,{method:"GET",mode:"cors",cache:"no-cache"})).json())?.Answer[0]?.data;if(!o)throw new Error("Wrong DNS response");return o}catch(e){return this.params.error$.next({id:"OneStat:ApiTransport:resolveApiBaseUrl",category:k.NETWORK,message:"Unhandled resolve api base url error",thrown:e}),U.vk_alias}finally{this.isApiBaseUrlFetched=!0}}sendBeacon(e,i,t){if(!window.Blob||!window.navigator.sendBeacon)return!1;let o=this._prepareQueryParams({method:e,queryParams:i,sessionKey:t}),r=new window.Blob([o.toString()],{type:"application/x-www-form-urlencoded"});try{return window.navigator.sendBeacon(`${this.apiBaseUrl}/fb.do`,r)}catch(d){this.params.error$.next({id:"OneStat:ApiTransport:sendBeacon",category:k.NETWORK,message:"Unhandled beacon error",thrown:d,data:{method:e,params:i}})}return!1}async sendRequest(e,i,t){let o=W(),r=d=>{if(d instanceof TypeError&&["Failed to fetch","NetworkError when attempting to fetch resource."].includes(d.message)){this.params.error$.next({id:"Network",category:k.NETWORK,message:"Request failed",thrown:d});return}this.params.error$.next({id:"OneStat:ApiTransport:sendRequest",category:k.NETWORK,message:"Unhandled request error",thrown:d,data:{method:e,params:i,sessionKey:t,time:W()-o}})};return this.apiBaseUrl=await this.resolveApiBaseUrl(),fetch(`${this.apiBaseUrl}/fb.do`,{method:"post",headers:{"Content-type":"application/x-www-form-urlencoded"},body:this._prepareQueryParams({method:e,queryParams:i,sessionKey:t})}).then(d=>{let u=Number(d.headers.get("content-length"))===0,l=new Date(d.headers.get("date")??"").getTime(),c=W()-o;if(isFinite(l)&&this.timeSynchronisation?.addServerTime(l,c),!u)return d.json().then(h=>Object.prototype.hasOwnProperty.call(h,"error_msg")?Promise.reject(h):h,r)},r)}_prepareQueryParams(e){let i=new URLSearchParams({format:"JSON",method:e.method,application_key:this.apiKey});return e.sessionKey!==void 0&&i.append("session_key",e.sessionKey),Object.entries(e.queryParams).forEach(([t,o])=>i.append(t,typeof o=="string"?o:JSON.stringify(o))),i}};import{ErrorCategory as we,now as ke,safeStorage as T,debounceFn as de}from"@vkontakte/videoplayer-shared";var L="onestat_events",H=n=>e=>e.timestamp+n>=ke(),$=class{constructor(e){this.unsaltedStorage=[];this.isPaused=!1;this.isUrgent=e=>{let{operation:i}=e;return["action_play","watch_coverage_record","watch_coverage_live"].includes(i)};this.params=e,this.api=e.api,this.error$=e.error$,this.userSalt=e.userSalt,this.loggerDebugLog=e.debugLogger.createComponentLog("stat logger"),this.firstFlush=de(()=>this.safeFlush(),this.params.config.firstFlushTime,{maxWait:this.params.config.firstFlushTime});let i=T.isPersistent()?this.params.config.flushMaxWait:0;this.debouncedFlush=de(()=>this.safeFlush(),this.params.config.flushDebounceTime,{maxWait:i}),this.subscription=this.api.authorized$.subscribe(t=>{t&&this.debouncedFlush()}),this.housekeepStorage()}safeFlush(){try{this.flush()}catch(e){this.error$.next({id:"LoggerError",category:we.WTF,message:String(e)??"Unknown logger error",thrown:e})}}readFromStorage(){let e=T.get(L);try{return e?JSON.parse(e):{}}catch{}return{}}addToStorage(e){if(!this.userSalt){this.unsaltedStorage.push(e);return}let i=this.readFromStorage(),o=(i[this.userSalt]??[]).filter(H(this.params.config.storageExpiration));T.set(L,JSON.stringify({...i,[this.userSalt]:[...o,e]}))}getFromStorage(){return this.userSalt?(this.readFromStorage()[this.userSalt]??[]).filter(H(this.params.config.storageExpiration)):this.unsaltedStorage}markStorageSent(){if(!this.userSalt){this.unsaltedStorage=[];return}let e=this.readFromStorage();delete e[this.userSalt],T.set(L,JSON.stringify(e))}housekeepStorage(){let e=this.readFromStorage();for(let[i,t]of Object.entries(e)){let o=t.filter(H(this.params.config.storageExpiration));o.length?e[i]=o:delete e[i],this.loggerDebugLog({message:`${t.length} retrieved from storage, ${o.length} of them actual`})}T.set(L,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){let i=this.getFromStorage();i.length!==0&&(this.api.authorized$.getValue()?(e&&this.params.config.useBeacon?(this.loggerDebugLog({message:`Flushing ${i.length} events through beacon`}),this.api.logBeacon(i)):(this.loggerDebugLog({message:`Flushing ${i.length} events`}),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()}};import{HttpConnectionType as K,Surface as S,VideoFormat as p,VideoQuality as m}from"@vkontakte/videoplayer-core";import{assertNever as ue}from"@vkontakte/videoplayer-shared";var ce=n=>n&&{[m.INVARIANT]:"unknown",[m.Q_144P]:"mobile",[m.Q_240P]:"lowest",[m.Q_360P]:"low",[m.Q_480P]:"medium",[m.Q_720P]:"high",[m.Q_1080P]:"fullhd",[m.Q_1440P]:"quadhd",[m.Q_2160P]:"ultrahd",[m.Q_4320P]:"unknown"}[n],q=n=>n&&{[K.HTTP1]:"http1",[K.HTTP2]:"http2",[K.QUIC]:"http3"}[n],le=n=>{if(n!==void 0)switch(n){case p.MPEG:return"mp4";case p.DASH:case p.DASH_LIVE:case p.DASH_STREAMS:return"dash";case p.DASH_SEP:return"dash_sep";case p.DASH_ONDEMAND:return"ondemand_dash";case p.DASH_WEBM:case p.DASH_LIVE_WEBM:return"webm";case p.DASH_WEBM_AV1:return"av1";case p.DASH_LIVE_CMAF:return"ondemand_dash_live";case p.HLS:case p.HLS_LIVE:return"hls";case p.HLS_ONDEMAND:return"ondemand_hls";case p.HLS_LIVE_CMAF:return"ondemand_hls_live";case p.WEB_RTC_LIVE:return"webrtc";default:return ue(n)}},R=n=>{if(n!==void 0)switch(n){case S.NONE:case S.INLINE:return;case S.FULLSCREEN:return"fullscreen";case S.SECOND_SCREEN:return"chromecast";case S.PIP:return"pip";case S.INVISIBLE:return"invisible";default:return ue(n)}},pe=n=>{switch(n){case"slow-2g":return"poor";case"2g":return"poor";case"3g":return"good";case"4g":return"excellent"}};var O=class{constructor(e){this.offset=void 0;this.offset=e}getOffset(){return this.offset??0}setOffset(e){this.offset=e}now(){return Date.now()+(this.offset??0)}date(e=new Date){return e.setTime(e.getTime()+(this.offset??0)),e}addServerTime(e,i){let t=Date.now(),o=e-t-i/2;if(Math.abs(o)<1e3){this.offset=0;return}this.offset===void 0?this.offset=Math.round(o):this.offset=Math.round(.2*o+(1-.2)*this.offset)}};var he=()=>Math.floor(Math.random()*4294967296).toString(36).padStart(7,"0"),fe=()=>Math.floor(Math.random()*18446744073709552e3).toString(36).padStart(13,"0");import{PlaybackState as ge}from"@vkontakte/videoplayer-core";import{filter as me,filterChanged as $e,fromEvent as Re,isNullable as be,map as Oe,merge as z,Observable as Ne,Subject as Q,Subscription as De,ValueSubject as Me}from"@vkontakte/videoplayer-shared";var ve=(n,e)=>new Ne(i=>{let t=new De,o=z(Re(window,"beforeunload"),n.events.willDestruct$),r=new Me(void 0),d;t.add(n.info.isLive$.pipe($e()).subscribe(v=>{d&&(d.unsubscribe(),r.next(void 0)),v?d=n.info.liveTime$.pipe(Oe(N=>N&&N/1e3)).subscribe(r):d=n.info.position$.subscribe(r),t.add(d)}));let{playing$:u,paused$:l}=n.events,c=n.events.willSeek$.pipe(me(()=>n.info.playbackState$.getValue()===ge.PLAYING)),h=n.events.seeked$.pipe(me(()=>n.info.playbackState$.getValue()===ge.PLAYING)),g=!1,s=new Q;t.add(c.subscribe(()=>{g||s.next(),g=!0})),t.add(h.subscribe(()=>g=!1));let a=new Q,f=new Q,P=z(u,h,a),C=z(l,s,o,n.events.looped$,f),A,Pe=()=>A=r.getValue(),Ae=()=>{let v=r.getValue();be(A)||A===v||be(v)||(i.next({from:A,to:v}),A=void 0)},Ee=()=>{f.next(),a.next()};if(t.add(P.subscribe(Pe)),t.add(C.subscribe(Ae)),e.forceInterval&&isFinite(e.forceInterval)){let v=0;t.add(P.subscribe(()=>v=window.setTimeout(Ee,e.forceInterval))),t.add(C.subscribe(()=>window.clearTimeout(v)))}return t});var qe="_one-stat_",Y=`${qe}uuid`,X=()=>{let n=new J;return{subscription:n,subscribe:(e,i)=>{e&&n.add(e.subscribe(i))}}},Z=class{constructor(e,i){this.subscription=new J;this.debugLogger=new He;this.oneStatDebugLog=this.debugLogger.createComponentLog("onestat");this.loopCounter=0;this.disabled=!1;this.vsid$=new G(void 0);this.isid$=new G(void 0);this.seekAction$=new G("unknown");this.statContext=e,this.config=re(i.config??{}),y(i.apiEnv)&&(this.config.apiEnv=i.apiEnv),this.config.synchronizeTime&&(this.timeSynchronisation=new O);let t=new We;this.experimental={error$:t};let o=j.get(Y);o?o.startsWith('"')&&o.endsWith('"')?(this.uuid=o.replaceAll('"',""),j.set(Y,this.uuid)):this.uuid=o:(this.uuid=V(),j.set(Y,this.uuid)),this.resetViewSession(),i.useIsid&&this.isid$.next(i.isid??fe());let r=new x({apiKey:ae,config:this.config,error$:t,timeSynchronisation:this.timeSynchronisation});this.api=new _({config:this.config,apiTransport:r,refreshAuthToken:i.refreshAuthToken,mobile:this.statContext.mobile??!1,uuid:this.uuid,error$:t}),this.logger=new $({config:this.config,debugLogger:this.debugLogger,api:this.api,error$:t,userSalt:i.userSalt});let{isEmbed:d,host:u}=Ke();this.isEmbed=d,this.embedParent=u,this.subscribe()}updateContext(e){this.statContext={...this.statContext,...e}}attachTo(e){let i=new J,t=(s,a)=>i.add(s.subscribe(a));t(e.events.willStart$,()=>{let s=e.info.position$.getValue();this.logActionPlay({position:s}),this.statContext.projectId&&this.logActionPlayInteractive()}),t(e.events.looped$,()=>{this.resetViewSession(),++this.loopCounter>this.config.maxLoops&&(this.disabled=!0),this.logActionPlay({position:e.info.position$.getValue()})}),t(e.events.seeked$,()=>{this.logSeek({action:this.seekAction$.getValue(),time:e.info.position$.getValue()}),this.seekAction$.next("unknown")}),t(e.events.paused$,()=>{this.logPause({position:e.info.position$.getValue()})}),t(e.events.willResume$,()=>{this.logPlay()}),t(e.events.started$,()=>{this.statContext.clip&&this.logWatchCoverageRecord({start:0,end:0})}),t(e.events.playing$,()=>{this.logPlaying()}),t(ve(e,{forceInterval:this.config.watchCoverageInterval}),s=>{let a=e.info.isLive$.getValue(),f={start:parseFloat(s.from.toFixed(3)),end:parseFloat(s.to.toFixed(3))};a?this.logWatchCoverageLive(f):this.logWatchCoverageRecord(f)});let o;t(e.info.isStalled$,s=>{s?o=b():(y(o)&&this.logEmptyBuffer({duration:b()-o}),o=void 0)});let r=!1;i.add(e.events.fatalError$.pipe(Ue()).subscribe(()=>r=!0)),t(e.events.willStop$,()=>{if(e.info.isStalled$.getValue()){let a=y(o)?b()-o:void 0;this.logCloseAtEmptyBuffer({duration:a??0}),o=void 0}else r||this.logActionStop()}),t(e.events.managedError$,({id:s})=>{this.logError({fatal:!1,errorType:s})}),t(e.events.fatalError$,({id:s})=>{this.logError({fatal:!0,errorType:s})});let d,u,l=!1;t(e.events.firstBytes$,s=>{d=b(),this.logFirstBytes({time:s})}),t(e.events.willStart$,()=>u=b()),t(e.info.currentBuffer$,s=>{!l&&s&&s.end-s.start>0&&y(d)&&(this.logPlayerReady({duration:b()-d}),l=!0)}),t(e.events.firstFrame$,()=>{y(d)&&!l&&(this.logPlayerReady({duration:b()-d}),l=!0),y(u)&&this.logFirstFrame({time:b()-u})});let c;t(e.info.currentVideoStream$,s=>{s&&(c&&s.id!==c&&this.logTrackSwitch(s),c=s.id)});let h;t(e.info.currentAudioStream$,s=>{s&&(h&&s.id!==h&&this.logTrackSwitch(s),h=s.id)}),t(e.info.atLiveEdge$,s=>this.updateContext({liveEdge:s})),t(Ie({muted:e.info.muted$,volume:e.info.volume$}),({muted:s,volume:a})=>this.updateContext({audible:!s&&a>0})),t(e.info.currentQuality$,s=>this.updateContext({quality:ce(s)})),t(e.info.isAutoQualityEnabled$,s=>this.updateContext({autoQuality:s})),t(e.info.currentFormat$,s=>this.updateContext({contentType:le(s)})),t(e.info.currentPlaybackRate$,s=>this.updateContext({rate:s})),t(e.info.is3DVideo$,s=>this.updateContext({is3d:s}));let g;return t(e.info.hostname$,s=>{let a=g!==void 0&&g!==s;this.updateContext({cdnHostname:s,failover:a}),a&&this.logFailover(s),g=s}),t(e.info.throughputEstimation$,s=>this.updateContext({downloadSpeed:s})),t(e.info.httpConnectionType$,s=>{this.statContext.firstConnectionType||this.updateContext({firstConnectionType:q(s)}),this.updateContext({connectionType:q(s)})}),t(e.info.httpConnectionReused$,s=>{ye(this.statContext.firstConnectionReused)&&this.updateContext({firstConnectionReused:s}),this.updateContext({connectionReused:s})}),t(e.info.surface$,s=>this.updateContext({mode:R(s)})),t(Ie({current:e.info.currentTextTrack$,available:e.info.availableTextTracks$}),({current:s,available:a})=>{let f=a.find(({id:C})=>C===s),P=f&&(f.isAuto?`${f.language}_auto`:f.language);this.updateContext({subtitles:P})}),this.player=e,this.uiEvents&&this.attachToUi(this.uiEvents),this.resubscribeBeforeunload(),this.subscription.add(i),i}attachToUi(e){this.uiEvents=e;let{subscription:i,subscribe:t}=X();return this.player&&(t(e.actionRewind$,()=>{this.player&&(this.resetViewSession(),this.logActionPlay({position:this.player.info.position$.getValue()}))}),t(e.actionSeek$,this.seekAction$),t(e.inPiP$,o=>{let r=o?"pip":R(this.player?.info.surface$.getValue());this.updateContext({mode:r})}),t(e.inFullscreen$,o=>{let r=o?"fullscreen":R(this.player?.info.surface$.getValue());this.updateContext({mode:r})}),t(e.actionSetSubtitle$,o=>this.updateContext({subtitles:o})),t(e.nextMovie$,o=>this.logNextMovie(o)),this.resubscribeBeforeunload(),this.subscription.add(i)),i}attachToAds(e){let{subscription:i,subscribe:t}=X();return t(e.slotRequested$,()=>this.logAdSlotRequest()),t(e.started$,o=>this.logAdStarted(o)),t(e.paused$,()=>this.logAdPaused()),t(e.resumed$,()=>this.logAdResumed()),t(e.ended$,()=>this.logAdEnded()),t(e.skipped$,()=>this.logAdSkipped()),t(e.clicked$,()=>this.logAdClicked()),this.resubscribeBeforeunload(),this.subscription.add(i),i}attachToInteractive(e){let{subscription:i,subscribe:t}=X();return t(e.click$,o=>this.logInterfaceClick(o)),t(e.nextMovie$,o=>this.logNextMovie(o)),this.resubscribeBeforeunload(),this.subscription.add(i),i}authorize(e){return this.api.authorize(e)}pause(){this.logger.pause(),this.oneStatDebugLog({message:"paused"})}resume(){this.logger.resume(),this.oneStatDebugLog({message:"resumed"})}destroy(){this.logger.flush(),this.subscription.unsubscribe(),this.api.destroy(),this.logger.destroy()}resetViewSession(){this.oneStatDebugLog({message:"VSID reset"}),this.vsid$.next(he())}getDeviceId(){return this.uuid}setFieldBlacklist(){}logInited(){}logReady(e){this.log({operation:"player_ready",param:String(e.time)})}logStarted(...e){this.logActionPlay(...e)}logPlay(){this.log({operation:"play_toggle"})}logPlaying(){this.log({operation:"playing"})}logPause(e){this.log({operation:"pause",param:String(Math.round(e.position))})}logSeek(e){this.log({operation:"seek",param:e.action,time:e.time})}logFirstBytes(e){this.log({operation:"first_bytes",param:String(e.time)})}logFirstFrame(e){this.log({operation:"first_frame",param:String(e.time)})}logError(e){this.log({operation:"content_error",param:`${e.fatal?"fatal":"recoverable"}_${e.errorType}`})}logWatchCoverageRecord(e){this.log({operation:"watch_coverage_record",param:`${e.start}-${e.end}`})}logWatchCoverageLive(e){let i=this.timeSynchronisation?.getOffset()??0,t=e.start+i,o=e.end+i;this.log({operation:"watch_coverage_live",param:`${t}-${o}`})}logEmptyBuffer(e){this.log({operation:"empty_buffer",param:String(e.duration)})}logDownloadSpeed(){}logAdSlotRequest(){this.log({operation:"adv",param:"slot_request"})}logAdStarted(e){this.log({operation:"adv",param:e})}logAdPaused(){this.log({operation:"adv",param:"pause"})}logAdResumed(){this.log({operation:"adv",param:"resume"})}logAdEnded(){this.log({operation:"adv",param:"ended"})}logAdSkipped(){this.log({operation:"adv",param:"skip"})}logAdClicked(){this.log({operation:"adv",param:"click"})}logInterfaceClick(e){this.log({operation:"player_interface_click",param:e})}logNextMovie(e){this.log({operation:"next_movie",param:String(e)})}subscribe(){this.resubscribeBeforeunload();let e=window.navigator.connection;e&&"onchange"in e&&"effectiveType"in e&&this.subscription.add(Fe(Se(e,"change"),Ve(["init"])).subscribe(()=>this.updateContext({network:pe(e.effectiveType)}))),this.config.debugLog&&this.debugLogger.log$.subscribe(i=>{console.debug("%c stat ","background:#fa6470;",`component: ${i.component}.`,i.message)})}resubscribeBeforeunload(){this.beforeunloadSubscription?.unsubscribe(),this.beforeunloadSubscription=Se(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))})}logActionPlayInteractive(){this.statContext.projectId&&this.log({operation:"action_play_interactive",param:String(this.statContext.movieId)},{vid:this.statContext.projectId})}logFailover(e){this.log({operation:"failover",param:e})}logCloseAtEmptyBuffer(e){this.log({operation:"close_at_empty_buffer",param:String(Math.round(e.duration))})}logActionStop(){this.log({operation:"action_stop"})}logTrackSwitch(e){this.log({operation:"track_switch",param:e.id})}log(e,i={}){if(this.disabled){this.oneStatDebugLog({message:`operation ${e.operation} but statistics is disabled`});return}if(this.config.disabledOperations.includes(e.operation)){this.oneStatDebugLog({message:`operation ${e.operation} but it is disabled`});return}this.oneStatDebugLog({message:`operation ${e.operation} ${e.param}`});let t=this.createLogItem(e,i);this.logger.log(t)}createLogItem({operation:e,param:i,time:t},o={}){let r=this.timeSynchronisation?.now()??b(),d=this.vsid$.getValue();Be(d);let u=this.isid$.getValue(),l=e==="empty_buffer"||e==="close_at_empty_buffer"?this.statContext.connectionType:this.statContext.firstConnectionType,c=this.statContext.firstConnectionReused,h,g;if(this.isEmbed){h=this.embedParent;let a=[...new URLSearchParams(location.search).entries()].filter(([f,P])=>this.config.embedUrlParams.includes(f));g=new URLSearchParams(a).toString()}else this.statContext.place==="direct"&&((this.statContext.refDomain||document.referrer)&&(h=new URL(this.statContext.refDomain||document.referrer).hostname),g=location.href.substring(0,1024));let s={vsid:d,isid:u,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?"auto":this.statContext.autoplay===!1?"":void 0,param:i,vk_app_id:this.statContext.vkAppId,track_code:this.statContext.trackCode,connection_type:l,connection_reused:c===!0?1:c===!1?0:void 0,cached_data:this.statContext.cached===!0?1:this.statContext.cached===!1?0:void 0,live:this.statContext.liveEdge?1:void 0,muted:this.statContext.audible===!1?1:void 0,mode:this.statContext.mode,subtitles:this.statContext.subtitles,download_speed:this.statContext.downloadSpeed,manual_quality:this.statContext.autoQuality?void 0:1,ref_domain:h,direct_url:g,rate:this.statContext.rate===1||ye(this.statContext.rate)?void 0:this.statContext.rate.toFixed(2),view_360:this.statContext.is3d?1:void 0,aid:this.statContext.albumId,vk_playlist_id:this.statContext.vkPlaylistId,...o};for(let a of this.config.disabledCustomFields)delete s[a];return{operation:e,type:1,time:t,network:this.statContext.network,timestamp:r,custom:s}}};export{E as ApiEnv,B as ConnectionType,M as ContentType,ee as InteractiveInterfaceClick,Z as OneStat,D as Quality,F as SeekAction,w as VERSION};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vkontakte/videoplayer-statistics",
3
- "version": "1.0.52-dev.22c05d5f.0",
3
+ "version": "1.0.52-dev.a5f6699f.0",
4
4
  "author": "vk.com",
5
5
  "description": "Statistics library for vk.com videoplayer",
6
6
  "homepage": "https://vk.com",
@@ -52,6 +52,6 @@
52
52
  "@vkontakte/videoplayer-shared": "^1.0.37"
53
53
  },
54
54
  "peerDependencies": {
55
- "@vkontakte/videoplayer-core": "2.0.106-dev.396a8bfb.0"
55
+ "@vkontakte/videoplayer-core": "2.0.106-dev.a3723727.0"
56
56
  }
57
57
  }