@vkontakte/videoplayer-interactive 1.0.6-beta.1 → 1.0.6-dev.35f8adc.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 +6 -6
- package/es2015.esm.js +6 -6
- package/es2018.cjs.js +6 -6
- package/es2018.esm.js +6 -6
- package/es5.umd.js +31792 -0
- package/esnext.cjs.js +6 -6
- package/esnext.esm.js +6 -6
- package/evergreen.esm.js +6 -6
- package/index.d.ts +4 -6
- package/package.json +7 -5
package/esnext.cjs.js
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @vkontakte/videoplayer-interactive v1.0.6-
|
|
3
|
-
*
|
|
2
|
+
* @vkontakte/videoplayer-interactive v1.0.6-dev.35f8adc.0
|
|
3
|
+
* Tue, 09 Jan 2024 10:19:32 GMT
|
|
4
4
|
* https://st.mycdn.me/static/vkontakte-videoplayer/1-0-6/doc/
|
|
5
5
|
*/
|
|
6
|
-
"use strict";var ct=Object.create;var ge=Object.defineProperty;var lt=Object.getOwnPropertyDescriptor;var ht=Object.getOwnPropertyNames;var dt=Object.getPrototypeOf,ut=Object.prototype.hasOwnProperty;var ft=(i,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of ht(e))!ut.call(i,s)&&s!==t&&ge(i,s,{get:()=>e[s],enumerable:!(n=lt(e,s))||n.enumerable});return i};var pt=(i,e,t)=>(t=i!=null?ct(dt(i)):{},ft(e||!i||!i.__esModule?ge(t,"default",{value:i,enumerable:!0}):t,i));var j=require("@vkontakte/videoplayer-shared/esnext.cjs.js"),ce=require("uuid"),mt=require("@vkontakte/videoplayer-core/esnext.cjs.js");const yt="1.0.6-beta.1";function Be(i,e=1){let t="0",n="0",s="0";return i.length===4?(t="0x"+i[1]+i[1],n="0x"+i[2]+i[2],s="0x"+i[3]+i[3]):i.length===7&&(t="0x"+i[1]+i[2],n="0x"+i[3]+i[4],s="0x"+i[5]+i[6]),`rgba(${+t},${+n},${+s},${e})`}const _="SDK_NAME",gt="SDK_NAME-controls-container",$e=()=>document.querySelector(`.${gt}`),M={textColor:"#000",textSize:.4,textContent:"",roundCorners:0,borderWidth:0,borderColor:"#000",borderAlpha:1,backgroundColor:"#fff",backgroundAlpha:1,innerSizesDependOn:"self",angle:0},ve={top:"flex-start",bottom:"flex-end",center:"center"},be={start:"flex-start",end:"flex-end",center:"center"},Ce={start:"left",end:"right",center:"center"},De=({target:i,props:e})=>{i.style.alignItems=ve[e?.text?.gravityVertical]??ve.center,i.style.justifyContent=be[e?.text?.gravityHorizontal]??be.center,i.style.textAlign=Ce[e?.text?.alignment]??Ce.start},He=({target:i,props:e,fallback:t,dependsOn:n})=>{i.style.color=e?.text?.color??t.textColor,i.style.fontSize=`calc(${n.height} * ${e?.text?.size??t.textSize})`,i.textContent=e?.text?.value??t.textContent},Ge=({target:i,props:e,fallback:t})=>{i.style.backgroundColor=Be(e?.background?.color??t.backgroundColor,e?.background?.alpha??t.backgroundAlpha)},Ue=({target:i,props:e,fallback:t,dependsOn:n})=>{i.style.border=`calc(${n.height} * ${e?.shape?.border?.width??t.borderWidth}) solid ${Be(e?.shape?.border?.color??t.borderColor,e?.shape?.border?.alpha??t.borderAlpha)}`,i.style.borderRadius=`calc(${n.height} * ${e?.shape?.roundCorners??t.roundCorners})`},le=({target:i,layoutParams:e,fallback:t})=>{i.style.transform=`rotate(${-e.angle}rad)`};class he{constructor(e){this.control=e}createView(e){const t=document.createElement("div");t.classList.add(`${_}-control-container-${this.control.id}`),e(t,this.control.layoutParams);const n=(this.control.layoutParams.innerSizesDependOn??M.innerSizesDependOn)==="self"?{height:t.style.height,width:t.style.width}:{height:"var(--interactive-content-height)",width:"var(--interactive-content-width)"};return{controlContainerEl:t,dependsOn:n}}setEvents(e,t){e&&this.control.events.forEach(n=>{switch(n.type.trim().toLowerCase()){case"onclick":e.addEventListener("click",r=>{r.stopPropagation(),t&&t({action:n.action,controlId:this.control.id,controlType:this.control.type})});break}})}getElement(){return document.querySelector(`.${_}-control-container-${this.control.id}`)}}const ze=i=>{if(i.type.trim().toLowerCase()==="area")return new vt(i)};class vt extends he{constructor(e){super(e)}createView({parent:e,layoutFn:t}){const{dependsOn:n,controlContainerEl:s}=super.createView(t),r=document.createElement("button");return r.classList.add(`${_}-${this.control.id}`),r.style.display="flex",r.style.width="100%",r.style.height="100%",r.style.cursor="pointer",r.type="button",Ge({target:r,props:this.control.props,fallback:{...M,backgroundColor:"transparent"}}),Ue({target:r,props:this.control.props,fallback:{...M,borderAlpha:0},dependsOn:n}),le({target:r,layoutParams:this.control.layoutParams,fallback:M}),s.append(r),e.append(s),s}getElement(){return document.querySelector(`.${_}-${this.control.id}`)}}const We=i=>{if(i.type.trim().toLowerCase()==="button")return new bt(i)};class bt extends he{constructor(e){super(e)}createView({parent:e,layoutFn:t}){const{dependsOn:n,controlContainerEl:s}=super.createView(t),r=document.createElement("button");r.type="button",r.classList.add(`${_}-${this.control.id}`),r.style.display="flex",r.style.width="100%",r.style.height="100%",r.style.cursor="pointer",r.style.fontFamily="inherit";const o=document.createElement("span");return o.style.display="inline-block",o.style.whiteSpace="pre",o.style.overflow="hidden",o.style.textOverflow="ellipsis",le({target:r,layoutParams:this.control.layoutParams,fallback:M}),Ge({target:r,props:this.control.props,fallback:M}),Ue({target:r,props:this.control.props,fallback:M,dependsOn:n}),De({target:r,props:this.control.props}),He({target:o,props:this.control.props,fallback:M,dependsOn:n}),r.append(o),s.append(r),e.append(s),s}getElement(){return document.querySelector(`.${_}-${this.control.id}`)}}const Ct=i=>{if(i.type.trim().toLowerCase()==="text")return new Et(i)};class Et extends he{constructor(e){super(e)}createView({parent:e,layoutFn:t}){const{dependsOn:n,controlContainerEl:s}=super.createView(t),r=document.createElement("div");r.classList.add(`${_}-${this.control.id}`),r.style.display="flex",r.style.width="100%",r.style.height="100%",r.style.fontFamily="inherit";const o=document.createElement("span");return o.style.whiteSpace="pre",le({target:r,layoutParams:this.control.layoutParams,fallback:M}),De({target:r,props:this.control.props}),He({target:o,props:this.control.props,fallback:M,dependsOn:n}),r.append(o),s.append(r),e.append(s),s}getElement(){return document.querySelector(`.${_}-${this.control.id}`)}}class wt{constructor(e){this.layout=e}}const It=i=>{if(i.type.trim().toLowerCase()==="relative")return new qe(i)};class qe extends wt{constructor(e){super(e)}setContainerLayout(e){e.style.position="relative"}setControlLayout(e,t){e.style.position="absolute",e.style.width=`calc(var(--interactive-content-width) * ${t.width})`,e.style.height=`calc(var(--interactive-content-height) * ${t.height})`,e.style.left=`calc(var(--interactive-content-width) * ${t.x} + ((var(--interactive-width) - var(--interactive-content-width)) / 2))`,e.style.top=`calc(var(--interactive-content-height) * ${t.y} + ((var(--interactive-height) - var(--interactive-content-height)) / 2))`}}class Qe{constructor(e){this.container=e,this.factories=new Map,this.#a()}addControlFactory(e,t){this.factories.set(e.trim().toLowerCase(),t),this.#a()}removeControlFactory(e){this.factories.delete(e.trim().toLowerCase()),this.#a()}#a(){this.controls=this.#s()}#s(){return this.container.controls?.reduce((e,t)=>{const n=t.type.trim().toLowerCase(),s=this.factories.get(n);return s?[...e,s(t)]:[...e]},[])}}const Ke=(i,e)=>{if(i.type.trim().toLowerCase()==="choice")return new St(i,e)};class St extends Qe{constructor(e,t){super(e),this.rootElement=t??$e(),this.layout=new qe(this.container.layout),this.isRemoved=!1,this.addControlFactory("button",We),this.addControlFactory("text",Ct),this.addControlFactory("area",ze)}createView(e){const t=document.createElement("div");return t.classList.add(`${_}-${this.container.id}`),this.layout.setContainerLayout(t),this.controls.forEach(n=>{const s=n.createView({parent:t,layoutFn:this.layout.setControlLayout});n.setEvents(s,e)}),this.rootElement.append(t),this.isRemoved=!1,t}hide(){const e=this.getElement();e&&(e.style.visibility="hidden")}show(){const e=this.getElement();e&&(e.style.visibility="visible")}removeView(){this.isRemoved||(this.getElement()?.remove(),this.isRemoved=!0)}getElement(){return this.rootElement.querySelector(`.${_}-${this.container.id}`)}}function Xe(i,e){let t;return(...n)=>{clearTimeout(t),t=setTimeout(()=>i(...n),e)}}const q={Object:"Object",String:"String",Array:"Array",Number:"Number",Function:"Function",Boolean:"Boolean"},U=(i,e)=>Object.prototype.toString.call(i)===`[object ${e}]`,de=i=>U(i,q.Object),re=i=>U(i,q.String),G=i=>U(i,q.Array),Ze=i=>U(i,q.Number),Tt=i=>U(i,q.Function),Ee=i=>Ze(i)&&!isNaN(i),Rt=i=>i==null,z=i=>de(i)&&Object.keys(i).length===0,Ye=i=>G(i)&&!i.length,X=(i,e)=>re(i)&&(e?i.trim():i).length,Je=window.navigator.userAgent.toLowerCase(),At=/mobi/i.test(Je);Je.indexOf("android")>-1;const xt="video_interactive",Ot="videoint",Lt=250;class Nt{constructor(e){this.init(e)}init({root:e,onOpenPreviewClick:t,onError:n,lang:s,visitedChapters:r=[]}){this.isHidden=!0,this.currentManifestId=void 0,this.currentChapterId=void 0,this.visitedChapterIds=new Set(r),this.onOpenPreviewClick=t,this.onError=n,this.lang=s??"ru",this.zoom=.7,this.isReady=!1,this.lastZoomInfo=void 0,this.ngEditorSize=void 0,this.ngEditor=void 0,this.graphWrapperElement=_t(e),this.resizeObserver=new ResizeObserver(Xe(this.onResize,Lt)),this.resizeObserver.observe(this.graphWrapperElement)}onResize=e=>{this.isReady&&(!e[0].contentRect.width||!e[0].contentRect.height||(this.lastZoomInfo&&this.ngEditor.zoomTo(this.getNextPoint()),this.ngEditorSize={width:e[0].contentRect.width,height:e[0].contentRect.height}))};getNextPoint(e=this.ngEditorSize){return[(this.lastZoomInfo.x-e.width/2)/this.lastZoomInfo.value*-1,(this.lastZoomInfo.y-e.height/2)/this.lastZoomInfo.value*-1]}handleChapterChange=e=>{if(this.isReady){if(this.isHidden||this.hide(),!e?.id){this.onError?.("Id is not found"),console.error("Id is not found");return}this.visitedChapterIds.add(e.id),this.ngEditor.selectChapter(e.id),this.ngEditor.setVisitedChapters(Array.from(this.visitedChapterIds)),this.currentChapterId=e.id,this.lastZoomInfo=void 0}};handleManifestChange=async(e,t=[])=>{if(!Ze(e.graph.edit.chapters[0].x)){this.isReady=!1,this.onError?.("Can't show graph"),console.error("Can't show graph");return}if(this.lastZoomInfo=void 0,!this.ngEditor){let n;try{n=await j.loadVKLangPack(this.lang,xt,Ot)}catch{console.log("Unable to load graph language pack")}const{GraphEditor:s}=await import("@interactiveplatform/movika-graph-editor");this.ngEditor=new s(this.graphWrapperElement,{mode:"read",lang:this.lang,translation:n}),this.ngEditor.on("control",({name:r,chapterId:o})=>{r==="openPreview"&&this.onOpenPreviewClick(o)}),this.ngEditor.on("zoomEnd",r=>{this.lastZoomInfo={...r}})}this.visitedChapterIds=new Set(t),e.metadata.id!==this.currentManifestId?(this.ngEditor.update(e),this.currentManifestId=e.metadata.id):this.ngEditor.setVisitedChapters(Array.from(this.visitedChapterIds)),this.isReady=!0};setVisitedChapters(e){this.visitedChapterIds=new Set([...this.visitedChapterIds,...e]),this.ngEditor.setVisitedChapters(Array.from(this.visitedChapterIds))}updateVideosInfo(e){this.ngEditor.updateVideosInfo(e)}show(){!this.ngEditor||!this.isReady||(this.graphWrapperElement.style.display="block",this.lastZoomInfo||this.ngEditor.focusChapter(this.currentChapterId),this.isHidden=!1)}hide(){this.graphWrapperElement.style.display="none",this.isHidden=!0}destroy(){this.hide(),this.resizeObserver.disconnect(),this.ngEditor?.setVisitedChapters([]),this.onOpenPreviewClick=void 0,this.ngEditor?.dispose(),this.graphWrapperElement.remove(),this.isReady=!1}}function _t(i){const e=document.createElement("div");return e.style.position="absolute",e.style.top="0",e.style.left="0",e.style.height="100%",e.style.width="100%",e.style.display="none",i.append(e),e}const jt=(i={})=>Array.from(new Set(i.sessions?.map(e=>e.visitedChapters.map(t=>t.chapterId)??[]).flat())),we=(i=[],e="")=>i.reduce((t,n)=>(t.find(s=>s[e]===n[e])||t.push(n),t),[]),Ie="chapterId";class ${constructor(e){this.id=e?.id??ce.v4(),this.startDate=e?.startDate?new Date(e.startDate).toISOString():new Date(Date.now()).toISOString(),this.updateOn=e?.updateOn?new Date(e.updateOn).toISOString():null,this.visitedChapters=e?.visitedChapters?we(Array.from(e.visitedChapters),Ie):[],this.branches=G(e?.branches)?e.branches:[]}update(e){e?.startDate&&(this.startDate=new Date(e.startDate).toISOString()),e?.updateOn&&(this.updateOn=new Date(e.updateOn).toISOString()),G(e?.visitedChapters)&&(this.visitedChapters=we([...this.visitedChapters,...e.visitedChapters],Ie)),G(e?.branches)&&(this.branches=this.branches.concat(e.branches))}getSession(){return{...this}}static createVisitedChapter(e){return[{chapterId:e}]}static createBranch(e,t,n){return[{chapterId:e,branchId:t,autoSelect:n}]}}class Z{constructor(e){this.id=e?.id??ce.v4(),this.manifestId=e?.manifestId,this.manifestVersion=e?.manifestVersion,this.manifestBuild=e?.manifestBuild,this.sessions=G(e?.sessions)?e?.sessions.map(t=>new $(t)):[],this.isCompleted=e?.isCompleted??!1}update(e){this.id=e?.id??this.id,this.manifestId=e?.manifestId??this.manifestId,this.manifestVersion=e?.manifestVersion??this.manifestVersion,this.manifestBuild=e?.manifestBuild??this.manifestBuild,this.isCompleted=e?.isCompleted??this.isCompleted}addSession(e){this.sessions.push(new $(e))}updateSession(e,t){let n;Rt(e)?n=this.sessions[this.sessions.length-1]:n=this.sessions.find(s=>s.id===e),n&&n.update(t)}resetSession(){this.sessions=[]}getHistory(){return{...this,sessions:this.sessions.map(e=>e.getSession())}}}const ae="SDK_NAME-history-changed";class Mt extends EventTarget{constructor(){super(),this.history=new Z,this.sendEvent()}onChapterChange({chapterId:e,mediaId:t,autoSelect:n=!1,isLastChapter:s=!1}){this.history.isCompleted?this.history=new Z({manifestId:this.history.manifestId,manifestVersion:this.history.manifestVersion,manifestBuild:this.history.manifestBuild}):s&&this.history.update({isCompleted:!0}),this.history.sessions.length?this.history.updateSession(null,{updateOn:Date.now(),visitedChapters:$.createVisitedChapter(e),branches:$.createBranch(e,t,n)}):this.history.addSession({updateOn:Date.now(),visitedChapters:$.createVisitedChapter(e),branches:$.createBranch(e,t,!1)}),this.sendEvent()}onManifestChange(e,t){t?this.history=new Z(t):this.history=new Z({manifestId:e.id,manifestVersion:e.version,manifestBuild:e.build}),this.history.addSession({updateOn:Date.now()}),this.sendEvent()}getHistory(){if(history)return this.history.getHistory()}sendEvent(){this.dispatchEvent(new CustomEvent(ae,{bubbles:!1,detail:this.getHistory()}))}destroy(){this.history=void 0}}function Vt(i,e){if(!e||!i||!e.sessions.length)return;const t=e.sessions.reverse().find(n=>n.branches.length);return t.branches[t.branches.length-1].chapterId??void 0}const W=(i="",e="")=>{i=i.split("."),e=e.split(".");let t=0;for(let n=0;n<Math.max(i.length,e.length)&&!t;n++)i[n]>e[n]?t=1:i[n]<e[n]?t=-1:t=0;return t},Pt="3.1",Se={default:"setNextBranch",random:"setRandomBranch",weightlessRandom:"setWeightlessRandomBranch",max:"setMaxWeightBranch",min:"setMinWeightBranch"},kt={type:"onSuspense",action:{type:"continuePlayback",args:{shouldOpenNow:!0,isDetachContainer:!0}}},Ft=i=>{const e=[];for(const t of i.chapters){let n;const s=[];for(const{isDefault:a,...c}of t.branches)a&&(n=c.id),s.push(c);let r=[];const o=[];for(const{fallbackStrategy:a,...c}of t.containers){const l=!!c.endTime;let p=[kt];switch(a){case"await":l?p=[]:r=[];break;case"default":{const u={type:"onSuspense",action:{type:Se.default,args:{branchId:n,shouldOpenNow:!l,isDetachContainer:!0}}};l?p=[u]:r=[u];break}case"random":case"weightlessRandom":case"max":case"min":{const u={type:"onSuspense",action:{type:Se[a],args:{}}};l?p=[u]:r=[u];break}}for(const u of c.controls)o.push({...c,controls:[{...u}],id:ce.v4(),events:p})}e.push({...t,containers:o,events:r,branches:s})}return i.metadata.version=Pt,i.metadata.updated=new Date().toISOString(),{...i,chapters:e}},Bt="3.2",$t=i=>{if(!i.media){const{media:e,...t}=i.metadata;return{...i,metadata:{...t,version:Bt},media:e}}return i},Dt="3.3",Ht=(i=[])=>({edit:{chapters:i},view:{}}),Te={type:"onSuspense",action:{type:"expect",args:{shouldOpenNow:!0,isDetachContainer:!0}}},Gt=i=>{const e=[],t=[];for(const n of i.chapters){const{id:s,x:r,y:o,...a}=n,c=a.containers.map(l=>({...l,controls:l.controls.map(({subtype:p,type:u,...b})=>({...b,type:p??u})),events:l.events?.length?l.events:[Te]}));e.push({id:s,...a,containers:c,events:a.events?.length?a.events:[Te]}),t.push({id:s,x:r,y:o})}return{...i,chapters:e,graph:Ht(t),metadata:{...i.metadata,version:Dt}}},Ut=[{version:"3.0",migrate:Ft},{version:"3.1",migrate:$t},{version:"3.2",migrate:Gt}],zt=i=>Ut.reduce((e,t)=>W(e.metadata.version,t.version)?e:t.migrate(e),i),Wt=Object.freeze({Button:"Button",Area:"Area",Text:"Text"}),I=Object.freeze({openURI:"openURI",setNextBranch:"setNextBranch",setWeightlessRandomBranch:"setWeightlessRandomBranch",setRandomBranch:"setRandomBranch",setMaxWeightBranch:"setMaxWeightBranch",setMinWeightBranch:"setMinWeightBranch",setDefaultBranch:"setDefaultBranch",continuePlayback:"continuePlayback",expect:"expect"});exports.INTERACTIVE_CLICK_ACTIONS=void 0;(function(i){i.GO_NEXT_BUTTON="GO_NEXT_BUTTON",i.GO_NEXT_AREA="GO_NEXT_AREA",i.WATCH_AGAIN="WATCH_AGAIN",i.OPEN_GRAPH="OPEN_GRAPH",i.CLOSE_GRAPH="CLOSE_GRAPH"})(exports.INTERACTIVE_CLICK_ACTIONS||(exports.INTERACTIVE_CLICK_ACTIONS={}));const Re={metadata:"Object",chapters:"Array"},qt="3.0.0",Qt="3.3.0",ue=i=>{const e=W(i,qt);return e===-1?!1:e===0?!0:W(i,Qt)!==1},Kt=i=>{if(!de(i))return!1;for(const e in Re)if(!i[e]||!U(i[e],Re[e]))return!1;return ue(i.metadata.version)},et=i=>i.type===Wt.Text;class A{constructor(e,t,...n){this.severity=e,this.category=t,this.data=n}toString(){return`SDK_NAME ERROR ${JSON.stringify(this,null," ")}`}static Severity={RECOVERABLE:1,CRITICAL:2};static Category={VIDEO:0,INTERACTIVES:1,GRAPH:2,MANIFEST:3,LOADERS:4,HISTORY:5,SEAMLESS:6}}class tt{listeners={};addListener(e,t){return this.listeners[e]=this.listeners[e]||[],this.listeners[e].push(t),this}on(e,t){return this.addListener(e,t)}once(e,t){this.listeners[e]=this.listeners[e]||[];const n=()=>{t(),this.off(e,n)};return this.listeners[e].push(n),this}off(e,t){return this.removeListener(e,t)}reset(){this.listeners={}}removeListener(e,t){const n=this.listeners[e];if(!n)return this;for(let s=n.length;s>0;s--)if(n[s]===t){n.splice(s,1);break}return this}emit(e,...t){const n=this.listeners[e];return n?(n.forEach(s=>{s(...t)}),!0):!1}listenerCount(e){return(this.listeners[e]||[]).length}rawListeners(e){return this.listeners[e]}}class Xt{constructor(e){this.raf,this.fn,this.fns=[],this.addFn(e)}addFn=(e,t=!1)=>{Tt(e)&&(this.fns.push(e),t&&this.updateFn())};removeFn=(e,t=!1)=>{this.fns=this.fns.filter(n=>n!==e),t&&this.updateFn()};updateFn=()=>{this.fn=()=>{this.fns.forEach(e=>e()),this.raf&&this.forceRequestAnimation()}};forceRequestAnimation=()=>{this.fn&&(this.raf=requestAnimationFrame(this.fn))};requestAnimation=()=>{this.raf||this.forceRequestAnimation()};cancelAnimation=()=>{cancelAnimationFrame(this.raf),this.raf=void 0};release(){this.cancelAnimation(),this.fn=void 0,this.fns=[]}}class Zt{loaders;constructor(e){this.loaders={chapterLoaders:e?.chapterLoaders??[],manifestLoaders:e?.manifestLoaders??[]}}async exec(e,t){return Yt(...this.loaders[e])(t)}}function Yt(...i){return async function(t){const n=[...i];for(;n.length>0;)t=await n.shift()(t);return t}}function te(i,e,t){return i?{...i,[e]:i[e]?[t,...i[e]]:[t]}:{[e]:[t]}}function oe({actions:i,errors:e,chapterId:t,...n}){if(t){const s=i.getManifest(),r=i.getChapter(s.chapters,t);if(r){const o=i.getMedia(s.media,r.videoId),a=i.getGraph(s.graph,r.id);return o?{...n,actions:i,errors:e,result:{chapter:r,media:o,graph:a}}:{...n,errors:te(e,oe.name,"Could not find media"),actions:i}}}return{...n,errors:te(e,oe.name,"Could not find chapter"),actions:i}}class Ae{constructor(){Object.defineProperty(this,"listeners",{value:{},writable:!0,configurable:!0})}addEventListener(e,t,n){e in this.listeners||(this.listeners[e]=[]),this.listeners[e].push({callback:t,options:n})}removeEventListener(e,t){if(!(e in this.listeners))return;const n=this.listeners[e];for(let s=0,r=n.length;s<r;s++)if(n[s].callback===t){n.splice(s,1);return}}dispatchEvent(e){if(!(e.type in this.listeners))return;const n=this.listeners[e.type].slice();for(let s=0,r=n.length;s<r;s++){const o=n[s];try{o.callback.call(this,e)}catch(a){Promise.resolve().then(()=>{throw a})}o.options&&o.options.once&&this.removeEventListener(e.type,o.callback)}return!e.defaultPrevented}}class it extends Ae{constructor(){super(),this.listeners||Ae.call(this),Object.defineProperty(this,"aborted",{value:!1,writable:!0,configurable:!0}),Object.defineProperty(this,"onabort",{value:null,writable:!0,configurable:!0}),Object.defineProperty(this,"reason",{value:void 0,writable:!0,configurable:!0})}toString(){return"[object AbortSignal]"}dispatchEvent(e){e.type==="abort"&&(this.aborted=!0,typeof this.onabort=="function"&&this.onabort.call(this,e)),super.dispatchEvent(e)}}class Jt{constructor(){Object.defineProperty(this,"signal",{value:new it,writable:!0,configurable:!0})}abort(e){let t;try{t=new Event("abort")}catch{typeof document<"u"?document.createEvent?(t=document.createEvent("Event"),t.initEvent("abort",!1,!1)):(t=document.createEventObject(),t.type="abort"):t={type:"abort",bubbles:!1,cancelable:!1}}let n=e;if(n===void 0)if(typeof document>"u")n=new Error("This operation was aborted"),n.name="AbortError";else try{n=new DOMException("signal is aborted without reason")}catch{n=new Error("This operation was aborted"),n.name="AbortError"}this.signal.reason=n,this.signal.dispatchEvent(t)}toString(){return"[object AbortController]"}}typeof Symbol<"u"&&Symbol.toStringTag&&(Jt.prototype[Symbol.toStringTag]="AbortController",it.prototype[Symbol.toStringTag]="AbortSignal");function nt(i){return i.__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL?(console.log("__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL=true is set, will force install polyfill"),!0):typeof i.Request=="function"&&!i.Request.prototype.hasOwnProperty("signal")||!i.AbortController}function ei(i){typeof i=="function"&&(i={fetch:i});const{fetch:e,Request:t=e.Request,AbortController:n,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:s=!1}=i;if(!nt({fetch:e,Request:t,AbortController:n,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:s}))return{fetch:e,Request:r};let r=t;(r&&!r.prototype.hasOwnProperty("signal")||s)&&(r=function(l,p){let u;p&&p.signal&&(u=p.signal,delete p.signal);const b=new t(l,p);return u&&Object.defineProperty(b,"signal",{writable:!1,enumerable:!1,configurable:!0,value:u}),b},r.prototype=t.prototype);const o=e;return{fetch:(c,l)=>{const p=r&&r.prototype.isPrototypeOf(c)?c.signal:l?l.signal:void 0;if(p){let u;try{u=new DOMException("Aborted","AbortError")}catch{u=new Error("Aborted"),u.name="AbortError"}if(p.aborted)return Promise.reject(u);const b=new Promise((C,x)=>{p.addEventListener("abort",()=>x(u),{once:!0})});return l&&l.signal&&delete l.signal,Promise.race([b,o(c,l)])}return o(c,l)},Request:r}}const fe=nt({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),st=fe?ei({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,xe=fe?st.fetch:window.fetch;fe?st.Request:window.Request;const ti=async i=>{try{let e,t;if(de(i))e=i;else if(re(i)){t=new URL(i).href;const s=await xe(t);if(!s.ok)return{};e=await s.json()}else return{};if(!Kt(e))return{};const n=e.metadata.media;if(re(n)&&!e.media)try{let s;t?s=new URL(n,t).href:(s=new URL(n).href,t=s);const r=await xe(s);if(!r.ok)throw new Error;e.metadata.media=await r.json()}catch{return ri(e.metadata.version)?{manifest:e}:{}}return{manifest:e,manifestURL:t}}catch{return{}}};async function ii(i){const{manifest:e,manifestURL:t}=await ti(i),n=zt(e);return n.media=ni(n.media,t),delete n.metadata.media,n}function ne(i,e){return i.find(t=>t.id===e)}function Oe(i,e){return i.edit?.chapters?i.edit.chapters.find(t=>t.id===e):i.view?.chapters?i.view.chapters.find(t=>t.id===e):void 0}function Le(i,e){return i.videos.find(t=>t.id===e)}function ni(i,e){return{...i,videos:i.videos.map(t=>({...t,variants:t.variants.map(n=>{const s=si(n.url,e);return{...n,url:s||n.url}})}))}}function si(i,e){try{return new URL(i,e).href}catch{return""}}function ri(i){return W(i,"3.2.0")>=0}class rt extends Zt{constructor(e,t){super(e),this.onError=t,this.release()}release(){return this.manifest=null,this.chapter=null,this.media=null,this.graph=null,this}async setManifest(e){this.release();const t=await this.exec("manifestLoaders",{actions:{addErrorMessage:te},result:null,errors:null,source:e});t.errors&&this.errorHandler(t.errors);const n=await ii(t.result??e);return this.manifest=n,this}async setInitial(){return this.setNext()}async setNext(e=this.manifest.metadata.initChapterId){const t=await this.exec("chapterLoaders",oe({actions:{getManifest:()=>this.manifest,getCurrent:this.getCurrent,getGraph:Oe,getChapter:ne,getMedia:Le,getByBranches:this.getByBranches.bind(this),addErrorMessage:te},result:null,errors:null,chapterId:e}));return t.errors&&this.errorHandler(t.errors),this.chapter=t.result.chapter,this.media=t.result.media,this.graph=t.result.graph,this}errorHandler(e){this.onError(e),console.error("Something went wrong with loaders",{errors:e})}getInitial(){return this.getByChapterId(this.manifest.metadata.initChapterId)||null}getByChapterId(e=this.manifest.metadata.initChapterId){const t=ne(this.manifest.chapters,e);if(t){const n=Le(this.manifest.media,t.videoId),s=Oe(this.manifest.graph,t.id);if(n)return{chapter:t,media:n,graph:s}}return null}getBranches(e=this.chapter.id){if(e===this.chapter.id)return this.getByBranches(this.chapter.branches);{const t=ne(this.manifest.chapters,e);return this.getByBranches(t?.branches)}}getByBranches(e=[]){return e.reduce((t,n)=>{const s=this.getByChapterId(n.chapterId);return s&&t.push(s),t},[])}getCurrent(){return{chapter:this.chapter,media:this.media,graph:this.graph}}}const y={graph:"graph",interactives:"interactives",chapterChanged:"chapter-changed",playerChanged:"player-changed",manifestChanged:"manifest-changed",errors:"errors",eachTick:"eachTick",historyChanged:"history-changed"},Ne={visibility:"visibility",watchAgainClicked:"watchAgainClicked"},R={actionChoice:"action-choice",actionExecution:"action-execution",visibility:"visibility",containerRemoved:"container-removed",rangeEnded:"range-ended"};function ai(){const i=new Map;function e({listId:s=Math.random().toString(),itemId:r=Math.random().toString(),...o}){const a=i.get(s),c={...o};return a?a[r]=c:i.set(s,{[r]:c}),{listId:s,itemId:r,...o}}function t(s,r){const o=i.get(s);if(o){if(r)return o[r]?.player.destroy(),o[r]?.container.remove(),o[r]?.subscription.unsubscribe(),delete o[r],Object.keys(o).length||i.delete(s),!0;for(const a of Object.values(o))a.player.destroy(),a.container.remove();return i.delete(s),!0}else throw Error("Can't remove. Not find.")}function n(){for(const s of i)t(s[0])}return{createPlayer:e,removePlayer:t,map:i,removeAll:n}}function _e(i,e=[]){let t={},n;const s=!e.length;for(const r of i.variants)if(!n&&"cover"in r&&(n=r.cover),"url"in r)switch(r.type.toLowerCase()){case"mp4":(s||e.includes("mp4"))&&(t.MPEG={...t.MPEG,[r.standard??"Invariant quality"]:r.url});break;case"mpeg":(s||e.includes("mpeg"))&&(t.MPEG={...t.MPEG,[r.standard??"Invariant quality"]:r.url});break;case"hls":(s||e.includes("hls"))&&(t={...t,HLS:{type:"url",url:r.url}});break;case"dash":(s||e.includes("dash"))&&(t={...t,DASH_SEP:{compatibilityMode:!0,type:"url",url:r.url}});break}return{sources:t,thumbUrl:n,title:i.title??""}}const Y=(i,e)=>{const t=i.info.currentQuality$.getValue(),n=i.info.availableQualities$.getValue();t!==e&&n.includes(e)&&(i.setQuality(e),i.setAutoQuality(!1))},oi=i=>{const e=i.variants.find(t=>t.payload?.type==="vk");if(e&&"payload"in e){const[t,n]=e.payload.id.split("_");return[t,n]}return[]},ee={activePlayerChanged:"sc-active-player-changed",initiated:"sc-initiated",playerCreated:"sc-player-created"},ci=2;function li(i){const e=ai();let t,n;const s=new tt;let r={},o=!1,a=null,c=!1,l;i&&p(i);function p(d){a=d}function u(d,g,m){if(!a)throw Error("need to set interactive controller");const E=(e.map.get(d)??{})[g];if(E){r={chapterId:m,listId:d,itemId:g,...E};const v=r.player;n=v.info.currentQuality$.subscribe(w=>{if(!(!w||!v.info.position$.getValue())){t=w;for(const L of e.map)Object.values(L[1]).forEach(({player:N})=>{v.info.isAutoQualityEnabled$.getValue()||Y(N,w)})}}),E.container.remove(),o=!1,a.setPlayer(E.player),c||(a.init(),c=!0),s.emit(ee.activePlayerChanged,{player:r.player,config:r.config});return}throw Error("Can't set. Not find.")}async function b(d,g,m){if(!a)throw Error("need to set interactive controller");if(z(r)||d!==r.itemId)return;if(m>=0&&!o){const E=a.getChapterBranches();o=!0;const v=new Set;for(const w of E)v.has(w.media.id)||(await x({media:w.media,chapterId:w.chapter.id,setAsActive:!1,title:w.chapter.label}),v.add(w.media.id))}}async function C({chapter:{id:d},media:g}){if(z(r))return;n?.unsubscribe();const m=r.player.info.muted$.getValue(),S=r.player.info.currentQuality$.getValue(),E=r.player.info.isAutoQualityEnabled$.getValue(),v=r.player.info.volume$.getValue(),w=r.player.info.currentPlaybackRate$.getValue(),L=!E;let N=!1;for(const O of e.map)if(O[0]===g.id){const Q=Object.keys(O[1]);for(const k of Q)k===r.itemId?(Q.length<ci||(N=!0),e.removePlayer(O[0],k)):(N=!0,u(O[0],k,d),L?Y(r.player,S):r.player.setAutoQuality(!0),r.player.setVolume(v),r.player.setMuted(m),r.player.setPlaybackRate(w))}else e.removePlayer(O[0]);N||(await x({media:g,chapterId:d,setAsActive:!0,playbackRate:w}),L?Y(r.player,S):r.player.setAutoQuality(!0),r.player.setVolume(v),r.player.setMuted(m))}async function x({media:d,chapterId:g,prefetch:m=!0,setAsActive:S=!0,autoplay:E=!1,preferredExt:v,title:w,playbackRate:L}){const N=Math.random().toString(),O=document.createElement("div");l.append(O);const Q=r?.player?.info.isAutoQualityEnabled$.getValue();let k;if(a?.options?.vkVideoLoader){const K=oi(d);K.length&&(k=await a.options.vkVideoLoader(...K))}const me={container:O,...k?.videos?.[0]||{sources:_e(d,v).sources},title:w},F=new mt.Player;F.initVideo(me);const ot=O.lastChild,ye=new j.Subscription;ye.add(F.info.position$.subscribe(function(K){b(N,F.info.duration$.getValue(),K)})).add(F.events.canplay$.subscribe(function(){Q||Y(F,t),L&&F.setPlaybackRate(L)})),ot&&(O.style.display="none",O.classList.add(g));const B=e.createPlayer({listId:d.id,itemId:N,player:F,container:O,sources:_e(d,v).sources,config:me,subscription:ye});return S&&u(d.id,B.itemId,g),E&&B.player.play(),m&&!E&&B.player.prepare(),s.emit(ee.playerCreated,B.player),{player:B.player,config:B.config}}function P(){h(),a=null}function h(){a?.off(y.chapterChanged,C),e.removeAll(),r={},c=!1,o=!1}async function f({source:d,initialChapter:g,container:m}){if(!a)throw Error("need to set interactive controller");await a.setManifest(d),h(),l=m;const{media:S,chapter:E}=await a.setChapter({chapterId:g});if(S){a.on(y.chapterChanged,C);const{player:v,config:w}=await x({media:S,chapterId:E.id,title:E.label});return s.emit(ee.initiated,{container:m,media:S,chapterId:E.id}),{player:v,config:w}}else console.error("not found")}return{...e,on:s.on.bind(s),off:s.off.bind(s),init:f,setInteractiveController:p,createPlayer:x,removeAll:P,getActivePlayer:function(){return r}}}const hi=3e3,di=()=>{let i=[],e=null;return{setPlayer:o=>{e=o},setContainers:o=>{i=o},deleteContainer:o=>{i=i.filter(a=>a.id!==o)},getNextInteractiveTime:(o=hi)=>{if(!i.length||e===null)return null;let a=-1,c=!1;const l=e.info.position$.getValue()*1e3;for(const p of i){const u=p.startTime-o;if(u<=l&&(l<=p.endTime||p.endTime===null)){c=!0;break}l<u&&(a=a===-1?u:Math.min(a,u))}return!c&&a!==-1?a:null}}},D=di(),T=Object.freeze({nothing:0,beforeInteractive:1,interactive:2,afterInteractive:3,end:4,removed:5,destroyed:6}),pe=i=>G(i)&&!Ye(i),at=i=>Ye(i.branches)||i.order==="end",ui=(i,e)=>{const t=i*1e3;return pe(e.controls)&&t<(e.startTime??0)},je=(i,e)=>{const t=i*1e3;return pe(e.controls)&&t>=(e.startTime??0)&&t<=(e.endTime??1/0)},ie=i=>i.some(e=>e.action.type==="expect"),Me=i=>i.find(e=>e.action.type==="expect"),fi=i=>i?.length===1,pi=i=>fi(i)&&et(i[0]),mi=({fn:i,type:e=1},...t)=>(...n)=>e?i(...n,...t):i({...n[e],...t[e]}),yi=(i=[])=>i.reduce((e,t,n)=>{const s=(t?.controls??[]).filter(r=>!et(r));if(pe(s)){const r=[t.startTime??0,t.endTime??1/0],o=t.id;if(!n)e.push({subjects:[o],range:r});else{const a=[];let c=-1/0,l=1/0,p=[];const u=[];for(let b=0;b<e.length;b++){const C=e[b];if(u.push(...C.subjects),C.range[0]<l&&(l=C.range[0]),C.range[1]>c&&(c=C.range[1]),C.range[0]<=r[0]&&C.range[1]>=r[1])return e[b].subjects.push(o),e;r[0]>=C.range[0]&&r[0]<=C.range[1]&&(a.push(b),p=p.concat(C.subjects),r[0]=C.range[0]),r[1]>=C.range[0]&&r[1]<=C.range[1]&&(a.push(b),p=p.concat(C.subjects),r[1]=C.range[1])}if(u.push(o),r[0]<=l&&r[1]>=c)return[{subjects:u,range:r}];a.length&&a.reverse().forEach(b=>{e.splice(b,1)}),e.push({subjects:p.concat([o]),range:r})}}return e},[]).sort((e,t)=>e.range[0]-t.range[0]),gi=(i,e)=>ie(i.events)?!1:e.some(({container:t})=>t.container.id!==i.id&&ie(t.container.events)&&t.container.endTime===i.endTime&&!t.isRemoved);class vi{constructor({player:e,container:t,branches:n,selectBranches:s,interactiveEvents:r,globalEventEmitter:o,ignoreContainerEvent:a,permanentTextControls:c}){this.container=t,this.branches=n,this.selectBranches=s,this.subscription=new j.Subscription,this.player=e,this.interactiveEvents=r,this.ignoreContainerEvent=a,this.isPermanentText=c&&pi(t.container.controls),this.globalEventEmitter=o,this.gameState=T.nothing,this.isSelectedControlEvent=!1,this.isSelectedContainerEvent=!1,this.registerEvents()}registerEvents(){this.subscription.add(this.player.events.playing$.subscribe(this.show)).add(this.player.events.paused$.subscribe(this.hide)).add(this.player.events.ended$.subscribe(this.onEndOfVideo))}hide=()=>{setTimeout(()=>{this.gameState!==T.end&&(ie(this.container.container.events)&&this.gameState===T.afterInteractive||this.selectBranches.state.isExpect||(this.container.hide?.(),this.globalEventEmitter.emit(y.interactives,{subjectId:this.container.container.id,subjectName:"container",type:R.visibility,visibility:!1})))})};show=()=>{if(this.gameState===T.interactive&&!this.isSelectedControlEvent)if(this.container.getElement())this.container.show?.(),this.globalEventEmitter.emit(y.interactives,{subjectId:this.container.container.id,subjectName:"container",type:R.visibility,visibility:!0,isFirst:!1});else{const t=mi({fn:this.selectBranches.onControlEvent,type:0},{branches:this.branches,containerId:this.container.container.id,onDetachContainer:()=>{this.removeView(),this.globalEventEmitter.emit(y.interactives,{subjectId:this.container.container.id,subjectName:"container",type:R.visibility,visibility:!1})},onEvent:(n,s)=>{this.isSelectedControlEvent=!0,n!==!1&&(this.removeView(),this.globalEventEmitter.emit(y.interactives,{subjectId:this.container.container.id,subjectName:"container",type:R.visibility,visibility:!1})),(this.gameState===T.end||this.gameState===T.afterInteractive||this.selectBranches.state.isExpect)&&(this.selectBranches.stopExpect(),s(),this.removeView(),this.globalEventEmitter.emit(y.interactives,{subjectId:this.container.container.id,subjectName:"container",type:R.visibility,visibility:!1})),D.deleteContainer(this.container.container.id)},isEOV:()=>this.gameState===T.end});this.container.createView(t),this.globalEventEmitter.emit(y.interactives,{subjectId:this.container.container.id,subjectName:"container",type:R.visibility,visibility:!0,isFirst:!0})}};selectContainerEvent(e=!1){this.interactiveEvents.containersEventsCallState.setCalled({timestamp:e?1/0:this.container.container.endTime,id:this.container.container.id}),!(this.isSelectedControlEvent||this.isSelectedContainerEvent)&&(this.isSelectedContainerEvent=!0,this.ignoreContainerEvent()||this.selectBranches.setManifestContainerEvents({container:this.container.container,branches:this.branches,isEOV:e}),!e&&this.interactiveEvents.exec(this.container.container.endTime))}onStartTime(){this.show()}onEndTime(){this.selectContainerEvent(!1);const e=ie(this.container.container.events)||this.ignoreContainerEvent();(this.isSelectedControlEvent||!e)&&this.removeView()}onBeforeStartTime(){this.container.hide?.(),this.globalEventEmitter.emit(y.interactives,{subjectId:this.container.container.id,subjectName:"container",type:R.visibility,visibility:!1})}onEndOfVideo=()=>{this.gameState=T.end,this.selectContainerEvent(!0)};whilePlaying=()=>{if(this.player.experimental.element$.getValue()?.readyState<1||[T.destroyed,T.removed].includes(this.gameState)&&!this.isPermanentText)return;const t=this.player.getExactTime();if(ui(t,this.container.container))this.gameState!==T.beforeInteractive&&(this.gameState=T.beforeInteractive,this.onBeforeStartTime());else if(je(t,this.container.container))this.gameState!==T.interactive&&(this.gameState=T.interactive,this.onStartTime());else if(this.gameState!==T.afterInteractive){const r=this.gameState;this.gameState=T.afterInteractive,r===T.interactive&&this.onEndTime()}else this.gameState!==T.destroyed&&this.removeView();const n=je(t,this.container.container),s=this.container.container.startTime?[this.container.container.startTime,this.container.container.endTime??1/0]:[];this.container.onProgress?.(t,n),this.globalEventEmitter.emit(y.eachTick,{subjectId:this.container.container.id,subjectName:"container",range:s,currentTime:t,isInteractiveTime:n})};reset(){this.isSelectedControlEvent=!1,this.isSelectedContainerEvent=!1,this.gameState=T.beforeInteractive}removeView(){this.container.removeView(),this.globalEventEmitter.emit(y.interactives,{subjectId:this.container.container.id,subjectName:"container",type:R.containerRemoved,visibility:!1}),this.gameState=T.removed}destroy(){this.reset(),this.removeView(),this.gameState=T.destroyed,this.subscription.unsubscribe(),this.branches=[],this.interactiveEvents.containersEventsCallState.setCalled({timestamp:this.container.container.endTime??1/0,id:this.container.container.id}),D.deleteContainer(this.container.container.id)}}function bi(){const i={};function e(){for(const a in i)Object.prototype.hasOwnProperty.call(i,a)&&delete i[a];return!0}function t(a){const c={};for(const l in i)+l<=a&&(c[l]=i[l]);return c}function n(a){const c={};for(const l in i)+l>=a&&(c[l]=i[l]);return c}function s({timestamp:a,priority:c,initiator:l}){if(Ee(a)){const p=i[a]??null;if(p&&X(c,!0)){let u={};const b=p[c];return b&&(u={...u,...b}),u=z(u)?null:u,u&&X(l,!0)?u[l]??null:u}return p}return null}function r({timestamp:a,priority:c,initiator:l}){if(Ee(a))if(i[a]){if(X(c,!0))if(i[a][c]){if(X(l,!0))if(i[a][c][l]){if(delete i[a][c][l],!z(i[a][c]))return!0}else return!1;if(delete i[a][c],!z(i[a]))return!0}else return!1;return delete i[a]}else return!1}function o({timestamp:a,priority:c,initiator:l,...p}){i[a]?.[c]?.[l]?i[a][c][l].push({...p}):i[a]?.[c]?i[a][c]={...i[a][c],[l]:[{...p}]}:i[a]?i[a]={...i[a],[c]:{[l]:[{...p}]}}:i[a]={[c]:{[l]:[{...p}]}}}return{map:i,remove:r,add:o,removeAll:e,get:s,getLte:t,getGte:n}}const Ci=[I.expect,I.setNextBranch],Ei=1/0;function Ve(i){let e=i,t;const n=wi(),s=new bi;let r;const o=()=>{u(),P()},a=h=>{s.add.call(void 0,h),b()},c=(h=[])=>{for(const f of h)if(f.action(),Ci.includes(f.actionType))break},l=h=>{if(!n.isReady(h))return;const f=J(s.get({timestamp:h,priority:"control"})??{}),d=J(s.get({timestamp:h,priority:"container"})??{}),g=J(s.get({timestamp:h,priority:"chapter"})??{});c([...f,...d,...g])},p=()=>{c([...J(s.get({timestamp:1/0,priority:"chapter"})??{})])},u=()=>{t&&(r?.unsubscribe(),t=void 0)},b=()=>{t||(t=()=>setTimeout(()=>{l(1/0)}),r=e.events.ended$.subscribe(t))},C=h=>{u(),e=h},x=h=>{h.priority==="container"&&n.resetCalled(h.timestamp),s.remove(h)},P=()=>{n.release(),s.removeAll()};return{setPlayer:C,add:a,remove:x,exec:l,execEndOfVideo:p,listen:b,unlisten:u,release:o,containersEventsCallState:n}}function wi(){const i=new Map;return{setCalled:({timestamp:o,id:a})=>{const c=i.get(o);c&&c[a]!==void 0&&(c[a]=!0)},setData:(o=[])=>{for(const a of o){const c=a.endTime??Ei,l=i.get(c)??{};i.set(c,{...l,[a.id]:!1})}},resetCalled:o=>{const a=i.get(o);if(a)for(const c in a)a[c]=!1},isReady:o=>{const a=i.get(o);return a?!Object.values(a).some(c=>!c):!0},release:()=>i.clear()}}function J(i){return Object.values(i).flat().sort(e=>e.actionType===I.expect?-1:1)}const Ii=(i,e)=>{const{height:t,width:n}=e.info.intrinsicVideoSize$.getValue()||{};if(!(t&&n))return{videoContentHeight:0,videoContentWidth:0};const{clientHeight:s,clientWidth:r}=e.experimental.element$.value||{};if(!(s&&r))return{videoContentHeight:0,videoContentWidth:0};const o=t/n,a=s/r;let c,l;return a>o?(l=r,c=r*o):a<o?(l=s/o,c=s):(l=r,c=s),{videoContentWidth:l,videoContentHeight:c}},Si=250;function Ti(i){let e=()=>{};const t=new ResizeObserver(a=>{r(a),e=r.bind(null,a)});function n(a){const{parentElement:c,player:l}=i();if(c&&l){const{videoContentWidth:p,videoContentHeight:u}=Ii(c,l);c.style.setProperty("--interactive-content-width",`${p}px`),c.style.setProperty("--interactive-content-height",`${u}px`),c.style.setProperty("--interactive-width",`${a[0].contentRect.width}px`),c.style.setProperty("--interactive-height",`${a[0].contentRect.height}px`)}}function s(){const{parentElement:a}=i();a.removeAttribute("style")}const r=Xe(a=>{const{fns:c=[]}=i();n(a);for(const l of c)l()},Si);function o(){e=void 0,t.disconnect(),s()}return{resizeObserver:t,calc:()=>{e()},release:o}}class Ri{constructor(){this.map={}}push(e,t){e in this.map?this.map[e].push(t):this.map[e]=[t]}get(e){const t=this.map[e];return t?t.slice():null}getAll(){const e=[];for(const t in this.map)e.push(...this.map[t]);return e}remove(e,t){e in this.map&&(this.map[e]=this.map[e].filter(n=>n!==t),this.map[e].length===0&&delete this.map[e])}clear(){this.map={}}size(){return Object.keys(this.map).length}keys(){return Object.keys(this.map)}}const Ai=i=>Math.floor(Math.random()*i),xi=i=>{let e=i.length,t=1/0,n=null;for(;e--;)i[e].weight<t&&(t=i[e].weight,n=i[e]);return n},Oi=i=>{let e=i.length,t=-1/0,n=null;for(;e--;)i[e].weight>t&&(t=i[e].weight,n=i[e]);return n},Li=i=>{const e=i.length,t=Ai(e);return i[t]},Pe=1,Ni=i=>{let e=0;for(let n=0;n<i.length;++n)e+=i[n].weight??Pe;const t=Math.random()*e;e=0;for(let n=0;n<i.length-1;++n)if(e+=i[n].weight??Pe,e>=t)return i[n];return i[i.length-1]},ke=Object.freeze({shouldOpenNow:!0,isDetachContainer:!0}),se=(i,e=!1)=>({...i,args:e?{...i.args,...ke}:{...ke,...i.args}}),Fe=({globalEventEmitter:i,player:e,interactiveEvents:t,removeControllers:n})=>{const s={isExpect:!1},r=()=>{s.isExpect&&(s.isExpect=!1)},o=({action:h,controlType:f,controlId:d,containerId:g,branches:m=[],onEvent:S,isEOV:E=()=>!1})=>{const v=se(h,E()),w={timestamp:1/0,priority:"control",initiator:d,actionType:v.type},L=i.emit.bind(i,y.interactives,{subjectId:d,subjectType:f,subjectName:"control",type:R.actionChoice,actionType:h.type,payload:{containerId:g,...v.args}});switch(v.type.trim().toLowerCase()){case I.setNextBranch.trim().toLowerCase():{const N=m.find(O=>O.id===v.args.branchId);if(!N)return;S(v.args.isDetachContainer,b.bind(null,{subjectId:d,subjectName:"control"})),L(),v.args.shouldOpenNow?x({subjectId:d,subjectName:"control",subjectType:f,action:v,payload:{chapterId:N.chapterId,autoSelect:!1}}):(t.add({...w,action:x.bind(null,{subjectId:d,subjectName:"control",subjectType:f,action:v,payload:{chapterId:N.chapterId,autoSelect:!1}})}),n?.());return}case I.continuePlayback.trim().toLowerCase():{S(v.args.isDetachContainer,b.bind(null,{subjectId:d,subjectName:"control"})),L(),v.args.shouldOpenNow?C({subjectId:d,subjectName:"control",subjectType:f,action:h}):t.add({...w,action:C.bind(null,{subjectId:d,subjectName:"control",subjectType:f,action:h})});return}case I.openURI.trim().toLowerCase():{S(v.args.isDetachContainer,b.bind(null,{subjectId:d,subjectName:"control"})),L(),v.args.shouldOpenNow?P({subjectId:d,subjectName:"control",subjectType:f,action:v,payload:{URI:h.args.uri}}):(t.add({...w,action:P.bind(null,{subjectId:d,subjectName:"control",subjectType:f,action:v,payload:{URI:h.args.uri}})}),n?.());return}default:console.error("Unexpected control event"),i.emit(y.errors,new A(A.Severity.RECOVERABLE,A.Category.INTERACTIVES,{message:"Unexpected control event"}));return}},a=({action:h,container:{id:f,endTime:d},branches:g=[],isEOV:m=!1,autoSelected:S=!1})=>{const E=se(h,m),v={timestamp:!E.args.shouldOpenNow||m?1/0:d,priority:"container",initiator:f,actionType:E.type},w=i.emit.bind(i,y.interactives,{subjectId:f,subjectName:"container",type:R.actionChoice,actionType:E.type,payload:E.args});switch(E.type.trim().toLowerCase()){case I.setNextBranch.trim().toLowerCase():{const L=g.find(N=>N.id===E.args.branchId);if(!L)return;w(),t.add({...v,action:x.bind(null,{subjectId:f,subjectName:"container",action:E,payload:{chapterId:L.chapterId,autoSelect:S}})}),n?.();return}case I.setMaxWeightBranch.trim().toLowerCase():return;case I.setMinWeightBranch.trim().toLowerCase():return;case I.setRandomBranch.trim().toLowerCase():return;case I.setWeightlessRandomBranch.trim().toLowerCase():return;case I.continuePlayback.trim().toLowerCase():{w(),t.add({...v,action:C.bind(null,{subjectId:f,subjectName:"container",action:E})});return}case I.openURI.trim().toLowerCase():{w(),t.add({...v,action:P.bind(null,{subjectId:f,subjectName:"container",action:E,payload:{URI:h.args.uri}})}),n?.();return}default:console.error("Unexpected container event"),i.emit(y.errors,new A(A.Severity.RECOVERABLE,A.Category.INTERACTIVES,{message:"Unexpected container event"}));return}};function c({container:h,branches:f,isEOV:d=!1}){const g=Me(h.events);if(g){const m=se(g.action,d);i.emit(y.interactives,{subjectId:h.id,subjectName:"container",type:R.actionChoice,actionType:m.type,payload:m.args}),t.add({timestamp:d?1/0:h.endTime,priority:"container",initiator:h.id,actionType:I.expect,action:u.bind(null,{subjectId:h.id,subjectName:"container"})}),s.isExpect=!0}else for(const m of h.events)a({action:m.action,container:h,branches:f,isEOV:d})}const l=({chapterId:h,action:f,branches:d=[]})=>{const g=i.emit.bind(i,y.interactives,{subjectId:h,subjectName:"chapter",type:R.actionChoice,actionType:f.type,payload:f.args});switch(f.type.trim().toLowerCase()){case I.setNextBranch.trim().toLowerCase():{const m=d.find(S=>S.id===f.args.branchId);return m?.chapterId?(g(),x.bind(null,{subjectId:h,subjectName:"chapter",action:f,payload:{chapterId:m.chapterId,autoSelect:!0}})):void 0}case I.setWeightlessRandomBranch.trim().toLowerCase():{const m=Li(d);return m?.chapterId?(g(),x.bind(null,{subjectId:h,subjectName:"chapter",action:f,payload:{chapterId:m.chapterId,autoSelect:!0}})):void 0}case I.setRandomBranch.trim().toLowerCase():{const m=Ni(d);return m?.chapterId?(g(),x.bind(null,{subjectId:h,subjectName:"chapter",action:f,payload:{chapterId:m.chapterId,autoSelect:!0}})):void 0}case I.setMaxWeightBranch.trim().toLowerCase():{const m=Oi(d);return m?.chapterId?(g(),x.bind(null,{subjectId:h,subjectName:"chapter",action:f,payload:{chapterId:m.chapterId,autoSelect:!0}})):void 0}case I.setMinWeightBranch.trim().toLowerCase():{const m=xi(d);return m?.chapterId?(g(),x.bind(null,{subjectId:h,subjectName:"chapter",action:f,payload:{chapterId:m.chapterId,autoSelect:!0}})):void 0}case I.continuePlayback.trim().toLowerCase():return g(),C.bind(null,{subjectId:h,subjectName:"chapter",action:f});case I.openURI.trim().toLowerCase():return g(),P.bind(null,{subjectId:h,subjectName:"chapter",action:f,payload:{URI:f.args.uri}});default:console.error("Unexpected chapter event"),i.emit(y.errors,new A(A.Severity.RECOVERABLE,A.Category.INTERACTIVES,{message:"Unexpected chapter event"}));return}};function p(h){const f=Me(h.events);if(f){if(at(h))return;i.emit(y.interactives,{subjectId:h.id,subjectName:"chapter",type:R.actionChoice,actionType:f.action.type,payload:f.action.args}),t.add({timestamp:1/0,priority:"chapter",initiator:h.id,actionType:I.expect,action:u.bind(null,{subjectId:h.id,subjectName:"chapter"})})}else h.events.forEach(d=>{const g=l({chapterId:h.id,action:d.action,branches:h.branches});g&&t.add({timestamp:1/0,priority:"chapter",initiator:h.id,actionType:d.action.type,action:g})})}const u=({subjectId:h,subjectName:f,action:d})=>{e.pause(),i.emit(y.interactives,{subjectId:h,subjectName:f,type:R.actionExecution,actionType:d?.type??I.expect})},b=({subjectId:h,subjectName:f})=>{e.info.isEnded$.getValue()?t.execEndOfVideo():e.play(),i.emit(y.interactives,{subjectId:h,subjectName:f,type:R.actionExecution,actionType:"after-expect"})},C=({subjectId:h,subjectName:f,subjectType:d,action:g})=>{i.emit(y.interactives,{subjectId:h,subjectName:f,subjectType:d,type:R.actionExecution,actionType:g.type})},x=({subjectId:h,subjectName:f,subjectType:d,action:g,payload:m})=>{m.behaviour="change-chapter",i.emit(y.interactives,{subjectId:h,subjectName:f,subjectType:d,type:R.actionExecution,actionType:g.type,payload:m})},P=({subjectId:h,subjectName:f,subjectType:d,action:g,payload:m})=>{if(!m.URI)return;const S=window.open(m.URI,"_blank","noopener,noreferrer");S&&(S.opener=null),i.emit(y.interactives,{subjectId:h,subjectName:f,subjectType:d,type:R.actionExecution,actionType:g.type})};return{onControlEvent:o,onContainerEvent:a,onChapterEvent:l,onExpectEvent:u,expectEventHandler:b,setManifestChapterEvents:p,setManifestContainerEvents:c,stopExpect:r,state:s}};class H{constructor(e,t,n,s){this.target=e,this.type=t,this.listener=n,this.options=H.#a(e,s),this.target.addEventListener(t,n,this.options)}unlisten(){this.target.removeEventListener(this.type,this.listener,this.options),this.target=null,this.listener=null,this.options=!1}static#a(e,t){if(t===void 0)return!1;if(typeof t=="boolean")return t;{const n=new Set(["passive","capture"]),s=Object.keys(t).filter(o=>!n.has(o));return s.length===0&&console.warn("Unsupported flag(s) to addEventListener: "+s.join(",")),H.#l(e)?t:t.capture||!1}}static#s=void 0;static#l(e){let t=H.#s;if(t===void 0){t=!1;try{const n={},s={get:()=>(t=!0,!1)};Object.defineProperty(n,"passive",s),Object.defineProperty(n,"capture",s);const r=()=>{};e.addEventListener("test",r,n),e.removeEventListener("test",r,n)}catch{t=!1}H.#s=t}return t||!1}}class _i{constructor(){this.bindingMap=new Ri}release(){this.removeAll(),this.bindingMap=null}listen(e,t,n,s){if(!this.bindingMap)return;const r=new H(e,t,n,s);this.bindingMap.push(t,r)}listenOnce(e,t,n,s){const r=o=>{this.unlisten(e,t,r),n(o)};this.listen(e,t,r,s)}unlisten(e,t,n){if(!this.bindingMap)return;const s=this.bindingMap.get(t)||[];for(const r of s)r.target===e&&(n===r.listener||!n)&&(r.unlisten(),this.bindingMap.remove(t,r))}removeAll(){if(!this.bindingMap)return;const e=this.bindingMap.getAll();for(const t of e)t.unlisten();this.bindingMap.clear()}}class ji{rootElement;canvasImgSrc;_prevSizeId=0;constructor(){this.rootElement=document.createElement("canvas")}clear(){this.rootElement.getContext("2d")?.clearRect(0,0,this.rootElement.width,this.rootElement.height)}isImageDrawn(){const e=this.rootElement.getContext("2d")?.getImageData(0,0,this.rootElement.width,this.rootElement.height);if(!e)return!1;const t=e.data,n=t.length;for(let s=3;s<n;s+=40)if(t[s]!==0)return!0;return!1}destroy(){this.rootElement.remove()}show(){this.rootElement.style.visibility="visible"}hide(){this.rootElement.style.visibility="hidden"}setCanvasImageSource(e){this.canvasImgSrc=e}draw(){this.canvasImgSrc&&this.rootElement.getContext("2d")?.drawImage(this.canvasImgSrc,0,0,this.rootElement.width,this.rootElement.height)}async updateCanvasDimensions(e,t=!1){const n=e.width+e.height;if(this._prevSizeId===n)return;let s;t&&(s=await this.save()),this.rootElement.width=e.width,this.rootElement.height=e.height,t&&s&&this.restore(s),this._prevSizeId=n}async save(){const e=this.rootElement.toDataURL("image/jpeg",1),t=new Image;return t.crossOrigin="anonymous",t.src=e,await t.decode(),t}restore(e){this.rootElement&&this.rootElement.getContext("2d")?.drawImage(e,0,0,this.rootElement.width,this.rootElement.height)}}class Mi{lastFrameCanvas;endOffsetMs;currentChapter;currentVideoDurationMs=1/0;rootElement;_containerTimeFrameShouldReceived=!1;_endTimeFrameReceived=!1;_shouldCallSkip=!1;_callbacks;constructor({parentElement:e,endOffsetMs:t=250,onError:n}){this.rootElement=document.createElement("div"),this.rootElement.style.cssText=`
|
|
6
|
+
"use strict";var ot=Object.create;var ge=Object.defineProperty;var ct=Object.getOwnPropertyDescriptor;var lt=Object.getOwnPropertyNames;var ht=Object.getPrototypeOf,dt=Object.prototype.hasOwnProperty;var ut=(i,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of lt(e))!dt.call(i,s)&&s!==t&&ge(i,s,{get:()=>e[s],enumerable:!(n=ct(e,s))||n.enumerable});return i};var ft=(i,e,t)=>(t=i!=null?ot(ht(i)):{},ut(e||!i||!i.__esModule?ge(t,"default",{value:i,enumerable:!0}):t,i));var j=require("@vkontakte/videoplayer-shared/esnext.cjs.js"),ce=require("uuid"),pt=require("@vkontakte/videoplayer-core/esnext.cjs.js");const mt="1.0.6-dev.35f8adc.0";function Be(i,e=1){let t="0",n="0",s="0";return i.length===4?(t="0x"+i[1]+i[1],n="0x"+i[2]+i[2],s="0x"+i[3]+i[3]):i.length===7&&(t="0x"+i[1]+i[2],n="0x"+i[3]+i[4],s="0x"+i[5]+i[6]),`rgba(${+t},${+n},${+s},${e})`}const _="SDK_NAME",yt="SDK_NAME-controls-container",$e=()=>document.querySelector(`.${yt}`),V={textColor:"#000",textSize:.4,textContent:"",roundCorners:0,borderWidth:0,borderColor:"#000",borderAlpha:1,backgroundColor:"#fff",backgroundAlpha:1,innerSizesDependOn:"self",angle:0},ve={top:"flex-start",bottom:"flex-end",center:"center"},be={start:"flex-start",end:"flex-end",center:"center"},Ce={start:"left",end:"right",center:"center"},De=({target:i,props:e})=>{i.style.alignItems=ve[e?.text?.gravityVertical]??ve.center,i.style.justifyContent=be[e?.text?.gravityHorizontal]??be.center,i.style.textAlign=Ce[e?.text?.alignment]??Ce.start},He=({target:i,props:e,fallback:t,dependsOn:n})=>{i.style.color=e?.text?.color??t.textColor,i.style.fontSize=`calc(${n.height} * ${e?.text?.size??t.textSize})`,i.textContent=e?.text?.value??t.textContent},Ue=({target:i,props:e,fallback:t})=>{i.style.backgroundColor=Be(e?.background?.color??t.backgroundColor,e?.background?.alpha??t.backgroundAlpha)},ze=({target:i,props:e,fallback:t,dependsOn:n})=>{i.style.border=`calc(${n.height} * ${e?.shape?.border?.width??t.borderWidth}) solid ${Be(e?.shape?.border?.color??t.borderColor,e?.shape?.border?.alpha??t.borderAlpha)}`,i.style.borderRadius=`calc(${n.height} * ${e?.shape?.roundCorners??t.roundCorners})`},le=({target:i,layoutParams:e,fallback:t})=>{i.style.transform=`rotate(${-e.angle}rad)`};class he{constructor(e){this.control=e}createView(e){const t=document.createElement("div");t.classList.add(`${_}-control-container-${this.control.id}`),e(t,this.control.layoutParams);const n=(this.control.layoutParams.innerSizesDependOn??V.innerSizesDependOn)==="self"?{height:t.style.height,width:t.style.width}:{height:"var(--interactive-content-height)",width:"var(--interactive-content-width)"};return{controlContainerEl:t,dependsOn:n}}setEvents(e,t){e&&this.control.events.forEach(n=>{switch(n.type.trim().toLowerCase()){case"onclick":e.addEventListener("click",r=>{r.stopPropagation(),t&&t({action:n.action,controlId:this.control.id,controlType:this.control.type})});break}})}getElement(){return document.querySelector(`.${_}-control-container-${this.control.id}`)}}const Ge=i=>{if(i.type.trim().toLowerCase()==="area")return new gt(i)};class gt extends he{constructor(e){super(e)}createView({parent:e,layoutFn:t}){const{dependsOn:n,controlContainerEl:s}=super.createView(t),r=document.createElement("button");return r.classList.add(`${_}-${this.control.id}`),r.style.display="flex",r.style.width="100%",r.style.height="100%",r.style.cursor="pointer",r.type="button",Ue({target:r,props:this.control.props,fallback:{...V,backgroundColor:"transparent"}}),ze({target:r,props:this.control.props,fallback:{...V,borderAlpha:0},dependsOn:n}),le({target:r,layoutParams:this.control.layoutParams,fallback:V}),s.append(r),e.append(s),s}getElement(){return document.querySelector(`.${_}-${this.control.id}`)}}const We=i=>{if(i.type.trim().toLowerCase()==="button")return new vt(i)};class vt extends he{constructor(e){super(e)}createView({parent:e,layoutFn:t}){const{dependsOn:n,controlContainerEl:s}=super.createView(t),r=document.createElement("button");r.type="button",r.classList.add(`${_}-${this.control.id}`),r.style.display="flex",r.style.width="100%",r.style.height="100%",r.style.cursor="pointer",r.style.fontFamily="inherit";const o=document.createElement("span");return o.style.display="inline-block",o.style.whiteSpace="pre",o.style.overflow="hidden",o.style.textOverflow="ellipsis",le({target:r,layoutParams:this.control.layoutParams,fallback:V}),Ue({target:r,props:this.control.props,fallback:V}),ze({target:r,props:this.control.props,fallback:V,dependsOn:n}),De({target:r,props:this.control.props}),He({target:o,props:this.control.props,fallback:V,dependsOn:n}),r.append(o),s.append(r),e.append(s),s}getElement(){return document.querySelector(`.${_}-${this.control.id}`)}}const bt=i=>{if(i.type.trim().toLowerCase()==="text")return new Ct(i)};class Ct extends he{constructor(e){super(e)}createView({parent:e,layoutFn:t}){const{dependsOn:n,controlContainerEl:s}=super.createView(t),r=document.createElement("div");r.classList.add(`${_}-${this.control.id}`),r.style.display="flex",r.style.width="100%",r.style.height="100%",r.style.fontFamily="inherit";const o=document.createElement("span");return o.style.whiteSpace="pre",le({target:r,layoutParams:this.control.layoutParams,fallback:V}),De({target:r,props:this.control.props}),He({target:o,props:this.control.props,fallback:V,dependsOn:n}),r.append(o),s.append(r),e.append(s),s}getElement(){return document.querySelector(`.${_}-${this.control.id}`)}}class Et{constructor(e){this.layout=e}}const wt=i=>{if(i.type.trim().toLowerCase()==="relative")return new qe(i)};class qe extends Et{constructor(e){super(e)}setContainerLayout(e){e.style.position="relative"}setControlLayout(e,t){e.style.position="absolute",e.style.width=`calc(var(--interactive-content-width) * ${t.width})`,e.style.height=`calc(var(--interactive-content-height) * ${t.height})`,e.style.left=`calc(var(--interactive-content-width) * ${t.x} + ((var(--interactive-width) - var(--interactive-content-width)) / 2))`,e.style.top=`calc(var(--interactive-content-height) * ${t.y} + ((var(--interactive-height) - var(--interactive-content-height)) / 2))`}}class Qe{constructor(e){this.container=e,this.factories=new Map,this.#a()}addControlFactory(e,t){this.factories.set(e.trim().toLowerCase(),t),this.#a()}removeControlFactory(e){this.factories.delete(e.trim().toLowerCase()),this.#a()}#a(){this.controls=this.#s()}#s(){return this.container.controls?.reduce((e,t)=>{const n=t.type.trim().toLowerCase(),s=this.factories.get(n);return s?[...e,s(t)]:[...e]},[])}}const Ke=(i,e)=>{if(i.type.trim().toLowerCase()==="choice")return new It(i,e)};class It extends Qe{constructor(e,t){super(e),this.rootElement=t??$e(),this.layout=new qe(this.container.layout),this.isRemoved=!1,this.addControlFactory("button",We),this.addControlFactory("text",bt),this.addControlFactory("area",Ge)}createView(e){const t=document.createElement("div");return t.classList.add(`${_}-${this.container.id}`),this.layout.setContainerLayout(t),this.controls.forEach(n=>{const s=n.createView({parent:t,layoutFn:this.layout.setControlLayout});n.setEvents(s,e)}),this.rootElement.append(t),t}hide(){const e=this.getElement();e&&(e.style.visibility="hidden")}show(){const e=this.getElement();e&&(e.style.visibility="visible")}removeView(){this.isRemoved||(this.getElement()?.remove(),this.isRemoved=!0)}getElement(){return this.rootElement.querySelector(`.${_}-${this.container.id}`)}}function Xe(i,e){let t;return(...n)=>{clearTimeout(t),t=setTimeout(()=>i(...n),e)}}const q={Object:"Object",String:"String",Array:"Array",Number:"Number",Function:"Function",Boolean:"Boolean"},z=(i,e)=>Object.prototype.toString.call(i)===`[object ${e}]`,de=i=>z(i,q.Object),re=i=>z(i,q.String),U=i=>z(i,q.Array),Ze=i=>z(i,q.Number),St=i=>z(i,q.Function),Ee=i=>Ze(i)&&!isNaN(i),Tt=i=>i==null,G=i=>de(i)&&Object.keys(i).length===0,Ye=i=>U(i)&&!i.length,X=(i,e)=>re(i)&&(e?i.trim():i).length,Je=window.navigator.userAgent.toLowerCase(),Rt=/mobi/i.test(Je);Je.indexOf("android")>-1;const At="video_interactive",xt="videoint",Ot=250;class Lt{constructor(e){this.init(e)}init({root:e,onOpenPreviewClick:t,onError:n,lang:s,visitedChapters:r=[]}){this.isHidden=!0,this.currentManifestId=void 0,this.currentChapterId=void 0,this.visitedChapterIds=new Set(r),this.onOpenPreviewClick=t,this.onError=n,this.lang=s??"ru",this.zoom=.7,this.isReady=!1,this.lastZoomInfo=void 0,this.ngEditorSize=void 0,this.ngEditor=void 0,this.graphWrapperElement=Nt(e),this.resizeObserver=new ResizeObserver(Xe(this.onResize,Ot)),this.resizeObserver.observe(this.graphWrapperElement)}onResize=e=>{this.isReady&&(!e[0].contentRect.width||!e[0].contentRect.height||(this.lastZoomInfo&&this.ngEditor.zoomTo(this.getNextPoint()),this.ngEditorSize={width:e[0].contentRect.width,height:e[0].contentRect.height}))};getNextPoint(e=this.ngEditorSize){return[(this.lastZoomInfo.x-e.width/2)/this.lastZoomInfo.value*-1,(this.lastZoomInfo.y-e.height/2)/this.lastZoomInfo.value*-1]}handleChapterChange=e=>{if(this.isReady){if(this.isHidden||this.hide(),!e?.id){this.onError?.("Id is not found"),console.error("Id is not found");return}this.visitedChapterIds.add(e.id),this.ngEditor.selectChapter(e.id),this.ngEditor.setVisitedChapters(Array.from(this.visitedChapterIds)),this.currentChapterId=e.id,this.lastZoomInfo=void 0}};handleManifestChange=async(e,t=[])=>{if(!Ze(e.graph.edit.chapters[0].x)){this.isReady=!1,this.onError?.("Can't show graph"),console.error("Can't show graph");return}if(this.lastZoomInfo=void 0,!this.ngEditor){let n;try{n=await j.loadVKLangPack(this.lang,At,xt)}catch{console.log("Unable to load graph language pack")}const{GraphEditor:s}=await import("@interactiveplatform/movika-graph-editor");this.ngEditor=new s(this.graphWrapperElement,{mode:"read",lang:this.lang,translation:n}),this.ngEditor.on("control",({name:r,chapterId:o})=>{r==="openPreview"&&this.onOpenPreviewClick(o)}),this.ngEditor.on("zoomEnd",r=>{this.lastZoomInfo={...r}})}this.visitedChapterIds=new Set(t),e.metadata.id!==this.currentManifestId?(this.ngEditor.update(e),this.currentManifestId=e.metadata.id):this.ngEditor.setVisitedChapters(Array.from(this.visitedChapterIds)),this.isReady=!0};setVisitedChapters(e){this.visitedChapterIds=new Set([...this.visitedChapterIds,...e]),this.ngEditor.setVisitedChapters(Array.from(this.visitedChapterIds))}updateVideosInfo(e){this.ngEditor.updateVideosInfo(e)}show(){!this.ngEditor||!this.isReady||(this.graphWrapperElement.style.display="block",this.lastZoomInfo||this.ngEditor.focusChapter(this.currentChapterId),this.isHidden=!1)}hide(){this.graphWrapperElement.style.display="none",this.isHidden=!0}destroy(){this.hide(),this.resizeObserver.disconnect(),this.ngEditor?.setVisitedChapters([]),this.onOpenPreviewClick=void 0,this.ngEditor?.dispose(),this.graphWrapperElement.remove(),this.isReady=!1}}function Nt(i){const e=document.createElement("div");return e.style.position="absolute",e.style.top="0",e.style.left="0",e.style.height="100%",e.style.width="100%",e.style.display="none",i.append(e),e}const _t=(i={})=>Array.from(new Set(i.sessions?.map(e=>e.visitedChapters.map(t=>t.chapterId)??[]).flat())),we=(i=[],e="")=>i.reduce((t,n)=>(t.find(s=>s[e]===n[e])||t.push(n),t),[]),Ie="chapterId";class ${constructor(e){this.id=e?.id??ce.v4(),this.startDate=e?.startDate?new Date(e.startDate).toISOString():new Date(Date.now()).toISOString(),this.updateOn=e?.updateOn?new Date(e.updateOn).toISOString():null,this.visitedChapters=e?.visitedChapters?we(Array.from(e.visitedChapters),Ie):[],this.branches=U(e?.branches)?e.branches:[]}update(e){e?.startDate&&(this.startDate=new Date(e.startDate).toISOString()),e?.updateOn&&(this.updateOn=new Date(e.updateOn).toISOString()),U(e?.visitedChapters)&&(this.visitedChapters=we([...this.visitedChapters,...e.visitedChapters],Ie)),U(e?.branches)&&(this.branches=this.branches.concat(e.branches))}getSession(){return{...this}}static createVisitedChapter(e){return[{chapterId:e}]}static createBranch(e,t,n){return[{chapterId:e,branchId:t,autoSelect:n}]}}class Z{constructor(e){this.id=e?.id??ce.v4(),this.manifestId=e?.manifestId,this.manifestVersion=e?.manifestVersion,this.manifestBuild=e?.manifestBuild,this.sessions=U(e?.sessions)?e?.sessions.map(t=>new $(t)):[],this.isCompleted=e?.isCompleted??!1}update(e){this.id=e?.id??this.id,this.manifestId=e?.manifestId??this.manifestId,this.manifestVersion=e?.manifestVersion??this.manifestVersion,this.manifestBuild=e?.manifestBuild??this.manifestBuild,this.isCompleted=e?.isCompleted??this.isCompleted}addSession(e){this.sessions.push(new $(e))}updateSession(e,t){let n;Tt(e)?n=this.sessions[this.sessions.length-1]:n=this.sessions.find(s=>s.id===e),n&&n.update(t)}resetSession(){this.sessions=[]}getHistory(){return{...this,sessions:this.sessions.map(e=>e.getSession())}}}const ae="SDK_NAME-history-changed";function jt(){return Object.assign(new EventTarget,{history:new Z,onChapterChange({chapterId:i,mediaId:e,autoSelect:t=!1,isLastChapter:n=!1}){this.history.isCompleted?this.history=new Z({manifestId:this.history.manifestId,manifestVersion:this.history.manifestVersion,manifestBuild:this.history.manifestBuild}):n&&this.history.update({isCompleted:!0}),this.history.sessions.length?this.history.updateSession(null,{updateOn:Date.now(),visitedChapters:$.createVisitedChapter(i),branches:$.createBranch(i,e,t)}):this.history.addSession({updateOn:Date.now(),visitedChapters:$.createVisitedChapter(i),branches:$.createBranch(i,e,!1)}),this.sendEvent()},onManifestChange(i,e){e?this.history=new Z(e):this.history=new Z({manifestId:i.id,manifestVersion:i.version,manifestBuild:i.build}),this.history.addSession({updateOn:Date.now()}),this.sendEvent()},getHistory(){if(history)return this.history.getHistory()},sendEvent(){this.dispatchEvent(new CustomEvent(ae,{bubbles:!1,detail:this.getHistory()}))},destroy(){this.history=void 0}})}function Vt(i,e){if(!e||!i||!e.sessions.length)return;const t=e.sessions.reverse().find(n=>n.branches.length);return t.branches[t.branches.length-1].chapterId??void 0}const W=(i="",e="")=>{i=i.split("."),e=e.split(".");let t=0;for(let n=0;n<Math.max(i.length,e.length)&&!t;n++)i[n]>e[n]?t=1:i[n]<e[n]?t=-1:t=0;return t},Mt="3.1",Se={default:"setNextBranch",random:"setRandomBranch",weightlessRandom:"setWeightlessRandomBranch",max:"setMaxWeightBranch",min:"setMinWeightBranch"},kt={type:"onSuspense",action:{type:"continuePlayback",args:{shouldOpenNow:!0,isDetachContainer:!0}}},Ft=i=>{const e=[];for(const t of i.chapters){let n;const s=[];for(const{isDefault:a,...c}of t.branches)a&&(n=c.id),s.push(c);let r=[];const o=[];for(const{fallbackStrategy:a,...c}of t.containers){const l=!!c.endTime;let p=[kt];switch(a){case"await":l?p=[]:r=[];break;case"default":{const u={type:"onSuspense",action:{type:Se.default,args:{branchId:n,shouldOpenNow:!l,isDetachContainer:!0}}};l?p=[u]:r=[u];break}case"random":case"weightlessRandom":case"max":case"min":{const u={type:"onSuspense",action:{type:Se[a],args:{}}};l?p=[u]:r=[u];break}}for(const u of c.controls)o.push({...c,controls:[{...u}],id:ce.v4(),events:p})}e.push({...t,containers:o,events:r,branches:s})}return i.metadata.version=Mt,i.metadata.updated=new Date().toISOString(),{...i,chapters:e}},Pt="3.2",Bt=i=>{if(!i.media){const{media:e,...t}=i.metadata;return{...i,metadata:{...t,version:Pt},media:e}}return i},$t="3.3",Dt=(i=[])=>({edit:{chapters:i},view:{}}),Te={type:"onSuspense",action:{type:"expect",args:{shouldOpenNow:!0,isDetachContainer:!0}}},Ht=i=>{const e=[],t=[];for(const n of i.chapters){const{id:s,x:r,y:o,...a}=n,c=a.containers.map(l=>({...l,controls:l.controls.map(({subtype:p,type:u,...b})=>({...b,type:p??u})),events:l.events?.length?l.events:[Te]}));e.push({id:s,...a,containers:c,events:a.events?.length?a.events:[Te]}),t.push({id:s,x:r,y:o})}return{...i,chapters:e,graph:Dt(t),metadata:{...i.metadata,version:$t}}},Ut=[{version:"3.0",migrate:Ft},{version:"3.1",migrate:Bt},{version:"3.2",migrate:Ht}],zt=i=>Ut.reduce((e,t)=>W(e.metadata.version,t.version)?e:t.migrate(e),i),Gt=Object.freeze({Button:"Button",Area:"Area",Text:"Text"}),I=Object.freeze({openURI:"openURI",setNextBranch:"setNextBranch",setWeightlessRandomBranch:"setWeightlessRandomBranch",setRandomBranch:"setRandomBranch",setMaxWeightBranch:"setMaxWeightBranch",setMinWeightBranch:"setMinWeightBranch",setDefaultBranch:"setDefaultBranch",continuePlayback:"continuePlayback",expect:"expect"});exports.INTERACTIVE_CLICK_ACTIONS=void 0;(function(i){i.GO_NEXT_BUTTON="GO_NEXT_BUTTON",i.GO_NEXT_AREA="GO_NEXT_AREA",i.WATCH_AGAIN="WATCH_AGAIN",i.OPEN_GRAPH="OPEN_GRAPH",i.CLOSE_GRAPH="CLOSE_GRAPH"})(exports.INTERACTIVE_CLICK_ACTIONS||(exports.INTERACTIVE_CLICK_ACTIONS={}));const Re={metadata:"Object",chapters:"Array"},Wt="3.0.0",qt="3.3.0",ue=i=>{const e=W(i,Wt);return e===-1?!1:e===0?!0:W(i,qt)!==1},Qt=i=>{if(!de(i))return!1;for(const e in Re)if(!i[e]||!z(i[e],Re[e]))return!1;return ue(i.metadata.version)},Kt=i=>i.type===Gt.Text;class A{constructor(e,t,...n){this.severity=e,this.category=t,this.data=n}toString(){return`SDK_NAME ERROR ${JSON.stringify(this,null," ")}`}static Severity={RECOVERABLE:1,CRITICAL:2};static Category={VIDEO:0,INTERACTIVES:1,GRAPH:2,MANIFEST:3,LOADERS:4,HISTORY:5,SEAMLESS:6}}class et{listeners={};addListener(e,t){return this.listeners[e]=this.listeners[e]||[],this.listeners[e].push(t),this}on(e,t){return this.addListener(e,t)}once(e,t){this.listeners[e]=this.listeners[e]||[];const n=()=>{t(),this.off(e,n)};return this.listeners[e].push(n),this}off(e,t){return this.removeListener(e,t)}reset(){this.listeners={}}removeListener(e,t){const n=this.listeners[e];if(!n)return this;for(let s=n.length;s>0;s--)if(n[s]===t){n.splice(s,1);break}return this}emit(e,...t){const n=this.listeners[e];return n?(n.forEach(s=>{s(...t)}),!0):!1}listenerCount(e){return(this.listeners[e]||[]).length}rawListeners(e){return this.listeners[e]}}class Xt{constructor(e){this.raf,this.fn,this.fns=[],this.addFn(e)}addFn=(e,t=!1)=>{St(e)&&(this.fns.push(e),t&&this.updateFn())};removeFn=(e,t=!1)=>{this.fns=this.fns.filter(n=>n!==e),t&&this.updateFn()};updateFn=()=>{this.fn=()=>{this.fns.forEach(e=>e()),this.raf&&this.forceRequestAnimation()}};forceRequestAnimation=()=>{this.fn&&(this.raf=requestAnimationFrame(this.fn))};requestAnimation=()=>{this.raf||this.forceRequestAnimation()};cancelAnimation=()=>{cancelAnimationFrame(this.raf),this.raf=void 0};release(){this.cancelAnimation(),this.fn=void 0,this.fns=[]}}class Zt{loaders;constructor(e){this.loaders={chapterLoaders:e?.chapterLoaders??[],manifestLoaders:e?.manifestLoaders??[]}}async exec(e,t){return Yt(...this.loaders[e])(t)}}function Yt(...i){return async function(t){const n=[...i];for(;n.length>0;)t=await n.shift()(t);return t}}function te(i,e,t){return i?{...i,[e]:i[e]?[t,...i[e]]:[t]}:{[e]:[t]}}function oe({actions:i,errors:e,chapterId:t,...n}){if(t){const s=i.getManifest(),r=i.getChapter(s.chapters,t);if(r){const o=i.getMedia(s.media,r.videoId),a=i.getGraph(s.graph,r.id);return o?{...n,actions:i,errors:e,result:{chapter:r,media:o,graph:a}}:{...n,errors:te(e,oe.name,"Could not find media"),actions:i}}}return{...n,errors:te(e,oe.name,"Could not find chapter"),actions:i}}class Ae{constructor(){Object.defineProperty(this,"listeners",{value:{},writable:!0,configurable:!0})}addEventListener(e,t,n){e in this.listeners||(this.listeners[e]=[]),this.listeners[e].push({callback:t,options:n})}removeEventListener(e,t){if(!(e in this.listeners))return;const n=this.listeners[e];for(let s=0,r=n.length;s<r;s++)if(n[s].callback===t){n.splice(s,1);return}}dispatchEvent(e){if(!(e.type in this.listeners))return;const n=this.listeners[e.type].slice();for(let s=0,r=n.length;s<r;s++){const o=n[s];try{o.callback.call(this,e)}catch(a){Promise.resolve().then(()=>{throw a})}o.options&&o.options.once&&this.removeEventListener(e.type,o.callback)}return!e.defaultPrevented}}class tt extends Ae{constructor(){super(),this.listeners||Ae.call(this),Object.defineProperty(this,"aborted",{value:!1,writable:!0,configurable:!0}),Object.defineProperty(this,"onabort",{value:null,writable:!0,configurable:!0}),Object.defineProperty(this,"reason",{value:void 0,writable:!0,configurable:!0})}toString(){return"[object AbortSignal]"}dispatchEvent(e){e.type==="abort"&&(this.aborted=!0,typeof this.onabort=="function"&&this.onabort.call(this,e)),super.dispatchEvent(e)}}class Jt{constructor(){Object.defineProperty(this,"signal",{value:new tt,writable:!0,configurable:!0})}abort(e){let t;try{t=new Event("abort")}catch{typeof document<"u"?document.createEvent?(t=document.createEvent("Event"),t.initEvent("abort",!1,!1)):(t=document.createEventObject(),t.type="abort"):t={type:"abort",bubbles:!1,cancelable:!1}}let n=e;if(n===void 0)if(typeof document>"u")n=new Error("This operation was aborted"),n.name="AbortError";else try{n=new DOMException("signal is aborted without reason")}catch{n=new Error("This operation was aborted"),n.name="AbortError"}this.signal.reason=n,this.signal.dispatchEvent(t)}toString(){return"[object AbortController]"}}typeof Symbol<"u"&&Symbol.toStringTag&&(Jt.prototype[Symbol.toStringTag]="AbortController",tt.prototype[Symbol.toStringTag]="AbortSignal");function it(i){return i.__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL?(console.log("__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL=true is set, will force install polyfill"),!0):typeof i.Request=="function"&&!i.Request.prototype.hasOwnProperty("signal")||!i.AbortController}function ei(i){typeof i=="function"&&(i={fetch:i});const{fetch:e,Request:t=e.Request,AbortController:n,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:s=!1}=i;if(!it({fetch:e,Request:t,AbortController:n,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:s}))return{fetch:e,Request:r};let r=t;(r&&!r.prototype.hasOwnProperty("signal")||s)&&(r=function(l,p){let u;p&&p.signal&&(u=p.signal,delete p.signal);const b=new t(l,p);return u&&Object.defineProperty(b,"signal",{writable:!1,enumerable:!1,configurable:!0,value:u}),b},r.prototype=t.prototype);const o=e;return{fetch:(c,l)=>{const p=r&&r.prototype.isPrototypeOf(c)?c.signal:l?l.signal:void 0;if(p){let u;try{u=new DOMException("Aborted","AbortError")}catch{u=new Error("Aborted"),u.name="AbortError"}if(p.aborted)return Promise.reject(u);const b=new Promise((C,x)=>{p.addEventListener("abort",()=>x(u),{once:!0})});return l&&l.signal&&delete l.signal,Promise.race([b,o(c,l)])}return o(c,l)},Request:r}}const fe=it({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),nt=fe?ei({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,xe=fe?nt.fetch:window.fetch;fe?nt.Request:window.Request;const ti=async i=>{try{let e,t;if(de(i))e=i;else if(re(i)){t=new URL(i).href;const s=await xe(t);if(!s.ok)return{};e=await s.json()}else return{};if(!Qt(e))return{};const n=e.metadata.media;if(re(n)&&!e.media)try{let s;t?s=new URL(n,t).href:(s=new URL(n).href,t=s);const r=await xe(s);if(!r.ok)throw new Error;e.metadata.media=await r.json()}catch{return ri(e.metadata.version)?{manifest:e}:{}}return{manifest:e,manifestURL:t}}catch{return{}}};async function ii(i){const{manifest:e,manifestURL:t}=await ti(i),n=zt(e);return n.media=ni(n.media,t),delete n.metadata.media,n}function ne(i,e){return i.find(t=>t.id===e)}function Oe(i,e){return i.edit?.chapters?i.edit.chapters.find(t=>t.id===e):i.view?.chapters?i.view.chapters.find(t=>t.id===e):void 0}function Le(i,e){return i.videos.find(t=>t.id===e)}function ni(i,e){return{...i,videos:i.videos.map(t=>({...t,variants:t.variants.map(n=>{const s=si(n.url,e);return{...n,url:s||n.url}})}))}}function si(i,e){try{return new URL(i,e).href}catch{return""}}function ri(i){return W(i,"3.2.0")>=0}class st extends Zt{constructor(e,t){super(e),this.onError=t,this.release()}release(){return this.manifest=null,this.chapter=null,this.media=null,this.graph=null,this}async setManifest(e){this.release();const t=await this.exec("manifestLoaders",{actions:{addErrorMessage:te},result:null,errors:null,source:e});t.errors&&this.errorHandler(t.errors);const n=await ii(t.result??e);return this.manifest=n,this}async setInitial(){return this.setNext()}async setNext(e=this.manifest.metadata.initChapterId){const t=await this.exec("chapterLoaders",oe({actions:{getManifest:()=>this.manifest,getCurrent:this.getCurrent,getGraph:Oe,getChapter:ne,getMedia:Le,getByBranches:this.getByBranches.bind(this),addErrorMessage:te},result:null,errors:null,chapterId:e}));return t.errors&&this.errorHandler(t.errors),this.chapter=t.result.chapter,this.media=t.result.media,this.graph=t.result.graph,this}errorHandler(e){this.onError(e),console.error("Something went wrong with loaders",{errors:e})}getInitial(){return this.getByChapterId(this.manifest.metadata.initChapterId)||null}getByChapterId(e=this.manifest.metadata.initChapterId){const t=ne(this.manifest.chapters,e);if(t){const n=Le(this.manifest.media,t.videoId),s=Oe(this.manifest.graph,t.id);if(n)return{chapter:t,media:n,graph:s}}return null}getBranches(e=this.chapter.id){if(e===this.chapter.id)return this.getByBranches(this.chapter.branches);{const t=ne(this.manifest.chapters,e);return this.getByBranches(t?.branches)}}getByBranches(e=[]){return e.reduce((t,n)=>{const s=this.getByChapterId(n.chapterId);return s&&t.push(s),t},[])}getCurrent(){return{chapter:this.chapter,media:this.media,graph:this.graph}}}const y={graph:"graph",interactives:"interactives",chapterChanged:"chapter-changed",playerChanged:"player-changed",manifestChanged:"manifest-changed",errors:"errors",eachTick:"eachTick",historyChanged:"history-changed"},Ne={visibility:"visibility",watchAgainClicked:"watchAgainClicked"},R={actionChoice:"action-choice",actionExecution:"action-execution",visibility:"visibility",containerRemoved:"container-removed",rangeEnded:"range-ended"};function ai(){const i=new Map;function e({listId:s=Math.random().toString(),itemId:r=Math.random().toString(),...o}){const a=i.get(s),c={...o};return a?a[r]=c:i.set(s,{[r]:c}),{listId:s,itemId:r,...o}}function t(s,r){const o=i.get(s);if(o){if(r)return o[r]?.player.destroy(),o[r]?.container.remove(),o[r]?.subscription.unsubscribe(),delete o[r],Object.keys(o).length||i.delete(s),!0;for(const a of Object.values(o))a.player.destroy(),a.container.remove();return i.delete(s),!0}else throw Error("Can't remove. Not find.")}function n(){for(const s of i)t(s[0])}return{createPlayer:e,removePlayer:t,map:i,removeAll:n}}function _e(i,e=[]){let t={},n;const s=!e.length;for(const r of i.variants)switch(!n&&"cover"in r&&(n=r.cover),r.type){case"mp4":(s||e.includes("mp4"))&&(t={...t,MPEG:{"Invariant quality":r.url}});break;case"hls":(s||e.includes("hls"))&&(t={...t,HLS:{type:"url",url:r.url}});break;case"dash":(s||e.includes("dash"))&&(t={...t,DASH:{type:"url",url:r.url}});break}return{sources:t,thumbUrl:n,title:i.id}}const Y=(i,e)=>{const t=i.info.currentQuality$.getValue(),n=i.info.availableQualities$.getValue();t!==e&&n.includes(e)&&(i.setQuality(e),i.setAutoQuality(!1))},oi=i=>{const e=i.variants.find(t=>t.payload?.type==="vk");if(e&&"payload"in e){const[t,n]=e.payload.id.split("_");return[t,n]}return[]},ee={activePlayerChanged:"sc-active-player-changed",initiated:"sc-initiated",playerCreated:"sc-player-created"},ci=2;function li(i){const e=ai();let t,n;const s=new et;let r={},o=!1,a=null,c=!1,l;i&&p(i);function p(d){a=d}function u(d,g,m){if(!a)throw Error("need to set interactive controller");const E=(e.map.get(d)??{})[g];if(E){r={chapterId:m,listId:d,itemId:g,...E};const v=r.player;n=v.info.currentQuality$.subscribe(w=>{if(!(!w||!v.info.position$.getValue())){t=w;for(const L of e.map)Object.values(L[1]).forEach(({player:N})=>{v.info.isAutoQualityEnabled$.getValue()||Y(N,w)})}}),E.container.remove(),o=!1,a.setPlayer(E.player),c||(a.init(),c=!0),s.emit(ee.activePlayerChanged,{player:r.player,config:r.config});return}throw Error("Can't set. Not find.")}async function b(d,g,m){if(!a)throw Error("need to set interactive controller");if(G(r)||d!==r.itemId)return;if(m>=0&&!o){const E=a.getChapterBranches();o=!0;const v=new Set;for(const w of E)v.has(w.media.id)||(await x({media:w.media,chapterId:w.chapter.id,setAsActive:!1,title:w.chapter.label}),v.add(w.media.id))}}async function C({chapter:{id:d},media:g}){if(G(r))return;n?.unsubscribe();const m=r.player.info.muted$.getValue(),S=r.player.info.currentQuality$.getValue(),E=r.player.info.isAutoQualityEnabled$.getValue(),v=r.player.info.volume$.getValue(),w=r.player.info.currentPlaybackRate$.getValue(),L=!E;let N=!1;for(const O of e.map)if(O[0]===g.id){const Q=Object.keys(O[1]);for(const F of Q)F===r.itemId?(Q.length<ci||(N=!0),e.removePlayer(O[0],F)):(N=!0,u(O[0],F,d),L?Y(r.player,S):r.player.setAutoQuality(!0),r.player.setVolume(v),r.player.setMuted(m),r.player.setPlaybackRate(w))}else e.removePlayer(O[0]);N||(await x({media:g,chapterId:d,setAsActive:!0,playbackRate:w}),L?Y(r.player,S):r.player.setAutoQuality(!0),r.player.setVolume(v),r.player.setMuted(m))}async function x({media:d,chapterId:g,prefetch:m=!0,setAsActive:S=!0,autoplay:E=!1,preferredExt:v,title:w,playbackRate:L}){const N=Math.random().toString(),O=document.createElement("div");l.append(O);const Q=r?.player?.info.isAutoQualityEnabled$.getValue();let F;if(a?.options?.vkVideoLoader){const K=oi(d);K.length&&(F=await a.options.vkVideoLoader(...K))}const me={container:O,...F?.videos?.[0]||{sources:_e(d,v).sources},title:w},P=new pt.Player;P.initVideo(me);const at=O.lastChild,ye=new j.Subscription;ye.add(P.info.position$.subscribe(function(K){b(N,P.info.duration$.getValue(),K)})).add(P.events.canplay$.subscribe(function(){Q||Y(P,t),L&&P.setPlaybackRate(L)})),at&&(O.style.display="none",O.classList.add(g));const B=e.createPlayer({listId:d.id,itemId:N,player:P,container:O,sources:_e(d,v).sources,config:me,subscription:ye});return S&&u(d.id,B.itemId,g),E&&B.player.play(),m&&!E&&B.player.prepare(),s.emit(ee.playerCreated,B.player),{player:B.player,config:B.config}}function k(){h(),a=null}function h(){a?.off(y.chapterChanged,C),e.removeAll(),r={},c=!1,o=!1}async function f({source:d,initialChapter:g,container:m}){if(!a)throw Error("need to set interactive controller");await a.setManifest(d),h(),l=m;const{media:S,chapter:E}=await a.setChapter({chapterId:g});if(S){a.on(y.chapterChanged,C);const{player:v,config:w}=await x({media:S,chapterId:E.id,title:E.label});return s.emit(ee.initiated,{container:m,media:S,chapterId:E.id}),{player:v,config:w}}else console.error("not found")}return{...e,on:s.on.bind(s),off:s.off.bind(s),init:f,setInteractiveController:p,createPlayer:x,removeAll:k,getActivePlayer:function(){return r}}}const hi=3e3,di=()=>{let i=[],e=null;return{setPlayer:o=>{e=o},setContainers:o=>{i=o},deleteContainer:o=>{i=i.filter(a=>a.id!==o)},getNextInteractiveTime:(o=hi)=>{if(!i.length||e===null)return null;let a=-1,c=!1;const l=e.info.position$.getValue()*1e3;for(const p of i){const u=p.startTime-o;if(u<=l&&(l<=p.endTime||p.endTime===null)){c=!0;break}l<u&&(a=a===-1?u:Math.min(a,u))}return!c&&a!==-1?a:null}}},D=di(),T=Object.freeze({nothing:0,beforeInteractive:1,interactive:2,afterInteractive:3,end:4,removed:5,destroyed:6}),pe=i=>U(i)&&!Ye(i),rt=i=>Ye(i.branches)||i.order==="end",ui=(i,e)=>{const t=i*1e3;return pe(e.controls)&&t<(e.startTime??0)},je=(i,e)=>{const t=i*1e3;return pe(e.controls)&&t>=(e.startTime??0)&&t<=(e.endTime??1/0)},ie=i=>i.some(e=>e.action.type==="expect"),Ve=i=>i.find(e=>e.action.type==="expect"),fi=({fn:i,type:e=1},...t)=>(...n)=>e?i(...n,...t):i({...n[e],...t[e]}),pi=(i=[])=>i.reduce((e,t,n)=>{const s=(t?.controls??[]).filter(r=>!Kt(r));if(pe(s)){const r=[t.startTime??0,t.endTime??1/0],o=t.id;if(!n)e.push({subjects:[o],range:r});else{const a=[];let c=-1/0,l=1/0,p=[];const u=[];for(let b=0;b<e.length;b++){const C=e[b];if(u.push(...C.subjects),C.range[0]<l&&(l=C.range[0]),C.range[1]>c&&(c=C.range[1]),C.range[0]<=r[0]&&C.range[1]>=r[1])return e[b].subjects.push(o),e;r[0]>=C.range[0]&&r[0]<=C.range[1]&&(a.push(b),p=p.concat(C.subjects),r[0]=C.range[0]),r[1]>=C.range[0]&&r[1]<=C.range[1]&&(a.push(b),p=p.concat(C.subjects),r[1]=C.range[1])}if(u.push(o),r[0]<=l&&r[1]>=c)return[{subjects:u,range:r}];a.length&&a.reverse().forEach(b=>{e.splice(b,1)}),e.push({subjects:p.concat([o]),range:r})}}return e},[]).sort((e,t)=>e.range[0]-t.range[0]),mi=(i,e)=>ie(i.events)?!1:e.some(({container:t})=>t.container.id!==i.id&&ie(t.container.events)&&t.container.endTime===i.endTime&&!t.isRemoved);class yi{constructor({player:e,container:t,branches:n,selectBranches:s,interactiveEvents:r,globalEventEmitter:o,ignoreContainerEvent:a}){this.container=t,this.branches=n,this.selectBranches=s,this.subscription=new j.Subscription,this.player=e,this.interactiveEvents=r,this.ignoreContainerEvent=a,this.globalEventEmitter=o,this.gameState=T.nothing,this.isSelectedControlEvent=!1,this.isSelectedContainerEvent=!1,this.registerEvents()}registerEvents(){this.subscription.add(this.player.events.playing$.subscribe(this.show)).add(this.player.events.paused$.subscribe(this.hide)).add(this.player.events.ended$.subscribe(this.onEndOfVideo))}hide=()=>{setTimeout(()=>{this.gameState!==T.end&&(ie(this.container.container.events)&&this.gameState===T.afterInteractive||this.selectBranches.state.isExpect||(this.container.hide?.(),this.globalEventEmitter.emit(y.interactives,{subjectId:this.container.container.id,subjectName:"container",type:R.visibility,visibility:!1})))})};show=()=>{if(this.gameState===T.interactive&&!this.isSelectedControlEvent)if(this.container.getElement())this.container.show?.(),this.globalEventEmitter.emit(y.interactives,{subjectId:this.container.container.id,subjectName:"container",type:R.visibility,visibility:!0,isFirst:!1});else{const t=fi({fn:this.selectBranches.onControlEvent,type:0},{branches:this.branches,containerId:this.container.container.id,onDetachContainer:()=>{this.removeView(),this.globalEventEmitter.emit(y.interactives,{subjectId:this.container.container.id,subjectName:"container",type:R.visibility,visibility:!1})},onEvent:(n,s)=>{this.isSelectedControlEvent=!0,n!==!1&&(this.removeView(),this.globalEventEmitter.emit(y.interactives,{subjectId:this.container.container.id,subjectName:"container",type:R.visibility,visibility:!1})),(this.gameState===T.end||this.gameState===T.afterInteractive||this.selectBranches.state.isExpect)&&(this.selectBranches.stopExpect(),s(),this.removeView(),this.globalEventEmitter.emit(y.interactives,{subjectId:this.container.container.id,subjectName:"container",type:R.visibility,visibility:!1})),D.deleteContainer(this.container.container.id)},isEOV:()=>this.gameState===T.end});this.container.createView(t),this.globalEventEmitter.emit(y.interactives,{subjectId:this.container.container.id,subjectName:"container",type:R.visibility,visibility:!0,isFirst:!0})}};selectContainerEvent(e=!1){this.interactiveEvents.containersEventsCallState.setCalled({timestamp:e?1/0:this.container.container.endTime,id:this.container.container.id}),!this.isSelectedControlEvent&&(this.isSelectedContainerEvent||(this.isSelectedContainerEvent=!0,this.ignoreContainerEvent()||this.selectBranches.setManifestContainerEvents({container:this.container.container,branches:this.branches,isEOV:e}),!e&&this.interactiveEvents.exec(this.container.container.endTime)))}onStartTime(){this.show()}onEndTime(){this.selectContainerEvent(!1);const e=ie(this.container.container.events)||this.ignoreContainerEvent();(this.isSelectedControlEvent||!e)&&this.removeView()}onBeforeStartTime(){this.container.hide?.(),this.globalEventEmitter.emit(y.interactives,{subjectId:this.container.container.id,subjectName:"container",type:R.visibility,visibility:!1})}onEndOfVideo=()=>{this.gameState=T.end,this.selectContainerEvent(!0)};whilePlaying=()=>{if(this.player.experimental.element$.getValue()?.readyState<1||[T.destroyed,T.removed].includes(this.gameState))return;const t=this.player.info.position$.getValue();if(ui(t,this.container.container))this.gameState!==T.beforeInteractive&&(this.gameState=T.beforeInteractive,this.onBeforeStartTime());else if(je(t,this.container.container))this.gameState!==T.interactive&&(this.gameState=T.interactive,this.onStartTime());else if(this.gameState!==T.afterInteractive){const r=this.gameState;this.gameState=T.afterInteractive,r===T.interactive&&this.onEndTime()}else this.gameState!==T.destroyed&&this.removeView();const n=je(t,this.container.container),s=this.container.container.startTime?[this.container.container.startTime,this.container.container.endTime??1/0]:[];this.container.onProgress?.(t,n),this.globalEventEmitter.emit(y.eachTick,{subjectId:this.container.container.id,subjectName:"container",range:s,currentTime:t,isInteractiveTime:n})};reset(){this.isSelectedControlEvent=!1,this.isSelectedContainerEvent=!1,this.gameState=T.beforeInteractive}removeView(){this.container.removeView(),this.globalEventEmitter.emit(y.interactives,{subjectId:this.container.container.id,subjectName:"container",type:R.containerRemoved,visibility:!1}),this.gameState=T.removed}destroy(){this.reset(),this.removeView(),this.gameState=T.destroyed,this.subscription.unsubscribe(),this.branches=[],this.interactiveEvents.containersEventsCallState.setCalled({timestamp:this.container.container.endTime??1/0,id:this.container.container.id}),D.deleteContainer(this.container.container.id)}}function gi(){const i={};function e(){for(const a in i)Object.prototype.hasOwnProperty.call(i,a)&&delete i[a];return!0}function t(a){const c={};for(const l in i)+l<=a&&(c[l]=i[l]);return c}function n(a){const c={};for(const l in i)+l>=a&&(c[l]=i[l]);return c}function s({timestamp:a,priority:c,initiator:l}){if(Ee(a)){const p=i[a]??null;if(p&&X(c,!0)){let u={};const b=p[c];return b&&(u={...u,...b}),u=G(u)?null:u,u&&X(l,!0)?u[l]??null:u}return p}return null}function r({timestamp:a,priority:c,initiator:l}){if(Ee(a))if(i[a]){if(X(c,!0))if(i[a][c]){if(X(l,!0))if(i[a][c][l]){if(delete i[a][c][l],!G(i[a][c]))return!0}else return!1;if(delete i[a][c],!G(i[a]))return!0}else return!1;return delete i[a]}else return!1}function o({timestamp:a,priority:c,initiator:l,...p}){i[a]?.[c]?.[l]?i[a][c][l].push({...p}):i[a]?.[c]?i[a][c]={...i[a][c],[l]:[{...p}]}:i[a]?i[a]={...i[a],[c]:{[l]:[{...p}]}}:i[a]={[c]:{[l]:[{...p}]}}}return{map:i,remove:r,add:o,removeAll:e,get:s,getLte:t,getGte:n}}const vi=[I.expect,I.setNextBranch],bi=1/0;function Me(i){let e=i,t;const n=Ci(),s=new gi;let r;const o=()=>{u(),k()},a=h=>{s.add.call(void 0,h),b()},c=(h=[])=>{for(const f of h)if(f.action(),vi.includes(f.actionType))break},l=h=>{if(!n.isReady(h))return;const f=J(s.get({timestamp:h,priority:"control"})??{}),d=J(s.get({timestamp:h,priority:"container"})??{}),g=J(s.get({timestamp:h,priority:"chapter"})??{});c([...f,...d,...g])},p=()=>{c([...J(s.get({timestamp:1/0,priority:"chapter"})??{})])},u=()=>{t&&(r?.unsubscribe(),t=void 0)},b=()=>{t||(t=()=>setTimeout(()=>{l(1/0)}),r=e.events.ended$.subscribe(t))},C=h=>{u(),e=h},x=h=>{h.priority==="container"&&n.resetCalled(h.timestamp),s.remove(h)},k=()=>{n.release(),s.removeAll()};return{setPlayer:C,add:a,remove:x,exec:l,execEndOfVideo:p,listen:b,unlisten:u,release:o,containersEventsCallState:n}}function Ci(){const i=new Map;return{setCalled:({timestamp:o,id:a})=>{const c=i.get(o);c&&c[a]!==void 0&&(c[a]=!0)},setData:(o=[])=>{for(const a of o){const c=a.endTime??bi,l=i.get(c)??{};i.set(c,{...l,[a.id]:!1})}},resetCalled:o=>{const a=i.get(o);if(a)for(const c in a)a[c]=!1},isReady:o=>{const a=i.get(o);return a?!Object.values(a).some(c=>!c):!0},release:()=>i.clear()}}function J(i){return Object.values(i).flat().sort(e=>e.actionType===I.expect?-1:1)}const Ei=(i,e)=>{const{height:t,width:n}=e.info.intrinsicVideoSize$.getValue()||{};if(!(t&&n))return{videoContentHeight:0,videoContentWidth:0};const{clientHeight:s,clientWidth:r}=e.experimental.element$.value||{};if(!(s&&r))return{videoContentHeight:0,videoContentWidth:0};const o=t/n,a=s/r;let c,l;return a>o?(l=r,c=r*o):a<o?(l=s/o,c=s):(l=r,c=s),{videoContentWidth:l,videoContentHeight:c}},wi=250;function Ii(i){let e=()=>{};const t=new ResizeObserver(a=>{r(a),e=r.bind(null,a)});function n(a){const{parentElement:c,player:l}=i();if(c&&l){const{videoContentWidth:p,videoContentHeight:u}=Ei(c,l);c.style.setProperty("--interactive-content-width",`${p}px`),c.style.setProperty("--interactive-content-height",`${u}px`),c.style.setProperty("--interactive-width",`${a[0].contentRect.width}px`),c.style.setProperty("--interactive-height",`${a[0].contentRect.height}px`)}}function s(){const{parentElement:a}=i();a.removeAttribute("style")}const r=Xe(a=>{const{fns:c=[]}=i();n(a);for(const l of c)l()},wi);function o(){e=void 0,t.disconnect(),s()}return{resizeObserver:t,calc:()=>{e()},release:o}}class Si{constructor(){this.map={}}push(e,t){e in this.map?this.map[e].push(t):this.map[e]=[t]}get(e){const t=this.map[e];return t?t.slice():null}getAll(){const e=[];for(const t in this.map)e.push(...this.map[t]);return e}remove(e,t){e in this.map&&(this.map[e]=this.map[e].filter(n=>n!==t),this.map[e].length===0&&delete this.map[e])}clear(){this.map={}}size(){return Object.keys(this.map).length}keys(){return Object.keys(this.map)}}const Ti=i=>Math.floor(Math.random()*i),Ri=i=>{let e=i.length,t=1/0,n=null;for(;e--;)i[e].weight<t&&(t=i[e].weight,n=i[e]);return n},Ai=i=>{let e=i.length,t=-1/0,n=null;for(;e--;)i[e].weight>t&&(t=i[e].weight,n=i[e]);return n},xi=i=>{const e=i.length,t=Ti(e);return i[t]},ke=1,Oi=i=>{let e=0;for(let n=0;n<i.length;++n)e+=i[n].weight??ke;const t=Math.random()*e;e=0;for(let n=0;n<i.length-1;++n)if(e+=i[n].weight??ke,e>=t)return i[n];return i[i.length-1]},Fe=Object.freeze({shouldOpenNow:!0,isDetachContainer:!0}),se=(i,e=!1)=>({...i,args:e?{...i.args,...Fe}:{...Fe,...i.args}}),Pe=({globalEventEmitter:i,player:e,interactiveEvents:t,removeControllers:n})=>{const s={isExpect:!1},r=()=>{s.isExpect&&(s.isExpect=!1)},o=({action:h,controlType:f,controlId:d,containerId:g,branches:m=[],onEvent:S,isEOV:E=()=>!1})=>{const v=se(h,E()),w={timestamp:1/0,priority:"control",initiator:d,actionType:v.type},L=i.emit.bind(i,y.interactives,{subjectId:d,subjectType:f,subjectName:"control",type:R.actionChoice,actionType:h.type,payload:{containerId:g,...v.args}});switch(v.type.trim().toLowerCase()){case I.setNextBranch.trim().toLowerCase():{const N=m.find(O=>O.id===v.args.branchId);if(!N)return;S(v.args.isDetachContainer,b.bind(null,{subjectId:d,subjectName:"control"})),L(),v.args.shouldOpenNow?x({subjectId:d,subjectName:"control",subjectType:f,action:v,payload:{chapterId:N.chapterId,autoSelect:!1}}):(t.add({...w,action:x.bind(null,{subjectId:d,subjectName:"control",subjectType:f,action:v,payload:{chapterId:N.chapterId,autoSelect:!1}})}),n?.());return}case I.continuePlayback.trim().toLowerCase():{S(v.args.isDetachContainer,b.bind(null,{subjectId:d,subjectName:"control"})),L(),v.args.shouldOpenNow?C({subjectId:d,subjectName:"control",subjectType:f,action:h}):t.add({...w,action:C.bind(null,{subjectId:d,subjectName:"control",subjectType:f,action:h})});return}case I.openURI.trim().toLowerCase():{S(v.args.isDetachContainer,b.bind(null,{subjectId:d,subjectName:"control"})),L(),v.args.shouldOpenNow?k({subjectId:d,subjectName:"control",subjectType:f,action:v,payload:{URI:h.args.uri}}):(t.add({...w,action:k.bind(null,{subjectId:d,subjectName:"control",subjectType:f,action:v,payload:{URI:h.args.uri}})}),n?.());return}default:console.error("Unexpected control event"),i.emit(y.errors,new A(A.Severity.RECOVERABLE,A.Category.INTERACTIVES,{message:"Unexpected control event"}));return}},a=({action:h,container:{id:f,endTime:d},branches:g=[],isEOV:m=!1,autoSelected:S=!1})=>{const E=se(h,m),v={timestamp:!E.args.shouldOpenNow||m?1/0:d,priority:"container",initiator:f,actionType:E.type},w=i.emit.bind(i,y.interactives,{subjectId:f,subjectName:"container",type:R.actionChoice,actionType:E.type,payload:E.args});switch(E.type.trim().toLowerCase()){case I.setNextBranch.trim().toLowerCase():{const L=g.find(N=>N.id===E.args.branchId);if(!L)return;w(),t.add({...v,action:x.bind(null,{subjectId:f,subjectName:"container",action:E,payload:{chapterId:L.chapterId,autoSelect:S}})}),n?.();return}case I.setMaxWeightBranch.trim().toLowerCase():return;case I.setMinWeightBranch.trim().toLowerCase():return;case I.setRandomBranch.trim().toLowerCase():return;case I.setWeightlessRandomBranch.trim().toLowerCase():return;case I.continuePlayback.trim().toLowerCase():{w(),t.add({...v,action:C.bind(null,{subjectId:f,subjectName:"container",action:E})});return}case I.openURI.trim().toLowerCase():{w(),t.add({...v,action:k.bind(null,{subjectId:f,subjectName:"container",action:E,payload:{URI:h.args.uri}})}),n?.();return}default:console.error("Unexpected container event"),i.emit(y.errors,new A(A.Severity.RECOVERABLE,A.Category.INTERACTIVES,{message:"Unexpected container event"}));return}};function c({container:h,branches:f,isEOV:d=!1}){const g=Ve(h.events);if(g){const m=se(g.action,d);i.emit(y.interactives,{subjectId:h.id,subjectName:"container",type:R.actionChoice,actionType:m.type,payload:m.args}),t.add({timestamp:d?1/0:h.endTime,priority:"container",initiator:h.id,actionType:I.expect,action:u.bind(null,{subjectId:h.id,subjectName:"container"})}),s.isExpect=!0}else for(const m of h.events)a({action:m.action,container:h,branches:f,isEOV:d})}const l=({chapterId:h,action:f,branches:d=[]})=>{const g=i.emit.bind(i,y.interactives,{subjectId:h,subjectName:"chapter",type:R.actionChoice,actionType:f.type,payload:f.args});switch(f.type.trim().toLowerCase()){case I.setNextBranch.trim().toLowerCase():{const m=d.find(S=>S.id===f.args.branchId);return m?.chapterId?(g(),x.bind(null,{subjectId:h,subjectName:"chapter",action:f,payload:{chapterId:m.chapterId,autoSelect:!0}})):void 0}case I.setWeightlessRandomBranch.trim().toLowerCase():{const m=xi(d);return m?.chapterId?(g(),x.bind(null,{subjectId:h,subjectName:"chapter",action:f,payload:{chapterId:m.chapterId,autoSelect:!0}})):void 0}case I.setRandomBranch.trim().toLowerCase():{const m=Oi(d);return m?.chapterId?(g(),x.bind(null,{subjectId:h,subjectName:"chapter",action:f,payload:{chapterId:m.chapterId,autoSelect:!0}})):void 0}case I.setMaxWeightBranch.trim().toLowerCase():{const m=Ai(d);return m?.chapterId?(g(),x.bind(null,{subjectId:h,subjectName:"chapter",action:f,payload:{chapterId:m.chapterId,autoSelect:!0}})):void 0}case I.setMinWeightBranch.trim().toLowerCase():{const m=Ri(d);return m?.chapterId?(g(),x.bind(null,{subjectId:h,subjectName:"chapter",action:f,payload:{chapterId:m.chapterId,autoSelect:!0}})):void 0}case I.continuePlayback.trim().toLowerCase():return g(),C.bind(null,{subjectId:h,subjectName:"chapter",action:f});case I.openURI.trim().toLowerCase():return g(),k.bind(null,{subjectId:h,subjectName:"chapter",action:f,payload:{URI:f.args.uri}});default:console.error("Unexpected chapter event"),i.emit(y.errors,new A(A.Severity.RECOVERABLE,A.Category.INTERACTIVES,{message:"Unexpected chapter event"}));return}};function p(h){const f=Ve(h.events);if(f){if(rt(h))return;i.emit(y.interactives,{subjectId:h.id,subjectName:"chapter",type:R.actionChoice,actionType:f.action.type,payload:f.action.args}),t.add({timestamp:1/0,priority:"chapter",initiator:h.id,actionType:I.expect,action:u.bind(null,{subjectId:h.id,subjectName:"chapter"})})}else h.events.forEach(d=>{const g=l({chapterId:h.id,action:d.action,branches:h.branches});g&&t.add({timestamp:1/0,priority:"chapter",initiator:h.id,actionType:d.action.type,action:g})})}const u=({subjectId:h,subjectName:f,action:d})=>{e.pause(),i.emit(y.interactives,{subjectId:h,subjectName:f,type:R.actionExecution,actionType:d?.type??I.expect})},b=({subjectId:h,subjectName:f})=>{e.info.isEnded$.getValue()?t.execEndOfVideo():e.play(),i.emit(y.interactives,{subjectId:h,subjectName:f,type:R.actionExecution,actionType:"after-expect"})},C=({subjectId:h,subjectName:f,subjectType:d,action:g})=>{i.emit(y.interactives,{subjectId:h,subjectName:f,subjectType:d,type:R.actionExecution,actionType:g.type})},x=({subjectId:h,subjectName:f,subjectType:d,action:g,payload:m})=>{m.behaviour="change-chapter",i.emit(y.interactives,{subjectId:h,subjectName:f,subjectType:d,type:R.actionExecution,actionType:g.type,payload:m})},k=({subjectId:h,subjectName:f,subjectType:d,action:g,payload:m})=>{if(!m.URI)return;const S=window.open(m.URI,"_blank","noopener,noreferrer");S&&(S.opener=null),i.emit(y.interactives,{subjectId:h,subjectName:f,subjectType:d,type:R.actionExecution,actionType:g.type})};return{onControlEvent:o,onContainerEvent:a,onChapterEvent:l,onExpectEvent:u,expectEventHandler:b,setManifestChapterEvents:p,setManifestContainerEvents:c,stopExpect:r,state:s}};class H{constructor(e,t,n,s){this.target=e,this.type=t,this.listener=n,this.options=H.#a(e,s),this.target.addEventListener(t,n,this.options)}unlisten(){this.target.removeEventListener(this.type,this.listener,this.options),this.target=null,this.listener=null,this.options=!1}static#a(e,t){if(t===void 0)return!1;if(typeof t=="boolean")return t;{const n=new Set(["passive","capture"]),s=Object.keys(t).filter(o=>!n.has(o));return s.length===0&&console.warn("Unsupported flag(s) to addEventListener: "+s.join(",")),H.#l(e)?t:t.capture||!1}}static#s=void 0;static#l(e){let t=H.#s;if(t===void 0){t=!1;try{const n={},s={get:()=>(t=!0,!1)};Object.defineProperty(n,"passive",s),Object.defineProperty(n,"capture",s);const r=()=>{};e.addEventListener("test",r,n),e.removeEventListener("test",r,n)}catch{t=!1}H.#s=t}return t||!1}}class Li{constructor(){this.bindingMap=new Si}release(){this.removeAll(),this.bindingMap=null}listen(e,t,n,s){if(!this.bindingMap)return;const r=new H(e,t,n,s);this.bindingMap.push(t,r)}listenOnce(e,t,n,s){const r=o=>{this.unlisten(e,t,r),n(o)};this.listen(e,t,r,s)}unlisten(e,t,n){if(!this.bindingMap)return;const s=this.bindingMap.get(t)||[];for(const r of s)r.target===e&&(n===r.listener||!n)&&(r.unlisten(),this.bindingMap.remove(t,r))}removeAll(){if(!this.bindingMap)return;const e=this.bindingMap.getAll();for(const t of e)t.unlisten();this.bindingMap.clear()}}class Ni{rootElement;canvasImgSrc;_prevSizeId=0;constructor(){this.rootElement=document.createElement("canvas")}clear(){this.rootElement.getContext("2d")?.clearRect(0,0,this.rootElement.width,this.rootElement.height)}isImageDrawn(){const e=this.rootElement.getContext("2d")?.getImageData(0,0,this.rootElement.width,this.rootElement.height);if(!e)return!1;const t=e.data,n=t.length;for(let s=3;s<n;s+=40)if(t[s]!==0)return!0;return!1}destroy(){this.rootElement.remove()}show(){this.rootElement.style.visibility="visible"}hide(){this.rootElement.style.visibility="hidden"}setCanvasImageSource(e){this.canvasImgSrc=e}draw(){this.canvasImgSrc&&this.rootElement.getContext("2d")?.drawImage(this.canvasImgSrc,0,0,this.rootElement.width,this.rootElement.height)}async updateCanvasDimensions(e,t=!1){const n=e.width+e.height;if(this._prevSizeId===n)return;let s;t&&(s=await this.save()),this.rootElement.width=e.width,this.rootElement.height=e.height,t&&s&&this.restore(s),this._prevSizeId=n}async save(){const e=this.rootElement.toDataURL("image/jpeg",1),t=new Image;return t.crossOrigin="anonymous",t.src=e,await t.decode(),t}restore(e){this.rootElement&&this.rootElement.getContext("2d")?.drawImage(e,0,0,this.rootElement.width,this.rootElement.height)}}class _i{lastFrameCanvas;endOffsetMs;currentChapter;currentVideoDurationMs=1/0;rootElement;_containerTimeFrameShouldReceived=!1;_endTimeFrameReceived=!1;_shouldCallSkip=!1;_callbacks;constructor({parentElement:e,endOffsetMs:t=250,onError:n}){this.rootElement=document.createElement("div"),this.rootElement.style.cssText=`
|
|
7
7
|
position: absolute;
|
|
8
8
|
top: 0;
|
|
9
9
|
left: 0;
|
|
@@ -11,13 +11,13 @@
|
|
|
11
11
|
height: var(--interactive-height);
|
|
12
12
|
background-color: var(--black);
|
|
13
13
|
visibility: hidden;
|
|
14
|
-
`,this.lastFrameCanvas=new
|
|
14
|
+
`,this.lastFrameCanvas=new Ni,this.endOffsetMs=t,this._callbacks={onError:n},this.lastFrameCanvas.rootElement.style.cssText=`
|
|
15
15
|
position: absolute;
|
|
16
16
|
top: 50%;
|
|
17
17
|
left: 50%;
|
|
18
18
|
transform: translate(-50%, -50%);
|
|
19
|
-
`,this.rootElement.prepend(this.lastFrameCanvas.rootElement),e.prepend(this.rootElement)}destroy(){this.hide(),this.reset(),this._callbacks=void 0,this.lastFrameCanvas.destroy(),this.rootElement.remove()}setVideoDuration(e){this.currentVideoDurationMs=e}setVideoElement(e){this.lastFrameCanvas.setCanvasImageSource(e)}setCurrentChapter(e){this.currentChapter=e}show(){this.rootElement.style.visibility="visible"}hide(){this.rootElement.style.visibility="hidden"}async updateCanvasDimensions(e=!1){this._containerTimeFrameShouldReceived||this._endTimeFrameReceived||(e=!1);const t=getComputedStyle(this.rootElement),n={width:parseInt(t.getPropertyValue("--interactive-content-width"),10),height:parseInt(t.getPropertyValue("--interactive-content-height"),10)};try{this.lastFrameCanvas.updateCanvasDimensions(n,e)}catch(s){this._onError(s)}}draw(){(this._containerTimeFrameShouldReceived||!this._containerTimeFrameShouldReceived&&!this._endTimeFrameReceived)&&this.lastFrameCanvas.draw()}isChapterEndTime(e){return this.currentVideoDurationMs&&e>=this.currentVideoDurationMs-this.endOffsetMs}isContainerTime(e){if(this.currentChapter)return this.currentChapter.containers.some(t=>t.controls?.length&&e>=(t.startTime??0)&&e<=Math.min(t.endTime??1/0,this.currentVideoDurationMs-this.endOffsetMs))}onEachTick=e=>{const t=e??this.lastFrameCanvas.canvasImgSrc.currentTime*1e3,n=this.isChapterEndTime(t);if(this.isContainerTime(t))this._endTimeFrameReceived=!1,this._containerTimeFrameShouldReceived=!0,this._shouldCallSkip=!0;else if(n)this._containerTimeFrameShouldReceived=!1,this._shouldCallSkip=!1,this._endTimeFrameReceived||(this.draw(),this._endTimeFrameReceived=!0,this.show());else{if(this._shouldCallSkip){this._shouldCallSkip=!1;return}this.reset()}};onSeek=()=>{this.onEachTick(),!this._containerTimeFrameShouldReceived&&!this._endTimeFrameReceived&&(this.hide(),this.lastFrameCanvas.clear())};reset(){this._endTimeFrameReceived=!1,this._containerTimeFrameShouldReceived=!1,this._shouldCallSkip=!1}_onError(e){this._callbacks?.onError?.(e)}}function
|
|
19
|
+
`,this.rootElement.prepend(this.lastFrameCanvas.rootElement),e.prepend(this.rootElement)}destroy(){this.hide(),this.reset(),this._callbacks=void 0,this.lastFrameCanvas.destroy(),this.rootElement.remove()}setVideoDuration(e){this.currentVideoDurationMs=e}setVideoElement(e){this.lastFrameCanvas.setCanvasImageSource(e)}setCurrentChapter(e){this.currentChapter=e}show(){this.rootElement.style.visibility="visible"}hide(){this.rootElement.style.visibility="hidden"}async updateCanvasDimensions(e=!1){this._containerTimeFrameShouldReceived||this._endTimeFrameReceived||(e=!1);const t=getComputedStyle(this.rootElement),n={width:parseInt(t.getPropertyValue("--interactive-content-width"),10),height:parseInt(t.getPropertyValue("--interactive-content-height"),10)};try{this.lastFrameCanvas.updateCanvasDimensions(n,e)}catch(s){this._onError(s)}}draw(){(this._containerTimeFrameShouldReceived||!this._containerTimeFrameShouldReceived&&!this._endTimeFrameReceived)&&this.lastFrameCanvas.draw()}isChapterEndTime(e){return this.currentVideoDurationMs&&e>=this.currentVideoDurationMs-this.endOffsetMs}isContainerTime(e){if(this.currentChapter)return this.currentChapter.containers.some(t=>t.controls?.length&&e>=(t.startTime??0)&&e<=Math.min(t.endTime??1/0,this.currentVideoDurationMs-this.endOffsetMs))}onEachTick=e=>{const t=e??this.lastFrameCanvas.canvasImgSrc.currentTime*1e3,n=this.isChapterEndTime(t);if(this.isContainerTime(t))this._endTimeFrameReceived=!1,this._containerTimeFrameShouldReceived=!0,this._shouldCallSkip=!0;else if(n)this._containerTimeFrameShouldReceived=!1,this._shouldCallSkip=!1,this._endTimeFrameReceived||(this.draw(),this._endTimeFrameReceived=!0,this.show());else{if(this._shouldCallSkip){this._shouldCallSkip=!1;return}this.reset()}};onSeek=()=>{this.onEachTick(),!this._containerTimeFrameShouldReceived&&!this._endTimeFrameReceived&&(this.hide(),this.lastFrameCanvas.clear())};reset(){this._endTimeFrameReceived=!1,this._containerTimeFrameShouldReceived=!1,this._shouldCallSkip=!1}_onError(e){this._callbacks?.onError?.(e)}}function ji(i=0){return new Promise(e=>{setTimeout(()=>{e(0)},i)})}const Vi=Object.freeze({parentElement:null,fullscreenTargetElement:null,lang:"ru",loaders:{},graph:!1,lastFrame:!1}),M=Object.freeze({created:0,initiated:1,ready:2,destroyed:3});function Mi(){const i=document.createElement("div");return i.style.cssText=`
|
|
20
20
|
position: absolute;
|
|
21
21
|
top: 0;
|
|
22
22
|
left: 0;
|
|
23
|
-
`,i}class
|
|
23
|
+
`,i}class ki{#a=null;#s=null;#l=null;#h=null;#r=null;#o=null;#d=null;#t=null;#u=new j.ValueSubject(!1);#m=new Set;#n=null;#c=null;#y=null;#i=null;#e=null;constructor(e){this.options={...Vi,...e},this.#s=[],this.factories=new Map([["choice",Ke]]),this.rootElement=Mi(),this.options.parentElement.append(this.rootElement),this.#e=new et,this.#h=new j.Subscription,this.#l=new Li,this.options.lastFrame&&(this.#i=new _i({parentElement:this.options.parentElement,interactivesRootElement:this.rootElement,onError:t=>this.#e.emit(y.errors,new A(A.Severity.RECOVERABLE,A.Category.SEAMLESS,t))})),this.#l.listen(this.rootElement,"mousedown",t=>t.stopPropagation()),this.#l.listen(this.rootElement,"mouseup",t=>t.stopPropagation()),this.#t=new st(this.options.loaders,t=>this.#e.emit(y.errors,new A(A.Severity.RECOVERABLE,A.Category.MANIFEST,t))),this.#r=Me(this.options.player),this.#o=new Xt,this.#d=Pe({player:this.options.player,interactiveEvents:this.#r,globalEventEmitter:this.#e,removeControllers:this.#f}),this.#a=Ii(()=>({player:this.options?.player,parentElement:this.options.parentElement,fns:this.options.lastFrame?[()=>{this.#i.updateCanvasDimensions(!0)}]:[]})),this.options.graph&&(this.#n=new Lt({root:this.options.parentElement,lang:this.options.lang,onOpenPreviewClick:t=>{this.setChapter({chapterId:t}),this.#e.emit(y.graph,{type:Ne.watchAgainClicked,chapterId:t})},onError:t=>this.#e.emit(y.errors,new A(A.Severity.RECOVERABLE,A.Category.LOADERS,{message:t}))})),this.#c=new jt,this.#c.addEventListener(ae,this.#C),this.#e.on(y.interactives,t=>{if(t.type===R.actionExecution){if(t.payload?.behaviour==="change-chapter"){const{chapterId:n,autoSelect:s}=t.payload;this.setChapter({chapterId:n,autoSelect:s})}if(t.payload?.behaviour==="change-manifest"){const{manifestURL:n}=t.payload;this.setManifest(n)}}}),this.isFirstChapterFetched=!1,this.state=M.created}emitPlayerChanged=e=>{this.#e.emit(y.playerChanged,e)};async initSeamless({source:e,initialChapter:t,visitedChapters:n=[],videosInfo:s}){this.#y=li(this);const r=document.createElement("div");this.#y.on(ee.activePlayerChanged,this.emitPlayerChanged);const{player:o,config:a}=await this.#y.init({source:e,initialChapter:t,container:r});return this.setVisitedChapters(n),this.updateGraphVideosInfo(s),{player:o,config:a}}getStatEvents(){return{click$:new j.Observable(e=>{this.#e.on(y.graph,({type:t,visibility:n})=>{t==="visibility"&&e.next(n?exports.INTERACTIVE_CLICK_ACTIONS.OPEN_GRAPH:exports.INTERACTIVE_CLICK_ACTIONS.CLOSE_GRAPH),t==="watchAgainClicked"&&e.next(exports.INTERACTIVE_CLICK_ACTIONS.WATCH_AGAIN)}),this.#e.on(y.interactives,({type:t,subjectName:n,subjectType:s})=>{t!=="action-choice"||n!=="control"||(s==="Button"&&e.next(exports.INTERACTIVE_CLICK_ACTIONS.GO_NEXT_BUTTON),s==="Area"&&e.next(exports.INTERACTIVE_CLICK_ACTIONS.GO_NEXT_AREA))})}),nextMovie$:new j.Observable(e=>{this.#e.on(y.playerChanged,({config:t})=>{t?.unitedVideoId&&e.next(t.unitedVideoId)})})}}setPlayer(e){this.#g(),this.options.player=e,D.setPlayer(this.options.player),this.#r?this.#r.setPlayer(this.options.player):this.#r=Me(this.options.player),this.#d=Pe({player:this.options.player,interactiveEvents:this.#r,globalEventEmitter:this.#e,removeControllers:this.#f}),this.state===M.initiated&&(this.#v(),this.#p(this.#t.chapter))}async setManifest(e,t){this.#g(),this.isFirstChapterFetched=!1;const n=await this.#t.setManifest(e),s=t&&t.manifestId===n.manifest.metadata.id?{...t}:void 0;return this.#c.onManifestChange(n.manifest.metadata,s),this.#n&&await this.#n.handleManifestChange(n.manifest,s?_t(s):[]),this.#e.emit(y.manifestChanged,{manifest:n.manifest}),this.#p(this.#t.chapter),n.manifest}setVisitedChapters(e){Array.isArray(e)&&this.#n?.setVisitedChapters(e)}updateGraphVideosInfo(e){Array.isArray(e)&&this.#n?.updateVideosInfo(e)}async setChapter({chapterId:e,autoSelect:t,tryContinueFromHistory:n=!1}={}){this.#g(),this.#i&&this.isFirstChapterFetched&&(this.#i.draw(),this.#i.show()),j.getCurrentBrowser().browser===j.CurrentClientBrowser.Safari&&await ji(35);let r;e?r=await this.#t.setNext(e):r=await(n?this.#t.setNext(Vt(this.#t.manifest,this.getHistory())):this.#t.setInitial());const{chapter:o,media:a,graph:c}=r;return this.#c.onChapterChange({chapterId:o.id,mediaId:a.id,autoSelect:t,isLastChapter:rt(o)}),this.#n&&this.#n.handleChapterChange(c),this.#i?.setCurrentChapter(this.getCurrentChapter().chapter),this.#e.emit(y.chapterChanged,{chapter:o,media:a,graph:c}),this.#p(this.#t.chapter),this.#m=new Set,this.isFirstChapterFetched=!0,{chapter:o,media:a,graph:c}}toggleGraphView(e=!0){this.#n&&(e?(this.#n.show(),this.#u.next(!1)):(this.#n.hide(),this.#b()),this.#e.emit(y.graph,{type:Ne.visibility,visibility:e}))}init(){this.#t.chapter&&this.options.parentElement&&this.options.player&&this.options.fullscreenTargetElement&&this.state===M.created&&(this.#a.resizeObserver.observe(this.options.fullscreenTargetElement),this.#v(),this.state=M.initiated,this.#p(this.#t.chapter))}#g(){this.state===M.ready&&(this.#f(),this.#s=[],this.#o.release(),this.#r?.release(),this.state=M.initiated,this.#u.next(!1))}#S=()=>{this.#o.fns.forEach(n=>n());const e=this.options.player.info.position$.getValue()*1e3,t=(this.#t.chapter.containers||[]).filter(n=>n.startTime>=Math.floor(e));for(const n of t){this.#r.remove({timestamp:1/0,priority:"container",initiator:n.id});for(const s of n.controls)this.#r.remove({timestamp:1/0,priority:"control",initiator:s.id});this.#s.find(s=>s.container.container.id===n.id).reset()}};#E=()=>{this.#a.calc(),this.#o.requestAnimation()};#w(e){(!this.#n||this.#n.isHidden)&&this.#b();const t=e*1e3,s=this.getInteractiveRanges().findLast(({range:r})=>t>=r[1]);if(s){const r=s.range.join("-");this.#m.has(r)||(this.#m.add(r),this.#e.emit(y.interactives,{type:R.rangeEnded,payload:s,visibility:!0}))}}#v(){this.#h.unsubscribe(),this.#h.add(this.options.player.events.started$.pipe(j.once()).subscribe(this.#E)).add(this.options.player.events.playing$.subscribe(this.#o.requestAnimation)).add(this.options.player.events.willPause$.subscribe(this.#o.cancelAnimation)).add(this.options.player.info.position$.subscribe(this.#w.bind(this))),this.options.lastFrame&&this.#h.add(this.options.player.info.duration$.subscribe(e=>{this.#i.setVideoDuration(e*1e3)})).add(this.options.player.experimental.element$.subscribe(e=>{e&&this.#i.setVideoElement(e)})).add(this.options.player.events.firstFrame$.subscribe(()=>{this.#i.reset(),setTimeout(()=>{this.#i.hide(),this.#i.lastFrameCanvas.clear()},50)})).add(this.options.player.events.seeked$.subscribe(this.#i.onSeek))}#f=()=>{this.#s.forEach(e=>{this.#o.removeFn(e.whilePlaying),e.destroy()})};#p(e){this.#t.chapter&&this.state===M.initiated&&(this.#d.setManifestChapterEvents(e),this.#s=this.#I(e),this.#r.containersEventsCallState.setData(e.containers),D.setContainers(this.#s.map(t=>t.container.container)),this.options.lastFrame&&this.#o.addFn(()=>{this.#i.onEachTick(this.options.player.info.position$.getValue()*1e3)},!0),this.state=M.ready)}#I(e){return e?.containers?.reduce((t,n)=>{const s=n.type.trim().toLowerCase(),r=this.factories.get(s);if(r){const o=new yi({player:this.options.player,container:r(n,this.rootElement),branches:this.#t.chapter.branches,selectBranches:this.#d,interactiveEvents:this.#r,globalEventEmitter:this.#e,ignoreContainerEvent:()=>mi(n,this.#s)});return this.#o.addFn(o.whilePlaying,!0),[...t,o]}return[...t]},[])??[]}#b(){const e=this.#u.getValue(),t=!!D.getNextInteractiveTime();(t&&!e||!t&&e)&&this.#u.next(!e)}isSupport(e=this.#t.manifest){return ue(e.metadata.version)}getIsSeekable(){return this.#u}getHistory(){return this.#c.getHistory()}#C=({detail:e})=>{this.#e.emit(y.historyChanged,e)};getInteractiveRanges(){return pi(this.#t.chapter?.containers)}getNextInteractiveStartTime(e){return D.getNextInteractiveTime(e)}getChapterBranches(e){return this.#t.getBranches(e)}getCurrentChapter(){return this.#t.getCurrent()}getCurrentManifest(){return this.#t.manifest}addFactory(e,t){this.factories.set(e.trim().toLowerCase(),t)}removeFactory(e){this.factories.delete(e.trim().toLowerCase())}on(...e){return this.#e.on(...e),this}off(...e){return this.#e.off(...e),this}once(...e){return this.#e.once(...e),this}destroy(){this.#f(),this.#s=void 0,this.#c.removeEventListener(ae,this.#C),this.#c.destroy(),this.#c=void 0,this.#n?.destroy(),this.#n=void 0,this.#a.release(),this.#a=void 0,this.#d=void 0,this.#o.release(),this.#o=void 0,this.#r.release(),this.#r=void 0,this.#t.release(),this.#d=void 0,this.#l.release(),this.#l=void 0,this.#h.unsubscribe(),this.#h=void 0,this.#e.reset(),this.#e=void 0,this.#i?.destroy(),this.#i=void 0,this.rootElement.remove(),this.rootElement=void 0,this.factories=void 0,this.options=void 0,this.isFirstChapterFetched=!1,this.state=M.destroyed}}const Fi={Container:Qe,createChoiceContainer:Ke,createAreaControl:Ge,createButtonControl:We,createRelativeLayout:wt,getRootEl:$e,classnamesPrefix:_},Pi={version:mt};exports.CustomError=A;exports.EVENT_NAMES=y;exports.Interactives=ki;exports.ManifestController=st;exports.SDKInfo=Pi;exports.compareVersions=W;exports.isSupportedManifest=ue;exports.utils=Fi;
|